CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_4_1_8_patch9/src/RecoLocalMuon/CSCValidation/src/CSCValidation.cc

Go to the documentation of this file.
00001 /*
00002  *  validation package for CSC DIGIs, RECHITs and SEGMENTs + more.
00003  *
00004  *  Michael Schmitt
00005  *  Andy Kubik
00006  *  Northwestern University
00007  */
00008 #include "RecoLocalMuon/CSCValidation/src/CSCValidation.h"
00009 
00010 using namespace std;
00011 using namespace edm;
00012 
00013 
00015 //  CONSTRUCTOR  //
00017 CSCValidation::CSCValidation(const ParameterSet& pset){ 
00018 
00019   // Get the various input parameters
00020   rootFileName         = pset.getUntrackedParameter<std::string>("rootFileName","valHists.root");
00021   isSimulation         = pset.getUntrackedParameter<bool>("isSimulation",false);
00022   writeTreeToFile      = pset.getUntrackedParameter<bool>("writeTreeToFile",true);
00023   detailedAnalysis     = pset.getUntrackedParameter<bool>("detailedAnalysis",false);
00024   useDigis             = pset.getUntrackedParameter<bool>("useDigis",true);
00025 
00026   // event quality filter
00027   useQualityFilter     = pset.getUntrackedParameter<bool>("useQualityFilter",false);
00028   pMin                 = pset.getUntrackedParameter<double>("pMin",4.);
00029   chisqMax             = pset.getUntrackedParameter<double>("chisqMax",20.);
00030   nCSCHitsMin          = pset.getUntrackedParameter<int>("nCSCHitsMin",10);
00031   nCSCHitsMax          = pset.getUntrackedParameter<int>("nCSCHitsMax",25);
00032   lengthMin            = pset.getUntrackedParameter<double>("lengthMin",140.);
00033   lengthMax            = pset.getUntrackedParameter<double>("lengthMax",600.);
00034   deltaPhiMax          = pset.getUntrackedParameter<double>("deltaPhiMax",0.2);
00035   polarMax             = pset.getUntrackedParameter<double>("polarMax",0.7);
00036   polarMin             = pset.getUntrackedParameter<double>("polarMin",0.3);
00037 
00038   // trigger filter
00039   useTriggerFilter     = pset.getUntrackedParameter<bool>("useTriggerFilter",false);
00040 
00041   // input tags for collections
00042   stripDigiTag  = pset.getParameter<edm::InputTag>("stripDigiTag");
00043   wireDigiTag   = pset.getParameter<edm::InputTag>("wireDigiTag"); 
00044   compDigiTag   = pset.getParameter<edm::InputTag>("compDigiTag");
00045   alctDigiTag   = pset.getParameter<edm::InputTag>("alctDigiTag") ;
00046   clctDigiTag   = pset.getParameter<edm::InputTag>("clctDigiTag") ;
00047   corrlctDigiTag= pset.getParameter<edm::InputTag>("corrlctDigiTag") ;
00048   cscRecHitTag  = pset.getParameter<edm::InputTag>("cscRecHitTag");
00049   cscSegTag     = pset.getParameter<edm::InputTag>("cscSegTag");
00050   saMuonTag     = pset.getParameter<edm::InputTag>("saMuonTag");
00051   l1aTag        = pset.getParameter<edm::InputTag>("l1aTag");
00052   simHitTag     = pset.getParameter<edm::InputTag>("simHitTag");
00053   hltTag        = pset.getParameter<edm::InputTag>("hltTag");
00054 
00055   // flags to switch on/off individual modules
00056   makeOccupancyPlots   = pset.getUntrackedParameter<bool>("makeOccupancyPlots",true);
00057   makeTriggerPlots     = pset.getUntrackedParameter<bool>("makeTriggerPlots",false);
00058   makeStripPlots       = pset.getUntrackedParameter<bool>("makeStripPlots",true);
00059   makeWirePlots        = pset.getUntrackedParameter<bool>("makeWirePlots",true);
00060   makeRecHitPlots      = pset.getUntrackedParameter<bool>("makeRecHitPlots",true);
00061   makeSimHitPlots      = pset.getUntrackedParameter<bool>("makeSimHitPlots",true);
00062   makeSegmentPlots     = pset.getUntrackedParameter<bool>("makeSegmentPlots",true);
00063   makeResolutionPlots  = pset.getUntrackedParameter<bool>("makeResolutionPlots",true);
00064   makePedNoisePlots    = pset.getUntrackedParameter<bool>("makePedNoisePlots",true);
00065   makeEfficiencyPlots  = pset.getUntrackedParameter<bool>("makeEfficiencyPlots",true);
00066   makeGasGainPlots     = pset.getUntrackedParameter<bool>("makeGasGainPlots",true);
00067   makeAFEBTimingPlots  = pset.getUntrackedParameter<bool>("makeAFEBTimingPlots",true);
00068   makeCompTimingPlots  = pset.getUntrackedParameter<bool>("makeCompTimingPlots",true);
00069   makeADCTimingPlots   = pset.getUntrackedParameter<bool>("makeADCTimingPlots",true);
00070   makeRHNoisePlots     = pset.getUntrackedParameter<bool>("makeRHNoisePlots",false);
00071   makeCalibPlots       = pset.getUntrackedParameter<bool>("makeCalibPlots",false);
00072   makeStandalonePlots  = pset.getUntrackedParameter<bool>("makeStandalonePlots",false);
00073   makeTimeMonitorPlots = pset.getUntrackedParameter<bool>("makeTimeMonitorPlots",false);
00074   makeHLTPlots         = pset.getUntrackedParameter<bool>("makeHLTPlots",false);
00075 
00076   // set counters to zero
00077   nEventsAnalyzed = 0;
00078   rhTreeCount = 0;
00079   segTreeCount = 0;
00080   firstEvent = true; 
00081  
00082   // Create the root file for the histograms
00083   theFile = new TFile(rootFileName.c_str(), "RECREATE");
00084   theFile->cd();
00085 
00086   // Create object of class CSCValHists to manage histograms
00087   histos = new CSCValHists();
00088 
00089   // book Occupancy Histos
00090   hOWires    = new TH2I("hOWires","Wire Digi Occupancy",36,0.5,36.5,20,0.5,20.5);
00091   hOStrips   = new TH2I("hOStrips","Strip Digi Occupancy",36,0.5,36.5,20,0.5,20.5);
00092   hORecHits  = new TH2I("hORecHits","RecHit Occupancy",36,0.5,36.5,20,0.5,20.5);
00093   hOSegments = new TH2I("hOSegments","Segments Occupancy",36,0.5,36.5,20,0.5,20.5);
00094 
00095   // book Eff histos
00096   hSSTE = new TH1F("hSSTE","hSSTE",40,0,40);
00097   hRHSTE = new TH1F("hRHSTE","hRHSTE",40,0,40);
00098   hSEff = new TH1F("hSEff","Segment Efficiency",20,0.5,20.5);
00099   hRHEff = new TH1F("hRHEff","recHit Efficiency",20,0.5,20.5);
00100 
00101   const int nChambers = 36; 
00102   const int nTypes = 18;
00103   float nCH_min = 0.5;
00104   float nCh_max = float(nChambers) + 0.5;
00105   float nT_min = 0.5;
00106   float nT_max = float(nTypes) + 0.5;
00107 
00108   hSSTE2 = new TH2F("hSSTE2","hSSTE2",nChambers,nCH_min,nCh_max, nTypes, nT_min, nT_max);
00109   hRHSTE2 = new TH2F("hRHSTE2","hRHSTE2",nChambers,nCH_min,nCh_max, nTypes, nT_min, nT_max);
00110   hStripSTE2 = new TH2F("hStripSTE2","hStripSTE2",nChambers,nCH_min,nCh_max, nTypes, nT_min, nT_max);
00111   hWireSTE2 = new TH2F("hWireSTE2","hWireSTE2",nChambers,nCH_min,nCh_max, nTypes, nT_min, nT_max);
00112   
00113 
00114   hEffDenominator = new TH2F("hEffDenominator","hEffDenominator",nChambers,nCH_min,nCh_max, nTypes, nT_min, nT_max);
00115   hSEff2 = new TH2F("hSEff2","Segment Efficiency 2D",nChambers,nCH_min,nCh_max, nTypes, nT_min, nT_max);
00116   hRHEff2 = new TH2F("hRHEff2","recHit Efficiency 2D",nChambers,nCH_min,nCh_max, nTypes, nT_min, nT_max);
00117 
00118   hStripEff2 = new TH2F("hStripEff2","strip Efficiency 2D",nChambers,nCH_min,nCh_max, nTypes, nT_min, nT_max);
00119   hWireEff2 = new TH2F("hWireEff2","wire Efficiency 2D",nChambers,nCH_min,nCh_max, nTypes, nT_min, nT_max);
00120 
00121   hSensitiveAreaEvt = new TH2F("hSensitiveAreaEvt","events in sensitive area",nChambers,nCH_min,nCh_max, nTypes, nT_min, nT_max);
00122  
00123   // setup trees to hold global position data for rechits and segments
00124   if (writeTreeToFile) histos->setupTrees();
00125 
00126 
00127 }
00128 
00130 //  DESTRUCTOR  //
00132 CSCValidation::~CSCValidation(){
00133 
00134   // produce final efficiency histograms
00135   histoEfficiency(hRHSTE,hRHEff);
00136   histoEfficiency(hSSTE,hSEff);
00137   hSEff2->Divide(hSSTE2,hEffDenominator,1.,1.,"B");
00138   hRHEff2->Divide(hRHSTE2,hEffDenominator,1.,1.,"B");
00139   hStripEff2->Divide(hStripSTE2,hEffDenominator,1.,1.,"B");
00140   hWireEff2->Divide(hWireSTE2,hEffDenominator,1.,1.,"B");
00141 
00142   histos->insertPlot(hRHSTE,"hRHSTE","Efficiency");
00143   histos->insertPlot(hSSTE,"hSSTE","Efficiency");
00144   histos->insertPlot(hSSTE2,"hSSTE2","Efficiency");
00145   histos->insertPlot(hEffDenominator,"hEffDenominator","Efficiency");
00146   histos->insertPlot(hRHSTE2,"hRHSTE2","Efficiency");
00147   histos->insertPlot(hStripSTE2,"hStripSTE2","Efficiency");
00148   histos->insertPlot(hWireSTE2,"hWireSTE2","Efficiency");
00149 
00150   //moving this to post job macros
00151   histos->insertPlot(hSEff,"hSEff","Efficiency");
00152   histos->insertPlot(hRHEff,"hRHEff","Efficiency");
00153 
00154   histos->insertPlot(hSEff2,"hSEff2","Efficiency");
00155   histos->insertPlot(hRHEff2,"hRHEff2","Efficiency");
00156   histos->insertPlot(hStripEff2,"hStripff2","Efficiency");
00157   histos->insertPlot(hWireEff2,"hWireff2","Efficiency");
00158   
00159   histos->insertPlot(hSensitiveAreaEvt,"","Efficiency");
00160 
00161   // throw in occupancy plots so they're saved
00162   histos->insertPlot(hOWires,"hOWires","Digis");
00163   histos->insertPlot(hOStrips,"hOStrips","Digis");
00164   histos->insertPlot(hORecHits,"hORecHits","recHits");
00165   histos->insertPlot(hOSegments,"hOSegments","Segments");
00166 
00167   
00168   // write histos to the specified file
00169   histos->writeHists(theFile);
00170   if (writeTreeToFile) histos->writeTrees(theFile);
00171   theFile->Close();
00172 
00173 }
00174 
00176 //  Analysis  //
00178 void CSCValidation::analyze(const Event & event, const EventSetup& eventSetup){
00179   
00180   // increment counter
00181   nEventsAnalyzed++;
00182 
00183   //int iRun   = event.id().run();
00184   //int iEvent = event.id().event();
00185 
00186   // Get the Digis
00187   edm::Handle<CSCWireDigiCollection> wires;
00188   edm::Handle<CSCStripDigiCollection> strips;
00189   edm::Handle<CSCComparatorDigiCollection> compars;
00190   edm::Handle<CSCALCTDigiCollection> alcts;
00191   edm::Handle<CSCCLCTDigiCollection> clcts;
00192   edm::Handle<CSCCorrelatedLCTDigiCollection> correlatedlcts;
00193   if (useDigis){
00194     event.getByLabel(stripDigiTag,strips);
00195     event.getByLabel(wireDigiTag,wires);
00196     event.getByLabel(compDigiTag,compars);
00197     event.getByLabel(alctDigiTag, alcts);
00198     event.getByLabel(clctDigiTag, clcts);
00199     event.getByLabel(corrlctDigiTag, correlatedlcts);
00200  }
00201 
00202   // Get the CSC Geometry :
00203   ESHandle<CSCGeometry> cscGeom;
00204   eventSetup.get<MuonGeometryRecord>().get(cscGeom);
00205 
00206   // Get the RecHits collection :
00207   Handle<CSCRecHit2DCollection> recHits;
00208   event.getByLabel(cscRecHitTag,recHits);
00209 
00210   // Get the SimHits (if applicable)
00211   Handle<PSimHitContainer> simHits;
00212   if (isSimulation) event.getByLabel(simHitTag, simHits);
00213 
00214   // get CSC segment collection
00215   Handle<CSCSegmentCollection> cscSegments;
00216   event.getByLabel(cscSegTag, cscSegments);
00217 
00218   // get the trigger collection
00219   edm::Handle<L1MuGMTReadoutCollection> pCollection;
00220   if (makeTriggerPlots || useTriggerFilter || (useDigis && makeTimeMonitorPlots)){
00221     event.getByLabel(l1aTag,pCollection);
00222   }
00223   edm::Handle<TriggerResults> hlt;
00224   if (makeHLTPlots) event.getByLabel(hltTag,hlt);
00225 
00226   // get the standalone muon collection
00227   Handle<reco::TrackCollection> saMuons;
00228   if (makeStandalonePlots || useQualityFilter) event.getByLabel(saMuonTag,saMuons);
00229 
00230 
00231 
00233   // Run the modules //
00235 
00236   // Only do this for the first event
00237   // this is probably outdated and needs to be looked at
00238   if (nEventsAnalyzed == 1 && makeCalibPlots) doCalibrations(eventSetup);
00239 
00240   // Look at the l1a trigger info (returns true if csc L1A present)
00241   bool CSCL1A = false;
00242   if (makeTriggerPlots || useTriggerFilter) CSCL1A = doTrigger(pCollection);
00243   if (!useTriggerFilter) CSCL1A = true;  // always true if not filtering on trigger
00244 
00245   cleanEvent = false;
00246   if (makeStandalonePlots || useQualityFilter) cleanEvent = filterEvents(recHits,cscSegments,saMuons);
00247   if (!useQualityFilter) cleanEvent = true; // always true if not filtering on event quality
00248   
00249   // look at various chamber occupancies
00250   // keep this outside of filter for diagnostics???
00251   if (makeOccupancyPlots && CSCL1A) doOccupancies(strips,wires,recHits,cscSegments);
00252 
00253   bool HLT = false;
00254   if (makeHLTPlots) HLT = doHLT(hlt);
00255 
00256   if (cleanEvent && CSCL1A){
00257     // general look at strip digis
00258     if (makeStripPlots && useDigis) doStripDigis(strips);
00259 
00260     // general look at wire digis
00261     if (makeWirePlots && useDigis) doWireDigis(wires);
00262 
00263     // general look at rechits
00264     if (makeRecHitPlots) doRecHits(recHits,cscGeom);
00265 
00266     // look at simHits
00267     if (isSimulation && makeSimHitPlots) doSimHits(recHits,simHits);
00268 
00269     // general look at Segments
00270     if (makeSegmentPlots) doSegments(cscSegments,cscGeom);
00271 
00272     // look at hit resolution
00273     if (makeResolutionPlots) doResolution(cscSegments,cscGeom);
00274 
00275     // look at Pedestal Noise
00276     if (makePedNoisePlots && useDigis) doPedestalNoise(strips);
00277   
00278     // look at recHit and segment efficiencies
00279     if (makeEfficiencyPlots) doEfficiencies(wires,strips, recHits, cscSegments,cscGeom);
00280 
00281     // gas gain
00282     if (makeGasGainPlots && useDigis) doGasGain(*wires,*strips,*recHits);
00283 
00284     // AFEB timing
00285     if (makeAFEBTimingPlots && useDigis) doAFEBTiming(*wires);
00286 
00287     // Comparators timing
00288     if (makeCompTimingPlots && useDigis) doCompTiming(*compars);
00289 
00290     // strip ADC timing
00291     if (makeADCTimingPlots) doADCTiming(*recHits);
00292 
00293     // recHit Noise
00294     if (makeRHNoisePlots && useDigis) doNoiseHits(recHits,cscSegments,cscGeom,strips);
00295 
00296     // look at standalone muons (not implemented yet)
00297     if (makeStandalonePlots) doStandalone(saMuons);
00298 
00299     // make plots for monitoring the trigger and offline timing
00300     if (makeTimeMonitorPlots) doTimeMonitoring(recHits,cscSegments, alcts, clcts, correlatedlcts, pCollection,cscGeom, eventSetup, event);
00301 
00302     firstEvent = false;
00303 
00304   }
00305 
00306 }
00307 
00308 // ==============================================
00309 //
00310 // event filter, returns true only for events with "good" standalone muon
00311 //
00312 // ==============================================
00313 
00314 bool CSCValidation::filterEvents(edm::Handle<CSCRecHit2DCollection> recHits, edm::Handle<CSCSegmentCollection> cscSegments,
00315                                  edm::Handle<reco::TrackCollection> saMuons){
00316 
00317   //int  nGoodSAMuons = 0;
00318 
00319   if (recHits->size() < 4 || recHits->size() > 100) return false;
00320   if (cscSegments->size() < 1 || cscSegments->size() > 15) return false;
00321   return true;
00322   //if (saMuons->size() != 1) return false;
00323   /*
00324   for(reco::TrackCollection::const_iterator muon = saMuons->begin(); muon != saMuons->end(); ++ muon ) {  
00325     double p  = muon->p();
00326     double reducedChisq = muon->normalizedChi2();
00327 
00328     GlobalPoint  innerPnt(muon->innerPosition().x(),muon->innerPosition().y(),muon->innerPosition().z());
00329     GlobalPoint  outerPnt(muon->outerPosition().x(),muon->outerPosition().y(),muon->outerPosition().z());
00330     GlobalVector innerKin(muon->innerMomentum().x(),muon->innerMomentum().y(),muon->innerMomentum().z());
00331     GlobalVector outerKin(muon->outerMomentum().x(),muon->outerMomentum().y(),muon->outerMomentum().z());
00332     GlobalVector deltaPnt = innerPnt - outerPnt;
00333     double crudeLength = deltaPnt.mag();
00334     double deltaPhi = innerPnt.phi() - outerPnt.phi();
00335     double innerGlobalPolarAngle = innerKin.theta();
00336     double outerGlobalPolarAngle = outerKin.theta();
00337 
00338     int nCSCHits = 0;
00339     for (trackingRecHit_iterator hit = muon->recHitsBegin(); hit != muon->recHitsEnd(); ++hit ) {
00340       if ( (*hit)->isValid() ) {
00341         const DetId detId( (*hit)->geographicalId() );
00342         if (detId.det() == DetId::Muon) {
00343           if (detId.subdetId() == MuonSubdetId::CSC) {
00344             nCSCHits++;
00345           } // this is a CSC hit
00346         } // this is a muon hit
00347       } // hit is valid
00348     } // end loop over rechits
00349 
00350     bool goodSAMuon = (p > pMin)
00351       && ( reducedChisq < chisqMax )
00352       && ( nCSCHits >= nCSCHitsMin )
00353       && ( nCSCHits <= nCSCHitsMax )
00354       && ( crudeLength > lengthMin )
00355       && ( crudeLength < lengthMax );
00356 
00357     
00358     goodSAMuon = goodSAMuon && ( fabs(deltaPhi) < deltaPhiMax );
00359     goodSAMuon = goodSAMuon &&
00360       (
00361        ( (     innerGlobalPolarAngle > polarMin) && (     innerGlobalPolarAngle < polarMax) ) ||
00362        ( (M_PI-innerGlobalPolarAngle > polarMin) && (M_PI-innerGlobalPolarAngle < polarMax) )
00363        );
00364     goodSAMuon = goodSAMuon &&
00365       (
00366        ( (     outerGlobalPolarAngle > polarMin) && (     outerGlobalPolarAngle < polarMax) ) ||
00367        ( (M_PI-outerGlobalPolarAngle > polarMin) && (M_PI-outerGlobalPolarAngle < polarMax) )
00368        );
00369 
00370    //goodSAMuon = goodSAMuon && (nCSCHits > nCSCHitsMin) && (nCSCHits < 13);  
00371    //goodSAMuon = goodSAMuon && (nCSCHits > 13) && (nCSCHits < 19);
00372    //goodSAMuon = goodSAMuon && (nCSCHits > 19) && (nCSCHits < nCSCHitsMax);
00373 
00374 
00375    if (goodSAMuon) nGoodSAMuons++;
00376    
00377   } // end loop over stand-alone muon collection
00378 
00379 
00380   histos->fill1DHist(nGoodSAMuons,"hNGoodMuons", "Number of Good STA Muons per Event",11,-0.5,10.5,"STAMuons");
00381 
00382   if (nGoodSAMuons == 1) return true;
00383   return false;
00384   */
00385 }
00386 
00387 // ==============================================
00388 //
00389 // look at Occupancies
00390 //
00391 // ==============================================
00392 
00393 void CSCValidation::doOccupancies(edm::Handle<CSCStripDigiCollection> strips, edm::Handle<CSCWireDigiCollection> wires,
00394                                   edm::Handle<CSCRecHit2DCollection> recHits, edm::Handle<CSCSegmentCollection> cscSegments){
00395 
00396   bool wireo[2][4][4][36];
00397   bool stripo[2][4][4][36];
00398   bool rechito[2][4][4][36];
00399   bool segmento[2][4][4][36];
00400 
00401   bool hasWires = false;
00402   bool hasStrips = false;
00403   bool hasRecHits = false;
00404   bool hasSegments = false;
00405 
00406   for (int e = 0; e < 2; e++){
00407     for (int s = 0; s < 4; s++){
00408       for (int r = 0; r < 4; r++){
00409         for (int c = 0; c < 36; c++){
00410           wireo[e][s][r][c] = false;
00411           stripo[e][s][r][c] = false;
00412           rechito[e][s][r][c] = false;
00413           segmento[e][s][r][c] = false;
00414         }
00415       }
00416     }
00417   }
00418 
00419   if (useDigis){
00420     //wires
00421     for (CSCWireDigiCollection::DigiRangeIterator wi=wires->begin(); wi!=wires->end(); wi++) {
00422       CSCDetId id = (CSCDetId)(*wi).first;
00423       int kEndcap  = id.endcap();
00424       int kRing    = id.ring();
00425       int kStation = id.station();
00426       int kChamber = id.chamber();
00427       std::vector<CSCWireDigi>::const_iterator wireIt = (*wi).second.first;
00428       std::vector<CSCWireDigi>::const_iterator lastWire = (*wi).second.second;
00429       for( ; wireIt != lastWire; ++wireIt){
00430         if (!wireo[kEndcap-1][kStation-1][kRing-1][kChamber-1]){
00431           wireo[kEndcap-1][kStation-1][kRing-1][kChamber-1] = true;
00432           hOWires->Fill(kChamber,typeIndex(id));
00433           histos->fill1DHist(chamberSerial(id),"hOWireSerial","Wire Occupancy by Chamber Serial",601,-0.5,600.5,"Digis");
00434           hasWires = true;
00435         }
00436       }
00437     }
00438   
00439     //strips
00440     for (CSCStripDigiCollection::DigiRangeIterator si=strips->begin(); si!=strips->end(); si++) {
00441       CSCDetId id = (CSCDetId)(*si).first;
00442       int kEndcap  = id.endcap();
00443       int kRing    = id.ring();
00444       int kStation = id.station();
00445       int kChamber = id.chamber();
00446       std::vector<CSCStripDigi>::const_iterator stripIt = (*si).second.first;
00447       std::vector<CSCStripDigi>::const_iterator lastStrip = (*si).second.second;
00448       for( ; stripIt != lastStrip; ++stripIt) {
00449         std::vector<int> myADCVals = stripIt->getADCCounts();
00450         bool thisStripFired = false;
00451         float thisPedestal = 0.5*(float)(myADCVals[0]+myADCVals[1]);
00452         float threshold = 13.3 ;
00453         float diff = 0.;
00454         for (unsigned int iCount = 0; iCount < myADCVals.size(); iCount++) {
00455           diff = (float)myADCVals[iCount]-thisPedestal;
00456           if (diff > threshold) { thisStripFired = true; }
00457         }
00458         if (thisStripFired) {
00459           if (!stripo[kEndcap-1][kStation-1][kRing-1][kChamber-1]){
00460             stripo[kEndcap-1][kStation-1][kRing-1][kChamber-1] = true;
00461             hOStrips->Fill(kChamber,typeIndex(id));
00462             histos->fill1DHist(chamberSerial(id),"hOStripSerial","Strip Occupancy by Chamber Serial",601,-0.5,600.5,"Digis");
00463             hasStrips = true;
00464           }
00465         }
00466       }
00467     }
00468   }
00469 
00470   //rechits
00471   CSCRecHit2DCollection::const_iterator recIt;
00472   for (recIt = recHits->begin(); recIt != recHits->end(); recIt++) {
00473     CSCDetId idrec = (CSCDetId)(*recIt).cscDetId();
00474     int kEndcap  = idrec.endcap();
00475     int kRing    = idrec.ring();
00476     int kStation = idrec.station();
00477     int kChamber = idrec.chamber();
00478     if (!rechito[kEndcap-1][kStation-1][kRing-1][kChamber-1]){
00479       rechito[kEndcap-1][kStation-1][kRing-1][kChamber-1] = true;
00480       histos->fill1DHist(chamberSerial(idrec),"hORecHitsSerial","RecHit Occupancy by Chamber Serial",601,-0.5,600.5,"recHits");
00481       hORecHits->Fill(kChamber,typeIndex(idrec));
00482       hasRecHits = true;
00483     }
00484   }
00485 
00486   //segments
00487   for(CSCSegmentCollection::const_iterator segIt=cscSegments->begin(); segIt != cscSegments->end(); segIt++) {
00488     CSCDetId id  = (CSCDetId)(*segIt).cscDetId();
00489     int kEndcap  = id.endcap();
00490     int kRing    = id.ring();
00491     int kStation = id.station();
00492     int kChamber = id.chamber();
00493     if (!segmento[kEndcap-1][kStation-1][kRing-1][kChamber-1]){
00494       segmento[kEndcap-1][kStation-1][kRing-1][kChamber-1] = true;
00495       histos->fill1DHist(chamberSerial(id),"hOSegmentsSerial","Segment Occupancy by Chamber Serial",601,-0.5,600.5,"Segments");
00496       hOSegments->Fill(kChamber,typeIndex(id));
00497       hasSegments = true;
00498     }
00499   }
00500 
00501   // overall CSC occupancy (events with CSC data compared to total)
00502   histos->fill1DHist(1,"hCSCOccupancy","overall CSC occupancy",15,-0.5,14.5,"GeneralHists");
00503   if (hasWires) histos->fill1DHist(3,"hCSCOccupancy","overall CSC occupancy",15,-0.5,14.5,"GeneralHists");
00504   if (hasStrips) histos->fill1DHist(5,"hCSCOccupancy","overall CSC occupancy",15,-0.5,14.5,"GeneralHists");
00505   if (hasWires && hasStrips) histos->fill1DHist(7,"hCSCOccupancy","overall CSC occupancy",15,-0.5,14.5,"GeneralHists");
00506   if (hasRecHits) histos->fill1DHist(9,"hCSCOccupancy","overall CSC occupancy",15,-0.5,14.5,"GeneralHists");
00507   if (hasSegments) histos->fill1DHist(11,"hCSCOccupancy","overall CSC occupancy",15,-0.5,14.5,"GeneralHists");
00508   if (!cleanEvent) histos->fill1DHist(13,"hCSCOccupancy","overall CSC occupancy",15,-0.5,14.5,"GeneralHists");
00509 
00510 }
00511 
00512 // ==============================================
00513 //
00514 // look at Trigger info
00515 //
00516 // ==============================================
00517 
00518 bool CSCValidation::doTrigger(edm::Handle<L1MuGMTReadoutCollection> pCollection){
00519 
00520   std::vector<L1MuGMTReadoutRecord> L1Mrec = pCollection->getRecords();
00521   std::vector<L1MuGMTReadoutRecord>::const_iterator igmtrr;
00522 
00523   bool csc_l1a  = false;
00524   bool dt_l1a   = false;
00525   bool rpcf_l1a = false;
00526   bool rpcb_l1a = false;
00527   bool beamHaloTrigger = false;
00528 
00529   int myBXNumber = -1000;
00530 
00531   for(igmtrr=L1Mrec.begin(); igmtrr!=L1Mrec.end(); igmtrr++) {
00532     std::vector<L1MuRegionalCand>::const_iterator iter1;
00533     std::vector<L1MuRegionalCand> rmc;
00534 
00535     // CSC
00536     int icsc = 0;
00537     rmc = igmtrr->getCSCCands();
00538     for(iter1=rmc.begin(); iter1!=rmc.end(); iter1++) {
00539       if ( !(*iter1).empty() ) {
00540         icsc++;
00541         int kQuality = (*iter1).quality();   // kQuality = 1 means beam halo
00542         if (kQuality == 1) beamHaloTrigger = true;
00543       }
00544     }
00545     if (igmtrr->getBxInEvent() == 0 && icsc>0) csc_l1a = true;
00546     if (igmtrr->getBxInEvent() == 0 ) { myBXNumber = igmtrr->getBxNr(); }
00547 
00548     // DT
00549     int idt = 0;
00550     rmc = igmtrr->getDTBXCands();
00551     for(iter1=rmc.begin(); iter1!=rmc.end(); iter1++) {
00552       if ( !(*iter1).empty() ) {
00553         idt++;
00554       }
00555     }
00556     if(igmtrr->getBxInEvent()==0 && idt>0) dt_l1a = true;
00557 
00558     // RPC Barrel
00559     int irpcb = 0;
00560     rmc = igmtrr->getBrlRPCCands();
00561     for(iter1=rmc.begin(); iter1!=rmc.end(); iter1++) {
00562       if ( !(*iter1).empty() ) {
00563         irpcb++;
00564       }
00565     }
00566     if(igmtrr->getBxInEvent()==0 && irpcb>0) rpcb_l1a = true;
00567 
00568     // RPC Forward
00569     int irpcf = 0;
00570     rmc = igmtrr->getFwdRPCCands();
00571     for(iter1=rmc.begin(); iter1!=rmc.end(); iter1++) {
00572       if ( !(*iter1).empty() ) {
00573         irpcf++;
00574       }
00575     }
00576     if(igmtrr->getBxInEvent()==0 && irpcf>0) rpcf_l1a = true;
00577 
00578   }
00579 
00580   // Fill some histograms with L1A info
00581   if (csc_l1a)          histos->fill1DHist(myBXNumber,"vtBXNumber","BX Number",4001,-0.5,4000.5,"Trigger");
00582   if (csc_l1a)          histos->fill1DHist(1,"vtBits","trigger bits",11,-0.5,10.5,"Trigger");
00583   if (dt_l1a)           histos->fill1DHist(2,"vtBits","trigger bits",11,-0.5,10.5,"Trigger");
00584   if (rpcb_l1a)         histos->fill1DHist(3,"vtBits","trigger bits",11,-0.5,10.5,"Trigger");
00585   if (rpcf_l1a)         histos->fill1DHist(4,"vtBits","trigger bits",11,-0.5,10.5,"Trigger");
00586   if (beamHaloTrigger)  histos->fill1DHist(8,"vtBits","trigger bits",11,-0.5,10.5,"Trigger");
00587 
00588   if (csc_l1a) {
00589     histos->fill1DHist(1,"vtCSCY","trigger bits",11,-0.5,10.5,"Trigger");
00590     if (dt_l1a)   histos->fill1DHist(2,"vtCSCY","trigger bits",11,-0.5,10.5,"Trigger");
00591     if (rpcb_l1a) histos->fill1DHist(3,"vtCSCY","trigger bits",11,-0.5,10.5,"Trigger");
00592     if (rpcf_l1a) histos->fill1DHist(4,"vtCSCY","trigger bits",11,-0.5,10.5,"Trigger");
00593     if (  dt_l1a || rpcb_l1a || rpcf_l1a)  histos->fill1DHist(5,"vtCSCY","trigger bits",11,-0.5,10.5,"Trigger");
00594     if (!(dt_l1a || rpcb_l1a || rpcf_l1a)) histos->fill1DHist(6,"vtCSCY","trigger bits",11,-0.5,10.5,"Trigger");
00595   } else {
00596     histos->fill1DHist(1,"vtCSCN","trigger bits",11,-0.5,10.5,"Trigger");
00597     if (dt_l1a)   histos->fill1DHist(2,"vtCSCN","trigger bits",11,-0.5,10.5,"Trigger");
00598     if (rpcb_l1a) histos->fill1DHist(3,"vtCSCN","trigger bits",11,-0.5,10.5,"Trigger");
00599     if (rpcf_l1a) histos->fill1DHist(4,"vtCSCN","trigger bits",11,-0.5,10.5,"Trigger");
00600     if (  dt_l1a || rpcb_l1a || rpcf_l1a)  histos->fill1DHist(5,"vtCSCN","trigger bits",11,-0.5,10.5,"Trigger");
00601     if (!(dt_l1a || rpcb_l1a || rpcf_l1a)) histos->fill1DHist(6,"vtCSCN","trigger bits",11,-0.5,10.5,"Trigger");
00602   }
00603 
00604   // if valid CSC L1A then return true for possible use elsewhere
00605 
00606   if (csc_l1a) return true;
00607   
00608   return false;
00609 
00610 }
00611 
00612 // ==============================================
00613 //    
00614 // look at HLT Trigger
00615 //  
00616 // ==============================================
00617 
00618 bool CSCValidation::doHLT(Handle<TriggerResults> hlt){
00619 
00620   // HLT stuff
00621   int hltSize = hlt->size();
00622   for (int i = 0; i < hltSize; ++i){
00623     if (hlt->accept(i)) histos->fill1DHist(i,"hltBits","HLT Trigger Bits",hltSize+1,-0.5,(float)hltSize+0.5,"Trigger");
00624   }
00625 
00626   return true;
00627 }
00628 
00629 
00630 // ==============================================
00631 //
00632 // look at Calibrations
00633 //
00634 // ==============================================
00635 
00636 void CSCValidation::doCalibrations(const edm::EventSetup& eventSetup){
00637 
00638   // Only do this for the first event
00639   if (nEventsAnalyzed == 1){
00640 
00641     LogDebug("Calibrations") << "Loading Calibrations...";
00642 
00643     // get the gains
00644     edm::ESHandle<CSCDBGains> hGains;
00645     eventSetup.get<CSCDBGainsRcd>().get( hGains );
00646     const CSCDBGains* pGains = hGains.product();
00647     // get the crosstalks
00648     edm::ESHandle<CSCDBCrosstalk> hCrosstalk;
00649     eventSetup.get<CSCDBCrosstalkRcd>().get( hCrosstalk );
00650     const CSCDBCrosstalk* pCrosstalk = hCrosstalk.product();
00651     // get the noise matrix
00652     edm::ESHandle<CSCDBNoiseMatrix> hNoiseMatrix;
00653     eventSetup.get<CSCDBNoiseMatrixRcd>().get( hNoiseMatrix );
00654     const CSCDBNoiseMatrix* pNoiseMatrix = hNoiseMatrix.product();
00655     // get pedestals
00656     edm::ESHandle<CSCDBPedestals> hPedestals;
00657     eventSetup.get<CSCDBPedestalsRcd>().get( hPedestals );
00658     const CSCDBPedestals* pPedestals = hPedestals.product();
00659 
00660     LogDebug("Calibrations") << "Calibrations Loaded!";
00661 
00662     for (int i = 0; i < 400; i++){
00663       int bin = i+1;
00664       histos->fillCalibHist(pGains->gains[i].gain_slope,"hCalibGainsS","Gains Slope",400,0,400,bin,"Calib");
00665       histos->fillCalibHist(pCrosstalk->crosstalk[i].xtalk_slope_left,"hCalibXtalkSL","Xtalk Slope Left",400,0,400,bin,"Calib");
00666       histos->fillCalibHist(pCrosstalk->crosstalk[i].xtalk_slope_right,"hCalibXtalkSR","Xtalk Slope Right",400,0,400,bin,"Calib");
00667       histos->fillCalibHist(pCrosstalk->crosstalk[i].xtalk_intercept_left,"hCalibXtalkIL","Xtalk Intercept Left",400,0,400,bin,"Calib");
00668       histos->fillCalibHist(pCrosstalk->crosstalk[i].xtalk_intercept_right,"hCalibXtalkIR","Xtalk Intercept Right",400,0,400,bin,"Calib");
00669       histos->fillCalibHist(pPedestals->pedestals[i].ped,"hCalibPedsP","Peds",400,0,400,bin,"Calib");
00670       histos->fillCalibHist(pPedestals->pedestals[i].rms,"hCalibPedsR","Peds RMS",400,0,400,bin,"Calib");
00671       histos->fillCalibHist(pNoiseMatrix->matrix[i].elem33,"hCalibNoise33","Noise Matrix 33",400,0,400,bin,"Calib");
00672       histos->fillCalibHist(pNoiseMatrix->matrix[i].elem34,"hCalibNoise34","Noise Matrix 34",400,0,400,bin,"Calib");
00673       histos->fillCalibHist(pNoiseMatrix->matrix[i].elem35,"hCalibNoise35","Noise Matrix 35",400,0,400,bin,"Calib");
00674       histos->fillCalibHist(pNoiseMatrix->matrix[i].elem44,"hCalibNoise44","Noise Matrix 44",400,0,400,bin,"Calib");
00675       histos->fillCalibHist(pNoiseMatrix->matrix[i].elem45,"hCalibNoise45","Noise Matrix 45",400,0,400,bin,"Calib");
00676       histos->fillCalibHist(pNoiseMatrix->matrix[i].elem46,"hCalibNoise46","Noise Matrix 46",400,0,400,bin,"Calib");
00677       histos->fillCalibHist(pNoiseMatrix->matrix[i].elem55,"hCalibNoise55","Noise Matrix 55",400,0,400,bin,"Calib");
00678       histos->fillCalibHist(pNoiseMatrix->matrix[i].elem56,"hCalibNoise56","Noise Matrix 56",400,0,400,bin,"Calib");
00679       histos->fillCalibHist(pNoiseMatrix->matrix[i].elem57,"hCalibNoise57","Noise Matrix 57",400,0,400,bin,"Calib");
00680       histos->fillCalibHist(pNoiseMatrix->matrix[i].elem66,"hCalibNoise66","Noise Matrix 66",400,0,400,bin,"Calib");
00681       histos->fillCalibHist(pNoiseMatrix->matrix[i].elem67,"hCalibNoise67","Noise Matrix 67",400,0,400,bin,"Calib");
00682       histos->fillCalibHist(pNoiseMatrix->matrix[i].elem77,"hCalibNoise77","Noise Matrix 77",400,0,400,bin,"Calib");
00683 
00684  
00685     }
00686 
00687   }
00688 
00689 
00690 }
00691 
00692 
00693 // ==============================================
00694 //
00695 // look at WIRE DIGIs
00696 //
00697 // ==============================================
00698 
00699 void CSCValidation::doWireDigis(edm::Handle<CSCWireDigiCollection> wires){
00700 
00701   int nWireGroupsTotal = 0;
00702   for (CSCWireDigiCollection::DigiRangeIterator dWDiter=wires->begin(); dWDiter!=wires->end(); dWDiter++) {
00703     CSCDetId id = (CSCDetId)(*dWDiter).first;
00704     std::vector<CSCWireDigi>::const_iterator wireIter = (*dWDiter).second.first;
00705     std::vector<CSCWireDigi>::const_iterator lWire = (*dWDiter).second.second;
00706     for( ; wireIter != lWire; ++wireIter) {
00707       int myWire = wireIter->getWireGroup();
00708       int myTBin = wireIter->getTimeBin();
00709       nWireGroupsTotal++;
00710       histos->fill1DHistByType(myWire,"hWireWire","Wiregroup Numbers Fired",id,113,-0.5,112.5,"Digis");
00711       histos->fill1DHistByType(myTBin,"hWireTBin","Wire TimeBin Fired",id,17,-0.5,16.5,"Digis");
00712       histos->fillProfile(chamberSerial(id),myTBin,"hWireTBinProfile","Wire TimeBin Fired",601,-0.5,600.5,-0.5,16.5,"Digis");
00713       if (detailedAnalysis){
00714         histos->fill1DHistByLayer(myWire,"hWireWire","Wiregroup Numbers Fired",id,113,-0.5,112.5,"WireNumberByLayer");
00715         histos->fill1DHistByLayer(myTBin,"hWireTBin","Wire TimeBin Fired",id,17,-0.5,16.5,"WireTimeByLayer");
00716       }
00717     }
00718   } // end wire loop
00719 
00720   // this way you can zero suppress but still store info on # events with no digis
00721   if (nWireGroupsTotal == 0) nWireGroupsTotal = -1;
00722 
00723   histos->fill1DHist(nWireGroupsTotal,"hWirenGroupsTotal","Wires Fired Per Event",151,-0.5,150.5,"Digis");
00724   
00725 }
00726 
00727 // ==============================================
00728 //
00729 // look at STRIP DIGIs
00730 //
00731 // ==============================================
00732 
00733 void CSCValidation::doStripDigis(edm::Handle<CSCStripDigiCollection> strips){
00734 
00735   int nStripsFired = 0;
00736   for (CSCStripDigiCollection::DigiRangeIterator dSDiter=strips->begin(); dSDiter!=strips->end(); dSDiter++) {
00737     CSCDetId id = (CSCDetId)(*dSDiter).first;
00738     std::vector<CSCStripDigi>::const_iterator stripIter = (*dSDiter).second.first;
00739     std::vector<CSCStripDigi>::const_iterator lStrip = (*dSDiter).second.second;
00740     for( ; stripIter != lStrip; ++stripIter) {
00741       int myStrip = stripIter->getStrip();
00742       std::vector<int> myADCVals = stripIter->getADCCounts();
00743       bool thisStripFired = false;
00744       float thisPedestal = 0.5*(float)(myADCVals[0]+myADCVals[1]);
00745       float threshold = 13.3 ;
00746       float diff = 0.;
00747       for (unsigned int iCount = 0; iCount < myADCVals.size(); iCount++) {
00748         diff = (float)myADCVals[iCount]-thisPedestal;
00749         if (diff > threshold) { thisStripFired = true; }
00750       } 
00751       if (thisStripFired) {
00752         nStripsFired++;
00753         // fill strip histos
00754         histos->fill1DHistByType(myStrip,"hStripStrip","Strip Number",id,81,-0.5,80.5,"Digis");
00755         if (detailedAnalysis){
00756           histos->fill1DHistByLayer(myStrip,"hStripStrip","Strip Number",id,81,-0.5,80.5,"StripNumberByLayer");
00757         }
00758       }
00759     }
00760   } // end strip loop
00761 
00762   if (nStripsFired == 0) nStripsFired = -1;
00763 
00764   histos->fill1DHist(nStripsFired,"hStripNFired","Fired Strips per Event",251,-0.5,250.5,"Digis");
00765 
00766 }
00767 
00768 //=======================================================
00769 //
00770 // Look at the Pedestal Noise Distributions
00771 //
00772 //=======================================================
00773 
00774 void CSCValidation::doPedestalNoise(edm::Handle<CSCStripDigiCollection> strips){
00775 
00776   for (CSCStripDigiCollection::DigiRangeIterator dPNiter=strips->begin(); dPNiter!=strips->end(); dPNiter++) {
00777     CSCDetId id = (CSCDetId)(*dPNiter).first;
00778     std::vector<CSCStripDigi>::const_iterator pedIt = (*dPNiter).second.first;
00779     std::vector<CSCStripDigi>::const_iterator lStrip = (*dPNiter).second.second;
00780     for( ; pedIt != lStrip; ++pedIt) {
00781       int myStrip = pedIt->getStrip();
00782       std::vector<int> myADCVals = pedIt->getADCCounts();
00783       float TotalADC = getSignal(*strips, id, myStrip);
00784       bool thisStripFired = false;
00785       float thisPedestal = 0.5*(float)(myADCVals[0]+myADCVals[1]);
00786       float thisSignal = (1./6)*(myADCVals[2]+myADCVals[3]+myADCVals[4]+myADCVals[5]+myADCVals[6]+myADCVals[7]);
00787       float threshold = 13.3;
00788       if(id.station() == 1 && id.ring() == 4)
00789         {
00790           if(myStrip <= 16) myStrip += 64; // no trapping for any bizarreness
00791         }
00792       if (TotalADC > threshold) { thisStripFired = true;}
00793       if (!thisStripFired){
00794         float ADC = thisSignal - thisPedestal;
00795         histos->fill1DHist(ADC,"hStripPed","Pedestal Noise Distribution",50,-25.,25.,"PedestalNoise");
00796         histos->fill1DHistByType(ADC,"hStripPedME","Pedestal Noise Distribution",id,50,-25.,25.,"PedestalNoise");
00797         histos->fillProfile(chamberSerial(id),ADC,"hStripPedMEProfile","Wire TimeBin Fired",601,-0.5,600.5,-25,25,"PedestalNoise");
00798         if (detailedAnalysis){
00799           histos->fill1DHistByLayer(ADC,"hStripPedME","Pedestal Noise Distribution",id,50,-25.,25.,"PedestalNoiseByLayer");
00800         }
00801       }
00802     }
00803   }
00804 
00805 }
00806 
00807 
00808 // ==============================================
00809 //
00810 // look at RECHITs
00811 //
00812 // ==============================================
00813 
00814 void CSCValidation::doRecHits(edm::Handle<CSCRecHit2DCollection> recHits, edm::ESHandle<CSCGeometry> cscGeom){
00815 
00816   // Get the RecHits collection :
00817   int nRecHits = recHits->size();
00818  
00819   // ---------------------
00820   // Loop over rechits 
00821   // ---------------------
00822   int iHit = 0;
00823 
00824   // Build iterator for rechits and loop :
00825   CSCRecHit2DCollection::const_iterator dRHIter;
00826   for (dRHIter = recHits->begin(); dRHIter != recHits->end(); dRHIter++) {
00827     iHit++;
00828 
00829     // Find chamber with rechits in CSC 
00830     CSCDetId idrec = (CSCDetId)(*dRHIter).cscDetId();
00831     int kEndcap  = idrec.endcap();
00832     int kRing    = idrec.ring();
00833     int kStation = idrec.station();
00834     int kChamber = idrec.chamber();
00835     int kLayer   = idrec.layer();
00836 
00837     // Store rechit as a Local Point:
00838     LocalPoint rhitlocal = (*dRHIter).localPosition();  
00839     float xreco = rhitlocal.x();
00840     float yreco = rhitlocal.y();
00841     LocalError rerrlocal = (*dRHIter).localPositionError();  
00842     //these errors are squared!
00843     float xxerr = rerrlocal.xx();
00844     float yyerr = rerrlocal.yy();
00845     float xyerr = rerrlocal.xy();
00846     // errors in strip units
00847     float stpos = (*dRHIter).positionWithinStrip();
00848     float sterr = (*dRHIter).errorWithinStrip();
00849 
00850     // Find the charge associated with this hit
00851     CSCRecHit2D::ADCContainer adcs = (*dRHIter).adcs();
00852     int adcsize = adcs.size();
00853     float rHSumQ = 0;
00854     float sumsides = 0;
00855     for (int i = 0; i < adcsize; i++){
00856       if (i != 3 && i != 7 && i != 11){
00857         rHSumQ = rHSumQ + adcs[i]; 
00858       }
00859       if (adcsize == 12 && (i < 3 || i > 7) && i < 11){
00860         sumsides = sumsides + adcs[i];
00861       }
00862     }
00863     float rHratioQ = sumsides/rHSumQ;
00864     if (adcsize != 12) rHratioQ = -99;
00865 
00866     // Get the signal timing of this hit
00867     float rHtime = 0;
00868     rHtime = (*dRHIter).tpeak()/50.;
00869 
00870     // Get pointer to the layer:
00871     const CSCLayer* csclayer = cscGeom->layer( idrec );
00872 
00873     // Transform hit position from local chamber geometry to global CMS geom
00874     GlobalPoint rhitglobal= csclayer->toGlobal(rhitlocal);
00875     float grecx   =  rhitglobal.x();
00876     float grecy   =  rhitglobal.y();
00877 
00878     // Fill the rechit position branch
00879     if (writeTreeToFile && rhTreeCount < 1500000){
00880       histos->fillRechitTree(xreco, yreco, grecx, grecy, kEndcap, kStation, kRing, kChamber, kLayer);
00881       rhTreeCount++;
00882     }    
00883 
00884     // Fill some histograms
00885     // only fill if 3 strips were used in the hit
00886     histos->fill2DHistByStation(grecx,grecy,"hRHGlobal","recHit Global Position",idrec,100,-800.,800.,100,-800.,800.,"recHits");
00887     if (kStation == 1 && (kRing == 1 || kRing == 4)) histos->fill1DHistByType(rHSumQ,"hRHSumQ","Sum 3x3 recHit Charge",idrec,125,0,4000,"recHits");
00888     else histos->fill1DHistByType(rHSumQ,"hRHSumQ","Sum 3x3 recHit Charge",idrec,125,0,2000,"recHits");
00889     histos->fill1DHistByType(rHratioQ,"hRHRatioQ","Charge Ratio (Ql+Qr)/Qt",idrec,120,-0.1,1.1,"recHits");
00890     histos->fill1DHistByType(rHtime,"hRHTiming","recHit Timing",idrec,200,-10,10,"recHits");
00891     histos->fill1DHistByType(sqrt(xxerr),"hRHxerr","RecHit Error on Local X",idrec,100,-0.1,2,"recHits");
00892     histos->fill1DHistByType(sqrt(yyerr),"hRHyerr","RecHit Error on Local Y",idrec,100,-0.1,2,"recHits");
00893     histos->fill1DHistByType(xyerr,"hRHxyerr","Corr. RecHit XY Error",idrec,100,-1,2,"recHits");
00894     if (adcsize == 12) histos->fill1DHistByType(stpos,"hRHstpos","Reconstructed Position on Strip",idrec,120,-0.6,0.6,"recHits");
00895     histos->fill1DHistByType(sterr,"hRHsterr","Estimated Error on Strip Measurement",idrec,120,-0.05,0.25,"recHits");
00896     histos->fillProfile(chamberSerial(idrec),rHSumQ,"hRHSumQProfile","Sum 3x3 recHit Charge",601,-0.5,600.5,0,4000,"recHits");
00897     histos->fillProfile(chamberSerial(idrec),rHtime,"hRHTimingProfile","recHit Timing",601,-0.5,600.5,-11,11,"recHits");
00898     if (detailedAnalysis){
00899       if (kStation == 1 && (kRing == 1 || kRing == 4)) histos->fill1DHistByLayer(rHSumQ,"hRHSumQ","Sum 3x3 recHit Charge",idrec,125,0,4000,"RHQByLayer");
00900       else histos->fill1DHistByLayer(rHSumQ,"hRHSumQ","Sum 3x3 recHit Charge",idrec,125,0,2000,"RHQByLayer");
00901       histos->fill1DHistByLayer(rHratioQ,"hRHRatioQ","Charge Ratio (Ql+Qr)/Qt",idrec,120,-0.1,1.1,"RHQByLayer");
00902       histos->fill1DHistByLayer(rHtime,"hRHTiming","recHit Timing",idrec,200,-10,10,"RHTimingByLayer");
00903       histos->fill2DHistByLayer(xreco,yreco,"hRHLocalXY","recHit Local Position",idrec,50,-100.,100.,75,-150.,150.,"RHLocalXYByLayer");
00904       histos->fill1DHistByLayer(sqrt(xxerr),"hRHxerr","RecHit Error on Local X",idrec,100,-0.1,2,"RHErrorsByLayer");
00905       histos->fill1DHistByLayer(sqrt(yyerr),"hRHyerr","RecHit Error on Local Y",idrec,100,-0.1,2,"RHErrorsByLayer");
00906       histos->fill1DHistByType(stpos,"hRHstpos","Reconstructed Position on Strip",idrec,120,-0.6,0.6,"RHStripPosByLayer");
00907       histos->fill1DHistByType(sterr,"hRHsterr","Estimated Error on Strip Measurement",idrec,120,-0.05,0.25,"RHStripPosByLayer");
00908     }
00909 
00910   } //end rechit loop
00911 
00912   if (nRecHits == 0) nRecHits = -1;
00913 
00914   histos->fill1DHist(nRecHits,"hRHnrechits","recHits per Event (all chambers)",151,-0.5,150.5,"recHits");
00915 
00916 }
00917 
00918 // ==============================================
00919 //
00920 // look at SIMHITS
00921 //
00922 // ==============================================
00923 
00924 void CSCValidation::doSimHits(edm::Handle<CSCRecHit2DCollection> recHits, edm::Handle<PSimHitContainer> simHits){
00925 
00926   CSCRecHit2DCollection::const_iterator dSHrecIter;
00927   for (dSHrecIter = recHits->begin(); dSHrecIter != recHits->end(); dSHrecIter++) {
00928 
00929     CSCDetId idrec = (CSCDetId)(*dSHrecIter).cscDetId();
00930     LocalPoint rhitlocal = (*dSHrecIter).localPosition();
00931     float xreco = rhitlocal.x();
00932     float yreco = rhitlocal.y();
00933     float xError = sqrt((*dSHrecIter).localPositionError().xx());
00934     float yError = sqrt((*dSHrecIter).localPositionError().yy());
00935     float simHitXres = -99;
00936     float simHitYres = -99;
00937     float xPull      = -99;
00938     float yPull      = -99;
00939     float mindiffX   = 99;
00940     float mindiffY   = 10;
00941     // If MC, find closest muon simHit to check resolution:
00942     PSimHitContainer::const_iterator dSHsimIter;
00943     for (dSHsimIter = simHits->begin(); dSHsimIter != simHits->end(); dSHsimIter++){
00944       // Get DetID for this simHit:
00945       CSCDetId sId = (CSCDetId)(*dSHsimIter).detUnitId();
00946       // Check if the simHit detID matches that of current recHit
00947       // and make sure it is a muon hit:
00948       if (sId == idrec && abs((*dSHsimIter).particleType()) == 13){
00949         // Get the position of this simHit in local coordinate system:
00950         LocalPoint sHitlocal = (*dSHsimIter).localPosition();
00951         // Now we need to make reasonably sure that this simHit is
00952         // responsible for this recHit:
00953         if ((sHitlocal.x() - xreco) < mindiffX && (sHitlocal.y() - yreco) < mindiffY){
00954           simHitXres = (sHitlocal.x() - xreco);
00955           simHitYres = (sHitlocal.y() - yreco);
00956           mindiffX = (sHitlocal.x() - xreco);
00957           xPull = simHitXres/xError;
00958           yPull = simHitYres/yError;
00959         }
00960       }
00961     }
00962 
00963     histos->fill1DHistByType(simHitXres,"hSimXResid","SimHitX - Reconstructed X",idrec,100,-1.0,1.0,"Resolution");
00964     histos->fill1DHistByType(simHitYres,"hSimYResid","SimHitY - Reconstructed Y",idrec,100,-5.0,5.0,"Resolution");
00965     histos->fill1DHistByType(xPull,"hSimXPull","Local X Pulls",idrec,100,-5.0,5.0,"Resolution");
00966     histos->fill1DHistByType(yPull,"hSimYPull","Local Y Pulls",idrec,100,-5.0,5.0,"Resolution");
00967 
00968   }
00969 
00970 }
00971 
00972 // ==============================================
00973 //
00974 // look at SEGMENTs
00975 //
00976 // ===============================================
00977 
00978 void CSCValidation::doSegments(edm::Handle<CSCSegmentCollection> cscSegments, edm::ESHandle<CSCGeometry> cscGeom){
00979 
00980   // get CSC segment collection
00981   int nSegments = cscSegments->size();
00982 
00983   // -----------------------
00984   // loop over segments
00985   // -----------------------
00986   int iSegment = 0;
00987   for(CSCSegmentCollection::const_iterator dSiter=cscSegments->begin(); dSiter != cscSegments->end(); dSiter++) {
00988     iSegment++;
00989     //
00990     CSCDetId id  = (CSCDetId)(*dSiter).cscDetId();
00991     int kEndcap  = id.endcap();
00992     int kRing    = id.ring();
00993     int kStation = id.station();
00994     int kChamber = id.chamber();
00995 
00996     //
00997     float chisq    = (*dSiter).chi2();
00998     int nhits      = (*dSiter).nRecHits();
00999     int nDOF       = 2*nhits-4;
01000     double chisqProb = ChiSquaredProbability( (double)chisq, nDOF );
01001     LocalPoint localPos = (*dSiter).localPosition();
01002     float segX     = localPos.x();
01003     float segY     = localPos.y();
01004     LocalVector segDir = (*dSiter).localDirection();
01005     double theta   = segDir.theta();
01006 
01007     // global transformation
01008     float globX = 0.;
01009     float globY = 0.;
01010     float globZ = 0.;
01011     float globpPhi = 0.;
01012     float globR = 0.;
01013     float globTheta = 0.;
01014     float globPhi   = 0.;
01015     const CSCChamber* cscchamber = cscGeom->chamber(id);
01016     if (cscchamber) {
01017       GlobalPoint globalPosition = cscchamber->toGlobal(localPos);
01018       globX = globalPosition.x();
01019       globY = globalPosition.y();
01020       globZ = globalPosition.z();
01021       globpPhi =  globalPosition.phi();
01022       globR   =  sqrt(globX*globX + globY*globY);
01023       GlobalVector globalDirection = cscchamber->toGlobal(segDir);
01024       globTheta = globalDirection.theta();
01025       globPhi   = globalDirection.phi();
01026     }
01027 
01028 
01029     // Fill segment position branch
01030     if (writeTreeToFile && segTreeCount < 1500000){
01031       histos->fillSegmentTree(segX, segY, globX, globY, kEndcap, kStation, kRing, kChamber);
01032       segTreeCount++;
01033     }
01034 
01035     // Fill histos
01036     histos->fill2DHistByStation(globX,globY,"hSGlobal","Segment Global Positions;global x (cm)",id,100,-800.,800.,100,-800.,800.,"Segments");
01037     histos->fill1DHistByType(nhits,"hSnHits","N hits on Segments",id,8,-0.5,7.5,"Segments");
01038     histos->fill1DHistByType(theta,"hSTheta","local theta segments",id,128,-3.2,3.2,"Segments");
01039     histos->fill1DHistByType((chisq/nDOF),"hSChiSq","segments chi-squared/ndof",id,110,-0.05,10.5,"Segments");
01040     histos->fill1DHistByType(chisqProb,"hSChiSqProb","segments chi-squared probability",id,110,-0.05,1.05,"Segments");
01041     histos->fill1DHist(globTheta,"hSGlobalTheta","segment global theta",128,0,3.2,"Segments");
01042     histos->fill1DHist(globPhi,"hSGlobalPhi","segment global phi",128,-3.2,3.2,"Segments");
01043     histos->fillProfile(chamberSerial(id),nhits,"hSnHitsProfile","N hits on Segments",601,-0.5,600.5,-0.5,7.5,"Segments");
01044     if (detailedAnalysis){
01045       histos->fill1DHistByChamber(nhits,"hSnHits","N hits on Segments",id,8,-0.5,7.5,"HitsOnSegmentByChamber");
01046       histos->fill1DHistByChamber(theta,"hSTheta","local theta segments",id,128,-3.2,3.2,"DetailedSegments");
01047       histos->fill1DHistByChamber((chisq/nDOF),"hSChiSq","segments chi-squared/ndof",id,110,-0.05,10.5,"SegChi2ByChamber");
01048       histos->fill1DHistByChamber(chisqProb,"hSChiSqProb","segments chi-squared probability",id,110,-0.05,1.05,"SegChi2ByChamber");
01049     }
01050 
01051   } // end segment loop
01052 
01053   if (nSegments == 0) nSegments = -1;
01054 
01055   histos->fill1DHist(nSegments,"hSnSegments","Segments per Event",31,-0.5,30.5,"Segments");
01056 
01057 }
01058 
01059 // ==============================================
01060 //
01061 // look at hit Resolution
01062 //
01063 // ===============================================
01064 
01065 void CSCValidation::doResolution(edm::Handle<CSCSegmentCollection> cscSegments, edm::ESHandle<CSCGeometry> cscGeom){
01066 
01067 
01068   for(CSCSegmentCollection::const_iterator dSiter=cscSegments->begin(); dSiter != cscSegments->end(); dSiter++) {
01069 
01070     CSCDetId id  = (CSCDetId)(*dSiter).cscDetId();
01071 
01072     //
01073     // try to get the CSC recHits that contribute to this segment.
01074     std::vector<CSCRecHit2D> theseRecHits = (*dSiter).specificRecHits();
01075     int nRH = (*dSiter).nRecHits();
01076     int jRH = 0;
01077     CLHEP::HepMatrix sp(6,1);
01078     CLHEP::HepMatrix se(6,1);
01079     for ( std::vector<CSCRecHit2D>::const_iterator iRH = theseRecHits.begin(); iRH != theseRecHits.end(); iRH++) {
01080       jRH++;
01081       CSCDetId idRH = (CSCDetId)(*iRH).cscDetId();
01082       int kRing    = idRH.ring();
01083       int kStation = idRH.station();
01084       int kLayer   = idRH.layer();
01085 
01086       // Find the strip containing this hit
01087       CSCRecHit2D::ChannelContainer hitstrips = (*iRH).channels();
01088       int nStrips     =  hitstrips.size();
01089       int centerid    =  nStrips/2 + 1;
01090       int centerStrip =  hitstrips[centerid - 1];
01091 
01092       // If this segment has 6 hits, find the position of each hit on the strip in units of stripwidth and store values
01093       if (nRH == 6){
01094         float stpos = (*iRH).positionWithinStrip();
01095         se(kLayer,1) = (*iRH).errorWithinStrip();
01096         // Take into account half-strip staggering of layers (ME1/1 has no staggering)
01097         if (kStation == 1 && (kRing == 1 || kRing == 4)) sp(kLayer,1) = stpos + centerStrip;
01098         else{
01099           if (kLayer == 1 || kLayer == 3 || kLayer == 5) sp(kLayer,1) = stpos + centerStrip;
01100           if (kLayer == 2 || kLayer == 4 || kLayer == 6) sp(kLayer,1) = stpos - 0.5 + centerStrip;
01101         }
01102       }
01103 
01104     }
01105 
01106     float residual = -99;
01107     float pull = -99;
01108     // Fit all points except layer 3, then compare expected value for layer 3 to reconstructed value
01109     if (nRH == 6){
01110       float expected = fitX(sp,se);
01111       residual = expected - sp(3,1);
01112       pull = residual/se(3,1);
01113     }
01114 
01115     // Fill histos
01116     histos->fill1DHistByType(residual,"hSResid","Fitted Position on Strip - Reconstructed for Layer 3",id,100,-0.5,0.5,"Resolution");
01117     histos->fill1DHistByType(pull,"hSStripPosPull","Strip Measurement Pulls",id,100,-5.0,5.0,"Resolution");
01118     histos->fillProfile(chamberSerial(id),residual,"hSResidProfile","Fitted Position on Strip - Reconstructed for Layer 3",601,-0.5,600.5,-0.5,0.5,"Resolution");
01119     if (detailedAnalysis){
01120       histos->fill1DHistByChamber(residual,"hSResid","Fitted Position on Strip - Reconstructed for Layer 3",id,100,-0.5,0.5,"DetailedResolution");
01121       histos->fill1DHistByChamber(pull,"hSStripPosPull","Strip Measurement Pulls",id,100,-5.0,5.0,"Resolution");
01122     }
01123 
01124 
01125   }
01126 
01127 }
01128 
01129 // ==============================================
01130 //
01131 // look at Standalone Muons
01132 //
01133 // ==============================================
01134 
01135 void CSCValidation::doStandalone(Handle<reco::TrackCollection> saMuons){
01136 
01137   int nSAMuons = saMuons->size();
01138   histos->fill1DHist(nSAMuons,"trNSAMuons","N Standalone Muons per Event",6,-0.5,5.5,"STAMuons");
01139 
01140   for(reco::TrackCollection::const_iterator muon = saMuons->begin(); muon != saMuons->end(); ++ muon ) {
01141     float preco  = muon->p();
01142     float ptreco = muon->pt();
01143     int   n = muon->recHitsSize();
01144     float chi2 = muon->chi2();
01145     float normchi2 = muon->normalizedChi2();
01146 
01147     // loop over hits
01148     int nDTHits = 0;
01149     int nCSCHits = 0;
01150     int nCSCHitsp = 0;
01151     int nCSCHitsm = 0;
01152     int nRPCHits = 0;
01153     int nRPCHitsp = 0;
01154     int nRPCHitsm = 0;
01155     int np = 0;
01156     int nm = 0;
01157     std::vector<CSCDetId> staChambers;
01158     for (trackingRecHit_iterator hit = muon->recHitsBegin(); hit != muon->recHitsEnd(); ++hit ) {
01159       const DetId detId( (*hit)->geographicalId() );
01160       if (detId.det() == DetId::Muon) {
01161         if (detId.subdetId() == MuonSubdetId::RPC) {
01162           RPCDetId rpcId(detId.rawId());
01163           nRPCHits++;
01164           if (rpcId.region() == 1){ nRPCHitsp++; np++;}
01165           if (rpcId.region() == -1){ nRPCHitsm++; nm++;}
01166         }
01167         if (detId.subdetId() == MuonSubdetId::DT) {
01168           nDTHits++;
01169         }
01170         else if (detId.subdetId() == MuonSubdetId::CSC) {
01171           CSCDetId cscId(detId.rawId());
01172           staChambers.push_back(detId.rawId());
01173           nCSCHits++;
01174           if (cscId.endcap() == 1){ nCSCHitsp++; np++;}
01175           if (cscId.endcap() == 2){ nCSCHitsm++; nm++;}
01176         }
01177       }
01178     }
01179 
01180     GlobalPoint  innerPnt(muon->innerPosition().x(),muon->innerPosition().y(),muon->innerPosition().z());
01181     GlobalPoint  outerPnt(muon->outerPosition().x(),muon->outerPosition().y(),muon->outerPosition().z());
01182     GlobalVector innerKin(muon->innerMomentum().x(),muon->innerMomentum().y(),muon->innerMomentum().z());
01183     GlobalVector outerKin(muon->outerMomentum().x(),muon->outerMomentum().y(),muon->outerMomentum().z());
01184     GlobalVector deltaPnt = innerPnt - outerPnt;
01185     double crudeLength = deltaPnt.mag();
01186     double deltaPhi = innerPnt.phi() - outerPnt.phi();
01187     double innerGlobalPolarAngle = innerKin.theta();
01188     double outerGlobalPolarAngle = outerKin.theta();
01189 
01190 
01191     // fill histograms
01192     histos->fill1DHist(n,"trN","N hits on a STA Muon Track",51,-0.5,50.5,"STAMuons");
01193     if (np != 0) histos->fill1DHist(np,"trNp","N hits on a STA Muon Track (plus endcap)",51,-0.5,50.5,"STAMuons");
01194     if (nm != 0) histos->fill1DHist(nm,"trNm","N hits on a STA Muon Track (minus endcap)",51,-0.5,50.5,"STAMuons");
01195     histos->fill1DHist(nDTHits,"trNDT","N DT hits on a STA Muon Track",51,-0.5,50.5,"STAMuons");
01196     histos->fill1DHist(nCSCHits,"trNCSC","N CSC hits on a STA Muon Track",51,-0.5,50.5,"STAMuons");
01197     if (nCSCHitsp != 0) histos->fill1DHist(nCSCHitsp,"trNCSCp","N CSC hits on a STA Muon Track (+ endcap)",51,-0.5,50.5,"STAMuons");
01198     if (nCSCHitsm != 0) histos->fill1DHist(nCSCHitsm,"trNCSCm","N CSC hits on a STA Muon Track (- endcap)",51,-0.5,50.5,"STAMuons");
01199     histos->fill1DHist(nRPCHits,"trNRPC","N RPC hits on a STA Muon Track",51,-0.5,50.5,"STAMuons");
01200     if (nRPCHitsp != 0) histos->fill1DHist(nRPCHitsp,"trNRPCp","N RPC hits on a STA Muon Track (+ endcap)",51,-0.5,50.5,"STAMuons");
01201     if (nRPCHitsm != 0) histos->fill1DHist(nRPCHitsm,"trNRPCm","N RPC hits on a STA Muon Track (- endcap)",51,-0.5,50.5,"STAMuons");
01202     histos->fill1DHist(preco,"trP","STA Muon Momentum",100,0,300,"STAMuons");
01203     histos->fill1DHist(ptreco,"trPT","STA Muon pT",100,0,40,"STAMuons");
01204     histos->fill1DHist(chi2,"trChi2","STA Muon Chi2",100,0,200,"STAMuons");
01205     histos->fill1DHist(normchi2,"trNormChi2","STA Muon Normalized Chi2",100,0,10,"STAMuons");
01206     histos->fill1DHist(crudeLength,"trLength","Straight Line Length of STA Muon",120,0.,2400.,"STAMuons");
01207     histos->fill1DHist(deltaPhi,"trDeltaPhi","Delta-Phi Between Inner and Outer STA Muon Pos.",100,-0.5,0.5,"STAMuons");
01208     histos->fill1DHist(innerGlobalPolarAngle,"trInnerPolar","Polar Angle of Inner P Vector (STA muons)",128,0,3.2,"STAMuons");
01209     histos->fill1DHist(outerGlobalPolarAngle,"trOuterPolar","Polar Angle of Outer P Vector (STA muons)",128,0,3.2,"STAMuons");
01210     histos->fill1DHist(innerPnt.phi(),"trInnerPhi","Phi of Inner Position (STA muons)",256,-3.2,3.2,"STAMuons");
01211     histos->fill1DHist(outerPnt.phi(),"trOuterPhi","Phi of Outer Position (STA muons)",256,-3.2,3.2,"STAMuons");
01212 
01213   }
01214 
01215 }
01216 
01217 
01218 //--------------------------------------------------------------
01219 // Compute a serial number for the chamber.
01220 // This is useful when filling histograms and working with arrays.
01221 //--------------------------------------------------------------
01222 int CSCValidation::chamberSerial( CSCDetId id ) {
01223   int st = id.station();
01224   int ri = id.ring();
01225   int ch = id.chamber();
01226   int ec = id.endcap();
01227   int kSerial = ch;
01228   if (st == 1 && ri == 1) kSerial = ch;
01229   if (st == 1 && ri == 2) kSerial = ch + 36;
01230   if (st == 1 && ri == 3) kSerial = ch + 72;
01231   if (st == 1 && ri == 4) kSerial = ch;
01232   if (st == 2 && ri == 1) kSerial = ch + 108;
01233   if (st == 2 && ri == 2) kSerial = ch + 126;
01234   if (st == 3 && ri == 1) kSerial = ch + 162;
01235   if (st == 3 && ri == 2) kSerial = ch + 180;
01236   if (st == 4 && ri == 1) kSerial = ch + 216;
01237   if (st == 4 && ri == 2) kSerial = ch + 234;  // one day...
01238   if (ec == 2) kSerial = kSerial + 300;
01239   return kSerial;
01240 }
01241 
01242 //--------------------------------------------------------------
01243 // Compute a serial number for the ring.
01244 // This is useful when filling histograms and working with arrays.
01245 //--------------------------------------------------------------
01246 int CSCValidation::ringSerial( CSCDetId id ) {
01247   int st = id.station();
01248   int ri = id.ring();
01249   int ec = id.endcap();
01250   int kSerial = 0 ;
01251   if (st == 1 && ri == 1) kSerial = ri;
01252   if (st == 1 && ri == 2) kSerial = ri ;
01253   if (st == 1 && ri == 3) kSerial = ri ;
01254   if (st == 1 && ri == 4) kSerial = 1;
01255   if (st == 2 ) kSerial = ri + 3;
01256   if (st == 3 ) kSerial = ri + 5;
01257   if (st == 4 ) kSerial = ri + 7;
01258   if (ec == 2) kSerial = kSerial * (-1);
01259   return kSerial;
01260 }
01261 
01262 //-------------------------------------------------------------------------------------
01263 // Fits a straight line to a set of 5 points with errors.  Functions assumes 6 points
01264 // and removes hit in layer 3.  It then returns the expected position value in layer 3
01265 // based on the fit.
01266 //-------------------------------------------------------------------------------------
01267 float CSCValidation::fitX(CLHEP::HepMatrix points, CLHEP::HepMatrix errors){
01268 
01269   float S   = 0;
01270   float Sx  = 0;
01271   float Sy  = 0;
01272   float Sxx = 0;
01273   float Sxy = 0;
01274   float sigma2 = 0;
01275 
01276   for (int i=1;i<7;i++){
01277     if (i != 3){
01278       sigma2 = errors(i,1)*errors(i,1);
01279       S = S + (1/sigma2);
01280       Sy = Sy + (points(i,1)/sigma2);
01281       Sx = Sx + ((i)/sigma2);
01282       Sxx = Sxx + (i*i)/sigma2;
01283       Sxy = Sxy + (((i)*points(i,1))/sigma2);
01284     }
01285   }
01286 
01287   float delta = S*Sxx - Sx*Sx;
01288   float intercept = (Sxx*Sy - Sx*Sxy)/delta;
01289   float slope = (S*Sxy - Sx*Sy)/delta;
01290 
01291   //float chi = 0;
01292   //float chi2 = 0;
01293 
01294   // calculate chi2 (not currently used)
01295   //for (int i=1;i<7;i++){
01296   //  chi = (points(i,1) - intercept - slope*i)/(errors(i,1));
01297   //  chi2 = chi2 + chi*chi;
01298   //}
01299 
01300   return (intercept + slope*3);
01301 
01302 }
01303 
01304 
01305 //----------------------------------------------------------------------------
01306 // Calculate basic efficiencies for recHits and Segments
01307 // Author: S. Stoynev
01308 //----------------------------------------------------------------------------
01309 
01310 void CSCValidation::doEfficiencies(edm::Handle<CSCWireDigiCollection> wires, edm::Handle<CSCStripDigiCollection> strips,
01311                                    edm::Handle<CSCRecHit2DCollection> recHits, edm::Handle<CSCSegmentCollection> cscSegments,
01312                                    edm::ESHandle<CSCGeometry> cscGeom){
01313 
01314   bool allWires[2][4][4][36][6];
01315   bool allStrips[2][4][4][36][6];
01316   bool AllRecHits[2][4][4][36][6];
01317   bool AllSegments[2][4][4][36];
01318   
01319   //bool MultiSegments[2][4][4][36];
01320   for(int iE = 0;iE<2;iE++){
01321     for(int iS = 0;iS<4;iS++){
01322       for(int iR = 0; iR<4;iR++){
01323         for(int iC =0;iC<36;iC++){
01324           AllSegments[iE][iS][iR][iC] = false;
01325           //MultiSegments[iE][iS][iR][iC] = false;
01326           for(int iL=0;iL<6;iL++){
01327             allWires[iE][iS][iR][iC][iL] = false;
01328             allStrips[iE][iS][iR][iC][iL] = false;
01329             AllRecHits[iE][iS][iR][iC][iL] = false;
01330           }
01331         }
01332       }
01333     }
01334   }
01335   
01336   if (useDigis){
01337     // Wires
01338     for (CSCWireDigiCollection::DigiRangeIterator dWDiter=wires->begin(); dWDiter!=wires->end(); dWDiter++) {
01339       CSCDetId idrec = (CSCDetId)(*dWDiter).first;
01340       std::vector<CSCWireDigi>::const_iterator wireIter = (*dWDiter).second.first;
01341       std::vector<CSCWireDigi>::const_iterator lWire = (*dWDiter).second.second;
01342       for( ; wireIter != lWire; ++wireIter) {
01343         allWires[idrec.endcap() -1][idrec.station() -1][idrec.ring() -1][idrec.chamber() -1][idrec.layer() -1] = true;
01344         break;
01345       }
01346     }
01347 
01348     //---- STRIPS
01349     for (CSCStripDigiCollection::DigiRangeIterator dSDiter=strips->begin(); dSDiter!=strips->end(); dSDiter++) {
01350       CSCDetId idrec = (CSCDetId)(*dSDiter).first;
01351       std::vector<CSCStripDigi>::const_iterator stripIter = (*dSDiter).second.first;
01352       std::vector<CSCStripDigi>::const_iterator lStrip = (*dSDiter).second.second;
01353       for( ; stripIter != lStrip; ++stripIter) {
01354         std::vector<int> myADCVals = stripIter->getADCCounts();
01355         bool thisStripFired = false;
01356         float thisPedestal = 0.5*(float)(myADCVals[0]+myADCVals[1]);
01357         float threshold = 13.3 ;
01358         float diff = 0.;
01359         for (unsigned int iCount = 0; iCount < myADCVals.size(); iCount++) {
01360           diff = (float)myADCVals[iCount]-thisPedestal;
01361           if (diff > threshold) {
01362             thisStripFired = true;
01363             break;
01364           }
01365         }
01366         if(thisStripFired){
01367           allStrips[idrec.endcap() -1][idrec.station() -1][idrec.ring() -1][idrec.chamber() -1][idrec.layer() -1] = true;
01368           break;
01369         }
01370       }
01371     }
01372   }
01373 
01374   // Rechits
01375   for (CSCRecHit2DCollection::const_iterator recEffIt = recHits->begin(); recEffIt != recHits->end(); recEffIt++) {
01376     //CSCDetId idrec = (CSCDetId)(*recIt).cscDetId();
01377     CSCDetId  idrec = (CSCDetId)(*recEffIt).cscDetId();
01378     AllRecHits[idrec.endcap() -1][idrec.station() -1][idrec.ring() -1][idrec.chamber() -1][idrec.layer() -1] = true;
01379 
01380   }
01381 
01382   std::vector <unsigned int> seg_ME2(2,0) ;
01383   std::vector <unsigned int> seg_ME3(2,0) ;
01384   std::vector < std::pair <CSCDetId, CSCSegment> > theSegments(4);
01385   // Segments
01386   for(CSCSegmentCollection::const_iterator segEffIt=cscSegments->begin(); segEffIt != cscSegments->end(); segEffIt++) {
01387     CSCDetId idseg  = (CSCDetId)(*segEffIt).cscDetId();
01388     //if(AllSegments[idrec.endcap() -1][idrec.station() -1][idrec.ring() -1][idrec.chamber()]){
01389     //MultiSegments[idrec.endcap() -1][idrec.station() -1][idrec.ring() -1][idrec.chamber()] = true;
01390     //}
01391     AllSegments[idseg.endcap() -1][idseg.station() -1][idseg.ring() -1][idseg.chamber() -1] = true;
01392     // "Intrinsic" efficiency measurement relies on "good" segment extrapolation - we need the pre-selection below
01393     // station 2 "good" segment will be used for testing efficiencies in ME1 and ME3
01394     // station 3 "good" segment will be used for testing efficiencies in ME2 and ME4
01395     if(2==idseg.station() || 3==idseg.station()){
01396       unsigned int seg_tmp ; 
01397       if(2==idseg.station()){
01398         ++seg_ME2[idseg.endcap() -1];
01399         seg_tmp = seg_ME2[idseg.endcap() -1];
01400       }
01401       else{
01402         ++seg_ME3[idseg.endcap() -1];
01403         seg_tmp = seg_ME3[idseg.endcap() -1];
01404       }
01405       // is the segment good
01406       if(1== seg_tmp&& 6==(*segEffIt).nRecHits() && (*segEffIt).chi2()/(*segEffIt).degreesOfFreedom()<3.){
01407         std::pair <CSCDetId, CSCSegment> specSeg = make_pair( (CSCDetId)(*segEffIt).cscDetId(),*segEffIt);
01408         theSegments[2*(idseg.endcap()-1)+(idseg.station() -2)] = specSeg;
01409       }
01410     }
01411     /*
01412     if(2==idseg.station()){
01413         ++seg_ME2[idseg.endcap() -1];
01414        if(1==seg_ME2[idseg.endcap() -1] && 6==(*segEffIt).nRecHits() && (*segEffIt).chi2()/(*segEffIt).degreesOfFreedom()<3.){
01415            std::pair <CSCDetId, CSCSegment> specSeg = make_pair( (CSCDetId)(*segEffIt).cscDetId(),*segEffIt);
01416            theSegments[2*(idseg.endcap()-1)+(idseg.station() -2)] = specSeg;
01417        }
01418     }
01419     else if(3==idseg.station()){
01420         ++seg_ME3[idseg.endcap() -1];
01421         if(1==seg_ME3[idseg.endcap() -1] && 6==(*segEffIt).nRecHits() && (*segEffIt).chi2()/(*segEffIt).degreesOfFreedom()<3.){
01422          std::pair <CSCDetId, CSCSegment> specSeg = make_pair( (CSCDetId)(*segEffIt).cscDetId(),*segEffIt);
01423          theSegments[2*(idseg.endcap()-1)+(idseg.station() -2)] = specSeg;
01424        }
01425     }
01426     */
01427     
01428   }
01429   // Simple efficiency calculations
01430   for(int iE = 0;iE<2;iE++){
01431     for(int iS = 0;iS<4;iS++){
01432       for(int iR = 0; iR<4;iR++){
01433         for(int iC =0;iC<36;iC++){
01434           int NumberOfLayers = 0;
01435           for(int iL=0;iL<6;iL++){
01436             if(AllRecHits[iE][iS][iR][iC][iL]){
01437               NumberOfLayers++;
01438             }
01439           }
01440           int bin = 0;
01441           if (iS==0) bin = iR+1+(iE*10);
01442           else bin = (iS+1)*2 + (iR+1) + (iE*10);
01443           if(NumberOfLayers>1){
01444             //if(!(MultiSegments[iE][iS][iR][iC])){
01445             if(AllSegments[iE][iS][iR][iC]){
01446               //---- Efficient segment evenents
01447               hSSTE->AddBinContent(bin);
01448             }
01449             //---- All segment events (normalization)
01450             hSSTE->AddBinContent(20+bin);
01451             //}
01452           }
01453           if(AllSegments[iE][iS][iR][iC]){
01454             if(NumberOfLayers==6){
01455               //---- Efficient rechit events
01456               hRHSTE->AddBinContent(bin);;
01457             }
01458             //---- All rechit events (normalization)
01459             hRHSTE->AddBinContent(20+bin);;
01460           }
01461         }
01462       }
01463     }
01464   }
01465 
01466 // pick a segment only if there are no others in the station
01467   std::vector < std::pair <CSCDetId, CSCSegment> * > theSeg;
01468   if(1==seg_ME2[0]) theSeg.push_back(&theSegments[0]);
01469   if(1==seg_ME3[0]) theSeg.push_back(&theSegments[1]);
01470   if(1==seg_ME2[1]) theSeg.push_back(&theSegments[2]);
01471   if(1==seg_ME3[1]) theSeg.push_back(&theSegments[3]);
01472 
01473   // Needed for plots
01474   // at the end the chamber types will be numbered as 1 to 18 
01475   // (ME-4/1, -ME3/2, -ME3/1, ..., +ME3/1, +ME3/2, ME+4/1 ) 
01476   std::map <std::string, float> chamberTypes;
01477   chamberTypes["ME1/a"] = 0.5;
01478   chamberTypes["ME1/b"] = 1.5;
01479   chamberTypes["ME1/2"] = 2.5;
01480   chamberTypes["ME1/3"] = 3.5;
01481   chamberTypes["ME2/1"] = 4.5;
01482   chamberTypes["ME2/2"] = 5.5;
01483   chamberTypes["ME3/1"] = 6.5;
01484   chamberTypes["ME3/2"] = 7.5;
01485   chamberTypes["ME4/1"] = 8.5;
01486 
01487   if(theSeg.size()){
01488     std::map <int , GlobalPoint> extrapolatedPoint;
01489     std::map <int , GlobalPoint>::iterator it;
01490     const std::vector<CSCChamber*> ChamberContainer = cscGeom->chambers();
01491     // Pick which chamber with which segment to test
01492     for(size_t nCh=0;nCh<ChamberContainer.size();nCh++){
01493       const CSCChamber *cscchamber = ChamberContainer[nCh];
01494       std::pair <CSCDetId, CSCSegment> * thisSegment = 0;
01495       for(size_t iSeg =0;iSeg<theSeg.size();++iSeg ){
01496         if(cscchamber->id().endcap() == theSeg[iSeg]->first.endcap()){ 
01497           if(1==cscchamber->id().station() || 3==cscchamber->id().station() ){
01498             if(2==theSeg[iSeg]->first.station()){
01499               thisSegment = theSeg[iSeg];
01500             }
01501           }
01502           else if (2==cscchamber->id().station() || 4==cscchamber->id().station()){
01503             if(3==theSeg[iSeg]->first.station()){
01504               thisSegment = theSeg[iSeg];
01505             }
01506           }
01507         }
01508       }
01509       // this chamber is to be tested with thisSegment
01510       if(thisSegment){
01511         CSCSegment * seg = &(thisSegment->second);
01512         const CSCChamber *segChamber = cscGeom->chamber(thisSegment->first);
01513         LocalPoint localCenter(0.,0.,0);
01514         GlobalPoint cscchamberCenter =  cscchamber->toGlobal(localCenter);
01515         // try to save some time (extrapolate a segment to a certain position only once)
01516         it = extrapolatedPoint.find(int(cscchamberCenter.z()));
01517         if(it==extrapolatedPoint.end()){
01518           GlobalPoint segPos = segChamber->toGlobal(seg->localPosition());
01519           GlobalVector segDir = segChamber->toGlobal(seg->localDirection());
01520           double paramaterLine = lineParametrization(segPos.z(),cscchamberCenter.z() , segDir.z());
01521           double xExtrapolated = extrapolate1D(segPos.x(),segDir.x(), paramaterLine);
01522           double yExtrapolated = extrapolate1D(segPos.y(),segDir.y(), paramaterLine);
01523           GlobalPoint globP (xExtrapolated, yExtrapolated, cscchamberCenter.z());
01524           extrapolatedPoint[int(cscchamberCenter.z())] = globP;
01525         }
01526         // Where does the extrapolated point lie in the (tested) chamber local frame? Here: 
01527         LocalPoint extrapolatedPointLocal = cscchamber->toLocal(extrapolatedPoint[int(cscchamberCenter.z())]);
01528         const CSCLayer *layer_p = cscchamber->layer(1);//layer 1
01529         const CSCLayerGeometry *layerGeom = layer_p->geometry ();
01530         const std::vector<float> layerBounds = layerGeom->parameters ();
01531         float shiftFromEdge = 15.;//cm
01532         float shiftFromDeadZone = 10.;
01533         // is the extrapolated point within a sensitive region
01534         bool pass = withinSensitiveRegion(extrapolatedPointLocal, layerBounds, 
01535                                           cscchamber->id().station(), cscchamber->id().ring(), 
01536                                           shiftFromEdge, shiftFromDeadZone);
01537         if(pass){// the extrapolation point of the segment lies within sensitive region of that chamber
01538           // how many rechit layers are there in the chamber?
01539           // 0 - maybe the muon died or is deflected at large angle? do not use that case
01540           // 1 - could be noise...
01541           // 2 or more - this is promissing; this is our definition of a reliable signal; use it below
01542           // is other definition better? 
01543           int nRHLayers = 0;
01544           for(int iL =0;iL<6;++iL){
01545             if(AllRecHits[cscchamber->id().endcap()-1]
01546                [cscchamber->id().station()-1]
01547                [cscchamber->id().ring()-1][cscchamber->id().chamber()-1][iL]){
01548               ++nRHLayers;
01549             }
01550           }
01551           //std::cout<<" nRHLayers = "<<nRHLayers<<std::endl;
01552           float verticalScale = chamberTypes[cscchamber->specs()->chamberTypeName()];
01553           if(cscchamberCenter.z()<0){
01554             verticalScale = - verticalScale;
01555           } 
01556           verticalScale +=9.5;
01557           hSensitiveAreaEvt->Fill(float(cscchamber->id().chamber()),verticalScale);
01558           if(nRHLayers>1){// this chamber contains a reliable signal
01559             //chamberTypes[cscchamber->specs()->chamberTypeName()];
01560             // "intrinsic" efficiencies
01561             //std::cout<<" verticalScale = "<<verticalScale<<" chType = "<<cscchamber->specs()->chamberTypeName()<<std::endl;
01562             // this is the denominator forr all efficiencies
01563             hEffDenominator->Fill(float(cscchamber->id().chamber()),verticalScale);
01564             // Segment efficiency
01565             if(AllSegments[cscchamber->id().endcap()-1]
01566                [cscchamber->id().station()-1]
01567                [cscchamber->id().ring()-1][cscchamber->id().chamber()-1]){
01568               hSSTE2->Fill(float(cscchamber->id().chamber()),float(verticalScale));
01569             }
01570           
01571             for(int iL =0;iL<6;++iL){
01572               float weight = 1./6.;
01573               // one shold account for the weight in the efficiency...
01574               // Rechit efficiency
01575               if(AllRecHits[cscchamber->id().endcap()-1]
01576                  [cscchamber->id().station()-1]
01577                  [cscchamber->id().ring()-1][cscchamber->id().chamber()-1][iL]){
01578                 hRHSTE2->Fill(float(cscchamber->id().chamber()),float(verticalScale),weight);
01579               }
01580               if (useDigis){
01581                 // Wire efficiency
01582                 if(allWires[cscchamber->id().endcap()-1]
01583                   [cscchamber->id().station()-1]
01584                   [cscchamber->id().ring()-1][cscchamber->id().chamber()-1][iL]){
01585                   // one shold account for the weight in the efficiency...
01586                   hWireSTE2->Fill(float(cscchamber->id().chamber()),float(verticalScale),weight);
01587                 }
01588                 // Strip efficiency
01589                 if(allStrips[cscchamber->id().endcap()-1]
01590                   [cscchamber->id().station()-1]
01591                   [cscchamber->id().ring()-1][cscchamber->id().chamber()-1][iL]){
01592                   // one shold account for the weight in the efficiency...
01593                   hStripSTE2->Fill(float(cscchamber->id().chamber()),float(verticalScale),weight);
01594                 }
01595               }
01596             }
01597           }
01598         }
01599       }
01600     }
01601   }
01602   //
01603   
01604   
01605 }
01606 
01607 void CSCValidation::getEfficiency(float bin, float Norm, std::vector<float> &eff){
01608   //---- Efficiency with binomial error
01609   float Efficiency = 0.;
01610   float EffError = 0.;
01611   if(fabs(Norm)>0.000000001){
01612     Efficiency = bin/Norm;
01613     if(bin<Norm){
01614       EffError = sqrt( (1.-Efficiency)*Efficiency/Norm );
01615     }
01616   }
01617   eff[0] = Efficiency;
01618   eff[1] = EffError;
01619 }
01620 
01621 void CSCValidation::histoEfficiency(TH1F *readHisto, TH1F *writeHisto){
01622   std::vector<float> eff(2);
01623   int Nbins =  readHisto->GetSize()-2;//without underflows and overflows
01624   std::vector<float> bins(Nbins);
01625   std::vector<float> Efficiency(Nbins);
01626   std::vector<float> EffError(Nbins);
01627   float Num = 1;
01628   float Den = 1;
01629   for (int i=0;i<20;i++){
01630     Num = readHisto->GetBinContent(i+1);
01631     Den = readHisto->GetBinContent(i+21);
01632     getEfficiency(Num, Den, eff);
01633     Efficiency[i] = eff[0];
01634     EffError[i] = eff[1];
01635     writeHisto->SetBinContent(i+1, Efficiency[i]);
01636     writeHisto->SetBinError(i+1, EffError[i]);
01637   }
01638 }
01639 
01640 bool CSCValidation::withinSensitiveRegion(LocalPoint localPos, const std::vector<float> layerBounds, int station, int ring, float shiftFromEdge, float shiftFromDeadZone){
01641 //---- check if it is in a good local region (sensitive area - geometrical and HV boundaries excluded) 
01642   bool pass = false;
01643 
01644   float y_center = 0.;
01645   double yUp = layerBounds[3] + y_center;
01646   double yDown = - layerBounds[3] + y_center;
01647   double xBound1Shifted = layerBounds[0] - shiftFromEdge;//
01648   double xBound2Shifted = layerBounds[1] - shiftFromEdge;//
01649   double lineSlope = (yUp - yDown)/(xBound2Shifted-xBound1Shifted);
01650   double lineConst = yUp - lineSlope*xBound2Shifted;
01651   double yBorder =  lineSlope*abs(localPos.x()) + lineConst;
01652       
01653   //bool withinChamberOnly = false;// false = "good region"; true - boundaries only
01654   std::vector <float> deadZoneCenter(6);
01655   float cutZone = shiftFromDeadZone;//cm
01656   //---- hardcoded... not good
01657   if(station>1 && station<5){
01658     if(2==ring){
01659       deadZoneCenter[0]= -162.48 ;
01660       deadZoneCenter[1] = -81.8744;
01661       deadZoneCenter[2] = -21.18165;
01662       deadZoneCenter[3] = 39.51105;
01663       deadZoneCenter[4] = 100.2939;
01664       deadZoneCenter[5] = 160.58;
01665       
01666       if(localPos.y() >yBorder &&
01667          ((localPos.y()> deadZoneCenter[0] + cutZone && localPos.y()< deadZoneCenter[1] - cutZone) ||
01668           (localPos.y()> deadZoneCenter[1] + cutZone && localPos.y()< deadZoneCenter[2] - cutZone) ||
01669           (localPos.y()> deadZoneCenter[2] + cutZone && localPos.y()< deadZoneCenter[3] - cutZone) ||
01670           (localPos.y()> deadZoneCenter[3] + cutZone && localPos.y()< deadZoneCenter[4] - cutZone) ||
01671           (localPos.y()> deadZoneCenter[4] + cutZone && localPos.y()< deadZoneCenter[5] - cutZone))){
01672         pass = true;
01673       }
01674     }
01675     else if(1==ring){
01676       if(2==station){
01677         deadZoneCenter[0]= -95.80 ;
01678         deadZoneCenter[1] = -27.47;
01679         deadZoneCenter[2] = 33.67;
01680         deadZoneCenter[3] = 90.85;
01681         }
01682       else if(3==station){
01683         deadZoneCenter[0]= -89.305 ;
01684         deadZoneCenter[1] = -39.705;
01685         deadZoneCenter[2] = 20.195;
01686         deadZoneCenter[3] = 77.395;
01687       }
01688       else if(4==station){
01689         deadZoneCenter[0]= -75.645;
01690         deadZoneCenter[1] = -26.055;
01691         deadZoneCenter[2] = 23.855;
01692         deadZoneCenter[3] = 70.575;
01693       }
01694       if(localPos.y() >yBorder &&
01695          ((localPos.y()> deadZoneCenter[0] + cutZone && localPos.y()< deadZoneCenter[1] - cutZone) ||
01696           (localPos.y()> deadZoneCenter[1] + cutZone && localPos.y()< deadZoneCenter[2] - cutZone) ||
01697           (localPos.y()> deadZoneCenter[2] + cutZone && localPos.y()< deadZoneCenter[3] - cutZone))){
01698         pass = true;
01699       }
01700     }
01701   }
01702   else if(1==station){
01703     if(3==ring){
01704       deadZoneCenter[0]= -83.155 ;
01705       deadZoneCenter[1] = -22.7401;
01706       deadZoneCenter[2] = 27.86665;
01707       deadZoneCenter[3] = 81.005;
01708       if(localPos.y() > yBorder &&
01709          ((localPos.y()> deadZoneCenter[0] + cutZone && localPos.y()< deadZoneCenter[1] - cutZone) ||
01710           (localPos.y()> deadZoneCenter[1] + cutZone && localPos.y()< deadZoneCenter[2] - cutZone) ||
01711           (localPos.y()> deadZoneCenter[2] + cutZone && localPos.y()< deadZoneCenter[3] - cutZone))){
01712         pass = true;
01713       }
01714     }
01715     else if(2==ring){
01716       deadZoneCenter[0]= -86.285 ;
01717       deadZoneCenter[1] = -32.88305;
01718       deadZoneCenter[2] = 32.867423;
01719       deadZoneCenter[3] = 88.205;
01720       if(localPos.y() > (yBorder) &&
01721          ((localPos.y()> deadZoneCenter[0] + cutZone && localPos.y()< deadZoneCenter[1] - cutZone) ||
01722           (localPos.y()> deadZoneCenter[1] + cutZone && localPos.y()< deadZoneCenter[2] - cutZone) ||
01723           (localPos.y()> deadZoneCenter[2] + cutZone && localPos.y()< deadZoneCenter[3] - cutZone))){
01724         pass = true;
01725       }
01726     }
01727     else{
01728       deadZoneCenter[0]= -81.0;
01729       deadZoneCenter[1] = 81.0;
01730       if(localPos.y() > (yBorder) &&
01731          (localPos.y()> deadZoneCenter[0] + cutZone && localPos.y()< deadZoneCenter[1] - cutZone )){
01732         pass = true;
01733       }
01734     }
01735   }
01736   return pass;
01737 }
01738 
01739 
01740 
01741 //---------------------------------------------------------------------------------------
01742 // Given a set of digis, the CSCDetId, and the central strip of your choosing, returns
01743 // the avg. Signal-Pedestal for 6 time bin x 5 strip .
01744 //
01745 // Author: P. Jindal
01746 //---------------------------------------------------------------------------------------
01747 
01748 float CSCValidation::getSignal(const CSCStripDigiCollection& stripdigis, CSCDetId idCS, int centerStrip){
01749 
01750   float SigADC[5];
01751   float TotalADC = 0;
01752   SigADC[0] = 0;
01753   SigADC[1] = 0;
01754   SigADC[2] = 0;
01755   SigADC[3] = 0;
01756   SigADC[4] = 0;
01757 
01758  
01759   // Loop over strip digis 
01760   CSCStripDigiCollection::DigiRangeIterator sIt;
01761   
01762   for (sIt = stripdigis.begin(); sIt != stripdigis.end(); sIt++){
01763     CSCDetId id = (CSCDetId)(*sIt).first;
01764     if (id == idCS){
01765 
01766       // First, find the Signal-Pedestal for center strip
01767       std::vector<CSCStripDigi>::const_iterator digiItr = (*sIt).second.first;
01768       std::vector<CSCStripDigi>::const_iterator last = (*sIt).second.second;
01769       for ( ; digiItr != last; ++digiItr ) {
01770         int thisStrip = digiItr->getStrip();
01771         if (thisStrip == (centerStrip)){
01772           std::vector<int> myADCVals = digiItr->getADCCounts();
01773           float thisPedestal = 0.5*(float)(myADCVals[0]+myADCVals[1]);
01774           float thisSignal = (myADCVals[2]+myADCVals[3]+myADCVals[4]+myADCVals[5]+myADCVals[6]+myADCVals[7]);
01775           SigADC[0] = thisSignal - 6*thisPedestal;
01776         }
01777      // Now,find the Signal-Pedestal for neighbouring 4 strips
01778         if (thisStrip == (centerStrip+1)){
01779           std::vector<int> myADCVals = digiItr->getADCCounts();
01780           float thisPedestal = 0.5*(float)(myADCVals[0]+myADCVals[1]);
01781           float thisSignal = (myADCVals[2]+myADCVals[3]+myADCVals[4]+myADCVals[5]+myADCVals[6]+myADCVals[7]);
01782           SigADC[1] = thisSignal - 6*thisPedestal;
01783         }
01784         if (thisStrip == (centerStrip+2)){
01785           std::vector<int> myADCVals = digiItr->getADCCounts();
01786           float thisPedestal = 0.5*(float)(myADCVals[0]+myADCVals[1]);
01787           float thisSignal = (myADCVals[2]+myADCVals[3]+myADCVals[4]+myADCVals[5]+myADCVals[6]+myADCVals[7]);
01788           SigADC[2] = thisSignal - 6*thisPedestal;
01789         }
01790         if (thisStrip == (centerStrip-1)){
01791           std::vector<int> myADCVals = digiItr->getADCCounts();
01792           float thisPedestal = 0.5*(float)(myADCVals[0]+myADCVals[1]);
01793           float thisSignal = (myADCVals[2]+myADCVals[3]+myADCVals[4]+myADCVals[5]+myADCVals[6]+myADCVals[7]);
01794           SigADC[3] = thisSignal - 6*thisPedestal;
01795         }
01796         if (thisStrip == (centerStrip-2)){
01797           std::vector<int> myADCVals = digiItr->getADCCounts();
01798           float thisPedestal = 0.5*(float)(myADCVals[0]+myADCVals[1]);
01799           float thisSignal = (myADCVals[2]+myADCVals[3]+myADCVals[4]+myADCVals[5]+myADCVals[6]+myADCVals[7]);
01800           SigADC[4] = thisSignal - 6*thisPedestal;
01801         }
01802       }
01803       TotalADC = 0.2*(SigADC[0]+SigADC[1]+SigADC[2]+SigADC[3]+SigADC[4]);
01804     }
01805   }
01806   return TotalADC;
01807 }
01808 
01809 //---------------------------------------------------------------------------------------
01810 // Look at non-associated recHits
01811 // Author: P. Jindal
01812 //---------------------------------------------------------------------------------------
01813 
01814 void CSCValidation::doNoiseHits(edm::Handle<CSCRecHit2DCollection> recHits, edm::Handle<CSCSegmentCollection> cscSegments,
01815                                 edm::ESHandle<CSCGeometry> cscGeom,  edm::Handle<CSCStripDigiCollection> strips){
01816 
01817   CSCRecHit2DCollection::const_iterator recIt;
01818   for (recIt = recHits->begin(); recIt != recHits->end(); recIt++) {
01819 
01820     CSCDetId idrec = (CSCDetId)(*recIt).cscDetId();
01821 
01822     //Store the Rechits into a Map
01823     AllRechits.insert(std::pair<CSCDetId , CSCRecHit2D>(idrec,*recIt));
01824 
01825     // Find the strip containing this hit
01826     CSCRecHit2D::ChannelContainer hitstrips = (*recIt).channels();
01827     int nStrips     =  hitstrips.size();
01828     //std::cout << " no of strips in Rec Hit " << nStrips << std::endl;
01829     int centerid    =  nStrips/2 + 1;
01830     int centerStrip =  hitstrips[centerid - 1];
01831 
01832     float  rHsignal = getthisSignal(*strips, idrec, centerStrip);
01833     histos->fill1DHist(rHsignal,"hrHSignal", "Signal in the 4th time bin for centre strip",1100,-99,1000,"recHits");
01834 
01835   }
01836 
01837   for(CSCSegmentCollection::const_iterator it=cscSegments->begin(); it != cscSegments->end(); it++) {
01838 
01839     std::vector<CSCRecHit2D> theseRecHits = (*it).specificRecHits();
01840     for ( std::vector<CSCRecHit2D>::const_iterator iRH = theseRecHits.begin(); iRH != theseRecHits.end(); iRH++) {
01841       CSCDetId idRH = (CSCDetId)(*iRH).cscDetId();
01842       LocalPoint lpRH = (*iRH).localPosition();
01843       float xrec = lpRH.x();
01844       float yrec = lpRH.y();
01845       float zrec = lpRH.z();
01846       bool RHalreadyinMap = false;
01847       //Store the rechits associated with segments into a Map
01848       multimap<CSCDetId , CSCRecHit2D>::iterator segRHit;
01849       segRHit = SegRechits.find(idRH);
01850       if (segRHit != SegRechits.end()){
01851         for( ; segRHit != SegRechits.upper_bound(idRH); ++segRHit){
01852           //for( segRHit = SegRechits.begin(); segRHit != SegRechits.end() ;++segRHit){
01853           LocalPoint lposRH = (segRHit->second).localPosition();
01854           float xpos = lposRH.x();
01855           float ypos = lposRH.y();
01856           float zpos = lposRH.z();
01857           if ( xrec == xpos && yrec == ypos && zrec == zpos){
01858           RHalreadyinMap = true;
01859           //std::cout << " Already exists " <<std ::endl;
01860           break;}
01861         }
01862       }
01863       if(!RHalreadyinMap){ SegRechits.insert(std::pair<CSCDetId , CSCRecHit2D>(idRH,*iRH));}
01864     }
01865   }
01866 
01867   findNonAssociatedRecHits(cscGeom,strips);
01868 
01869 }
01870 
01871 //---------------------------------------------------------------------------------------
01872 // Given  the list of all rechits and the rechits on a segment finds the rechits 
01873 // not associated to a segment and stores in a list
01874 //
01875 //---------------------------------------------------------------------------------------
01876 
01877 void CSCValidation::findNonAssociatedRecHits(edm::ESHandle<CSCGeometry> cscGeom,  edm::Handle<CSCStripDigiCollection> strips){
01878  
01879   for(std::multimap<CSCDetId , CSCRecHit2D>::iterator allRHiter =  AllRechits.begin();allRHiter != AllRechits.end(); ++allRHiter){
01880         CSCDetId idRH = allRHiter->first;
01881     LocalPoint lpRH = (allRHiter->second).localPosition();
01882     float xrec = lpRH.x();
01883     float yrec = lpRH.y();
01884     float zrec = lpRH.z();
01885     
01886     bool foundmatch = false;
01887     multimap<CSCDetId , CSCRecHit2D>::iterator segRHit;
01888     segRHit = SegRechits.find(idRH);
01889     if (segRHit != SegRechits.end()){
01890                 for( ; segRHit != SegRechits.upper_bound(idRH); ++segRHit){
01891                         
01892                         LocalPoint lposRH = (segRHit->second).localPosition();
01893                         float xpos = lposRH.x();
01894                         float ypos = lposRH.y();
01895                         float zpos = lposRH.z();
01896 
01897                         if ( xrec == xpos && yrec == ypos && zrec == zpos){
01898                                 foundmatch = true;}
01899           
01900                         float d      = 0.;
01901                         float dclose =1000.;
01902 
01903                         if ( !foundmatch) {
01904                                 
01905                                 d = sqrt(pow(xrec-xpos,2)+pow(yrec-ypos,2)+pow(zrec-zpos,2));
01906                                 if (d < dclose) {
01907                                         dclose = d;
01908                                         if( distRHmap.find((allRHiter->second)) ==  distRHmap.end() ) { // entry for rechit does not yet exist, create one
01909                                                 distRHmap.insert(make_pair(allRHiter->second,dclose) );
01910                                         }
01911                                         else {
01912                                                 // we already have an entry for the detid.
01913                                                 distRHmap.erase(allRHiter->second);
01914                                                 distRHmap.insert(make_pair(allRHiter->second,dclose)); // fill rechits for the segment with the given detid
01915                                         }
01916                                 }
01917                         }           
01918                 }
01919     }
01920     if(!foundmatch){NonAssociatedRechits.insert(std::pair<CSCDetId , CSCRecHit2D>(idRH,allRHiter->second));}
01921   }
01922 
01923   for(std::map<CSCRecHit2D,float,ltrh>::iterator iter =  distRHmap.begin();iter != distRHmap.end(); ++iter){
01924     histos->fill1DHist(iter->second,"hdistRH","Distance of Non Associated RecHit from closest Segment RecHit",500,0.,100.,"NonAssociatedRechits");
01925   }
01926 
01927   for(std::multimap<CSCDetId , CSCRecHit2D>::iterator iter =  NonAssociatedRechits.begin();iter != NonAssociatedRechits.end(); ++iter){
01928     CSCDetId idrec = iter->first;
01929     int kEndcap  = idrec.endcap();
01930     int cEndcap  = idrec.endcap();
01931     if (kEndcap == 2)cEndcap = -1;
01932     int kRing    = idrec.ring();
01933     int kStation = idrec.station();
01934     int kChamber = idrec.chamber();
01935     int kLayer   = idrec.layer();
01936 
01937     // Store rechit as a Local Point:
01938     LocalPoint rhitlocal = (iter->second).localPosition();  
01939     float xreco = rhitlocal.x();
01940     float yreco = rhitlocal.y();
01941 
01942     // Find the strip containing this hit
01943     CSCRecHit2D::ChannelContainer hitstrips = (iter->second).channels();
01944     int nStrips     =  hitstrips.size();
01945     int centerid    =  nStrips/2 + 1;
01946     int centerStrip =  hitstrips[centerid - 1];
01947 
01948 
01949     // Find the charge associated with this hit
01950 
01951     CSCRecHit2D::ADCContainer adcs = (iter->second).adcs();
01952     int adcsize = adcs.size();
01953     float rHSumQ = 0;
01954     float sumsides = 0;
01955     for (int i = 0; i < adcsize; i++){
01956       if (i != 3 && i != 7 && i != 11){
01957         rHSumQ = rHSumQ + adcs[i]; 
01958       }
01959       if (adcsize == 12 && (i < 3 || i > 7) && i < 12){
01960         sumsides = sumsides + adcs[i];
01961       }
01962     }
01963     float rHratioQ = sumsides/rHSumQ;
01964     if (adcsize != 12) rHratioQ = -99;
01965 
01966     // Get the signal timing of this hit
01967     float rHtime = (iter->second).tpeak()/50;
01968 
01969     // Get the width of this hit
01970     int rHwidth = getWidth(*strips, idrec, centerStrip);
01971 
01972 
01973     // Get pointer to the layer:
01974     const CSCLayer* csclayer = cscGeom->layer( idrec );
01975 
01976     // Transform hit position from local chamber geometry to global CMS geom
01977     GlobalPoint rhitglobal= csclayer->toGlobal(rhitlocal);
01978     float grecx   =  rhitglobal.x();
01979     float grecy   =  rhitglobal.y();
01980 
01981 
01982 
01983    // Simple occupancy variables
01984     int kCodeBroad  = cEndcap * ( 4*(kStation-1) + kRing) ;
01985     int kCodeNarrow = cEndcap * ( 100*(kRing-1) + kChamber) ;
01986 
01987     //Fill the non-associated rechits parameters in histogram
01988     histos->fill1DHist(kCodeBroad,"hNARHCodeBroad","broad scope code for recHits",33,-16.5,16.5,"NonAssociatedRechits");
01989     if (kStation == 1) histos->fill1DHist(kCodeNarrow,"hNARHCodeNarrow1","narrow scope recHit code station 1",801,-400.5,400.5,"NonAssociatedRechits");
01990     if (kStation == 2) histos->fill1DHist(kCodeNarrow,"hNARHCodeNarrow2","narrow scope recHit code station 2",801,-400.5,400.5,"NonAssociatedRechits");
01991     if (kStation == 3) histos->fill1DHist(kCodeNarrow,"hNARHCodeNarrow3","narrow scope recHit code station 3",801,-400.5,400.5,"NonAssociatedRechits");
01992     if (kStation == 4) histos->fill1DHist(kCodeNarrow,"hNARHCodeNarrow4","narrow scope recHit code station 4",801,-400.5,400.5,"NonAssociatedRechits");
01993     histos->fill1DHistByType(kLayer,"hNARHLayer","RecHits per Layer",idrec,8,-0.5,7.5,"NonAssociatedRechits");
01994     histos->fill1DHistByType(xreco,"hNARHX","Local X of recHit",idrec,160,-80.,80.,"NonAssociatedRechits");
01995     histos->fill1DHistByType(yreco,"hNARHY","Local Y of recHit",idrec,60,-180.,180.,"NonAssociatedRechits");
01996     if (kStation == 1 && (kRing == 1 || kRing == 4)) histos->fill1DHistByType(rHSumQ,"hNARHSumQ","Sum 3x3 recHit Charge",idrec,250,0,4000,"NonAssociatedRechits");
01997     else histos->fill1DHistByType(rHSumQ,"hNARHSumQ","Sum 3x3 recHit Charge",idrec,250,0,2000,"NonAssociatedRechits");
01998     histos->fill1DHistByType(rHratioQ,"hNARHRatioQ","Ratio (Ql+Qr)/Qt)",idrec,120,-0.1,1.1,"NonAssociatedRechits");
01999     histos->fill1DHistByType(rHtime,"hNARHTiming","recHit Timing",idrec,200,-10,10,"NonAssociatedRechits");
02000     histos->fill2DHistByStation(grecx,grecy,"hNARHGlobal","recHit Global Position",idrec,400,-800.,800.,400,-800.,800.,"NonAssociatedRechits");
02001     histos->fill1DHistByType(rHwidth,"hNARHwidth","width for Non associated recHit",idrec,21,-0.5,20.5,"NonAssociatedRechits");
02002     
02003   }
02004 
02005    for(std::multimap<CSCDetId , CSCRecHit2D>::iterator iter =  SegRechits.begin();iter != SegRechits.end(); ++iter){
02006            CSCDetId idrec = iter->first;
02007            int kEndcap  = idrec.endcap();
02008            int cEndcap  = idrec.endcap();
02009            if (kEndcap == 2)cEndcap = -1;
02010            int kRing    = idrec.ring();
02011            int kStation = idrec.station();
02012            int kChamber = idrec.chamber();
02013            int kLayer   = idrec.layer();
02014 
02015            // Store rechit as a Local Point:
02016            LocalPoint rhitlocal = (iter->second).localPosition();  
02017            float xreco = rhitlocal.x();
02018            float yreco = rhitlocal.y();
02019 
02020            // Find the strip containing this hit
02021            CSCRecHit2D::ChannelContainer hitstrips = (iter->second).channels();
02022            int nStrips     =  hitstrips.size();
02023            int centerid    =  nStrips/2 + 1;
02024            int centerStrip =  hitstrips[centerid - 1];
02025 
02026 
02027            // Find the charge associated with this hit
02028            
02029            CSCRecHit2D::ADCContainer adcs = (iter->second).adcs();
02030            int adcsize = adcs.size();
02031            float rHSumQ = 0;
02032            float sumsides = 0;
02033            for (int i = 0; i < adcsize; i++){
02034                    if (i != 3 && i != 7 && i != 11){
02035                            rHSumQ = rHSumQ + adcs[i]; 
02036                    }
02037                    if (adcsize == 12 && (i < 3 || i > 7) && i < 12){
02038                            sumsides = sumsides + adcs[i];
02039                    }
02040            }
02041            float rHratioQ = sumsides/rHSumQ;
02042            if (adcsize != 12) rHratioQ = -99;
02043            
02044            // Get the signal timing of this hit
02045            float rHtime = (iter->second).tpeak()/50;
02046 
02047            // Get the width of this hit
02048            int rHwidth = getWidth(*strips, idrec, centerStrip);
02049 
02050 
02051            // Get pointer to the layer:
02052            const CSCLayer* csclayer = cscGeom->layer( idrec );
02053            
02054            // Transform hit position from local chamber geometry to global CMS geom
02055            GlobalPoint rhitglobal= csclayer->toGlobal(rhitlocal);
02056            float grecx   =  rhitglobal.x();
02057            float grecy   =  rhitglobal.y();
02058 
02059            // Simple occupancy variables
02060            int kCodeBroad  = cEndcap * ( 4*(kStation-1) + kRing) ;
02061            int kCodeNarrow = cEndcap * ( 100*(kRing-1) + kChamber) ;
02062 
02063            //Fill the non-associated rechits global position in histogram
02064            histos->fill1DHist(kCodeBroad,"hSegRHCodeBroad","broad scope code for recHits",33,-16.5,16.5,"AssociatedRechits");
02065            if (kStation == 1) histos->fill1DHist(kCodeNarrow,"hSegRHCodeNarrow1","narrow scope recHit code station 1",801,-400.5,400.5,"AssociatedRechits");
02066            if (kStation == 2) histos->fill1DHist(kCodeNarrow,"hSegRHCodeNarrow2","narrow scope recHit code station 2",801,-400.5,400.5,"AssociatedRechits");
02067            if (kStation == 3) histos->fill1DHist(kCodeNarrow,"hSegRHCodeNarrow3","narrow scope recHit code station 3",801,-400.5,400.5,"AssociatedRechits");
02068            if (kStation == 4) histos->fill1DHist(kCodeNarrow,"hSegRHCodeNarrow4","narrow scope recHit code station 4",801,-400.5,400.5,"AssociatedRechits");
02069            histos->fill1DHistByType(kLayer,"hSegRHLayer","RecHits per Layer",idrec,8,-0.5,7.5,"AssociatedRechits");
02070            histos->fill1DHistByType(xreco,"hSegRHX","Local X of recHit",idrec,160,-80.,80.,"AssociatedRechits");
02071            histos->fill1DHistByType(yreco,"hSegRHY","Local Y of recHit",idrec,60,-180.,180.,"AssociatedRechits");
02072            if (kStation == 1 && (kRing == 1 || kRing == 4)) histos->fill1DHistByType(rHSumQ,"hSegRHSumQ","Sum 3x3 recHit Charge",idrec,250,0,4000,"AssociatedRechits");
02073            else histos->fill1DHistByType(rHSumQ,"hSegRHSumQ","Sum 3x3 recHit Charge",idrec,250,0,2000,"AssociatedRechits");
02074            histos->fill1DHistByType(rHratioQ,"hSegRHRatioQ","Ratio (Ql+Qr)/Qt)",idrec,120,-0.1,1.1,"AssociatedRechits");
02075            histos->fill1DHistByType(rHtime,"hSegRHTiming","recHit Timing",idrec,200,-10,10,"AssociatedRechits");
02076            histos->fill2DHistByStation(grecx,grecy,"hSegRHGlobal","recHit Global Position",idrec,400,-800.,800.,400,-800.,800.,"AssociatedRechits");
02077            histos->fill1DHistByType(rHwidth,"hSegRHwidth","width for Non associated recHit",idrec,21,-0.5,20.5,"AssociatedRechits");
02078            
02079    }
02080 
02081    distRHmap.clear();
02082    AllRechits.clear();
02083    SegRechits.clear();
02084    NonAssociatedRechits.clear();
02085 }
02086 
02087 
02088 
02089 float CSCValidation::getthisSignal(const CSCStripDigiCollection& stripdigis, CSCDetId idRH, int centerStrip){
02090         // Loop over strip digis responsible for this recHit
02091         CSCStripDigiCollection::DigiRangeIterator sIt;
02092         float thisADC = 0.;
02093         bool foundRHid = false;
02094         // std::cout<<"iD   S/R/C/L = "<<idRH<<"    "<<idRH.station()<<"/"<<idRH.ring()<<"/"<<idRH.chamber()<<"/"<<idRH.layer()<<std::endl;
02095         for (sIt = stripdigis.begin(); sIt != stripdigis.end(); sIt++){
02096                 CSCDetId id = (CSCDetId)(*sIt).first;
02097                 //std::cout<<"STRIPS: id    S/R/C/L = "<<id<<"     "<<id.station()<<"/"<<id.ring()<<"/"<<id.chamber()<<"/"<<id.layer()<<std::endl;
02098                 if (id == idRH){
02099                         foundRHid = true;
02100                         vector<CSCStripDigi>::const_iterator digiItr = (*sIt).second.first;
02101                         vector<CSCStripDigi>::const_iterator last = (*sIt).second.second;
02102                         //if(digiItr == last ) {std::cout << " Attention1 :: Size of digi collection is zero " << std::endl;}
02103                         int St = idRH.station();
02104                         int Rg    = idRH.ring();
02105                         if (St == 1 && Rg == 4){
02106                                 while(centerStrip> 16) centerStrip -= 16;
02107                         }
02108                         for ( ; digiItr != last; ++digiItr ) {
02109                                 int thisStrip = digiItr->getStrip();
02110                                 //std::cout<<" thisStrip = "<<thisStrip<<" centerStrip = "<<centerStrip<<std::endl;
02111                                 std::vector<int> myADCVals = digiItr->getADCCounts();
02112                                 float thisPedestal = 0.5*(float)(myADCVals[0]+myADCVals[1]);
02113                                 float Signal = (float) myADCVals[3];
02114                                 if (thisStrip == (centerStrip)){
02115                                         thisADC = Signal-thisPedestal;
02116                                         //if(thisADC >= 0. && thisADC <2.) {std::cout << " Attention2 :: The Signal is equal to the pedestal " << std::endl;
02117                                         //}
02118                                         //if(thisADC < 0.) {std::cout << " Attention3 :: The Signal is less than the pedestal " << std::endl;
02119                                         //}
02120                                 }
02121                                 if (thisStrip == (centerStrip+1)){
02122                                         std::vector<int> myADCVals = digiItr->getADCCounts();
02123                                 }
02124                                 if (thisStrip == (centerStrip-1)){
02125                                         std::vector<int> myADCVals = digiItr->getADCCounts();
02126                                 }
02127                         }
02128                 }
02129         }
02130         //if(!foundRHid){std::cout << " Attention4 :: Did not find a matching RH id in the Strip Digi collection " << std::endl;}
02131         return thisADC;
02132 }
02133 
02134 //---------------------------------------------------------------------------------------
02135 //
02136 // Function is meant to take the DetId and center strip number of a recHit and return
02137 // the width in terms of strips
02138 //---------------------------------------------------------------------------------------
02139 
02140 int CSCValidation::getWidth(const CSCStripDigiCollection& stripdigis, CSCDetId idRH, int centerStrip){
02141 
02142   int width = 1;
02143   int widthpos = 0;
02144   int widthneg = 0;
02145 
02146   // Loop over strip digis responsible for this recHit and sum charge
02147   CSCStripDigiCollection::DigiRangeIterator sIt;
02148 
02149   for (sIt = stripdigis.begin(); sIt != stripdigis.end(); sIt++){
02150           CSCDetId id = (CSCDetId)(*sIt).first;
02151           if (id == idRH){
02152                   std::vector<CSCStripDigi>::const_iterator digiItr = (*sIt).second.first;
02153                   std::vector<CSCStripDigi>::const_iterator first = (*sIt).second.first;
02154                   std::vector<CSCStripDigi>::const_iterator last = (*sIt).second.second;
02155                   std::vector<CSCStripDigi>::const_iterator it = (*sIt).second.first;
02156                   std::vector<CSCStripDigi>::const_iterator itr = (*sIt).second.first;
02157                   //std::cout << " IDRH " << id <<std::endl;
02158                   int St = idRH.station();
02159                   int Rg    = idRH.ring();
02160                   if (St == 1 && Rg == 4){
02161                           while(centerStrip> 16) centerStrip -= 16;
02162                   }
02163                   for ( ; digiItr != last; ++digiItr ) {
02164                           int thisStrip = digiItr->getStrip();
02165                           if (thisStrip == (centerStrip)){
02166                                   it = digiItr;
02167                                   for( ; it != last; ++it ) {
02168                                           int strip = it->getStrip();
02169                                           std::vector<int> myADCVals = it->getADCCounts();
02170                                           float thisPedestal = 0.5*(float)(myADCVals[0]+myADCVals[1]);
02171                                           if(((float)myADCVals[3]-thisPedestal) < 6 || widthpos == 10 || it==last){break;}
02172                                            if(strip != centerStrip){ widthpos += 1;
02173                                            }
02174                                   }
02175                                   itr = digiItr;
02176                                   for( ; itr != first; --itr) {
02177                                           int strip = itr->getStrip();
02178                                           std::vector<int> myADCVals = itr->getADCCounts();
02179                                           float thisPedestal = 0.5*(float)(myADCVals[0]+myADCVals[1]);
02180                                           if(((float)myADCVals[3]-thisPedestal) < 6 || widthneg == 10 || itr==first){break;}     
02181                                           if(strip != centerStrip) {widthneg += 1 ; 
02182                                           }
02183                                   }
02184                           }
02185                   }
02186           }
02187   }
02188   //std::cout << "Widthneg - " <<  widthneg << "Widthpos + " <<  widthpos << std::endl;
02189   width =  width + widthneg +  widthpos ;
02190   //std::cout << "Width " <<  width << std::endl;
02191   return width;
02192 }
02193 
02194 
02195 //---------------------------------------------------------------------------
02196 // Module for looking at gas gains
02197 // Author N. Terentiev
02198 //---------------------------------------------------------------------------
02199 
02200 void CSCValidation::doGasGain(const CSCWireDigiCollection& wirecltn, 
02201                               const CSCStripDigiCollection&   strpcltn,
02202                               const CSCRecHit2DCollection& rechitcltn) {
02203      float y;
02204      int channel=0,mult,wire,layer,idlayer,idchamber,ring;
02205      int wire_strip_rechit_present;
02206      std::string name,title,endcapstr;
02207      ostringstream ss;
02208      CSCIndexer indexer;
02209      std::map<int,int>::iterator intIt;
02210 
02211      m_single_wire_layer.clear();
02212 
02213   if(firstEvent) {
02214 
02215   // HV segments, their # and location in terms of wire groups
02216 
02217   m_wire_hvsegm.clear();
02218   std::map<int,std::vector<int> >::iterator intvecIt;
02219   //                    ME1a ME1b ME1/2 ME1/3 ME2/1 ME2/2 ME3/1 ME3/2 ME4/1 ME4/2 
02220   int csctype[10]=     {1,   2,   3,    4,    5,    6,    7,    8,    9,    10};
02221   int hvsegm_layer[10]={1,   1,   3,    3,    3,    5,    3,    5,    3,    5};
02222   int id;
02223   nmbhvsegm.clear();
02224   for(int i=0;i<10;i++) nmbhvsegm.push_back(hvsegm_layer[i]);
02225   // For ME1/1a
02226   std::vector<int> zer_1_1a(49,0);
02227   id=csctype[0];
02228   if(m_wire_hvsegm.find(id) == m_wire_hvsegm.end()) m_wire_hvsegm[id]=zer_1_1a;
02229   intvecIt=m_wire_hvsegm.find(id);
02230   for(int wire=1;wire<=48;wire++)  intvecIt->second[wire]=1;  // Segment 1
02231 
02232   // For ME1/1b
02233   std::vector<int> zer_1_1b(49,0);
02234   id=csctype[1];
02235   if(m_wire_hvsegm.find(id) == m_wire_hvsegm.end()) m_wire_hvsegm[id]=zer_1_1b;
02236   intvecIt=m_wire_hvsegm.find(id);
02237   for(int wire=1;wire<=48;wire++)  intvecIt->second[wire]=1;  // Segment 1
02238  
02239   // For ME1/2
02240   std::vector<int> zer_1_2(65,0);
02241   id=csctype[2];
02242   if(m_wire_hvsegm.find(id) == m_wire_hvsegm.end()) m_wire_hvsegm[id]=zer_1_2;
02243   intvecIt=m_wire_hvsegm.find(id);
02244   for(int wire=1;wire<=24;wire++)  intvecIt->second[wire]=1;  // Segment 1
02245   for(int wire=25;wire<=48;wire++) intvecIt->second[wire]=2;  // Segment 2
02246   for(int wire=49;wire<=64;wire++) intvecIt->second[wire]=3;  // Segment 3
02247  
02248   // For ME1/3
02249   std::vector<int> zer_1_3(33,0);
02250   id=csctype[3];
02251   if(m_wire_hvsegm.find(id) == m_wire_hvsegm.end()) m_wire_hvsegm[id]=zer_1_3;
02252   intvecIt=m_wire_hvsegm.find(id);
02253   for(int wire=1;wire<=12;wire++)  intvecIt->second[wire]=1;  // Segment 1
02254   for(int wire=13;wire<=22;wire++) intvecIt->second[wire]=2;  // Segment 2
02255   for(int wire=23;wire<=32;wire++) intvecIt->second[wire]=3;  // Segment 3
02256  
02257   // For ME2/1
02258   std::vector<int> zer_2_1(113,0);
02259   id=csctype[4];
02260   if(m_wire_hvsegm.find(id) == m_wire_hvsegm.end()) m_wire_hvsegm[id]=zer_2_1;
02261   intvecIt=m_wire_hvsegm.find(id);
02262   for(int wire=1;wire<=44;wire++)   intvecIt->second[wire]=1;  // Segment 1
02263   for(int wire=45;wire<=80;wire++)  intvecIt->second[wire]=2;  // Segment 2
02264   for(int wire=81;wire<=112;wire++) intvecIt->second[wire]=3;  // Segment 3
02265  
02266   // For ME2/2
02267   std::vector<int> zer_2_2(65,0);
02268   id=csctype[5];
02269   if(m_wire_hvsegm.find(id) == m_wire_hvsegm.end()) m_wire_hvsegm[id]=zer_2_2;
02270   intvecIt=m_wire_hvsegm.find(id);
02271   for(int wire=1;wire<=16;wire++)  intvecIt->second[wire]=1;  // Segment 1
02272   for(int wire=17;wire<=28;wire++) intvecIt->second[wire]=2;  // Segment 2
02273   for(int wire=29;wire<=40;wire++) intvecIt->second[wire]=3;  // Segment 3
02274   for(int wire=41;wire<=52;wire++) intvecIt->second[wire]=4;  // Segment 4
02275   for(int wire=53;wire<=64;wire++) intvecIt->second[wire]=5;  // Segment 5
02276 
02277   // For ME3/1
02278   std::vector<int> zer_3_1(97,0);
02279   id=csctype[6];
02280   if(m_wire_hvsegm.find(id) == m_wire_hvsegm.end()) m_wire_hvsegm[id]=zer_3_1;
02281   intvecIt=m_wire_hvsegm.find(id);
02282   for(int wire=1;wire<=32;wire++)  intvecIt->second[wire]=1;  // Segment 1
02283   for(int wire=33;wire<=64;wire++) intvecIt->second[wire]=2;  // Segment 2
02284   for(int wire=65;wire<=96;wire++) intvecIt->second[wire]=3;  // Segment 3
02285  
02286   // For ME3/2
02287   std::vector<int> zer_3_2(65,0);
02288   id=csctype[7];
02289   if(m_wire_hvsegm.find(id) == m_wire_hvsegm.end()) m_wire_hvsegm[id]=zer_3_2;
02290   intvecIt=m_wire_hvsegm.find(id);
02291   for(int wire=1;wire<=16;wire++)  intvecIt->second[wire]=1;  // Segment 1
02292   for(int wire=17;wire<=28;wire++) intvecIt->second[wire]=2;  // Segment 2
02293   for(int wire=29;wire<=40;wire++) intvecIt->second[wire]=3;  // Segment 3
02294   for(int wire=41;wire<=52;wire++) intvecIt->second[wire]=4;  // Segment 4
02295   for(int wire=53;wire<=64;wire++) intvecIt->second[wire]=5;  // Segment 5
02296 
02297   // For ME4/1
02298   std::vector<int> zer_4_1(97,0);
02299   id=csctype[8];
02300   if(m_wire_hvsegm.find(id) == m_wire_hvsegm.end()) m_wire_hvsegm[id]=zer_4_1;
02301   intvecIt=m_wire_hvsegm.find(id);
02302   for(int wire=1;wire<=32;wire++)  intvecIt->second[wire]=1;  // Segment 1
02303   for(int wire=33;wire<=64;wire++) intvecIt->second[wire]=2;  // Segment 2
02304   for(int wire=65;wire<=96;wire++) intvecIt->second[wire]=3;  // Segment 3
02305 
02306   // For ME4/2
02307   std::vector<int> zer_4_2(65,0);
02308   id=csctype[9];
02309   if(m_wire_hvsegm.find(id) == m_wire_hvsegm.end()) m_wire_hvsegm[id]=zer_4_2;
02310   intvecIt=m_wire_hvsegm.find(id);
02311   for(int wire=1;wire<=16;wire++)  intvecIt->second[wire]=1;  // Segment 1
02312   for(int wire=17;wire<=28;wire++) intvecIt->second[wire]=2;  // Segment 2
02313   for(int wire=29;wire<=40;wire++) intvecIt->second[wire]=3;  // Segment 3
02314   for(int wire=41;wire<=52;wire++) intvecIt->second[wire]=4;  // Segment 4
02315   for(int wire=53;wire<=64;wire++) intvecIt->second[wire]=5;  // Segment 5
02316 
02317   } // end of if(nEventsAnalyzed==1)
02318 
02319 
02320      // do wires, strips and rechits present?
02321      wire_strip_rechit_present=0;
02322      if(wirecltn.begin() != wirecltn.end())  
02323        wire_strip_rechit_present= wire_strip_rechit_present+1;
02324      if(strpcltn.begin() != strpcltn.end())    
02325        wire_strip_rechit_present= wire_strip_rechit_present+2;
02326      if(rechitcltn.begin() != rechitcltn.end())
02327        wire_strip_rechit_present= wire_strip_rechit_present+4;
02328 
02329      if(wire_strip_rechit_present==7) {
02330 
02331 //       std::cout<<"Event "<<nEventsAnalyzed<<std::endl;
02332 //       std::cout<<std::endl;
02333 
02334        // cycle on wire collection for all CSC to select single wire hit layers
02335        CSCWireDigiCollection::DigiRangeIterator wiredetUnitIt;
02336  
02337        for(wiredetUnitIt=wirecltn.begin();wiredetUnitIt!=wirecltn.end();
02338           ++wiredetUnitIt) {
02339           const CSCDetId id = (*wiredetUnitIt).first;
02340           idlayer=indexer.dbIndex(id, channel);
02341           idchamber=idlayer/10;
02342           layer=id.layer();
02343           // looping in the layer of given CSC
02344           mult=0; wire=0; 
02345           const CSCWireDigiCollection::Range& range = (*wiredetUnitIt).second;
02346           for(CSCWireDigiCollection::const_iterator digiIt =
02347              range.first; digiIt!=range.second; ++digiIt){
02348              wire=(*digiIt).getWireGroup();
02349              mult++;
02350           }     // end of digis loop in layer
02351 
02352           // select layers with single wire hit
02353           if(mult==1) {
02354             if(m_single_wire_layer.find(idlayer) == m_single_wire_layer.end())
02355               m_single_wire_layer[idlayer]=wire;
02356           } // end of if(mult==1)
02357        }   // end of cycle on detUnit
02358 
02359        // Looping thru rechit collection
02360        CSCRecHit2DCollection::const_iterator recIt;
02361        CSCRecHit2D::ADCContainer m_adc;
02362        CSCRecHit2D::ChannelContainer m_strip;
02363        for(recIt = rechitcltn.begin(); recIt != rechitcltn.end(); ++recIt) {
02364           CSCDetId id = (CSCDetId)(*recIt).cscDetId();
02365           idlayer=indexer.dbIndex(id, channel);
02366           idchamber=idlayer/10;
02367           layer=id.layer();
02368           // select layer with single wire rechit
02369           if(m_single_wire_layer.find(idlayer) != m_single_wire_layer.end()) {
02370 
02371             // getting strips comprising rechit
02372             m_strip=(CSCRecHit2D::ChannelContainer)(*recIt).channels(); 
02373             if(m_strip.size()==3)  {        
02374               // get 3X3 ADC Sum
02375               m_adc=(CSCRecHit2D::ADCContainer)(*recIt).adcs();
02376               std::vector<float> adc_left,adc_center,adc_right;
02377               int binmx=0;
02378               float adcmax=0.0;
02379               unsigned k=0;
02380  
02381               for(int i=0;i<3;i++) 
02382                  for(int j=0;j<4;j++){
02383                     if(m_adc[k]>adcmax) {adcmax=m_adc[k]; binmx=j;}
02384                     if(i==0) adc_left.push_back(m_adc[k]);
02385                     if(i==1) adc_center.push_back(m_adc[k]);
02386                     if(i==2) adc_right.push_back(m_adc[k]);
02387                     k=k+1;
02388                  }
02389                 float adc_3_3_sum=0.0;
02390                 for(int j=binmx-1;j<=binmx+1;j++) {
02391                    adc_3_3_sum=adc_3_3_sum+adc_left[j]
02392                                           +adc_center[j]
02393                                           +adc_right[j];
02394                 }
02395 
02396                if(adc_3_3_sum > 0.0 &&  adc_3_3_sum < 2000.0) {
02397 
02398                  // temporary fix for ME1/1a to avoid triple entries
02399                  int flag=0;
02400                  if(id.station()==1 && id.ring()==4 &&  m_strip[1]>16)  flag=1;
02401                  // end of temporary fix
02402                  if(flag==0) {
02403 
02404                  wire= m_single_wire_layer[idlayer];
02405                  int chambertype=id.iChamberType(id.station(),id.ring());
02406                  int hvsgmtnmb=m_wire_hvsegm[chambertype][wire];
02407                  int nmbofhvsegm=nmbhvsegm[chambertype-1];
02408                  int location= (layer-1)*nmbofhvsegm+hvsgmtnmb;
02409                  float x=location;
02410                 
02411                  ss<<"gas_gain_rechit_adc_3_3_sum_location_ME_"<<idchamber;
02412                  name=ss.str(); ss.str("");
02413                  if(id.endcap()==1) endcapstr = "+";
02414                  ring=id.ring();
02415                  if(id.station()==1 && id.ring()==4) ring=1;
02416                  if(id.endcap()==2) endcapstr = "-"; 
02417                  ss<<"Gas Gain Rechit ADC3X3 Sum ME"<<endcapstr<<
02418                    id.station()<<"/"<<ring<<"/"<<id.chamber();
02419                  title=ss.str(); ss.str("");
02420                  x=location;
02421                  y=adc_3_3_sum;
02422                  histos->fill2DHist(x,y,name.c_str(),title.c_str(),30,1.0,31.0,50,0.0,2000.0,"GasGain");
02423 
02424                  /*
02425                    std::cout<<idchamber<<"   "<<id.station()<<" "<<id.ring()<<" "
02426                    <<id.chamber()<<"    "<<layer<<" "<< wire<<" "<<m_strip[1]<<" "<<
02427                    chambertype<<" "<< hvsgmtnmb<<" "<< nmbofhvsegm<<" "<< 
02428                    location<<"   "<<adc_3_3_sum<<std::endl;
02429                  */
02430                } // end of if flag==0
02431                } // end if(adcsum>0.0 && adcsum<2000.0)
02432             } // end of if if(m_strip.size()==3
02433           } // end of if single wire
02434         } // end of looping thru rechit collection
02435      }   // end of if wire and strip and rechit present 
02436 }
02437 
02438 //---------------------------------------------------------------------------
02439 // Module for looking at AFEB Timing
02440 // Author N. Terentiev
02441 //---------------------------------------------------------------------------
02442 
02443 void CSCValidation::doAFEBTiming(const CSCWireDigiCollection& wirecltn) {
02444      ostringstream ss;
02445      std::string name,title,endcapstr;
02446      float x,y;
02447      int wire,wiretbin,nmbwiretbin,layer,afeb,idlayer,idchamber;
02448      int channel=0; // for  CSCIndexer::dbIndex(id, channel); irrelevant here
02449      CSCIndexer indexer;
02450 
02451      if(wirecltn.begin() != wirecltn.end())  {
02452 
02453        //std::cout<<std::endl;
02454        //std::cout<<"Event "<<nEventsAnalyzed<<std::endl;
02455        //std::cout<<std::endl;
02456 
02457        // cycle on wire collection for all CSC
02458        CSCWireDigiCollection::DigiRangeIterator wiredetUnitIt;
02459        for(wiredetUnitIt=wirecltn.begin();wiredetUnitIt!=wirecltn.end();
02460           ++wiredetUnitIt) {
02461           const CSCDetId id = (*wiredetUnitIt).first;
02462           idlayer=indexer.dbIndex(id, channel);
02463           idchamber=idlayer/10;
02464           layer=id.layer();
02465 
02466           if (id.endcap() == 1) endcapstr = "+";
02467           if (id.endcap() == 2) endcapstr = "-";
02468 
02469           // looping in the layer of given CSC
02470  
02471           const CSCWireDigiCollection::Range& range = (*wiredetUnitIt).second;
02472           for(CSCWireDigiCollection::const_iterator digiIt =
02473              range.first; digiIt!=range.second; ++digiIt){
02474              wire=(*digiIt).getWireGroup();
02475              wiretbin=(*digiIt).getTimeBin();
02476              nmbwiretbin=(*digiIt).getTimeBinsOn().size();
02477              afeb=3*((wire-1)/8)+(layer+1)/2;
02478              
02479              // Anode wire group time bin vs afeb for each CSC
02480              x=afeb;
02481              y=wiretbin;
02482              ss<<"afeb_time_bin_vs_afeb_occupancy_ME_"<<idchamber;
02483              name=ss.str(); ss.str("");
02484              ss<<"Time Bin vs AFEB Occupancy ME"<<endcapstr<<id.station()<<"/"<<id.ring()<<"/"<< id.chamber();
02485              title=ss.str(); ss.str("");
02486              histos->fill2DHist(x,y,name.c_str(),title.c_str(),42,1.,43.,16,0.,16.,"AFEBTiming");
02487 
02488              // Number of anode wire group time bin vs afeb for each CSC
02489              x=afeb;
02490              y=nmbwiretbin;
02491              ss<<"nmb_afeb_time_bins_vs_afeb_ME_"<<idchamber;
02492              name=ss.str(); ss.str("");
02493              ss<<"Number of Time Bins vs AFEB ME"<<endcapstr<<id.station()<<"/"<<id.ring()<<"/"<< id.chamber();
02494              title=ss.str(); 
02495              ss.str("");
02496              histos->fill2DHist(x,y,name.c_str(),title.c_str(),42,1.,43.,16,0.,16.,"AFEBTiming");
02497              
02498           }     // end of digis loop in layer
02499        } // end of wire collection loop
02500      } // end of      if(wirecltn.begin() != wirecltn.end())
02501 }
02502 
02503 //---------------------------------------------------------------------------
02504 // Module for looking at Comparitor Timing
02505 // Author N. Terentiev
02506 //---------------------------------------------------------------------------
02507 
02508 void CSCValidation::doCompTiming(const CSCComparatorDigiCollection& compars) {
02509 
02510      ostringstream ss;      std::string name,title,endcap;
02511      float x,y;
02512      int strip,tbin,layer,cfeb,idlayer,idchamber,idum;
02513      int channel=0; // for  CSCIndexer::dbIndex(id, channel); irrelevant here
02514      CSCIndexer indexer;
02515                                                                                 
02516      if(compars.begin() != compars.end())  {
02517                                                                                 
02518        //std::cout<<std::endl;
02519        //std::cout<<"Event "<<nEventsAnalyzed<<std::endl;
02520        //std::cout<<std::endl;
02521                                                                                 
02522        // cycle on comparators collection for all CSC
02523        CSCComparatorDigiCollection::DigiRangeIterator compdetUnitIt;
02524        for(compdetUnitIt=compars.begin();compdetUnitIt!=compars.end();
02525           ++compdetUnitIt) {
02526           const CSCDetId id = (*compdetUnitIt).first;
02527           idlayer=indexer.dbIndex(id, channel); // channel irrelevant here
02528           idchamber=idlayer/10;
02529           layer=id.layer();
02530                                                                                 
02531           if (id.endcap() == 1) endcap = "+";
02532           if (id.endcap() == 2) endcap = "-";
02533           // looping in the layer of given CSC
02534           const CSCComparatorDigiCollection::Range& range = 
02535           (*compdetUnitIt).second;
02536           for(CSCComparatorDigiCollection::const_iterator digiIt =
02537              range.first; digiIt!=range.second; ++digiIt){
02538              strip=(*digiIt).getStrip();
02539           /*
02540           if(id.station()==1 && (id.ring()==1 || id.ring()==4))
02541              std::cout<<idchamber<<" "<<id.station()<<" "<<id.ring()<<" "
02542                       <<strip <<std::endl;  
02543           */
02544              idum=indexer.dbIndex(id, strip); // strips 1-16 of ME1/1a 
02545                                               // become strips 65-80 of ME1/1 
02546              tbin=(*digiIt).getTimeBin();
02547              cfeb=(strip-1)/16+1;
02548                                                                                 
02549              // time bin vs cfeb for each CSC
02550 
02551              x=cfeb;
02552              y=tbin;
02553              ss<<"comp_time_bin_vs_cfeb_occupancy_ME_"<<idchamber;
02554              name=ss.str(); ss.str("");
02555              ss<<"Comparator Time Bin vs CFEB Occupancy ME"<<endcap<<
02556                  id.station()<<"/"<< id.ring()<<"/"<< id.chamber();             
02557              title=ss.str(); ss.str("");
02558              histos->fill2DHist(x,y,name.c_str(),title.c_str(),5,1.,6.,16,0.,16.,"CompTiming");
02559 
02560          }     // end of digis loop in layer
02561        } // end of collection loop
02562      } // end of      if(compars.begin() !=compars.end())
02563 }
02564 
02565 //---------------------------------------------------------------------------
02566 // Module for looking at Strip Timing
02567 // Author N. Terentiev
02568 //---------------------------------------------------------------------------
02569 
02570 void CSCValidation::doADCTiming(const CSCRecHit2DCollection& rechitcltn) {
02571      float  adc_3_3_sum,adc_3_3_wtbin,x,y;
02572      int cfeb,idchamber,ring;
02573 
02574      std::string name,title,endcapstr;
02575      ostringstream ss;
02576      std::vector<float> zer(6,0.0);
02577 
02578      CSCIndexer indexer;
02579      std::map<int,int>::iterator intIt;
02580 
02581      if(rechitcltn.begin() != rechitcltn.end()) {
02582 
02583   //   std::cout<<"Event "<<nEventsAnalyzed <<std::endl;
02584 
02585        // Looping thru rechit collection
02586        CSCRecHit2DCollection::const_iterator recIt;
02587        CSCRecHit2D::ADCContainer m_adc;
02588        CSCRecHit2D::ChannelContainer m_strip;
02589        for(recIt = rechitcltn.begin(); recIt != rechitcltn.end(); ++recIt) {
02590           CSCDetId id = (CSCDetId)(*recIt).cscDetId();
02591           // getting strips comprising rechit
02592           m_strip=(CSCRecHit2D::ChannelContainer)(*recIt).channels();
02593           if(m_strip.size()==3) {
02594             // get 3X3 ADC Sum
02595             m_adc=(CSCRecHit2D::ADCContainer)(*recIt).adcs();
02596             std::vector<float> adc_left,adc_center,adc_right;
02597             int binmx=0;
02598             float adcmax=0.0;
02599             unsigned k=0;
02600               
02601             for(int i=0;i<3;i++)
02602                for(int j=0;j<4;j++){
02603                   if(m_adc[k]>adcmax) {adcmax=m_adc[k]; binmx=j;}
02604                   if(i==0) adc_left.push_back(m_adc[k]);
02605                   if(i==1) adc_center.push_back(m_adc[k]);
02606                   if(i==2) adc_right.push_back(m_adc[k]);
02607                   k=k+1;
02608                }
02609 
02610                adc_3_3_sum=0.0;
02611                for(int j=binmx-1;j<=binmx+1;j++) { 
02612                   adc_3_3_sum=adc_3_3_sum+adc_left[j]
02613                                           +adc_center[j]
02614                                           +adc_right[j];
02615                }
02616 
02617                 // ADC weighted time bin
02618                 if(adc_3_3_sum > 100.0) {
02619                   
02620                   int centerStrip=m_strip[1]; //take central from 3 strips;
02621                 // temporary fix
02622                   int flag=0;
02623                   if(id.station()==1 && id.ring()==4 &&  centerStrip>16) flag=1;
02624                 // end of temporary fix
02625                   if(flag==0) {
02626                   adc_3_3_wtbin=(*recIt).tpeak()/50;   //getTiming(strpcltn, id, centerStrip);
02627                   idchamber=indexer.dbIndex(id, centerStrip)/10; //strips 1-16 ME1/1a
02628                                               // become strips 65-80 ME1/1 !!!
02629                   /*
02630                   if(id.station()==1 && (id.ring()==1 || id.ring()==4))
02631                   std::cout<<idchamber<<" "<<id.station()<<" "<<id.ring()<<" "<<m_strip[1]<<" "<<
02632                       "      "<<centerStrip<<
02633                          " "<<adc_3_3_wtbin<<"     "<<adc_3_3_sum<<std::endl;    
02634                   */      
02635                  ss<<"adc_3_3_weight_time_bin_vs_cfeb_occupancy_ME_"<<idchamber;
02636                  name=ss.str(); ss.str("");
02637 
02638                  std::string endcapstr;
02639                  if(id.endcap() == 1) endcapstr = "+";
02640                  if(id.endcap() == 2) endcapstr = "-";
02641                  ring=id.ring(); if(id.ring()==4) ring=1;
02642                  ss<<"ADC 3X3 Weighted Time Bin vs CFEB Occupancy ME"
02643                    <<endcapstr<<id.station()<<"/"<<ring<<"/"<<id.chamber();
02644                  title=ss.str(); ss.str("");
02645 
02646                  cfeb=(centerStrip-1)/16+1;
02647                  x=cfeb; y=adc_3_3_wtbin;
02648                  histos->fill2DHist(x,y,name.c_str(),title.c_str(),5,1.,6.,80,-8.,8.,"ADCTiming");                                     
02649                  } // end of if flag==0
02650                 } // end of if (adc_3_3_sum > 100.0)
02651             } // end of if if(m_strip.size()==3
02652        } // end of the  pass thru CSCRecHit2DCollection
02653      }  // end of if (rechitcltn.begin() != rechitcltn.end())
02654 }
02655 
02656 //---------------------------------------------------------------------------------------
02657 // Construct histograms for monitoring the trigger and offline timing
02658 // Author: A. Deisher
02659 //---------------------------------------------------------------------------------------
02660 
02661 void CSCValidation::doTimeMonitoring(edm::Handle<CSCRecHit2DCollection> recHits, edm::Handle<CSCSegmentCollection> cscSegments,
02662                                      edm::Handle<CSCALCTDigiCollection> alcts, edm::Handle<CSCCLCTDigiCollection> clcts,
02663                                      edm::Handle<CSCCorrelatedLCTDigiCollection> correlatedlcts,
02664                                      edm::Handle<L1MuGMTReadoutCollection> pCollection, edm::ESHandle<CSCGeometry> cscGeom, 
02665                                      const edm::EventSetup& eventSetup, const edm::Event &event){
02666 
02667   map<CSCDetId, float > segment_median_map; //structure for storing the median time for segments in a chamber 
02668   map<CSCDetId, GlobalPoint > segment_position_map; //structure for storing the global position for segments in a chamber 
02669   
02670   // -----------------------
02671   // loop over segments
02672   // -----------------------
02673   int iSegment = 0; 
02674   for(CSCSegmentCollection::const_iterator dSiter=cscSegments->begin(); dSiter != cscSegments->end(); dSiter++) {
02675     iSegment++;
02676     
02677     CSCDetId id  = (CSCDetId)(*dSiter).cscDetId();
02678     LocalPoint localPos = (*dSiter).localPosition();
02679     GlobalPoint globalPosition = GlobalPoint(0.0, 0.0, 0.0);
02680     const CSCChamber* cscchamber = cscGeom->chamber(id);
02681     if (cscchamber) {
02682       globalPosition = cscchamber->toGlobal(localPos);
02683     }
02684     
02685     // try to get the CSC recHits that contribute to this segment.
02686     std::vector<CSCRecHit2D> theseRecHits = (*dSiter).specificRecHits();
02687     int nRH = (*dSiter).nRecHits();
02688     if (nRH < 4 ) continue;
02689     
02690     //Store the recHit times of a segment in a vector for later sorting
02691     vector<float> non_zero;
02692     
02693     for ( vector<CSCRecHit2D>::const_iterator iRH = theseRecHits.begin(); iRH != theseRecHits.end(); iRH++) {
02694       CSCDetId idRH = (CSCDetId)(*iRH).cscDetId();
02695       non_zero.push_back( iRH->tpeak());
02696       
02697     }// end rechit loop
02698     
02699     //Sort the vector of hit times for this segment and average the center two
02700     sort(non_zero.begin(),non_zero.end());
02701     int middle_index = non_zero.size()/2;
02702     float average_two = (non_zero.at(middle_index-1) + non_zero.at(middle_index))/2.;
02703     if(non_zero.size()%2)
02704       average_two = non_zero.at(middle_index);
02705 
02706     //If we've vetoed events with multiple segments per chamber, this should never overwrite informations
02707     segment_median_map[id]=average_two;
02708     segment_position_map[id]=globalPosition;
02709     
02710     double distToIP = sqrt(globalPosition.x()*globalPosition.x()+globalPosition.y()*globalPosition.y()+globalPosition.z()*globalPosition.z());
02711      
02712     histos->fillProfile(chamberSerial(id),average_two,"timeChamber","Segment mean time",601,-0.5,600.5,-400.,400.,"TimeMonitoring");
02713     histos->fillProfileByType(id.chamber(),average_two,"timeChamberByType","Segment mean time by chamber",id,36,0.5,36.5,-400,400.,"TimeMonitoring");
02714     histos->fill2DHist(distToIP,average_two,"seg_time_vs_distToIP","Segment time vs. Distance to IP",80,600.,1400.,800,-400,400.,"TimeMonitoring");
02715     histos->fill2DHist(globalPosition.z(),average_two,"seg_time_vs_globZ","Segment time vs. z position",240,-1200,1200,800,-400.,400.,"TimeMonitoring");
02716     histos->fill2DHist(fabs(globalPosition.z()),average_two,"seg_time_vs_absglobZ","Segment time vs. abs(z position)",120,0.,1200.,800,-400.,400.,"TimeMonitoring");
02717     
02718   }//end segment loop
02719   
02720    //Now that the information for each segment we're interest in is stored, it is time to go through the pairs and make plots
02721   map<CSCDetId, float >::const_iterator it_outer; //for the outer loop 
02722   map<CSCDetId, float >::const_iterator it_inner; //for the nested inner loop
02723   for (it_outer = segment_median_map.begin(); it_outer != segment_median_map.end(); it_outer++){
02724     
02725     CSCDetId id_outer =  it_outer->first;
02726     float t_outer = it_outer->second;
02727     
02728     //begin the inner loop
02729     for (it_inner = segment_median_map.begin(); it_inner != segment_median_map.end(); it_inner++){
02730       
02731       CSCDetId id_inner =  it_inner->first;
02732       float t_inner = it_inner->second;
02733       
02734       // we're looking at ordered pairs, so combinations will be double counted 
02735       // (chamber a, chamber b) will be counted as well as (chamber b, chamber a)
02736       // We will avoid (chamber a, chamber a) with the following line
02737       if (chamberSerial(id_outer) == chamberSerial(id_inner)) continue;
02738       
02739       // Calculate expected TOF (in ns units)
02740       // GlobalPoint gp_outer = segment_position_map.find(id_outer)->second;
02741       // GlobalPoint gp_inner = segment_position_map.find(id_inner)->second;
02742       // GlobalVector flight = gp_outer - gp_inner; //in cm
02743       // float TOF = flight.mag()/30.0;             //to ns
02744       
02745       //Plot t(ME+) - t(ME-) for chamber pairs in the same stations and rings but opposite endcaps
02746       if (id_outer.endcap() ==1 && id_inner.endcap() == 2 && id_outer.station() == id_inner.station() && id_outer.ring() == id_inner.ring() ){
02747         histos->fill1DHist(t_outer-t_inner,"diff_opposite_endcaps","#Delta t [ME+]-[ME-] for chambers in same station and ring",800,-400.,400.,"TimeMonitoring");
02748         histos->fill1DHistByType(t_outer-t_inner,"diff_opposite_endcaps_byType","#Delta t [ME+]-[ME-] for chambers in same station and ring",id_outer,800,-400.,400.,"TimeMonitoring");
02749       }
02750 
02751     }//end inner loop of segment pairs
02752   }//end outer loop of segment pairs
02753 
02754   //if the digis, return here
02755   if( !useDigis ) return;
02756 
02757   //looking for the global trigger number 
02758   vector<L1MuGMTReadoutRecord> L1Mrec = pCollection->getRecords();
02759   vector<L1MuGMTReadoutRecord>::const_iterator igmtrr;
02760   int L1GMT_BXN = -100;
02761   bool has_CSCTrigger = false;
02762   bool has_beamHaloTrigger = false;
02763   for(igmtrr=L1Mrec.begin(); igmtrr!=L1Mrec.end(); igmtrr++) {
02764     std::vector<L1MuRegionalCand>::const_iterator iter1;
02765     std::vector<L1MuRegionalCand> rmc;
02766     // CSC
02767     int icsc = 0;
02768     rmc = igmtrr->getCSCCands();
02769     for(iter1=rmc.begin(); iter1!=rmc.end(); iter1++) {
02770       if ( !(*iter1).empty() ) {
02771         icsc++;
02772         int kQuality = (*iter1).quality();   // kQuality = 1 means beam halo
02773         if (kQuality == 1) has_beamHaloTrigger = true;
02774       }
02775     }
02776     if (igmtrr->getBxInEvent() == 0 && icsc>0){
02777       //printf("L1 CSCCands exist.  L1MuGMTReadoutRecord BXN = %d \n", igmtrr->getBxNr());
02778       L1GMT_BXN = igmtrr->getBxNr();
02779       has_CSCTrigger = true;
02780     }
02781     else if (igmtrr->getBxInEvent() == 0 ) { 
02782       //printf("L1 CSCCands do not exist.  L1MuGMTReadoutRecord BXN = %d \n", igmtrr->getBxNr());
02783       L1GMT_BXN = igmtrr->getBxNr();
02784     }
02785   }
02786 
02787   // *************************************************
02788   // *** ALCT Digis **********************************
02789   // *************************************************
02790   
02791   int n_alcts = 0;
02792   map<CSCDetId, int > ALCT_KeyWG_map; //structure for storing the key wire group for the first ALCT for each chamber
02793   for (CSCALCTDigiCollection::DigiRangeIterator j=alcts->begin(); j!=alcts->end(); j++) {
02794     const CSCALCTDigiCollection::Range& range =(*j).second;
02795     const CSCDetId& idALCT = (*j).first;
02796     for (CSCALCTDigiCollection::const_iterator digiIt = range.first; digiIt!=range.second; ++digiIt){
02797       // Valid digi in the chamber (or in neighbouring chamber)  
02798       if((*digiIt).isValid()){
02799         n_alcts++;
02800         histos->fill1DHist( (*digiIt).getBX(), "ALCT_getBX","ALCT.getBX()",11,-0.5,10.5,"TimeMonitoring");
02801         histos->fill1DHist( (*digiIt).getFullBX(), "ALCT_getFullBX","ALCT.getFullBX()",3601,-0.5,3600.5,"TimeMonitoring");
02802         //if we don't already have digi information stored for this chamber, then we fill it
02803         if (ALCT_KeyWG_map.find(idALCT.chamberId()) == ALCT_KeyWG_map.end()){
02804           ALCT_KeyWG_map[idALCT.chamberId()] = (*digiIt).getKeyWG();
02805           //printf("I did fill ALCT info for Chamber %d %d %d %d \n",idALCT.chamberId().endcap(), idALCT.chamberId().station(), idALCT.chamberId().ring(), idALCT.chamberId().chamber());
02806         }
02807 
02808       }
02809     }
02810   }
02811    
02812   // *************************************************
02813   // *** CLCT Digis **********************************
02814   // *************************************************
02815   int n_clcts = 0;
02816   map<CSCDetId, int > CLCT_getFullBx_map; //structure for storing the pretrigger bxn for the first CLCT for each chamber
02817   for (CSCCLCTDigiCollection::DigiRangeIterator j=clcts->begin(); j!=clcts->end(); j++) {
02818     const CSCCLCTDigiCollection::Range& range =(*j).second;
02819     const CSCDetId& idCLCT = (*j).first;
02820     for (CSCCLCTDigiCollection::const_iterator digiIt = range.first; digiIt!=range.second; ++digiIt){
02821       // Valid digi in the chamber (or in neighbouring chamber) 
02822       if((*digiIt).isValid()){
02823         n_clcts++;
02824         histos->fill1DHist( (*digiIt).getBX(), "CLCT_getBX","CLCT.getBX()",11,-0.5,10.5,"TimeMonitoring");
02825         histos->fill1DHist( (*digiIt).getFullBX(), "CLCT_getFullBX","CLCT.getFullBX()",3601,-0.5,3600.5,"TimeMonitoring");
02826         //if we don't already have digi information stored for this chamber, then we fill it
02827         if (CLCT_getFullBx_map.find(idCLCT.chamberId()) == CLCT_getFullBx_map.end()){
02828           CLCT_getFullBx_map[idCLCT.chamberId()] = (*digiIt).getFullBX();
02829           //printf("I did fill CLCT info for Chamber %d %d %d %d \n",idCLCT.chamberId().endcap(), idCLCT.chamberId().station(), idCLCT.chamberId().ring(), idCLCT.chamberId().chamber());
02830         }
02831       }
02832     }
02833   }
02834   
02835   // *************************************************
02836   // *** CorrelatedLCT Digis *************************
02837   // *************************************************
02838   int n_correlatedlcts = 0;
02839   for (CSCCorrelatedLCTDigiCollection::DigiRangeIterator j=correlatedlcts->begin(); j!=correlatedlcts->end(); j++) {
02840     const CSCCorrelatedLCTDigiCollection::Range& range =(*j).second;
02841     for (CSCCorrelatedLCTDigiCollection::const_iterator digiIt = range.first; digiIt!=range.second; ++digiIt){
02842       if((*digiIt).isValid()){
02843         n_correlatedlcts++;
02844         histos->fill1DHist( (*digiIt).getBX(), "CorrelatedLCTS_getBX","CorrelatedLCT.getBX()",11,-0.5,10.5,"TimeMonitoring");
02845       }
02846     }
02847   }
02848 
02849 
02850   int nRecHits = recHits->size();
02851   int nSegments = cscSegments->size();
02852   if (has_CSCTrigger){
02853     histos->fill1DHist(L1GMT_BXN,"BX_L1CSCCand","BX of L1 CSC Cand",4001,-0.5,4000.5,"TimeMonitoring");
02854     histos->fill2DHist(L1GMT_BXN,n_alcts,"n_ALCTs_v_BX_L1CSCCand","Number of ALCTs vs. BX of L1 CSC Cand",4001,-0.5,4000.5,51,-0.5,50.5,"TimeMonitoring");
02855     histos->fill2DHist(L1GMT_BXN,n_clcts,"n_CLCTs_v_BX_L1CSCCand","Number of CLCTs vs. BX of L1 CSC Cand",4001,-0.5,4000.5,51,-0.5,50.5,"TimeMonitoring");
02856     histos->fill2DHist(L1GMT_BXN,n_correlatedlcts,"n_CorrelatedLCTs_v_BX_L1CSCCand","Number of CorrelatedLCTs vs. BX of L1 CSC Cand",4001,-0.5,4000.5,51,-0.5,50.5,"TimeMonitoring");
02857     histos->fill2DHist(L1GMT_BXN,nRecHits,"n_RecHits_v_BX_L1CSCCand","Number of RecHits vs. BX of L1 CSC Cand",4001,-0.5,4000.5,101,-0.5,100.5,"TimeMonitoring");
02858     histos->fill2DHist(L1GMT_BXN,nSegments,"n_Segments_v_BX_L1CSCCand","Number of Segments vs. BX of L1 CSC Cand",4001,-0.5,4000.5,51,-0.5,50.5,"TimeMonitoring");
02859   }
02860   if (has_CSCTrigger && has_beamHaloTrigger){
02861     histos->fill1DHist(L1GMT_BXN,"BX_L1CSCCand_w_beamHalo","BX of L1 CSC (w beamHalo bit)",4001,-0.5,4000.5,"TimeMonitoring");
02862     histos->fill2DHist(L1GMT_BXN,n_alcts,"n_ALCTs_v_BX_L1CSCCand_w_beamHalo","Number of ALCTs vs. BX of L1 CSC Cand (w beamHalo bit)",4001,-0.5,4000.5,51,-0.5,50.5,"TimeMonitoring");
02863     histos->fill2DHist(L1GMT_BXN,n_clcts,"n_CLCTs_v_BX_L1CSCCand_w_beamHalo","Number of CLCTs vs. BX of L1 CSC Cand (w beamHalo bit)",4001,-0.5,4000.5,51,-0.5,50.5,"TimeMonitoring");
02864     histos->fill2DHist(L1GMT_BXN,n_correlatedlcts,"n_CorrelatedLCTs_v_BX_L1CSCCand_w_beamHalo","Number of CorrelatedLCTs vs. BX of L1 CSC Cand (w beamHalo bit)",4001,-0.5,4000.5,51,-0.5,50.5,"TimeMonitoring");
02865     histos->fill2DHist(L1GMT_BXN,nRecHits,"n_RecHits_v_BX_L1CSCCand_w_beamHalo","Number of RecHits vs. BX of L1 CSC Cand (w beamHalo bit)",4001,-0.5,4000.5,101,-0.5,100.5,"TimeMonitoring");
02866     histos->fill2DHist(L1GMT_BXN,nSegments,"n_Segments_v_BX_L1CSCCand_w_beamHalo","Number of Segments vs. BX of L1 CSC Cand (w beamHalo bit)",4001,-0.5,4000.5,51,-0.5,50.5,"TimeMonitoring");
02867   }
02868   
02869   // *******************************************************************
02870   // Get information from the TMB header.  
02871   // Can this eventually come out of the digis?
02872   // Taking code from EventFilter/CSCRawToDigis/CSCDCCUnpacker.cc
02873   // *******************************************************************
02874   
02875   edm::ESHandle<CSCCrateMap> hcrate;
02876   eventSetup.get<CSCCrateMapRcd>().get(hcrate); 
02877   const CSCCrateMap* pcrate = hcrate.product();
02878   
02880   edm::Handle<FEDRawDataCollection> rawdata;
02881   event.getByLabel("source", rawdata);
02882   bool goodEvent = false;
02883   // If set selective unpacking mode 
02884   // hardcoded examiner mask below to check for DCC and DDU level errors will be used first
02885   // then examinerMask for CSC level errors will be used during unpacking of each CSC block
02886   unsigned long dccBinCheckMask = 0x06080016;
02887   unsigned int examinerMask = 0x1FEBF3F6; 
02888   unsigned int errorMask = 0x0;
02889 
02890   for (int id=FEDNumbering::MINCSCFEDID; id<=FEDNumbering::MAXCSCFEDID; ++id) {
02891     // loop over DCCs
02894     
02896     const FEDRawData& fedData = rawdata->FEDData(id);
02897     unsigned long length =  fedData.size();
02898     
02899     if (length>=32){ 
02900       CSCDCCExaminer* examiner = NULL;
02901       std::stringstream examiner_out, examiner_err;
02902       goodEvent = true;
02904       //CSCDCCExaminer examiner;
02905       examiner = new CSCDCCExaminer();
02906       examiner->output1().redirect(examiner_out);
02907       examiner->output2().redirect(examiner_err);
02908       if( examinerMask&0x40000 ) examiner->crcCFEB(1);
02909       if( examinerMask&0x8000  ) examiner->crcTMB (1);
02910       if( examinerMask&0x0400  ) examiner->crcALCT(1);
02911       examiner->output1().show();
02912       examiner->output2().show();
02913       examiner->setMask(examinerMask);
02914       const short unsigned int *data = (short unsigned int *)fedData.data();
02915      
02916       if( examiner->check(data,long(fedData.size()/2)) < 0 )    {
02917         goodEvent=false;
02918       } 
02919       else {      
02920         goodEvent=!(examiner->errors()&dccBinCheckMask);
02921       }  
02922       
02923       if (goodEvent) {
02925         CSCDCCExaminer * ptrExaminer = examiner;
02926         CSCDCCEventData dccData((short unsigned int *) fedData.data(),ptrExaminer);
02927         
02929         const std::vector<CSCDDUEventData> & dduData = dccData.dduData();
02930         
02932         CSCDetId layer(1, 1, 1, 1, 1);
02933         
02934         for (unsigned int iDDU=0; iDDU<dduData.size(); ++iDDU) {  // loop over DDUs
02937           if (dduData[iDDU].trailer().errorstat()&errorMask) {
02938             LogTrace("CSCDCCUnpacker|CSCRawToDigi") << "DDU# " << iDDU << " has serious error - no digis unpacked! " <<
02939               std::hex << dduData[iDDU].trailer().errorstat();
02940             continue; // to next iteration of DDU loop
02941           }
02942           
02944           const std::vector<CSCEventData> & cscData = dduData[iDDU].cscData();
02945           for (unsigned int iCSC=0; iCSC<cscData.size(); ++iCSC) { // loop over CSCs
02946             
02947             int vmecrate = cscData[iCSC].dmbHeader()->crateID();
02948             int dmb = cscData[iCSC].dmbHeader()->dmbID();
02949             
02951             // SKIPPING MTCC redefinition of vmecrate
02952             
02953             int icfeb = 0;  
02954             int ilayer = 0; 
02955             
02956             if ((vmecrate>=1)&&(vmecrate<=60) && (dmb>=1)&&(dmb<=10)&&(dmb!=6)) {
02957               layer = pcrate->detId(vmecrate, dmb,icfeb,ilayer );
02958             } 
02959             else{
02960               LogTrace ("CSCTimingAlignment|CSCDCCUnpacker|CSCRawToDigi") << " detID input out of range!!! ";
02961               LogTrace ("CSCTimingAlignment|CSCDCCUnpacker|CSCRawToDigi")
02962                 << " skipping chamber vme= " << vmecrate << " dmb= " << dmb;
02963               continue; // to next iteration of iCSC loop
02964             }
02965             
02967             int nalct = cscData[iCSC].dmbHeader()->nalct();
02968             bool goodALCT=false;
02969             //if (nalct&&(cscData[iCSC].dataPresent>>6&0x1)==1) {
02970             if (nalct&&cscData[iCSC].alctHeader()) {  
02971               if (cscData[iCSC].alctHeader()->check()){
02972                 goodALCT=true;
02973               }
02974             }
02975             
02977             int nclct = cscData[iCSC].dmbHeader()->nclct();
02978             bool goodTMB=false;
02979             if (nclct&&cscData[iCSC].tmbData()) {
02980               if (cscData[iCSC].tmbHeader()->check()){
02981                 if (cscData[iCSC].clctData()->check()) goodTMB=true; 
02982               }
02983             }  
02984               
02985             if (goodTMB && goodALCT) { 
02986 
02987               if (ALCT_KeyWG_map.find(layer) == ALCT_KeyWG_map.end()) {
02988                 printf("no ALCT info for Chamber %d %d %d %d \n",layer.endcap(), layer.station(), layer.ring(), layer.chamber());
02989                 continue;
02990               }
02991               if (CLCT_getFullBx_map.find(layer) == CLCT_getFullBx_map.end()) {
02992                 printf("no CLCT info for Chamber %d %d %d %d \n",layer.endcap(), layer.station(), layer.ring(), layer.chamber());
02993                 continue;
02994               }
02995               int ALCT0Key = ALCT_KeyWG_map.find(layer)->second;
02996               int CLCTPretrigger = CLCT_getFullBx_map.find(layer)->second;
02997 
02998 
02999 
03000               const CSCTMBHeader *tmbHead = cscData[iCSC].tmbHeader();
03001 
03002               histos->fill1DHistByStation(tmbHead->BXNCount(),     "TMB_BXNCount"     ,"TMB_BXNCount"     , layer.chamberId(),3601,-0.5,3600.5,"TimeMonitoring");
03003               histos->fill1DHistByStation(tmbHead->ALCTMatchTime(),"TMB_ALCTMatchTime","TMB_ALCTMatchTime", layer.chamberId(),7,-0.5,6.5,"TimeMonitoring");
03004 
03005               histos->fill1DHist(tmbHead->BXNCount(),     "TMB_BXNCount"     ,"TMB_BXNCount"     , 3601,-0.5,3600.5,"TimeMonitoring");
03006               histos->fill1DHist(tmbHead->ALCTMatchTime(),"TMB_ALCTMatchTime","TMB_ALCTMatchTime", 7,-0.5,6.5,"TimeMonitoring");
03007 
03008               histos->fill1DHistByType(tmbHead->ALCTMatchTime(),"TMB_ALCTMatchTime","TMB_ALCTMatchTime",layer.chamberId(), 7,-0.5,6.5,"TimeMonitoring");
03009 
03010               histos->fillProfile( chamberSerial(layer.chamberId()),tmbHead->ALCTMatchTime(),"prof_TMB_ALCTMatchTime","prof_TMB_ALCTMatchTime", 601,-0.5,600.5,-0.5,7.5,"TimeMonitoring");
03011               histos->fillProfile(ALCT0Key,tmbHead->ALCTMatchTime(),"prof_TMB_ALCTMatchTime_v_ALCT0KeyWG","prof_TMB_ALCTMatchTime_v_ALCT0KeyWG",128,-0.5,127.5,0,7,"TimeMonitoring");
03012               histos->fillProfileByType(ALCT0Key,tmbHead->ALCTMatchTime(),"prf_TMB_ALCTMatchTime_v_ALCT0KeyWG","prf_TMB_ALCTMatchTime_v_ALCT0KeyWG",layer.chamberId(),128,-0.5,127.5,0,7,"TimeMonitoring");
03013 
03014               //Attempt to make a few sum plots
03015 
03016               int TMB_ALCT_rel_L1A = tmbHead->BXNCount()-(CLCTPretrigger+2+tmbHead->ALCTMatchTime());
03017               if (TMB_ALCT_rel_L1A > 3563)
03018                 TMB_ALCT_rel_L1A = TMB_ALCT_rel_L1A - 3564;
03019               if (TMB_ALCT_rel_L1A < 0)
03020                 TMB_ALCT_rel_L1A = TMB_ALCT_rel_L1A + 3564;
03021 
03022               //Plot TMB_ALCT_rel_L1A
03023               histos->fill1DHist(TMB_ALCT_rel_L1A,"h1D_TMB_ALCT_rel_L1A","h1D_TMB_ALCT_rel_L1A",11,144.5,155.5,"TimeMonitoring");
03024               histos->fill2DHist( chamberSerial(layer.chamberId()),TMB_ALCT_rel_L1A,"h2D_TMB_ALCT_rel_L1A","h2D_TMB_ALCT_rel_L1A", 601,-0.5,600.5,11,144.5,155.5,"TimeMonitoring");
03025               histos->fill2DHist( ringSerial(layer.chamberId()),TMB_ALCT_rel_L1A,"h2D_TMB_ALCT_rel_L1A_by_ring","h2D_TMB_ALCT_rel_L1A_by_ring",19,-9.5,9.5,11,144.5,155.5,"TimeMonitoring");
03026               histos->fillProfile( chamberSerial(layer.chamberId()),TMB_ALCT_rel_L1A,"prof_TMB_ALCT_rel_L1A","prof_TMB_ALCT_rel_L1A", 601,-0.5,600.5,145,155,"TimeMonitoring");
03027               histos->fillProfile( ringSerial(layer.chamberId()),TMB_ALCT_rel_L1A,"prof_TMB_ALCT_rel_L1A_by_ring","prof_TMB_ALCT_rel_L1A_by_ring",19,-9.5,9.5,145,155,"TimeMonitoring");
03028 
03029               histos->fill2DHist (ALCT0Key,TMB_ALCT_rel_L1A,"h2D_TMB_ALCT_rel_L1A_v_ALCT0KeyWG","h2D_TMB_ALCT_rel_L1A_v_ALCT0KeyWG",  128,-0.5,127.5,11,144.5,155.5,"TimeMonitoring");
03030               histos->fillProfile(ALCT0Key,TMB_ALCT_rel_L1A,"prof_TMB_ALCT_rel_L1A_v_ALCT0KeyWG","prof_TMB_ALCT_rel_L1A_v_ALCT0KeyWG",128,-0.5,127.5,145,155,"TimeMonitoring");
03031               histos->fillProfileByType(ALCT0Key,TMB_ALCT_rel_L1A,"prf_TMB_ALCT_rel_L1A_v_ALCT0KeyWG","prf_TMB_ALCT_rel_L1A_v_ALCT0KeyWG",layer.chamberId(),128,-0.5,127.5,145,155,"TimeMonitoring");
03032             }
03033 
03034           } // end CSCData loop
03035         } // end ddu data loop
03036       } // end if goodEvent
03037       if (examiner!=NULL) delete examiner;
03038     }// end if non-zero fed data
03039   } // end DCC loop for NON-REFERENCE
03040 
03041 }
03042 
03043 
03044 void CSCValidation::endJob() {
03045 
03046      std::cout<<"Events in "<<nEventsAnalyzed<<std::endl;
03047 }
03048 
03049 DEFINE_FWK_MODULE(CSCValidation);
03050