CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_4_1_8_patch13/src/RecoParticleFlow/PFRootEvent/src/PFRootEventManager.cc

Go to the documentation of this file.
00001 #include "DataFormats/Common/interface/OrphanHandle.h"
00002 #include "DataFormats/Provenance/interface/ProductID.h"
00003 #include "DataFormats/Common/interface/RefToPtr.h"
00004 
00005 #include "DataFormats/Math/interface/LorentzVector.h"
00006 #include "DataFormats/Math/interface/Point3D.h"
00007 
00008 #include "DataFormats/ParticleFlowReco/interface/PFLayer.h"
00009 
00010 #include "DataFormats/ParticleFlowReco/interface/PFBlock.h"
00011 #include "DataFormats/ParticleFlowReco/interface/PFBlockElement.h"
00012 
00013 #include "DataFormats/FWLite/interface/ChainEvent.h"
00014 
00015 #include "RecoParticleFlow/PFClusterProducer/interface/PFClusterAlgo.h"
00016 #include "RecoParticleFlow/PFProducer/interface/PFGeometry.h"
00017 
00018 #include "RecoParticleFlow/PFRootEvent/interface/PFRootEventManager.h"
00019 
00020 #include "RecoParticleFlow/PFRootEvent/interface/IO.h"
00021 
00022 #include "RecoParticleFlow/PFRootEvent/interface/PFJetAlgorithm.h" 
00023 #include "RecoParticleFlow/PFRootEvent/interface/JetMaker.h"
00024 
00025 #include "RecoParticleFlow/PFRootEvent/interface/Utils.h" 
00026 #include "RecoParticleFlow/PFRootEvent/interface/EventColin.h" 
00027 #include "RecoParticleFlow/PFRootEvent/interface/METManager.h"
00028 
00029 #include "RecoParticleFlow/PFClusterTools/interface/PFEnergyCalibration.h"
00030 #include "RecoParticleFlow/PFClusterTools/interface/PFSCEnergyCalibration.h"
00031 #include "RecoParticleFlow/PFClusterTools/interface/PFEnergyCalibrationHF.h"
00032 #include "RecoParticleFlow/PFClusterTools/interface/PFClusterCalibration.h"
00033 #include "RecoParticleFlow/PFClusterTools/interface/PFEnergyResolution.h"
00034 
00035 #include "FWCore/ServiceRegistry/interface/Service.h" 
00036 #include "DQMServices/Core/interface/DQMStore.h"
00037 #include "DQMServices/Core/interface/MonitorElement.h"
00038 
00039 #include "FWCore/FWLite/interface/AutoLibraryLoader.h"
00040 
00041 #include "TFile.h"
00042 #include "TTree.h"
00043 #include "TBranch.h"
00044 #include "TCutG.h"
00045 #include "TVector3.h"
00046 #include "TROOT.h"
00047 
00048 #include <iostream>
00049 #include <vector>
00050 #include <cstdlib>
00051 
00052 using namespace std;
00053 // using namespace boost;
00054 using namespace reco;
00055 
00056 using boost::shared_ptr;
00057 
00058 PFRootEventManager::PFRootEventManager() {}
00059 
00060 
00061 
00062 PFRootEventManager::PFRootEventManager(const char* file)
00063   : 
00064   iEvent_(0),
00065   options_(0),
00066   ev_(0),
00067   tree_(0),
00068   outTree_(0),
00069   outEvent_(0),
00070   //   clusters_(new reco::PFClusterCollection),
00071   eventAuxiliary_( new edm::EventAuxiliary ),
00072   clustersECAL_(new reco::PFClusterCollection),
00073   clustersHCAL_(new reco::PFClusterCollection),
00074   clustersHFEM_(new reco::PFClusterCollection),
00075   clustersHFHAD_(new reco::PFClusterCollection),
00076   clustersPS_(new reco::PFClusterCollection),
00077   pfBlocks_(new reco::PFBlockCollection),
00078   pfCandidates_(new reco::PFCandidateCollection),
00079   //pfJets_(new reco::PFJetCollection),
00080   outFile_(0),
00081   calibFile_(0)
00082 {
00083   
00084   
00085   //   iEvent_=0;
00086   h_deltaETvisible_MCEHT_ 
00087     = new TH1F("h_deltaETvisible_MCEHT","Jet Et difference CaloTowers-MC"
00088                ,1000,-50.,50.);
00089   h_deltaETvisible_MCPF_  
00090     = new TH1F("h_deltaETvisible_MCPF" ,"Jet Et difference ParticleFlow-MC"
00091                ,1000,-50.,50.);
00092 
00093   readOptions(file, true, true);
00094  
00095   initializeEventInformation();
00096        
00097   //   maxERecHitEcal_ = -1;
00098   //   maxERecHitHcal_ = -1;
00099 
00100 }
00101 
00102 
00103 void PFRootEventManager::initializeEventInformation() {
00104 
00105   unsigned int nev = ev_->size();
00106   for ( unsigned int entry = 0; entry < nev; ++entry ) { 
00107     ev_->to(entry);
00108     const edm::EventBase& iEv = *ev_;
00109     mapEventToEntry_[iEv.id().run()][iEv.id().luminosityBlock()][iEv.id().event()] = entry;
00110   }
00111 
00112   cout<<"Number of events: "<< nev
00113       <<" starting with event: "<<mapEventToEntry_.begin()->first<<endl;
00114 }
00115 
00116 
00117 void PFRootEventManager::reset() { 
00118 
00119   if(outEvent_) {
00120     outEvent_->reset();
00121     outTree_->GetBranch("event")->SetAddress(&outEvent_);
00122   }  
00123 
00124   if ( ev_ && ev_->isValid() ) 
00125     ev_->getTFile()->cd();
00126 }
00127 
00128 
00129 
00130 void PFRootEventManager::readOptions(const char* file, 
00131                                      bool refresh, 
00132                                      bool reconnect) {
00133                                      
00134   readSpecificOptions(file);
00135   
00136   cout<<"calling PFRootEventManager::readOptions"<<endl;
00137    
00138 
00139   reset();
00140   
00141   PFGeometry pfGeometry; // initialize geometry
00142   
00143   // cout<<"reading options "<<endl;
00144 
00145   try {
00146     if( !options_ )
00147       options_ = new IO(file);
00148     else if( refresh) {
00149       delete options_;
00150       options_ = new IO(file);
00151     }
00152   }
00153   catch( const string& err ) {
00154     cout<<err<<endl;
00155     return;
00156   }
00157 
00158 
00159   debug_ = false; 
00160   options_->GetOpt("rootevent", "debug", debug_);
00161 
00162   
00163   // output text file for calibration
00164   string calibfilename;
00165   options_->GetOpt("calib","outfile",calibfilename);
00166   if (!calibfilename.empty()) { 
00167     calibFile_ = new std::ofstream(calibfilename.c_str());
00168     std::cout << "Calib file name " << calibfilename << " " << calibfilename.c_str() << std::endl;
00169   }
00170 
00171   // output root file   ------------------------------------------
00172 
00173   
00174   if(!outFile_) {
00175     string outfilename;
00176     options_->GetOpt("root","outfile", outfilename);
00177     bool doOutTree = false;
00178     options_->GetOpt("root","outtree", doOutTree);
00179     if(doOutTree) {
00180       if(!outfilename.empty() ) {
00181         outFile_ = TFile::Open(outfilename.c_str(), "recreate");
00182         
00183         outFile_->cd();
00184         //options_->GetOpt("root","outtree", doOutTree);
00185         //if(doOutTree) {
00186         // cout<<"do tree"<<endl;
00187         outEvent_ = new EventColin();
00188         outTree_ = new TTree("Eff","");
00189         outTree_->Branch("event","EventColin", &outEvent_,32000,2);
00190       }
00191       // cout<<"don't do tree"<<endl;
00192     }
00193   }
00194   // PFJet benchmark options and output jetfile to be open before input file!!!--
00195 
00196   doPFJetBenchmark_ = false;
00197   options_->GetOpt("pfjet_benchmark", "on/off", doPFJetBenchmark_);
00198   
00199   if (doPFJetBenchmark_) {
00200     string outjetfilename;
00201     options_->GetOpt("pfjet_benchmark", "outjetfile", outjetfilename);
00202         
00203     bool pfjBenchmarkDebug;
00204     options_->GetOpt("pfjet_benchmark", "debug", pfjBenchmarkDebug);
00205     
00206     bool plotAgainstReco=0;
00207     options_->GetOpt("pfjet_benchmark", "plotAgainstReco", plotAgainstReco);
00208     
00209     bool onlyTwoJets=1;
00210     options_->GetOpt("pfjet_benchmark", "onlyTwoJets", onlyTwoJets);
00211     
00212     double deltaRMax=0.1;
00213     options_->GetOpt("pfjet_benchmark", "deltaRMax", deltaRMax);
00214 
00215     fastsim_=true;
00216     options_->GetOpt("Simulation","Fast",fastsim_);
00217  
00218     PFJetBenchmark_.setup( outjetfilename, 
00219                            pfjBenchmarkDebug,
00220                            plotAgainstReco,
00221                            onlyTwoJets,
00222                            deltaRMax );
00223   }
00224 
00225 // PFMET benchmark options and output jetfile to be open before input file!!!--
00226 
00227   doPFMETBenchmark_ = false;
00228   options_->GetOpt("pfmet_benchmark", "on/off", doPFMETBenchmark_);
00229   
00230   if (doPFMETBenchmark_) {
00231     //COLIN : looks like this benchmark is not written in the standard output file. Any particular reason for it? 
00232     
00233     doMet_ = false;
00234     options_->GetOpt("MET", "on/off", doMet_);
00235 
00236     JECinCaloMet_ = false;
00237     options_->GetOpt("pfmet_benchmark", "JECinCaloMET", JECinCaloMet_);
00238 
00239     std::string outmetfilename;
00240     options_->GetOpt("pfmet_benchmark", "outmetfile", outmetfilename);
00241 
00242     // define here the various benchmark comparison
00243     metManager_.reset( new METManager(outmetfilename) );
00244     metManager_->addGenBenchmark("PF");
00245     metManager_->addGenBenchmark("Calo");
00246     if ( doMet_ ) metManager_->addGenBenchmark("recompPF");
00247     if (JECinCaloMet_) metManager_->addGenBenchmark("corrCalo");
00248 
00249     bool pfmetBenchmarkDebug;
00250     options_->GetOpt("pfmet_benchmark", "debug", pfmetBenchmarkDebug);
00251         
00252     MET1cut = 10.0;
00253     options_->GetOpt("pfmet_benchmark", "truemetcut", MET1cut);
00254     
00255     DeltaMETcut = 30.0;
00256     options_->GetOpt("pfmet_benchmark", "deltametcut", DeltaMETcut);
00257     
00258     DeltaPhicut = 0.8;
00259     options_->GetOpt("pfmet_benchmark", "deltaphicut", DeltaPhicut);
00260     
00261 
00262     std::vector<unsigned int> vIgnoreParticlesIDs;
00263     options_->GetOpt("pfmet_benchmark", "trueMetIgnoreParticlesIDs", vIgnoreParticlesIDs);
00264     //std::cout << "FL: vIgnoreParticlesIDs.size() = " << vIgnoreParticlesIDs.size() << std::endl;
00265     //std::cout << "FL: first = " << vIgnoreParticlesIDs[0] << std::endl;
00266     metManager_->SetIgnoreParticlesIDs(&vIgnoreParticlesIDs);
00267 
00268     std::vector<unsigned int> trueMetSpecificIdCut;
00269     std::vector<double> trueMetSpecificEtaCut;
00270     options_->GetOpt("pfmet_benchmark", "trueMetSpecificIdCut", trueMetSpecificIdCut);
00271     options_->GetOpt("pfmet_benchmark", "trueMetSpecificEtaCut", trueMetSpecificEtaCut);
00272     if (trueMetSpecificIdCut.size()!=trueMetSpecificEtaCut.size()) std::cout << "Warning: PFRootEventManager: trueMetSpecificIdCut.size()!=trueMetSpecificEtaCut.size()" << std::endl;
00273     else metManager_->SetSpecificIdCut(&trueMetSpecificIdCut,&trueMetSpecificEtaCut);
00274 
00275   }
00276 
00277   doPFCandidateBenchmark_ = true;
00278   options_->GetOpt("pfCandidate_benchmark", "on/off", doPFCandidateBenchmark_); 
00279   if (doPFCandidateBenchmark_) {    
00280     cout<<"+++ Setting PFCandidate benchmark"<<endl;
00281     TDirectory* dir = outFile_->mkdir("DQMData");
00282     dir = dir->mkdir("PFTask");    
00283     dir = dir->mkdir("particleFlowManager");
00284     pfCandidateManager_.setDirectory( dir );
00285 
00286     float dRMax = 0.5; 
00287     options_->GetOpt("pfCandidate_benchmark", "dRMax", dRMax); 
00288     float ptMin = 2; 
00289     options_->GetOpt("pfCandidate_benchmark", "ptMin", ptMin); 
00290     bool matchCharge = true; 
00291     options_->GetOpt("pfCandidate_benchmark", "matchCharge", matchCharge); 
00292     int mode = static_cast<int>(Benchmark::DEFAULT);
00293     options_->GetOpt("pfCandidate_benchmark", "mode", mode); 
00294     
00295     pfCandidateManager_.setParameters( dRMax, matchCharge, 
00296                                        static_cast<Benchmark::Mode>(mode));
00297     pfCandidateManager_.setRange( ptMin, 10e5, -4.5, 4.5, -10, 10);
00298     pfCandidateManager_.setup();
00299     //COLIN need to set the subdirectory.  
00300     cout<<"+++ Done "<<endl;
00301   }
00302 
00303   std::string outputFile0;
00304   TFile* file0 = 0;
00305   TH2F* hBNeighbour0 = 0;
00306   TH2F* hENeighbour0 = 0;
00307   options_->GetOpt("clustering", "ECAL", outputFile0);
00308   if(!outputFile0.empty() ) {
00309     file0 = TFile::Open(outputFile0.c_str(),"recreate");
00310     hBNeighbour0 = new TH2F("BNeighbour0","f_{Neighbours} vs 1/E_{Seed} (ECAL Barrel)",500, 0., 0.5, 1000,0.,1.);
00311     hENeighbour0 = new TH2F("ENeighbour0","f_{Neighbours} vs 1/E_{Seed} (ECAL Endcap)",500, 0., 0.2, 1000,0.,1.);
00312   }
00313 
00314   std::string outputFile1;
00315   TFile* file1 = 0;
00316   TH2F* hBNeighbour1 = 0;
00317   TH2F* hENeighbour1 = 0;
00318   options_->GetOpt("clustering", "HCAL", outputFile1);
00319   if(!outputFile1.empty() ) {
00320     file1 = TFile::Open(outputFile1.c_str(),"recreate");
00321     hBNeighbour1 = new TH2F("BNeighbour1","f_{Neighbours} vs 1/E_{Seed} (HCAL Barrel)",500, 0., 0.05, 400,0.,1.);
00322     hENeighbour1 = new TH2F("ENeighbour1","f_{Neighbours} vs 1/E_{Seed} (HCAL Endcap)",500, 0., 0.05, 400,0.,1.);
00323   }
00324 
00325   std::string outputFile2;
00326   TFile* file2 = 0;
00327   TH2F* hBNeighbour2 = 0;
00328   TH2F* hENeighbour2 = 0;
00329   options_->GetOpt("clustering", "HFEM", outputFile2);
00330   if(!outputFile2.empty() ) {
00331     file2 = TFile::Open(outputFile2.c_str(),"recreate");
00332     hBNeighbour2 = new TH2F("BNeighbour2","f_{Neighbours} vs 1/E_{Seed} (HFEM Barrel)",500, 0., 0.02, 400,0.,1.);
00333     hENeighbour2 = new TH2F("ENeighbour2","f_{Neighbours} vs 1/E_{Seed} (HFEM Endcap)",500, 0., 0.02, 400,0.,1.);
00334   }
00335 
00336   std::string outputFile3;
00337   TFile* file3 = 0;
00338   TH2F* hBNeighbour3 = 0;
00339   TH2F* hENeighbour3 = 0;
00340   options_->GetOpt("clustering", "HFHAD", outputFile3);
00341   if(!outputFile3.empty() ) {
00342     file3 = TFile::Open(outputFile3.c_str(),"recreate");
00343     hBNeighbour3 = new TH2F("BNeighbour3","f_{Neighbours} vs 1/E_{Seed} (HFHAD Barrel)",500, 0., 0.02, 400,0.,1.);
00344     hENeighbour3 = new TH2F("ENeighbour3","f_{Neighbours} vs 1/E_{Seed} (HFHAD Endcap)",500, 0., 0.02, 400,0.,1.);
00345   }
00346 
00347   std::string outputFile4;
00348   TFile* file4 = 0;
00349   TH2F* hBNeighbour4 = 0;
00350   TH2F* hENeighbour4 = 0;
00351   options_->GetOpt("clustering", "Preshower", outputFile4);
00352   if(!outputFile4.empty() ) {
00353     file4 = TFile::Open(outputFile4.c_str(),"recreate");
00354     hBNeighbour4 = new TH2F("BNeighbour4","f_{Neighbours} vs 1/E_{Seed} (Preshower Barrel)",200, 0., 1000., 400,0.,1.);
00355     hENeighbour4 = new TH2F("ENeighbour4","f_{Neighbours} vs 1/E_{Seed} (Preshower Endcap)",200, 0., 1000., 400,0.,1.);
00356   }
00357 
00358   // input root file --------------------------------------------
00359 
00360   if( reconnect )
00361     connect(); 
00362 
00363   // filter --------------------------------------------------------------
00364 
00365   filterNParticles_ = 0;
00366   options_->GetOpt("filter", "nparticles", filterNParticles_);
00367   
00368   filterHadronicTaus_ = true;
00369   options_->GetOpt("filter", "hadronic_taus", filterHadronicTaus_);
00370   
00371   filterTaus_.clear();
00372   options_->GetOpt("filter", "taus", filterTaus_);
00373   if( !filterTaus_.empty() &&
00374       filterTaus_.size() != 2 ) {
00375     cerr<<"PFRootEventManager::ReadOptions, bad filter/taus option."<<endl
00376         <<"please use : "<<endl
00377         <<"\tfilter taus n_charged n_neutral"<<endl;
00378     filterTaus_.clear();
00379   }
00380   
00381   
00382   // clustering parameters -----------------------------------------------
00383 
00384   doClustering_ = true;
00385   //options_->GetOpt("clustering", "on/off", doClustering_);
00386   
00387   bool clusteringDebug = false;
00388   options_->GetOpt("clustering", "debug", clusteringDebug );
00389 
00390   findRecHitNeighbours_ = true;
00391   options_->GetOpt("clustering", "findRecHitNeighbours", 
00392                    findRecHitNeighbours_);
00393   
00394   double threshEcalBarrel = 0.1;
00395   options_->GetOpt("clustering", "thresh_Ecal_Barrel", threshEcalBarrel);
00396   
00397   double threshPtEcalBarrel = 0.0;
00398   options_->GetOpt("clustering", "thresh_Pt_Ecal_Barrel", threshPtEcalBarrel);
00399   
00400   double threshSeedEcalBarrel = 0.3;
00401   options_->GetOpt("clustering", "thresh_Seed_Ecal_Barrel", 
00402                    threshSeedEcalBarrel);
00403 
00404   double threshPtSeedEcalBarrel = 0.0;
00405   options_->GetOpt("clustering", "thresh_Pt_Seed_Ecal_Barrel", 
00406                    threshPtSeedEcalBarrel);
00407 
00408   double threshCleanEcalBarrel = 1E5;
00409   options_->GetOpt("clustering", "thresh_Clean_Ecal_Barrel", 
00410                    threshCleanEcalBarrel);
00411 
00412   std::vector<double> minS4S1CleanEcalBarrel;
00413   options_->GetOpt("clustering", "minS4S1_Clean_Ecal_Barrel", 
00414                    minS4S1CleanEcalBarrel);
00415 
00416   double threshDoubleSpikeEcalBarrel = 10.;
00417   options_->GetOpt("clustering", "thresh_DoubleSpike_Ecal_Barrel", 
00418                    threshDoubleSpikeEcalBarrel);
00419 
00420   double minS6S2DoubleSpikeEcalBarrel = 0.04;
00421   options_->GetOpt("clustering", "minS6S2_DoubleSpike_Ecal_Barrel", 
00422                    minS6S2DoubleSpikeEcalBarrel);
00423 
00424   double threshEcalEndcap = 0.2;
00425   options_->GetOpt("clustering", "thresh_Ecal_Endcap", threshEcalEndcap);
00426 
00427   double threshPtEcalEndcap = 0.0;
00428   options_->GetOpt("clustering", "thresh_Pt_Ecal_Endcap", threshPtEcalEndcap);
00429 
00430   double threshSeedEcalEndcap = 0.8;
00431   options_->GetOpt("clustering", "thresh_Seed_Ecal_Endcap",
00432                    threshSeedEcalEndcap);
00433 
00434   double threshPtSeedEcalEndcap = 0.0;
00435   options_->GetOpt("clustering", "thresh_Pt_Seed_Ecal_Endcap",
00436                    threshPtSeedEcalEndcap);
00437 
00438   double threshCleanEcalEndcap = 1E5;
00439   options_->GetOpt("clustering", "thresh_Clean_Ecal_Endcap", 
00440                    threshCleanEcalEndcap);
00441 
00442   std::vector<double> minS4S1CleanEcalEndcap;
00443   options_->GetOpt("clustering", "minS4S1_Clean_Ecal_Endcap", 
00444                    minS4S1CleanEcalEndcap);
00445 
00446   double threshDoubleSpikeEcalEndcap = 1E9;
00447   options_->GetOpt("clustering", "thresh_DoubleSpike_Ecal_Endcap", 
00448                    threshDoubleSpikeEcalEndcap);
00449 
00450   double minS6S2DoubleSpikeEcalEndcap = -1.;
00451   options_->GetOpt("clustering", "minS6S2_DoubleSpike_Ecal_Endcap", 
00452                    minS6S2DoubleSpikeEcalEndcap);
00453 
00454   double showerSigmaEcal = 3;  
00455   options_->GetOpt("clustering", "shower_Sigma_Ecal",
00456                    showerSigmaEcal);
00457 
00458   int nNeighboursEcal = 4;
00459   options_->GetOpt("clustering", "neighbours_Ecal", nNeighboursEcal);
00460   
00461   int posCalcNCrystalEcal = -1;
00462   options_->GetOpt("clustering", "posCalc_nCrystal_Ecal", 
00463                    posCalcNCrystalEcal);
00464 
00465   double posCalcP1Ecal 
00466     = threshEcalBarrel<threshEcalEndcap ? threshEcalBarrel:threshEcalEndcap;
00467 //   options_->GetOpt("clustering", "posCalc_p1_Ecal", 
00468 //                    posCalcP1Ecal);
00469   
00470   bool useCornerCellsEcal = false;
00471   options_->GetOpt("clustering", "useCornerCells_Ecal",
00472                    useCornerCellsEcal);
00473 
00474   clusterAlgoECAL_.setHistos(file0,hBNeighbour0,hENeighbour0);
00475 
00476   clusterAlgoECAL_.setThreshBarrel( threshEcalBarrel );
00477   clusterAlgoECAL_.setThreshSeedBarrel( threshSeedEcalBarrel );
00478   
00479   clusterAlgoECAL_.setThreshPtBarrel( threshPtEcalBarrel );
00480   clusterAlgoECAL_.setThreshPtSeedBarrel( threshPtSeedEcalBarrel );
00481   
00482   clusterAlgoECAL_.setThreshCleanBarrel(threshCleanEcalBarrel);
00483   clusterAlgoECAL_.setS4S1CleanBarrel(minS4S1CleanEcalBarrel);
00484 
00485   clusterAlgoECAL_.setThreshDoubleSpikeBarrel( threshDoubleSpikeEcalBarrel );
00486   clusterAlgoECAL_.setS6S2DoubleSpikeBarrel( minS6S2DoubleSpikeEcalBarrel );
00487 
00488   clusterAlgoECAL_.setThreshEndcap( threshEcalEndcap );
00489   clusterAlgoECAL_.setThreshSeedEndcap( threshSeedEcalEndcap );
00490 
00491   clusterAlgoECAL_.setThreshPtEndcap( threshPtEcalEndcap );
00492   clusterAlgoECAL_.setThreshPtSeedEndcap( threshPtSeedEcalEndcap );
00493 
00494   clusterAlgoECAL_.setThreshCleanEndcap(threshCleanEcalEndcap);
00495   clusterAlgoECAL_.setS4S1CleanEndcap(minS4S1CleanEcalEndcap);
00496 
00497   clusterAlgoECAL_.setThreshDoubleSpikeEndcap( threshDoubleSpikeEcalEndcap );
00498   clusterAlgoECAL_.setS6S2DoubleSpikeEndcap( minS6S2DoubleSpikeEcalEndcap );
00499 
00500   clusterAlgoECAL_.setNNeighbours( nNeighboursEcal );
00501   clusterAlgoECAL_.setShowerSigma( showerSigmaEcal );
00502 
00503   clusterAlgoECAL_.setPosCalcNCrystal( posCalcNCrystalEcal );
00504   clusterAlgoECAL_.setPosCalcP1( posCalcP1Ecal );
00505 
00506   clusterAlgoECAL_.setUseCornerCells( useCornerCellsEcal );
00507 
00508   clusterAlgoECAL_.enableDebugging( clusteringDebug ); 
00509 
00510   int dcormode = 0;
00511   options_->GetOpt("clustering", "depthCor_Mode", dcormode);
00512   
00513   double dcora = -1;
00514   options_->GetOpt("clustering", "depthCor_A", dcora);
00515   double dcorb = -1;
00516   options_->GetOpt("clustering", "depthCor_B", dcorb);
00517   double dcorap = -1;
00518   options_->GetOpt("clustering", "depthCor_A_preshower", dcorap);
00519   double dcorbp = -1;
00520   options_->GetOpt("clustering", "depthCor_B_preshower", dcorbp);
00521 
00522   //   if( dcormode > 0 && 
00523   //       dcora > -0.5 && 
00524   //       dcorb > -0.5 && 
00525   //       dcorap > -0.5 && 
00526   //       dcorbp > -0.5 ) {
00527 
00528   //     cout<<"set depth correction "
00529   //    <<dcormode<<" "<<dcora<<" "<<dcorb<<" "<<dcorap<<" "<<dcorbp<<endl;
00530   reco::PFCluster::setDepthCorParameters( dcormode, 
00531                                           dcora, dcorb, 
00532                                           dcorap, dcorbp);
00533   //   }
00534   //   else {
00535   //     reco::PFCluster::setDepthCorParameters( -1, 
00536   //                                        0,0 , 
00537   //                                        0,0 );
00538   //   }
00539 
00540   
00541 
00542   double threshHcalBarrel = 0.8;
00543   options_->GetOpt("clustering", "thresh_Hcal_Barrel", threshHcalBarrel);
00544   
00545   double threshPtHcalBarrel = 0.0;
00546   options_->GetOpt("clustering", "thresh_Pt_Hcal_Barrel", threshPtHcalBarrel);
00547   
00548   double threshSeedHcalBarrel = 1.4;
00549   options_->GetOpt("clustering", "thresh_Seed_Hcal_Barrel", 
00550                    threshSeedHcalBarrel);
00551 
00552   double threshPtSeedHcalBarrel = 0.0;
00553   options_->GetOpt("clustering", "thresh_Pt_Seed_Hcal_Barrel", 
00554                    threshPtSeedHcalBarrel);
00555 
00556   double threshCleanHcalBarrel = 1E5;
00557   options_->GetOpt("clustering", "thresh_Clean_Hcal_Barrel", 
00558                    threshCleanHcalBarrel);
00559 
00560   std::vector<double> minS4S1CleanHcalBarrel;
00561   options_->GetOpt("clustering", "minS4S1_Clean_Hcal_Barrel", 
00562                    minS4S1CleanHcalBarrel);
00563 
00564   double threshHcalEndcap = 0.8;
00565   options_->GetOpt("clustering", "thresh_Hcal_Endcap", threshHcalEndcap);
00566 
00567   double threshPtHcalEndcap = 0.0;
00568   options_->GetOpt("clustering", "thresh_Pt_Hcal_Endcap", threshPtHcalEndcap);
00569 
00570   double threshSeedHcalEndcap = 1.4;
00571   options_->GetOpt("clustering", "thresh_Seed_Hcal_Endcap",
00572                    threshSeedHcalEndcap);
00573 
00574   double threshPtSeedHcalEndcap = 0.0;
00575   options_->GetOpt("clustering", "thresh_Pt_Seed_Hcal_Endcap",
00576                    threshPtSeedHcalEndcap);
00577 
00578   double threshCleanHcalEndcap = 1E5;
00579   options_->GetOpt("clustering", "thresh_Clean_Hcal_Endcap", 
00580                    threshCleanHcalEndcap);
00581 
00582   std::vector<double> minS4S1CleanHcalEndcap;
00583   options_->GetOpt("clustering", "minS4S1_Clean_Hcal_Endcap", 
00584                    minS4S1CleanHcalEndcap);
00585 
00586   double showerSigmaHcal    = 15;
00587   options_->GetOpt("clustering", "shower_Sigma_Hcal",
00588                    showerSigmaHcal);
00589  
00590   int nNeighboursHcal = 4;
00591   options_->GetOpt("clustering", "neighbours_Hcal", nNeighboursHcal);
00592 
00593   int posCalcNCrystalHcal = 5;
00594   options_->GetOpt("clustering", "posCalc_nCrystal_Hcal",
00595                    posCalcNCrystalHcal);
00596 
00597   bool useCornerCellsHcal = false;
00598   options_->GetOpt("clustering", "useCornerCells_Hcal",
00599                    useCornerCellsHcal);
00600 
00601   bool cleanRBXandHPDs = false;
00602   options_->GetOpt("clustering", "cleanRBXandHPDs_Hcal",
00603                    cleanRBXandHPDs);
00604 
00605   double posCalcP1Hcal 
00606     = threshHcalBarrel<threshHcalEndcap ? threshHcalBarrel:threshHcalEndcap;
00607 //   options_->GetOpt("clustering", "posCalc_p1_Hcal", 
00608 //                    posCalcP1Hcal);
00609 
00610 
00611   clusterAlgoHCAL_.setHistos(file1,hBNeighbour1,hENeighbour1);
00612 
00613 
00614   clusterAlgoHCAL_.setThreshBarrel( threshHcalBarrel );
00615   clusterAlgoHCAL_.setThreshSeedBarrel( threshSeedHcalBarrel );
00616   
00617   clusterAlgoHCAL_.setThreshPtBarrel( threshPtHcalBarrel );
00618   clusterAlgoHCAL_.setThreshPtSeedBarrel( threshPtSeedHcalBarrel );
00619   
00620   clusterAlgoHCAL_.setThreshCleanBarrel(threshCleanHcalBarrel);
00621   clusterAlgoHCAL_.setS4S1CleanBarrel(minS4S1CleanHcalBarrel);
00622 
00623   clusterAlgoHCAL_.setThreshEndcap( threshHcalEndcap );
00624   clusterAlgoHCAL_.setThreshSeedEndcap( threshSeedHcalEndcap );
00625 
00626   clusterAlgoHCAL_.setThreshPtEndcap( threshPtHcalEndcap );
00627   clusterAlgoHCAL_.setThreshPtSeedEndcap( threshPtSeedHcalEndcap );
00628 
00629   clusterAlgoHCAL_.setThreshCleanEndcap(threshCleanHcalEndcap);
00630   clusterAlgoHCAL_.setS4S1CleanEndcap(minS4S1CleanHcalEndcap);
00631 
00632   clusterAlgoHCAL_.setNNeighbours( nNeighboursHcal );
00633   clusterAlgoHCAL_.setShowerSigma( showerSigmaHcal );
00634 
00635   clusterAlgoHCAL_.setPosCalcNCrystal( posCalcNCrystalHcal );
00636   clusterAlgoHCAL_.setPosCalcP1( posCalcP1Hcal );
00637 
00638   clusterAlgoHCAL_.setUseCornerCells( useCornerCellsHcal );
00639   clusterAlgoHCAL_.setCleanRBXandHPDs( cleanRBXandHPDs );
00640 
00641   clusterAlgoHCAL_.enableDebugging( clusteringDebug ); 
00642 
00643 
00644   // clustering HF EM 
00645 
00646   double threshHFEM = 0.;
00647   options_->GetOpt("clustering", "thresh_HFEM", threshHFEM);
00648   
00649   double threshPtHFEM = 0.;
00650   options_->GetOpt("clustering", "thresh_Pt_HFEM", threshPtHFEM);
00651   
00652   double threshSeedHFEM = 0.001;
00653   options_->GetOpt("clustering", "thresh_Seed_HFEM", 
00654                    threshSeedHFEM);
00655   
00656   double threshPtSeedHFEM = 0.0;
00657   options_->GetOpt("clustering", "thresh_Pt_Seed_HFEM", 
00658                    threshPtSeedHFEM);
00659   
00660   double threshCleanHFEM = 1E5;
00661   options_->GetOpt("clustering", "thresh_Clean_HFEM", 
00662                    threshCleanHFEM);
00663 
00664   std::vector<double> minS4S1CleanHFEM;
00665   options_->GetOpt("clustering", "minS4S1_Clean_HFEM", 
00666                    minS4S1CleanHFEM);
00667 
00668   double showerSigmaHFEM    = 0.1;
00669   options_->GetOpt("clustering", "shower_Sigma_HFEM",
00670                    showerSigmaHFEM);
00671  
00672   int nNeighboursHFEM = 4;
00673   options_->GetOpt("clustering", "neighbours_HFEM", nNeighboursHFEM);
00674 
00675   int posCalcNCrystalHFEM = -1;
00676   options_->GetOpt("clustering", "posCalc_nCrystal_HFEM",
00677                    posCalcNCrystalHFEM);
00678 
00679   bool useCornerCellsHFEM = false;
00680   options_->GetOpt("clustering", "useCornerCells_HFEM",
00681                    useCornerCellsHFEM);
00682 
00683   double posCalcP1HFEM = threshHFEM;
00684 //   options_->GetOpt("clustering", "posCalc_p1_HFEM", 
00685 //                    posCalcP1HFEM);
00686 
00687 
00688   clusterAlgoHFEM_.setHistos(file2,hBNeighbour2,hENeighbour2);
00689 
00690   clusterAlgoHFEM_.setThreshEndcap( threshHFEM );
00691   clusterAlgoHFEM_.setThreshSeedEndcap( threshSeedHFEM );
00692 
00693   clusterAlgoHFEM_.setThreshPtEndcap( threshPtHFEM );
00694   clusterAlgoHFEM_.setThreshPtSeedEndcap( threshPtSeedHFEM );
00695 
00696   clusterAlgoHFEM_.setThreshCleanEndcap(threshCleanHFEM);
00697   clusterAlgoHFEM_.setS4S1CleanEndcap(minS4S1CleanHFEM);
00698 
00699   clusterAlgoHFEM_.setNNeighbours( nNeighboursHFEM );
00700   clusterAlgoHFEM_.setShowerSigma( showerSigmaHFEM );
00701 
00702   clusterAlgoHFEM_.setPosCalcNCrystal( posCalcNCrystalHFEM );
00703   clusterAlgoHFEM_.setPosCalcP1( posCalcP1HFEM );
00704 
00705   clusterAlgoHFEM_.setUseCornerCells( useCornerCellsHFEM );
00706 
00707   clusterAlgoHFEM_.enableDebugging( clusteringDebug ); 
00708 
00709   // clustering HFHAD 
00710 
00711   double threshHFHAD = 0.;
00712   options_->GetOpt("clustering", "thresh_HFHAD", threshHFHAD);
00713   
00714   double threshPtHFHAD = 0.;
00715   options_->GetOpt("clustering", "thresh_Pt_HFHAD", threshPtHFHAD);
00716   
00717   double threshSeedHFHAD = 0.001;
00718   options_->GetOpt("clustering", "thresh_Seed_HFHAD", 
00719                    threshSeedHFHAD);
00720   
00721   double threshPtSeedHFHAD = 0.0;
00722   options_->GetOpt("clustering", "thresh_Pt_Seed_HFHAD", 
00723                    threshPtSeedHFHAD);
00724   
00725   double threshCleanHFHAD = 1E5;
00726   options_->GetOpt("clustering", "thresh_Clean_HFHAD", 
00727                    threshCleanHFHAD);
00728 
00729   std::vector<double> minS4S1CleanHFHAD;
00730   options_->GetOpt("clustering", "minS4S1_Clean_HFHAD", 
00731                    minS4S1CleanHFHAD);
00732 
00733   double showerSigmaHFHAD    = 0.1;
00734   options_->GetOpt("clustering", "shower_Sigma_HFHAD",
00735                    showerSigmaHFHAD);
00736  
00737   int nNeighboursHFHAD = 4;
00738   options_->GetOpt("clustering", "neighbours_HFHAD", nNeighboursHFHAD);
00739 
00740   int posCalcNCrystalHFHAD = -1;
00741   options_->GetOpt("clustering", "posCalc_nCrystal_HFHAD",
00742                    posCalcNCrystalHFHAD);
00743 
00744   bool useCornerCellsHFHAD = false;
00745   options_->GetOpt("clustering", "useCornerCells_HFHAD",
00746                    useCornerCellsHFHAD);
00747 
00748   double posCalcP1HFHAD = threshHFHAD;
00749 //   options_->GetOpt("clustering", "posCalc_p1_HFHAD", 
00750 //                    posCalcP1HFHAD);
00751 
00752 
00753   clusterAlgoHFHAD_.setHistos(file3,hBNeighbour3,hENeighbour3);
00754 
00755   clusterAlgoHFHAD_.setThreshEndcap( threshHFHAD );
00756   clusterAlgoHFHAD_.setThreshSeedEndcap( threshSeedHFHAD );
00757 
00758   clusterAlgoHFHAD_.setThreshPtEndcap( threshPtHFHAD );
00759   clusterAlgoHFHAD_.setThreshPtSeedEndcap( threshPtSeedHFHAD );
00760 
00761   clusterAlgoHFHAD_.setThreshCleanEndcap(threshCleanHFHAD);
00762   clusterAlgoHFHAD_.setS4S1CleanEndcap(minS4S1CleanHFHAD);
00763 
00764   clusterAlgoHFHAD_.setNNeighbours( nNeighboursHFHAD );
00765   clusterAlgoHFHAD_.setShowerSigma( showerSigmaHFHAD );
00766 
00767   clusterAlgoHFHAD_.setPosCalcNCrystal( posCalcNCrystalHFHAD );
00768   clusterAlgoHFHAD_.setPosCalcP1( posCalcP1HFHAD );
00769 
00770   clusterAlgoHFHAD_.setUseCornerCells( useCornerCellsHFHAD );
00771 
00772   clusterAlgoHFHAD_.enableDebugging( clusteringDebug ); 
00773 
00774   // clustering preshower
00775 
00776   double threshPS = 0.0001;
00777   options_->GetOpt("clustering", "thresh_PS", threshPS);
00778   
00779   double threshPtPS = 0.0;
00780   options_->GetOpt("clustering", "thresh_Pt_PS", threshPtPS);
00781   
00782   double threshSeedPS = 0.001;
00783   options_->GetOpt("clustering", "thresh_Seed_PS", 
00784                    threshSeedPS);
00785   
00786   double threshPtSeedPS = 0.0;
00787   options_->GetOpt("clustering", "thresh_Pt_Seed_PS", threshPtSeedPS);
00788   
00789   double threshCleanPS = 1E5;
00790   options_->GetOpt("clustering", "thresh_Clean_PS", threshCleanPS);
00791 
00792   std::vector<double> minS4S1CleanPS;
00793   options_->GetOpt("clustering", "minS4S1_Clean_PS", minS4S1CleanPS);
00794 
00795   //Comment Michel: PSBarrel shall be removed?
00796   double threshPSBarrel     = threshPS;
00797   double threshSeedPSBarrel = threshSeedPS;
00798 
00799   double threshPtPSBarrel     = threshPtPS;
00800   double threshPtSeedPSBarrel = threshPtSeedPS;
00801 
00802   double threshCleanPSBarrel = threshCleanPS;
00803   std::vector<double> minS4S1CleanPSBarrel = minS4S1CleanPS;
00804 
00805   double threshPSEndcap     = threshPS;
00806   double threshSeedPSEndcap = threshSeedPS;
00807 
00808   double threshPtPSEndcap     = threshPtPS;
00809   double threshPtSeedPSEndcap = threshPtSeedPS;
00810 
00811   double threshCleanPSEndcap = threshCleanPS;
00812   std::vector<double> minS4S1CleanPSEndcap = minS4S1CleanPS;
00813 
00814   double showerSigmaPS    = 0.1;
00815   options_->GetOpt("clustering", "shower_Sigma_PS",
00816                    showerSigmaPS);
00817  
00818   int nNeighboursPS = 4;
00819   options_->GetOpt("clustering", "neighbours_PS", nNeighboursPS);
00820 
00821   int posCalcNCrystalPS = -1;
00822   options_->GetOpt("clustering", "posCalc_nCrystal_PS",
00823                    posCalcNCrystalPS);
00824 
00825   bool useCornerCellsPS = false;
00826   options_->GetOpt("clustering", "useCornerCells_PS",
00827                    useCornerCellsPS);
00828 
00829   double posCalcP1PS = threshPS;
00830 //   options_->GetOpt("clustering", "posCalc_p1_PS", 
00831 //                    posCalcP1PS);
00832 
00833 
00834   clusterAlgoPS_.setHistos(file4,hBNeighbour4,hENeighbour4);
00835 
00836 
00837 
00838   clusterAlgoPS_.setThreshBarrel( threshPSBarrel );
00839   clusterAlgoPS_.setThreshSeedBarrel( threshSeedPSBarrel );
00840   
00841   clusterAlgoPS_.setThreshPtBarrel( threshPtPSBarrel );
00842   clusterAlgoPS_.setThreshPtSeedBarrel( threshPtSeedPSBarrel );
00843   
00844   clusterAlgoPS_.setThreshCleanBarrel(threshCleanPSBarrel);
00845   clusterAlgoPS_.setS4S1CleanBarrel(minS4S1CleanPSBarrel);
00846 
00847   clusterAlgoPS_.setThreshEndcap( threshPSEndcap );
00848   clusterAlgoPS_.setThreshSeedEndcap( threshSeedPSEndcap );
00849 
00850   clusterAlgoPS_.setThreshPtEndcap( threshPtPSEndcap );
00851   clusterAlgoPS_.setThreshPtSeedEndcap( threshPtSeedPSEndcap );
00852 
00853   clusterAlgoPS_.setThreshCleanEndcap(threshCleanPSEndcap);
00854   clusterAlgoPS_.setS4S1CleanEndcap(minS4S1CleanPSEndcap);
00855 
00856   clusterAlgoPS_.setNNeighbours( nNeighboursPS );
00857   clusterAlgoPS_.setShowerSigma( showerSigmaPS );
00858 
00859   clusterAlgoPS_.setPosCalcNCrystal( posCalcNCrystalPS );
00860   clusterAlgoPS_.setPosCalcP1( posCalcP1PS );
00861 
00862   clusterAlgoPS_.setUseCornerCells( useCornerCellsPS );
00863 
00864   clusterAlgoPS_.enableDebugging( clusteringDebug ); 
00865 
00866   // options for particle flow ---------------------------------------------
00867 
00868 
00869   doParticleFlow_ = true;
00870   doCompare_ = false;
00871   options_->GetOpt("particle_flow", "on/off", doParticleFlow_);  
00872   options_->GetOpt("particle_flow", "comparison", doCompare_);  
00873 
00874   std::vector<double> DPtovPtCut;
00875   std::vector<unsigned> NHitCut;
00876   bool useIterTracking;
00877   int nuclearInteractionsPurity;
00878   options_->GetOpt("particle_flow", "DPtoverPt_Cut", DPtovPtCut);
00879   options_->GetOpt("particle_flow", "NHit_Cut", NHitCut);
00880   options_->GetOpt("particle_flow", "useIterTracking", useIterTracking);
00881   options_->GetOpt("particle_flow", "nuclearInteractionsPurity", nuclearInteractionsPurity);
00882 
00883 
00884   try {
00885     pfBlockAlgo_.setParameters( DPtovPtCut, 
00886                                 NHitCut,
00887                                 useIterTracking,
00888                                 useConvBremPFRecTracks_,
00889                                 nuclearInteractionsPurity); 
00890   }  
00891   catch( std::exception& err ) {
00892     cerr<<"exception setting PFBlockAlgo parameters: "
00893         <<err.what()<<". terminating."<<endl;
00894     delete this;
00895     exit(1);
00896   }
00897   
00898 
00899   bool blockAlgoDebug = false;
00900   options_->GetOpt("blockAlgo", "debug",  blockAlgoDebug);  
00901   pfBlockAlgo_.setDebug( blockAlgoDebug );
00902 
00903   bool AlgoDebug = false;
00904   options_->GetOpt("PFAlgo", "debug",  AlgoDebug);  
00905   pfAlgo_.setDebug( AlgoDebug );
00906 
00907   // read PFCluster calibration parameters
00908   
00909 
00910   double e_slope = 1.0;
00911   options_->GetOpt("particle_flow","calib_ECAL_slope", e_slope);
00912   double e_offset = 0;
00913   options_->GetOpt("particle_flow","calib_ECAL_offset", e_offset);
00914   
00915   double eh_eslope = 1.05;
00916   options_->GetOpt("particle_flow","calib_ECAL_HCAL_eslope", eh_eslope);
00917   double eh_hslope = 1.06;
00918   options_->GetOpt("particle_flow","calib_ECAL_HCAL_hslope", eh_hslope);
00919   double eh_offset = 6.11;
00920   options_->GetOpt("particle_flow","calib_ECAL_HCAL_offset", eh_offset);
00921   
00922   double h_slope = 2.17;
00923   options_->GetOpt("particle_flow","calib_HCAL_slope", h_slope);
00924   double h_offset = 1.73;
00925   options_->GetOpt("particle_flow","calib_HCAL_offset", h_offset);
00926   double h_damping = 2.49;
00927   options_->GetOpt("particle_flow","calib_HCAL_damping", h_damping);
00928   
00929 
00930   unsigned newCalib = 0;
00931   options_->GetOpt("particle_flow", "newCalib", newCalib);  
00932   std::cout << "New calib = " << newCalib << std::endl;
00933 
00934   boost::shared_ptr<pftools::PFClusterCalibration> 
00935     clusterCalibration( new pftools::PFClusterCalibration() );
00936   clusterCalibration_ = clusterCalibration;
00937 
00938   boost::shared_ptr<PFEnergyCalibration> 
00939     calibration( new PFEnergyCalibration( e_slope,
00940                                           e_offset, 
00941                                           eh_eslope,
00942                                           eh_hslope,
00943                                           eh_offset,
00944                                           h_slope,
00945                                           h_offset,
00946                                           h_damping,
00947                                           newCalib) );
00948   calibration_ = calibration;
00949 
00950   bool usePFSCEleCalib;
00951   std::vector<double>  calibPFSCEle_barrel;
00952   std::vector<double>  calibPFSCEle_endcap;
00953   options_->GetOpt("particle_flow","usePFSCEleCalib",usePFSCEleCalib);
00954   options_->GetOpt("particle_flow","calibPFSCEle_barrel",calibPFSCEle_barrel);
00955   options_->GetOpt("particle_flow","calibPFSCEle_endcap",calibPFSCEle_endcap);
00956   boost::shared_ptr<PFSCEnergyCalibration>  
00957     thePFSCEnergyCalibration ( new PFSCEnergyCalibration(calibPFSCEle_barrel,calibPFSCEle_endcap ));
00958   
00959   bool useEGammaSupercluster;
00960   double sumEtEcalIsoForEgammaSC_barrel;
00961   double sumEtEcalIsoForEgammaSC_endcap;
00962   double coneEcalIsoForEgammaSC;
00963   double sumPtTrackIsoForEgammaSC_barrel;
00964   double sumPtTrackIsoForEgammaSC_endcap;
00965   unsigned int nTrackIsoForEgammaSC;
00966   double coneTrackIsoForEgammaSC;
00967   bool useEGammaElectrons;
00968   options_->GetOpt("particle_flow","useEGammaSupercluster",useEGammaSupercluster);
00969   options_->GetOpt("particle_flow","sumEtEcalIsoForEgammaSC_barrel",sumEtEcalIsoForEgammaSC_barrel);
00970   options_->GetOpt("particle_flow","sumEtEcalIsoForEgammaSC_endcap",sumEtEcalIsoForEgammaSC_endcap);
00971   options_->GetOpt("particle_flow","coneEcalIsoForEgammaSC",coneEcalIsoForEgammaSC);
00972   options_->GetOpt("particle_flow","sumPtTrackIsoForEgammaSC_barrel",sumPtTrackIsoForEgammaSC_barrel);
00973   options_->GetOpt("particle_flow","sumPtTrackIsoForEgammaSC_endcap",sumPtTrackIsoForEgammaSC_endcap);
00974   options_->GetOpt("particle_flow","nTrackIsoForEgammaSC",nTrackIsoForEgammaSC);
00975   options_->GetOpt("particle_flow","coneTrackIsoForEgammaSC",coneTrackIsoForEgammaSC);
00976   options_->GetOpt("particle_flow","useEGammaElectrons",useEGammaElectrons);
00977 
00978   //--ab: get calibration factors for HF:
00979   bool calibHF_use = false;
00980   std::vector<double>  calibHF_eta_step;
00981   std::vector<double>  calibHF_a_EMonly;
00982   std::vector<double>  calibHF_b_HADonly;
00983   std::vector<double>  calibHF_a_EMHAD;
00984   std::vector<double>  calibHF_b_EMHAD;
00985 
00986   options_->GetOpt("particle_flow","calib_calibHF_use",calibHF_use);
00987   options_->GetOpt("particle_flow","calib_calibHF_eta_step",calibHF_eta_step);
00988   options_->GetOpt("particle_flow","calib_calibHF_a_EMonly",calibHF_a_EMonly);
00989   options_->GetOpt("particle_flow","calib_calibHF_b_HADonly",calibHF_b_HADonly);
00990   options_->GetOpt("particle_flow","calib_calibHF_a_EMHAD",calibHF_a_EMHAD);
00991   options_->GetOpt("particle_flow","calib_calibHF_b_EMHAD",calibHF_b_EMHAD);
00992 
00993   boost::shared_ptr<PFEnergyCalibrationHF>  thepfEnergyCalibrationHF
00994     ( new PFEnergyCalibrationHF(calibHF_use,calibHF_eta_step,calibHF_a_EMonly,calibHF_b_HADonly,calibHF_a_EMHAD,calibHF_b_EMHAD) ) ;
00995 
00996   thepfEnergyCalibrationHF_ = thepfEnergyCalibrationHF;
00997 
00998 
00999   //----------------------------------------
01000   double nSigmaECAL = 99999;
01001   options_->GetOpt("particle_flow", "nsigma_ECAL", nSigmaECAL);
01002   double nSigmaHCAL = 99999;
01003   options_->GetOpt("particle_flow", "nsigma_HCAL", nSigmaHCAL);
01004 
01005   // pfAlgo_.setNewCalibration(newCalib);
01006 
01007   // Set the parameters for the brand-new calibration
01008   double g0, g1, e0, e1;
01009   options_->GetOpt("correction", "globalP0", g0);
01010   options_->GetOpt("correction", "globalP1", g1);
01011   options_->GetOpt("correction", "lowEP0", e0);
01012   options_->GetOpt("correction", "lowEP1", e1);
01013   clusterCalibration->setCorrections(e0, e1, g0, g1);
01014   
01015   int allowNegative(0);
01016   options_->GetOpt("correction", "allowNegativeEnergy", allowNegative);
01017   clusterCalibration->setAllowNegativeEnergy(allowNegative);
01018   
01019   int doCorrection(1);
01020   options_->GetOpt("correction", "doCorrection", doCorrection);
01021   clusterCalibration->setDoCorrection(doCorrection);
01022 
01023   int doEtaCorrection(1);
01024   options_->GetOpt("correction", "doEtaCorrection", doEtaCorrection);
01025   clusterCalibration->setDoEtaCorrection(doEtaCorrection);
01026   
01027   double barrelEta;
01028   options_->GetOpt("evolution", "barrelEndcapEtaDiv", barrelEta);
01029   clusterCalibration->setBarrelBoundary(barrelEta);
01030   
01031   double ecalEcut;
01032   options_->GetOpt("evolution", "ecalECut", ecalEcut);
01033   double hcalEcut;
01034   options_->GetOpt("evolution", "hcalECut", hcalEcut);
01035   clusterCalibration->setEcalHcalEnergyCuts(ecalEcut,hcalEcut);
01036 
01037   std::vector<std::string>* names = clusterCalibration->getKnownSectorNames();
01038   for(std::vector<std::string>::iterator i = names->begin(); i != names->end(); ++i) {
01039     std::string sector = *i;
01040     std::vector<double> params;
01041     options_->GetOpt("evolution", sector.c_str(), params);
01042     clusterCalibration->setEvolutionParameters(sector, params);
01043   }
01044 
01045   std::vector<double> etaCorrectionParams; 
01046   options_->GetOpt("evolution","etaCorrection", etaCorrectionParams);
01047   clusterCalibration->setEtaCorrectionParameters(etaCorrectionParams);
01048 
01049   try {
01050     pfAlgo_.setParameters( nSigmaECAL, nSigmaHCAL, 
01051                            calibration,
01052                            clusterCalibration,thepfEnergyCalibrationHF_, newCalib);
01053   }
01054   catch( std::exception& err ) {
01055     cerr<<"exception setting PFAlgo parameters: "
01056         <<err.what()<<". terminating."<<endl;
01057     delete this;
01058     exit(1);
01059   }
01060 
01061   std::vector<double> muonHCAL;
01062   std::vector<double> muonECAL;
01063   options_->GetOpt("particle_flow", "muon_HCAL", muonHCAL);
01064   options_->GetOpt("particle_flow", "muon_ECAL", muonECAL);
01065   assert ( muonHCAL.size() == 2 && muonECAL.size() == 2 );
01066 
01067   double nSigmaTRACK = 3.0;
01068   options_->GetOpt("particle_flow", "nsigma_TRACK", nSigmaTRACK);
01069 
01070   double ptError = 1.0;
01071   options_->GetOpt("particle_flow", "pt_error", ptError);
01072   
01073   std::vector<double> factors45;
01074   options_->GetOpt("particle_flow", "factors_45", factors45);
01075   assert ( factors45.size() == 2 );
01076   
01077   bool usePFMuonMomAssign = false;
01078   options_->GetOpt("particle_flow", "usePFMuonMomAssign", usePFMuonMomAssign);
01079  
01080   try { 
01081     pfAlgo_.setPFMuonAndFakeParameters(muonHCAL,
01082                                        muonECAL,
01083                                        nSigmaTRACK,
01084                                        ptError,
01085                                        factors45,
01086                                        usePFMuonMomAssign);
01087   }
01088   catch( std::exception& err ) {
01089     cerr<<"exception setting PFAlgo Muon and Fake parameters: "
01090         <<err.what()<<". terminating."<<endl;
01091     delete this;
01092     exit(1);
01093   }
01094   
01095   bool postHFCleaning = true;
01096   options_->GetOpt("particle_flow", "postHFCleaning", postHFCleaning);
01097   double minHFCleaningPt = 5.;
01098   options_->GetOpt("particle_flow", "minHFCleaningPt", minHFCleaningPt);
01099   double minSignificance = 2.5;
01100   options_->GetOpt("particle_flow", "minSignificance", minSignificance);
01101   double maxSignificance = 2.5;
01102   options_->GetOpt("particle_flow", "maxSignificance", maxSignificance);
01103   double minSignificanceReduction = 1.4;
01104   options_->GetOpt("particle_flow", "minSignificanceReduction", minSignificanceReduction);
01105   double maxDeltaPhiPt = 7.0;
01106   options_->GetOpt("particle_flow", "maxDeltaPhiPt", maxDeltaPhiPt);
01107   double minDeltaMet = 0.4;
01108   options_->GetOpt("particle_flow", "minDeltaMet", minDeltaMet);
01109 
01110   // Set post HF cleaning muon parameters
01111   try { 
01112     pfAlgo_.setPostHFCleaningParameters(postHFCleaning,
01113                                         minHFCleaningPt,
01114                                         minSignificance,
01115                                         maxSignificance,
01116                                         minSignificanceReduction,
01117                                         maxDeltaPhiPt,
01118                                         minDeltaMet);
01119   }
01120   catch( std::exception& err ) {
01121     cerr<<"exception setting post HF cleaning parameters: "
01122         <<err.what()<<". terminating."<<endl;
01123     delete this;
01124     exit(1);
01125   }
01126   
01127   useAtHLT = false;
01128   options_->GetOpt("particle_flow", "useAtHLT", useAtHLT);
01129   cout<<"use HLT tracking "<<useAtHLT<<endl;
01130 
01131 
01132   bool usePFElectrons = false;   // set true to use PFElectrons
01133   options_->GetOpt("particle_flow", "usePFElectrons", usePFElectrons);
01134   cout<<"use PFElectrons "<<usePFElectrons<<endl;
01135 
01136   if( usePFElectrons ) { 
01137     // PFElectrons options -----------------------------
01138     double mvaEleCut = -1.;  // if = -1. get all the pre-id electrons
01139     options_->GetOpt("particle_flow", "electron_mvaCut", mvaEleCut);
01140 
01141     bool applyCrackCorrections=true;
01142     options_->GetOpt("particle_flow","electron_crackCorrection",applyCrackCorrections);
01143 
01144     string mvaWeightFileEleID = "";
01145     options_->GetOpt("particle_flow", "electronID_mvaWeightFile", 
01146                      mvaWeightFileEleID);
01147     mvaWeightFileEleID = expand(mvaWeightFileEleID);
01148     
01149     try { 
01150       pfAlgo_.setPFEleParameters(mvaEleCut,
01151                                  mvaWeightFileEleID,
01152                                  usePFElectrons,
01153                                  thePFSCEnergyCalibration,
01154                                  sumEtEcalIsoForEgammaSC_barrel,
01155                                  sumEtEcalIsoForEgammaSC_endcap,
01156                                  coneEcalIsoForEgammaSC,
01157                                  sumPtTrackIsoForEgammaSC_barrel,
01158                                  sumPtTrackIsoForEgammaSC_endcap,
01159                                  nTrackIsoForEgammaSC,
01160                                  coneTrackIsoForEgammaSC,
01161                                  applyCrackCorrections,
01162                                  usePFSCEleCalib,
01163                                  useEGammaElectrons,
01164                                  useEGammaSupercluster);
01165     }
01166     catch( std::exception& err ) {
01167       cerr<<"exception setting PFAlgo Electron parameters: "
01168           <<err.what()<<". terminating."<<endl;
01169       delete this;
01170       exit(1);
01171     }
01172   }
01173 
01174 
01175   bool rejectTracks_Bad = true;
01176   bool rejectTracks_Step45 = true;
01177   bool usePFConversions = false;   // set true to use PFConversions
01178   bool usePFNuclearInteractions = false;
01179   bool usePFV0s = false;
01180 
01181 
01182   double dptRel_DispVtx = 10;
01183   
01184 
01185   options_->GetOpt("particle_flow", "usePFConversions", usePFConversions);
01186   options_->GetOpt("particle_flow", "usePFV0s", usePFV0s);
01187   options_->GetOpt("particle_flow", "usePFNuclearInteractions", usePFNuclearInteractions);
01188   options_->GetOpt("particle_flow", "dptRel_DispVtx",  dptRel_DispVtx);
01189 
01190   try { 
01191     pfAlgo_.setDisplacedVerticesParameters(rejectTracks_Bad,
01192                                            rejectTracks_Step45,
01193                                            usePFNuclearInteractions,
01194                                            usePFConversions,
01195                                            usePFV0s,
01196                                            dptRel_DispVtx);
01197 
01198   }
01199   catch( std::exception& err ) {
01200     cerr<<"exception setting PFAlgo displaced vertex parameters: "
01201         <<err.what()<<". terminating."<<endl;
01202     delete this;
01203     exit(1);
01204   }
01205 
01206   bool bCorrect = false;
01207   bool bCalibPrimary = false;
01208   double dptRel_PrimaryTrack = 0;
01209   double dptRel_MergedTrack = 0;
01210   double ptErrorSecondary = 0;
01211   vector<double> nuclCalibFactors;
01212 
01213   options_->GetOpt("particle_flow", "bCorrect", bCorrect);
01214   options_->GetOpt("particle_flow", "bCalibPrimary", bCalibPrimary);
01215   options_->GetOpt("particle_flow", "dptRel_PrimaryTrack", dptRel_PrimaryTrack);
01216   options_->GetOpt("particle_flow", "dptRel_MergedTrack", dptRel_MergedTrack);
01217   options_->GetOpt("particle_flow", "ptErrorSecondary", ptErrorSecondary);
01218   options_->GetOpt("particle_flow", "nuclCalibFactors", nuclCalibFactors);
01219 
01220   try { 
01221     pfAlgo_.setCandConnectorParameters(bCorrect, bCalibPrimary, dptRel_PrimaryTrack, dptRel_MergedTrack, ptErrorSecondary, nuclCalibFactors);
01222   }
01223   catch( std::exception& err ) {
01224     cerr<<"exception setting PFAlgo cand connector parameters: "
01225         <<err.what()<<". terminating."<<endl;
01226     delete this;
01227     exit(1);
01228   }
01229 
01230 
01231 
01232 
01233   int    algo = 2;
01234   options_->GetOpt("particle_flow", "algorithm", algo);
01235 
01236   pfAlgo_.setAlgo( algo );
01237   //   pfAlgoOther_.setAlgo( 1 );
01238 
01239 
01240   // jets options ---------------------------------
01241 
01242   doJets_ = false;
01243   options_->GetOpt("jets", "on/off", doJets_);
01244 
01245   jetsDebug_ = false;
01246   options_->GetOpt("jets", "debug", jetsDebug_);
01247 
01248   jetAlgoType_=3; //FastJet as Default
01249   options_->GetOpt("jets", "algo", jetAlgoType_);
01250 
01251   double mEtInputCut = 0.5;
01252   options_->GetOpt("jets", "EtInputCut",  mEtInputCut);           
01253 
01254   double mEInputCut = 0.;
01255   options_->GetOpt("jets", "EInputCut",  mEInputCut);  
01256 
01257   double seedThreshold  = 1.0;
01258   options_->GetOpt("jets", "seedThreshold", seedThreshold);
01259 
01260   double coneRadius = 0.5;
01261   options_->GetOpt("jets", "coneRadius", coneRadius);             
01262 
01263   double coneAreaFraction= 1.0;
01264   options_->GetOpt("jets", "coneAreaFraction",  coneAreaFraction);   
01265 
01266   int maxPairSize=2;
01267   options_->GetOpt("jets", "maxPairSize",  maxPairSize);  
01268 
01269   int maxIterations=100;
01270   options_->GetOpt("jets", "maxIterations",  maxIterations);      
01271 
01272   double overlapThreshold  = 0.75;
01273   options_->GetOpt("jets", "overlapThreshold", overlapThreshold);
01274 
01275   double ptMin = 10.;
01276   options_->GetOpt("jets", "ptMin",  ptMin);      
01277 
01278   double rparam = 1.0;
01279   options_->GetOpt("jets", "rParam",  rparam);    
01280  
01281   jetMaker_.setmEtInputCut (mEtInputCut);
01282   jetMaker_.setmEInputCut(mEInputCut); 
01283   jetMaker_.setSeedThreshold(seedThreshold); 
01284   jetMaker_.setConeRadius(coneRadius);
01285   jetMaker_.setConeAreaFraction(coneAreaFraction);
01286   jetMaker_.setMaxPairSize(maxPairSize);
01287   jetMaker_.setMaxIterations(maxIterations) ;
01288   jetMaker_.setOverlapThreshold(overlapThreshold) ;
01289   jetMaker_.setPtMin (ptMin);
01290   jetMaker_.setRParam (rparam);
01291   jetMaker_.setDebug(jetsDebug_);
01292   jetMaker_.updateParameter();
01293   cout <<"Opt: doJets? " << doJets_  <<endl; 
01294   cout <<"Opt: jetsDebug " << jetsDebug_  <<endl; 
01295   cout <<"Opt: algoType " << jetAlgoType_  <<endl; 
01296   cout <<"----------------------------------" << endl;
01297 
01298 
01299   // tau benchmark options ---------------------------------
01300 
01301   doTauBenchmark_ = false;
01302   options_->GetOpt("tau_benchmark", "on/off", doTauBenchmark_);
01303   
01304   if (doTauBenchmark_) {
01305     double coneAngle = 0.5;
01306     options_->GetOpt("tau_benchmark", "cone_angle", coneAngle);
01307     
01308     double seedEt    = 0.4;
01309     options_->GetOpt("tau_benchmark", "seed_et", seedEt);
01310     
01311     double coneMerge = 100.0;
01312     options_->GetOpt("tau_benchmark", "cone_merge", coneMerge);
01313     
01314     options_->GetOpt("tau_benchmark", "debug", tauBenchmarkDebug_);
01315 
01316     // cout<<"jets debug "<<jetsDebug_<<endl;
01317     
01318     if( tauBenchmarkDebug_ ) {
01319       cout << "Tau Benchmark Options : ";
01320       cout << "Angle=" << coneAngle << " seedEt=" << seedEt 
01321            << " Merge=" << coneMerge << endl;
01322     }
01323 
01324     jetAlgo_.SetConeAngle(coneAngle);
01325     jetAlgo_.SetSeedEt(seedEt);
01326     jetAlgo_.SetConeMerge(coneMerge);   
01327   }
01328 
01329 
01330 
01331   // print flags -------------
01332 
01333   printRecHits_ = false;
01334   printRecHitsEMin_ = 0.;
01335   options_->GetOpt("print", "rechits", printRecHits_ );
01336   options_->GetOpt("print", "rechits_emin", printRecHitsEMin_ );
01337   
01338   printClusters_ = false;
01339   printClustersEMin_ = 0.;
01340   options_->GetOpt("print", "clusters", printClusters_ );
01341   options_->GetOpt("print", "clusters_emin", printClustersEMin_ );
01342 
01343   printPFBlocks_ = false;
01344   options_->GetOpt("print", "PFBlocks", printPFBlocks_ );
01345   
01346   printPFCandidates_ = true;
01347   printPFCandidatesPtMin_ = 0.;
01348   options_->GetOpt("print", "PFCandidates", printPFCandidates_ );
01349   options_->GetOpt("print", "PFCandidates_ptmin", printPFCandidatesPtMin_ );
01350   
01351   printPFJets_ = true;
01352   printPFJetsPtMin_ = 0.;
01353   options_->GetOpt("print", "jets", printPFJets_ );
01354   options_->GetOpt("print", "jets_ptmin", printPFJetsPtMin_ );
01355  
01356   printSimParticles_ = true;
01357   printSimParticlesPtMin_ = 0.;
01358   options_->GetOpt("print", "simParticles", printSimParticles_ );
01359   options_->GetOpt("print", "simParticles_ptmin", printSimParticlesPtMin_ );
01360 
01361   printGenParticles_ = true;
01362   printGenParticlesPtMin_ = 0.;
01363   options_->GetOpt("print", "genParticles", printGenParticles_ );
01364   options_->GetOpt("print", "genParticles_ptmin", printGenParticlesPtMin_ );
01365 
01366   //MCTruthMatching Tool set to false by default
01367   //can only be used with fastsim and the UnFoldedMode set to true
01368   //when generating the simulated file
01369   printMCTruthMatching_ = false; 
01370   options_->GetOpt("print", "mctruthmatching", printMCTruthMatching_ );  
01371 
01372 
01373   verbosity_ = VERBOSE;
01374   options_->GetOpt("print", "verbosity", verbosity_ );
01375   cout<<"verbosity : "<<verbosity_<<endl;
01376 
01377 
01378 
01379   
01380 
01381 }
01382 
01383 void PFRootEventManager::connect( const char* infilename ) {
01384 
01385   cout<<"Opening input root files"<<endl;
01386 
01387   options_->GetOpt("root","file", inFileNames_);
01388   
01389 
01390 
01391   try {
01392     AutoLibraryLoader::enable();
01393   }
01394   catch(string& err) {
01395     cout<<err<<endl;
01396   }
01397 
01398   ev_ = new fwlite::ChainEvent(inFileNames_);
01399 
01400 
01401   if ( !ev_ || !ev_->isValid() ) { 
01402     cout << "The rootfile(s) " << endl;
01403     for ( unsigned int ifile=0; ifile<inFileNames_.size(); ++ifile ) 
01404       std::cout << " - " << inFileNames_[ifile] << std::endl;
01405     cout << " is (are) not valid file(s) to open" << endl;
01406     return;
01407   } else { 
01408     cout << "The rootfile(s) : " << endl;
01409     for ( unsigned int ifile=0; ifile<inFileNames_.size(); ++ifile ) 
01410       std::cout << " - " << inFileNames_[ifile] << std::endl;
01411     cout<<" are opened with " << ev_->size() << " events." <<endl;
01412   }
01413   
01414   // hits branches ----------------------------------------------
01415   std::string rechitsECALtagname;
01416   options_->GetOpt("root","rechits_ECAL_inputTag", rechitsECALtagname);
01417   rechitsECALTag_ = edm::InputTag(rechitsECALtagname);
01418 
01419   std::string rechitsHCALtagname;
01420   options_->GetOpt("root","rechits_HCAL_inputTag", rechitsHCALtagname);
01421   rechitsHCALTag_ = edm::InputTag(rechitsHCALtagname);
01422 
01423   std::string rechitsHFEMtagname;
01424   options_->GetOpt("root","rechits_HFEM_inputTag", rechitsHFEMtagname);
01425   rechitsHFEMTag_ = edm::InputTag(rechitsHFEMtagname);
01426 
01427   std::string rechitsHFHADtagname;
01428   options_->GetOpt("root","rechits_HFHAD_inputTag", rechitsHFHADtagname);
01429   rechitsHFHADTag_ = edm::InputTag(rechitsHFHADtagname);
01430 
01431   std::vector<string> rechitsCLEANEDtagnames;
01432   options_->GetOpt("root","rechits_CLEANED_inputTags", rechitsCLEANEDtagnames);
01433   for ( unsigned tags = 0; tags<rechitsCLEANEDtagnames.size(); ++tags )
01434     rechitsCLEANEDTags_.push_back(edm::InputTag(rechitsCLEANEDtagnames[tags]));
01435   rechitsCLEANEDV_.resize(rechitsCLEANEDTags_.size());
01436   rechitsCLEANEDHandles_.resize(rechitsCLEANEDTags_.size());
01437 
01438 
01439   // Tracks branches
01440   std::string rechitsPStagname;
01441   options_->GetOpt("root","rechits_PS_inputTag", rechitsPStagname);
01442   rechitsPSTag_ = edm::InputTag(rechitsPStagname);
01443 
01444   std::string recTrackstagname;
01445   options_->GetOpt("root","recTracks_inputTag", recTrackstagname);
01446   recTracksTag_ = edm::InputTag(recTrackstagname);
01447 
01448   std::string displacedRecTrackstagname;
01449   options_->GetOpt("root","displacedRecTracks_inputTag", displacedRecTrackstagname);
01450   displacedRecTracksTag_ = edm::InputTag(displacedRecTrackstagname);
01451 
01452   std::string primaryVerticestagname;
01453   options_->GetOpt("root","primaryVertices_inputTag", primaryVerticestagname);
01454   primaryVerticesTag_ = edm::InputTag(primaryVerticestagname);
01455 
01456   std::string stdTrackstagname;
01457   options_->GetOpt("root","stdTracks_inputTag", stdTrackstagname);
01458   stdTracksTag_ = edm::InputTag(stdTrackstagname);
01459 
01460   std::string gsfrecTrackstagname;
01461   options_->GetOpt("root","gsfrecTracks_inputTag", gsfrecTrackstagname);
01462   gsfrecTracksTag_ = edm::InputTag(gsfrecTrackstagname);
01463 
01464   useConvBremGsfTracks_ = false;
01465   options_->GetOpt("particle_flow", "useConvBremGsfTracks", useConvBremGsfTracks_);
01466   if ( useConvBremGsfTracks_ ) { 
01467     std::string convBremGsfrecTrackstagname;
01468     options_->GetOpt("root","convBremGsfrecTracks_inputTag", convBremGsfrecTrackstagname);
01469     convBremGsfrecTracksTag_ = edm::InputTag(convBremGsfrecTrackstagname);
01470   }
01471 
01472   useConvBremPFRecTracks_ = false;
01473   options_->GetOpt("particle_flow", "useConvBremPFRecTracks", useConvBremPFRecTracks_);
01474 
01475 
01476   // muons branch
01477   std::string muonstagname;
01478   options_->GetOpt("root","muon_inputTag", muonstagname);
01479   muonsTag_ = edm::InputTag(muonstagname);
01480 
01481   // conversion
01482   usePFConversions_=false;
01483   options_->GetOpt("particle_flow", "usePFConversions", usePFConversions_);
01484   if( usePFConversions_ ) {
01485     std::string conversiontagname;
01486     options_->GetOpt("root","conversion_inputTag", conversiontagname);
01487     conversionTag_ = edm::InputTag(conversiontagname);
01488   }
01489 
01490   // V0
01491   usePFV0s_=false;
01492   options_->GetOpt("particle_flow", "usePFV0s", usePFV0s_);
01493   if( usePFV0s_ ) {
01494     std::string v0tagname;
01495     options_->GetOpt("root","V0_inputTag", v0tagname);
01496     v0Tag_ = edm::InputTag(v0tagname);
01497   }
01498 
01499  //Displaced Vertices
01500   usePFNuclearInteractions_=false;
01501   options_->GetOpt("particle_flow", "usePFNuclearInteractions", usePFNuclearInteractions_);
01502   if( usePFNuclearInteractions_ ) {
01503     std::string pfNuclearTrackerVertextagname;
01504     options_->GetOpt("root","PFDisplacedVertex_inputTag", pfNuclearTrackerVertextagname);
01505     pfNuclearTrackerVertexTag_ = edm::InputTag(pfNuclearTrackerVertextagname);
01506   }
01507 
01508   std::string trueParticlestagname;
01509   options_->GetOpt("root","trueParticles_inputTag", trueParticlestagname);
01510   trueParticlesTag_ = edm::InputTag(trueParticlestagname);
01511 
01512   std::string MCTruthtagname;
01513   options_->GetOpt("root","MCTruth_inputTag", MCTruthtagname);
01514   MCTruthTag_ = edm::InputTag(MCTruthtagname);
01515 
01516   std::string caloTowerstagname;
01517   options_->GetOpt("root","caloTowers_inputTag", caloTowerstagname);
01518   caloTowersTag_ = edm::InputTag(caloTowerstagname);
01519 
01520   std::string genJetstagname;
01521   options_->GetOpt("root","genJets_inputTag", genJetstagname);
01522   genJetsTag_ = edm::InputTag(genJetstagname);
01523 
01524   
01525   std::string genParticlesforMETtagname;
01526   options_->GetOpt("root","genParticlesforMET_inputTag", genParticlesforMETtagname);
01527   genParticlesforMETTag_ = edm::InputTag(genParticlesforMETtagname);
01528 
01529   std::string genParticlesforJetstagname;
01530   options_->GetOpt("root","genParticlesforJets_inputTag", genParticlesforJetstagname);
01531   genParticlesforJetsTag_ = edm::InputTag(genParticlesforJetstagname);
01532 
01533   // PF candidates 
01534   std::string pfCandidatetagname;
01535   options_->GetOpt("root","particleFlowCand_inputTag", pfCandidatetagname);
01536   pfCandidateTag_ = edm::InputTag(pfCandidatetagname);
01537 
01538   std::string caloJetstagname;
01539   options_->GetOpt("root","CaloJets_inputTag", caloJetstagname);
01540   caloJetsTag_ = edm::InputTag(caloJetstagname);
01541 
01542   std::string corrcaloJetstagname;
01543   options_->GetOpt("root","corrCaloJets_inputTag", corrcaloJetstagname);
01544   corrcaloJetsTag_ = edm::InputTag(corrcaloJetstagname);
01545 
01546   std::string pfJetstagname;
01547   options_->GetOpt("root","PFJets_inputTag", pfJetstagname);
01548   pfJetsTag_ = edm::InputTag(pfJetstagname);
01549 
01550   std::string pfMetstagname;
01551   options_->GetOpt("root","PFMET_inputTag", pfMetstagname);
01552   pfMetsTag_ = edm::InputTag(pfMetstagname);
01553 
01554   std::string caloMetstagname;
01555   options_->GetOpt("root","CaloMET_inputTag", caloMetstagname);
01556   caloMetsTag_ = edm::InputTag(caloMetstagname);
01557 
01558   std::string tcMetstagname;
01559   options_->GetOpt("root","TCMET_inputTag", tcMetstagname);
01560   tcMetsTag_ = edm::InputTag(tcMetstagname);
01561 
01562 }
01563 
01564 
01565 
01566 
01567 
01568 PFRootEventManager::~PFRootEventManager() {
01569 
01570   if(outFile_) {
01571     outFile_->Close();
01572   }
01573 
01574   if(outEvent_) delete outEvent_;
01575 
01576   delete options_;
01577 
01578 }
01579 
01580 
01581 void PFRootEventManager::write() {
01582 
01583   if(doPFJetBenchmark_) PFJetBenchmark_.write();
01584   if(doPFMETBenchmark_) metManager_->write();
01585   clusterAlgoECAL_.write();
01586   clusterAlgoHCAL_.write();
01587   clusterAlgoPS_.write();
01588   clusterAlgoHFEM_.write();
01589   clusterAlgoHFHAD_.write();
01590   
01591   
01592   if(outFile_) {
01593     outFile_->Write();
01594 //     outFile_->cd(); 
01595 //     // write histos here
01596 //     cout<<"writing output to "<<outFile_->GetName()<<endl;
01597 //     h_deltaETvisible_MCEHT_->Write();
01598 //     h_deltaETvisible_MCPF_->Write();
01599 //     if(outTree_) outTree_->Write();
01600 //     if(doPFCandidateBenchmark_) pfCandidateBenchmark_.write();
01601   }
01602 }
01603 
01604 
01605 int PFRootEventManager::eventToEntry(int run, int lumi, int event) const {
01606   
01607   RunsMap::const_iterator iR = mapEventToEntry_.find( run );
01608   if( iR != mapEventToEntry_.end() ) {
01609     LumisMap::const_iterator iL = iR->second.find( lumi );
01610     if( iL != iR->second.end() ) {
01611       EventToEntry::const_iterator iE = iL->second.find( event );
01612       if( iE != iL->second.end() ) {
01613         return iE->second;
01614       }  
01615       else {
01616         cout<<"event "<<event<<" not found in run "<<run<<", lumi "<<lumi<<endl;
01617       }
01618     }
01619     else {
01620       cout<<"lumi "<<lumi<<" not found in run "<<run<<endl;
01621     }
01622   }
01623   else{
01624     cout<<"run "<<run<<" not found"<<endl;
01625   }
01626   return -1;    
01627 }
01628 
01629 bool PFRootEventManager::processEvent(int run, int lumi, int event) {
01630 
01631   int entry = eventToEntry(run, lumi, event);
01632   if( entry < 0 ) {
01633     cout<<"event "<<event<<" is not present, sorry."<<endl;
01634     return false;
01635   }
01636   else
01637     return processEntry( entry ); 
01638 } 
01639 
01640 
01641 bool PFRootEventManager::processEntry(int entry) {
01642 
01643   reset();
01644 
01645   iEvent_ = entry;
01646  
01647   bool exists = ev_->to(entry);
01648   if ( !exists ) { 
01649     std::cout << "Entry " << entry << " does not exist " << std::endl; 
01650     return false;
01651   }
01652   const edm::EventBase& iEvent = *ev_;
01653 
01654   if( outEvent_ ) outEvent_->setNumber(entry);
01655 
01656   if(verbosity_ == VERBOSE  || 
01657      //entry < 10000 ||
01658      (entry < 100 && entry%10 == 0) || 
01659      (entry < 1000 && entry%100 == 0) || 
01660      entry%1000 == 0 ) 
01661     cout<<"process entry "<< entry 
01662         <<", run "<<iEvent.id().run()
01663         <<", lumi "<<iEvent.id().luminosityBlock()      
01664         <<", event:"<<iEvent.id().event()
01665         << endl;
01666 
01667   //ev_->getTFile()->cd();
01668   bool goodevent =  readFromSimulation(entry);
01669 
01670   /* 
01671   std::cout << "Rechits cleaned : " << std::endl;
01672   for(unsigned i=0; i<rechitsCLEANED_.size(); i++) {
01673     string seedstatus = "    ";
01674     printRecHit(rechitsCLEANED_[i], i, seedstatus.c_str());
01675   }
01676   */
01677 
01678   if(verbosity_ == VERBOSE ) {
01679     cout<<"number of vertices             : "<<primaryVertices_.size()<<endl;
01680     cout<<"number of recTracks            : "<<recTracks_.size()<<endl;
01681     cout<<"number of gsfrecTracks         : "<<gsfrecTracks_.size()<<endl;
01682     cout<<"number of convBremGsfrecTracks : "<<convBremGsfrecTracks_.size()<<endl;
01683     cout<<"number of muons                : "<<muons_.size()<<endl;
01684     cout<<"number of displaced vertices   : "<<pfNuclearTrackerVertex_.size()<<endl;
01685     cout<<"number of conversions          : "<<conversion_.size()<<endl;
01686     cout<<"number of v0                   : "<<v0_.size()<<endl;
01687     cout<<"number of stdTracks            : "<<stdTracks_.size()<<endl;
01688     cout<<"number of true particles       : "<<trueParticles_.size()<<endl;
01689     cout<<"number of ECAL rechits         : "<<rechitsECAL_.size()<<endl;
01690     cout<<"number of HCAL rechits         : "<<rechitsHCAL_.size()<<endl;
01691     cout<<"number of HFEM rechits         : "<<rechitsHFEM_.size()<<endl;
01692     cout<<"number of HFHAD rechits        : "<<rechitsHFHAD_.size()<<endl;
01693     cout<<"number of HF Cleaned rechits   : "<<rechitsCLEANED_.size()<<endl;
01694     cout<<"number of PS rechits           : "<<rechitsPS_.size()<<endl;
01695   }  
01696 
01697   if( doClustering_ ) clustering(); 
01698   else if( verbosity_ == VERBOSE )
01699     cout<<"clustering is OFF - clusters come from the input file"<<endl; 
01700 
01701   if(verbosity_ == VERBOSE ) {
01702     if(clustersECAL_.get() ) {
01703       cout<<"number of ECAL clusters : "<<clustersECAL_->size()<<endl;
01704     }
01705     if(clustersHCAL_.get() ) {
01706       cout<<"number of HCAL clusters : "<<clustersHCAL_->size()<<endl;
01707     }
01708     if(clustersHFEM_.get() ) {
01709       cout<<"number of HFEM clusters : "<<clustersHFEM_->size()<<endl;
01710     }
01711     if(clustersHFHAD_.get() ) {
01712       cout<<"number of HFHAD clusters : "<<clustersHFHAD_->size()<<endl;
01713     }
01714     if(clustersPS_.get() ) {
01715       cout<<"number of PS clusters : "<<clustersPS_->size()<<endl;
01716     }
01717   }
01718 
01719   if(doParticleFlow_) { 
01720     particleFlow();
01721 
01722     if (doCompare_) pfCandCompare(entry);
01723   }
01724 
01725   if(doJets_) {
01726     reconstructGenJets();
01727     reconstructCaloJets();
01728     reconstructPFJets();
01729   }    
01730         
01731  
01732   // call print() in verbose mode
01733   if( verbosity_ == VERBOSE ) print();
01734   
01735   //COLIN the PFJet and PFMET benchmarks are very messy. 
01736   //COLIN    compare with the filling of the PFCandidateBenchmark, which is one line. 
01737   
01738   goodevent = eventAccepted(); 
01739 
01740   // evaluate PFJet Benchmark 
01741   if(doPFJetBenchmark_) { // start PFJet Benchmark
01742 
01743     PFJetBenchmark_.process(pfJets_, genJets_);
01744     double resPt = PFJetBenchmark_.resPtMax();
01745     double resChargedHadEnergy = PFJetBenchmark_.resChargedHadEnergyMax();
01746     double resNeutralHadEnergy = PFJetBenchmark_.resNeutralHadEnergyMax();
01747     double resNeutralEmEnergy = PFJetBenchmark_.resNeutralEmEnergyMax();
01748           
01749     if( verbosity_ == VERBOSE ){ //start debug print
01750 
01751       cout << " =====================PFJetBenchmark =================" << endl;
01752       cout<<"Resol Pt max "<<resPt
01753           <<" resChargedHadEnergy Max " << resChargedHadEnergy
01754           <<" resNeutralHadEnergy Max " << resNeutralHadEnergy
01755           << " resNeutralEmEnergy Max "<< resNeutralEmEnergy << endl;
01756     } // end debug print
01757 
01758     // PJ : printout for bad events (selected by the "if")
01759     /*
01760     if ( fabs(resPt) > 0.4 )
01761       std::cout << "'" << iEvent.id().run() << ":" << iEvent.id().event() << "-" 
01762                 << iEvent.id().run() << ":" << iEvent.id().event() << "'," << std::endl;
01763     */
01764     if ( resPt < -1. ) { 
01765       cout << " =====================PFJetBenchmark =================" << endl;
01766       cout<<"process entry "<< entry << endl;
01767       cout<<"Resol Pt max "<<resPt
01768           <<" resChargedHadEnergy Max " << resChargedHadEnergy
01769           <<" resNeutralHadEnergy Max " << resNeutralHadEnergy
01770           << " resNeutralEmEnergy Max "<< resNeutralEmEnergy 
01771           << " Jet pt " << genJets_[0].pt() << endl;
01772       // return true;
01773     } else { 
01774       // return false;
01775     }
01776     //   if (resNeutralEmEnergy>0.5) return true;
01777     //   else return false;
01778   }// end PFJet Benchmark
01779 
01780   //COLIN would  be nice to move this long code to a separate function. 
01781   // is it necessary to re-set everything at each event?? 
01782   if(doPFMETBenchmark_) { // start PFMet Benchmark
01783 
01784     // Fill here the various met benchmarks
01785     // pfMET vs GenMET
01786     metManager_->setMET1(&genParticlesCMSSW_);
01787     metManager_->setMET2(&pfMetsCMSSW_[0]);
01788     metManager_->FillHisto("PF");
01789     // cout events in tail
01790     metManager_->coutTailEvents(entry,DeltaMETcut,DeltaPhicut, MET1cut);
01791 
01792     // caloMET vs GenMET
01793     metManager_->setMET2(&caloMetsCMSSW_[0]);
01794     metManager_->FillHisto("Calo");
01795 
01796     if ( doMet_ ) { 
01797       // recomputed pfMET vs GenMET
01798       metManager_->setMET2(*pfCandidates_);
01799       metManager_->FillHisto("recompPF");
01800       metManager_->coutTailEvents(entry,DeltaMETcut,DeltaPhicut, MET1cut);
01801     }
01802 
01803     if (JECinCaloMet_)
01804     {
01805       // corrCaloMET vs GenMET
01806       metManager_->setMET2(&caloMetsCMSSW_[0]);
01807       metManager_->propagateJECtoMET2(caloJetsCMSSW_, corrcaloJetsCMSSW_);
01808       metManager_->FillHisto("corrCalo");
01809     }
01810   }// end PFMET Benchmark
01811 
01812   if( goodevent && doPFCandidateBenchmark_ ) {
01813     pfCandidateManager_.fill( *pfCandidates_, genParticlesCMSSW_);
01814   }
01815     
01816   // evaluate tau Benchmark   
01817   if( goodevent && doTauBenchmark_) { // start tau Benchmark
01818     double deltaEt = 0.;
01819     deltaEt  = tauBenchmark( *pfCandidates_ ); 
01820     if( verbosity_ == VERBOSE ) cout<<"delta E_t ="<<deltaEt <<endl;
01821     //      cout<<"delta E_t ="<<deltaEt<<" delta E_t Other ="<<deltaEt1<<endl;
01822 
01823 
01824     //   if( deltaEt>0.4 ) {
01825     //     cout<<deltaEt<<endl;
01826     //     return true;
01827     //   }  
01828     //   else return false;
01829 
01830   
01831   } // end tau Benchmark
01832 
01833   if(goodevent && outTree_) 
01834     outTree_->Fill();
01835 
01836   if(calibFile_)
01837     printMCCalib(*calibFile_);
01838   
01839   return goodevent;
01840 
01841 }
01842 
01843 
01844 
01845 bool PFRootEventManager::eventAccepted() const {
01846   // return highPtJet(10); 
01847   //return highPtPFCandidate( 10, PFCandidate::h ); 
01848   return true;
01849 } 
01850 
01851 
01852 bool PFRootEventManager::highPtJet(double ptMin) const {
01853   for( unsigned i=0; i<pfJets_.size(); ++i) {
01854     if( pfJets_[i].pt() > ptMin ) return true;
01855   }
01856   return false;
01857 }
01858 
01859 bool PFRootEventManager::highPtPFCandidate( double ptMin, 
01860                                             PFCandidate::ParticleType type) const {
01861   for( unsigned i=0; i<pfCandidates_->size(); ++i) {
01862 
01863     const PFCandidate& pfc = (*pfCandidates_)[i];
01864     if(type!= PFCandidate::X &&  
01865        pfc.particleId() != type ) continue;
01866     if( pfc.pt() > ptMin ) return true;
01867   }
01868   return false;
01869 }
01870 
01871 
01872 bool PFRootEventManager::readFromSimulation(int entry) {
01873 
01874   if (verbosity_ == VERBOSE ) {
01875     cout <<"start reading from simulation"<<endl;
01876   }
01877 
01878 
01879   // if(!tree_) return false;
01880   
01881   const edm::EventBase& iEvent = *ev_;
01882   
01883 
01884   bool foundstdTracks = iEvent.getByLabel(stdTracksTag_,stdTracksHandle_);
01885   if ( foundstdTracks ) { 
01886     stdTracks_ = *stdTracksHandle_;
01887     // cout << "Found " << stdTracks_.size() << " standard tracks" << endl;
01888   } else { 
01889     cerr<<"PFRootEventManager::ProcessEntry : stdTracks Collection not found : "
01890         <<entry << " " << stdTracksTag_<<endl;
01891   }
01892 
01893   bool foundMCTruth = iEvent.getByLabel(MCTruthTag_,MCTruthHandle_);
01894   if ( foundMCTruth ) { 
01895     MCTruth_ = *MCTruthHandle_;
01896     // cout << "Found MC truth" << endl;
01897   } else { 
01898     // cerr<<"PFRootEventManager::ProcessEntry : MCTruth Collection not found : "
01899     //    <<entry << " " << MCTruthTag_<<endl;
01900   }
01901 
01902   bool foundTP = iEvent.getByLabel(trueParticlesTag_,trueParticlesHandle_);
01903   if ( foundTP ) { 
01904     trueParticles_ = *trueParticlesHandle_;
01905     // cout << "Found " << trueParticles_.size() << " true particles" << endl;
01906   } else { 
01907     //cerr<<"PFRootEventManager::ProcessEntry : trueParticles Collection not found : "
01908     //    <<entry << " " << trueParticlesTag_<<endl;
01909   }
01910 
01911   bool foundECAL = iEvent.getByLabel(rechitsECALTag_,rechitsECALHandle_);
01912   if ( foundECAL ) { 
01913     rechitsECAL_ = *rechitsECALHandle_;
01914     // cout << "Found " << rechitsECAL_.size() << " ECAL rechits" << endl;
01915   } else { 
01916     cerr<<"PFRootEventManager::ProcessEntry : rechitsECAL Collection not found : "
01917         <<entry << " " << rechitsECALTag_<<endl;
01918   }
01919 
01920   bool foundHCAL = iEvent.getByLabel(rechitsHCALTag_,rechitsHCALHandle_);
01921   if ( foundHCAL ) { 
01922     rechitsHCAL_ = *rechitsHCALHandle_;
01923     // cout << "Found " << rechitsHCAL_.size() << " HCAL rechits" << endl;
01924   } else { 
01925     cerr<<"PFRootEventManager::ProcessEntry : rechitsHCAL Collection not found : "
01926         <<entry << " " << rechitsHCALTag_<<endl;
01927   }
01928 
01929   bool foundHFEM = iEvent.getByLabel(rechitsHFEMTag_,rechitsHFEMHandle_);
01930   if ( foundHFEM ) { 
01931     rechitsHFEM_ = *rechitsHFEMHandle_;
01932     // cout << "Found " << rechitsHFEM_.size() << " HFEM rechits" << endl;
01933   } else { 
01934     cerr<<"PFRootEventManager::ProcessEntry : rechitsHFEM Collection not found : "
01935         <<entry << " " << rechitsHFEMTag_<<endl;
01936   }
01937 
01938   bool foundHFHAD = iEvent.getByLabel(rechitsHFHADTag_,rechitsHFHADHandle_);
01939   if ( foundHFHAD ) { 
01940     rechitsHFHAD_ = *rechitsHFHADHandle_;
01941     // cout << "Found " << rechitsHFHAD_.size() << " HFHAD rechits" << endl;
01942   } else { 
01943     cerr<<"PFRootEventManager::ProcessEntry : rechitsHFHAD Collection not found : "
01944         <<entry << " " << rechitsHFHADTag_<<endl;
01945   }
01946 
01947   for ( unsigned i=0; i<rechitsCLEANEDTags_.size(); ++i ) { 
01948     bool foundCLEANED = iEvent.getByLabel(rechitsCLEANEDTags_[i],
01949                                           rechitsCLEANEDHandles_[i]);
01950     if ( foundCLEANED ) { 
01951       rechitsCLEANEDV_[i] = *(rechitsCLEANEDHandles_[i]);
01952       // cout << "Found " << rechitsCLEANEDV_[i].size() << " CLEANED rechits" << endl;
01953     } else { 
01954       cerr<<"PFRootEventManager::ProcessEntry : rechitsCLEANED Collection not found : "
01955           <<entry << " " << rechitsCLEANEDTags_[i]<<endl;
01956     }
01957 
01958   }
01959 
01960   bool foundPS = iEvent.getByLabel(rechitsPSTag_,rechitsPSHandle_);
01961   if ( foundPS ) { 
01962     rechitsPS_ = *rechitsPSHandle_;
01963     // cout << "Found " << rechitsPS_.size() << " PS rechits" << endl;
01964   } else { 
01965     cerr<<"PFRootEventManager::ProcessEntry : rechitsPS Collection not found : "
01966         <<entry << " " << rechitsPSTag_<<endl;
01967   }
01968 
01969   bool foundCT = iEvent.getByLabel(caloTowersTag_,caloTowersHandle_);
01970   if ( foundCT ) { 
01971     caloTowers_ = *caloTowersHandle_;
01972     // cout << "Found " << caloTowers_.size() << " calo Towers" << endl;
01973   } else { 
01974     cerr<<"PFRootEventManager::ProcessEntry : caloTowers Collection not found : "
01975         <<entry << " " << caloTowersTag_<<endl;
01976   }
01977 
01978   bool foundPV = iEvent.getByLabel(primaryVerticesTag_,primaryVerticesHandle_);
01979   if ( foundPV ) { 
01980     primaryVertices_ = *primaryVerticesHandle_;
01981     // cout << "Found " << primaryVertices_.size() << " primary vertices" << endl;
01982   } else { 
01983     cerr<<"PFRootEventManager::ProcessEntry : primaryVertices Collection not found : "
01984         <<entry << " " << primaryVerticesTag_<<endl;
01985   }
01986 
01987   bool foundPFV = iEvent.getByLabel(pfNuclearTrackerVertexTag_,pfNuclearTrackerVertexHandle_);
01988   if ( foundPFV ) { 
01989     pfNuclearTrackerVertex_ = *pfNuclearTrackerVertexHandle_;
01990     // cout << "Found " << pfNuclearTrackerVertex_.size() << " secondary PF vertices" << endl;
01991   } else if ( usePFNuclearInteractions_ ) { 
01992     cerr<<"PFRootEventManager::ProcessEntry : pfNuclearTrackerVertex Collection not found : "
01993         <<entry << " " << pfNuclearTrackerVertexTag_<<endl;
01994   }
01995 
01996   bool foundrecTracks = iEvent.getByLabel(recTracksTag_,recTracksHandle_);
01997   if ( foundrecTracks ) { 
01998     recTracks_ = *recTracksHandle_;
01999     // cout << "Found " << recTracks_.size() << " PFRecTracks" << endl;
02000   } else { 
02001     cerr<<"PFRootEventManager::ProcessEntry : recTracks Collection not found : "
02002         <<entry << " " << recTracksTag_<<endl;
02003   }
02004 
02005   bool founddisplacedRecTracks = iEvent.getByLabel(displacedRecTracksTag_,displacedRecTracksHandle_);
02006   if ( founddisplacedRecTracks ) { 
02007     displacedRecTracks_ = *displacedRecTracksHandle_;
02008     // cout << "Found " << displacedRecTracks_.size() << " PFRecTracks" << endl;
02009   } else { 
02010     cerr<<"PFRootEventManager::ProcessEntry : displacedRecTracks Collection not found : "
02011         <<entry << " " << displacedRecTracksTag_<<endl;
02012   }
02013 
02014 
02015   bool foundgsfrecTracks = iEvent.getByLabel(gsfrecTracksTag_,gsfrecTracksHandle_);
02016   if ( foundgsfrecTracks ) { 
02017     gsfrecTracks_ = *gsfrecTracksHandle_;
02018     // cout << "Found " << gsfrecTracks_.size() << " GsfPFRecTracks" << endl;
02019   } else { 
02020     cerr<<"PFRootEventManager::ProcessEntry : gsfrecTracks Collection not found : "
02021         <<entry << " " << gsfrecTracksTag_<<endl;
02022   }
02023 
02024   bool foundconvBremGsfrecTracks = iEvent.getByLabel(convBremGsfrecTracksTag_,convBremGsfrecTracksHandle_);
02025   if ( foundconvBremGsfrecTracks ) { 
02026     convBremGsfrecTracks_ = *convBremGsfrecTracksHandle_;
02027     // cout << "Found " << convBremGsfrecTracks_.size() << " ConvBremGsfPFRecTracks" << endl;
02028   } else if ( useConvBremGsfTracks_ ) { 
02029     cerr<<"PFRootEventManager::ProcessEntry : convBremGsfrecTracks Collection not found : "
02030         <<entry << " " << convBremGsfrecTracksTag_<<endl;
02031   }
02032 
02033   bool foundmuons = iEvent.getByLabel(muonsTag_,muonsHandle_);
02034   if ( foundmuons ) { 
02035     muons_ = *muonsHandle_;
02036     /*
02037     cout << "Found " << muons_.size() << " muons" << endl;
02038     for ( unsigned imu=0; imu<muons_.size(); ++imu ) { 
02039       std::cout << " Muon " << imu << ":" << std::endl;
02040       reco::MuonRef muonref( &muons_, imu );
02041       PFMuonAlgo::printMuonProperties(muonref);
02042     }
02043     */
02044   } else { 
02045     cerr<<"PFRootEventManager::ProcessEntry : muons Collection not found : "
02046         <<entry << " " << muonsTag_<<endl;
02047   }
02048 
02049   bool foundconversion = iEvent.getByLabel(conversionTag_,conversionHandle_);
02050   if ( foundconversion ) { 
02051     conversion_ = *conversionHandle_;
02052     // cout << "Found " << conversion_.size() << " conversion" << endl;
02053   } else if ( usePFConversions_ ) { 
02054     cerr<<"PFRootEventManager::ProcessEntry : conversion Collection not found : "
02055         <<entry << " " << conversionTag_<<endl;
02056   }
02057 
02058   bool foundv0 = iEvent.getByLabel(v0Tag_,v0Handle_);
02059   if ( foundv0 ) { 
02060     v0_ = *v0Handle_;
02061     // cout << "Found " << v0_.size() << " v0" << endl;
02062   } else if ( usePFV0s_ ) { 
02063     cerr<<"PFRootEventManager::ProcessEntry : v0 Collection not found : "
02064         <<entry << " " << v0Tag_<<endl;
02065   }
02066 
02067   bool foundgenJets = iEvent.getByLabel(genJetsTag_,genJetsHandle_);
02068   if ( foundgenJets ) { 
02069     genJetsCMSSW_ = *genJetsHandle_;
02070     // cout << "Found " << genJetsCMSSW_.size() << " genJets" << endl;
02071   } else { 
02072     //cerr<<"PFRootEventManager::ProcessEntry : genJets Collection not found : "
02073     //    <<entry << " " << genJetsTag_<<endl;
02074   }
02075 
02076   bool foundgenParticlesforJets = iEvent.getByLabel(genParticlesforJetsTag_,genParticlesforJetsHandle_);
02077   if ( foundgenParticlesforJets ) { 
02078     genParticlesforJets_ = *genParticlesforJetsHandle_;
02079     // cout << "Found " << genParticlesforJets_.size() << " genParticlesforJets" << endl;
02080   } else { 
02081     //cerr<<"PFRootEventManager::ProcessEntry : genParticlesforJets Collection not found : "
02082     //    <<entry << " " << genParticlesforJetsTag_<<endl;
02083   }
02084 
02085   bool foundgenParticlesforMET = iEvent.getByLabel(genParticlesforMETTag_,genParticlesforMETHandle_);
02086   if ( foundgenParticlesforMET ) { 
02087     genParticlesCMSSW_ = *genParticlesforMETHandle_;
02088     // cout << "Found " << genParticlesCMSSW_.size() << " genParticlesforMET" << endl;
02089   } else { 
02090     //cerr<<"PFRootEventManager::ProcessEntry : genParticlesforMET Collection not found : "
02091     //    <<entry << " " << genParticlesforMETTag_<<endl;
02092   }
02093 
02094   bool foundcaloJets = iEvent.getByLabel(caloJetsTag_,caloJetsHandle_);
02095   if ( foundcaloJets ) { 
02096     caloJetsCMSSW_ = *caloJetsHandle_;
02097     // cout << "Found " << caloJetsCMSSW_.size() << " caloJets" << endl;
02098   } else { 
02099     cerr<<"PFRootEventManager::ProcessEntry : caloJets Collection not found : "
02100         <<entry << " " << caloJetsTag_<<endl;
02101   }
02102 
02103   bool foundcorrcaloJets = iEvent.getByLabel(corrcaloJetsTag_,corrcaloJetsHandle_);
02104   if ( foundcorrcaloJets ) { 
02105     corrcaloJetsCMSSW_ = *corrcaloJetsHandle_;
02106     // cout << "Found " << corrcaloJetsCMSSW_.size() << " corrcaloJets" << endl;
02107   } else { 
02108     //cerr<<"PFRootEventManager::ProcessEntry : corrcaloJets Collection not found : "
02109     //    <<entry << " " << corrcaloJetsTag_<<endl;
02110   }
02111 
02112   bool foundpfJets = iEvent.getByLabel(pfJetsTag_,pfJetsHandle_);
02113   if ( foundpfJets ) { 
02114     pfJetsCMSSW_ = *pfJetsHandle_;
02115     // cout << "Found " << pfJetsCMSSW_.size() << " PFJets" << endl;
02116   } else { 
02117     cerr<<"PFRootEventManager::ProcessEntry : PFJets Collection not found : "
02118         <<entry << " " << pfJetsTag_<<endl;
02119   }
02120 
02121   bool foundpfCands = iEvent.getByLabel(pfCandidateTag_,pfCandidateHandle_);
02122   if ( foundpfCands ) { 
02123     pfCandCMSSW_ = *pfCandidateHandle_;
02124     // cout << "Found " << pfCandCMSSW_.size() << " PFCandidates" << endl;
02125   } else { 
02126     cerr<<"PFRootEventManager::ProcessEntry : PFCandidate Collection not found : "
02127         <<entry << " " << pfCandidateTag_<<endl;
02128   }
02129 
02130   bool foundpfMets = iEvent.getByLabel(pfMetsTag_,pfMetsHandle_);
02131   if ( foundpfMets ) { 
02132     pfMetsCMSSW_ = *pfMetsHandle_;
02133     //cout << "Found " << pfMetsCMSSW_.size() << " PFMets" << endl;
02134   } else { 
02135     cerr<<"PFRootEventManager::ProcessEntry : PFMets Collection not found : "
02136         <<entry << " " << pfMetsTag_<<endl;
02137   }
02138 
02139   bool foundtcMets = iEvent.getByLabel(tcMetsTag_,tcMetsHandle_);
02140   if ( foundtcMets ) { 
02141     tcMetsCMSSW_ = *tcMetsHandle_;
02142     //cout << "Found " << tcMetsCMSSW_.size() << " TCMets" << endl;
02143   } else { 
02144     cerr<<"TCRootEventManager::ProcessEntry : TCMets Collection not found : "
02145         <<entry << " " << tcMetsTag_<<endl;
02146   }
02147 
02148   bool foundcaloMets = iEvent.getByLabel(caloMetsTag_,caloMetsHandle_);
02149   if ( foundcaloMets ) { 
02150     caloMetsCMSSW_ = *caloMetsHandle_;
02151     //cout << "Found " << caloMetsCMSSW_.size() << " CALOMets" << endl;
02152   } else { 
02153     cerr<<"CALORootEventManager::ProcessEntry : CALOMets Collection not found : "
02154         <<entry << " " << caloMetsTag_<<endl;
02155   }
02156 
02157   // now can use the tree
02158 
02159   bool goodevent = true;
02160   if(trueParticles_.size() ) {
02161     // this is a filter to select single particle events.
02162     if(filterNParticles_ && doTauBenchmark_ &&
02163        trueParticles_.size() != filterNParticles_ ) {
02164       cout << "PFRootEventManager : event discarded Nparticles="
02165            <<filterNParticles_<< endl; 
02166       goodevent = false;
02167     }
02168     if(goodevent && doTauBenchmark_ && filterHadronicTaus_ && !isHadronicTau() ) {
02169       cout << "PFRootEventManager : leptonic tau discarded " << endl; 
02170       goodevent =  false;
02171     }
02172     if( goodevent && doTauBenchmark_ && !filterTaus_.empty() 
02173         && !countChargedAndPhotons() ) {
02174       assert( filterTaus_.size() == 2 );
02175       cout <<"PFRootEventManager : tau discarded: "
02176            <<"number of charged and neutral particles different from "
02177            <<filterTaus_[0]<<","<<filterTaus_[1]<<endl;
02178       goodevent =  false;      
02179     } 
02180     
02181     if(goodevent)
02182       fillOutEventWithSimParticles( trueParticles_ );
02183 
02184   }
02185   
02186   //   if(caloTowersBranch_) {
02187   //     if(goodevent)
02188   //       fillOutEventWithCaloTowers( caloTowers_ );
02189   //   } 
02190 
02191   if(rechitsECAL_.size()) {
02192     PreprocessRecHits( rechitsECAL_ , findRecHitNeighbours_);
02193   }
02194   if(rechitsHCAL_.size()) {
02195     PreprocessRecHits( rechitsHCAL_ , findRecHitNeighbours_);
02196   }
02197   if(rechitsHFEM_.size()) {
02198     PreprocessRecHits( rechitsHFEM_ , findRecHitNeighbours_);
02199   }
02200   if(rechitsHFHAD_.size()) {
02201     PreprocessRecHits( rechitsHFHAD_ , findRecHitNeighbours_);
02202   }
02203   rechitsCLEANED_.clear();
02204   for ( unsigned i=0; i<rechitsCLEANEDV_.size(); ++i ) { 
02205     if(rechitsCLEANEDV_[i].size()) {
02206       PreprocessRecHits( rechitsCLEANEDV_[i] , false);
02207       for ( unsigned j=0; j<rechitsCLEANEDV_[i].size(); ++j ) { 
02208         rechitsCLEANED_.push_back( (rechitsCLEANEDV_[i])[j] );
02209       }
02210     }
02211   }
02212 
02213   if(rechitsPS_.size()) {
02214     PreprocessRecHits( rechitsPS_ , findRecHitNeighbours_);
02215   }
02216 
02217   if ( recTracks_.size() ) { 
02218     PreprocessRecTracks( recTracks_);
02219   }
02220 
02221   if ( displacedRecTracks_.size() ) { 
02222     cout << "preprocessing rec tracks" << endl;
02223     PreprocessRecTracks( displacedRecTracks_);
02224   }
02225 
02226 
02227   if(gsfrecTracks_.size()) {
02228     PreprocessRecTracks( gsfrecTracks_);
02229   }
02230    
02231   if(convBremGsfrecTracks_.size()) {
02232     PreprocessRecTracks( convBremGsfrecTracks_);
02233   }
02234 
02235   return goodevent;
02236 }
02237 
02238 
02239 bool PFRootEventManager::isHadronicTau() const {
02240 
02241   for ( unsigned i=0;  i < trueParticles_.size(); i++) {
02242     const reco::PFSimParticle& ptc = trueParticles_[i];
02243     const std::vector<int>& ptcdaughters = ptc.daughterIds();
02244     if (std::abs(ptc.pdgCode()) == 15) {
02245       for ( unsigned int dapt=0; dapt < ptcdaughters.size(); ++dapt) {
02246         
02247         const reco::PFSimParticle& daughter 
02248           = trueParticles_[ptcdaughters[dapt]];
02249         
02250 
02251         int pdgdaugther = daughter.pdgCode();
02252         int abspdgdaughter = std::abs(pdgdaugther);
02253 
02254 
02255         if (abspdgdaughter == 11 || 
02256             abspdgdaughter == 13) { 
02257           return false; 
02258         }//electron or muons?
02259       }//loop daughter
02260     }//tau
02261   }//loop particles
02262 
02263 
02264   return true;
02265 }
02266 
02267 
02268 
02269 bool PFRootEventManager::countChargedAndPhotons() const {
02270   
02271   int nPhoton = 0;
02272   int nCharged = 0;
02273   
02274   for ( unsigned i=0;  i < trueParticles_.size(); i++) {
02275     const reco::PFSimParticle& ptc = trueParticles_[i];
02276    
02277     const std::vector<int>& daughters = ptc.daughterIds();
02278 
02279     // if the particle decays before ECAL, we do not want to 
02280     // consider it.
02281     if(!daughters.empty() ) continue; 
02282 
02283     double charge = ptc.charge();
02284     double pdgCode = ptc.pdgCode();
02285     
02286     if( std::abs(charge)>1e-9) 
02287       nCharged++;
02288     else if( pdgCode==22 )
02289       nPhoton++;
02290   }    
02291 
02292   //   const HepMC::GenEvent* myGenEvent = MCTruth_.GetEvent();
02293   //   if(!myGenEvent) {
02294   //     cerr<<"impossible to filter on the number of charged and "
02295   //    <<"neutral particles without the HepMCProduct. "
02296   //    <<"Please check that the branch edmHepMCProduct_*_*_* is found"<<endl;
02297   //     exit(1);
02298   //   }
02299   
02300   //   for ( HepMC::GenEvent::particle_const_iterator 
02301   //      piter  = myGenEvent->particles_begin();
02302   //    piter != myGenEvent->particles_end(); 
02303   //    ++piter ) {
02304     
02305   //     const HepMC::GenParticle* p = *piter;
02306   //     int partId = p->pdg_id();Long64_t lines = T->ReadFile("mon_fichier","i:j:k:x:y:z");
02307     
02308   // //     pdgTable_->GetParticle( partId )->Print();
02309        
02310   //     int charge = chargeValue(partId);
02311   //     cout<<partId <<" "<<charge/3.<<endl;
02312 
02313   //     if(charge) 
02314   //       nCharged++;
02315   //     else 
02316   //       nNeutral++;
02317   //   }
02318   
02319   if( nCharged == filterTaus_[0] && 
02320       nPhoton == filterTaus_[1]  )
02321     return true;
02322   else 
02323     return false;
02324 }
02325 
02326 
02327 
02328 int PFRootEventManager::chargeValue(const int& Id) const {
02329 
02330   
02331   //...Purpose: to give three times the charge for a particle/parton.
02332 
02333   //      ID     = particle ID
02334   //      hepchg = particle charge times 3
02335 
02336   int kqa,kq1,kq2,kq3,kqj,irt,kqx,kqn;
02337   int hepchg;
02338 
02339 
02340   int ichg[109]={-1,2,-1,2,-1,2,-1,2,0,0,-3,0,-3,0,-3,0,
02341                  -3,0,0,0,0,0,0,3,0,0,0,0,0,0,3,0,3,6,0,0,3,6,0,0,-1,2,-1,2,-1,2,0,0,0,0,
02342                  -3,0,-3,0,-3,0,0,0,0,0,-1,2,-1,2,-1,2,0,0,0,0,
02343                  -3,0,-3,0,-3,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
02344 
02345 
02346   //...Initial values. Simple case of direct readout.
02347   hepchg=0;
02348   kqa=std::abs(Id);
02349   kqn=kqa/1000000000%10;
02350   kqx=kqa/1000000%10;
02351   kq3=kqa/1000%10;
02352   kq2=kqa/100%10;
02353   kq1=kqa/10%10;
02354   kqj=kqa%10;
02355   irt=kqa%10000;
02356 
02357   //...illegal or ion
02358   //...set ion charge to zero - not enough information
02359   if(kqa==0 || kqa >= 10000000) {
02360 
02361     if(kqn==1) {hepchg=0;}
02362   }
02363   //... direct translation
02364   else if(kqa<=100) {hepchg = ichg[kqa-1];}
02365   //... deuteron or tritium
02366   else if(kqa==100 || kqa==101) {hepchg = -3;}
02367   //... alpha or He3
02368   else if(kqa==102 || kqa==104) {hepchg = -6;}
02369   //... KS and KL (and undefined)
02370   else if(kqj == 0) {hepchg = 0;}
02371   //C... direct translation
02372   else if(kqx>0 && irt<100)
02373     {
02374       hepchg = ichg[irt-1];
02375       if(kqa==1000017 || kqa==1000018) {hepchg = 0;}
02376       if(kqa==1000034 || kqa==1000052) {hepchg = 0;}
02377       if(kqa==1000053 || kqa==1000054) {hepchg = 0;}
02378       if(kqa==5100061 || kqa==5100062) {hepchg = 6;}
02379     }
02380   //...Construction from quark content for heavy meson, diquark, baryon.
02381   //...Mesons.
02382   else if(kq3==0)
02383     {
02384       hepchg = ichg[kq2-1]-ichg[kq1-1];
02385       //...Strange or beauty mesons.
02386       if((kq2==3) || (kq2==5)) {hepchg = ichg[kq1-1]-ichg[kq2-1];}
02387     }
02388   else if(kq1 == 0) {
02389     //...Diquarks.
02390     hepchg = ichg[kq3-1] + ichg[kq2-1];
02391   }
02392 
02393   else{
02394     //...Baryons
02395     hepchg = ichg[kq3-1]+ichg[kq2-1]+ichg[kq1-1];
02396   }
02397 
02398   //... fix sign of charge
02399   if(Id<0 && hepchg!=0) {hepchg = -1*hepchg;}
02400 
02401   // cout << hepchg<< endl;
02402   return hepchg;
02403 }
02404 
02405 
02406 
02407 void 
02408 PFRootEventManager::PreprocessRecTracks(reco::PFRecTrackCollection& recTracks) {  
02409   for( unsigned i=0; i<recTracks.size(); ++i ) {     
02410     recTracks[i].calculatePositionREP();
02411   }
02412 }
02413 
02414 void 
02415 PFRootEventManager::PreprocessRecTracks(reco::GsfPFRecTrackCollection& recTracks) {  
02416   for( unsigned i=0; i<recTracks.size(); ++i ) {     
02417     recTracks[i].calculatePositionREP();
02418     recTracks[i].calculateBremPositionREP();
02419   }
02420 }
02421 
02422 
02423  
02424 void 
02425 PFRootEventManager::PreprocessRecHits(reco::PFRecHitCollection& rechits, 
02426                                       bool findNeighbours) {
02427   
02428  
02429   map<unsigned, unsigned> detId2index;
02430 
02431   for(unsigned i=0; i<rechits.size(); i++) { 
02432     rechits[i].calculatePositionREP();
02433     
02434     if(findNeighbours) 
02435       detId2index.insert( make_pair(rechits[i].detId(), i) );
02436   }
02437   
02438   if(findNeighbours) {
02439     for(unsigned i=0; i<rechits.size(); i++) { 
02440       setRecHitNeigbours( rechits[i], detId2index );
02441     }
02442   }
02443 }
02444 
02445 
02446 void PFRootEventManager::setRecHitNeigbours
02447 ( reco::PFRecHit& rh, 
02448   const map<unsigned, unsigned>& detId2index ) {
02449 
02450   rh.clearNeighbours();
02451 
02452   vector<unsigned> neighbours4DetId = rh.neighboursIds4();
02453   vector<unsigned> neighbours8DetId = rh.neighboursIds8();
02454   
02455   for( unsigned i=0; i<neighbours4DetId.size(); i++) {
02456     unsigned detId = neighbours4DetId[i];
02457     //     cout<<"finding n for detId "<<detId<<endl;
02458     const map<unsigned, unsigned>::const_iterator& it = detId2index.find(detId);
02459     
02460     if(it != detId2index.end() ) {
02461       //       cout<<"found n index "<<it->second<<endl;
02462       rh.add4Neighbour( it->second );
02463     }
02464   }
02465 
02466   for( unsigned i=0; i<neighbours8DetId.size(); i++) {
02467     unsigned detId = neighbours8DetId[i];
02468     //     cout<<"finding n for detId "<<detId<<endl;
02469     const map<unsigned, unsigned>::const_iterator& it = detId2index.find(detId);
02470     
02471     if(it != detId2index.end() ) {
02472       //       cout<<"found n index "<<it->second<<endl;
02473       rh.add8Neighbour( it->second );
02474     }
02475   }
02476 
02477   
02478 }
02479 
02480 
02481 void PFRootEventManager::clustering() {
02482 
02483   if (verbosity_ == VERBOSE ) {
02484     cout <<"start clustering"<<endl;
02485   }
02486   
02487   // ECAL clustering -------------------------------------------
02488 
02489   vector<bool> mask;
02490   fillRecHitMask( mask, rechitsECAL_ );
02491   clusterAlgoECAL_.setMask( mask );  
02492 
02493   //   edm::OrphanHandle< reco::PFRecHitCollection > rechitsHandleECAL( &rechitsECAL_, edm::ProductID(10001) );
02494   clusterAlgoECAL_.doClustering( rechitsECAL_ );
02495   clustersECAL_ = clusterAlgoECAL_.clusters();
02496 
02497   assert(clustersECAL_.get() );
02498 
02499   fillOutEventWithClusters( *clustersECAL_ );
02500 
02501   // HCAL clustering -------------------------------------------
02502 
02503   fillRecHitMask( mask, rechitsHCAL_ );
02504   clusterAlgoHCAL_.setMask( mask );  
02505   //   edm::OrphanHandle< reco::PFRecHitCollection > rechitsHandleHCAL( &rechitsHCAL_, edm::ProductID(10002) );
02506   clusterAlgoHCAL_.doClustering( rechitsHCAL_ );
02507   clustersHCAL_ = clusterAlgoHCAL_.clusters();
02508 
02509   fillOutEventWithClusters( *clustersHCAL_ );
02510 
02511   // HF clustering -------------------------------------------
02512 
02513   fillRecHitMask( mask, rechitsHFEM_ );
02514   clusterAlgoHFEM_.setMask( mask );  
02515   clusterAlgoHFEM_.doClustering( rechitsHFEM_ );
02516   clustersHFEM_ = clusterAlgoHFEM_.clusters();
02517   
02518   fillRecHitMask( mask, rechitsHFHAD_ );
02519   clusterAlgoHFHAD_.setMask( mask );  
02520   clusterAlgoHFHAD_.doClustering( rechitsHFHAD_ );
02521   clustersHFHAD_ = clusterAlgoHFHAD_.clusters();
02522   
02523 
02524   // PS clustering -------------------------------------------
02525 
02526   fillRecHitMask( mask, rechitsPS_ );
02527   clusterAlgoPS_.setMask( mask );  
02528   //   edm::OrphanHandle< reco::PFRecHitCollection > rechitsHandlePS( &rechitsPS_, edm::ProductID(10003) );
02529   clusterAlgoPS_.doClustering( rechitsPS_ );
02530   clustersPS_ = clusterAlgoPS_.clusters();
02531 
02532   fillOutEventWithClusters( *clustersPS_ );
02533   
02534 }
02535 
02536 
02537 
02538 void 
02539 PFRootEventManager::fillOutEventWithClusters(const reco::PFClusterCollection& 
02540                                              clusters) {
02541 
02542   if(!outEvent_) return;
02543   
02544   for(unsigned i=0; i<clusters.size(); i++) {
02545     EventColin::Cluster cluster;
02546     cluster.eta = clusters[i].position().Eta();
02547     cluster.phi = clusters[i].position().Phi();
02548     cluster.e = clusters[i].energy();
02549     cluster.layer = clusters[i].layer();
02550     cluster.type = 1;
02551 
02552     reco::PFTrajectoryPoint::LayerType tpLayer = 
02553       reco::PFTrajectoryPoint::NLayers;
02554     switch( clusters[i].layer() ) {
02555     case PFLayer::ECAL_BARREL:
02556     case PFLayer::ECAL_ENDCAP:
02557       tpLayer = reco::PFTrajectoryPoint::ECALEntrance;
02558       break;
02559     case PFLayer::HCAL_BARREL1:
02560     case PFLayer::HCAL_ENDCAP:
02561       tpLayer = reco::PFTrajectoryPoint::HCALEntrance;
02562       break;
02563     default:
02564       break;
02565     }
02566     if(tpLayer < reco::PFTrajectoryPoint::NLayers) {
02567       try {
02568         double peta = -10;
02569         double phi = -10;
02570         double pe = -10;
02571         
02572         const reco::PFSimParticle& ptc 
02573           = closestParticle( tpLayer, 
02574                              cluster.eta, cluster.phi, 
02575                              peta, phi, pe );
02576 
02577         
02578         cluster.particle.eta = peta;
02579         cluster.particle.phi = phi;
02580         cluster.particle.e = pe;
02581         cluster.particle.pdgCode = ptc.pdgCode();
02582         
02583         
02584       }
02585       catch( std::exception& err ) {
02586         // cerr<<err.what()<<endl;
02587       } 
02588     }
02589 
02590     outEvent_->addCluster(cluster);
02591   }   
02592 }
02593 
02594 
02595 void 
02596 PFRootEventManager::fillOutEventWithSimParticles(const reco::PFSimParticleCollection& trueParticles ) {
02597 
02598   if(!outEvent_) return;
02599   
02600   for ( unsigned i=0;  i < trueParticles.size(); i++) {
02601 
02602     const reco::PFSimParticle& ptc = trueParticles[i];
02603 
02604     unsigned ntrajpoints = ptc.nTrajectoryPoints();
02605     
02606     if(ptc.daughterIds().empty() ) { // stable
02607       reco::PFTrajectoryPoint::LayerType ecalEntrance 
02608         = reco::PFTrajectoryPoint::ECALEntrance;
02609 
02610       if(ntrajpoints == 3) { 
02611         // old format for PFSimCandidates. 
02612         // in this case, the PFSimCandidate which does not decay 
02613         // before ECAL has 3 points: initial, ecal entrance, hcal entrance
02614         ecalEntrance = static_cast<reco::PFTrajectoryPoint::LayerType>(1);
02615       }
02616       // else continue; // endcap case we do not care;
02617 
02618       const reco::PFTrajectoryPoint& tpatecal 
02619         = ptc.extrapolatedPoint( ecalEntrance );
02620         
02621       EventColin::Particle outptc;
02622       outptc.eta = tpatecal.position().Eta();
02623       outptc.phi = tpatecal.position().Phi();    
02624       outptc.e = tpatecal.momentum().E();
02625       outptc.pdgCode = ptc.pdgCode();
02626     
02627       
02628       outEvent_->addParticle(outptc);
02629     }  
02630   }   
02631 }      
02632 
02633 void 
02634 PFRootEventManager::fillOutEventWithPFCandidates(const reco::PFCandidateCollection& pfCandidates ) {
02635 
02636   if(!outEvent_) return;
02637   
02638   for ( unsigned i=0;  i < pfCandidates.size(); i++) {
02639 
02640     const reco::PFCandidate& candidate = pfCandidates[i];
02641     
02642     EventColin::Particle outptc;
02643     outptc.eta = candidate.eta();
02644     outptc.phi = candidate.phi();    
02645     outptc.e = candidate.energy();
02646     outptc.pdgCode = candidate.particleId();
02647     
02648     
02649     outEvent_->addCandidate(outptc);  
02650   }   
02651 }      
02652 
02653 
02654 void 
02655 PFRootEventManager::fillOutEventWithCaloTowers( const CaloTowerCollection& cts ){
02656 
02657   if(!outEvent_) return;
02658   
02659   for ( unsigned i=0;  i < cts.size(); i++) {
02660 
02661     const CaloTower& ct = cts[i];
02662     
02663     EventColin::CaloTower outct;
02664     outct.e  = ct.energy();
02665     outct.ee = ct.emEnergy();
02666     outct.eh = ct.hadEnergy();
02667 
02668     outEvent_->addCaloTower( outct );
02669   }
02670 }
02671 
02672 
02673 void 
02674 PFRootEventManager::fillOutEventWithBlocks( const reco::PFBlockCollection& 
02675                                             blocks ) {
02676 
02677   if(!outEvent_) return;
02678   
02679   for ( unsigned i=0;  i < blocks.size(); i++) {
02680 
02681     //    const reco::PFBlock& block = blocks[i];
02682     
02683     EventColin::Block outblock;
02684  
02685     outEvent_->addBlock( outblock );
02686   }
02687 }
02688 
02689 
02690 
02691 void PFRootEventManager::particleFlow() {
02692   
02693   if (verbosity_ == VERBOSE ) {
02694     cout <<"start particle flow"<<endl;
02695   }
02696 
02697 
02698   if( debug_) {
02699     cout<<"PFRootEventManager::particleFlow start"<<endl;
02700     //     cout<<"number of elements in memory: "
02701     //  <<reco::PFBlockElement::instanceCounter()<<endl;
02702   }
02703 
02704 
02705   edm::OrphanHandle< reco::PFRecTrackCollection > trackh( &recTracks_, 
02706                                                           edm::ProductID(1) );  
02707   
02708   edm::OrphanHandle< reco::PFRecTrackCollection > displacedtrackh( &displacedRecTracks_, 
02709                                                           edm::ProductID(77) );  
02710 
02711   edm::OrphanHandle< reco::PFClusterCollection > ecalh( clustersECAL_.get(), 
02712                                                         edm::ProductID(2) );  
02713   
02714   edm::OrphanHandle< reco::PFClusterCollection > hcalh( clustersHCAL_.get(), 
02715                                                         edm::ProductID(3) );  
02716 
02717   edm::OrphanHandle< reco::PFClusterCollection > hfemh( clustersHFEM_.get(), 
02718                                                         edm::ProductID(31) );  
02719 
02720   edm::OrphanHandle< reco::PFClusterCollection > hfhadh( clustersHFHAD_.get(), 
02721                                                         edm::ProductID(32) );  
02722 
02723   edm::OrphanHandle< reco::PFClusterCollection > psh( clustersPS_.get(), 
02724                                                       edm::ProductID(4) );   
02725   
02726   edm::OrphanHandle< reco::GsfPFRecTrackCollection > gsftrackh( &gsfrecTracks_, 
02727                                                                 edm::ProductID(5) );  
02728   
02729   edm::OrphanHandle< reco::MuonCollection > muonh( &muons_, 
02730                                                    edm::ProductID(6) );
02731 
02732   edm::OrphanHandle< reco::PFDisplacedTrackerVertexCollection > nuclearh( &pfNuclearTrackerVertex_, 
02733                                                           edm::ProductID(7) );
02734 
02735 
02736   //recoPFRecTracks_pfNuclearTrackerVertex__TEST.
02737 
02738   edm::OrphanHandle< reco::PFConversionCollection > convh( &conversion_, 
02739                                                            edm::ProductID(8) );
02740 
02741   edm::OrphanHandle< reco::PFV0Collection > v0( &v0_, 
02742                                                 edm::ProductID(9) );
02743 
02744 
02745   edm::OrphanHandle< reco::VertexCollection > vertexh( &primaryVertices_, 
02746                                                        edm::ProductID(10) );  
02747 
02748   edm::OrphanHandle< reco::GsfPFRecTrackCollection > convBremGsftrackh( &convBremGsfrecTracks_, 
02749                                                                         edm::ProductID(11) );  
02750   
02751   vector<bool> trackMask;
02752   fillTrackMask( trackMask, recTracks_ );
02753   vector<bool> gsftrackMask;
02754   fillTrackMask( gsftrackMask, gsfrecTracks_ );
02755   vector<bool> ecalMask;
02756   fillClusterMask( ecalMask, *clustersECAL_ );
02757   vector<bool> hcalMask;
02758   fillClusterMask( hcalMask, *clustersHCAL_ );
02759   vector<bool> hfemMask;
02760   fillClusterMask( hfemMask, *clustersHFEM_ );
02761   vector<bool> hfhadMask;
02762   fillClusterMask( hfhadMask, *clustersHFHAD_ );
02763   vector<bool> psMask;
02764   fillClusterMask( psMask, *clustersPS_ );
02765   
02766   
02767   if ( !useAtHLT )
02768     pfBlockAlgo_.setInput( trackh, gsftrackh, convBremGsftrackh,
02769                            muonh, nuclearh, displacedtrackh, convh, v0,
02770                            ecalh, hcalh, hfemh, hfhadh, psh,
02771                            trackMask,gsftrackMask,
02772                            ecalMask, hcalMask, hfemMask, hfhadMask, psMask );
02773   else    
02774     pfBlockAlgo_.setInput( trackh, ecalh, hcalh, hfemh, hfhadh, psh,
02775                            trackMask, ecalMask, hcalMask, psMask );
02776 
02777   pfBlockAlgo_.findBlocks();
02778   
02779   if( debug_) cout<<pfBlockAlgo_<<endl;
02780 
02781   pfBlocks_ = pfBlockAlgo_.transferBlocks();
02782 
02783   pfAlgo_.setPFVertexParameters(true, primaryVertices_); 
02784 
02785   pfAlgo_.reconstructParticles( *pfBlocks_.get() );
02786   //   pfAlgoOther_.reconstructParticles( blockh );
02787 
02788   pfAlgo_.postMuonCleaning(muonsHandle_, *vertexh);
02789 
02790   pfAlgo_.checkCleaning( rechitsCLEANED_ );
02791 
02792   if( debug_) cout<< pfAlgo_<<endl;
02793   pfCandidates_ = pfAlgo_.transferCandidates();
02794   //   pfCandidatesOther_ = pfAlgoOther_.transferCandidates();
02795   
02796   fillOutEventWithPFCandidates( *pfCandidates_ );
02797 
02798   if( debug_) cout<<"PFRootEventManager::particleFlow stop"<<endl;
02799 }
02800 
02801 void PFRootEventManager::pfCandCompare(int entry) {
02802 
02803   bool differentSize = pfCandCMSSW_.size() != pfCandidates_->size();
02804   if ( differentSize ) { 
02805     cout << "+++WARNING+++ PFCandidate size changed for entry " 
02806          << entry << " !" << endl
02807          << " - original size : " << pfCandCMSSW_.size() << endl 
02808          << " - current  size : " << pfCandidates_->size() << endl;
02809   } else { 
02810     for(unsigned i=0; i<pfCandidates_->size(); i++) {
02811       double deltaE = (*pfCandidates_)[i].energy()-pfCandCMSSW_[i].energy();
02812       double deltaEta = (*pfCandidates_)[i].eta()-pfCandCMSSW_[i].eta();
02813       double deltaPhi = (*pfCandidates_)[i].phi()-pfCandCMSSW_[i].phi();
02814       if ( fabs(deltaE) > 1E-5 ||
02815            fabs(deltaEta) > 1E-9 ||
02816            fabs(deltaPhi) > 1E-9 ) { 
02817         cout << "+++WARNING+++ PFCandidate " << i 
02818              << " changed  for entry " << entry << " ! " << endl 
02819              << " - Original : " << pfCandCMSSW_[i] << endl
02820              << " - Current  : " << (*pfCandidates_)[i] << endl
02821              << " DeltaE   = : " << deltaE << endl
02822              << " DeltaEta = : " << deltaEta << endl
02823              << " DeltaPhi = : " << deltaPhi << endl << endl;
02824       }
02825     }
02826   }
02827 
02828 }
02829 
02830 
02831 void PFRootEventManager::reconstructGenJets() {
02832 
02833   if (verbosity_ == VERBOSE || jetsDebug_) {
02834     cout<<endl;
02835     cout<<"start reconstruct GenJets  --- "<<endl;
02836     cout<< " input gen particles for jet: all neutrinos removed ; muons present" << endl;
02837   }
02838 
02839   genJets_.clear();
02840   genParticlesforJetsPtrs_.clear();
02841 
02842   if ( !genParticlesforJets_.size() ) return;
02843 
02844   for(unsigned i=0; i<genParticlesforJets_.size(); i++) {
02845 
02846     const reco::GenParticle&    genPart = *(genParticlesforJets_[i]);
02847 
02848     // remove all muons/neutrinos for PFJet studies
02849     //    if (reco::isNeutrino( genPart ) || reco::isMuon( genPart )) continue;
02850     //    remove all neutrinos for PFJet studies
02851     if (reco::isNeutrino( genPart )) continue;
02852     // Work-around a bug in the pythia di-jet gun.
02853     if (std::abs(genPart.pdgId())<7 || std::abs(genPart.pdgId())==21 ) continue;
02854 
02855     if (jetsDebug_ ) {
02856       cout << "      #" << i << "  PDG code:" << genPart.pdgId() 
02857            << " status " << genPart.status()
02858            << ", p/pt/eta/phi: " << genPart.p() << '/' << genPart.pt() 
02859            << '/' << genPart.eta() << '/' << genPart.phi() << endl;
02860     }
02861     
02862     genParticlesforJetsPtrs_.push_back( refToPtr(genParticlesforJets_[i]) );
02863   }
02864   
02865   vector<ProtoJet> protoJets;
02866   reconstructFWLiteJets(genParticlesforJetsPtrs_, protoJets );
02867 
02868 
02869   // Convert Protojets to GenJets
02870   int ijet = 0;
02871   typedef vector <ProtoJet>::const_iterator IPJ;
02872   for  (IPJ ipj = protoJets.begin(); ipj != protoJets.end (); ipj++) {
02873     const ProtoJet& protojet = *ipj;
02874     const ProtoJet::Constituents& constituents = protojet.getTowerList();
02875           
02876     reco::Jet::Point vertex (0,0,0); // do not have true vertex yet, use default
02877     GenJet::Specific specific;
02878     JetMaker::makeSpecific(constituents, &specific);
02879     // constructor without constituents
02880     GenJet newJet (protojet.p4(), vertex, specific);
02881           
02882     // last step is to copy the constituents into the jet (new jet definition since 18X)
02883     // namespace reco {
02884     //class Jet : public CompositeRefBaseCandidate {
02885     // public:
02886     //  typedef reco::CandidateBaseRefVector Constituents;
02887           
02888     ProtoJet::Constituents::const_iterator constituent = constituents.begin();
02889     for (; constituent != constituents.end(); ++constituent) {
02890       // find index of this ProtoJet constituent in the overall collection PFconstit
02891       // see class IndexedCandidate in JetRecoTypes.h
02892       uint index = constituent->index();
02893       newJet.addDaughter( genParticlesforJetsPtrs_[index] );
02894     }  // end loop on ProtoJet constituents
02895     // last step: copy ProtoJet Variables into Jet
02896     newJet.setJetArea(protojet.jetArea()); 
02897     newJet.setPileup(protojet.pileup());
02898     newJet.setNPasses(protojet.nPasses());
02899     ++ijet;
02900     if (jetsDebug_ ) cout<<" gen jet "<<ijet<<" "<<newJet.print()<<endl;
02901     genJets_.push_back (newJet);
02902           
02903   } // end loop on protojets iterator IPJ
02904   
02905 }
02906 
02907 void PFRootEventManager::reconstructCaloJets() {
02908 
02909   if (verbosity_ == VERBOSE || jetsDebug_ ) {
02910     cout<<endl;
02911     cout<<"start reconstruct CaloJets --- "<<endl;
02912   }
02913   caloJets_.clear();
02914   caloTowersPtrs_.clear();
02915 
02916   for( unsigned i=0; i<caloTowers_.size(); i++) {
02917     reco::CandidatePtr candPtr( &caloTowers_, i );
02918     caloTowersPtrs_.push_back( candPtr );
02919   }
02920  
02921   reconstructFWLiteJets( caloTowersPtrs_, caloJets_ );
02922 
02923   if (jetsDebug_ ) {
02924     for(unsigned ipj=0; ipj<caloJets_.size(); ipj++) {
02925       const ProtoJet& protojet = caloJets_[ipj];      
02926       cout<<" calo jet "<<ipj<<" "<<protojet.pt() <<endl;
02927     }
02928   }
02929 
02930 }
02931 
02932 
02933 void PFRootEventManager::reconstructPFJets() {
02934 
02935   if (verbosity_ == VERBOSE || jetsDebug_) {
02936     cout<<endl;
02937     cout<<"start reconstruct PF Jets --- "<<endl;
02938   }
02939   pfJets_.clear();
02940   pfCandidatesPtrs_.clear();
02941         
02942   for( unsigned i=0; i<pfCandidates_->size(); i++) {
02943     reco::CandidatePtr candPtr( pfCandidates_.get(), i );
02944     pfCandidatesPtrs_.push_back( candPtr );
02945   }
02946 
02947   vector<ProtoJet> protoJets;
02948   reconstructFWLiteJets(pfCandidatesPtrs_, protoJets );
02949 
02950   // Convert Protojets to PFJets
02951 
02952   int ijet = 0;
02953   typedef vector <ProtoJet>::const_iterator IPJ;
02954   for  (IPJ ipj = protoJets.begin(); ipj != protoJets.end (); ipj++) {
02955     const ProtoJet& protojet = *ipj;
02956     const ProtoJet::Constituents& constituents = protojet.getTowerList();
02957         
02958     reco::Jet::Point vertex (0,0,0); // do not have true vertex yet, use default
02959     PFJet::Specific specific;
02960     JetMaker::makeSpecific(constituents, &specific);
02961     // constructor without constituents
02962     PFJet newJet (protojet.p4(), vertex, specific);
02963         
02964     // last step is to copy the constituents into the jet (new jet definition since 18X)
02965     // namespace reco {
02966     //class Jet : public CompositeRefBaseCandidate {
02967     // public:
02968     //  typedef reco::CandidateBaseRefVector Constituents;
02969         
02970     ProtoJet::Constituents::const_iterator constituent = constituents.begin();
02971     for (; constituent != constituents.end(); ++constituent) {
02972       // find index of this ProtoJet constituent in the overall collection PFconstit
02973       // see class IndexedCandidate in JetRecoTypes.h
02974       uint index = constituent->index();
02975       newJet.addDaughter(pfCandidatesPtrs_[index]);
02976     }  // end loop on ProtoJet constituents
02977     // last step: copy ProtoJet Variables into Jet
02978     newJet.setJetArea(protojet.jetArea()); 
02979     newJet.setPileup(protojet.pileup());
02980     newJet.setNPasses(protojet.nPasses());
02981     ++ijet;
02982     if (jetsDebug_ )  cout<<" PF jet "<<ijet<<" "<<newJet.print()<<endl;
02983     pfJets_.push_back (newJet);
02984         
02985   } // end loop on protojets iterator IPJ
02986 
02987 }
02988 
02989 void 
02990 PFRootEventManager::reconstructFWLiteJets(const reco::CandidatePtrVector& Candidates, vector<ProtoJet>& output ) {
02991 
02992   // cout<<"!!! Make FWLite Jets  "<<endl;  
02993   JetReco::InputCollection input;
02994   // vector<ProtoJet> output;
02995   jetMaker_.applyCuts (Candidates, &input); 
02996   if (jetAlgoType_==1) {// ICone 
02998     jetMaker_.makeIterativeConeJets(input, &output);
02999   }
03000   if (jetAlgoType_==2) {// MCone
03001     jetMaker_.makeMidpointJets(input, &output);
03002   }     
03003   if (jetAlgoType_==3) {// Fastjet
03004     jetMaker_.makeFastJets(input, &output);  
03005   }
03006   if((jetAlgoType_>3)||(jetAlgoType_<0)) {
03007     cout<<"Unknown Jet Algo ! " <<jetAlgoType_ << endl;
03008   }
03009   //if (jetsDebug_) cout<<"Proto Jet Size " <<output.size()<<endl;
03010 
03011 }
03012 
03013 
03014 
03016 double 
03017 PFRootEventManager::tauBenchmark( const reco::PFCandidateCollection& candidates) {
03018   //std::cout << "building jets from MC particles," 
03019   //    << "PF particles and caloTowers" << std::endl;
03020   
03021   //initialize Jets Reconstruction
03022   jetAlgo_.Clear();
03023 
03024   //COLIN The following comment is not really adequate, 
03025   // since partTOTMC is not an action..
03026   // one should say what this variable is for.
03027   // see my comment later 
03028   //MAKING TRUE PARTICLE JETS
03029 //   TLorentzVector partTOTMC;
03030 
03031   // colin: the following is not necessary
03032   // since the lorentz vectors are initialized to 0,0,0,0. 
03033   // partTOTMC.SetPxPyPzE(0.0, 0.0, 0.0, 0.0);
03034 
03035   //MAKING JETS WITH TAU DAUGHTERS
03036   //Colin: this vector vectPART is not necessary !!
03037   //it was just an efficient copy of trueparticles_.....
03038 //   vector<reco::PFSimParticle> vectPART;
03039 //   for ( unsigned i=0;  i < trueParticles_.size(); i++) {
03040 //     const reco::PFSimParticle& ptc = trueParticles_[i];
03041 //     vectPART.push_back(ptc);
03042 //   }//loop
03043 
03044 
03045   //COLIN one must not loop on trueParticles_ to find taus. 
03046   //the code was giving wrong results on non single tau events. 
03047 
03048   // first check that this is a single tau event. 
03049 
03050   TLorentzVector partTOTMC;
03051   bool tauFound = false;
03052   bool tooManyTaus = false;
03053   if (fastsim_){
03054 
03055     for ( unsigned i=0;  i < trueParticles_.size(); i++) {
03056       const reco::PFSimParticle& ptc = trueParticles_[i];
03057       if (std::abs(ptc.pdgCode()) == 15) {
03058         // this is a tau
03059         if( i ) tooManyTaus = true;
03060         else tauFound=true;
03061       }
03062     }
03063     
03064     if(!tauFound || tooManyTaus ) {
03065       // cerr<<"PFRootEventManager::tauBenchmark : not a single tau event"<<endl;
03066       return -9999;
03067     }
03068     
03069     // loop on the daugthers of the tau
03070     const std::vector<int>& ptcdaughters = trueParticles_[0].daughterIds();
03071     
03072     // will contain the sum of the lorentz vectors of the visible daughters
03073     // of the tau.
03074     
03075     
03076     for ( unsigned int dapt=0; dapt < ptcdaughters.size(); ++dapt) {
03077       
03078       const reco::PFTrajectoryPoint& tpatvtx 
03079         = trueParticles_[ptcdaughters[dapt]].trajectoryPoint(0);
03080       TLorentzVector partMC;
03081       partMC.SetPxPyPzE(tpatvtx.momentum().Px(),
03082                         tpatvtx.momentum().Py(),
03083                         tpatvtx.momentum().Pz(),
03084                         tpatvtx.momentum().E());
03085       
03086       partTOTMC += partMC;
03087       if (tauBenchmarkDebug_) {
03088         //pdgcode
03089         int pdgcode =  trueParticles_[ptcdaughters[dapt]].pdgCode();
03090         cout << pdgcode << endl;
03091         cout << tpatvtx << endl;
03092         cout << partMC.Px() << " " << partMC.Py() << " " 
03093              << partMC.Pz() << " " << partMC.E()
03094              << " PT=" 
03095              << sqrt(partMC.Px()*partMC.Px()+partMC.Py()*partMC.Py()) 
03096              << endl;
03097       }//debug
03098     }//loop daughter
03099   }else{
03100 
03101     uint itau=0;
03102     const HepMC::GenEvent* myGenEvent = MCTruth_.GetEvent();
03103     for ( HepMC::GenEvent::particle_const_iterator 
03104             piter  = myGenEvent->particles_begin();
03105           piter != myGenEvent->particles_end(); 
03106           ++piter ) {
03107       
03108     
03109       if (std::abs((*piter)->pdg_id())==15){
03110         itau++;
03111         tauFound=true;
03112         for ( HepMC::GenVertex::particles_out_const_iterator bp =
03113                 (*piter)->end_vertex()->particles_out_const_begin();
03114               bp != (*piter)->end_vertex()->particles_out_const_end(); ++bp ) {
03115           uint nuId=std::abs((*bp)->pdg_id());
03116           bool isNeutrino=(nuId==12)||(nuId==14)||(nuId==16);
03117           if (!isNeutrino){
03118             
03119 
03120             TLorentzVector partMC;
03121             partMC.SetPxPyPzE((*bp)->momentum().x(),
03122                               (*bp)->momentum().y(),
03123                               (*bp)->momentum().z(),
03124                               (*bp)->momentum().e());
03125             partTOTMC += partMC;
03126           }
03127         }
03128       }
03129     }
03130     if (itau>1) tooManyTaus=true;
03131 
03132     if(!tauFound || tooManyTaus ) {
03133       cerr<<"PFRootEventManager::tauBenchmark : not a single tau event"<<endl;
03134       return -9999;
03135     }
03136   }
03137 
03138 
03139 
03140 
03141 
03142 
03143 
03144   EventColin::Jet jetmc;
03145 
03146   jetmc.eta = partTOTMC.Eta();
03147   jetmc.phi = partTOTMC.Phi();
03148   jetmc.et = partTOTMC.Et();
03149   jetmc.e = partTOTMC.E();
03150   
03151   if(outEvent_) outEvent_->addJetMC( jetmc );
03152 
03153   /*
03154   //MC JETS RECONSTRUCTION (visible energy)
03155   for ( unsigned i=0;  i < trueParticles_.size(); i++) {
03156   const reco::PFSimParticle& ptc = trueParticles_[i];
03157   const std::vector<int>& ptcdaughters = ptc.daughterIds();
03158     
03159   //PARTICULE NOT DISINTEGRATING BEFORE ECAL
03160   if(ptcdaughters.size() != 0) continue;
03161     
03162   //TAKE INFO AT VERTEX //////////////////////////////////////////////////
03163   const reco::PFTrajectoryPoint& tpatvtx = ptc.trajectoryPoint(0);
03164   TLorentzVector partMC;
03165   partMC.SetPxPyPzE(tpatvtx.momentum().Px(),
03166   tpatvtx.momentum().Py(),
03167   tpatvtx.momentum().Pz(),
03168   tpatvtx.momentum().E());
03169     
03170   partTOTMC += partMC;
03171   if (tauBenchmarkDebug_) {
03172   //pdgcode
03173   int pdgcode = ptc.pdgCode();
03174   cout << pdgcode << endl;
03175   cout << tpatvtx << endl;
03176   cout << partMC.Px() << " " << partMC.Py() << " " 
03177   << partMC.Pz() << " " << partMC.E() 
03178   << " PT=" 
03179   << sqrt(partMC.Px()*partMC.Px()+partMC.Py()*partMC.Py()) 
03180   << endl;
03181   }//debug?
03182   }//loop true particles
03183   */
03184   if (tauBenchmarkDebug_) {
03185     cout << " ET Vector=" << partTOTMC.Et() 
03186          << " " << partTOTMC.Eta() 
03187          << " " << partTOTMC.Phi() << endl; cout << endl;
03188   }//debug
03189 
03191   //CALO TOWER JETS (ECAL+HCAL Towers)
03192   //cout << endl;  
03193   //cout << "THERE ARE " << caloTowers_.size() << " CALO TOWERS" << endl;
03194 
03195   vector<TLorentzVector> allcalotowers;
03196   //   vector<double>         allemenergy;
03197   //   vector<double>         allhadenergy;
03198   double threshCaloTowers = 1E-10;
03199   for ( unsigned int i = 0; i < caloTowers_.size(); ++i) {
03200     
03201     if(caloTowers_[i].energy() < threshCaloTowers) {
03202       //     cout<<"skipping calotower"<<endl;
03203       continue;
03204     }
03205 
03206     TLorentzVector caloT;
03207     TVector3 pepr( caloTowers_[i].eta(),
03208                    caloTowers_[i].phi(),
03209                    caloTowers_[i].energy());
03210     TVector3 pxyz = Utils::VectorEPRtoXYZ( pepr );
03211     caloT.SetPxPyPzE(pxyz.X(),pxyz.Y(),pxyz.Z(),caloTowers_[i].energy());
03212     allcalotowers.push_back(caloT);
03213     //     allemenergy.push_back( caloTowers_[i].emEnergy() );
03214     //     allhadenergy.push_back( caloTowers_[i].hadEnergy() );
03215   }//loop calo towers
03216   if ( tauBenchmarkDebug_)  
03217     cout << " RETRIEVED " << allcalotowers.size() 
03218          << " CALOTOWER 4-VECTORS " << endl;
03219   
03220   //ECAL+HCAL tower jets computation
03221   jetAlgo_.Clear();
03222   const vector< PFJetAlgorithm::Jet >&  caloTjets 
03223     = jetAlgo_.FindJets( &allcalotowers );
03224   
03225   //cout << caloTjets.size() << " CaloTower Jets found" << endl;
03226   double JetEHTETmax = 0.0;
03227   for ( unsigned i = 0; i < caloTjets.size(); i++) {
03228     TLorentzVector jetmom = caloTjets[i].GetMomentum();
03229     double jetcalo_pt = sqrt(jetmom.Px()*jetmom.Px()+jetmom.Py()*jetmom.Py());
03230     double jetcalo_et = jetmom.Et();
03231 
03232 
03233 
03234     EventColin::Jet jet;
03235     jet.eta = jetmom.Eta();
03236     jet.phi = jetmom.Phi();
03237     jet.et  = jetmom.Et();
03238     jet.e   = jetmom.E();
03239     
03240     const vector<int>& indexes = caloTjets[i].GetIndexes();
03241     for( unsigned ii=0; ii<indexes.size(); ii++){
03242       jet.ee   +=  caloTowers_[ indexes[ii] ].emEnergy();
03243       jet.eh   +=  caloTowers_[ indexes[ii] ].hadEnergy();
03244       jet.ete   +=  caloTowers_[ indexes[ii] ].emEt();
03245       jet.eth   +=  caloTowers_[ indexes[ii] ].hadEt();
03246     }
03247     
03248     if(outEvent_) outEvent_->addJetEHT( jet );
03249 
03250     if ( tauBenchmarkDebug_) {
03251       cout << " ECAL+HCAL jet : " << caloTjets[i] << endl;
03252       cout << jetmom.Px() << " " << jetmom.Py() << " " 
03253            << jetmom.Pz() << " " << jetmom.E() 
03254            << " PT=" << jetcalo_pt << endl;
03255     }//debug
03256 
03257     if (jetcalo_et >= JetEHTETmax) 
03258       JetEHTETmax = jetcalo_et;
03259   }//loop MCjets
03260 
03262   //PARTICLE FLOW JETS
03263   vector<TLorentzVector> allrecparticles;
03264   //   if ( tauBenchmarkDebug_) {
03265   //     cout << endl;
03266   //     cout << " THERE ARE " << pfBlocks_.size() << " EFLOW BLOCKS" << endl;
03267   //   }//debug
03268 
03269   //   for ( unsigned iefb = 0; iefb < pfBlocks_.size(); iefb++) {
03270   //       const std::vector< PFBlockParticle >& recparticles 
03271   //    = pfBlocks_[iefb].particles();
03272 
03273   
03274   
03275   for(unsigned i=0; i<candidates.size(); i++) {
03276   
03277     //       if (tauBenchmarkDebug_) 
03278     //  cout << " there are " << recparticles.size() 
03279     //       << " particle in this block" << endl;
03280     
03281     const reco::PFCandidate& candidate = candidates[i];
03282 
03283     if (tauBenchmarkDebug_) {
03284       cout << i << " " << candidate << endl;
03285       int type = candidate.particleId();
03286       cout << " type= " << type << " " << candidate.charge() 
03287            << endl;
03288     }//debug
03289 
03290     const math::XYZTLorentzVector& PFpart = candidate.p4();
03291     
03292     TLorentzVector partRec(PFpart.Px(), 
03293                            PFpart.Py(), 
03294                            PFpart.Pz(),
03295                            PFpart.E());
03296     
03297     //loading 4-vectors of Rec particles
03298     allrecparticles.push_back( partRec );
03299 
03300   }//loop on candidates
03301   
03302 
03303   if (tauBenchmarkDebug_) 
03304     cout << " THERE ARE " << allrecparticles.size() 
03305          << " RECONSTRUCTED 4-VECTORS" << endl;
03306 
03307   jetAlgo_.Clear();
03308   const vector< PFJetAlgorithm::Jet >&  PFjets 
03309     = jetAlgo_.FindJets( &allrecparticles );
03310 
03311   if (tauBenchmarkDebug_) 
03312     cout << PFjets.size() << " PF Jets found" << endl;
03313   double JetPFETmax = 0.0;
03314   for ( unsigned i = 0; i < PFjets.size(); i++) {
03315     TLorentzVector jetmom = PFjets[i].GetMomentum();
03316     double jetpf_pt = sqrt(jetmom.Px()*jetmom.Px()+jetmom.Py()*jetmom.Py());
03317     double jetpf_et = jetmom.Et();
03318 
03319     EventColin::Jet jet;
03320     jet.eta = jetmom.Eta();
03321     jet.phi = jetmom.Phi();
03322     jet.et  = jetmom.Et();
03323     jet.e   = jetmom.E();
03324 
03325     if(outEvent_) outEvent_->addJetPF( jet );
03326 
03327     if (tauBenchmarkDebug_) {
03328       cout <<" Rec jet : "<< PFjets[i] <<endl;
03329       cout << jetmom.Px() << " " << jetmom.Py() << " " 
03330            << jetmom.Pz() << " " << jetmom.E() 
03331            << " PT=" << jetpf_pt << " eta="<< jetmom.Eta() 
03332            << " Phi=" << jetmom.Phi() << endl;
03333       cout << "------------------------------------------------" << endl;
03334     }//debug
03335     
03336     if (jetpf_et >= JetPFETmax)  
03337       JetPFETmax = jetpf_et;
03338   }//loop PF jets
03339 
03340   //fill histos
03341 
03342   double deltaEtEHT = JetEHTETmax - partTOTMC.Et();
03343   h_deltaETvisible_MCEHT_->Fill(deltaEtEHT);
03344   
03345   double deltaEt = JetPFETmax - partTOTMC.Et();
03346   h_deltaETvisible_MCPF_ ->Fill(deltaEt);
03347 
03348   if (verbosity_ == VERBOSE ) {
03349     cout << "tau benchmark E_T(PF) - E_T(true) = " << deltaEt << endl;
03350   }
03351 
03352   return deltaEt/partTOTMC.Et();
03353 }//Makejets
03354 
03355 
03356 
03357 
03358 
03359 /*
03360 
03361 void PFRootEventManager::lookForGenParticle(unsigned barcode) {
03362   
03363 const HepMC::GenEvent* event = MCTruth_.GetEvent();
03364 if(!event) {
03365 cerr<<"no GenEvent"<<endl;
03366 return;
03367 }
03368   
03369 const HepMC::GenParticle* particle = event->barcode_to_particle(barcode);
03370 if(!particle) {
03371 cerr<<"no particle with barcode "<<barcode<<endl;
03372 return;
03373 }
03374 
03375 math::XYZTLorentzVector momentum(particle->momentum().px(),
03376 particle->momentum().py(),
03377 particle->momentum().pz(),
03378 particle->momentum().e());
03379 
03380 double eta = momentum.Eta();
03381 double phi = momentum.phi();
03382 
03383 double phisize = 0.05;
03384 double etasize = 0.05;
03385   
03386 double etagate = displayZoomFactor_ * etasize;
03387 double phigate = displayZoomFactor_ * phisize;
03388   
03389 if(displayHist_[EPE]) {
03390 displayHist_[EPE]->GetXaxis()->SetRangeUser(eta-etagate, eta+etagate);
03391 displayHist_[EPE]->GetYaxis()->SetRangeUser(phi-phigate, phi+phigate);
03392 }
03393 if(displayHist_[EPH]) {
03394 displayHist_[EPH]->GetXaxis()->SetRangeUser(eta-etagate, eta+etagate);
03395 displayHist_[EPH]->GetYaxis()->SetRangeUser(phi-phigate, phi+phigate);
03396 }
03397   
03398 updateDisplay();
03399 
03400 }
03401 */
03402 
03403 
03404 
03405 string PFRootEventManager::expand(const string& oldString) const {
03406 
03407   string newString = oldString;
03408  
03409   string dollar = "$";
03410   string slash  = "/";
03411   
03412   // protection necessary or segv !!
03413   int dollarPos = newString.find(dollar,0);
03414   if( dollarPos == -1 ) return oldString;
03415 
03416   int    lengh  = newString.find(slash,0) - newString.find(dollar,0) + 1;
03417   string env_variable =
03418     newString.substr( ( newString.find(dollar,0) + 1 ), lengh -2);
03419   // the env var could be defined between { }
03420   int begin = env_variable.find_first_of("{");
03421   int end = env_variable.find_last_of("}");
03422   
03423   // cout << "var=" << env_variable << begin<<" "<<end<< endl;
03424   
03425 
03426   env_variable = env_variable.substr( begin+1, end-1 );
03427   // cout << "var=" << env_variable <<endl;
03428 
03429 
03430   // cerr<<"call getenv "<<endl;
03431   char* directory = getenv( env_variable.c_str() );
03432 
03433   if(!directory) {
03434     cerr<<"please define environment variable $"<<env_variable<<endl;
03435     delete this;
03436     exit(1);
03437   }
03438   string sdir = directory;
03439   sdir += "/";
03440 
03441   newString.replace( 0, lengh , sdir);
03442 
03443   if (verbosity_ == VERBOSE ) {
03444     cout << "expand " <<oldString<<" to "<< newString << endl;
03445   }
03446 
03447   return newString;
03448 }
03449 
03450 
03451 void 
03452 PFRootEventManager::printMCCalib(ofstream& out) const {
03453 
03454   if(!out) return;
03455   // if (!out.is_open()) return;
03456 
03457   // Use only for one PFSimParticle/GenParticles
03458   const HepMC::GenEvent* myGenEvent = MCTruth_.GetEvent();
03459   if(!myGenEvent) return;
03460   int nGen = 0;
03461   for ( HepMC::GenEvent::particle_const_iterator 
03462           piter  = myGenEvent->particles_begin();
03463           piter != myGenEvent->particles_end(); 
03464         ++piter ) nGen++;
03465   int nSim = trueParticles_.size();
03466   if ( nGen != 1 || nSim != 1 ) return;
03467 
03468   // One GenJet 
03469   if ( genJets_.size() != 1 ) return;
03470   double true_E = genJets_[0].p();
03471   double true_eta = genJets_[0].eta();
03472   double true_phi = genJets_[0].phi();
03473 
03474   // One particle-flow jet
03475   // if ( pfJets_.size() != 1 ) return;
03476   double rec_ECALEnergy = 0.;
03477   double rec_HCALEnergy = 0.;
03478   double deltaRMin = 999.;
03479   unsigned int theJet = 0;
03480   for ( unsigned int ijet=0; ijet<pfJets_.size(); ++ijet ) { 
03481     double rec_ECAL = pfJets_[ijet].neutralEmEnergy();
03482     double rec_HCAL = pfJets_[ijet].neutralHadronEnergy();
03483     double rec_eta = pfJets_[0].eta();
03484     double rec_phi = pfJets_[0].phi();
03485     double deltaR = std::sqrt( (rec_eta-true_eta)*(rec_eta-true_eta)
03486                              + (rec_phi-true_phi)*(rec_phi-true_phi) ); 
03487     if ( deltaR < deltaRMin ) { 
03488       deltaRMin = deltaR;
03489       rec_ECALEnergy = rec_ECAL;
03490       rec_HCALEnergy = rec_HCAL;
03491     }
03492   }
03493   if ( deltaRMin > 0.1 ) return;
03494   
03495   std::vector < PFCandidatePtr > constituents = pfJets_[theJet].getPFConstituents ();
03496   double pat_ECALEnergy = 0.;
03497   double pat_HCALEnergy = 0.;
03498   for (unsigned ic = 0; ic < constituents.size (); ++ic) {
03499     if ( constituents[ic]->particleId() < 4 ) continue;
03500     if ( constituents[ic]->particleId() == 4 ) 
03501       pat_ECALEnergy += constituents[ic]->rawEcalEnergy();
03502     else if ( constituents[ic]->particleId() == 5 ) 
03503       pat_HCALEnergy += constituents[ic]->rawHcalEnergy();
03504   }
03505 
03506   double col_ECALEnergy = rec_ECALEnergy * 1.05;
03507   double col_HCALEnergy = rec_HCALEnergy;
03508   if ( col_HCALEnergy > 1E-6 ) 
03509     col_HCALEnergy = col_ECALEnergy > 1E-6 ? 
03510     6. + 1.06*rec_HCALEnergy : (2.17*rec_HCALEnergy+1.73)/(1.+std::exp(2.49/rec_HCALEnergy));
03511 
03512   double jam_ECALEnergy = rec_ECALEnergy;
03513   double jam_HCALEnergy = rec_HCALEnergy;
03514   clusterCalibration_->
03515     getCalibratedEnergyEmbedAInHcal(jam_ECALEnergy, jam_HCALEnergy, true_eta, true_phi);
03516 
03517   out << true_eta << " " << true_phi << " " << true_E 
03518       << " " <<  rec_ECALEnergy << " " << rec_HCALEnergy
03519       << " " <<  pat_ECALEnergy << " " << pat_HCALEnergy
03520       << " " << deltaRMin << std::endl;
03521 }
03522 
03523 void  PFRootEventManager::print(ostream& out,int maxNLines ) const {
03524 
03525   if(!out) return;
03526 
03527   //If McTruthMatching print a detailed list 
03528   //of matching between simparticles and PFCandidates
03529   //MCTruth Matching vectors.
03530   std::vector< std::list <simMatch> > candSimMatchTrack;
03531   std::vector< std::list <simMatch> >  candSimMatchEcal;  
03532   if( printMCTruthMatching_){
03533     mcTruthMatching( std::cout,
03534                      *pfCandidates_,
03535                      candSimMatchTrack,
03536                      candSimMatchEcal);
03537   }
03538 
03539 
03540   if( printRecHits_ ) {
03541     out<<"ECAL RecHits ==============================================="<<endl;
03542     printRecHits(rechitsECAL_, clusterAlgoECAL_, out );             out<<endl;
03543     out<<"HCAL RecHits ==============================================="<<endl;
03544     printRecHits(rechitsHCAL_, clusterAlgoHCAL_, out );             out<<endl;
03545     out<<"HFEM RecHits ==============================================="<<endl;
03546     printRecHits(rechitsHFEM_, clusterAlgoHFEM_, out );             out<<endl;
03547     out<<"HFHAD RecHits =============================================="<<endl;
03548     printRecHits(rechitsHFHAD_, clusterAlgoHFHAD_, out );           out<<endl;
03549     out<<"PS RecHits ================================================="<<endl;
03550     printRecHits(rechitsPS_, clusterAlgoPS_, out );                 out<<endl;
03551   }
03552 
03553   if( printClusters_ ) {
03554     out<<"ECAL Clusters ============================================="<<endl;
03555     printClusters( *clustersECAL_, out);                           out<<endl;
03556     out<<"HCAL Clusters ============================================="<<endl;
03557     printClusters( *clustersHCAL_, out);                           out<<endl;
03558     out<<"HFEM Clusters ============================================="<<endl;
03559     printClusters( *clustersHFEM_, out);                           out<<endl;
03560     out<<"HFHAD Clusters ============================================"<<endl;
03561     printClusters( *clustersHFHAD_, out);                          out<<endl;
03562     out<<"PS Clusters   ============================================="<<endl;
03563     printClusters( *clustersPS_, out);                             out<<endl;
03564   }
03565   bool printTracks = true;
03566   if( printTracks) {
03567     
03568   }
03569   if( printPFBlocks_ ) {
03570     out<<"Particle Flow Blocks ======================================"<<endl;
03571     for(unsigned i=0; i<pfBlocks_->size(); i++) {
03572       out<<i<<" "<<(*pfBlocks_)[i]<<endl;
03573     }    
03574     out<<endl;
03575   }
03576   if(printPFCandidates_) {
03577     out<<"Particle Flow Candidates =================================="<<endl;
03578     double mex = 0.;
03579     double mey = 0.;
03580     for(unsigned i=0; i<pfCandidates_->size(); i++) {
03581       const PFCandidate& pfc = (*pfCandidates_)[i];
03582       mex -= pfc.px();
03583       mey -= pfc.py();
03584       if(pfc.pt()>printPFCandidatesPtMin_)
03585       out<<i<<" " <<(*pfCandidates_)[i]<<endl;
03586     }    
03587     out<<endl;
03588     out<< "MEX, MEY, MET ============================================" <<endl 
03589        << mex << " " << mey << " " << sqrt(mex*mex+mey*mey);
03590     out<<endl;
03591     out<<endl;
03592 
03593     //print a detailed list of PFSimParticles matching
03594     //the PFCandiates
03595     if(printMCTruthMatching_){
03596       cout<<"MCTruthMatching Results"<<endl;
03597       for(unsigned icand=0; icand<pfCandidates_->size(); 
03598           icand++) {
03599         out <<icand<<" " <<(*pfCandidates_)[icand]<<endl;
03600         out << "is matching:" << endl;
03601 
03602         //tracking
03603         ITM it_t    = candSimMatchTrack[icand].begin();
03604         ITM itend_t = candSimMatchTrack[icand].end();
03605         for(;it_t!=itend_t;++it_t){
03606           unsigned simid = it_t->second;
03607           out << "\tSimParticle " << trueParticles_[simid]
03608               <<endl;
03609           out << "\t\tthrough Track matching pTrectrack=" 
03610               << it_t->first << " GeV" << endl;
03611         }//loop simparticles
03612 
03613         ITM it_e    = candSimMatchEcal[icand].begin();
03614         ITM itend_e = candSimMatchEcal[icand].end();
03615         for(;it_e!=itend_e;++it_e){
03616           unsigned simid = it_e->second;
03617           out << "\tSimParticle " << trueParticles_[simid]
03618               << endl; 
03619           out << "\t\tsimparticle contributing to a total of " 
03620               << it_e->first
03621               << " GeV of its ECAL cluster"
03622               << endl;  
03623         }//loop simparticles
03624         cout<<"________________"<<endl;
03625       }//loop candidates 
03626     }
03627   }
03628   if(printPFJets_) {
03629     out<<"Jets  ====================================================="<<endl;
03630     out<<"Particle Flow: "<<endl;
03631     for(unsigned i=0; i<pfJets_.size(); i++) {      
03632       if (pfJets_[i].pt() > printPFJetsPtMin_ )
03633         out<<i<<pfJets_[i].print()<<endl;
03634     }    
03635     out<<endl;
03636     out<<"Generated: "<<endl;
03637     for(unsigned i=0; i<genJets_.size(); i++) {
03638       if (genJets_[i].pt() > printPFJetsPtMin_ )
03639         out<<i<<genJets_[i].print()<<endl;
03640       // <<" invisible energy = "<<genJets_[i].invisibleEnergy()<<endl;
03641     }        
03642     out<<endl;
03643     out<<"Calo: "<<endl;
03644     for(unsigned i=0; i<caloJets_.size(); i++) {      
03645       out<<"pt = "<<caloJets_[i].pt()<<endl;
03646     }        
03647     out<<endl;  
03648   }
03649   if( printSimParticles_ ) {
03650     out<<"Sim Particles  ==========================================="<<endl;
03651 
03652     for(unsigned i=0; i<trueParticles_.size(); i++) {
03653       if( trackInsideGCut( trueParticles_[i]) ){ 
03654 
03655         const reco::PFSimParticle& ptc = trueParticles_[i];
03656 
03657         // get trajectory at start point
03658         const reco::PFTrajectoryPoint& tp0 = ptc.extrapolatedPoint( 0 );
03659 
03660         if(tp0.momentum().pt()>printSimParticlesPtMin_)
03661           out<<"\t"<<trueParticles_[i]<<endl;
03662       }
03663     }   
03664  
03665     //print a detailed list of PFSimParticles matching
03666     //the PFCandiates
03667     if(printMCTruthMatching_) {
03668       cout<<"MCTruthMatching Results"<<endl;
03669       for ( unsigned i=0;  i < trueParticles_.size(); i++) {
03670         cout << "==== Particle Simulated " << i << endl;
03671         const reco::PFSimParticle& ptc = trueParticles_[i];
03672         out <<i<<" "<<trueParticles_[i]<<endl;
03673         
03674         if(!ptc.daughterIds().empty()){
03675           cout << "Look at the desintegration products" << endl;
03676           cout << endl;
03677           continue;
03678         }
03679         
03680         //TRACKING
03681         if(ptc.rectrackId() != 99999){
03682           cout << "matching pfCandidate (trough tracking): " << endl;
03683           for( unsigned icand=0; icand<pfCandidates_->size()
03684                  ; icand++ ) 
03685             {
03686               ITM it    = candSimMatchTrack[icand].begin();
03687               ITM itend = candSimMatchTrack[icand].end();
03688               for(;it!=itend;++it)
03689                 if( i == it->second ){
03690                   out<<icand<<" "<<(*pfCandidates_)[icand]<<endl;
03691                   cout << endl;
03692                 }
03693             }//loop candidate
03694         }//trackmatch
03695         
03696         //CALORIMETRY
03697         vector<unsigned> rechitSimIDs  
03698           = ptc.recHitContrib();
03699         vector<double>   rechitSimFrac 
03700           = ptc.recHitContribFrac();
03701         //cout << "Number of rechits contrib =" << rechitSimIDs.size() << endl;
03702         if( !rechitSimIDs.size() ) continue; //no rechit
03703         
03704         cout << "matching pfCandidate (through ECAL): " << endl;
03705         
03706         //look at total ECAL desposition:
03707         double totalEcalE = 0.0;
03708         for(unsigned irh=0; irh<rechitsECAL_.size();++irh)
03709           for ( unsigned isimrh=0;  isimrh < rechitSimIDs.size(); 
03710                 isimrh++ )
03711             if(rechitSimIDs[isimrh] == rechitsECAL_[irh].detId())
03712               totalEcalE += (rechitsECAL_[irh].energy()*rechitSimFrac[isimrh]/100.0);
03713         cout << "For info, this particle deposits E=" << totalEcalE 
03714              << "(GeV) in the ECAL" << endl;
03715         
03716         for( unsigned icand=0; icand<pfCandidates_->size()
03717                ; icand++ ) 
03718           {
03719             ITM it    = candSimMatchEcal[icand].begin();
03720             ITM itend = candSimMatchEcal[icand].end();
03721             for(;it!=itend;++it)
03722               if( i == it->second )
03723                 out<<icand<<" "<<it->first<<"GeV "<<(*pfCandidates_)[icand]<<endl;        
03724           }//loop candidate
03725         cout << endl;      
03726       }//loop particles  
03727     }//mctruthmatching
03728 
03729   }
03730 
03731   
03732   if ( printGenParticles_ ) { 
03733     printGenParticles(out,maxNLines);
03734   }
03735 }
03736 
03737 
03738 void
03739 PFRootEventManager::printGenParticles(std::ostream& out,
03740                                       int maxNLines) const {
03741                                  
03742                                  
03743   const HepMC::GenEvent* myGenEvent = MCTruth_.GetEvent();
03744   if(!myGenEvent) return;
03745 
03746   out<<"GenParticles ==========================================="<<endl;
03747 
03748   std::cout << "Id  Gen Name       eta    phi     pT     E    Vtx1   " 
03749             << " x      y      z   " 
03750             << "Moth  Vtx2  eta   phi     R      Z   Da1  Da2 Ecal?" 
03751             << std::endl;
03752 
03753   int nLines = 0;
03754   for ( HepMC::GenEvent::particle_const_iterator 
03755           piter  = myGenEvent->particles_begin();
03756         piter != myGenEvent->particles_end(); 
03757         ++piter ) {
03758     
03759     if( nLines == maxNLines) break;
03760     nLines++;
03761     
03762     HepMC::GenParticle* p = *piter;
03763     /* */
03764     int partId = p->pdg_id();
03765 
03766     // We have here a subset of particles only. 
03767     // To be filled according to the needs.
03768     /*switch(partId) {
03769       case    1: { name = "d"; break; } 
03770       case    2: { name = "u"; break; } 
03771       case    3: { name = "s"; break; } 
03772       case    4: { name = "c"; break; } 
03773       case    5: { name = "b"; break; } 
03774       case    6: { name = "t"; break; } 
03775       case   -1: { name = "~d"; break; } 
03776       case   -2: { name = "~u"; break; } 
03777       case   -3: { name = "~s"; break; } 
03778       case   -4: { name = "~c"; break; } 
03779       case   -5: { name = "~b"; break; } 
03780       case   -6: { name = "~t"; break; } 
03781       case   11: { name = "e-"; break; }
03782       case  -11: { name = "e+"; break; }
03783       case   12: { name = "nu_e"; break; }
03784       case  -12: { name = "~nu_e"; break; }
03785       case   13: { name = "mu-"; break; }
03786       case  -13: { name = "mu+"; break; }
03787       case   14: { name = "nu_mu"; break; }
03788       case  -14: { name = "~nu_mu"; break; }
03789       case   15: { name = "tau-"; break; }
03790       case  -15: { name = "tau+"; break; }
03791       case   16: { name = "nu_tau"; break; }
03792       case  -16: { name = "~nu_tau"; break; }
03793       case   21: { name = "gluon"; break; }
03794       case   22: { name = "gamma"; break; }
03795       case   23: { name = "Z0"; break; }
03796       case   24: { name = "W+"; break; }
03797       case   25: { name = "H0"; break; }
03798       case  -24: { name = "W-"; break; }
03799       case  111: { name = "pi0"; break; }
03800       case  113: { name = "rho0"; break; }
03801       case  223: { name = "omega"; break; }
03802       case  333: { name = "phi"; break; }
03803       case  443: { name = "J/psi"; break; }
03804       case  553: { name = "Upsilon"; break; }
03805       case  130: { name = "K0L"; break; }
03806       case  211: { name = "pi+"; break; }
03807       case -211: { name = "pi-"; break; }
03808       case  213: { name = "rho+"; break; }
03809       case -213: { name = "rho-"; break; }
03810       case  221: { name = "eta"; break; }
03811       case  331: { name = "eta'"; break; }
03812       case  441: { name = "etac"; break; }
03813       case  551: { name = "etab"; break; }
03814       case  310: { name = "K0S"; break; }
03815       case  311: { name = "K0"; break; }
03816       case -311: { name = "Kbar0"; break; }
03817       case  321: { name = "K+"; break; }
03818       case -321: { name = "K-"; break; }
03819       case  411: { name = "D+"; break; }
03820       case -411: { name = "D-"; break; }
03821       case  421: { name = "D0"; break; }
03822       case  431: { name = "Ds_+"; break; }
03823       case -431: { name = "Ds_-"; break; }
03824       case  511: { name = "B0"; break; }
03825       case  521: { name = "B+"; break; }
03826       case -521: { name = "B-"; break; }
03827       case  531: { name = "Bs_0"; break; }
03828       case  541: { name = "Bc_+"; break; }
03829       case -541: { name = "Bc_+"; break; }
03830       case  313: { name = "K*0"; break; }
03831       case -313: { name = "K*bar0"; break; }
03832       case  323: { name = "K*+"; break; }
03833       case -323: { name = "K*-"; break; }
03834       case  413: { name = "D*+"; break; }
03835       case -413: { name = "D*-"; break; }
03836       case  423: { name = "D*0"; break; }
03837       case  513: { name = "B*0"; break; }
03838       case  523: { name = "B*+"; break; }
03839       case -523: { name = "B*-"; break; }
03840       case  533: { name = "B*_s0"; break; }
03841       case  543: { name = "B*_c+"; break; }
03842       case -543: { name = "B*_c-"; break; }
03843       case  1114: { name = "Delta-"; break; }
03844       case -1114: { name = "Deltabar+"; break; }
03845       case -2112: { name = "nbar0"; break; }
03846       case  2112: { name = "n"; break; }
03847       case  2114: { name = "Delta0"; break; }
03848       case -2114: { name = "Deltabar0"; break; }
03849       case  3122: { name = "Lambda0"; break; }
03850       case -3122: { name = "Lambdabar0"; break; }
03851       case  3112: { name = "Sigma-"; break; }
03852       case -3112: { name = "Sigmabar+"; break; }
03853       case  3212: { name = "Sigma0"; break; }
03854       case -3212: { name = "Sigmabar0"; break; }
03855       case  3214: { name = "Sigma*0"; break; }
03856       case -3214: { name = "Sigma*bar0"; break; }
03857       case  3222: { name = "Sigma+"; break; }
03858       case -3222: { name = "Sigmabar-"; break; }
03859       case  2212: { name = "p"; break; }
03860       case -2212: { name = "~p"; break; }
03861       case -2214: { name = "Delta-"; break; }
03862       case  2214: { name = "Delta+"; break; }
03863       case -2224: { name = "Deltabar--"; break; }
03864       case  2224: { name = "Delta++"; break; }
03865       default: { 
03866       name = "unknown"; 
03867       cout << "Unknown code : " << partId << endl;
03868       }   
03869       }
03870     */
03871     std::string latexString;
03872     std::string name = getGenParticleName(partId,latexString);
03873 
03874     math::XYZTLorentzVector momentum1(p->momentum().px(),
03875                                       p->momentum().py(),
03876                                       p->momentum().pz(),
03877                                       p->momentum().e() );
03878 
03879     if(momentum1.pt()<printGenParticlesPtMin_) continue;
03880 
03881     int vertexId1 = 0;
03882 
03883     if ( !p->production_vertex() && p->pdg_id() == 2212 ) continue;
03884 
03885     math::XYZVector vertex1;
03886     vertexId1 = -1;
03887 
03888     if(p->production_vertex() ) {
03889       vertex1.SetCoordinates( p->production_vertex()->position().x()/10.,
03890                               p->production_vertex()->position().y()/10.,
03891                               p->production_vertex()->position().z()/10. );
03892       vertexId1 = p->production_vertex()->barcode();
03893     }
03894 
03895     out.setf(std::ios::fixed, std::ios::floatfield);
03896     out.setf(std::ios::right, std::ios::adjustfield);
03897     
03898     out << std::setw(4) << p->barcode() << " " 
03899         << name;
03900     
03901     for(unsigned int k=0;k<11-name.length() && k<12; k++) out << " ";  
03902     
03903     double eta = momentum1.eta();
03904     if ( eta > +10. ) eta = +10.;
03905     if ( eta < -10. ) eta = -10.;
03906     
03907     out << std::setw(6) << std::setprecision(2) << eta << " " 
03908         << std::setw(6) << std::setprecision(2) << momentum1.phi() << " " 
03909         << std::setw(7) << std::setprecision(2) << momentum1.pt() << " " 
03910         << std::setw(7) << std::setprecision(2) << momentum1.e() << " " 
03911         << std::setw(4) << vertexId1 << " " 
03912         << std::setw(6) << std::setprecision(1) << vertex1.x() << " " 
03913         << std::setw(6) << std::setprecision(1) << vertex1.y() << " " 
03914         << std::setw(6) << std::setprecision(1) << vertex1.z() << " ";
03915 
03916 
03917     if( p->production_vertex() ) {
03918       if ( p->production_vertex()->particles_in_size() ) {
03919         const HepMC::GenParticle* mother = 
03920           *(p->production_vertex()->particles_in_const_begin());
03921         
03922         out << std::setw(4) << mother->barcode() << " ";
03923       }
03924       else 
03925         out << "     " ;
03926     }    
03927 
03928     if ( p->end_vertex() ) {  
03929       math::XYZTLorentzVector vertex2(p->end_vertex()->position().x()/10.,
03930                                       p->end_vertex()->position().y()/10.,
03931                                       p->end_vertex()->position().z()/10.,
03932                                       p->end_vertex()->position().t()/10.);
03933       int vertexId2 = p->end_vertex()->barcode();
03934 
03935       std::vector<const HepMC::GenParticle*> children;
03936       HepMC::GenVertex::particles_out_const_iterator firstDaughterIt = 
03937         p->end_vertex()->particles_out_const_begin();
03938       HepMC::GenVertex::particles_out_const_iterator lastDaughterIt = 
03939         p->end_vertex()->particles_out_const_end();
03940       for ( ; firstDaughterIt != lastDaughterIt ; ++firstDaughterIt ) {
03941         children.push_back(*firstDaughterIt);
03942       }      
03943 
03944       out << std::setw(4) << vertexId2 << " "
03945           << std::setw(6) << std::setprecision(2) << vertex2.eta() << " " 
03946           << std::setw(6) << std::setprecision(2) << vertex2.phi() << " " 
03947           << std::setw(5) << std::setprecision(1) << vertex2.pt() << " " 
03948           << std::setw(6) << std::setprecision(1) << vertex2.z() << " ";
03949 
03950       for ( unsigned id=0; id<children.size(); ++id )
03951         out << std::setw(4) << children[id]->barcode() << " ";
03952     }
03953     out << std::endl;
03954   }
03955 }
03956 
03957 void PFRootEventManager::printRecHits(const reco::PFRecHitCollection& rechits, const PFClusterAlgo& clusterAlgo, ostream& out) const{
03958 
03959     for(unsigned i=0; i<rechits.size(); i++) {
03960       string seedstatus = "    ";
03961       if(clusterAlgo.isSeed(i) ) 
03962         seedstatus = "SEED";
03963       printRecHit(rechits[i], i, seedstatus.c_str(), out);
03964     }
03965     return;
03966 }
03967 
03968 void  PFRootEventManager::printRecHit(const reco::PFRecHit& rh,
03969                                       unsigned index,  
03970                                       const char* seedstatus,
03971                                       ostream& out) const {
03972 
03973   if(!out) return;
03974   double eta = rh.position().Eta();
03975   double phi = rh.position().Phi();
03976   double energy = rh.energy();
03977 
03978   if(energy<printRecHitsEMin_)  return;
03979 
03980   TCutG* cutg = (TCutG*) gROOT->FindObject("CUTG");
03981   if( !cutg || cutg->IsInside( eta, phi ) ) 
03982     out<<index<<"\t"<<seedstatus<<" "<<rh<<endl; 
03983 }
03984 
03985 void PFRootEventManager::printClusters(const reco::PFClusterCollection& clusters,
03986                                        ostream& out ) const {  
03987   for(unsigned i=0; i<clusters.size(); i++) {
03988     printCluster(clusters[i], out);
03989   }
03990   return;
03991 }
03992 
03993 void  PFRootEventManager::printCluster(const reco::PFCluster& cluster,
03994                                        ostream& out ) const {
03995   
03996   if(!out) return;
03997 
03998   double eta = cluster.position().Eta();
03999   double phi = cluster.position().Phi();
04000   double energy = cluster.energy();
04001 
04002   if(energy<printClustersEMin_)  return;
04003 
04004   TCutG* cutg = (TCutG*) gROOT->FindObject("CUTG");
04005   if( !cutg || cutg->IsInside( eta, phi ) ) 
04006     out<<cluster<<endl;
04007 }
04008 
04009 
04010 
04011 
04012 
04013 bool PFRootEventManager::trackInsideGCut( const reco::PFTrack& track ) const {
04014 
04015   TCutG* cutg = (TCutG*) gROOT->FindObject("CUTG");
04016   if(!cutg) return true;
04017   
04018   const vector< reco::PFTrajectoryPoint >& points = track.trajectoryPoints();
04019   
04020   for( unsigned i=0; i<points.size(); i++) {
04021     if( ! points[i].isValid() ) continue;
04022     
04023     const math::XYZPoint& pos = points[i].position();
04024     if( cutg->IsInside( pos.Eta(), pos.Phi() ) ) return true;
04025   }
04026 
04027   // no point inside cut
04028   return false;
04029 }
04030 
04031 
04032 void  
04033 PFRootEventManager::fillRecHitMask( vector<bool>& mask, 
04034                                     const reco::PFRecHitCollection& rechits ) 
04035   const {
04036 
04037   TCutG* cutg = (TCutG*) gROOT->FindObject("CUTG");
04038   if(!cutg) return;
04039 
04040   mask.clear();
04041   mask.reserve( rechits.size() );
04042   for(unsigned i=0; i<rechits.size(); i++) {
04043     
04044     double eta = rechits[i].position().Eta();
04045     double phi = rechits[i].position().Phi();
04046 
04047     if( cutg->IsInside( eta, phi ) )
04048       mask.push_back( true );
04049     else 
04050       mask.push_back( false );   
04051   }
04052 }
04053 
04054 void  
04055 PFRootEventManager::fillClusterMask(vector<bool>& mask, 
04056                                     const reco::PFClusterCollection& clusters) 
04057   const {
04058   
04059   TCutG* cutg = (TCutG*) gROOT->FindObject("CUTG");
04060   if(!cutg) return;
04061 
04062   mask.clear();
04063   mask.reserve( clusters.size() );
04064   for(unsigned i=0; i<clusters.size(); i++) {
04065     
04066     double eta = clusters[i].position().Eta();
04067     double phi = clusters[i].position().Phi();
04068 
04069     if( cutg->IsInside( eta, phi ) )
04070       mask.push_back( true );
04071     else 
04072       mask.push_back( false );   
04073   }
04074 }
04075 
04076 void  
04077 PFRootEventManager::fillTrackMask(vector<bool>& mask, 
04078                                   const reco::PFRecTrackCollection& tracks) 
04079   const {
04080   
04081   TCutG* cutg = (TCutG*) gROOT->FindObject("CUTG");
04082   if(!cutg) return;
04083 
04084   mask.clear();
04085   mask.reserve( tracks.size() );
04086   for(unsigned i=0; i<tracks.size(); i++) {
04087     if( trackInsideGCut( tracks[i] ) )
04088       mask.push_back( true );
04089     else 
04090       mask.push_back( false );   
04091   }
04092 }
04093 
04094 void  
04095 PFRootEventManager::fillTrackMask(vector<bool>& mask, 
04096                                   const reco::GsfPFRecTrackCollection& tracks) 
04097   const {
04098   
04099   TCutG* cutg = (TCutG*) gROOT->FindObject("CUTG");
04100   if(!cutg) return;
04101 
04102   mask.clear();
04103   mask.reserve( tracks.size() );
04104   for(unsigned i=0; i<tracks.size(); i++) {
04105     if( trackInsideGCut( tracks[i] ) )
04106       mask.push_back( true );
04107     else 
04108       mask.push_back( false );   
04109   }
04110 }
04111 
04112 
04113 const reco::PFSimParticle&
04114 PFRootEventManager::closestParticle( reco::PFTrajectoryPoint::LayerType layer, 
04115                                      double eta, double phi,
04116                                      double& peta, double& pphi, double& pe) 
04117   const {
04118   
04119 
04120   if( trueParticles_.empty() ) {
04121     string err  = "PFRootEventManager::closestParticle : ";
04122     err        += "vector of PFSimParticles is empty";
04123     throw std::length_error( err.c_str() );
04124   }
04125 
04126   double mindist2 = 99999999;
04127   unsigned iClosest=0;
04128   for(unsigned i=0; i<trueParticles_.size(); i++) {
04129     
04130     const reco::PFSimParticle& ptc = trueParticles_[i];
04131 
04132     // protection for old version of the PFSimParticle 
04133     // dataformats. 
04134     if( layer >= reco::PFTrajectoryPoint::NLayers ||
04135         ptc.nTrajectoryMeasurements() + layer >= 
04136         ptc.nTrajectoryPoints() ) {
04137       continue;
04138     }
04139 
04140     const reco::PFTrajectoryPoint& tp
04141       = ptc.extrapolatedPoint( layer );
04142 
04143     peta = tp.position().Eta();
04144     pphi = tp.position().Phi();
04145     pe = tp.momentum().E();
04146 
04147     double deta = peta - eta;
04148     double dphi = pphi - phi;
04149 
04150     double dist2 = deta*deta + dphi*dphi;
04151 
04152     if(dist2<mindist2) {
04153       mindist2 = dist2;
04154       iClosest = i;
04155     }
04156   }
04157 
04158   return trueParticles_[iClosest];
04159 }
04160 
04161 
04162 
04163 //-----------------------------------------------------------
04164 void 
04165 PFRootEventManager::readCMSSWJets() {
04166 
04167   cout<<"CMSSW Gen jets : size = " <<  genJetsCMSSW_.size() << endl;
04168   for ( unsigned i = 0; i < genJetsCMSSW_.size(); i++) {
04169     cout<<"Gen jet Et : " <<  genJetsCMSSW_[i].et() << endl;
04170   }
04171   cout<<"CMSSW PF jets : size = " <<  pfJetsCMSSW_.size() << endl;
04172   for ( unsigned i = 0; i < pfJetsCMSSW_.size(); i++) {
04173     cout<<"PF jet Et : " <<  pfJetsCMSSW_[i].et() << endl;
04174   }
04175   cout<<"CMSSW Calo jets : size = " <<  caloJetsCMSSW_.size() << endl;
04176   for ( unsigned i = 0; i < caloJetsCMSSW_.size(); i++) {
04177     cout<<"Calo jet Et : " << caloJetsCMSSW_[i].et() << endl;
04178   }
04179 }
04180 //________________________________________________________________
04181 std::string PFRootEventManager::getGenParticleName(int partId, std::string &latexString) const
04182 {
04183   std::string  name;
04184   switch(partId) {
04185   case    1: { name = "d";latexString="d"; break; } 
04186   case    2: { name = "u";latexString="u";break; } 
04187   case    3: { name = "s";latexString="s" ;break; } 
04188   case    4: { name = "c";latexString="c" ; break; } 
04189   case    5: { name = "b";latexString="b" ; break; } 
04190   case    6: { name = "t";latexString="t" ; break; } 
04191   case   -1: { name = "~d";latexString="#bar{d}" ; break; } 
04192   case   -2: { name = "~u";latexString="#bar{u}" ; break; } 
04193   case   -3: { name = "~s";latexString="#bar{s}" ; break; } 
04194   case   -4: { name = "~c";latexString="#bar{c}" ; break; } 
04195   case   -5: { name = "~b";latexString="#bar{b}" ; break; } 
04196   case   -6: { name = "~t";latexString="#bar{t}" ; break; } 
04197   case   11: { name = "e-";latexString=name ; break; }
04198   case  -11: { name = "e+";latexString=name ; break; }
04199   case   12: { name = "nu_e";latexString="#nu_{e}" ; break; }
04200   case  -12: { name = "~nu_e";latexString="#bar{#nu}_{e}" ; break; }
04201   case   13: { name = "mu-";latexString="#mu-" ; break; }
04202   case  -13: { name = "mu+";latexString="#mu+" ; break; }
04203   case   14: { name = "nu_mu";latexString="#nu_{mu}" ; break; }
04204   case  -14: { name = "~nu_mu";latexString="#bar{#nu}_{#mu}"; break; }
04205   case   15: { name = "tau-";latexString="#tau^{-}" ; break; }
04206   case  -15: { name = "tau+";latexString="#tau^{+}" ; break; }
04207   case   16: { name = "nu_tau";latexString="#nu_{#tau}" ; break; }
04208   case  -16: { name = "~nu_tau";latexString="#bar{#nu}_{#tau}"; break; }
04209   case   21: { name = "gluon";latexString= name; break; }
04210   case   22: { name = "gamma";latexString= "#gamma"; break; }
04211   case   23: { name = "Z0";latexString="Z^{0}" ; break; }
04212   case   24: { name = "W+";latexString="W^{+}" ; break; }
04213   case   25: { name = "H0";latexString=name ; break; }
04214   case  -24: { name = "W-";latexString="W^{-}" ; break; }
04215   case  111: { name = "pi0";latexString="#pi^{0}" ; break; }
04216   case  113: { name = "rho0";latexString="#rho^{0}" ; break; }
04217   case  223: { name = "omega";latexString="#omega" ; break; }
04218   case  333: { name = "phi";latexString= "#phi"; break; }
04219   case  443: { name = "J/psi";latexString="J/#psi" ; break; }
04220   case  553: { name = "Upsilon";latexString="#Upsilon" ; break; }
04221   case  130: { name = "K0L";latexString=name ; break; }
04222   case  211: { name = "pi+";latexString="#pi^{+}" ; break; }
04223   case -211: { name = "pi-";latexString="#pi^{-}" ; break; }
04224   case  213: { name = "rho+";latexString="#rho^{+}" ; break; }
04225   case -213: { name = "rho-";latexString="#rho^{-}" ; break; }
04226   case  221: { name = "eta";latexString="#eta" ; break; }
04227   case  331: { name = "eta'";latexString="#eta'" ; break; }
04228   case  441: { name = "etac";latexString="#eta_{c}" ; break; }
04229   case  551: { name = "etab";latexString= "#eta_{b}"; break; }
04230   case  310: { name = "K0S";latexString=name ; break; }
04231   case  311: { name = "K0";latexString="K^{0}" ; break; }
04232   case -311: { name = "Kbar0";latexString="#bar{#Kappa}^{0}" ; break; }
04233   case  321: { name = "K+";latexString= "K^{+}"; break; }
04234   case -321: { name = "K-";latexString="K^{-}"; break; }
04235   case  411: { name = "D+";latexString="D^{+}" ; break; }
04236   case -411: { name = "D-";latexString="D^{-}"; break; }
04237   case  421: { name = "D0";latexString=name ; break; }
04238   case  431: { name = "Ds_+";latexString="Ds_{+}" ; break; }
04239   case -431: { name = "Ds_-";latexString="Ds_{-}" ; break; }
04240   case  511: { name = "B0";latexString= name; break; }
04241   case  521: { name = "B+";latexString="B^{+}" ; break; }
04242   case -521: { name = "B-";latexString="B^{-}" ; break; }
04243   case  531: { name = "Bs_0";latexString="Bs_{0}" ; break; }
04244   case  541: { name = "Bc_+";latexString="Bc_{+}" ; break; }
04245   case -541: { name = "Bc_+";latexString="Bc_{+}" ; break; }
04246   case  313: { name = "K*0";latexString="K^{*0}" ; break; }
04247   case -313: { name = "K*bar0";latexString="#bar{K}^{*0}" ; break; }
04248   case  323: { name = "K*+";latexString="#K^{*+}"; break; }
04249   case -323: { name = "K*-";latexString="#K^{*-}" ; break; }
04250   case  413: { name = "D*+";latexString= "D^{*+}"; break; }
04251   case -413: { name = "D*-";latexString= "D^{*-}" ; break; }
04252   case  423: { name = "D*0";latexString="D^{*0}" ; break; }
04253   case  513: { name = "B*0";latexString="B^{*0}" ; break; }
04254   case  523: { name = "B*+";latexString="B^{*+}" ; break; }
04255   case -523: { name = "B*-";latexString="B^{*-}" ; break; }
04256   case  533: { name = "B*_s0";latexString="B^{*}_{s0}" ; break; }
04257   case  543: { name = "B*_c+";latexString= "B^{*}_{c+}"; break; }
04258   case -543: { name = "B*_c-";latexString= "B^{*}_{c-}"; break; }
04259   case  1114: { name = "Delta-";latexString="#Delta^{-}" ; break; }
04260   case -1114: { name = "Deltabar+";latexString="#bar{#Delta}^{+}" ; break; }
04261   case -2112: { name = "nbar0";latexString="{bar}n^{0}" ; break; }
04262   case  2112: { name = "n"; latexString=name ;break;}
04263   case  2114: { name = "Delta0"; latexString="#Delta^{0}" ;break; }
04264   case -2114: { name = "Deltabar0"; latexString="#bar{#Delta}^{0}" ;break; }
04265   case  3122: { name = "Lambda0";latexString= "#Lambda^{0}"; break; }
04266   case -3122: { name = "Lambdabar0";latexString="#bar{#Lambda}^{0}" ; break; }
04267   case  3112: { name = "Sigma-"; latexString="#Sigma" ;break; }
04268   case -3112: { name = "Sigmabar+"; latexString="#bar{#Sigma}^{+}" ;break; }
04269   case  3212: { name = "Sigma0";latexString="#Sigma^{0}" ; break; }
04270   case -3212: { name = "Sigmabar0";latexString="#bar{#Sigma}^{0}" ; break; }
04271   case  3214: { name = "Sigma*0"; latexString="#Sigma^{*0}" ;break; }
04272   case -3214: { name = "Sigma*bar0";latexString="#bar{#Sigma}^{*0}" ; break; }
04273   case  3222: { name = "Sigma+"; latexString="#Sigma^{+}" ;break; }
04274   case -3222: { name = "Sigmabar-"; latexString="#bar{#Sigma}^{-}";break; }
04275   case  2212: { name = "p";latexString=name ; break; }
04276   case -2212: { name = "~p";latexString="#bar{p}" ; break; }
04277   case -2214: { name = "Delta-";latexString="#Delta^{-}" ; break; }
04278   case  2214: { name = "Delta+";latexString="#Delta^{+}" ; break; }
04279   case -2224: { name = "Deltabar--"; latexString="#bar{#Delta}^{--}" ;break; }
04280   case  2224: { name = "Delta++"; latexString= "#Delta^{++}";break; }
04281   default:
04282     {
04283       name = "unknown"; 
04284       cout << "Unknown code : " << partId << endl;
04285       break;
04286     } 
04287                 
04288                   
04289   }
04290   return name;  
04291 
04292 }
04293 
04294 //_____________________________________________________________________________
04295 void PFRootEventManager::mcTruthMatching( std::ostream& out,
04296                                           const reco::PFCandidateCollection& candidates,
04297                                           std::vector< std::list <simMatch> >& candSimMatchTrack,
04298                                           std::vector< std::list <simMatch> >& candSimMatchEcal) const
04299 {
04300   
04301   if(!out) return;
04302   out << endl;
04303   out << "Running Monte Carlo Truth Matching Tool" << endl;
04304   out << endl;
04305 
04306   //resize matching vectors
04307   candSimMatchTrack.resize(candidates.size());
04308   candSimMatchEcal.resize(candidates.size());
04309 
04310   for(unsigned i=0; i<candidates.size(); i++) {
04311     const reco::PFCandidate& pfCand = candidates[i];
04312     
04313     //Matching with ECAL clusters
04314     if (verbosity_ == VERBOSE ) {
04315       out <<i<<" " <<(*pfCandidates_)[i]<<endl;
04316       out << "is matching:" << endl;
04317     }
04318     
04319     PFCandidate::ElementsInBlocks eleInBlocks 
04320       = pfCand.elementsInBlocks();
04321 
04322     for(unsigned iel=0; iel<eleInBlocks.size(); ++iel) {
04323       PFBlockRef blockRef   = eleInBlocks[iel].first;
04324       unsigned indexInBlock = eleInBlocks[iel].second;
04325       
04326       //Retrieving elements of the block
04327       const reco::PFBlock& blockh 
04328         = *blockRef;
04329       const edm::OwnVector< reco::PFBlockElement >& 
04330         elements_h = blockh.elements();
04331       
04332       reco::PFBlockElement::Type type 
04333         = elements_h[ indexInBlock ].type();   
04334 //       cout <<"(" << blockRef.key() << "|" <<indexInBlock <<"|" 
04335 //         << elements_h[ indexInBlock ].type() << ")," << endl;
04336       
04337       //TRACK=================================
04338       if(type == reco::PFBlockElement::TRACK){
04339         const reco::PFRecTrackRef trackref 
04340           = elements_h[ indexInBlock ].trackRefPF();
04341         assert( !trackref.isNull() );     
04342         const reco::PFRecTrack& track = *trackref; 
04343         const reco::TrackRef trkREF = track.trackRef();
04344         unsigned rtrkID = track.trackId();
04345 
04346         //looking for the matching charged simulated particle:
04347         for ( unsigned isim=0;  isim < trueParticles_.size(); isim++) {
04348           const reco::PFSimParticle& ptc = trueParticles_[isim];
04349           unsigned trackIDM = ptc.rectrackId();
04350           if(trackIDM != 99999 
04351              && trackIDM == rtrkID){
04352 
04353             if (verbosity_ == VERBOSE ) 
04354               out << "\tSimParticle " << isim 
04355                   << " through Track matching pTrectrack=" 
04356                   << trkREF->pt() << " GeV" << endl;     
04357             
04358             //store info
04359             std::pair<double, unsigned> simtrackmatch
04360               = make_pair(trkREF->pt(),trackIDM);
04361             candSimMatchTrack[i].push_back(simtrackmatch);
04362           }//match
04363         }//loop simparticles 
04364         
04365       }//TRACK
04366 
04367       //ECAL=================================
04368       if(type == reco::PFBlockElement::ECAL)
04369         {
04370           const reco::PFClusterRef clusterref 
04371             = elements_h[ indexInBlock ].clusterRef();
04372           assert( !clusterref.isNull() );         
04373           const reco::PFCluster& cluster = *clusterref; 
04374           
04375           const std::vector< reco::PFRecHitFraction >& 
04376             fracs = cluster.recHitFractions();  
04377 
04378 //        cout << "This is an ecal cluster of energy " 
04379 //             << cluster.energy() << endl;
04380           vector<unsigned> simpID;
04381           vector<double>   simpEC(trueParticles_.size(),0.0);     
04382           vector<unsigned> simpCN(trueParticles_.size(),0);      
04383           for(unsigned int rhit = 0; rhit < fracs.size(); ++rhit){
04384             
04385             const reco::PFRecHitRef& rh = fracs[rhit].recHitRef();
04386             if(rh.isNull()) continue;
04387             const reco::PFRecHit& rechit_cluster = *rh;
04388 //          cout << rhit << " ID=" << rechit_cluster.detId() 
04389 //               << " E=" << rechit_cluster.energy() 
04390 //               << " fraction=" << fracs[rhit].fraction() << " ";
04391             
04392             //loop on sim particules
04393 //          cout << "coming from sim particles: ";
04394             for ( unsigned isim=0;  isim < trueParticles_.size(); isim++) {
04395               const reco::PFSimParticle& ptc = trueParticles_[isim];
04396               
04397               vector<unsigned> rechitSimIDs  
04398                 = ptc.recHitContrib();
04399               vector<double>   rechitSimFrac 
04400                 = ptc.recHitContribFrac();
04401               //cout << "Number of rechits contrib =" << rechitSimIDs.size() << endl;
04402               if( !rechitSimIDs.size() ) continue; //no rechit
04403                                                                        
04404               for ( unsigned isimrh=0;  isimrh < rechitSimIDs.size(); isimrh++) {
04405                 if( rechitSimIDs[isimrh] == rechit_cluster.detId() ){
04406                   
04407                   bool takenalready = false;
04408                   for(unsigned iss = 0; iss < simpID.size(); ++iss)
04409                     if(simpID[iss] == isim) takenalready = true;
04410                   if(!takenalready) simpID.push_back(isim);
04411                   
04412                   simpEC[isim] += 
04413                     ((rechit_cluster.energy()*rechitSimFrac[isimrh])/100.0)
04414                     *fracs[rhit].fraction();
04415                   
04416                   simpCN[isim]++; //counting rechits
04417 
04418 //                cout << isim << " with contribution of =" 
04419 //                     << rechitSimFrac[isimrh] << "%, "; 
04420                 }//match rechit
04421               }//loop sim rechit
04422             }//loop sim particules
04423 //          cout << endl;
04424           }//loop cand rechit 
04425 
04426           for(unsigned is=0; is < simpID.size(); ++is)
04427             {
04428               double frac_of_cluster 
04429                 = (simpEC[simpID[is]]/cluster.energy())*100.0;
04430               
04431               //store info
04432               std::pair<double, unsigned> simecalmatch
04433                 = make_pair(simpEC[simpID[is]],simpID[is]);
04434               candSimMatchEcal[i].push_back(simecalmatch);
04435               
04436               if (verbosity_ == VERBOSE ) {
04437                 out << "\tSimParticle " << simpID[is] 
04438                     << " through ECAL matching Epfcluster=" 
04439                     << cluster.energy() 
04440                     << " GeV with N=" << simpCN[simpID[is]]
04441                     << " rechits in common "
04442                     << endl; 
04443                 out << "\t\tsimparticle contributing to a total of " 
04444                     << simpEC[simpID[is]]
04445                     << " GeV of this cluster (" 
04446                     <<  frac_of_cluster << "%) " 
04447                     << endl;
04448               }
04449             }//loop particle matched
04450         }//ECAL clusters
04451 
04452     }//loop elements
04453 
04454     if (verbosity_ == VERBOSE )
04455       cout << "===============================================================" 
04456            << endl;
04457 
04458   }//loop pfCandidates_
04459 
04460   if (verbosity_ == VERBOSE ){
04461 
04462     cout << "=================================================================="
04463          << endl;
04464     cout << "SimParticles" << endl;
04465     
04466     //loop simulated particles  
04467     for ( unsigned i=0;  i < trueParticles_.size(); i++) {
04468       cout << "==== Particle Simulated " << i << endl;
04469       const reco::PFSimParticle& ptc = trueParticles_[i];
04470       out <<i<<" "<<trueParticles_[i]<<endl;
04471 
04472       if(!ptc.daughterIds().empty()){
04473         cout << "Look at the desintegration products" << endl;
04474         cout << endl;
04475         continue;
04476       }
04477       
04478       //TRACKING
04479       if(ptc.rectrackId() != 99999){
04480         cout << "matching pfCandidate (trough tracking): " << endl;
04481         for( unsigned icand=0; icand<candidates.size(); icand++ ) 
04482           {
04483             ITM it    = candSimMatchTrack[icand].begin();
04484             ITM itend = candSimMatchTrack[icand].end();
04485             for(;it!=itend;++it)
04486               if( i == it->second ){
04487                 out<<icand<<" "<<(*pfCandidates_)[icand]<<endl;
04488                 cout << endl;
04489               }
04490           }//loop candidate
04491       }//trackmatch
04492       
04493       
04494       //CALORIMETRY
04495       vector<unsigned> rechitSimIDs  
04496         = ptc.recHitContrib();
04497       vector<double>   rechitSimFrac 
04498         = ptc.recHitContribFrac();
04499       //cout << "Number of rechits contrib =" << rechitSimIDs.size() << endl;
04500       if( !rechitSimIDs.size() ) continue; //no rechit
04501       
04502       cout << "matching pfCandidate (through ECAL): " << endl;
04503       
04504       //look at total ECAL desposition:
04505       double totalEcalE = 0.0;
04506       for(unsigned irh=0; irh<rechitsECAL_.size();++irh)
04507         for ( unsigned isimrh=0;  isimrh < rechitSimIDs.size(); 
04508               isimrh++ )
04509           if(rechitSimIDs[isimrh] == rechitsECAL_[irh].detId())
04510             totalEcalE += (rechitsECAL_[irh].energy()*rechitSimFrac[isimrh]/100.0);
04511       cout << "For info, this particle deposits E=" << totalEcalE 
04512            << "(GeV) in the ECAL" << endl;
04513       
04514       for( unsigned icand=0; icand<candidates.size(); icand++ ) 
04515         {
04516           ITM it    = candSimMatchEcal[icand].begin();
04517           ITM itend = candSimMatchEcal[icand].end();
04518           for(;it!=itend;++it)
04519             if( i == it->second )
04520               out<<icand<<" "<<it->first<<"GeV "<<(*pfCandidates_)[icand]<<endl;          
04521         }//loop candidate
04522       cout << endl;
04523     }//loop particles  
04524   }//verbose
04525 
04526 }//mctruthmatching
04527 //_____________________________________________________________________________
04528 
04529 edm::InputTag 
04530 PFRootEventManager::stringToTag(const std::vector< std::string >& tagname) { 
04531 
04532   if ( tagname.size() == 1 ) 
04533     return edm::InputTag(tagname[0]);
04534 
04535   else if ( tagname.size() == 2 ) 
04536     return edm::InputTag(tagname[0], tagname[1]);
04537 
04538   else if ( tagname.size() == 3 ) 
04539     return tagname[2] == '*' ? 
04540       edm::InputTag(tagname[0], tagname[1]) :
04541       edm::InputTag(tagname[0], tagname[1], tagname[2]);
04542   else {
04543     cout << "Invalid tag name with " << tagname.size() << " strings "<< endl;
04544     return edm::InputTag();
04545   }
04546   
04547 }