CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_4_1_8_patch12/src/Alignment/OfflineValidation/plugins/TrackerOfflineValidationSummary.cc

Go to the documentation of this file.
00001 // -*- C++ -*-
00002 //
00003 // Package:    TrackerOfflineValidationSummary
00004 // Class:      TrackerOfflineValidationSummary
00005 // 
00013 //
00014 // Original Author:  Johannes Hauk
00015 //         Created:  Sat Aug 22 10:31:34 CEST 2009
00016 // $Id: TrackerOfflineValidationSummary.cc,v 1.5 2009/12/11 19:10:32 hauk Exp $
00017 //
00018 //
00019 
00020 
00021 // system include files
00022 #include <memory>
00023 
00024 // user include files
00025 #include "FWCore/Framework/interface/Frameworkfwd.h"
00026 #include "FWCore/Framework/interface/EDAnalyzer.h"
00027 
00028 #include "FWCore/Framework/interface/Event.h"
00029 #include "FWCore/Framework/interface/MakerMacros.h"
00030 
00031 #include "FWCore/ParameterSet/interface/ParameterSet.h"
00032 
00033 
00034 #include "FWCore/Framework/interface/ESHandle.h"
00035 #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h"
00036 #include "Geometry/Records/interface/TrackerDigiGeometryRecord.h"
00037 #include "Alignment/TrackerAlignment/interface/AlignableTracker.h"
00038 #include "Alignment/CommonAlignment/interface/AlignableObjectId.h"
00039 
00040 
00041 #include "TTree.h"
00042 //#include "Alignment/OfflineValidation/interface/TrackerValidationVariables.h"
00043 #include "Alignment/OfflineValidation/interface/TkOffTreeVariables.h"
00044 
00045 #include "DataFormats/SiPixelDetId/interface/PixelSubdetector.h"
00046 #include "DataFormats/SiPixelDetId/interface/PXBDetId.h"
00047 #include "DataFormats/SiPixelDetId/interface/PXFDetId.h"
00048 #include "DataFormats/SiStripDetId/interface/TECDetId.h"
00049 #include "DataFormats/SiStripDetId/interface/TIBDetId.h"
00050 #include "DataFormats/SiStripDetId/interface/TIDDetId.h"
00051 #include "DataFormats/SiStripDetId/interface/TOBDetId.h"
00052 #include "DataFormats/GeometrySurface/interface/Surface.h"
00053 #include "Geometry/CommonDetUnit/interface/GeomDet.h"
00054 #include "DataFormats/Math/interface/deltaPhi.h"
00055 #include "TH1.h"
00056 #include "TMath.h"
00057 
00058 #include "DQMServices/Core/interface/DQMStore.h"
00059 #include "DQMServices/Core/interface/MonitorElement.h"
00060 #include "FWCore/ServiceRegistry/interface/Service.h"
00061 
00062 //
00063 // class decleration
00064 //
00065 
00066 class TrackerOfflineValidationSummary : public edm::EDAnalyzer {
00067    public:
00068       explicit TrackerOfflineValidationSummary(const edm::ParameterSet&);
00069       ~TrackerOfflineValidationSummary();
00070 
00071 
00072    private:
00073       
00074       struct ModuleHistos{
00075         ModuleHistos() :  ResHisto(), NormResHisto(), ResXprimeHisto(), NormResXprimeHisto(), 
00076                           ResYprimeHisto(), NormResYprimeHisto() {} 
00077         TH1* ResHisto;
00078         TH1* NormResHisto;
00079         TH1* ResXprimeHisto;
00080         TH1* NormResXprimeHisto;
00081         TH1* ResYprimeHisto;
00082         TH1* NormResYprimeHisto;
00083       };
00084       
00086       struct HarvestingHistos{
00087         HarvestingHistos() : DmrXprime(), DmrYprime() {}
00088         TH1* DmrXprime;
00089         TH1* DmrYprime;
00090       };
00091       
00092       struct HarvestingHierarchy{
00093         HarvestingHierarchy() {}
00094         HarvestingHierarchy(const std::string& name, const std::string& component, const std::vector<unsigned int>& entries) : hierarchyName(name), componentName(component), treeEntries(entries) {}
00095         // Needed for naming of histogram according to residual histograms
00096         std::string hierarchyName;
00097         // "Pixel" or "Strip"
00098         std::string componentName;
00099         // Modules belonging to selected hierarchy
00100         std::vector<unsigned int> treeEntries;
00101         HarvestingHistos harvestingHistos;
00102       };
00103       
00104       virtual void analyze(const edm::Event& evt, const edm::EventSetup&);
00105       virtual void endJob() ;
00106       
00107       void fillTree(TTree& tree, std::map<int, TrackerOfflineValidationSummary::ModuleHistos>& moduleHist, 
00108                 TkOffTreeVariables& treeMem, const TrackerGeometry& tkgeom, std::map<std::string,std::string>& substructureName);
00109       
00110       std::pair<float,float> fitResiduals(TH1* hist)const;
00111       float getMedian(const TH1* hist)const;
00112       
00113       const std::string associateModuleHistsWithTree(const TkOffTreeVariables& treeMem, TrackerOfflineValidationSummary::ModuleHistos& moduleHists, std::map<std::string,std::string>& substructureName);
00114       
00115       void collateHarvestingHists(TTree& tree);
00116       void applyHarvestingHierarchy(TTree& treeMem);
00117       void bookHarvestingHists();
00118       void getBinning(const std::string& binningPSetName, int& nBinsX, double& lowerBoundX, double& upperBoundX)const;
00119       void fillHarvestingHists(TTree& tree);
00120       
00121       // ----------member data ---------------------------
00122       
00123       const edm::ParameterSet parSet_;
00124       edm::ESHandle<TrackerGeometry> tkGeom_;
00125       
00126       // parameters from cfg to steer
00127       const std::string moduleDirectory_;
00128       const bool useFit_;
00129       
00130       DQMStore* dbe_;
00131       
00132       bool moduleMapsInitialized;
00133       
00134       std::map<int,TrackerOfflineValidationSummary::ModuleHistos> mPxbResiduals_;
00135       std::map<int,TrackerOfflineValidationSummary::ModuleHistos> mPxeResiduals_;
00136       std::map<int,TrackerOfflineValidationSummary::ModuleHistos> mTibResiduals_;
00137       std::map<int,TrackerOfflineValidationSummary::ModuleHistos> mTidResiduals_;
00138       std::map<int,TrackerOfflineValidationSummary::ModuleHistos> mTobResiduals_;
00139       std::map<int,TrackerOfflineValidationSummary::ModuleHistos> mTecResiduals_;
00140       
00141       std::vector<HarvestingHierarchy> vHarvestingHierarchy_;
00142 };
00143 
00144 //
00145 // constants, enums and typedefs
00146 //
00147 
00148 //
00149 // static data member definitions
00150 //
00151 
00152 //
00153 // constructors and destructor
00154 //
00155 TrackerOfflineValidationSummary::TrackerOfflineValidationSummary(const edm::ParameterSet& iConfig):
00156    parSet_(iConfig), moduleDirectory_(parSet_.getParameter<std::string>("moduleDirectoryInOutput")),
00157    useFit_(parSet_.getParameter<bool>("useFit")), dbe_(0), moduleMapsInitialized(false)
00158 {
00159   //now do what ever initialization is needed
00160   dbe_ = edm::Service<DQMStore>().operator->();
00161 }
00162 
00163 
00164 TrackerOfflineValidationSummary::~TrackerOfflineValidationSummary()
00165 {
00166  
00167    // do anything here that needs to be done at desctruction time
00168    // (e.g. close files, deallocate resources etc.)
00169 
00170 }
00171 
00172 
00173 //
00174 // member functions
00175 //
00176 
00177 // ------------ method called to for each event  ------------
00178 void
00179 TrackerOfflineValidationSummary::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup)
00180 {
00181   // Access of EventSetup is needed to get the list of silicon-modules and their IDs
00182   // Since they do not change, it is accessed only once
00183   if(moduleMapsInitialized)return;
00184   iSetup.get<TrackerDigiGeometryRecord>().get( tkGeom_ );
00185   const TrackerGeometry* bareTkGeomPtr = &(*tkGeom_);
00186   const TrackingGeometry::DetIdContainer& detIdContainer = bareTkGeomPtr->detIds();
00187   std::vector<DetId>::const_iterator iDet;
00188   for(iDet = detIdContainer.begin(); iDet != detIdContainer.end(); ++iDet){
00189     const DetId& detId = *iDet;
00190     const uint32_t rawId = detId.rawId();
00191     const unsigned int subdetId = detId.subdetId();
00192     if     (subdetId == PixelSubdetector::PixelBarrel) mPxbResiduals_[rawId];
00193     else if(subdetId == PixelSubdetector::PixelEndcap) mPxeResiduals_[rawId];
00194     else if(subdetId  == StripSubdetector::TIB) mTibResiduals_[rawId];
00195     else if(subdetId  == StripSubdetector::TID) mTidResiduals_[rawId];
00196     else if(subdetId  == StripSubdetector::TOB) mTobResiduals_[rawId];
00197     else if(subdetId  == StripSubdetector::TEC) mTecResiduals_[rawId];
00198     else {
00199       throw cms::Exception("Geometry Error")
00200         << "[TrackerOfflineValidationSummary] Error, tried to get reference for non-tracker subdet " << subdetId 
00201         << " from detector " << detId.det();
00202       mPxbResiduals_[0];
00203     }
00204   }
00205   moduleMapsInitialized = true;
00206 }
00207 
00208 
00209 // ------------ method called once each job just after ending the event loop  ------------
00210 void 
00211 TrackerOfflineValidationSummary::endJob()
00212 {
00213   AlignableTracker aliTracker(&(*tkGeom_));
00214   AlignableObjectId aliobjid;
00215   
00216   TTree* tree = new TTree("TkOffVal","TkOffVal");
00217   
00218   TkOffTreeVariables *treeMemPtr = new TkOffTreeVariables;
00219   // We create branches for all members of 'TkOffTreeVariables' (even if not needed).
00220   // This works because we have a dictionary for 'TkOffTreeVariables'
00221   // (see src/classes_def.xml and src/classes.h):
00222   tree->Branch("TkOffTreeVariables", &treeMemPtr); // address of pointer!
00223   // second branch needed for assigning names and titles to harvesting histograms consistent to others
00224   std::map<std::string,std::string> *substructureName = new std::map<std::string,std::string>;
00225   tree->Branch("SubstructureName", &substructureName, 32000, 00);  // SplitLevel must be set to zero
00226   
00227   
00228   this->fillTree(*tree, mPxbResiduals_, *treeMemPtr, *tkGeom_, *substructureName);
00229   this->fillTree(*tree, mPxeResiduals_, *treeMemPtr, *tkGeom_, *substructureName);
00230   this->fillTree(*tree, mTibResiduals_, *treeMemPtr, *tkGeom_, *substructureName);
00231   this->fillTree(*tree, mTidResiduals_, *treeMemPtr, *tkGeom_, *substructureName);
00232   this->fillTree(*tree, mTobResiduals_, *treeMemPtr, *tkGeom_, *substructureName);
00233   this->fillTree(*tree, mTecResiduals_, *treeMemPtr, *tkGeom_, *substructureName);
00234   
00235   //dbe_->showDirStructure();
00236   //dbe_->save("dqmOut.root");
00237   
00238   // Method for filling histograms which show summarized values (mean, rms, median ...)
00239   // of the module-based histograms from TrackerOfflineValidation
00240   this->collateHarvestingHists(*tree);
00241   
00242   delete tree; tree = 0;
00243   delete treeMemPtr; treeMemPtr = 0;
00244   delete substructureName; substructureName = 0;
00245 }
00246 
00247 
00248 void 
00249 TrackerOfflineValidationSummary::fillTree(TTree& tree,
00250                                    std::map<int, TrackerOfflineValidationSummary::ModuleHistos>& moduleHist,
00251                                    TkOffTreeVariables& treeMem, const TrackerGeometry& tkgeom, std::map<std::string,std::string>& substructureName)
00252 {
00253   for(std::map<int, TrackerOfflineValidationSummary::ModuleHistos>::iterator it = moduleHist.begin(), 
00254         itEnd= moduleHist.end(); it != itEnd;++it ) { 
00255     treeMem.clear(); // make empty/default
00256     
00257     //variables concerning the tracker components/hierarchy levels
00258     const DetId detId = it->first;
00259     treeMem.moduleId = detId;
00260     treeMem.subDetId = detId.subdetId();
00261 
00262     if(treeMem.subDetId == PixelSubdetector::PixelBarrel){
00263       PXBDetId pxbId(detId);
00264       unsigned int whichHalfBarrel(1), rawId(detId.rawId());  //DetId does not know about halfBarrels is PXB ...
00265       if( (rawId>=302056964 && rawId<302059300) || (rawId>=302123268 && rawId<302127140) || (rawId>=302189572 && rawId<302194980) )whichHalfBarrel=2;
00266       treeMem.layer = pxbId.layer();
00267       treeMem.half = whichHalfBarrel; 
00268       treeMem.rod = pxbId.ladder();     // ... so, ladder is not per halfBarrel-Layer, but per barrel-layer! Needs complicated calculation in associateModuleHistsWithTree()
00269       treeMem.module = pxbId.module();
00270     } else if(treeMem.subDetId == PixelSubdetector::PixelEndcap){
00271       PXFDetId pxfId(detId); 
00272       unsigned int whichHalfCylinder(1), rawId(detId.rawId());  //DetId does not kmow about halfCylinders in PXF
00273       if( (rawId>=352394500 && rawId<352406032) || (rawId>=352460036 && rawId<352471568) || (rawId>=344005892 && rawId<344017424) || (rawId>=344071428 && rawId<344082960) )whichHalfCylinder=2;
00274       treeMem.layer = pxfId.disk(); 
00275       treeMem.side = pxfId.side();
00276       treeMem.half = whichHalfCylinder;
00277       treeMem.blade = pxfId.blade(); 
00278       treeMem.panel = pxfId.panel();
00279       treeMem.module = pxfId.module();
00280     } else if(treeMem.subDetId == StripSubdetector::TIB){
00281       TIBDetId tibId(detId); 
00282       unsigned int whichHalfShell(1), rawId(detId.rawId());  //DetId does not kmow about halfShells in TIB
00283        if ( (rawId>=369120484 && rawId<369120688) || (rawId>=369121540 && rawId<369121776) || (rawId>=369136932 && rawId<369137200) || (rawId>=369137988 && rawId<369138288) ||
00284             (rawId>=369153396 && rawId<369153744) || (rawId>=369154436 && rawId<369154800) || (rawId>=369169844 && rawId<369170256) || (rawId>=369170900 && rawId<369171344) ||
00285             (rawId>=369124580 && rawId<369124784) || (rawId>=369125636 && rawId<369125872) || (rawId>=369141028 && rawId<369141296) || (rawId>=369142084 && rawId<369142384) ||
00286             (rawId>=369157492 && rawId<369157840) || (rawId>=369158532 && rawId<369158896) || (rawId>=369173940 && rawId<369174352) || (rawId>=369174996 && rawId<369175440) ) whichHalfShell=2;
00287       treeMem.layer = tibId.layer(); 
00288       treeMem.side = tibId.string()[0];
00289       treeMem.half = whichHalfShell;
00290       treeMem.rod = tibId.string()[2]; 
00291       treeMem.outerInner = tibId.string()[1]; 
00292       treeMem.module = tibId.module();
00293       treeMem.isStereo = tibId.stereo();
00294       treeMem.isDoubleSide = tibId.isDoubleSide();
00295     } else if(treeMem.subDetId == StripSubdetector::TID){
00296       TIDDetId tidId(detId); 
00297       treeMem.layer = tidId.wheel(); 
00298       treeMem.side = tidId.side();
00299       treeMem.ring = tidId.ring(); 
00300       treeMem.outerInner = tidId.module()[0]; 
00301       treeMem.module = tidId.module()[1];
00302       treeMem.isStereo = tidId.stereo();
00303       treeMem.isDoubleSide = tidId.isDoubleSide();
00304     } else if(treeMem.subDetId == StripSubdetector::TOB){
00305       TOBDetId tobId(detId); 
00306       treeMem.layer = tobId.layer(); 
00307       treeMem.side = tobId.rod()[0];
00308       treeMem.rod = tobId.rod()[1]; 
00309       treeMem.module = tobId.module();
00310       treeMem.isStereo = tobId.stereo();
00311       treeMem.isDoubleSide = tobId.isDoubleSide();
00312     } else if(treeMem.subDetId == StripSubdetector::TEC) {
00313       TECDetId tecId(detId); 
00314       treeMem.layer = tecId.wheel(); 
00315       treeMem.side  = tecId.side();
00316       treeMem.ring  = tecId.ring(); 
00317       treeMem.petal = tecId.petal()[1]; 
00318       treeMem.outerInner = tecId.petal()[0];
00319       treeMem.module = tecId.module();
00320       treeMem.isStereo = tecId.stereo();
00321       treeMem.isDoubleSide = tecId.isDoubleSide();
00322     }
00323     
00324     //variables concerning the tracker geometry
00325     
00326     const Surface::PositionType &gPModule = tkgeom.idToDet(detId)->position();
00327     treeMem.posPhi = gPModule.phi();
00328     treeMem.posEta = gPModule.eta();
00329     treeMem.posR   = gPModule.perp();
00330     treeMem.posX   = gPModule.x();
00331     treeMem.posY   = gPModule.y();
00332     treeMem.posZ   = gPModule.z();
00333  
00334     const Surface& surface =  tkgeom.idToDet(detId)->surface();
00335     
00336     //global Orientation of local coordinate system of dets/detUnits   
00337     LocalPoint  lUDirection(1.,0.,0.), lVDirection(0.,1.,0.), lWDirection(0.,0.,1.);
00338     GlobalPoint gUDirection = surface.toGlobal(lUDirection),
00339                 gVDirection = surface.toGlobal(lVDirection),
00340                 gWDirection = surface.toGlobal(lWDirection);
00341     double dR(999.), dPhi(999.), dZ(999.);
00342     if(treeMem.subDetId==PixelSubdetector::PixelBarrel || treeMem.subDetId==StripSubdetector::TIB || treeMem.subDetId==StripSubdetector::TOB){
00343       dR = gWDirection.perp() - gPModule.perp();
00344       dPhi = deltaPhi(gUDirection.phi(),gPModule.phi());
00345       dZ = gVDirection.z() - gPModule.z();
00346       if(dZ>=0.)treeMem.rOrZDirection = 1; else treeMem.rOrZDirection = -1;
00347     }else if(treeMem.subDetId==PixelSubdetector::PixelEndcap){
00348       dR = gUDirection.perp() - gPModule.perp();
00349       dPhi = deltaPhi(gVDirection.phi(),gPModule.phi());
00350       dZ = gWDirection.z() - gPModule.z();
00351       if(dR>=0.)treeMem.rOrZDirection = 1; else treeMem.rOrZDirection = -1;
00352     }else if(treeMem.subDetId==StripSubdetector::TID || treeMem.subDetId==StripSubdetector::TEC){
00353       dR = gVDirection.perp() - gPModule.perp();
00354       dPhi = deltaPhi(gUDirection.phi(),gPModule.phi());
00355       dZ = gWDirection.z() - gPModule.z();
00356       if(dR>=0.)treeMem.rOrZDirection = 1; else treeMem.rOrZDirection = -1;
00357     }
00358     if(dR>=0.)treeMem.rDirection = 1; else treeMem.rDirection = -1;
00359     if(dPhi>=0.)treeMem.phiDirection = 1; else treeMem.phiDirection = -1;
00360     if(dZ>=0.)treeMem.zDirection = 1; else treeMem.zDirection = -1;
00361     
00362     
00363     // Assign histos from first step (TrackerOfflineValidation) to the module's entry in the TTree for retrieving mean, rms, median ...
00364     const std::string histDir = associateModuleHistsWithTree(treeMem, it->second, substructureName);
00365     
00366     
00367     //mean and RMS values (extracted from histograms Xprime on module level)
00368     treeMem.entries = static_cast<UInt_t>(it->second.ResXprimeHisto->GetEntries());
00369     treeMem.meanX = it->second.ResXprimeHisto->GetMean();
00370     treeMem.rmsX  = it->second.ResXprimeHisto->GetRMS();
00371     //treeMem.sigmaX = Fwhm(it->second.ResXprimeHisto)/2.355;
00372     if (useFit_) {
00373       //call fit function which returns mean and sigma from the fit
00374       //for absolute residuals
00375       std::pair<float,float> fitResult1 = this->fitResiduals(it->second.ResXprimeHisto);
00376       treeMem.fitMeanX = fitResult1.first;
00377       treeMem.fitSigmaX = fitResult1.second;
00378       //for normalized residuals
00379       std::pair<float,float> fitResult2 = this->fitResiduals(it->second.NormResXprimeHisto);
00380       treeMem.fitMeanNormX = fitResult2.first;
00381       treeMem.fitSigmaNormX = fitResult2.second;
00382     }
00383     
00384     //get median for absolute residuals
00385     treeMem.medianX = this->getMedian(it->second.ResXprimeHisto);
00386 
00387     int numberOfBins=it->second.ResXprimeHisto->GetNbinsX();
00388     treeMem.numberOfUnderflows = it->second.ResXprimeHisto->GetBinContent(0);
00389     treeMem.numberOfOverflows = it->second.ResXprimeHisto->GetBinContent(numberOfBins+1);
00390     treeMem.numberOfOutliers =  it->second.ResXprimeHisto->GetBinContent(0)+it->second.ResXprimeHisto->GetBinContent(numberOfBins+1);
00391     //mean and RMS values (extracted from histograms(normalized Xprime on module level)
00392     treeMem.meanNormX = it->second.NormResXprimeHisto->GetMean();
00393     treeMem.rmsNormX = it->second.NormResXprimeHisto->GetRMS();
00394 
00395     double stats[20];
00396     it->second.NormResXprimeHisto->GetStats(stats);
00397     // GF  treeMem.chi2PerDofX = stats[3]/(stats[0]-1);
00398     if (stats[0]) treeMem.chi2PerDofX = stats[3]/stats[0];
00399     
00400     //treeMem.sigmaNormX = Fwhm(it->second.NormResXprimeHisto)/2.355;
00401     treeMem.histNameX = it->second.ResXprimeHisto->GetName();
00402     treeMem.histNameNormX = it->second.NormResXprimeHisto->GetName();
00403     
00404 
00405     // fill tree variables in local coordinates if set in cfg of TrackerOfllineValidation
00406     if(it->second.ResHisto && it->second.NormResHisto){ // if(lCoorHistOn_) {
00407       treeMem.meanLocalX = it->second.ResHisto->GetMean();
00408       treeMem.rmsLocalX = it->second.ResHisto->GetRMS();
00409       treeMem.meanNormLocalX = it->second.NormResHisto->GetMean();
00410       treeMem.rmsNormLocalX = it->second.NormResHisto->GetRMS();
00411       treeMem.histNameLocalX = it->second.ResHisto->GetName();
00412       treeMem.histNameNormLocalX = it->second.NormResHisto->GetName();
00413     }
00414 
00415     // mean and RMS values in local y (extracted from histograms Yprime on module level)
00416     // might exist in pixel only
00417     if (it->second.ResYprimeHisto) { //(stripYResiduals_){
00418       TH1 *h = it->second.ResYprimeHisto;
00419       treeMem.meanY = h->GetMean();
00420       treeMem.rmsY  = h->GetRMS();
00421       
00422       if (useFit_) { // fit function which returns mean and sigma from the fit
00423         std::pair<float,float> fitMeanSigma = this->fitResiduals(h);
00424         treeMem.fitMeanY  = fitMeanSigma.first;
00425         treeMem.fitSigmaY = fitMeanSigma.second;
00426       }
00427       
00428       //get median for absolute residuals
00429       treeMem.medianY = this->getMedian(h);
00430 
00431       treeMem.histNameY = h->GetName();
00432     }
00433     
00434     if (it->second.NormResYprimeHisto) {
00435       TH1 *h = it->second.NormResYprimeHisto;
00436       treeMem.meanNormY = h->GetMean();
00437       treeMem.rmsNormY  = h->GetRMS();
00438       h->GetStats(stats); // stats buffer defined above
00439       if (stats[0]) treeMem.chi2PerDofY = stats[3]/stats[0];
00440 
00441       if (useFit_) { // fit function which returns mean and sigma from the fit
00442         std::pair<float,float> fitMeanSigma = this->fitResiduals(h);
00443         treeMem.fitMeanNormY  = fitMeanSigma.first;
00444         treeMem.fitSigmaNormY = fitMeanSigma.second;
00445       }
00446       treeMem.histNameNormY = h->GetName();
00447     }
00448     
00449     // Delete module level hists if set in cfg
00450     const bool removeModuleLevelHists(parSet_.getParameter<bool>("removeModuleLevelHists"));
00451     if(removeModuleLevelHists){
00452       dbe_->setCurrentFolder("");
00453       if(it->second.ResHisto)          dbe_->removeElement(histDir + "/" + it->second.ResHisto->GetName());
00454       if(it->second.NormResHisto)      dbe_->removeElement(histDir + "/" + it->second.NormResHisto->GetName());
00455       if(it->second.ResXprimeHisto)    dbe_->removeElement(histDir + "/" + it->second.ResXprimeHisto->GetName());
00456       if(it->second.NormResXprimeHisto)dbe_->removeElement(histDir + "/" + it->second.NormResXprimeHisto->GetName());
00457       if(it->second.ResYprimeHisto)    dbe_->removeElement(histDir + "/" + it->second.ResYprimeHisto->GetName());
00458       if(it->second.NormResYprimeHisto)dbe_->removeElement(histDir + "/" + it->second.NormResYprimeHisto->GetName());
00459     }
00460     
00461     tree.Fill();
00462   }
00463 }
00464 
00465 
00466 const std::string
00467 TrackerOfflineValidationSummary::associateModuleHistsWithTree(const TkOffTreeVariables& treeMem, TrackerOfflineValidationSummary::ModuleHistos& moduleHists, std::map<std::string,std::string>& substructureName){
00468    std::stringstream histDir, sSubdetName;
00469    std::string componentName;
00470    if(moduleDirectory_.length() != 0)histDir<<moduleDirectory_<<"/";
00471    std::string wheelOrLayer("_layer_");
00472    if(treeMem.subDetId == PixelSubdetector::PixelBarrel){
00473      unsigned int half(treeMem.half), layer(treeMem.layer), ladder(0);
00474      if(layer==1){
00475        if(half==2)ladder = treeMem.rod -5;
00476        else if(treeMem.rod>15)ladder = treeMem.rod -10;
00477        else ladder = treeMem.rod;
00478      }else if(layer==2){
00479        if(half==2)ladder = treeMem.rod -8;
00480        else if(treeMem.rod>24)ladder = treeMem.rod -16;
00481        else ladder = treeMem.rod;
00482      }else if(layer==3){
00483        if(half==2)ladder = treeMem.rod -11;
00484        else if(treeMem.rod>33)ladder = treeMem.rod -22;
00485        else ladder = treeMem.rod;
00486      }
00487      componentName = "Pixel";
00488      sSubdetName<<"TPBBarrel_1";
00489      histDir<<componentName<<"/"<<sSubdetName.str()<<"/TPBHalfBarrel_"<<treeMem.half<<"/TPBLayer_"<<treeMem.layer<<"/TPBLadder_"<<ladder;
00490    }else if(treeMem.subDetId == PixelSubdetector::PixelEndcap){
00491      unsigned int side(treeMem.side), half(treeMem.half), blade(0);
00492      if(side==1)side=3;
00493      if(half==2)blade = treeMem.blade -6;
00494      else if(treeMem.blade>18)blade = treeMem.blade -12;
00495      else blade = treeMem.blade;
00496      componentName = "Pixel";
00497      sSubdetName<<"TPEEndcap_"<<side;
00498      histDir<<componentName<<"/"<<sSubdetName.str()<<"/TPEHalfCylinder_"<<treeMem.half<<"/TPEHalfDisk_"<<treeMem.layer<<"/TPEBlade_"<<blade<<"/TPEPanel_"<<treeMem.panel;
00499      wheelOrLayer = "_wheel_";
00500    }else if(treeMem.subDetId == StripSubdetector::TIB){
00501      unsigned int half(treeMem.half), layer(treeMem.layer), surface(treeMem.outerInner), string(0);
00502      if(half==2){
00503        if(layer==1){
00504          if(surface==1)string = treeMem.rod -13;
00505          else if(surface==2)string = treeMem.rod -15;
00506        }
00507        if(layer==2){
00508          if(surface==1)string = treeMem.rod -17;
00509          else if(surface==2)string = treeMem.rod -19;
00510        }
00511        if(layer==3){
00512          if(surface==1)string = treeMem.rod -22;
00513          else if(surface==2)string = treeMem.rod -23;
00514        }
00515        if(layer==4){
00516          if(surface==1)string = treeMem.rod -26;
00517          else if(surface==2)string = treeMem.rod -28;
00518        }
00519      }
00520      else string = treeMem.rod;
00521      std::stringstream detString;
00522      if(treeMem.layer<3 && !treeMem.isDoubleSide)detString<<"/Det_"<<treeMem.module;
00523      else detString<<"";
00524      componentName = "Strip";
00525      sSubdetName<<"TIBBarrel_1";
00526      histDir<<componentName<<"/"<<sSubdetName.str()<<"/TIBHalfBarrel_"<<treeMem.side<<"/TIBLayer_"<<treeMem.layer<<"/TIBHalfShell_"<<treeMem.half<<"/TIBSurface_"<<treeMem.outerInner<<"/TIBString_"<<string<<detString.str();
00527    }else if(treeMem.subDetId == StripSubdetector::TID){
00528      unsigned int side(treeMem.side), outerInner(0);
00529      if(side==1)side=3;
00530      if(treeMem.outerInner==1)outerInner=2;
00531      else if(treeMem.outerInner==2)outerInner=1;
00532      std::stringstream detString;
00533      if(treeMem.ring<3 && !treeMem.isDoubleSide)detString<<"/Det_"<<treeMem.module;
00534      else detString<<"";
00535      componentName = "Strip";
00536      sSubdetName<<"TIDEndcap_"<<side;
00537      histDir<<componentName<<"/"<<sSubdetName.str()<<"/TIDDisk_"<<treeMem.layer<<"/TIDRing_"<<treeMem.ring<<"/TIDSide_"<<outerInner<<detString.str();
00538      wheelOrLayer = "_wheel_";
00539    }else if(treeMem.subDetId == StripSubdetector::TOB){
00540      std::stringstream detString;
00541      if(treeMem.layer<3 && !treeMem.isDoubleSide)detString<<"/Det_"<<treeMem.module;
00542      else detString<<"";
00543      componentName = "Strip";
00544      sSubdetName<<"TOBBarrel_4";
00545      histDir<<componentName<<"/"<<sSubdetName.str()<<"/TOBHalfBarrel_"<<treeMem.side<<"/TOBLayer_"<<treeMem.layer<<"/TOBRod_"<<treeMem.rod<<detString.str();
00546    }else if(treeMem.subDetId == StripSubdetector::TEC) {
00547      unsigned int side(0), outerInner(0), ring(0);
00548      if(treeMem.side==1)side=6;
00549      else if(treeMem.side==2)side=5;
00550      if(treeMem.outerInner==1)outerInner = 2;
00551      else if(treeMem.outerInner==2)outerInner=1;
00552      if(treeMem.layer>3 && treeMem.layer<7)ring = treeMem.ring -1;
00553      else if(treeMem.layer==7 || treeMem.layer==8)ring = treeMem.ring -2;
00554      else if(treeMem.layer==9)ring = treeMem.ring -3;
00555      else ring = treeMem.ring;
00556      std::stringstream detString;
00557      if((treeMem.ring<3 || treeMem.ring==5) && !treeMem.isDoubleSide)detString<<"/Det_"<<treeMem.module;
00558      else detString<<"";
00559      componentName = "Strip";
00560      sSubdetName<<"TECEndcap_"<<side;
00561      histDir<<componentName<<"/"<<sSubdetName.str()<<"/TECDisk_"<<treeMem.layer<<"/TECSide_"<<outerInner<<"/TECPetal_"<<treeMem.petal<<"/TECRing_"<<ring<<detString.str();
00562      wheelOrLayer = "_wheel_";
00563    }
00564    
00565    substructureName["component"] = componentName;
00566    substructureName["subdet"] = sSubdetName.str();
00567    
00568    std::stringstream histName;
00569    histName<<"residuals_subdet_"<<treeMem.subDetId<<wheelOrLayer<<treeMem.layer<<"_module_"<<treeMem.moduleId;
00570    
00571    std::string fullPath;
00572    fullPath = histDir.str()+"/h_xprime_"+histName.str();
00573    if(dbe_->get(fullPath)) moduleHists.ResXprimeHisto = dbe_->get(fullPath)->getTH1();
00574    else{edm::LogError("TrackerOfflineValidationSummary")<<"Problem with names in input file produced in TrackerOfflineValidation ...\n"
00575                                                         <<"This histogram should exist in every configuration, "
00576                                                         <<"but no histogram with name "<<fullPath<<" is found!";
00577      return "";
00578    }
00579    fullPath = histDir.str()+"/h_normxprime"+histName.str();
00580    if(dbe_->get(fullPath)) moduleHists.NormResXprimeHisto = dbe_->get(fullPath)->getTH1();
00581    fullPath = histDir.str()+"/h_yprime_"+histName.str();
00582    if(dbe_->get(fullPath)) moduleHists.ResYprimeHisto = dbe_->get(fullPath)->getTH1();
00583    fullPath = histDir.str()+"/h_normyprime"+histName.str();
00584    if(dbe_->get(fullPath)) moduleHists.NormResYprimeHisto = dbe_->get(fullPath)->getTH1();
00585    fullPath = histDir.str()+"/h_"+histName.str();
00586    if(dbe_->get(fullPath)) moduleHists.ResHisto = dbe_->get(fullPath)->getTH1();
00587    fullPath = histDir.str()+"/h_norm"+histName.str();
00588    if(dbe_->get(fullPath)) moduleHists.NormResHisto = dbe_->get(fullPath)->getTH1();
00589    
00590    return histDir.str();
00591 }
00592 
00593 
00594 std::pair<float,float> 
00595 TrackerOfflineValidationSummary::fitResiduals(TH1* hist) const
00596 {
00597   std::pair<float,float> fitResult(9999., 9999.);
00598   if (!hist || hist->GetEntries() < 20) return fitResult;
00599 
00600   float mean  = hist->GetMean();
00601   float sigma = hist->GetRMS();
00602 
00603   try { // for < CMSSW_2_2_0 since ROOT warnings from fit are converted to exceptions
00604     // Remove the try/catch for more recent CMSSW!
00605     // first fit: two RMS around mean
00606     TF1 func("tmp", "gaus", mean - 2.*sigma, mean + 2.*sigma); 
00607     if (0 == hist->Fit(&func,"QNR")) { // N: do not blow up file by storing fit!
00608       mean  = func.GetParameter(1);
00609       sigma = func.GetParameter(2);
00610       // second fit: three sigma of first fit around mean of first fit
00611       func.SetRange(mean - 3.*sigma, mean + 3.*sigma);
00612       // I: integral gives more correct results if binning is too wide
00613       // L: Likelihood can treat empty bins correctly (if hist not weighted...)
00614       if (0 == hist->Fit(&func, "Q0LR")) {
00615         if (hist->GetFunction(func.GetName())) { // Take care that it is later on drawn:
00616           hist->GetFunction(func.GetName())->ResetBit(TF1::kNotDraw);
00617         }
00618         fitResult.first = func.GetParameter(1);
00619         fitResult.second = func.GetParameter(2);
00620       }
00621     }
00622   } catch (cms::Exception const & e) {
00623     edm::LogWarning("Alignment") << "@SUB=TrackerOfflineValidation::fitResiduals"
00624                                  << "Caught this exception during ROOT fit: "
00625                                  << e.what();
00626   }
00627   return fitResult;
00628 }
00629 
00630 
00631 float 
00632 TrackerOfflineValidationSummary::getMedian(const TH1 *histo) const
00633 {
00634   float median = 999;
00635   const int nbins = histo->GetNbinsX();
00636  
00637   //extract median from histogram
00638   double *x = new double[nbins];
00639   double *y = new double[nbins];
00640   for (int j = 0; j < nbins; j++) {
00641     x[j] = histo->GetBinCenter(j+1);
00642     y[j] = histo->GetBinContent(j+1);
00643   }
00644   median = TMath::Median(nbins, x, y);
00645   
00646   delete[] x; x = 0;
00647   delete [] y; y = 0;  
00648 
00649   return median;
00650 }
00651 
00652 
00653 void
00654 TrackerOfflineValidationSummary::collateHarvestingHists(TTree& tree)
00655 {
00656   this->applyHarvestingHierarchy(tree);
00657   this->fillHarvestingHists(tree);
00658 }
00659 
00660 
00661 void
00662 TrackerOfflineValidationSummary::applyHarvestingHierarchy(TTree& tree)
00663 {
00664   TkOffTreeVariables *treeMemPtr = 0;
00665   std::map<std::string,std::string> *substructureName = 0;
00666   tree.SetBranchAddress("TkOffTreeVariables", &treeMemPtr);
00667   tree.SetBranchAddress("SubstructureName", &substructureName);
00668   
00669   // Loop over modules to select accumulation criteria for harvesting plots
00670   for(unsigned int iSubdet = 1; iSubdet<7; ++iSubdet){
00671     std::string hierarchyName("");
00672     std::string componentName("");
00673     std::vector<unsigned int> treeEntries;
00674     for(unsigned int iSide = 1; iSide<3; ++iSide){
00675       // Set up only one collection for Barrels, not separated for side
00676       if(iSide==1 && (iSubdet==PixelSubdetector::PixelBarrel || iSubdet==StripSubdetector::TIB || iSubdet==StripSubdetector::TOB))continue;
00677       for(int iTree=0; iTree<tree.GetEntries(); ++iTree){
00678         tree.GetEntry(iTree);
00679         // Do not use glued Dets
00680         if(treeMemPtr->isDoubleSide)continue;
00681         if(treeMemPtr->subDetId == iSubdet){
00682           if(iSide!=treeMemPtr->side && (iSubdet==PixelSubdetector::PixelEndcap || iSubdet==StripSubdetector::TID || iSubdet==StripSubdetector::TEC))continue;
00683           treeEntries.push_back(iTree);
00684           if(hierarchyName.length() == 0){
00685             hierarchyName = (*substructureName)["subdet"];
00686             componentName = (*substructureName)["component"];
00687           }
00688         }
00689       }
00690       HarvestingHierarchy harvestingHierarchy(hierarchyName,componentName,treeEntries);
00691       vHarvestingHierarchy_.push_back(harvestingHierarchy);
00692       hierarchyName = ""; componentName = ""; treeEntries.clear();
00693     }
00694   }
00695   // Here could be a further separation of the HarvestingHierarchy.
00696   // E.g. separate the existing ones by layer and add them to the vector without deleting any element from the vector.
00697   // The existing hists will stay and the new ones are added
00698   
00699   // Now, book the corresponding histos
00700   this->bookHarvestingHists();
00701 }
00702 
00703 
00704 void
00705 TrackerOfflineValidationSummary::bookHarvestingHists()
00706 {
00707   edm::LogInfo("TrackerOfflineValidationSummary")<<"Harvesting histograms will be booked for "<<vHarvestingHierarchy_.size()<<" different hierarchy selections";
00708   for(std::vector<HarvestingHierarchy>::iterator iHier = vHarvestingHierarchy_.begin(); iHier != vHarvestingHierarchy_.end(); ++iHier){
00709     
00710     std::stringstream dmrXprimeHistoName, dmrYprimeHistoName, dmrXprimeHistoTitle, dmrYprimeHistoTitle;
00711     dmrXprimeHistoName << "h_DmrXprime_" << iHier->hierarchyName;
00712     dmrYprimeHistoName << "h_DmrYprime_" << iHier->hierarchyName;
00713     dmrXprimeHistoTitle<<  "DMR for " << iHier->hierarchyName <<";<#DeltaX> [cm];# modules";
00714     dmrYprimeHistoTitle<<  "DMR for " << iHier->hierarchyName <<";<#DeltaY> [cm];# modules";
00715     
00716     std::string directoryString(moduleDirectory_);
00717     if(directoryString.length()!=0)directoryString += "/";
00718     directoryString += iHier->componentName;
00719     dbe_->setCurrentFolder(directoryString);
00720     
00721     int nBinsX(0); double xMin(0.), xMax(0.);
00722     if(iHier->componentName == "Pixel"){
00723       this->getBinning("TH1DmrXprimePixelModules",nBinsX,xMin,xMax);
00724       iHier->harvestingHistos.DmrXprime = dbe_->book1D(dmrXprimeHistoName.str(),dmrXprimeHistoTitle.str(),nBinsX,xMin,xMax)->getTH1();
00725       this->getBinning("TH1DmrYprimePixelModules",nBinsX,xMin,xMax);
00726       iHier->harvestingHistos.DmrYprime = dbe_->book1D(dmrYprimeHistoName.str(),dmrYprimeHistoTitle.str(),nBinsX,xMin,xMax)->getTH1();
00727     }
00728     else if(iHier->componentName == "Strip"){
00729       this->getBinning("TH1DmrXprimeStripModules",nBinsX,xMin,xMax);
00730       iHier->harvestingHistos.DmrXprime = dbe_->book1D(dmrXprimeHistoName.str(),dmrXprimeHistoTitle.str(),nBinsX,xMin,xMax)->getTH1();
00731       if(!parSet_.getParameter<bool>("stripYDmrs"))continue;
00732       this->getBinning("TH1DmrYprimeStripModules",nBinsX,xMin,xMax);
00733       iHier->harvestingHistos.DmrYprime = dbe_->book1D(dmrYprimeHistoName.str(),dmrYprimeHistoTitle.str(),nBinsX,xMin,xMax)->getTH1();
00734     }
00735   }
00736 }
00737 
00738 
00739 void
00740 TrackerOfflineValidationSummary::getBinning(const std::string& binningPSetName, int& nBinsX, double& lowerBoundX, double& upperBoundX)const
00741 {
00742   const edm::ParameterSet& binningPSet = parSet_.getParameter<edm::ParameterSet>(binningPSetName);
00743   nBinsX      = binningPSet.getParameter<int>("Nbinx");                
00744   lowerBoundX = binningPSet.getParameter<double>("xmin");                      
00745   upperBoundX = binningPSet.getParameter<double>("xmax");
00746 }
00747 
00748 
00749 void
00750 TrackerOfflineValidationSummary::fillHarvestingHists(TTree& tree)
00751 {
00752   TkOffTreeVariables *treeMemPtr = 0;
00753   std::map<std::string,std::string> *substructureName = 0;
00754   tree.SetBranchAddress("TkOffTreeVariables", &treeMemPtr);
00755   tree.SetBranchAddress("SubstructureName", &substructureName);
00756   
00757   const unsigned int minEntriesPerModule(parSet_.getParameter<unsigned int>("minEntriesPerModuleForDmr"));
00758   edm::LogInfo("TrackerOfflineValidationSummary")<<"Median of a module is added to DMR plots if it contains at least "<<minEntriesPerModule<<" hits";
00759   
00760   for(std::vector<HarvestingHierarchy>::iterator iHier = vHarvestingHierarchy_.begin(); iHier != vHarvestingHierarchy_.end(); ++iHier){
00761     for(std::vector<unsigned int>::const_iterator iTreeEntries = iHier->treeEntries.begin(); iTreeEntries != iHier->treeEntries.end(); ++iTreeEntries){
00762       tree.GetEntry(*iTreeEntries);
00763       if(treeMemPtr->entries < minEntriesPerModule)continue;
00764       iHier->harvestingHistos.DmrXprime->Fill(treeMemPtr->medianX);
00765       if(iHier->harvestingHistos.DmrYprime)iHier->harvestingHistos.DmrYprime->Fill(treeMemPtr->medianY);
00766     }
00767   }
00768 }
00769 
00770 
00771 //define this as a plug-in
00772 DEFINE_FWK_MODULE(TrackerOfflineValidationSummary);