CMS 3D CMS Logo

PrimaryVertexAnalyzer.cc

Go to the documentation of this file.
00001 #include "Validation/RecoVertex/interface/PrimaryVertexAnalyzer.h"
00002 
00003 #include "FWCore/ParameterSet/interface/ParameterSet.h"
00004 #include "FWCore/MessageLogger/interface/MessageLogger.h"
00005 
00006 // reco track and vertex 
00007 #include "DataFormats/TrackReco/interface/Track.h"
00008 #include "DataFormats/VertexReco/interface/Vertex.h"
00009 #include "RecoVertex/VertexPrimitives/interface/TransientVertex.h"
00010 
00011 // simulated vertices,..., add <use name=SimDataFormats/Vertex> and <../Track>
00012 #include <SimDataFormats/Vertex/interface/SimVertex.h>
00013 #include <SimDataFormats/Vertex/interface/SimVertexContainer.h>
00014 #include <SimDataFormats/Track/interface/SimTrack.h>
00015 #include <SimDataFormats/Track/interface/SimTrackContainer.h>
00016 
00017 //generator level + CLHEP
00018 #include "HepMC/GenEvent.h"
00019 #include "HepMC/GenVertex.h"
00020 //#include "SimGeneral/HepPDTRecord/interface/ParticleDataTable.h"
00021 
00022 #include "CommonTools/Statistics/interface/ChiSquaredProbability.h"
00023 
00024 // Root
00025 #include <TH1.h>
00026 #include <TH2.h>
00027 #include <TFile.h>
00028 #include <TProfile.h>
00029  
00030 #include <cmath>
00031 #include <gsl/gsl_math.h>
00032 #include <gsl/gsl_eigen.h>
00033 
00034 
00035 using namespace edm;
00036 using namespace reco;
00037 //
00038 // constants, enums and typedefs
00039 //
00040 
00041 //
00042 // static data member definitions
00043 //
00044 
00045 //
00046 // constructors and destructor
00047 //
00048 PrimaryVertexAnalyzer::PrimaryVertexAnalyzer(const ParameterSet& iConfig)
00049 {
00050    //now do what ever initialization is needed
00051   simG4_=iConfig.getParameter<edm::InputTag>( "simG4" );
00052   recoTrackProducer_= iConfig.getUntrackedParameter<std::string>("recoTrackProducer");
00053   // open output file to store histograms}
00054   outputFile_  = iConfig.getUntrackedParameter<std::string>("outputFile");
00055   TString tversion(edm::getReleaseVersion());
00056   tversion = tversion.Remove(0,1);
00057   tversion = tversion.Remove(tversion.Length()-1,tversion.Length());
00058   outputFile_  = std::string(tversion)+"_"+outputFile_;
00059 
00060   vtxSample_   = iConfig.getUntrackedParameter<std::vector< std::string > >("vtxSample");
00061   for(std::vector<std::string>::iterator isample = vtxSample_.begin(); isample!=vtxSample_.end(); ++isample) {
00062     if ( *isample == "offlinePrimaryVerticesFromCTFTracks" ) suffixSample_.push_back("AVF");
00063     if ( *isample == "offlinePrimaryVerticesFromCTFTracksAVF" ) suffixSample_.push_back("AVF");
00064     if ( *isample == "offlinePrimaryVerticesFromCTFTracksKVF" ) suffixSample_.push_back("KVF");
00065     if ( *isample == "offlinePrimaryVerticesFromCTFTracksTKF" ) suffixSample_.push_back("TKF");
00066   }
00067   if ( suffixSample_.size() == 0 ) throw cms::Exception("NoVertexSamples") << " no known vertex samples given";
00068 
00069   rootFile_ = new TFile(outputFile_.c_str(),"RECREATE");
00070   verbose_= iConfig.getUntrackedParameter<bool>("verbose", false);
00071   simUnit_= 1.0;  // starting with CMSSW_1_2_x ??
00072   if ( (edm::getReleaseVersion()).find("CMSSW_1_1_",0)!=std::string::npos){
00073     simUnit_=0.1;  // for use in  CMSSW_1_1_1 tutorial
00074   }
00075 }
00076 
00077 
00078 PrimaryVertexAnalyzer::~PrimaryVertexAnalyzer()
00079 {
00080     // do anything here that needs to be done at desctruction time
00081    // (e.g. close files, deallocate resources etc.)
00082    delete rootFile_;
00083    /*for(std::map<std::string,TH1*>::const_iterator hist=h.begin(); hist!=h.end(); hist++){
00084     delete hist->second;
00085     }*/
00086    
00087 }
00088 
00089 
00090 
00091 //
00092 // member functions
00093 //
00094 void PrimaryVertexAnalyzer::beginJob(edm::EventSetup const& iSetup){
00095   std::cout << " PrimaryVertexAnalyzer::beginJob  conversion from sim units to rec units is " << simUnit_ << std::endl;
00096 
00097 
00098   rootFile_->cd();
00099   // release validation histograms used in DoCompare.C
00100   for (std::vector<std::string>::iterator isuffix= suffixSample_.begin(); isuffix!=suffixSample_.end(); ++isuffix++) {
00101 
00102     hdir[*isuffix] = rootFile_->mkdir(TString(*isuffix));
00103     hdir[*isuffix]->cd();
00104     h["nbvtx"+ *isuffix]        = new TH1F(TString("nbvtx"+ *isuffix),"Reconstructed Vertices in Event",20,-0.5,19.5);
00105     h["nbtksinvtx"+ *isuffix]   = new TH1F(TString("nbtksinvtx"+ *isuffix),"Reconstructed Tracks in Vertex",40,-0.5,39.5); 
00106     h["resx"+ *isuffix]         = new TH1F(TString("resx"+ *isuffix),"Residual X",100,-0.04,0.04);
00107     h["resy"+ *isuffix]         = new TH1F(TString("resy"+ *isuffix),"Residual Y",100,-0.04,0.04);
00108     h["resz"+ *isuffix]         = new TH1F(TString("resz"+ *isuffix),"Residual Z",100,-0.1,0.1);
00109     h["pullx"+ *isuffix]        = new TH1F(TString("pullx"+ *isuffix),"Pull X",100,-25.,25.);
00110     h["pully"+ *isuffix]        = new TH1F(TString("pully"+ *isuffix),"Pull Y",100,-25.,25.);
00111     h["pullz"+ *isuffix]        = new TH1F(TString("pullz"+ *isuffix),"Pull Z",100,-25.,25.);
00112     h["vtxchi2"+ *isuffix]      = new TH1F(TString("vtxchi2"+ *isuffix),"#chi^{2}",100,0.,100.);
00113     h["vtxndf"+ *isuffix]       = new TH1F(TString("vtxndf"+ *isuffix),"ndof",100,0.,100.);
00114     h["tklinks"+ *isuffix]      = new TH1F(TString("tklinks"+ *isuffix),"Usable track links",2,-0.5,1.5);
00115     h["nans"+ *isuffix]         = new TH1F(TString("nans"+ *isuffix),"Illegal values for x,y,z,xx,xy,xz,yy,yz,zz",9,0.5,9.5);
00116     // more histograms
00117     h["vtxprob"+ *isuffix]      = new TH1F(TString("vtxprob"+ *isuffix),"#chi^{2} probability",100,0.,1.);
00118     h["eff"+ *isuffix]          = new TH1F(TString("eff"+ *isuffix),"efficiency",2, -0.5, 1.5);
00119     h["efftag"+ *isuffix]       = new TH1F(TString("efftag"+ *isuffix),"efficiency tagged vertex",2, -0.5, 1.5);
00120     h["effvseta"+ *isuffix]     = new TProfile(TString("effvseta"+ *isuffix),"efficiency vs eta",20, -2.5, 2.5, 0, 1.);
00121     h["effvsptsq"+ *isuffix]    = new TProfile(TString("effvsptsq"+ *isuffix),"efficiency vs ptsq",20, 0., 10000., 0, 1.);
00122     h["effvsntrk"+ *isuffix]    = new TProfile(TString("effvsntrk"+ *isuffix),"efficiency vs # tracks",50, 0., 50., 0, 1.);
00123     h["effvsnrectrk"+ *isuffix] = new TProfile(TString("effvsnrectrk"+ *isuffix),"efficiency vs # rectracks",50, 0., 50., 0, 1.);
00124     h["effvsz"+ *isuffix]       = new TProfile(TString("effvsz"+ *isuffix),"efficiency vs z",40, -20., 20., 0, 1.);
00125     h["nbsimtksinvtx"+ *isuffix]= new TH1F(TString("nbsimtksinvtx"+ *isuffix),"simulated tracks in vertex",100,-0.5,99.5); 
00126     h["xrec"+ *isuffix]         = new TH1F(TString("xrec"+ *isuffix),"reconstructed x",100,-0.01,0.01);
00127     h["yrec"+ *isuffix]         = new TH1F(TString("yrec"+ *isuffix),"reconstructed y",100,-0.01,0.01);
00128     h["zrec"+ *isuffix]         = new TH1F(TString("zrec"+ *isuffix),"reconstructed z",100,-20.,20.);
00129     h["xsim"+ *isuffix]         = new TH1F(TString("xsim"+ *isuffix),"simulated x",100,-0.01,0.01); // 0.01cm = 100 um
00130     h["ysim"+ *isuffix]         = new TH1F(TString("ysim"+ *isuffix),"simulated y",100,-0.01,0.01);
00131     h["zsim"+ *isuffix]         = new TH1F(TString("zsim"+ *isuffix),"simulated z",100,-20.,20.);
00132     h["nrecvtx"+ *isuffix]      = new TH1F(TString("nrecvtx"+ *isuffix),"# of reconstructed vertices", 50, -0.5, 49.5);
00133     h["nsimvtx"+ *isuffix]      = new TH1F(TString("nsimvtx"+ *isuffix),"# of simulated vertices", 50, -0.5, 49.5);
00134     h["nrectrk"+ *isuffix]      = new TH1F(TString("nrectrk"+ *isuffix),"# of reconstructed tracks", 50, -0.5, 49.5);
00135     h["nsimtrk"+ *isuffix]      = new TH1F(TString("nsimtrk"+ *isuffix),"# of simulated tracks", 50, -0.5, 49.5);
00136     h["xrectag"+ *isuffix]      = new TH1F(TString("xrectag"+ *isuffix),"reconstructed x, signal vtx",100,-0.01,0.01);
00137     h["yrectag"+ *isuffix]      = new TH1F(TString("yrectag"+ *isuffix),"reconstructed y, signal vtx",100,-0.01,0.01);
00138     h["zrectag"+ *isuffix]      = new TH1F(TString("zrectag"+ *isuffix),"reconstructed z, signal vtx",100,-20.,20.);
00139     h["rapidity"+ *isuffix] = new TH1F(TString("rapidity"+ *isuffix),"rapidity ",100,-10., 10.);
00140     h["pt"+ *isuffix] = new TH1F(TString("pt"+ *isuffix),"pt ",100,0., 20.);
00141     h["nrectrk0vtx"+ *isuffix] = new TH1F(TString("nrectrk0vtx"+ *isuffix),"# rec tracks no vertex ",50,0., 50.);
00142     h["zdistancetag"+ *isuffix] = new TH1F(TString("zdistancetag"+ *isuffix),"z-distance between tagged and generated",100, -0.1, 0.1);
00143     h["puritytag"+ *isuffix]    = new TH1F(TString("puritytag"+ *isuffix),"purity of primary vertex tags",2, -0.5, 1.5);
00144   }
00145 
00146 }
00147 
00148 
00149 void PrimaryVertexAnalyzer::endJob() {
00150   
00151   rootFile_->cd();
00152   // save all histograms created in beginJob()
00153 
00154   for(std::map<std::string,TDirectory*>::const_iterator idir=hdir.begin(); idir!=hdir.end(); ++idir){
00155     idir->second->Write(); 
00156     idir->second->Close();
00157     }
00158   //for(std::map<std::string,TH1*>::const_iterator hist=h.begin(); hist!=h.end(); hist++){
00159   //   hist->second->Write();
00160   // }
00161   
00162 }
00163 
00164 
00165 // helper functions
00166 bool PrimaryVertexAnalyzer::matchVertex(const simPrimaryVertex  &vsim, 
00167                                        const reco::Vertex       &vrec){
00168   return (fabs(vsim.z*simUnit_-vrec.z())<0.0500); // =500um
00169 }
00170 
00171 bool PrimaryVertexAnalyzer::isResonance(const HepMC::GenParticle * p){
00172   double ctau=(pdt->particle( abs(p->pdg_id()) ))->lifetime();
00173   std::cout << "isResonance   " << p->pdg_id() << " " << ctau << std::endl;
00174   return  ctau >0 && ctau <1e-6;
00175 }
00176 
00177 bool PrimaryVertexAnalyzer::isFinalstateParticle(const HepMC::GenParticle * p){
00178   return ( !p->end_vertex() && p->status()==1 );
00179 }
00180 
00181 bool PrimaryVertexAnalyzer::isCharged(const HepMC::GenParticle * p){
00182   const ParticleData * part = pdt->particle( p->pdg_id() );
00183   if (part){
00184     return part->charge()!=0;
00185   }else{
00186     // the new/improved particle table doesn't know anti-particles
00187     return  pdt->particle( -p->pdg_id() )!=0;
00188   }
00189 }
00190 
00191 void PrimaryVertexAnalyzer::printRecVtxs(const Handle<reco::VertexCollection> recVtxs){
00192     int ivtx=0;
00193     for(reco::VertexCollection::const_iterator v=recVtxs->begin(); 
00194         v!=recVtxs->end(); ++v){
00195       std::cout << "Recvtx "<< std::setw(3) << std::setfill(' ')<<ivtx++
00196                 << "#trk " << std::setw(3) << v->tracksSize() 
00197                 << " chi2 " << std::setw(4) << v->chi2() 
00198                 << " ndof " << std::setw(3) << v->ndof() << std::endl 
00199                 << " x "  << std::setw(8) <<std::fixed << std::setprecision(4) << v->x() 
00200                 << " dx " << std::setw(8) << v->xError()<< std::endl
00201                 << " y "  << std::setw(8) << v->y() 
00202                 << " dy " << std::setw(8) << v->yError()<< std::endl
00203                 << " z "  << std::setw(8) << v->z() 
00204                 << " dz " << std::setw(8) << v->zError()
00205                 << std::endl;
00206     }
00207 }
00208 
00209 
00210 void PrimaryVertexAnalyzer::printSimVtxs(const Handle<SimVertexContainer> simVtxs){
00211     int i=0;
00212     for(SimVertexContainer::const_iterator vsim=simVtxs->begin();
00213         vsim!=simVtxs->end(); ++vsim){
00214       std::cout << i++ << ")" << std::scientific
00215                 << " evtid=" << vsim->eventId().event() 
00216                 << " sim x=" << vsim->position().x()*simUnit_
00217                 << " sim y=" << vsim->position().y()*simUnit_
00218                 << " sim z=" << vsim->position().z()*simUnit_
00219                 << " sim t=" << vsim->position().t()
00220                 << " parent=" << vsim->parentIndex() 
00221                 << std::endl;
00222     }
00223 }
00224 
00225 
00226 void PrimaryVertexAnalyzer::printSimTrks(const Handle<SimTrackContainer> simTrks){
00227   std::cout <<  " simTrks   type, (momentum), vertIndex, genpartIndex"  << std::endl;
00228   int i=1;
00229   for(SimTrackContainer::const_iterator t=simTrks->begin();
00230       t!=simTrks->end(); ++t){
00231     //HepMC::GenParticle* gp=evtMC->GetEvent()->particle( (*t).genpartIndex() );
00232     std::cout << i++ << ")" 
00233               << (*t)
00234               << " index="
00235               << (*t).genpartIndex();
00236     //if (gp) {
00237     //  HepMC::GenVertex *gv=gp->production_vertex();
00238     //  std::cout  <<  " genvertex =" << (*gv);
00239     //}
00240     std::cout << std::endl;
00241   }
00242 }
00243 
00244 
00245 std::vector<PrimaryVertexAnalyzer::simPrimaryVertex> PrimaryVertexAnalyzer::getSimPVs(
00246                                       const Handle<HepMCProduct> evtMC, std::string suffix="")
00247 {
00248   std::vector<PrimaryVertexAnalyzer::simPrimaryVertex> simpv;
00249   const HepMC::GenEvent* evt=evtMC->GetEvent();
00250   if (evt) {
00251     std::cout << "process id " <<evt->signal_process_id()<<std::endl;
00252     std::cout <<"signal process vertex "<< ( evt->signal_process_vertex() ?
00253                                              evt->signal_process_vertex()->barcode() : 0 )   <<std::endl;
00254     std::cout <<"number of vertices " << evt->vertices_size() << std::endl;
00255 
00256 
00257     int idx=0;
00258     for(HepMC::GenEvent::vertex_const_iterator vitr= evt->vertices_begin();
00259         vitr != evt->vertices_end(); ++vitr ) 
00260       { // loop for vertex ...
00261         /*
00262         std::cout << "looking at vertex " << idx << std::endl;
00263         std::cout << "has parents  " <<(*vitr)->hasParents() << " n= " <<  (*vitr)->numParents()<< std::endl;
00264         std::cout << "has children  " << (*vitr)->hasChildren() <<  " n= " <<  (*vitr)->numChildren()<<  std::endl;
00265         */
00266         HepMC::FourVector pos = (*vitr)->position();
00267         //HepLorentzVector pos = (*vitr)->position();
00268         if (pos.t()>0) { continue;}
00269 
00270         bool hasMotherVertex=false;
00271         std::cout << "mothers" << std::endl;
00272         for ( HepMC::GenVertex::particle_iterator
00273               mother  = (*vitr)->particles_begin(HepMC::parents);
00274               mother != (*vitr)->particles_end(HepMC::parents);
00275               ++mother ) {
00276           HepMC::GenVertex * mv=(*mother)->production_vertex();
00277           if (mv) {hasMotherVertex=true;}
00278           std::cout << "\t";
00279           (*mother)->print();
00280         }
00281         /*
00282         std::cout << "daughters" << std::endl;
00283         for ( HepMC::GenVertex::particle_iterator
00284               daughter  = (*vitr)->particles_begin(HepMC::children);
00285               daughter != (*vitr)->particles_end(HepMC::children);
00286               ++daughter ) {
00287           (*daughter)->print();
00288         }
00289         std::cout << " hasMotherVertex " << hasMotherVertex <<std::endl;
00290         */
00291 
00292         if(hasMotherVertex) {continue;}
00293 
00294         // could be a new vertex, check  all primaries found so far to avoid multiple entries
00295         const double mm=0.1;
00296         simPrimaryVertex sv(pos.x()*mm,pos.y()*mm,pos.z()*mm);
00297         simPrimaryVertex *vp=NULL;  // will become non-NULL if a vertex is found and then point to it
00298         for(std::vector<simPrimaryVertex>::iterator v0=simpv.begin();
00299             v0!=simpv.end(); v0++){
00300           if( (fabs(sv.x-v0->x)<1e-5) && (fabs(sv.y-v0->y)<1e-5) && (fabs(sv.z-v0->z)<1e-5)){
00301             vp=&(*v0);
00302             break;
00303           }
00304         }
00305 
00306         if(!vp){
00307           // this is a new vertex
00308           std::cout << "this is a new vertex" << sv.x << " " << sv.y << " " << sv.z <<std::endl;
00309           simpv.push_back(sv);
00310           vp=&simpv.back();
00311         }else{
00312           std::cout << "this is not new vertex" << std::endl;
00313         }
00314         vp->genVertex.push_back((*vitr)->barcode());
00315         // collect final state descendants
00316         for ( HepMC::GenVertex::particle_iterator
00317               daughter  = (*vitr)->particles_begin(HepMC::descendants);
00318               daughter != (*vitr)->particles_end(HepMC::descendants);
00319               ++daughter ) {
00320           if (isFinalstateParticle(*daughter)){ 
00321             if ( find(vp->finalstateParticles.begin(), vp->finalstateParticles.end(),(*daughter)->barcode())
00322                  == vp->finalstateParticles.end()){
00323               vp->finalstateParticles.push_back((*daughter)->barcode());
00324               HepMC::FourVector m=(*daughter)->momentum();
00325               // the next four lines used to be "vp->ptot+=m;" in the days of CLHEP::HepLorentzVector
00326               // but adding FourVectors seems not to be foreseen
00327               vp->ptot.setPx(vp->ptot.px()+m.px());
00328               vp->ptot.setPy(vp->ptot.py()+m.py());
00329               vp->ptot.setPz(vp->ptot.pz()+m.pz());
00330               vp->ptot.setE(vp->ptot.e()+m.e());
00331               vp->ptsq+=(m.perp())*(m.perp());
00332               if ( (m.perp()>0.8) && (fabs(m.pseudoRapidity())<2.5) && isCharged( *daughter ) ){
00333                 vp->nGenTrk++;
00334               }
00335               
00336               h["rapidity"+suffix]->Fill(m.pseudoRapidity());
00337               h["pt"+suffix]->Fill(m.perp());
00338             }
00339           }
00340         }
00341         idx++;
00342       }
00343   }
00344   return simpv;
00345 }
00346 
00347 
00348 
00349 std::vector<PrimaryVertexAnalyzer::simPrimaryVertex> PrimaryVertexAnalyzer::getSimPVs(
00350                                       const Handle<HepMCProduct> evtMC, 
00351                                       const Handle<SimVertexContainer> simVtxs, 
00352                                       const Handle<SimTrackContainer> simTrks)
00353 {
00354    // simvertices don't have enough information to decide, 
00355    // genVertices don't have the simulated coordinates  ( with VtxSmeared they might)
00356    // go through simtracks to get the link between simulated and generated vertices
00357    std::vector<PrimaryVertexAnalyzer::simPrimaryVertex> simpv;
00358    int idx=0;
00359    for(SimTrackContainer::const_iterator t=simTrks->begin();
00360        t!=simTrks->end(); ++t){
00361      if ( !(t->noVertex()) && !(t->type()==-99) ){
00362        double ptsq=0;
00363        bool primary=false;   // something coming directly from the primary vertex
00364        bool resonance=false; // resonance
00365        bool track=false;     // undecayed, charged particle
00366        HepMC::GenParticle* gp=evtMC->GetEvent()->barcode_to_particle( (*t).genpartIndex() );
00367        if (gp) {
00368          HepMC::GenVertex * gv=gp->production_vertex();
00369          if (gv) {
00370            for ( HepMC::GenVertex::particle_iterator 
00371                  daughter =  gv->particles_begin(HepMC::descendants);
00372                  daughter != gv->particles_end(HepMC::descendants);
00373                  ++daughter ) {
00374              if (isFinalstateParticle(*daughter)){
00375                ptsq+=(*daughter)->momentum().perp()*(*daughter)->momentum().perp();
00376              }
00377            }
00378            primary =  ( gv->position().t()==0);
00379            //resonance= ( gp->mother() && isResonance(gp->mother()));  // in CLHEP/HepMC days
00380            // no more mother pointer in the improved HepMC GenParticle
00381            resonance= ( isResonance(*(gp->production_vertex()->particles_in_const_begin())));
00382            if (gp->status()==1){
00383              //track=((pdt->particle(gp->pdg_id()))->charge() != 0);
00384              track=not isCharged(gp);
00385            }
00386          }
00387        }
00388 
00389        const HepMC::FourVector & v=(*simVtxs)[t->vertIndex()].position();
00390        //const HepLorentzVector & v=(*simVtxs)[t->vertIndex()].position();
00391        if(primary or resonance){
00392          {
00393            // check all primaries found so far to avoid multiple entries
00394            bool newVertex=true;
00395            for(std::vector<simPrimaryVertex>::iterator v0=simpv.begin();
00396                v0!=simpv.end(); v0++){
00397              if( (fabs(v0->x-v.x())<0.001) && (fabs(v0->y-v.y())<0.001) && (fabs(v0->z-v.z())<0.001) ){
00398                if (track) {
00399                  v0->simTrackIndex.push_back(idx);
00400                  if (ptsq>(*v0).ptsq){(*v0).ptsq=ptsq;}
00401                }
00402                newVertex=false;
00403              }
00404            }
00405            if(newVertex && !resonance){
00406              simPrimaryVertex anotherVertex(v.x(),v.y(),v.z());
00407              if (track) anotherVertex.simTrackIndex.push_back(idx);
00408              anotherVertex.ptsq=ptsq;
00409              simpv.push_back(anotherVertex);
00410            }
00411          }// 
00412        }
00413        
00414      }// simtrack has vertex and valid type
00415      idx++;
00416    }//simTrack loop
00417    return simpv;
00418 }
00419 
00420 
00421 
00422 
00423 // ------------ method called to produce the data  ------------
00424 void
00425 PrimaryVertexAnalyzer::analyze(const Event& iEvent, const EventSetup& iSetup)
00426 {
00427   
00428   Handle<reco::TrackCollection> recTrks;
00429   iEvent.getByLabel(recoTrackProducer_, recTrks);
00430 
00431   Handle<SimVertexContainer> simVtxs;
00432   iEvent.getByLabel( simG4_, simVtxs);
00433   
00434   Handle<SimTrackContainer> simTrks;
00435   iEvent.getByLabel( simG4_, simTrks);
00436 
00437   for (int ivtxSample=0; ivtxSample!= (int)vtxSample_.size(); ++ivtxSample) {
00438     std::string isuffix = suffixSample_[ivtxSample];
00439 
00440     Handle<reco::VertexCollection> recVtxs;
00441     iEvent.getByLabel(vtxSample_[ivtxSample], recVtxs);
00442 
00443   try{
00444     iSetup.getData(pdt);
00445   }catch(const Exception&){
00446     std::cout << "Some problem occurred with the particle data table. This may not work !." <<std::endl;
00447   }
00448 
00449   bool MC=false;
00450   Handle<HepMCProduct> evtMC;
00451   /* 
00452  try{
00453      iEvent.getByLabel("VtxSmeared",evtMC);
00454     MC=true;
00455     if(verbose_){
00456       std::cout << "VtxSmeared HepMCProduct found"<< std::endl;
00457     }
00458     //if(evtMC->GetEvent()){ evtMC->GetEvent()->print();
00459   }catch(const Exception&){
00460     // VtxSmeared not found, try source
00461     try{
00462       iEvent.getByLabel("source",evtMC);
00463       if(verbose_){
00464         std::cout << "source HepMCProduct found"<< std::endl;
00465       }
00466       MC=true;
00467     }catch(const Exception&) {
00468       MC=false;
00469       if(verbose_){
00470         std::cout << "no HepMCProduct found"<< std::endl;
00471       }
00472     }
00473   }
00474  */
00475   iEvent.getByLabel("source",evtMC);
00476   if (!evtMC.isValid()) {
00477     MC=false;
00478     if(verbose_){
00479       std::cout << "no HepMCProduct found"<< std::endl;
00480     }
00481   } else {
00482     if(verbose_){
00483       std::cout << "source HepMCProduct found"<< std::endl;
00484     }
00485     MC=true;
00486   }
00487 
00488   /*
00489   if(evtMC->GetEvent()->signal_process_vertex()){
00490     HepLorentzVector vsig=evtMC->GetEvent()->signal_process_vertex()->position();
00491     std::cout <<" signal vertex " << vsig.x() << " " << vsig.z() << std::endl;
00492   }else{
00493     std::cout <<" no signal vertex"  << std::endl;
00494   }
00495   */
00496 
00497   if(verbose_){
00498     //evtMC->GetEvent()->print();
00499     printRecVtxs(recVtxs);
00500     //printSimVtxs(simVtxs);
00501     //printSimTrks(simTrks);
00502   }
00503 
00504   if(MC){
00505    // make a list of primary vertices:
00506    std::vector<simPrimaryVertex> simpv;
00507    //simpv=getSimPVs(evtMC, simVtxs, simTrks);
00508    simpv=getSimPVs(evtMC,isuffix);
00509 
00510    /*
00511    if(verbose_){
00512      for(std::vector<simPrimaryVertex>::const_iterator vsim=simpv.begin();
00513          vsim!=simpv.end(); vsim++){
00514        std::cout <<"primary " << vsim->x << " " << vsim->y << " " << vsim->z << " : ";
00515        for(unsigned int i=0; i<vsim->simTrackIndex.size(); i++){
00516          std::cout << (*simTrks)[vsim->simTrackIndex[i]].type() << " ";
00517        }
00518        std::cout << std::endl;
00519      }
00520    }
00521    */
00522 
00523    // vertex matching and efficiency bookkeeping
00524    h["nsimvtx"+isuffix]->Fill(simpv.size());
00525    int nsimtrk=0;
00526    for(std::vector<simPrimaryVertex>::iterator vsim=simpv.begin();
00527        vsim!=simpv.end(); vsim++){
00528 
00529      hdir[isuffix]->cd();
00530            
00531      h["nbsimtksinvtx"+isuffix]->Fill(vsim->nGenTrk);
00532      h["xsim"+isuffix]->Fill(vsim->x*simUnit_);
00533      h["ysim"+isuffix]->Fill(vsim->y*simUnit_);
00534      h["zsim"+isuffix]->Fill(vsim->z*simUnit_);
00535      nsimtrk+=vsim->nGenTrk;
00536      // look for a matching reconstructed vertex
00537      vsim->recVtx=NULL;
00538      for(reco::VertexCollection::const_iterator vrec=recVtxs->begin(); 
00539          vrec!=recVtxs->end(); ++vrec){
00540        if ( matchVertex(*vsim,*vrec) ){
00541          // if the matching critera are fulfilled, accept the rec-vertex that is closest in z
00542          if(    ((vsim->recVtx) && (fabs(vsim->recVtx->position().z()-vsim->z)>fabs(vrec->z()-vsim->z)))
00543                 || (!vsim->recVtx) )
00544            {
00545              vsim->recVtx=&(*vrec);
00546            }
00547        }
00548      }
00549      h["nsimtrk"+isuffix]->Fill(float(nsimtrk));
00550      
00551        
00552      // histogram properties of matched vertices
00553      if (vsim->recVtx){
00554        
00555        if(verbose_){std::cout <<"primary matched " << vsim->x << " " << vsim->y << " " << vsim->z << std:: endl;}
00556        
00557        h["resx"+isuffix]->Fill( vsim->recVtx->x()-vsim->x*simUnit_ );
00558        h["resy"+isuffix]->Fill( vsim->recVtx->y()-vsim->y*simUnit_ );
00559        h["resz"+isuffix]->Fill( vsim->recVtx->z()-vsim->z*simUnit_ );
00560        h["pullx"+isuffix]->Fill( (vsim->recVtx->x()-vsim->x*simUnit_)/vsim->recVtx->xError() );
00561        h["pully"+isuffix]->Fill( (vsim->recVtx->y()-vsim->y*simUnit_)/vsim->recVtx->yError() );
00562        h["pullz"+isuffix]->Fill( (vsim->recVtx->z()-vsim->z*simUnit_)/vsim->recVtx->zError() );
00563        h["eff"+isuffix]->Fill( 1.);
00564        if(simpv.size()==1){
00565          if (vsim->recVtx==&(*recVtxs->begin())){
00566            h["efftag"+isuffix]->Fill( 1.); 
00567          }else{
00568            h["efftag"+isuffix]->Fill( 0.); 
00569          }
00570        }
00571        h["effvseta"+isuffix]->Fill(vsim->ptot.pseudoRapidity(),1.);
00572        h["effvsptsq"+isuffix]->Fill(vsim->ptsq,1.);
00573        h["effvsntrk"+isuffix]->Fill(vsim->nGenTrk,1.);
00574        h["effvsnrectrk"+isuffix]->Fill(recTrks->size(),1.);
00575        h["effvsz"+isuffix]->Fill(vsim->z*simUnit_,1.);
00576        
00577      }else{  // no rec vertex found for this simvertex
00578        
00579        if(verbose_){std::cout <<"primary not found " << vsim->x << " " << vsim->y << " " << vsim->z << " nGenTrk=" << vsim->nGenTrk << std::endl;}
00580 
00581        h["eff"+isuffix]->Fill( 0.);
00582        if(simpv.size()==1){ h["efftag"+isuffix]->Fill( 0.); }
00583        h["effvseta"+isuffix]->Fill(vsim->ptot.pseudoRapidity(),0.);
00584        h["effvsptsq"+isuffix]->Fill(vsim->ptsq,0.);
00585        h["effvsntrk"+isuffix]->Fill(float(vsim->nGenTrk),0.);
00586        h["effvsnrectrk"+isuffix]->Fill(recTrks->size(),0.);
00587        h["effvsz"+isuffix]->Fill(vsim->z*simUnit_,0.);
00588      } // no recvertex for this simvertex
00589    }//found MC event
00590    // end of sim/rec matching 
00591    
00592      
00593    // purity of event vertex tags
00594    if (recVtxs->size()>0){
00595      Double_t dz=(*recVtxs->begin()).z() - (*simpv.begin()).z*simUnit_;
00596      h["zdistancetag"+isuffix]->Fill(dz);
00597      if( fabs(dz)<0.0500){
00598        h["puritytag"+isuffix]->Fill(1.);
00599      }else{
00600        // bad tag: the true primary was more than 500 um away from the tagged primary
00601        h["puritytag"+isuffix]->Fill(0.);
00602      }
00603    }
00604 
00605 
00606   }// MC event
00607 
00608   // test track links, use reconstructed vertices
00609 
00610   h["nrecvtx"+isuffix]->Fill(recVtxs->size());
00611   h["nrectrk"+isuffix]->Fill(recTrks->size());
00612   if(recVtxs->size()==0) {h["nrectrk0vtx"+isuffix]->Fill(recTrks->size());}
00613 
00614   for(reco::VertexCollection::const_iterator v=recVtxs->begin(); 
00615       v!=recVtxs->end(); ++v){
00616 
00617     try {
00618       for(reco::Vertex::trackRef_iterator t = v->tracks_begin(); 
00619           t!=v->tracks_end(); t++) {
00620         // illegal charge
00621         if ( (**t).charge() < -1 || (**t).charge() > 1 ) {
00622           h["tklinks"+isuffix]->Fill(0.);
00623         }
00624         else {
00625           h["tklinks"+isuffix]->Fill(1.);
00626         }
00627       }
00628     }
00629     catch (...) {
00630       // exception thrown when trying to use linked track
00631       h["tklinks"+isuffix]->Fill(0.);
00632     }
00633 
00634     h["nbvtx"+isuffix]->Fill(recVtxs->size()*1.);
00635     h["nbtksinvtx"+isuffix]->Fill(v->tracksSize());
00636     h["vtxchi2"+isuffix]->Fill(v->chi2());
00637     h["vtxndf"+isuffix]->Fill(v->ndof());
00638     h["vtxprob"+isuffix]->Fill(ChiSquaredProbability(v->chi2() ,v->ndof()));
00639     h["xrec"+isuffix]->Fill(v->position().x());
00640     h["yrec"+isuffix]->Fill(v->position().y());
00641     h["zrec"+isuffix]->Fill(v->position().z());
00642     if (v==recVtxs->begin()){
00643       h["xrectag"+isuffix]->Fill(v->position().x());
00644       h["yrectag"+isuffix]->Fill(v->position().y());
00645       h["zrectag"+isuffix]->Fill(v->position().z());
00646     }
00647 
00648     bool problem = false;
00649     h["nans"+isuffix]->Fill(1.,isnan(v->position().x())*1.);
00650     h["nans"+isuffix]->Fill(2.,isnan(v->position().y())*1.);
00651     h["nans"+isuffix]->Fill(3.,isnan(v->position().z())*1.);
00652 
00653     int index = 3;
00654     for (int i = 0; i != 3; i++) {
00655       for (int j = i; j != 3; j++) {
00656         index++;
00657         h["nans"+isuffix]->Fill(index*1., isnan(v->covariance(i, j))*1.);
00658         if (isnan(v->covariance(i, j))) problem = true;
00659         // in addition, diagonal element must be positive
00660         if (j == i && v->covariance(i, j) < 0) {
00661           h["nans"+isuffix]->Fill(index*1., 1.);
00662           problem = true;
00663         }
00664       }
00665     }
00666 
00667     if (problem) {
00668       // analyze track parameter covariance definiteness
00669       double data[25];
00670       try {
00671         int itk = 0;
00672         for(reco::Vertex::trackRef_iterator t = v->tracks_begin(); 
00673             t!=v->tracks_end(); t++) {
00674           std::cout << "Track " << itk++ << std::endl;
00675           int i2 = 0;
00676           for (int i = 0; i != 5; i++) {
00677             for (int j = 0; j != 5; j++) {
00678               data[i2] = (**t).covariance(i, j);
00679               std::cout << std:: scientific << data[i2] << " ";
00680               i2++;
00681             }
00682             std::cout << std::endl;
00683           }
00684           gsl_matrix_view m 
00685             = gsl_matrix_view_array (data, 5, 5);
00686           
00687           gsl_vector *eval = gsl_vector_alloc (5);
00688           gsl_matrix *evec = gsl_matrix_alloc (5, 5);
00689           
00690           gsl_eigen_symmv_workspace * w = 
00691             gsl_eigen_symmv_alloc (5);
00692           
00693           gsl_eigen_symmv (&m.matrix, eval, evec, w);
00694           
00695           gsl_eigen_symmv_free (w);
00696           
00697           gsl_eigen_symmv_sort (eval, evec, 
00698                                 GSL_EIGEN_SORT_ABS_ASC);
00699           
00700           // print sorted eigenvalues
00701           {
00702             int i;
00703             for (i = 0; i < 5; i++) {
00704               double eval_i 
00705                 = gsl_vector_get (eval, i);
00706               gsl_vector_view evec_i 
00707                 = gsl_matrix_column (evec, i);
00708               
00709               printf ("eigenvalue = %g\n", eval_i);
00710               //              printf ("eigenvector = \n");
00711               //              gsl_vector_fprintf (stdout, 
00712               //                                  &evec_i.vector, "%g");
00713             }
00714           }
00715         }
00716       }
00717       catch (...) {
00718         // exception thrown when trying to use linked track
00719         break;
00720       }
00721     }// if (problem)
00722   }
00723   } // for vertex loop
00724 }

Generated on Tue Jun 9 17:49:41 2009 for CMSSW by  doxygen 1.5.4