CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_6_1_2_SLHC4_patch1/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.7 2012/06/30 09:09:47 eulisse 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     }
00203   }
00204   moduleMapsInitialized = true;
00205 }
00206 
00207 
00208 // ------------ method called once each job just after ending the event loop  ------------
00209 void 
00210 TrackerOfflineValidationSummary::endJob()
00211 {
00212   AlignableTracker aliTracker(&(*tkGeom_));
00213   
00214   TTree* tree = new TTree("TkOffVal","TkOffVal");
00215   
00216   TkOffTreeVariables *treeMemPtr = new TkOffTreeVariables;
00217   // We create branches for all members of 'TkOffTreeVariables' (even if not needed).
00218   // This works because we have a dictionary for 'TkOffTreeVariables'
00219   // (see src/classes_def.xml and src/classes.h):
00220   tree->Branch("TkOffTreeVariables", &treeMemPtr); // address of pointer!
00221   // second branch needed for assigning names and titles to harvesting histograms consistent to others
00222   std::map<std::string,std::string> *substructureName = new std::map<std::string,std::string>;
00223   tree->Branch("SubstructureName", &substructureName, 32000, 00);  // SplitLevel must be set to zero
00224   
00225   
00226   this->fillTree(*tree, mPxbResiduals_, *treeMemPtr, *tkGeom_, *substructureName);
00227   this->fillTree(*tree, mPxeResiduals_, *treeMemPtr, *tkGeom_, *substructureName);
00228   this->fillTree(*tree, mTibResiduals_, *treeMemPtr, *tkGeom_, *substructureName);
00229   this->fillTree(*tree, mTidResiduals_, *treeMemPtr, *tkGeom_, *substructureName);
00230   this->fillTree(*tree, mTobResiduals_, *treeMemPtr, *tkGeom_, *substructureName);
00231   this->fillTree(*tree, mTecResiduals_, *treeMemPtr, *tkGeom_, *substructureName);
00232   
00233   //dbe_->showDirStructure();
00234   //dbe_->save("dqmOut.root");
00235   
00236   // Method for filling histograms which show summarized values (mean, rms, median ...)
00237   // of the module-based histograms from TrackerOfflineValidation
00238   this->collateHarvestingHists(*tree);
00239   
00240   delete tree; tree = 0;
00241   delete treeMemPtr; treeMemPtr = 0;
00242   delete substructureName; substructureName = 0;
00243 }
00244 
00245 
00246 void 
00247 TrackerOfflineValidationSummary::fillTree(TTree& tree,
00248                                    std::map<int, TrackerOfflineValidationSummary::ModuleHistos>& moduleHist,
00249                                    TkOffTreeVariables& treeMem, const TrackerGeometry& tkgeom, std::map<std::string,std::string>& substructureName)
00250 {
00251   for(std::map<int, TrackerOfflineValidationSummary::ModuleHistos>::iterator it = moduleHist.begin(), 
00252         itEnd= moduleHist.end(); it != itEnd;++it ) { 
00253     treeMem.clear(); // make empty/default
00254     
00255     //variables concerning the tracker components/hierarchy levels
00256     const DetId detId = it->first;
00257     treeMem.moduleId = detId;
00258     treeMem.subDetId = detId.subdetId();
00259 
00260     if(treeMem.subDetId == PixelSubdetector::PixelBarrel){
00261       PXBDetId pxbId(detId);
00262       unsigned int whichHalfBarrel(1), rawId(detId.rawId());  //DetId does not know about halfBarrels is PXB ...
00263       if( (rawId>=302056964 && rawId<302059300) || (rawId>=302123268 && rawId<302127140) || (rawId>=302189572 && rawId<302194980) )whichHalfBarrel=2;
00264       treeMem.layer = pxbId.layer();
00265       treeMem.half = whichHalfBarrel; 
00266       treeMem.rod = pxbId.ladder();     // ... so, ladder is not per halfBarrel-Layer, but per barrel-layer! Needs complicated calculation in associateModuleHistsWithTree()
00267       treeMem.module = pxbId.module();
00268     } else if(treeMem.subDetId == PixelSubdetector::PixelEndcap){
00269       PXFDetId pxfId(detId); 
00270       unsigned int whichHalfCylinder(1), rawId(detId.rawId());  //DetId does not kmow about halfCylinders in PXF
00271       if( (rawId>=352394500 && rawId<352406032) || (rawId>=352460036 && rawId<352471568) || (rawId>=344005892 && rawId<344017424) || (rawId>=344071428 && rawId<344082960) )whichHalfCylinder=2;
00272       treeMem.layer = pxfId.disk(); 
00273       treeMem.side = pxfId.side();
00274       treeMem.half = whichHalfCylinder;
00275       treeMem.blade = pxfId.blade(); 
00276       treeMem.panel = pxfId.panel();
00277       treeMem.module = pxfId.module();
00278     } else if(treeMem.subDetId == StripSubdetector::TIB){
00279       TIBDetId tibId(detId); 
00280       unsigned int whichHalfShell(1), rawId(detId.rawId());  //DetId does not kmow about halfShells in TIB
00281        if ( (rawId>=369120484 && rawId<369120688) || (rawId>=369121540 && rawId<369121776) || (rawId>=369136932 && rawId<369137200) || (rawId>=369137988 && rawId<369138288) ||
00282             (rawId>=369153396 && rawId<369153744) || (rawId>=369154436 && rawId<369154800) || (rawId>=369169844 && rawId<369170256) || (rawId>=369170900 && rawId<369171344) ||
00283             (rawId>=369124580 && rawId<369124784) || (rawId>=369125636 && rawId<369125872) || (rawId>=369141028 && rawId<369141296) || (rawId>=369142084 && rawId<369142384) ||
00284             (rawId>=369157492 && rawId<369157840) || (rawId>=369158532 && rawId<369158896) || (rawId>=369173940 && rawId<369174352) || (rawId>=369174996 && rawId<369175440) ) whichHalfShell=2;
00285       treeMem.layer = tibId.layer(); 
00286       treeMem.side = tibId.string()[0];
00287       treeMem.half = whichHalfShell;
00288       treeMem.rod = tibId.string()[2]; 
00289       treeMem.outerInner = tibId.string()[1]; 
00290       treeMem.module = tibId.module();
00291       treeMem.isStereo = tibId.stereo();
00292       treeMem.isDoubleSide = tibId.isDoubleSide();
00293     } else if(treeMem.subDetId == StripSubdetector::TID){
00294       TIDDetId tidId(detId); 
00295       treeMem.layer = tidId.wheel(); 
00296       treeMem.side = tidId.side();
00297       treeMem.ring = tidId.ring(); 
00298       treeMem.outerInner = tidId.module()[0]; 
00299       treeMem.module = tidId.module()[1];
00300       treeMem.isStereo = tidId.stereo();
00301       treeMem.isDoubleSide = tidId.isDoubleSide();
00302     } else if(treeMem.subDetId == StripSubdetector::TOB){
00303       TOBDetId tobId(detId); 
00304       treeMem.layer = tobId.layer(); 
00305       treeMem.side = tobId.rod()[0];
00306       treeMem.rod = tobId.rod()[1]; 
00307       treeMem.module = tobId.module();
00308       treeMem.isStereo = tobId.stereo();
00309       treeMem.isDoubleSide = tobId.isDoubleSide();
00310     } else if(treeMem.subDetId == StripSubdetector::TEC) {
00311       TECDetId tecId(detId); 
00312       treeMem.layer = tecId.wheel(); 
00313       treeMem.side  = tecId.side();
00314       treeMem.ring  = tecId.ring(); 
00315       treeMem.petal = tecId.petal()[1]; 
00316       treeMem.outerInner = tecId.petal()[0];
00317       treeMem.module = tecId.module();
00318       treeMem.isStereo = tecId.stereo();
00319       treeMem.isDoubleSide = tecId.isDoubleSide();
00320     }
00321     
00322     //variables concerning the tracker geometry
00323     
00324     const Surface::PositionType &gPModule = tkgeom.idToDet(detId)->position();
00325     treeMem.posPhi = gPModule.phi();
00326     treeMem.posEta = gPModule.eta();
00327     treeMem.posR   = gPModule.perp();
00328     treeMem.posX   = gPModule.x();
00329     treeMem.posY   = gPModule.y();
00330     treeMem.posZ   = gPModule.z();
00331  
00332     const Surface& surface =  tkgeom.idToDet(detId)->surface();
00333     
00334     //global Orientation of local coordinate system of dets/detUnits   
00335     LocalPoint  lUDirection(1.,0.,0.), lVDirection(0.,1.,0.), lWDirection(0.,0.,1.);
00336     GlobalPoint gUDirection = surface.toGlobal(lUDirection),
00337                 gVDirection = surface.toGlobal(lVDirection),
00338                 gWDirection = surface.toGlobal(lWDirection);
00339     double dR(999.), dPhi(999.), dZ(999.);
00340     if(treeMem.subDetId==PixelSubdetector::PixelBarrel || treeMem.subDetId==StripSubdetector::TIB || treeMem.subDetId==StripSubdetector::TOB){
00341       dR = gWDirection.perp() - gPModule.perp();
00342       dPhi = deltaPhi(gUDirection.phi(),gPModule.phi());
00343       dZ = gVDirection.z() - gPModule.z();
00344       if(dZ>=0.)treeMem.rOrZDirection = 1; else treeMem.rOrZDirection = -1;
00345     }else if(treeMem.subDetId==PixelSubdetector::PixelEndcap){
00346       dR = gUDirection.perp() - gPModule.perp();
00347       dPhi = deltaPhi(gVDirection.phi(),gPModule.phi());
00348       dZ = gWDirection.z() - gPModule.z();
00349       if(dR>=0.)treeMem.rOrZDirection = 1; else treeMem.rOrZDirection = -1;
00350     }else if(treeMem.subDetId==StripSubdetector::TID || treeMem.subDetId==StripSubdetector::TEC){
00351       dR = gVDirection.perp() - gPModule.perp();
00352       dPhi = deltaPhi(gUDirection.phi(),gPModule.phi());
00353       dZ = gWDirection.z() - gPModule.z();
00354       if(dR>=0.)treeMem.rOrZDirection = 1; else treeMem.rOrZDirection = -1;
00355     }
00356     if(dR>=0.)treeMem.rDirection = 1; else treeMem.rDirection = -1;
00357     if(dPhi>=0.)treeMem.phiDirection = 1; else treeMem.phiDirection = -1;
00358     if(dZ>=0.)treeMem.zDirection = 1; else treeMem.zDirection = -1;
00359     
00360     
00361     // Assign histos from first step (TrackerOfflineValidation) to the module's entry in the TTree for retrieving mean, rms, median ...
00362     const std::string histDir = associateModuleHistsWithTree(treeMem, it->second, substructureName);
00363     
00364     
00365     //mean and RMS values (extracted from histograms Xprime on module level)
00366     treeMem.entries = static_cast<UInt_t>(it->second.ResXprimeHisto->GetEntries());
00367     treeMem.meanX = it->second.ResXprimeHisto->GetMean();
00368     treeMem.rmsX  = it->second.ResXprimeHisto->GetRMS();
00369     //treeMem.sigmaX = Fwhm(it->second.ResXprimeHisto)/2.355;
00370     if (useFit_) {
00371       //call fit function which returns mean and sigma from the fit
00372       //for absolute residuals
00373       std::pair<float,float> fitResult1 = this->fitResiduals(it->second.ResXprimeHisto);
00374       treeMem.fitMeanX = fitResult1.first;
00375       treeMem.fitSigmaX = fitResult1.second;
00376       //for normalized residuals
00377       std::pair<float,float> fitResult2 = this->fitResiduals(it->second.NormResXprimeHisto);
00378       treeMem.fitMeanNormX = fitResult2.first;
00379       treeMem.fitSigmaNormX = fitResult2.second;
00380     }
00381     
00382     //get median for absolute residuals
00383     treeMem.medianX = this->getMedian(it->second.ResXprimeHisto);
00384 
00385     int numberOfBins=it->second.ResXprimeHisto->GetNbinsX();
00386     treeMem.numberOfUnderflows = it->second.ResXprimeHisto->GetBinContent(0);
00387     treeMem.numberOfOverflows = it->second.ResXprimeHisto->GetBinContent(numberOfBins+1);
00388     treeMem.numberOfOutliers =  it->second.ResXprimeHisto->GetBinContent(0)+it->second.ResXprimeHisto->GetBinContent(numberOfBins+1);
00389     //mean and RMS values (extracted from histograms(normalized Xprime on module level)
00390     treeMem.meanNormX = it->second.NormResXprimeHisto->GetMean();
00391     treeMem.rmsNormX = it->second.NormResXprimeHisto->GetRMS();
00392 
00393     double stats[20];
00394     it->second.NormResXprimeHisto->GetStats(stats);
00395     // GF  treeMem.chi2PerDofX = stats[3]/(stats[0]-1);
00396     if (stats[0]) treeMem.chi2PerDofX = stats[3]/stats[0];
00397     
00398     //treeMem.sigmaNormX = Fwhm(it->second.NormResXprimeHisto)/2.355;
00399     treeMem.histNameX = it->second.ResXprimeHisto->GetName();
00400     treeMem.histNameNormX = it->second.NormResXprimeHisto->GetName();
00401     
00402 
00403     // fill tree variables in local coordinates if set in cfg of TrackerOfllineValidation
00404     if(it->second.ResHisto && it->second.NormResHisto){ // if(lCoorHistOn_) {
00405       treeMem.meanLocalX = it->second.ResHisto->GetMean();
00406       treeMem.rmsLocalX = it->second.ResHisto->GetRMS();
00407       treeMem.meanNormLocalX = it->second.NormResHisto->GetMean();
00408       treeMem.rmsNormLocalX = it->second.NormResHisto->GetRMS();
00409       treeMem.histNameLocalX = it->second.ResHisto->GetName();
00410       treeMem.histNameNormLocalX = it->second.NormResHisto->GetName();
00411     }
00412 
00413     // mean and RMS values in local y (extracted from histograms Yprime on module level)
00414     // might exist in pixel only
00415     if (it->second.ResYprimeHisto) { //(stripYResiduals_){
00416       TH1 *h = it->second.ResYprimeHisto;
00417       treeMem.meanY = h->GetMean();
00418       treeMem.rmsY  = h->GetRMS();
00419       
00420       if (useFit_) { // fit function which returns mean and sigma from the fit
00421         std::pair<float,float> fitMeanSigma = this->fitResiduals(h);
00422         treeMem.fitMeanY  = fitMeanSigma.first;
00423         treeMem.fitSigmaY = fitMeanSigma.second;
00424       }
00425       
00426       //get median for absolute residuals
00427       treeMem.medianY = this->getMedian(h);
00428 
00429       treeMem.histNameY = h->GetName();
00430     }
00431     
00432     if (it->second.NormResYprimeHisto) {
00433       TH1 *h = it->second.NormResYprimeHisto;
00434       treeMem.meanNormY = h->GetMean();
00435       treeMem.rmsNormY  = h->GetRMS();
00436       h->GetStats(stats); // stats buffer defined above
00437       if (stats[0]) treeMem.chi2PerDofY = stats[3]/stats[0];
00438 
00439       if (useFit_) { // fit function which returns mean and sigma from the fit
00440         std::pair<float,float> fitMeanSigma = this->fitResiduals(h);
00441         treeMem.fitMeanNormY  = fitMeanSigma.first;
00442         treeMem.fitSigmaNormY = fitMeanSigma.second;
00443       }
00444       treeMem.histNameNormY = h->GetName();
00445     }
00446     
00447     // Delete module level hists if set in cfg
00448     const bool removeModuleLevelHists(parSet_.getParameter<bool>("removeModuleLevelHists"));
00449     if(removeModuleLevelHists){
00450       dbe_->setCurrentFolder("");
00451       if(it->second.ResHisto)          dbe_->removeElement(histDir + "/" + it->second.ResHisto->GetName());
00452       if(it->second.NormResHisto)      dbe_->removeElement(histDir + "/" + it->second.NormResHisto->GetName());
00453       if(it->second.ResXprimeHisto)    dbe_->removeElement(histDir + "/" + it->second.ResXprimeHisto->GetName());
00454       if(it->second.NormResXprimeHisto)dbe_->removeElement(histDir + "/" + it->second.NormResXprimeHisto->GetName());
00455       if(it->second.ResYprimeHisto)    dbe_->removeElement(histDir + "/" + it->second.ResYprimeHisto->GetName());
00456       if(it->second.NormResYprimeHisto)dbe_->removeElement(histDir + "/" + it->second.NormResYprimeHisto->GetName());
00457     }
00458     
00459     tree.Fill();
00460   }
00461 }
00462 
00463 
00464 const std::string
00465 TrackerOfflineValidationSummary::associateModuleHistsWithTree(const TkOffTreeVariables& treeMem, TrackerOfflineValidationSummary::ModuleHistos& moduleHists, std::map<std::string,std::string>& substructureName){
00466    std::stringstream histDir, sSubdetName;
00467    std::string componentName;
00468    if(moduleDirectory_.length() != 0)histDir<<moduleDirectory_<<"/";
00469    std::string wheelOrLayer("_layer_");
00470    if(treeMem.subDetId == PixelSubdetector::PixelBarrel){
00471      unsigned int half(treeMem.half), layer(treeMem.layer), ladder(0);
00472      if(layer==1){
00473        if(half==2)ladder = treeMem.rod -5;
00474        else if(treeMem.rod>15)ladder = treeMem.rod -10;
00475        else ladder = treeMem.rod;
00476      }else if(layer==2){
00477        if(half==2)ladder = treeMem.rod -8;
00478        else if(treeMem.rod>24)ladder = treeMem.rod -16;
00479        else ladder = treeMem.rod;
00480      }else if(layer==3){
00481        if(half==2)ladder = treeMem.rod -11;
00482        else if(treeMem.rod>33)ladder = treeMem.rod -22;
00483        else ladder = treeMem.rod;
00484      }
00485      componentName = "Pixel";
00486      sSubdetName<<"TPBBarrel_1";
00487      histDir<<componentName<<"/"<<sSubdetName.str()<<"/TPBHalfBarrel_"<<treeMem.half<<"/TPBLayer_"<<treeMem.layer<<"/TPBLadder_"<<ladder;
00488    }else if(treeMem.subDetId == PixelSubdetector::PixelEndcap){
00489      unsigned int side(treeMem.side), half(treeMem.half), blade(0);
00490      if(side==1)side=3;
00491      if(half==2)blade = treeMem.blade -6;
00492      else if(treeMem.blade>18)blade = treeMem.blade -12;
00493      else blade = treeMem.blade;
00494      componentName = "Pixel";
00495      sSubdetName<<"TPEEndcap_"<<side;
00496      histDir<<componentName<<"/"<<sSubdetName.str()<<"/TPEHalfCylinder_"<<treeMem.half<<"/TPEHalfDisk_"<<treeMem.layer<<"/TPEBlade_"<<blade<<"/TPEPanel_"<<treeMem.panel;
00497      wheelOrLayer = "_wheel_";
00498    }else if(treeMem.subDetId == StripSubdetector::TIB){
00499      unsigned int half(treeMem.half), layer(treeMem.layer), surface(treeMem.outerInner), string(0);
00500      if(half==2){
00501        if(layer==1){
00502          if(surface==1)string = treeMem.rod -13;
00503          else if(surface==2)string = treeMem.rod -15;
00504        }
00505        if(layer==2){
00506          if(surface==1)string = treeMem.rod -17;
00507          else if(surface==2)string = treeMem.rod -19;
00508        }
00509        if(layer==3){
00510          if(surface==1)string = treeMem.rod -22;
00511          else if(surface==2)string = treeMem.rod -23;
00512        }
00513        if(layer==4){
00514          if(surface==1)string = treeMem.rod -26;
00515          else if(surface==2)string = treeMem.rod -28;
00516        }
00517      }
00518      else string = treeMem.rod;
00519      std::stringstream detString;
00520      if(treeMem.layer<3 && !treeMem.isDoubleSide)detString<<"/Det_"<<treeMem.module;
00521      else detString<<"";
00522      componentName = "Strip";
00523      sSubdetName<<"TIBBarrel_1";
00524      histDir<<componentName<<"/"<<sSubdetName.str()<<"/TIBHalfBarrel_"<<treeMem.side<<"/TIBLayer_"<<treeMem.layer<<"/TIBHalfShell_"<<treeMem.half<<"/TIBSurface_"<<treeMem.outerInner<<"/TIBString_"<<string<<detString.str();
00525    }else if(treeMem.subDetId == StripSubdetector::TID){
00526      unsigned int side(treeMem.side), outerInner(0);
00527      if(side==1)side=3;
00528      if(treeMem.outerInner==1)outerInner=2;
00529      else if(treeMem.outerInner==2)outerInner=1;
00530      std::stringstream detString;
00531      if(treeMem.ring<3 && !treeMem.isDoubleSide)detString<<"/Det_"<<treeMem.module;
00532      else detString<<"";
00533      componentName = "Strip";
00534      sSubdetName<<"TIDEndcap_"<<side;
00535      histDir<<componentName<<"/"<<sSubdetName.str()<<"/TIDDisk_"<<treeMem.layer<<"/TIDRing_"<<treeMem.ring<<"/TIDSide_"<<outerInner<<detString.str();
00536      wheelOrLayer = "_wheel_";
00537    }else if(treeMem.subDetId == StripSubdetector::TOB){
00538      std::stringstream detString;
00539      if(treeMem.layer<3 && !treeMem.isDoubleSide)detString<<"/Det_"<<treeMem.module;
00540      else detString<<"";
00541      componentName = "Strip";
00542      sSubdetName<<"TOBBarrel_4";
00543      histDir<<componentName<<"/"<<sSubdetName.str()<<"/TOBHalfBarrel_"<<treeMem.side<<"/TOBLayer_"<<treeMem.layer<<"/TOBRod_"<<treeMem.rod<<detString.str();
00544    }else if(treeMem.subDetId == StripSubdetector::TEC) {
00545      unsigned int side(0), outerInner(0), ring(0);
00546      if(treeMem.side==1)side=6;
00547      else if(treeMem.side==2)side=5;
00548      if(treeMem.outerInner==1)outerInner = 2;
00549      else if(treeMem.outerInner==2)outerInner=1;
00550      if(treeMem.layer>3 && treeMem.layer<7)ring = treeMem.ring -1;
00551      else if(treeMem.layer==7 || treeMem.layer==8)ring = treeMem.ring -2;
00552      else if(treeMem.layer==9)ring = treeMem.ring -3;
00553      else ring = treeMem.ring;
00554      std::stringstream detString;
00555      if((treeMem.ring<3 || treeMem.ring==5) && !treeMem.isDoubleSide)detString<<"/Det_"<<treeMem.module;
00556      else detString<<"";
00557      componentName = "Strip";
00558      sSubdetName<<"TECEndcap_"<<side;
00559      histDir<<componentName<<"/"<<sSubdetName.str()<<"/TECDisk_"<<treeMem.layer<<"/TECSide_"<<outerInner<<"/TECPetal_"<<treeMem.petal<<"/TECRing_"<<ring<<detString.str();
00560      wheelOrLayer = "_wheel_";
00561    }
00562    
00563    substructureName["component"] = componentName;
00564    substructureName["subdet"] = sSubdetName.str();
00565    
00566    std::stringstream histName;
00567    histName<<"residuals_subdet_"<<treeMem.subDetId<<wheelOrLayer<<treeMem.layer<<"_module_"<<treeMem.moduleId;
00568    
00569    std::string fullPath;
00570    fullPath = histDir.str()+"/h_xprime_"+histName.str();
00571    if(dbe_->get(fullPath)) moduleHists.ResXprimeHisto = dbe_->get(fullPath)->getTH1();
00572    else{edm::LogError("TrackerOfflineValidationSummary")<<"Problem with names in input file produced in TrackerOfflineValidation ...\n"
00573                                                         <<"This histogram should exist in every configuration, "
00574                                                         <<"but no histogram with name "<<fullPath<<" is found!";
00575      return "";
00576    }
00577    fullPath = histDir.str()+"/h_normxprime"+histName.str();
00578    if(dbe_->get(fullPath)) moduleHists.NormResXprimeHisto = dbe_->get(fullPath)->getTH1();
00579    fullPath = histDir.str()+"/h_yprime_"+histName.str();
00580    if(dbe_->get(fullPath)) moduleHists.ResYprimeHisto = dbe_->get(fullPath)->getTH1();
00581    fullPath = histDir.str()+"/h_normyprime"+histName.str();
00582    if(dbe_->get(fullPath)) moduleHists.NormResYprimeHisto = dbe_->get(fullPath)->getTH1();
00583    fullPath = histDir.str()+"/h_"+histName.str();
00584    if(dbe_->get(fullPath)) moduleHists.ResHisto = dbe_->get(fullPath)->getTH1();
00585    fullPath = histDir.str()+"/h_norm"+histName.str();
00586    if(dbe_->get(fullPath)) moduleHists.NormResHisto = dbe_->get(fullPath)->getTH1();
00587    
00588    return histDir.str();
00589 }
00590 
00591 
00592 std::pair<float,float> 
00593 TrackerOfflineValidationSummary::fitResiduals(TH1* hist) const
00594 {
00595   std::pair<float,float> fitResult(9999., 9999.);
00596   if (!hist || hist->GetEntries() < 20) return fitResult;
00597 
00598   float mean  = hist->GetMean();
00599   float sigma = hist->GetRMS();
00600 
00601   try { // for < CMSSW_2_2_0 since ROOT warnings from fit are converted to exceptions
00602     // Remove the try/catch for more recent CMSSW!
00603     // first fit: two RMS around mean
00604     TF1 func("tmp", "gaus", mean - 2.*sigma, mean + 2.*sigma); 
00605     if (0 == hist->Fit(&func,"QNR")) { // N: do not blow up file by storing fit!
00606       mean  = func.GetParameter(1);
00607       sigma = func.GetParameter(2);
00608       // second fit: three sigma of first fit around mean of first fit
00609       func.SetRange(mean - 3.*sigma, mean + 3.*sigma);
00610       // I: integral gives more correct results if binning is too wide
00611       // L: Likelihood can treat empty bins correctly (if hist not weighted...)
00612       if (0 == hist->Fit(&func, "Q0LR")) {
00613         if (hist->GetFunction(func.GetName())) { // Take care that it is later on drawn:
00614           hist->GetFunction(func.GetName())->ResetBit(TF1::kNotDraw);
00615         }
00616         fitResult.first = func.GetParameter(1);
00617         fitResult.second = func.GetParameter(2);
00618       }
00619     }
00620   } catch (cms::Exception const & e) {
00621     edm::LogWarning("Alignment") << "@SUB=TrackerOfflineValidation::fitResiduals"
00622                                  << "Caught this exception during ROOT fit: "
00623                                  << e.what();
00624   }
00625   return fitResult;
00626 }
00627 
00628 
00629 float 
00630 TrackerOfflineValidationSummary::getMedian(const TH1 *histo) const
00631 {
00632   float median = 999;
00633   const int nbins = histo->GetNbinsX();
00634  
00635   //extract median from histogram
00636   double *x = new double[nbins];
00637   double *y = new double[nbins];
00638   for (int j = 0; j < nbins; j++) {
00639     x[j] = histo->GetBinCenter(j+1);
00640     y[j] = histo->GetBinContent(j+1);
00641   }
00642   median = TMath::Median(nbins, x, y);
00643   
00644   delete[] x; x = 0;
00645   delete [] y; y = 0;  
00646 
00647   return median;
00648 }
00649 
00650 
00651 void
00652 TrackerOfflineValidationSummary::collateHarvestingHists(TTree& tree)
00653 {
00654   this->applyHarvestingHierarchy(tree);
00655   this->fillHarvestingHists(tree);
00656 }
00657 
00658 
00659 void
00660 TrackerOfflineValidationSummary::applyHarvestingHierarchy(TTree& tree)
00661 {
00662   TkOffTreeVariables *treeMemPtr = 0;
00663   std::map<std::string,std::string> *substructureName = 0;
00664   tree.SetBranchAddress("TkOffTreeVariables", &treeMemPtr);
00665   tree.SetBranchAddress("SubstructureName", &substructureName);
00666   
00667   // Loop over modules to select accumulation criteria for harvesting plots
00668   for(unsigned int iSubdet = 1; iSubdet<7; ++iSubdet){
00669     std::string hierarchyName("");
00670     std::string componentName("");
00671     std::vector<unsigned int> treeEntries;
00672     for(unsigned int iSide = 1; iSide<3; ++iSide){
00673       // Set up only one collection for Barrels, not separated for side
00674       if(iSide==1 && (iSubdet==PixelSubdetector::PixelBarrel || iSubdet==StripSubdetector::TIB || iSubdet==StripSubdetector::TOB))continue;
00675       for(int iTree=0; iTree<tree.GetEntries(); ++iTree){
00676         tree.GetEntry(iTree);
00677         // Do not use glued Dets
00678         if(treeMemPtr->isDoubleSide)continue;
00679         if(treeMemPtr->subDetId == iSubdet){
00680           if(iSide!=treeMemPtr->side && (iSubdet==PixelSubdetector::PixelEndcap || iSubdet==StripSubdetector::TID || iSubdet==StripSubdetector::TEC))continue;
00681           treeEntries.push_back(iTree);
00682           if(hierarchyName.length() == 0){
00683             hierarchyName = (*substructureName)["subdet"];
00684             componentName = (*substructureName)["component"];
00685           }
00686         }
00687       }
00688       HarvestingHierarchy harvestingHierarchy(hierarchyName,componentName,treeEntries);
00689       vHarvestingHierarchy_.push_back(harvestingHierarchy);
00690       hierarchyName = ""; componentName = ""; treeEntries.clear();
00691     }
00692   }
00693   // Here could be a further separation of the HarvestingHierarchy.
00694   // E.g. separate the existing ones by layer and add them to the vector without deleting any element from the vector.
00695   // The existing hists will stay and the new ones are added
00696   
00697   // Now, book the corresponding histos
00698   this->bookHarvestingHists();
00699 }
00700 
00701 
00702 void
00703 TrackerOfflineValidationSummary::bookHarvestingHists()
00704 {
00705   edm::LogInfo("TrackerOfflineValidationSummary")<<"Harvesting histograms will be booked for "<<vHarvestingHierarchy_.size()<<" different hierarchy selections";
00706   for(std::vector<HarvestingHierarchy>::iterator iHier = vHarvestingHierarchy_.begin(); iHier != vHarvestingHierarchy_.end(); ++iHier){
00707     
00708     std::stringstream dmrXprimeHistoName, dmrYprimeHistoName, dmrXprimeHistoTitle, dmrYprimeHistoTitle;
00709     dmrXprimeHistoName << "h_DmrXprime_" << iHier->hierarchyName;
00710     dmrYprimeHistoName << "h_DmrYprime_" << iHier->hierarchyName;
00711     dmrXprimeHistoTitle<<  "DMR for " << iHier->hierarchyName <<";<#DeltaX> [cm];# modules";
00712     dmrYprimeHistoTitle<<  "DMR for " << iHier->hierarchyName <<";<#DeltaY> [cm];# modules";
00713     
00714     std::string directoryString(moduleDirectory_);
00715     if(directoryString.length()!=0)directoryString += "/";
00716     directoryString += iHier->componentName;
00717     dbe_->setCurrentFolder(directoryString);
00718     
00719     int nBinsX(0); double xMin(0.), xMax(0.);
00720     if(iHier->componentName == "Pixel"){
00721       this->getBinning("TH1DmrXprimePixelModules",nBinsX,xMin,xMax);
00722       iHier->harvestingHistos.DmrXprime = dbe_->book1D(dmrXprimeHistoName.str(),dmrXprimeHistoTitle.str(),nBinsX,xMin,xMax)->getTH1();
00723       this->getBinning("TH1DmrYprimePixelModules",nBinsX,xMin,xMax);
00724       iHier->harvestingHistos.DmrYprime = dbe_->book1D(dmrYprimeHistoName.str(),dmrYprimeHistoTitle.str(),nBinsX,xMin,xMax)->getTH1();
00725     }
00726     else if(iHier->componentName == "Strip"){
00727       this->getBinning("TH1DmrXprimeStripModules",nBinsX,xMin,xMax);
00728       iHier->harvestingHistos.DmrXprime = dbe_->book1D(dmrXprimeHistoName.str(),dmrXprimeHistoTitle.str(),nBinsX,xMin,xMax)->getTH1();
00729       if(!parSet_.getParameter<bool>("stripYDmrs"))continue;
00730       this->getBinning("TH1DmrYprimeStripModules",nBinsX,xMin,xMax);
00731       iHier->harvestingHistos.DmrYprime = dbe_->book1D(dmrYprimeHistoName.str(),dmrYprimeHistoTitle.str(),nBinsX,xMin,xMax)->getTH1();
00732     }
00733   }
00734 }
00735 
00736 
00737 void
00738 TrackerOfflineValidationSummary::getBinning(const std::string& binningPSetName, int& nBinsX, double& lowerBoundX, double& upperBoundX)const
00739 {
00740   const edm::ParameterSet& binningPSet = parSet_.getParameter<edm::ParameterSet>(binningPSetName);
00741   nBinsX      = binningPSet.getParameter<int>("Nbinx");                
00742   lowerBoundX = binningPSet.getParameter<double>("xmin");                      
00743   upperBoundX = binningPSet.getParameter<double>("xmax");
00744 }
00745 
00746 
00747 void
00748 TrackerOfflineValidationSummary::fillHarvestingHists(TTree& tree)
00749 {
00750   TkOffTreeVariables *treeMemPtr = 0;
00751   std::map<std::string,std::string> *substructureName = 0;
00752   tree.SetBranchAddress("TkOffTreeVariables", &treeMemPtr);
00753   tree.SetBranchAddress("SubstructureName", &substructureName);
00754   
00755   const unsigned int minEntriesPerModule(parSet_.getParameter<unsigned int>("minEntriesPerModuleForDmr"));
00756   edm::LogInfo("TrackerOfflineValidationSummary")<<"Median of a module is added to DMR plots if it contains at least "<<minEntriesPerModule<<" hits";
00757   
00758   for(std::vector<HarvestingHierarchy>::iterator iHier = vHarvestingHierarchy_.begin(); iHier != vHarvestingHierarchy_.end(); ++iHier){
00759     for(std::vector<unsigned int>::const_iterator iTreeEntries = iHier->treeEntries.begin(); iTreeEntries != iHier->treeEntries.end(); ++iTreeEntries){
00760       tree.GetEntry(*iTreeEntries);
00761       if(treeMemPtr->entries < minEntriesPerModule)continue;
00762       iHier->harvestingHistos.DmrXprime->Fill(treeMemPtr->medianX);
00763       if(iHier->harvestingHistos.DmrYprime)iHier->harvestingHistos.DmrYprime->Fill(treeMemPtr->medianY);
00764     }
00765   }
00766 }
00767 
00768 
00769 //define this as a plug-in
00770 DEFINE_FWK_MODULE(TrackerOfflineValidationSummary);