CMS 3D CMS Logo

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