CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_5_3_8_patch3/src/Validation/RecoVertex/src/PrimaryVertexAnalyzer4PU.cc

Go to the documentation of this file.
00001 #include "Validation/RecoVertex/interface/PrimaryVertexAnalyzer4PU.h"
00002 
00003 #include "FWCore/ParameterSet/interface/ParameterSet.h"
00004 #include "FWCore/MessageLogger/interface/MessageLogger.h"
00005 #include "FWCore/Version/interface/GetReleaseVersion.h"
00006 #include "MagneticField/Engine/interface/MagneticField.h"
00007 
00008 // reco track and vertex 
00009 #include "DataFormats/TrackReco/interface/Track.h"
00010 #include "DataFormats/VertexReco/interface/Vertex.h"
00011 #include "DataFormats/Math/interface/Point3D.h"
00012 #include "RecoVertex/VertexPrimitives/interface/TransientVertex.h"
00013 
00014 // simulated vertices,..., add <use name=SimDataFormats/Vertex> and <../Track>
00015 #include <SimDataFormats/Vertex/interface/SimVertex.h>
00016 #include <SimDataFormats/Vertex/interface/SimVertexContainer.h>
00017 #include <SimDataFormats/Track/interface/SimTrack.h>
00018 #include <SimDataFormats/Track/interface/SimTrackContainer.h>
00019 
00020 #include "SimDataFormats/CrossingFrame/interface/CrossingFrame.h"
00021 #include "SimDataFormats/CrossingFrame/interface/CrossingFramePlaybackInfo.h"
00022 #include "SimDataFormats/CrossingFrame/interface/MixCollection.h"
00023 #include "SimDataFormats/TrackingHit/interface/PSimHit.h"
00024 
00025 //generator level + CLHEP
00026 #include "HepMC/GenEvent.h"
00027 #include "HepMC/GenVertex.h"
00028 
00029 
00030 // TrackingParticle
00031 #include "SimDataFormats/TrackingAnalysis/interface/TrackingParticleFwd.h"
00032 #include "SimDataFormats/TrackingAnalysis/interface/TrackingVertexContainer.h"
00033 //associator
00034 #include "SimTracker/Records/interface/TrackAssociatorRecord.h"
00035 
00036 
00037 // fit
00038 #include "RecoVertex/KalmanVertexFit/interface/KalmanVertexFitter.h"
00039 #include "RecoVertex/AdaptiveVertexFit/interface/AdaptiveVertexFitter.h"
00040 
00041 #include "CommonTools/Statistics/interface/ChiSquaredProbability.h"
00042 
00043 // Root
00044 #include <TH1.h>
00045 #include <TH2.h>
00046 #include <TFile.h>
00047 #include <TProfile.h>
00048  
00049 #include <cmath>
00050 #include <gsl/gsl_math.h>
00051 #include <gsl/gsl_eigen.h>
00052 
00053 
00054 // cluster stufff
00055 //#include "DataFormats/TrackRecoTrack.h"
00056 #include "DataFormats/TrackerRecHit2D/interface/SiPixelRecHitCollection.h"
00057 #include "Geometry/TrackerGeometryBuilder/interface/PixelGeomDetUnit.h"
00058 
00059 
00060 using namespace edm;
00061 using namespace reco;
00062 using namespace std;
00063 //
00064 // constants, enums and typedefs
00065 //
00066 typedef reco::Vertex::trackRef_iterator trackit_t;
00067 //
00068 // static data member definitions
00069 //
00070 
00071 //
00072 // constructors and destructor
00073 //
00074 PrimaryVertexAnalyzer4PU::PrimaryVertexAnalyzer4PU(const ParameterSet& iConfig):theTrackFilter(iConfig.getParameter<edm::ParameterSet>("TkFilterParameters"))
00075 {
00076    //now do what ever initialization is needed
00077   simG4_=iConfig.getParameter<edm::InputTag>( "simG4" );
00078   recoTrackProducer_= iConfig.getUntrackedParameter<std::string>("recoTrackProducer");
00079   // open output file to store histograms}
00080   outputFile_  = iConfig.getUntrackedParameter<std::string>("outputFile");
00081 
00082   rootFile_ = TFile::Open(outputFile_.c_str(),"RECREATE");
00083   verbose_= iConfig.getUntrackedParameter<bool>("verbose", false);
00084   doMatching_= iConfig.getUntrackedParameter<bool>("matching", false);
00085   printXBS_= iConfig.getUntrackedParameter<bool>("XBS", false);
00086   simUnit_= 1.0;  // starting with CMSSW_1_2_x ??
00087   if ( (edm::getReleaseVersion()).find("CMSSW_1_1_",0)!=std::string::npos){
00088     simUnit_=0.1;  // for use in  CMSSW_1_1_1 tutorial
00089   }
00090   
00091   dumpPUcandidates_=iConfig.getUntrackedParameter<bool>("dumpPUcandidates", false);
00092 
00093   zmatch_=iConfig.getUntrackedParameter<double>("zmatch", 0.0500);
00094   cout << "PrimaryVertexAnalyzer4PU: zmatch=" << zmatch_ << endl;
00095   eventcounter_=0;
00096   dumpcounter_=0;
00097   ndump_=10;
00098   DEBUG_=false;
00099   //DEBUG_=true;
00100 }
00101 
00102 
00103 
00104 
00105 PrimaryVertexAnalyzer4PU::~PrimaryVertexAnalyzer4PU()
00106 {
00107     // do anything here that needs to be done at desctruction time
00108    // (e.g. close files, deallocate resources etc.)
00109   delete rootFile_;
00110 }
00111 
00112 
00113 
00114 //
00115 // member functions
00116 //
00117 
00118 
00119 std::map<std::string, TH1*>  PrimaryVertexAnalyzer4PU::bookVertexHistograms(){
00120   std::map<std::string, TH1*> h;
00121 
00122   // release validation histograms used in DoCompare.C
00123   h["nbtksinvtx"]   = new TH1F("nbtksinvtx","reconstructed tracks in vertex",40,-0.5,39.5); 
00124   h["nbtksinvtxPU"] = new TH1F("nbtksinvtxPU","reconstructed tracks in vertex",40,-0.5,39.5); 
00125   h["nbtksinvtxTag"]= new TH1F("nbtksinvtxTag","reconstructed tracks in vertex",40,-0.5,39.5); 
00126   h["resx"]         = new TH1F("resx","residual x",100,-0.04,0.04);
00127   h["resy"]         = new TH1F("resy","residual y",100,-0.04,0.04);
00128   h["resz"]         = new TH1F("resz","residual z",100,-0.1,0.1);
00129   h["resz10"]       = new TH1F("resz10","residual z",100,-1.0,1.);
00130   h["pullx"]        = new TH1F("pullx","pull x",100,-25.,25.);
00131   h["pully"]        = new TH1F("pully","pull y",100,-25.,25.);
00132   h["pullz"]        = new TH1F("pullz","pull z",100,-25.,25.);
00133   h["vtxchi2"]      = new TH1F("vtxchi2","chi squared",100,0.,100.);
00134   h["vtxndf"]       = new TH1F("vtxndf","degrees of freedom",500,0.,100.);
00135   h["vtxndfc"]       = new TH1F("vtxndfc","expected 2nd highest ndof",500,0.,100.);
00136 
00137   h["vtxndfvsntk"]  = new TH2F("vtxndfvsntk","ndof vs #tracks",20,0.,100, 20, 0., 200.);
00138   h["vtxndfoverntk"]= new TH1F("vtxndfoverntk","ndof / #tracks",40,0.,2.);
00139   h["vtxndf2overntk"]= new TH1F("vtxndf2overntk","(ndof+2) / #tracks",40,0.,2.);
00140   h["tklinks"]      = new TH1F("tklinks","Usable track links",2,-0.5,1.5);
00141   h["nans"]         = new TH1F("nans","Illegal values for x,y,z,xx,xy,xz,yy,yz,zz",9,0.5,9.5);
00142 
00143 
00144   // raw
00145   add(h, new TH1F("szRecVtx","size of recvtx collection",20, -0.5, 19.5));
00146   add(h, new TH1F("isFake","fake vertex",2, -0.5, 1.5));
00147   add(h, new TH1F("isFake1","fake vertex or ndof<0",2, -0.5, 1.5));
00148   add(h, new TH1F("bunchCrossing","bunchCrossing",4000, 0., 4000.));
00149   add(h, new TH2F("bunchCrossingLogNtk","bunchCrossingLogNtk",4000, 0., 4000.,5,0., 5.));
00150   add(h, new TH1F("highpurityTrackFraction","fraction of high purity tracks",20, 0., 1.));
00151   add(h, new TH2F("trkchi2vsndof","vertices chi2 vs ndof",50, 0., 100., 50, 0., 200.));
00152   add(h, new TH1F("trkchi2overndof","vertices chi2 / ndof",50, 0., 5.));
00153   // two track vertices
00154   add(h,new TH2F("2trkchi2vsndof","two-track vertices chi2 vs ndof",40, 0., 10., 20, 0., 20.));
00155   add(h,new TH1F("2trkmassSS","two-track vertices mass (same sign)",100, 0., 2.));
00156   add(h,new TH1F("2trkmassOS","two-track vertices mass (opposite sign)",100, 0., 2.));
00157   add(h,new TH1F("2trkdphi","two-track vertices delta-phi",360, 0, 2*M_PI));
00158   add(h,new TH1F("2trkseta","two-track vertices sum-eta",50, -2., 2.));
00159   add(h,new TH1F("2trkdphicurl","two-track vertices delta-phi (sum eta<0.1)",360, 0, 2*M_PI));
00160   add(h,new TH1F("2trksetacurl","two-track vertices sum-eta (delta-phi<0.1)",50, -2., 2.));
00161   add(h,new TH1F("2trkdetaOS","two-track vertices delta-eta (same sign)",50, -0.5, 0.5));
00162   add(h,new TH1F("2trkdetaSS","two-track vertices delta-eta (opposite sign)",50, -0.5, 0.5));
00163   // two track PU vertices
00164   add(h,new TH1F("2trkmassSSPU","two-track vertices mass (same sign)",100, 0., 2.));
00165   add(h,new TH1F("2trkmassOSPU","two-track vertices mass (opposite sign)",100, 0., 2.));
00166   add(h,new TH1F("2trkdphiPU","two-track vertices delta-phi",360, 0, 2*M_PI));
00167   add(h,new TH1F("2trksetaPU","two-track vertices sum-eta",50, -2., 2.));
00168   add(h,new TH1F("2trkdphicurlPU","two-track vertices delta-phi (sum eta<0.1)",360, 0, 2*M_PI));
00169   add(h,new TH1F("2trksetacurlPU","two-track vertices sum-eta (delta-phi<0.1)",50, -2., 2.));
00170   add(h,new TH1F("2trkdetaOSPU","two-track vertices delta-eta (same sign)",50, -0.5, 0.5));
00171   add(h,new TH1F("2trkdetaSSPU","two-track vertices delta-eta (opposite sign)",50, -0.5, 0.5));
00172   // three track vertices
00173   add(h,new TH2F("2trkchi2vsndof","two-track vertices chi2 vs ndof",40, 0., 10., 20, 0., 20.));
00174   add(h,new TH2F("3trkchi2vsndof","three-track vertices chi2 vs ndof",40, 0., 10., 20, 0., 20.));
00175   add(h,new TH2F("4trkchi2vsndof","four-track vertices chi2 vs ndof",40, 0., 10., 20, 0., 20.));
00176   add(h,new TH2F("5trkchi2vsndof","five-track vertices chi2 vs ndof",40, 0., 10., 20, 0., 20.));
00177   // same for fakes
00178   add(h,new TH2F("fake2trkchi2vsndof","fake two-track vertices chi2 vs ndof",40, 0., 10., 20, 0., 20.));
00179   add(h,new TH2F("fake3trkchi2vsndof","fake three-track vertices chi2 vs ndof",40, 0., 10., 20, 0., 20.));
00180   add(h,new TH2F("fake4trkchi2vsndof","fake four-track vertices chi2 vs ndof",40, 0., 10., 20, 0., 20.));
00181   add(h,new TH2F("fake5trkchi2vsndof","fake five-track vertices chi2 vs ndof",40, 0., 10., 20, 0., 20.));
00182   h["resxr"]        = new TH1F("resxr","relative residual x",100,-0.04,0.04);
00183   h["resyr"]        = new TH1F("resyr","relative residual y",100,-0.04,0.04);
00184   h["reszr"]        = new TH1F("reszr","relative residual z",100,-0.1,0.1);
00185   h["pullxr"]       = new TH1F("pullxr","relative pull x",100,-25.,25.);
00186   h["pullyr"]       = new TH1F("pullyr","relative pull y",100,-25.,25.);
00187   h["pullzr"]       = new TH1F("pullzr","relative pull z",100,-25.,25.);
00188   h["vtxprob"]      = new TH1F("vtxprob","chisquared probability",100,0.,1.);
00189   h["eff"]          = new TH1F("eff","efficiency",2, -0.5, 1.5);
00190   h["efftag"]       = new TH1F("efftag","efficiency tagged vertex",2, -0.5, 1.5);
00191   h["zdistancetag"] = new TH1F("zdistancetag","z-distance between tagged and generated",100, -0.1, 0.1);
00192   h["abszdistancetag"] = new TH1F("abszdistancetag","z-distance between tagged and generated",1000, 0., 1.0);
00193   h["abszdistancetagcum"] = new TH1F("abszdistancetagcum","z-distance between tagged and generated",1000, 0., 1.0);
00194   h["puritytag"]    = new TH1F("puritytag","purity of primary vertex tags",2, -0.5, 1.5);
00195   h["effvsptsq"]    = new TProfile("effvsptsq","efficiency vs ptsq",20, 0., 10000., 0, 1.);
00196   h["effvsnsimtrk"] = new TProfile("effvsnsimtrk","efficiency vs # simtracks",50, 0., 50., 0, 1.);
00197   h["effvsnrectrk"] = new TProfile("effvsnrectrk","efficiency vs # rectracks",50, 0., 50., 0, 1.);
00198   h["effvsnseltrk"] = new TProfile("effvsnseltrk","efficiency vs # selected tracks",50, 0., 50., 0, 1.);
00199   h["effvsz"]       = new TProfile("effvsz","efficiency vs z",20, -20., 20., 0, 1.);
00200   h["effvsz2"]      = new TProfile("effvsz2","efficiency vs z (2mm)",20, -20., 20., 0, 1.);
00201   h["effvsr"]       = new TProfile("effvsr","efficiency vs r",20, 0., 1., 0, 1.);
00202   h["xresvsntrk"] = new TProfile("xresvsntrk","xresolution vs # vertex tracks",40, 0., 200., 0, 0.01);
00203   h["yresvsntrk"] = new TProfile("yresvsntrk","yresolution vs # vertex tracks",40, 0., 200., 0, 0.01);
00204   h["zresvsntrk"] = new TProfile("zresvsntrk","zresolution vs # vertex tracks",40, 0., 200., 0, 0.01);
00205   h["cpuvsntrk"] = new TProfile("cpuvsntrk","cpu time vs # of fitted tracks",40, 0., 200., 0, 200.);
00206   h["cpucluvsntrk"] = new TProfile("cpucluvsntrk","clustering cpu time # of tracks",40, 0., 200., 0, 10.);
00207   h["cpufit"]    = new TH1F("cpufit","cpu time for fitting",100, 0., 200.);
00208   h["cpuclu"]    = new TH1F("cpuclu","cpu time for clustering",100, 0., 200.);
00209   h["nbtksinvtx2"]   = new TH1F("nbtksinvtx2","reconstructed tracks in vertex",40,0.,200.); 
00210   h["nbtksinvtxPU2"]   = new TH1F("nbtksinvtxPU2","reconstructed tracks in vertex",40,0.,200.); 
00211   h["nbtksinvtxTag2"]   = new TH1F("nbtksinvtxTag2","reconstructed tracks in vertex",40,0.,200.); 
00212 
00213   h["xrec"]         = new TH1F("xrec","reconstructed x",100,-0.1,0.1);
00214   h["yrec"]         = new TH1F("yrec","reconstructed y",100,-0.1,0.1);
00215   h["zrec"]         = new TH1F("zrec","reconstructed z",100,-20.,20.);
00216   h["err1"]         = new TH1F("err1","error 1",100,0.,0.1);
00217   h["err2"]         = new TH1F("err2","error 2",100,0.,0.1);
00218   h["errx"]         = new TH1F("errx","error x",100,0.,0.1);
00219   h["erry"]         = new TH1F("erry","error y",100,0.,0.1);
00220   h["errz"]         = new TH1F("errz","error z",100,0.,2.0);
00221   h["errz1"]        = new TH1F("errz1","error z",100,0.,0.2);
00222 
00223   h["zrecNt100"]         = new TH1F("zrecNt100","reconstructed z for high multiplicity events",80,-40.,40.);
00224   add(h, new TH2F("zrecvsnt","reconstructed z vs number of tracks",100,-50., 50., 20, 0., 200.));
00225   add(h, new TH2F("xyrec","reconstructed xy",100, -4., 4., 100, -4., 4.));
00226   h["xrecBeam"]     = new TH1F("xrecBeam","reconstructed x - beam x",100,-0.1,0.1);
00227   h["yrecBeam"]     = new TH1F("yrecBeam","reconstructed y - beam y",100,-0.1,0.1);
00228   h["zrecBeam"]     = new TH1F("zrecBeam","reconstructed z - beam z",100,-20.,20.);
00229   h["xrecBeamvsz"] = new TH2F("xrecBeamvsz","reconstructed x - beam x vs z", 20, -20., 20.,100,-0.1,0.1);
00230   h["yrecBeamvsz"] = new TH2F("yrecBeamvsz","reconstructed y - beam y vs z", 20, -20., 20.,100,-0.1,0.1);
00231   h["xrecBeamvszprof"] = new TProfile("xrecBeamvszprof","reconstructed x - beam x vs z-z0", 20, -20., 20.,-0.1,0.1);
00232   h["yrecBeamvszprof"] = new TProfile("yrecBeamvszprof","reconstructed y - beam y vs z-z0", 20, -20., 20.,-0.1,0.1);
00233   add(h, new TH2F("xrecBeamvsdxXBS","reconstructed x - beam x vs resolution",10,0., 0.02, 100, -0.1,0.1)); // just a test
00234   add(h, new TH2F("yrecBeamvsdyXBS","reconstructed z - beam z vs resolution",10,0., 0.02, 100, -0.1,0.1));
00235   add(h, new TH2F("xrecBeamvsdx","reconstructed x - beam x vs resolution",10,0., 0.02, 100, -0.1,0.1));
00236   add(h, new TH2F("yrecBeamvsdy","reconstructed z - beam z vs resolution",10,0., 0.02, 100, -0.1,0.1));
00237   add(h, new TH2F("xrecBeamvsdxR2","reconstructed x - beam x vs resolution",20,0., 0.04, 100, -0.1,0.1));
00238   add(h, new TH2F("yrecBeamvsdyR2","reconstructed z - beam z vs resolution",20,0., 0.04, 100, -0.1,0.1));
00239   //  add(h, new TH2F("xrecBeamvsdx","reconstructed x - beam x vs resolution",100,-0.1,0.1, 10, 0., 0.04));
00240   //  add(h, new TH2F("yrecBeamvsdy","reconstructed y - beam y vs resolution",100,-0.1,0.1, 10, 0., 0.04));
00241   h["xrecBeamvsdxprof"] = new TProfile("xrecBeamvsdxprof","reconstructed x - beam x vs resolution",10, 0., 0.04,-0.1,0.1 );
00242   h["yrecBeamvsdyprof"] = new TProfile("yrecBeamvsdyprof","reconstructed y - beam y vs resolution",10, 0., 0.04,-0.1,0.1 );
00243   add(h, new TProfile("xrecBeam2vsdx2prof","reconstructed x - beam x vs resolution",10,0., 0.002, 0., 0.01));
00244   add(h, new TProfile("yrecBeam2vsdy2prof","reconstructed y - beam y vs resolution",10,0., 0.002, 0., 0.01));
00245   add(h,new TH2F("xrecBeamvsdx2","reconstructed x - beam x vs resolution",10,0., 0.002, 100, -0.01, 0.01));
00246   add(h,new TH2F("yrecBeamvsdy2","reconstructed y - beam y vs resolution",10,0., 0.002, 100, -0.01, 0.01));
00247   h["xrecb"]        = new TH1F("xrecb","reconstructed x - beam x",100,-0.01,0.01);
00248   h["yrecb"]        = new TH1F("yrecb","reconstructed y - beam y",100,-0.01,0.01);
00249   h["zrecb"]        = new TH1F("zrecb","reconstructed z - beam z",100,-20.,20.);
00250   h["xrec1"]        = new TH1F("xrec1","reconstructed x",100,-4,4);
00251   h["yrec1"]        = new TH1F("yrec1","reconstructed y",100,-4,4);  // should match the sim histos
00252   h["zrec1"]        = new TH1F("zrec1","reconstructed z",100,-80.,80.);
00253   h["xrec2"]        = new TH1F("xrec2","reconstructed x",100,-1,1);
00254   h["yrec2"]        = new TH1F("yrec2","reconstructed y",100,-1,1);
00255   h["zrec2"]        = new TH1F("zrec2","reconstructed z",100,-40.,40.);
00256   h["xrec3"]        = new TH1F("xrec3","reconstructed x",100,-0.1,0.1);
00257   h["yrec3"]        = new TH1F("yrec3","reconstructed y",100,-0.1,0.1);
00258   h["zrec3"]        = new TH1F("zrec3","reconstructed z",100,-20.,20.);
00259   add(h, new TH1F("xrecBeamPull","normalized residuals reconstructed x - beam x",100,-20,20));
00260   add(h, new TH1F("yrecBeamPull","normalized residuals reconstructed y - beam y",100,-20,20));
00261   add(h, new TH1F("zdiffrec","z-distance between vertices",200,-20., 20.));
00262   add(h, new TH1F("zdiffrec2","z-distance between ndof>2 vertices",200,-20., 20.));
00263   add(h, new TH1F("zdiffrec4","z-distance between ndof>4 vertices",200,-20., 20.));
00264   add(h, new TH1F("zdiffrec8","z-distance between ndof>8 vertices",200,-20., 20.));
00265   add(h, new TH2F("zvszrec2","z positions of multiple vertices",200,-20., 20., 200,-20., 20.));
00266   add(h, new TH2F("pzvspz2","prob(z) of multiple vertices",100, 0.,1.,100,0., 1.));
00267   add(h, new TH2F("zvszrec4","z positions of multiple vertices",100,-20., 20., 100,-20., 20.));
00268   add(h, new TH2F("pzvspz4","prob(z) of multiple vertices",100, 0.,1.,100,0., 1.));
00269   add(h, new TH2F("zdiffvsz","z-distance vs z",100,-10.,10.,30,-15.,15.));
00270   add(h, new TH2F("zdiffvsz4","z-distance vs z (ndof>4)",100,-10.,10.,30,-15.,15.));
00271   add(h, new TProfile("eff0vsntrec","efficiency vs # reconstructed tracks",50, 0., 50., 0, 1.));
00272   add(h, new TProfile("eff0vsntsel","efficiency vs # selected tracks",50, 0., 50., 0, 1.));
00273   add(h, new TProfile("eff0ndof0vsntsel","efficiency (ndof>0) vs # selected tracks",50, 0., 50., 0, 1.));
00274   add(h, new TProfile("eff0ndof8vsntsel","efficiency (ndof>8) vs # selected tracks",50, 0., 50., 0, 1.));
00275   add(h, new TProfile("eff0ndof2vsntsel","efficiency (ndof>2) vs # selected tracks",50, 0., 50., 0, 1.));
00276   add(h, new TProfile("eff0ndof4vsntsel","efficiency (ndof>4) vs # selected tracks",50, 0., 50., 0, 1.));
00277   add(h, new TH1F("xbeamPUcand","x - beam of PU candidates (ndof>4)",100,-1., 1.));
00278   add(h, new TH1F("ybeamPUcand","y - beam of PU candidates (ndof>4)",100,-1., 1.));
00279   add(h, new TH1F("xbeamPullPUcand","x - beam pull of PU candidates (ndof>4)",100,-20., 20.));
00280   add(h, new TH1F("ybeamPullPUcand","y - beam pull of PU candidates (ndof>4)",100,-20., 20.));
00281   add(h, new TH1F("ndofOverNtk","ndof / ntk of ndidates (ndof>4)",100,0., 2.));
00282   //add(h, new TH1F("sumwOverNtk","sumw / ntk of ndidates (ndof>4)",100,0., 2.));
00283   add(h, new TH1F("ndofOverNtkPUcand","ndof / ntk of ndidates (ndof>4)",100,0., 2.));
00284   //add(h, new TH1F("sumwOverNtkPUcand","sumw / ntk of ndidates (ndof>4)",100,0., 2.));
00285   add(h, new TH1F("zPUcand","z positions of PU candidates (all)",100,-20., 20.));
00286   add(h, new TH1F("zPUcand2","z positions of PU candidates (ndof>2)",100,-20., 20.));
00287   add(h, new TH1F("zPUcand4","z positions of PU candidates (ndof>4)",100,-20., 20.));
00288   add(h, new TH1F("ndofPUcand","ndof of PU candidates (all)",50,0., 100.));
00289   add(h, new TH1F("ndofPUcand2","ndof of PU candidates (ndof>2)",50,0., 100.));
00290   add(h, new TH1F("ndofPUcand4","ndof of PU candidates (ndof>4)",50,0., 100.));
00291   add(h, new TH1F("ndofnr2","second highest ndof",500,0., 100.));
00292   add(h, new TH1F("ndofnr2d1cm","second highest ndof (dz>1cm)",500,0., 100.));
00293   add(h, new TH1F("ndofnr2d2cm","second highest ndof (dz>2cm)",500,0., 100.));
00294 
00295   h["nrecvtx"]      = new TH1F("nrecvtx","# of reconstructed vertices", 50, -0.5, 49.5);
00296   h["nrecvtx8"]      = new TH1F("nrecvtx8","# of reconstructed vertices with ndof>8", 50, -0.5, 49.5);
00297   h["nrecvtx2"]      = new TH1F("nrecvtx2","# of reconstructed vertices with ndof>2", 50, -0.5, 49.5);
00298   h["nrecvtx4"]      = new TH1F("nrecvtx4","# of reconstructed vertices with ndof>4", 50, -0.5, 49.5);
00299   //  h["nsimvtx"]      = new TH1F("nsimvtx","# of simulated vertices", 50, -0.5, 49.5);
00300   h["nrectrk"]      = new TH1F("nrectrk","# of reconstructed tracks", 100, -0.5, 99.5);
00301   add(h, new TH1F("nsimtrk","# of simulated tracks", 100, -0.5, 99.5));
00302   add(h, new TH1F("nsimtrkSignal","# of simulated tracks (Signal)", 100, -0.5, 99.5));
00303   add(h, new TH1F("nsimtrkPU","# of simulated tracks (PU)", 100, -0.5, 99.5));
00304   h["nsimtrk"]->StatOverflows(kTRUE);
00305   h["nsimtrkPU"]->StatOverflows(kTRUE);
00306   h["nsimtrkSignal"]->StatOverflows(kTRUE);
00307   h["xrectag"]      = new TH1F("xrectag","reconstructed x, signal vtx",100,-0.05,0.05);
00308   h["yrectag"]      = new TH1F("yrectag","reconstructed y, signal vtx",100,-0.05,0.05);
00309   h["zrectag"]      = new TH1F("zrectag","reconstructed z, signal vtx",100,-20.,20.);
00310   h["nrectrk0vtx"] = new TH1F("nrectrk0vtx","# rec tracks no vertex ",100,-0.5, 99.5);
00311   h["nseltrk0vtx"] = new TH1F("nseltrk0vtx","# rec tracks no vertex ",100,-0.5, 99.5);
00312   h["nrecsimtrk"] = new TH1F("nrecsimtrk","# rec tracks matched to sim tracks in vertex",100,-0.5, 99.5);
00313   h["nrecnosimtrk"] = new TH1F("nrecsimtrk","# rec tracks not matched to sim tracks in vertex",100,-0.5, 99.5);
00314   h["trackAssEffvsPt"] =  new TProfile("trackAssEffvsPt","track association efficiency vs pt",20, 0., 100., 0, 1.);
00315 
00316   // cluster stuff
00317   h["nseltrk"]         = new TH1F("nseltrk","# of reconstructed tracks selected for PV", 100, -0.5, 99.5);
00318   h["nclutrkall"]      = new TH1F("nclutrkall","# of reconstructed tracks in clusters", 100, -0.5, 99.5);
00319   h["nclutrkvtx"]      = new TH1F("nclutrkvtx","# of reconstructed tracks in clusters of reconstructed vertices", 100, -0.5, 99.5);
00320   h["nclu"]            = new TH1F("nclu","# of clusters", 100, -0.5, 99.5);
00321   h["nclu0vtx"]        = new TH1F("nclu0vtx","# of clusters in events with no PV", 100, -0.5, 99.5);
00322   h["zlost1"]           = new TH1F("zlost1","z of lost vertices (bad z)", 100, -20., 20.);
00323   h["zlost2"]           = new TH1F("zlost2","z of lost vertices (no matching cluster)", 100, -20., 20.);
00324   h["zlost3"]           = new TH1F("zlost3","z of lost vertices (vertex too far from beam)", 100, -20., 20.);
00325   h["zlost4"]           = new TH1F("zlost4","z of lost vertices (invalid vertex)", 100, -20., 20.);
00326   h["selstat"]     = new TH1F("selstat","selstat", 5, -2.5, 2.5);
00327   
00328 
00329   // properties of fake vertices  (MC only)_
00330   add(h, new TH1F("fakeVtxZNdofgt05","z of fake vertices with ndof>0.5", 100, -20., 20.));
00331   add(h, new TH1F("fakeVtxZNdofgt2","z of fake vertices with ndof>2", 100, -20., 20.));
00332   add(h, new TH1F("fakeVtxZ","z of fake vertices", 100, -20., 20.));
00333   add(h, new TH1F("fakeVtxNdof","ndof of fake vertices", 500,0., 100.));
00334   add(h,new TH1F("fakeVtxNtrk","number of tracks in fake vertex",20,-0.5, 19.5));
00335   add(h,new TH1F("matchedVtxNdof","ndof of matched vertices", 500,0., 100.));
00336 
00337 
00338   //  histograms of track quality (Data and MC)
00339   string types[] = {"all","sel","bachelor","sellost","wgt05","wlt05","M","tagged","untagged","ndof4","PUcand","PUfake"};
00340   for(int t=0; t<12; t++){
00341     add(h, new TH1F(("rapidity_"+types[t]).c_str(),"rapidity ",100,-3., 3.));
00342     h["z0_"+types[t]] = new TH1F(("z0_"+types[t]).c_str(),"z0 ",80,-40., 40.);
00343     h["phi_"+types[t]] = new TH1F(("phi_"+types[t]).c_str(),"phi ",80,-3.14159, 3.14159);
00344     h["eta_"+types[t]] = new TH1F(("eta_"+types[t]).c_str(),"eta ",80,-4., 4.);
00345     h["pt_"+types[t]] = new TH1F(("pt_"+types[t]).c_str(),"pt ",100,0., 20.);
00346     h["found_"+types[t]]     = new TH1F(("found_"+types[t]).c_str(),"found hits",20, 0., 20.);
00347     h["lost_"+types[t]]      = new TH1F(("lost_"+types[t]).c_str(),"lost hits",20, 0., 20.);
00348     h["nchi2_"+types[t]]     = new TH1F(("nchi2_"+types[t]).c_str(),"normalized track chi2",100, 0., 20.);
00349     h["rstart_"+types[t]]    = new TH1F(("rstart_"+types[t]).c_str(),"start radius",100, 0., 20.);
00350     h["tfom_"+types[t]]      = new TH1F(("tfom_"+types[t]).c_str(),"track figure of merit",100, 0., 100.);
00351     h["expectedInner_"+types[t]]      = new TH1F(("expectedInner_"+types[t]).c_str(),"expected inner hits ",10, 0., 10.);
00352     h["expectedOuter_"+types[t]]      = new TH1F(("expectedOuter_"+types[t]).c_str(),"expected outer hits ",10, 0., 10.);
00353     h["logtresxy_"+types[t]] = new TH1F(("logtresxy_"+types[t]).c_str(),"log10(track r-phi resolution/um)",100, 0., 5.);
00354     h["logtresz_"+types[t]] = new TH1F(("logtresz_"+types[t]).c_str(),"log10(track z resolution/um)",100, 0., 5.);
00355     h["tpullxy_"+types[t]]   = new TH1F(("tpullxy_"+types[t]).c_str(),"track r-phi pull",100, -10., 10.);
00356     add(h, new TH2F( ("lvseta_"+types[t]).c_str(),"cluster length vs eta",60,-3., 3., 20, 0., 20));
00357     add(h, new TH2F( ("lvstanlambda_"+types[t]).c_str(),"cluster length vs tan lambda",60,-6., 6., 20, 0., 20));
00358     add(h, new TH1F( ("restrkz_"+types[t]).c_str(),"z-residuals (track vs vertex)", 200, -5., 5.));
00359     add(h, new TH2F( ("restrkzvsphi_"+types[t]).c_str(),"z-residuals (track - vertex)", 12,-3.14159,3.14159,100, -5., 5.));
00360     add(h, new TH2F( ("restrkzvseta_"+types[t]).c_str(),"z-residuals (track - vertex)", 12,-3.,3.,200, -5., 5.));
00361     add(h, new TH2F( ("pulltrkzvsphi_"+types[t]).c_str(),"normalized z-residuals (track - vertex)", 12,-3.14159,3.14159,100, -5., 5.));
00362     add(h, new TH2F( ("pulltrkzvseta_"+types[t]).c_str(),"normalized z-residuals (track - vertex)", 12,-3.,3.,100, -5., 5.));
00363     add(h, new TH1F( ("pulltrkz_"+types[t]).c_str(),"normalized z-residuals (track vs vertex)", 100, -5., 5.));
00364     add(h, new TH1F( ("sigmatrkz0_"+types[t]).c_str(),"z-resolution (excluding beam)", 100, 0., 5.));
00365     add(h, new TH1F( ("sigmatrkz_"+types[t]).c_str(),"z-resolution (including beam)", 100,0., 5.));
00366     add(h, new TH1F( ("nbarrelhits_"+types[t]).c_str(),"number of pixel barrel hits", 10, 0., 10.));
00367     add(h, new TH1F( ("nbarrelLayers_"+types[t]).c_str(),"number of pixel barrel layers", 10, 0., 10.));
00368     add(h, new TH1F( ("nPxLayers_"+types[t]).c_str(),"number of pixel layers (barrel+endcap)", 10, 0., 10.));
00369     add(h, new TH1F( ("nSiLayers_"+types[t]).c_str(),"number of Tracker layers ", 20, 0., 20.));
00370     add(h, new TH1F( ("trackAlgo_"+types[t]).c_str(),"track algorithm ", 30, 0., 30.));
00371     add(h, new TH1F( ("trackQuality_"+types[t]).c_str(),"track quality ", 7, -1., 6.));
00372   }
00373   add(h, new TH1F("trackWt","track weight in vertex",100,0., 1.));
00374    
00375 
00376   h["nrectrk"]->StatOverflows(kTRUE);
00377   h["nrectrk"]->StatOverflows(kTRUE);
00378   h["nrectrk0vtx"]->StatOverflows(kTRUE);
00379   h["nseltrk0vtx"]->StatOverflows(kTRUE);
00380   h["nrecsimtrk"]->StatOverflows(kTRUE);
00381   h["nrecnosimtrk"]->StatOverflows(kTRUE);
00382   h["nseltrk"]->StatOverflows(kTRUE);
00383   h["nbtksinvtx"]->StatOverflows(kTRUE);
00384   h["nbtksinvtxPU"]->StatOverflows(kTRUE);
00385   h["nbtksinvtxTag"]->StatOverflows(kTRUE);
00386   h["nbtksinvtx2"]->StatOverflows(kTRUE);
00387   h["nbtksinvtxPU2"]->StatOverflows(kTRUE);
00388   h["nbtksinvtxTag2"]->StatOverflows(kTRUE);
00389 
00390   // pile-up and track assignment related histograms (MC)
00391   h["npu0"]       =new TH1F("npu0","Number of simulated vertices",40,0.,40.);
00392   h["npu1"]       =new TH1F("npu1","Number of simulated vertices with >0 track",40,0.,40.);
00393   h["npu2"]       =new TH1F("npu2","Number of simulated vertices with >1 track",40,0.,40.);
00394   h["nrecv"]      =new TH1F("nrecv","# of reconstructed vertices", 40, 0, 40);
00395   add(h,new TH2F("nrecvsnpu","#rec vertices vs number of sim vertices with >0 tracks", 40,  0., 40, 40,  0, 40));
00396   add(h,new TH2F("nrecvsnpu2","#rec vertices vs number of sim vertices with >1 tracks", 40,  0., 40, 40,  0, 40));
00397   add(h,new TH1F("sumpt","sumpt of simulated tracks",100,0.,100.));
00398   add(h,new TH1F("sumptSignal","sumpt of simulated tracks in Signal events",100,0.,200.));
00399   add(h,new TH1F("sumptPU","sumpt of simulated tracks in PU events",100,0.,200.));
00400   add(h,new TH1F("sumpt2rec","sumpt2 of reconstructed and matched tracks",100,0.,100.));
00401   add(h,new TH1F("sumpt2","sumpt2 of simulated tracks",100,0.,100.));
00402   add(h,new TH1F("sumpt2Signal","sumpt2 of simulated tracks in Signal events",100,0.,200.));
00403   add(h,new TH1F("sumpt2PU","sumpt2 of simulated tracks in PU events",100,0.,200.));
00404   add(h,new TH1F("sumpt2rec","sumpt2 of reconstructed and matched tracks",100,0.,100.));
00405   add(h,new TH1F("sumpt2recSignal","sumpt2 of reconstructed and matched tracks in Signal events",100,0.,200.));
00406   add(h,new TH1F("sumpt2recPU","sumpt2 of reconstructed and matched tracks in PU events",100,0.,200.));
00407   add(h,new TH1F("nRecTrkInSimVtx","number of reco tracks matched to sim-vertex", 101, 0., 100));
00408   add(h,new TH1F("nRecTrkInSimVtxSignal","number of reco tracks matched to signal sim-vertex", 101, 0., 100));
00409   add(h,new TH1F("nRecTrkInSimVtxPU","number of reco tracks matched to PU-vertex", 101, 0., 100));
00410   add(h,new TH1F("nPrimRecTrkInSimVtx","number of reco primary tracks matched to sim-vertex", 101, 0., 100));
00411   add(h,new TH1F("nPrimRecTrkInSimVtxSignal","number of reco primary tracks matched to signal sim-vertex", 101, 0., 100));
00412   add(h,new TH1F("nPrimRecTrkInSimVtxPU","number of reco primary tracks matched to PU-vertex", 101, 0., 100));
00413   // obsolete, scheduled for removal
00414   add(h,new TH1F("recPurity","track purity of reconstructed vertices", 101, 0., 1.01));
00415   add(h,new TH1F("recPuritySignal","track purity of reconstructed Signal vertices", 101, 0., 1.01));
00416   add(h,new TH1F("recPurityPU","track purity of reconstructed PU vertices", 101, 0., 1.01));
00417   // end of obsolete
00418   add(h,new TH1F("recmatchPurity","track purity of all vertices", 101, 0., 1.01));
00419   add(h,new TH1F("recmatchPurityTag","track purity of tagged vertices", 101, 0., 1.01));
00420   add(h,new TH1F("recmatchPurityTagSignal","track purity of tagged Signal vertices", 101, 0., 1.01));
00421   add(h,new TH1F("recmatchPurityTagPU","track purity of tagged PU vertices", 101, 0., 1.01));
00422   add(h,new TH1F("recmatchPuritynoTag","track purity of untagged vertices", 101, 0., 1.01));
00423   add(h,new TH1F("recmatchPuritynoTagSignal","track purity of untagged Signal vertices", 101, 0., 1.01));
00424   add(h,new TH1F("recmatchPuritynoTagPU","track purity of untagged PU vertices", 101, 0., 1.01));
00425   add(h,new TH1F("recmatchvtxs","number of sim vertices contributing to recvtx", 10, 0., 10.));
00426   add(h,new TH1F("recmatchvtxsTag","number of sim vertices contributing to recvtx", 10, 0., 10.));
00427   add(h,new TH1F("recmatchvtxsnoTag","number of sim vertices contributing to recvtx", 10, 0., 10.));
00428   //
00429   add(h,new TH1F("trkAssignmentEfficiency", "track to vertex assignment efficiency", 101, 0., 1.01) );
00430   add(h,new TH1F("trkAssignmentEfficiencySignal", "track to signal vertex assignment efficiency", 101, 0., 1.01) );
00431   add(h,new TH1F("trkAssignmentEfficiencyPU", "track to PU vertex assignment efficiency", 101, 0., 1.01) );
00432   add(h,new TH1F("primtrkAssignmentEfficiency", "track to vertex assignment efficiency", 101, 0., 1.01) );
00433   add(h,new TH1F("primtrkAssignmentEfficiencySignal", "track to signal vertex assignment efficiency", 101, 0., 1.01) );
00434   add(h,new TH1F("primtrkAssignmentEfficiencyPU", "track to PU vertex assignment efficiency", 101, 0., 1.01) );
00435   add(h,new TH1F("vtxMultiplicity", "number of rec vertices containg tracks from one true vertex", 10, 0., 10.) );
00436   add(h,new TH1F("vtxMultiplicitySignal", "number of rec vertices containg tracks from the Signal Vertex", 10, 0., 10.) );
00437   add(h,new TH1F("vtxMultiplicityPU", "number of rec vertices containg tracks from a PU Vertex", 10, 0., 10.) );
00438   
00439   add(h,new TProfile("vtxFindingEfficiencyVsNtrk","finding efficiency vs number of associated rec tracks",100, 0., 100., 0., 1.) );
00440   add(h,new TProfile("vtxFindingEfficiencyVsNtrkSignal","Signal vertex finding efficiency vs number of associated rec tracks",100, 0., 100., 0., 1.) );
00441   add(h,new TProfile("vtxFindingEfficiencyVsNtrkPU","PU vertex finding efficiency vs number of associated rec tracks",100, 0., 100., 0., 1.) );
00442 
00443   add(h,new TH1F("TagVtxTrkPurity","TagVtxTrkPurity",100,0.,1.01));
00444   add(h,new TH1F("TagVtxTrkEfficiency","TagVtxTrkEfficiency",100,0.,1.01));
00445   
00446   add(h,new TH1F("matchVtxFraction","fraction of sim vertex tracks found in a recvertex",101,0,1.01));
00447   add(h,new TH1F("matchVtxFractionSignal","fraction of sim vertex tracks found in a recvertex",101,0,1.01));
00448   add(h,new TH1F("matchVtxFractionPU","fraction of sim vertex tracks found in a recvertex",101,0,1.01));
00449   add(h,new TH1F("matchVtxFractionCum","fraction of sim vertex tracks found in a recvertex",101,0,1.01));
00450   add(h,new TH1F("matchVtxFractionCumSignal","fraction of sim vertexs track found in a recvertex",101,0,1.01));
00451   add(h,new TH1F("matchVtxFractionCumPU","fraction of sim vertex tracks found in a recvertex",101,0,1.01));
00452   add(h,new TH1F("matchVtxEfficiency","efficiency for finding matching rec vertex",2,-0.5,1.5));
00453   add(h,new TH1F("matchVtxEfficiencySignal","efficiency for finding matching rec vertex",2,-0.5,1.5));
00454   add(h,new TH1F("matchVtxEfficiencyPU","efficiency for finding matching rec vertex",2,-0.5,1.5));
00455   add(h,new TH1F("matchVtxEfficiency2","efficiency for finding matching rec vertex (nt>1)",2,-0.5,1.5));
00456   add(h,new TH1F("matchVtxEfficiency2Signal","efficiency for finding matching rec vertex (nt>1)",2,-0.5,1.5));
00457   add(h,new TH1F("matchVtxEfficiency2PU","efficiency for finding matching rec vertex (nt>1)",2,-0.5,1.5));
00458   add(h,new TH1F("matchVtxEfficiency5","efficiency for finding matching rec vertex (purity>0.5)",2,-0.5,1.5));
00459   add(h,new TH1F("matchVtxEfficiency5Signal","efficiency for finding matching rec vertex (purity>0.5)",2,-0.5,1.5));
00460   add(h,new TH1F("matchVtxEfficiency5PU","efficiency for finding matching rec vertex (purity>0.5)",2,-0.5,1.5));
00461 
00462 
00463   add(h,new TH1F("matchVtxEfficiencyZ","efficiency for finding matching rec vertex within 1 mm",2,-0.5,1.5));
00464   add(h,new TH1F("matchVtxEfficiencyZSignal","efficiency for finding matching rec vertex within 1 mm",2,-0.5,1.5));
00465   add(h,new TH1F("matchVtxEfficiencyZPU","efficiency for finding matching rec vertex within 1 mm",2,-0.5,1.5));
00466 
00467   add(h,new TH1F("matchVtxEfficiencyZ1","efficiency for finding matching rec vertex within 1 mm (nt>0)",2,-0.5,1.5));
00468   add(h,new TH1F("matchVtxEfficiencyZ1Signal","efficiency for finding matching rec vertex within 1 mm (nt>0)",2,-0.5,1.5));
00469   add(h,new TH1F("matchVtxEfficiencyZ1PU","efficiency for finding matching rec vertex within 1 mm (nt>0)",2,-0.5,1.5));
00470 
00471   add(h,new TH1F("matchVtxEfficiencyZ2","efficiency for finding matching rec vertex within 1 mm (nt>1)",2,-0.5,1.5));
00472   add(h,new TH1F("matchVtxEfficiencyZ2Signal","efficiency for finding matching rec vertex within 1 mm (nt>1)",2,-0.5,1.5));
00473   add(h,new TH1F("matchVtxEfficiencyZ2PU","efficiency for finding matching rec vertex within 1 mm (nt>1)",2,-0.5,1.5));
00474 
00475   add(h,new TH1F("matchVtxZ","z distance to matched recvtx",100, -0.1, 0.1));
00476   add(h,new TH1F("matchVtxZPU","z distance to matched recvtx",100, -0.1, 0.1));
00477   add(h,new TH1F("matchVtxZSignal","z distance to matched recvtx",100, -0.1, 0.1));
00478 
00479   add(h,new TH1F("matchVtxZCum","z distance to matched recvtx",1001,0, 1.01));
00480   add(h,new TH1F("matchVtxZCumSignal","z distance to matched recvtx",1001,0, 1.01));
00481   add(h,new TH1F("matchVtxZCumPU","z distance to matched recvtx",1001,0, 1.01));
00482 
00483   add(h, new TH1F("unmatchedVtx","number of unmatched rec vertices (fakes)",10,0.,10.));
00484   add(h, new TH1F("unmatchedVtxFrac","fraction of unmatched rec vertices (fakes)",1000,0.,1.0));
00485   add(h, new TH1F("unmatchedVtxZ","z of unmached rec  vertices (fakes)",100,-20., 20.));
00486   add(h, new TH1F("unmatchedVtxNdof","ndof of unmatched rec vertices (fakes)", 500,0., 100.));
00487   add(h,new TH2F("correctlyassigned","pt and eta of correctly assigned tracks", 60,  -3., 3., 100, 0, 10.));
00488   add(h,new TH2F("misassigned","pt and eta of mis assigned tracks", 60,  -3., 3., 100, 0, 10.));
00489 
00490   add(h,new TH1F("ptcat","pt of correctly assigned tracks", 100, 0, 10.));
00491   add(h,new TH1F("etacat","eta of correctly assigned tracks", 60, -3., 3.));
00492   add(h,new TH1F("phicat","phi of correctly assigned tracks", 100, -3.14159, 3.14159));
00493   add(h,new TH1F("dzcat","dz of correctly assigned tracks", 100, 0., 1.));
00494 
00495   add(h,new TH1F("ptmis","pt of mis-assigned tracks", 100, 0, 10.));
00496   add(h,new TH1F("etamis","eta of mis-assigned tracks", 60, -3., 3.));
00497   add(h,new TH1F("phimis","phi of mis-assigned tracks",100, -3.14159, 3.14159));
00498   add(h,new TH1F("dzmis","dz of mis-assigned tracks", 100, 0., 1.));
00499 
00500 
00501   add(h,new TH1F("Tc","Tc computed with Truth matched Reco Tracks",100,0.,20.));
00502   add(h,new TH1F("TcSignal","Tc of signal vertices computed with Truth matched Reco Tracks",100,0.,20.));
00503   add(h,new TH1F("TcPU","Tc of PU vertices computed with Truth matched Reco Tracks",100,0.,20.));
00504 
00505   add(h,new TH1F("logTc","log Tc computed with Truth matched Reco Tracks",100,-2.,8.));
00506   add(h,new TH1F("logTcSignal","log Tc of signal vertices computed with Truth matched Reco Tracks",100,-2.,8.));
00507   add(h,new TH1F("logTcPU","log Tc of PU vertices computed with Truth matched Reco Tracks",100,-2.,8.));
00508 
00509   add(h,new TH1F("xTc","Tc of merged clusters",100,0.,20.));
00510   add(h,new TH1F("xTcSignal","Tc of signal vertices merged with PU",100,0.,20.));
00511   add(h,new TH1F("xTcPU","Tc of merged PU vertices",100,0.,20.));
00512 
00513   add(h,new TH1F("logxTc","log Tc merged vertices",100,-2.,8.));
00514   add(h,new TH1F("logxTcSignal","log Tc of signal vertices merged with PU",100,-2.,8.));
00515   add(h,new TH1F("logxTcPU","log Tc of merged PU vertices ",100,-2.,8.));
00516 
00517   add(h,new TH1F("logChisq","Chisq/ntrk computed with Truth matched Reco Tracks",100,-2.,8.));
00518   add(h,new TH1F("logChisqSignal","Chisq/ntrk of signal vertices computed with Truth matched Reco Tracks",100,-2.,8.));
00519   add(h,new TH1F("logChisqPU","Chisq/ntrk of PU vertices computed with Truth matched Reco Tracks",100,-2.,8.));
00520 
00521   add(h,new TH1F("logxChisq","Chisq/ntrk of merged clusters",100,-2.,8.));
00522   add(h,new TH1F("logxChisqSignal","Chisq/ntrk of signal vertices merged with PU",100,-2.,8.));
00523   add(h,new TH1F("logxChisqPU","Chisq/ntrk of merged PU vertices",100,-2.,8.));
00524 
00525   add(h,new TH1F("Chisq","Chisq/ntrk computed with Truth matched Reco Tracks",100,0.,20.));
00526   add(h,new TH1F("ChisqSignal","Chisq/ntrk of signal vertices computed with Truth matched Reco Tracks",100,0.,20.));
00527   add(h,new TH1F("ChisqPU","Chisq/ntrk of PU vertices computed with Truth matched Reco Tracks",100,0.,20.));
00528 
00529   add(h,new TH1F("xChisq","Chisq/ntrk of merged clusters",100,0.,20.));
00530   add(h,new TH1F("xChisqSignal","Chisq/ntrk of signal vertices merged with PU",100,0.,20.));
00531   add(h,new TH1F("xChisqPU","Chisq/ntrk of merged PU vertices",100,0.,20.));
00532 
00533   add(h,new TH1F("dzmax","dzmax computed with Truth matched Reco Tracks",100,0.,2.));
00534   add(h,new TH1F("dzmaxSignal","dzmax of signal vertices computed with Truth matched Reco Tracks",100,0.,2.));
00535   add(h,new TH1F("dzmaxPU","dzmax of PU vertices computed with Truth matched Reco Tracks",100,0.,2.));
00536 
00537   add(h,new TH1F("xdzmax","dzmax of merged clusters",100,0.,2.));
00538   add(h,new TH1F("xdzmaxSignal","dzmax of signal vertices merged with PU",100,0.,2.));
00539   add(h,new TH1F("xdzmaxPU","dzmax of merged PU vertices",100,0.,2.));
00540 
00541   add(h,new TH1F("dztrim","dzmax computed with Truth matched Reco Tracks",100,0.,2.));
00542   add(h,new TH1F("dztrimSignal","dzmax of signal vertices computed with Truth matched Reco Tracks",100,0.,2.));
00543   add(h,new TH1F("dztrimPU","dzmax of PU vertices computed with Truth matched Reco Tracks",100,0.,2.));
00544 
00545   add(h,new TH1F("xdztrim","dzmax of merged clusters",100,0.,2.));
00546   add(h,new TH1F("xdztrimSignal","dzmax of signal vertices merged with PU",100,0.,2.));
00547   add(h,new TH1F("xdztrimPU","dzmax of merged PU vertices",100,0.,2.));
00548 
00549   add(h,new TH1F("m4m2","m4m2 computed with Truth matched Reco Tracks",100,0.,100.));
00550   add(h,new TH1F("m4m2Signal","m4m2 of signal vertices computed with Truth matched Reco Tracks",100,0.,100.));
00551   add(h,new TH1F("m4m2PU","m4m2 of PU vertices computed with Truth matched Reco Tracks",100,0.,100.));
00552 
00553   add(h,new TH1F("xm4m2","m4m2 of merged clusters",100,0.,100.));
00554   add(h,new TH1F("xm4m2Signal","m4m2 of signal vertices merged with PU",100,0.,100.));
00555   add(h,new TH1F("xm4m2PU","m4m2 of merged PU vertices",100,0.,100.));
00556 
00557   return h;
00558 }
00559 
00560 
00561 //
00562 // member functions
00563 //
00564 void PrimaryVertexAnalyzer4PU::beginJob(){
00565   std::cout << " PrimaryVertexAnalyzer4PU::beginJob  conversion from sim units to rec units is " << simUnit_ << std::endl;
00566 
00567 
00568   rootFile_->cd();
00569 
00570   TDirectory *noBS = rootFile_->mkdir("noBS");
00571   noBS->cd();
00572   hnoBS=bookVertexHistograms();
00573   for(std::map<std::string,TH1*>::const_iterator hist=hnoBS.begin(); hist!=hnoBS.end(); hist++){
00574     hist->second->SetDirectory(noBS);
00575   }
00576 
00577   TDirectory *withBS = rootFile_->mkdir("BS");
00578   withBS->cd();
00579   hBS=bookVertexHistograms();
00580   for(std::map<std::string,TH1*>::const_iterator hist=hBS.begin(); hist!=hBS.end(); hist++){
00581     hist->second->SetDirectory(withBS);
00582   }
00583 
00584   TDirectory *DA = rootFile_->mkdir("DA");
00585   DA->cd();
00586   hDA=bookVertexHistograms();
00587   for(std::map<std::string,TH1*>::const_iterator hist=hDA.begin(); hist!=hDA.end(); hist++){
00588     hist->second->SetDirectory(DA);
00589   }
00590 
00591 //   TDirectory *PIX = rootFile_->mkdir("PIX");
00592 //   PIX->cd();
00593 //   hPIX=bookVertexHistograms();
00594 //   for(std::map<std::string,TH1*>::const_iterator hist=hPIX.begin(); hist!=hPIX.end(); hist++){
00595 //     hist->second->SetDirectory(PIX);
00596 //   }
00597 
00598 //   TDirectory *MVF = rootFile_->mkdir("MVF");
00599 //   MVF->cd();
00600 //   hMVF=bookVertexHistograms();
00601 //   for(std::map<std::string,TH1*>::const_iterator hist=hMVF.begin(); hist!=hMVF.end(); hist++){
00602 //     hist->second->SetDirectory(MVF);
00603 //   }
00604 
00605   rootFile_->cd();
00606   hsimPV["rapidity"] = new TH1F("rapidity","rapidity ",100,-10., 10.);
00607   hsimPV["chRapidity"] = new TH1F("chRapidity","charged rapidity ",100,-10., 10.);
00608   hsimPV["recRapidity"] = new TH1F("recRapidity","reconstructed rapidity ",100,-10., 10.);
00609   hsimPV["pt"] = new TH1F("pt","pt ",100,0., 20.);
00610 
00611   hsimPV["xsim"]         = new TH1F("xsim","simulated x",100,-0.01,0.01); // 0.01cm = 100 um
00612   hsimPV["ysim"]         = new TH1F("ysim","simulated y",100,-0.01,0.01);
00613   hsimPV["zsim"]         = new TH1F("zsim","simulated z",100,-20.,20.);
00614 
00615   hsimPV["xsim1"]        = new TH1F("xsim1","simulated x",100,-4.,4.);
00616   hsimPV["ysim1"]        = new TH1F("ysim1","simulated y",100,-4.,4.);
00617   hsimPV["zsim1"]        = new TH1F("zsim1","simulated z",100,-40.,40.);
00618 
00619   add(hsimPV, new TH1F("xsim2PU","simulated x (Pile-up)",100,-1.,1.));
00620   add(hsimPV, new TH1F("ysim2PU","simulated y (Pile-up)",100,-1.,1.)); 
00621   add(hsimPV, new TH1F("zsim2PU","simulated z (Pile-up)",100,-20.,20.)); 
00622   add(hsimPV, new TH1F("xsim2Signal","simulated x (Signal)",100,-1.,1.));
00623   add(hsimPV, new TH1F("ysim2Signal","simulated y (Signal)",100,-1.,1.));
00624   add(hsimPV, new TH1F("zsim2Signal","simulated z (Signal)",100,-20.,20.));
00625 
00626   hsimPV["xsim2"]        = new TH1F("xsim2","simulated x",100,-1,1); // 0.01cm = 100 um
00627   hsimPV["ysim2"]        = new TH1F("ysim2","simulated y",100,-1,1);
00628   hsimPV["zsim2"]        = new TH1F("zsim2","simulated z",100,-20.,20.);
00629   hsimPV["xsim3"]        = new TH1F("xsim3","simulated x",100,-0.1,0.1); // 0.01cm = 100 um
00630   hsimPV["ysim3"]        = new TH1F("ysim3","simulated y",100,-0.1,0.1);
00631   hsimPV["zsim3"]        = new TH1F("zsim3","simulated z",100,-20.,20.);
00632   hsimPV["xsimb"]        = new TH1F("xsimb","simulated x",100,-0.01,0.01); // 0.01cm = 100 um
00633   hsimPV["ysimb"]        = new TH1F("ysimb","simulated y",100,-0.01,0.01);
00634   hsimPV["zsimb"]        = new TH1F("zsimb","simulated z",100,-20.,20.);
00635   hsimPV["xsimb1"]        = new TH1F("xsimb1","simulated x",100,-0.1,0.1); // 0.01cm = 100 um
00636   hsimPV["ysimb1"]        = new TH1F("ysimb1","simulated y",100,-0.1,0.1);
00637   hsimPV["zsimb1"]        = new TH1F("zsimb1","simulated z",100,-20.,20.);
00638   add(hsimPV, new TH1F("xbeam","beamspot x",100,-1.,1.));
00639   add(hsimPV, new TH1F("ybeam","beamspot y",100,-1.,1.));
00640   add(hsimPV, new TH1F("zbeam","beamspot z",100,-1.,1.));
00641   add(hsimPV, new TH1F("wxbeam","beamspot sigma x",100,-1.,1.));
00642   add(hsimPV, new TH1F("wybeam","beamspot sigma y",100,-1.,1.));
00643   add(hsimPV, new TH1F("wzbeam","beamspot sigma z",100,-1.,1.));
00644   hsimPV["xsim2"]->StatOverflows(kTRUE);
00645   hsimPV["ysim2"]->StatOverflows(kTRUE);
00646   hsimPV["zsim2"]->StatOverflows(kTRUE);
00647   hsimPV["xsimb"]->StatOverflows(kTRUE);
00648   hsimPV["ysimb"]->StatOverflows(kTRUE);
00649   hsimPV["zsimb"]->StatOverflows(kTRUE);
00650   hsimPV["nsimvtx"]      = new TH1F("nsimvtx","# of simulated vertices", 50, -0.5, 49.5);
00651   //  hsimPV["nsimtrk"]      = new TH1F("nsimtrk","# of simulated tracks", 100, -0.5, 99.5); //  not filled right now, also exists in hBS..
00652   //  hsimPV["nsimtrk"]->StatOverflows(kTRUE);
00653   hsimPV["nbsimtksinvtx"]= new TH1F("nbsimtksinvtx","simulated tracks in vertex",100,-0.5,99.5); 
00654   hsimPV["nbsimtksinvtx"]->StatOverflows(kTRUE);
00655 
00656 }
00657 
00658 
00659 void PrimaryVertexAnalyzer4PU::endJob() {
00660   std::cout << "this is void PrimaryVertexAnalyzer4PU::endJob() " << std::endl;
00661   //cumulate some histos
00662   double sumDA=0,sumBS=0,sumnoBS=0;
00663   // double sumPIX=0,sumMVF=0;
00664   for(int i=101; i>0; i--){
00665     sumDA+=hDA["matchVtxFractionSignal"]->GetBinContent(i)/hDA["matchVtxFractionSignal"]->Integral();
00666     hDA["matchVtxFractionCumSignal"]->SetBinContent(i,sumDA);
00667     sumBS+=hBS["matchVtxFractionSignal"]->GetBinContent(i)/hBS["matchVtxFractionSignal"]->Integral();
00668     hBS["matchVtxFractionCumSignal"]->SetBinContent(i,sumBS);
00669     sumnoBS+=hnoBS["matchVtxFractionSignal"]->GetBinContent(i)/hnoBS["matchVtxFractionSignal"]->Integral();
00670     hnoBS["matchVtxFractionCumSignal"]->SetBinContent(i,sumnoBS);
00671 //     sumPIX+=hPIX["matchVtxFractionSignal"]->GetBinContent(i)/hPIX["matchVtxFractionSignal"]->Integral();
00672 //     hPIX["matchVtxFractionCumSignal"]->SetBinContent(i,sumPIX);
00673 //     sumMVF+=hMVF["matchVtxFractionSignal"]->GetBinContent(i)/hMVF["matchVtxFractionSignal"]->Integral();
00674 //     hMVF["matchVtxFractionCumSignal"]->SetBinContent(i,sumMVF);
00675   }
00676   sumDA=0,sumBS=0,sumnoBS=0;
00677   //sumPIX=0,sumMVF=0;
00678   for(int i=1; i<1001; i++){
00679     sumDA+=hDA["abszdistancetag"]->GetBinContent(i);
00680     hDA["abszdistancetagcum"]->SetBinContent(i,sumDA/float(hDA["abszdistancetag"]->GetEntries()));
00681     sumBS+=hBS["abszdistancetag"]->GetBinContent(i);
00682     hBS["abszdistancetagcum"]->SetBinContent(i,sumBS/float(hBS["abszdistancetag"]->GetEntries()));
00683     sumnoBS+=hnoBS["abszdistancetag"]->GetBinContent(i);
00684     hnoBS["abszdistancetagcum"]->SetBinContent(i,sumnoBS/float(hnoBS["abszdistancetag"]->GetEntries()));
00685 //     sumPIX+=hPIX["abszdistancetag"]->GetBinContent(i);
00686 //     hPIX["abszdistancetagcum"]->SetBinContent(i,sumPIX/float(hPIX["abszdistancetag"]->GetEntries()));
00687 //     sumMVF+=hMVF["abszdistancetag"]->GetBinContent(i);
00688 //     hMVF["abszdistancetagcum"]->SetBinContent(i,sumMVF/float(hMVF["abszdistancetag"]->GetEntries()));
00689   }
00690 
00691   Cumulate(hBS["matchVtxZCum"]);   Cumulate(hBS["matchVtxZCumSignal"]);   Cumulate(hBS["matchVtxZCumPU"]); 
00692   Cumulate(hnoBS["matchVtxZCum"]);   Cumulate(hnoBS["matchVtxZCumSignal"]);   Cumulate(hnoBS["matchVtxZCumPU"]); 
00693   Cumulate(hDA["matchVtxZCum"]);   Cumulate(hDA["matchVtxZCumSignal"]);   Cumulate(hDA["matchVtxZCumPU"]); 
00694   /*
00695    h->ComputeIntegral();
00696    Double_t *integral = h->GetIntegral();
00697    h->SetContent(integral);
00698   */
00699 
00700   // make a reference for ndofnr2
00701   //hDA["vtxndof"]->ComputeIntegral();
00702   //Double_t *integral = hDA["vtxndf"]->GetIntegral();
00703   //   h->SetContent(integral);
00704   double p;
00705   for(int i=1; i<501; i++){
00706     if(hDA["vtxndf"]->GetEntries()>0){
00707       p=  hDA["vtxndf"]->Integral(i,501)/hDA["vtxndf"]->GetEntries();    hDA["vtxndfc"]->SetBinContent(i,p*hDA["vtxndf"]->GetBinContent(i));
00708     }
00709     if(hBS["vtxndf"]->GetEntries()>0){
00710       p=  hBS["vtxndf"]->Integral(i,501)/hBS["vtxndf"]->GetEntries();    hBS["vtxndfc"]->SetBinContent(i,p*hBS["vtxndf"]->GetBinContent(i));
00711     }
00712     if(hnoBS["vtxndf"]->GetEntries()>0){
00713       p=hnoBS["vtxndf"]->Integral(i,501)/hnoBS["vtxndf"]->GetEntries();  hnoBS["vtxndfc"]->SetBinContent(i,p*hnoBS["vtxndf"]->GetBinContent(i));
00714     }
00715 //     if(hPIX["vtxndf"]->GetEntries()>0){
00716 //       p=hPIX["vtxndf"]->Integral(i,501)/hPIX["vtxndf"]->GetEntries();  hPIX["vtxndfc"]->SetBinContent(i,p*hPIX["vtxndf"]->GetBinContent(i));
00717 //     }
00718   }
00719   
00720   rootFile_->cd();
00721   for(std::map<std::string,TH1*>::const_iterator hist=hsimPV.begin(); hist!=hsimPV.end(); hist++){
00722     std::cout << "writing " << hist->first << std::endl;
00723     hist->second->Write();
00724   }
00725   rootFile_->Write();
00726   std::cout << "PrimaryVertexAnalyzer4PU::endJob: done" << std::endl;
00727 }
00728 
00729 
00730 
00731 
00732 // helper functions
00733 std::vector<PrimaryVertexAnalyzer4PU::SimPart> PrimaryVertexAnalyzer4PU::getSimTrkParameters(
00734                                                                                              edm::Handle<edm::SimTrackContainer> & simTrks,
00735                                                                                              edm::Handle<edm::SimVertexContainer> & simVtcs,
00736                                                                                              double simUnit)
00737 {
00738    std::vector<SimPart > tsim;
00739    if(simVtcs->begin()==simVtcs->end()){
00740      if(verbose_){
00741        cout << "  PrimaryVertexAnalyzer4PU::getSimTrkParameters  no simvtcs" << endl;
00742      }
00743      return tsim;
00744    }
00745    if(verbose_){
00746      cout << "  PrimaryVertexAnalyzer4PU::getSimTrkParameters simVtcs n=" << simVtcs->size() << endl;
00747      cout << "  PrimaryVertexAnalyzer4PU::getSimTrkParameters 1st position" << setw(8) << setprecision(4) << simVtcs->begin()->position() << endl;
00748    }
00749    double t0=simVtcs->begin()->position().e();
00750 
00751    for(edm::SimTrackContainer::const_iterator t=simTrks->begin();
00752        t!=simTrks->end(); ++t){
00753      if (t->noVertex()){
00754        std::cout << "simtrk  has no vertex" << std::endl;
00755      }else{
00756        // get the vertex position
00757        //HepLorentzVector v=(*simVtcs)[t->vertIndex()].position();
00758        math::XYZTLorentzVectorD v((*simVtcs)[t->vertIndex()].position().x(),
00759                           (*simVtcs)[t->vertIndex()].position().y(),
00760                           (*simVtcs)[t->vertIndex()].position().z(),
00761                           (*simVtcs)[t->vertIndex()].position().e());
00762        int pdgCode=t->type();
00763 
00764        if( pdgCode==-99 ){
00765          // such entries cause crashes, no idea what they are
00766          std::cout << "funny particle skipped  , code="  << pdgCode << std::endl;
00767        }else{
00768          double Q=0; //double Q=HepPDT::theTable().getParticleData(pdgCode)->charge();
00769          if ((pdgCode==11)||(pdgCode==13)||(pdgCode==15)||(pdgCode==-211)||(pdgCode==-2212)||(pdgCode==-321)||(pdgCode==-3222)){Q=-1;}
00770          else if((pdgCode==-11)||(pdgCode==-13)||(pdgCode==-15)||(pdgCode==211)||(pdgCode==2212)||(pdgCode==321)||(pdgCode==3222)){Q=1;}
00771          else {
00772            //std::cout << pdgCode << " " <<std::endl;
00773          }
00774          math::XYZTLorentzVectorD p(t->momentum().x(),t->momentum().y(),t->momentum().z(),t->momentum().e());
00775          if ( (Q != 0) && (p.pt()>0.1)  && (fabs(t->momentum().eta())<3.0)
00776               && fabs(v.z()*simUnit<20) && (sqrt(v.x()*v.x()+v.y()*v.y())<10.)){
00777            double x0=v.x()*simUnit;
00778            double y0=v.y()*simUnit;
00779            double z0=v.z()*simUnit;
00780            double kappa=-Q*0.002998*fBfield_/p.pt();
00781            double D0=x0*sin(p.phi())-y0*cos(p.phi())-0.5*kappa*(x0*x0+y0*y0);
00782            double q=sqrt(1.-2.*kappa*D0);
00783            double s0=(x0*cos(p.phi())+y0*sin(p.phi()))/q;
00784            double s1;
00785            if (fabs(kappa*s0)>0.001){
00786              s1=asin(kappa*s0)/kappa;
00787            }else{
00788              double ks02=(kappa*s0)*(kappa*s0);
00789              s1=s0*(1.+ks02/6.+3./40.*ks02*ks02+5./112.*pow(ks02,3));
00790            }
00791            SimPart sp;//ParameterVector par;
00792            sp.par[reco::TrackBase::i_qoverp] = Q/p.P();
00793            sp.par[reco::TrackBase::i_lambda] = M_PI/2.-p.theta();
00794            sp.par[reco::TrackBase::i_phi] = p.phi()-asin(kappa*s0);
00795            sp.par[reco::TrackBase::i_dxy] = -2.*D0/(1.+q);
00796            sp.par[reco::TrackBase::i_dsz] = z0*sin(p.theta())-s1*cos(p.theta());
00797 
00798            sp.pdg=pdgCode;
00799            if (v.t()-t0<1e-15){
00800              sp.type=0;  // primary
00801            }else{
00802              sp.type=1;  //secondary
00803            }
00804 
00805            // now get zpca  (get perigee wrt beam)
00806            double x1=x0-0.033; double y1=y0-0.; // FIXME how do we get the simulated beam position?
00807            D0=x1*sin(p.phi())-y1*cos(p.phi())-0.5*kappa*(x1*x1+y1*y1);
00808            q=sqrt(1.-2.*kappa*D0);
00809            s0=(x1*cos(p.phi())+y1*sin(p.phi()))/q;
00810            if (fabs(kappa*s0)>0.001){
00811              s1=asin(kappa*s0)/kappa;
00812            }else{
00813              double ks02=(kappa*s0)*(kappa*s0);
00814              s1=s0*(1.+ks02/6.+3./40.*ks02*ks02+5./112.*pow(ks02,3));
00815            }
00816            sp.ddcap=-2.*D0/(1.+q);
00817            sp.zdcap=z0-s1/tan(p.theta());
00818            sp.zvtx=z0;
00819            sp.xvtx=x0;
00820            sp.yvtx=y0;
00821 
00822            tsim.push_back(sp);
00823          }
00824        }
00825      }// has vertex
00826    }//for loop
00827    return tsim;
00828 }
00829 
00830 
00831 int*  PrimaryVertexAnalyzer4PU::supf(std::vector<SimPart>& simtrks, const reco::TrackCollection & trks){
00832   int nsim=simtrks.size();
00833   int nrec=trks.size();
00834   int *rectosim=new int[nrec]; // pointer to associated simtrk
00835   double** pij=new double*[nrec];
00836   double mu=100.; // initial chi^2 cut-off  (5 dofs !)
00837   int nmatch=0;
00838   int i=0;
00839   for(reco::TrackCollection::const_iterator t=trks.begin(); t!=trks.end(); ++t){
00840     pij[i]=new double[nsim];
00841     rectosim[i]=-1;
00842     ParameterVector  par = t->parameters();
00843     //reco::TrackBase::CovarianceMatrix V = t->covariance();
00844     reco::TrackBase::CovarianceMatrix S = t->covariance();
00845     S.Invert();
00846     for(int j=0; j<nsim; j++){
00847       simtrks[j].rec=-1;
00848       SimPart s=simtrks[j];
00849       double c=0;
00850       for(int k=0; k<5; k++){
00851         for(int l=0; l<5; l++){
00852           c+=(par(k)-s.par[k])*(par(l)-s.par[l])*S(k,l);
00853         }
00854       }
00855       pij[i][j]=exp(-0.5*c);
00856 
00857 //       double c0=pow((par[0]-s.par[0])/t->qoverpError(),2)*0.1
00858 //      +pow((par[1]-s.par[1])/t->lambdaError(),2)
00859 //      +pow((par[2]-s.par[2])/t->phiError(),2)
00860 //      +pow((par[3]-s.par[3])/t->dxyError(),2)*0.1;
00861 //         +pow((par[4]-s.par[4])/t->dszError(),2)*0.1;
00862 //       pij[i][j]=exp(-0.5*c0);
00863 
00864 //       if( c0 <100 ){
00865 //       cout << setw(3) << i << " rec " << setw(6) << par << endl;
00866 //       cout << setw(3) << j << " sim " << setw(6) << s.par << " ---> C=" << c << endl;
00867 //       cout <<  "       "  << setw(6)
00868 //         << (par[0]-s.par[0])<< ","
00869 //         << (par[1]-s.par[1])<< ","
00870 //         << (par[2]-s.par[2])<< ","
00871 //         << (par[3]-s.par[3])<< ","
00872 //         << (par[4]-s.par[4])
00873 //         << " match=" << match(simtrks[j].par, trks.at(i).parameters())
00874 //         << endl;
00875 //       cout <<  "       "  << setw(6)
00876 //         << (par[0]-s.par[0])/t->qoverpError() << ","
00877 //         << (par[1]-s.par[1])/t->lambdaError() << ","
00878 //         << (par[2]-s.par[2])/t->phiError() << ","
00879 //         << (par[3]-s.par[3])/t->dxyError() << ","
00880 //         << (par[4]-s.par[4])/t->dszError() << " c0=" << c0
00881 //         << endl <<endl;
00882 //       }
00883 
00884     }
00885     i++;
00886   }
00887 
00888   for(int k=0; k<nrec; k++){
00889     int imatch=-1; int jmatch=-1;
00890     double pmatch=0;
00891     for(int j=0; j<nsim; j++){
00892       if ((simtrks[j].rec)<0){
00893         double psum=exp(-0.5*mu); //cutoff
00894         for(int i=0; i<nrec; i++){
00895           if (rectosim[i]<0){ psum+=pij[i][j];}
00896         }
00897         for(int i=0; i<nrec; i++){
00898           if ((rectosim[i]<0)&&(pij[i][j]/psum>pmatch)){
00899             pmatch=pij[i][j]/psum;
00900             imatch=i; jmatch=j;
00901           }
00902         }
00903       }
00904     }// sim loop
00905    if((jmatch>=0)||(imatch>=0)){
00906      //std::cout << pmatch << "    " << pij[imatch][jmatch] << "  match=" <<
00907      // match(simtrks[jmatch].par, trks.at(imatch).parameters()) <<std::endl;
00908       if (pmatch>0.01){
00909         rectosim[imatch]=jmatch;
00910         simtrks[jmatch].rec=imatch;
00911         nmatch++;
00912       }else if (match(simtrks[jmatch].par, trks.at(imatch).parameters())){
00913         // accept it anyway if it matches crudely and relax the cut-off
00914         rectosim[imatch]=jmatch;
00915         simtrks[jmatch].rec=imatch;
00916         nmatch++;
00917         mu=mu*2;
00918       }
00919     }
00920   }
00921 
00922 //   std::cout << ">>>>>>>>>>>>>>>--------------supf----------------------" << std::endl;
00923 //   std::cout <<"nsim=" << nsim   << "   nrec=" << nrec << "    nmatch=" << nmatch << std::endl;
00924 //   std::cout << "rec to sim " << std::endl;
00925 //   for(int i=0; i<nrec; i++){
00926 //     std::cout << i << " ---> " << rectosim[i] << std::endl;
00927 //   }
00928 //   std::cout << "sim to rec " << std::endl;
00929 //   for(int j=0; j<nsim; j++){
00930 //     std::cout << j << " ---> " << simtrks[j].rec << std::endl;
00931 //   }
00932 
00933    std::cout << "unmatched sim " << std::endl;
00934    for(int j=0; j<nsim; j++){
00935      if(simtrks[j].rec<0){
00936        double pt= 1./simtrks[j].par[0]/tan(simtrks[j].par[1]);
00937        if((fabs(pt))>1.){
00938          std::cout << setw(3) << j << setw(8) << simtrks[j].pdg 
00939                    << setw(8) << setprecision(4) << "  (" << simtrks[j].xvtx << "," << simtrks[j].yvtx <<  "," << simtrks[j].zvtx << ")" 
00940                    << " pt= " <<  pt
00941                    << " phi=" << simtrks[j].par[2] 
00942                    << " eta= " <<  -log(tan(0.5*(M_PI/2-simtrks[j].par[1]))) 
00943                    << std::endl; 
00944        }
00945      }
00946    }
00947 //   std::cout << "<<<<<<<<<<<<<<<--------------supf----------------------" << std::endl;
00948 
00949   //delete rectosim; // or return it?
00950   for(int i=0; i<nrec; i++){delete pij[i];}
00951   delete pij;
00952   return rectosim;  // caller must delete it
00953 }
00954 
00955 
00956 
00957 
00958 
00959 
00960 
00961 
00962 bool PrimaryVertexAnalyzer4PU::match(const ParameterVector  &a,
00963                                      const ParameterVector  &b){
00964   double dqoverp =a(0)-b(0);
00965   double dlambda =a(1)-b(1);
00966   double dphi    =a(2)-b(2);
00967   double dsz     =a(4)-b(4);
00968   if (dphi>M_PI){ dphi-=M_2_PI; }else if(dphi<-M_PI){dphi+=M_2_PI;}
00969   //  return ( (fabs(dqoverp)<0.2) && (fabs(dlambda)<0.02) && (fabs(dphi)<0.04) && (fabs(dsz)<0.1) );
00970   return ( (fabs(dqoverp)<0.2) && (fabs(dlambda)<0.02) && (fabs(dphi)<0.04) && (fabs(dsz)<1.0) );
00971 }
00972 
00973 
00974 bool PrimaryVertexAnalyzer4PU::matchVertex(const simPrimaryVertex  &vsim, 
00975                                        const reco::Vertex       &vrec){
00976   return (fabs(vsim.z*simUnit_-vrec.z())<zmatch_);
00977 }
00978 
00979 bool PrimaryVertexAnalyzer4PU::isResonance(const HepMC::GenParticle * p){
00980   double ctau=(pdt_->particle( abs(p->pdg_id()) ))->lifetime();
00981   //std::cout << "isResonance   " << p->pdg_id() << " " << ctau << std::endl;
00982   return  ctau >0 && ctau <1e-6;
00983 }
00984 
00985 bool PrimaryVertexAnalyzer4PU::isFinalstateParticle(const HepMC::GenParticle * p){
00986   return ( !p->end_vertex() && p->status()==1 );
00987 }
00988 
00989 
00990 bool PrimaryVertexAnalyzer4PU::isCharged(const HepMC::GenParticle * p){
00991   const ParticleData * part = pdt_->particle( p->pdg_id() );
00992   if (part){
00993     return part->charge()!=0;
00994   }else{
00995     // the new/improved particle table doesn't know anti-particles
00996     return  pdt_->particle( -p->pdg_id() )!=0;
00997   }
00998 }
00999 
01000 
01001 
01002 
01003 void PrimaryVertexAnalyzer4PU::fillTrackHistos(std::map<std::string, TH1*> & h, const std::string & ttype, const reco::Track & t, const reco::Vertex * v){
01004     Fill(h,"rapidity_"+ttype,t.eta());
01005     Fill(h,"z0_"+ttype,t.vz());
01006     Fill(h,"phi_"+ttype,t.phi());
01007     Fill(h,"eta_"+ttype,t.eta());
01008     Fill(h,"pt_"+ttype,t.pt());
01009     Fill(h,"found_"+ttype,t.found());
01010     Fill(h,"lost_"+ttype,t.lost());
01011     Fill(h,"nchi2_"+ttype,t.normalizedChi2());
01012     Fill(h,"rstart_"+ttype,(t.innerPosition()).Rho());
01013 
01014     double d0Error=t.d0Error();
01015     double d0=t.dxy(vertexBeamSpot_.position());
01016     if (d0Error>0){ 
01017       Fill(h,"logtresxy_"+ttype,log(d0Error/0.0001)/log(10.));
01018       Fill(h,"tpullxy_"+ttype,d0/d0Error);
01019     }
01020     //double z0=t.vz();
01021     double dzError=t.dzError();
01022     if(dzError>0){
01023       Fill(h,"logtresz_"+ttype,log(dzError/0.0001)/log(10.));
01024     }
01025 
01026     //
01027     Fill(h,"sigmatrkz_"+ttype,sqrt(pow(t.dzError(),2)+wxy2_/pow(tan(t.theta()),2)));
01028     Fill(h,"sigmatrkz0_"+ttype,t.dzError());
01029 
01030     // track vs vertex 
01031     if((! (v==NULL)) && (v->ndof()>10.)) {
01032       // emulate clusterizer input
01033       //const TransientTrack & tt = theB_->build(&t);    wrong !!!!
01034       TransientTrack tt = theB_->build(&t);    tt.setBeamSpot(vertexBeamSpot_); // need the setBeamSpot !
01035       double z=(tt.stateAtBeamLine().trackStateAtPCA()).position().z();
01036       double tantheta=tan((tt.stateAtBeamLine().trackStateAtPCA()).momentum().theta());
01037       double dz2= pow(tt.track().dzError(),2)+wxy2_/pow(tantheta,2);
01038       
01039       Fill(h,"restrkz_"+ttype,z-v->position().z());
01040       Fill(h,"restrkzvsphi_"+ttype,t.phi(), z-v->position().z());
01041       Fill(h,"restrkzvseta_"+ttype,t.eta(), z-v->position().z());
01042       Fill(h,"pulltrkzvsphi_"+ttype,t.phi(), (z-v->position().z())/sqrt(dz2));
01043       Fill(h,"pulltrkzvseta_"+ttype,t.eta(), (z-v->position().z())/sqrt(dz2));
01044 
01045       Fill(h,"pulltrkz_"+ttype,(z-v->position().z())/sqrt(dz2));
01046 
01047       double x1=t.vx()-vertexBeamSpot_.x0(); double y1=t.vy()-vertexBeamSpot_.y0();
01048       double kappa=-0.002998*fBfield_*t.qoverp()/cos(t.theta());
01049       double D0=x1*sin(t.phi())-y1*cos(t.phi())-0.5*kappa*(x1*x1+y1*y1);
01050       double q=sqrt(1.-2.*kappa*D0);
01051       double s0=(x1*cos(t.phi())+y1*sin(t.phi()))/q; 
01052       // double s1;
01053       if (fabs(kappa*s0)>0.001){
01054         //s1=asin(kappa*s0)/kappa;
01055       }else{
01056         //double ks02=(kappa*s0)*(kappa*s0);
01057         //s1=s0*(1.+ks02/6.+3./40.*ks02*ks02+5./112.*pow(ks02,3));
01058       }
01059       //     sp.ddcap=-2.*D0/(1.+q);
01060       //double zdcap=t.vz()-s1/tan(t.theta());
01061 
01062     }
01063     //
01064     
01065     // collect some info on hits and clusters
01066     Fill(h,"nbarrelLayers_"+ttype,t.hitPattern().pixelBarrelLayersWithMeasurement());
01067     Fill(h,"nPxLayers_"+ttype,t.hitPattern().pixelLayersWithMeasurement());
01068     Fill(h,"nSiLayers_"+ttype,t.hitPattern().trackerLayersWithMeasurement());
01069     Fill(h,"expectedInner_"+ttype,t.trackerExpectedHitsInner().numberOfHits());
01070     Fill(h,"expectedOuter_"+ttype,t.trackerExpectedHitsOuter().numberOfHits());
01071     Fill(h,"trackAlgo_"+ttype,t.algo());
01072     Fill(h,"trackQuality_"+ttype,t.qualityMask());
01073 
01074     //
01075     int longesthit=0, nbarrel=0;
01076     for(trackingRecHit_iterator hit=t.recHitsBegin(); hit!=t.recHitsEnd(); hit++){
01077       if ((**hit).isValid()   && (**hit).geographicalId().det() == DetId::Tracker ){
01078        bool barrel = DetId((**hit).geographicalId()).subdetId() == static_cast<int>(PixelSubdetector::PixelBarrel);
01079        //bool endcap = DetId::DetId((**hit).geographicalId()).subdetId() == static_cast<int>(PixelSubdetector::PixelEndcap);
01080        if (barrel){
01081          const SiPixelRecHit *pixhit = dynamic_cast<const SiPixelRecHit*>( &(**hit));
01082          edm::Ref<edmNew::DetSetVector<SiPixelCluster>, SiPixelCluster> const& clust = (*pixhit).cluster();
01083          if (clust.isNonnull()) {
01084            nbarrel++;
01085            if (clust->sizeY()-longesthit>0) longesthit=clust->sizeY();
01086            if (clust->sizeY()>20.){
01087              Fill(h,"lvseta_"+ttype,t.eta(), 19.9);
01088              Fill(h,"lvstanlambda_"+ttype,tan(t.lambda()), 19.9);
01089            }else{
01090              Fill(h,"lvseta_"+ttype,t.eta(), float(clust->sizeY()));
01091              Fill(h,"lvstanlambda_"+ttype,tan(t.lambda()), float(clust->sizeY()));
01092            }
01093          }
01094        }
01095       }
01096     }
01097     Fill(h,"nbarrelhits_"+ttype,float(nbarrel));
01098     //-------------------------------------------------------------------
01099 
01100 }
01101 
01102 void PrimaryVertexAnalyzer4PU::dumpHitInfo(const reco::Track & t){
01103     // collect some info on hits and clusters
01104   int longesthit=0, nbarrel=0;
01105   cout << Form("%5.2f  %5.2f  : ",t.pt(),t.eta());
01106   for(trackingRecHit_iterator hit=t.recHitsBegin(); hit!=t.recHitsEnd(); hit++){
01107     if ((**hit).isValid()   && (**hit).geographicalId().det() == DetId::Tracker ){
01108       bool barrel = DetId((**hit).geographicalId()).subdetId() == static_cast<int>(PixelSubdetector::PixelBarrel);
01109       //bool endcap = DetId::DetId((**hit).geographicalId()).subdetId() == static_cast<int>(PixelSubdetector::PixelEndcap);
01110       if (barrel){
01111         nbarrel++;
01112         const SiPixelRecHit *pixhit = dynamic_cast<const SiPixelRecHit*>( &(**hit));
01113         edm::Ref<edmNew::DetSetVector<SiPixelCluster>, SiPixelCluster> const& clust = (*pixhit).cluster();
01114         if (clust.isNonnull()) {
01115           cout << Form("%4d",clust->sizeY());
01116           if (clust->sizeY()-longesthit>0) longesthit=clust->sizeY();
01117         }
01118       }
01119     }
01120   }
01121   //cout << endl;
01122 }
01123 
01124 void PrimaryVertexAnalyzer4PU::printRecVtxs(const Handle<reco::VertexCollection> recVtxs, std::string title){
01125     int ivtx=0;
01126     std::cout << std::endl << title << std::endl;
01127     for(reco::VertexCollection::const_iterator v=recVtxs->begin(); 
01128         v!=recVtxs->end(); ++v){
01129       string vtype=" recvtx  ";
01130       if( v->isFake()){
01131         vtype=" fake   ";
01132       }else if (v->ndof()==-5){
01133         vtype=" cluster "; // pos=selector[iclu],cputime[iclu],clusterz[iclu]
01134       }else if(v->ndof()==-3){
01135         vtype=" event   ";
01136       }
01137       std::cout << "vtx "<< std::setw(3) << std::setfill(' ')<<ivtx++
01138                 << vtype
01139                 << " #trk " << std::fixed << std::setprecision(4) << std::setw(3) << v->tracksSize() 
01140                 << " chi2 " << std::fixed << std::setw(4) << std::setprecision(1) << v->chi2() 
01141                 << " ndof " << std::fixed << std::setw(5) << std::setprecision(2) << v->ndof()
01142                 << " x "  << std::setw(8) <<std::fixed << std::setprecision(4) << v->x() 
01143                 << " dx " << std::setw(8) << v->xError()// <<  std::endl 
01144                 << " y "  << std::setw(8) << v->y() 
01145                 << " dy " << std::setw(8) << v->yError()//<< std::endl
01146                 << " z "  << std::setw(8) << v->z() 
01147                 << " dz " << std::setw(8) << v->zError()
01148                 << std::endl;
01149     }
01150 }
01151 
01152 
01153 void PrimaryVertexAnalyzer4PU::printSimVtxs(const Handle<SimVertexContainer> simVtxs){
01154     int i=0;
01155     for(SimVertexContainer::const_iterator vsim=simVtxs->begin();
01156         vsim!=simVtxs->end(); ++vsim){
01157       if ( vsim->position().x()*vsim->position().x()+vsim->position().y()*vsim->position().y() < 1.){
01158         std::cout << i++ << ")" << std::scientific
01159                   << " evtid=" << vsim->eventId().event()  << ","  << vsim->eventId().bunchCrossing()
01160                   << " sim x=" << vsim->position().x()*simUnit_
01161                   << " sim y=" << vsim->position().y()*simUnit_
01162                   << " sim z=" << vsim->position().z()*simUnit_
01163                   << " sim t=" << vsim->position().t()
01164                   << " parent=" << vsim->parentIndex() 
01165                   << std::endl;
01166       }
01167     }
01168 }
01169 
01170 
01171 
01172 
01173 
01174 
01175 
01176 void PrimaryVertexAnalyzer4PU::printSimTrks(const Handle<SimTrackContainer> simTrks){
01177   std::cout <<  " simTrks   type, (momentum), vertIndex, genpartIndex"  << std::endl;
01178   int i=1;
01179   for(SimTrackContainer::const_iterator t=simTrks->begin();
01180       t!=simTrks->end(); ++t){
01181     //HepMC::GenParticle* gp=evtMC->GetEvent()->particle( (*t).genpartIndex() );
01182     std::cout << i++ << ")" 
01183               << t->eventId().event()  << ","  << t->eventId().bunchCrossing()
01184               << (*t)
01185               << " index="
01186               << (*t).genpartIndex();
01187     //if (gp) {
01188     //  HepMC::GenVertex *gv=gp->production_vertex();
01189     //  std::cout  <<  " genvertex =" << (*gv);
01190     //}
01191     std::cout << std::endl;
01192   }
01193 }
01194 
01195 
01196 
01197 void PrimaryVertexAnalyzer4PU::printRecTrks(const Handle<reco::TrackCollection> &recTrks  ){
01198 
01199   cout << "printRecTrks" << endl;
01200   int i =1;
01201   for(reco::TrackCollection::const_iterator t=recTrks->begin(); t!=recTrks->end(); ++t){
01202     //    reco::TrackBase::ParameterVector  par = t->parameters();
01203     
01204     cout << endl;
01205     cout << "Track "<<i << " " ; i++;
01206     //enum TrackQuality { undefQuality=-1, loose=0, tight=1, highPurity=2, confirmed=3, goodIterative=4, qualitySize=5};
01207     if( t->quality(reco::TrackBase::loose)){ cout << "loose ";};
01208     if( t->quality(reco::TrackBase::tight)){ cout << "tight ";};
01209     if( t->quality(reco::TrackBase::highPurity)){ cout << "highPurity ";};
01210     if( t->quality(reco::TrackBase::confirmed)){ cout << "confirmed  ";};
01211     if( t->quality(reco::TrackBase::goodIterative)){ cout << "goodIterative  ";};
01212     cout  << endl;
01213 
01214     TransientTrack  tk = theB_->build(&(*t)); tk.setBeamSpot(vertexBeamSpot_);   
01215     double ipsig=0;
01216     if (tk.stateAtBeamLine().isValid()){
01217       ipsig= tk.stateAtBeamLine().transverseImpactParameter().significance();
01218     }else{
01219       ipsig=-1;
01220     }
01221 
01222     cout << Form("pt=%8.3f phi=%6.3f eta=%6.3f z=%8.4f  dz=%6.4f, ipsig=%6.1f",t->pt(), t->phi(), t->eta(), t->vz(), t->dzError(),ipsig) << endl;
01223 
01224 
01225     cout << Form(" found=%6d  lost=%6d   chi2/ndof=%10.3f ",t->found(), t->lost(),t->normalizedChi2())<<endl;
01226     const reco::HitPattern & p= t->hitPattern();
01227     cout << "subdet layers valid lost" << endl;
01228     cout << Form(" barrel  %2d  %2d  %2d",p.pixelBarrelLayersWithMeasurement(),p.numberOfValidPixelBarrelHits(), p.numberOfLostPixelBarrelHits()) << endl;
01229     cout << Form(" fwd     %2d  %2d  %2d",p.pixelEndcapLayersWithMeasurement(),p.numberOfValidPixelEndcapHits(), p.numberOfLostPixelEndcapHits()) << endl;
01230     cout << Form(" pixel   %2d  %2d  %2d",p.pixelLayersWithMeasurement(), p.numberOfValidPixelHits(), p.numberOfLostPixelHits()) << endl;
01231     cout << Form(" tracker %2d  %2d  %2d",p.trackerLayersWithMeasurement(), p.numberOfValidTrackerHits(), p.numberOfLostTrackerHits()) << endl;
01232     cout << endl;
01233     const reco::HitPattern & pinner= t->trackerExpectedHitsInner();
01234     const reco::HitPattern & pouter= t->trackerExpectedHitsOuter();
01235     int ninner=pinner.numberOfHits();
01236     int nouter=pouter.numberOfHits();
01237 
01238     //    double d0Error=t.d0Error();
01239     //    double d0=t.dxy(myBeamSpot);
01240     
01241     //
01242     for(trackingRecHit_iterator hit=t->recHitsBegin(); hit!=t->recHitsEnd(); hit++){
01243       if ((**hit).isValid()   && (**hit).geographicalId().det() == DetId::Tracker ){
01244        bool barrel = DetId((**hit).geographicalId()).subdetId() == static_cast<int>(PixelSubdetector::PixelBarrel);
01245        bool endcap = DetId((**hit).geographicalId()).subdetId() == static_cast<int>(PixelSubdetector::PixelEndcap);
01246        if (barrel){
01247          const SiPixelRecHit *pixhit = dynamic_cast<const SiPixelRecHit*>( &(**hit));
01248          edm::Ref<edmNew::DetSetVector<SiPixelCluster>, SiPixelCluster> const& clust = (*pixhit).cluster();
01249          if (clust.isNonnull()) {
01250            cout << Form(" barrel cluster size=%2d   charge=%6.1f wx=%2d  wy=%2d, expected=%3.1f",clust->size(),clust->charge(),clust->sizeX(),clust->sizeY(),1.+2./fabs(tan(t->theta()))) << endl;
01251          }
01252        }else if(endcap){
01253          const SiPixelRecHit *pixhit = dynamic_cast<const SiPixelRecHit*>( &(**hit));
01254          edm::Ref<edmNew::DetSetVector<SiPixelCluster>, SiPixelCluster> const& clust = (*pixhit).cluster();
01255          if (clust.isNonnull()) {
01256            cout << Form(" endcap cluster size=%2d   charge=%6.1f wx=%2d  wy=%2d",clust->size(),clust->charge(),clust->sizeX(),clust->sizeY()) << endl;
01257          }
01258        }
01259       }
01260     }
01261     cout << "hitpattern" << endl;
01262     for(int i=0; i<p.numberOfHits(); i++){      p.printHitPattern(i,std::cout);    }
01263     cout << "expected inner " << ninner << endl;
01264     for(int i=0; i<pinner.numberOfHits(); i++){      pinner.printHitPattern(i,std::cout);    }
01265     cout << "expected outer " << nouter << endl;
01266     for(int i=0; i<pouter.numberOfHits(); i++){      pouter.printHitPattern(i,std::cout);    }
01267   }
01268 }
01269 
01270 namespace {
01271 
01272   bool recTrackLessZ(const reco::TransientTrack & tk1,
01273                      const reco::TransientTrack & tk2)
01274   {
01275     return tk1.stateAtBeamLine().trackStateAtPCA().position().z() < tk2.stateAtBeamLine().trackStateAtPCA().position().z();
01276   }
01277 
01278 }
01279 
01280 
01281 
01282 
01283 void PrimaryVertexAnalyzer4PU::printPVTrks(const Handle<reco::TrackCollection> &recTrks, 
01284                                            const Handle<reco::VertexCollection> &recVtxs,  
01285                                            std::vector<SimPart>& tsim,
01286                                            std::vector<SimEvent>& simEvt,
01287                                            bool selectedOnly){
01288   // make a printout of the tracks selected for PV reconstructions, show matching MC tracks, too
01289 
01290   vector<TransientTrack>  selTrks;
01291   for(reco::TrackCollection::const_iterator t=recTrks->begin();
01292       t!=recTrks->end(); ++t){
01293     TransientTrack  tt = theB_->build(&(*t));  tt.setBeamSpot(vertexBeamSpot_);
01294     if( (!selectedOnly) || (selectedOnly && theTrackFilter(tt))){     selTrks.push_back(tt);    }
01295   }
01296   if (selTrks.size()==0) return;
01297   stable_sort(selTrks.begin(), selTrks.end(), recTrackLessZ);
01298 
01299   // select tracks like for PV reconstruction and match them to sim tracks
01300   reco::TrackCollection selRecTrks;
01301 
01302   for(unsigned int i=0; i<selTrks.size(); i++){ selRecTrks.push_back(selTrks[i].track());} 
01303   int* rectosim=supf(tsim, selRecTrks);
01304 
01305 
01306 
01307   // now dump in a format similar to the clusterizer
01308   cout << "printPVTrks" << endl;
01309   cout << "----          z +/- dz     1bet-m     ip +/-dip         pt   phi   eta";
01310   if((tsim.size()>0)||(simEvt.size()>0)) {cout << " type     pdg    zvtx    zdca      dca    zvtx   zdca    dsz";}
01311   cout << endl;
01312 
01313   cout.precision(4);
01314   int isel=0;
01315   for(unsigned int i=0; i<selTrks.size(); i++){
01316     if  (selectedOnly || (theTrackFilter(selTrks[i]))) {
01317           cout <<  setw (3)<< isel;
01318           isel++;
01319     }else{
01320       cout <<  "   ";
01321     }
01322 
01323 
01324     // is this track in the tracklist of a recvtx ?
01325     int vmatch=-1;
01326     int iv=0;
01327     for(reco::VertexCollection::const_iterator v=recVtxs->begin(); 
01328         v!=recVtxs->end(); ++v){
01329       if ( (v->ndof()<-1) || (v->chi2()<=0) ) continue;  // skip clusters 
01330       for(trackit_t tv=v->tracks_begin(); tv!=v->tracks_end(); tv++){
01331         const reco::Track & RTv=*(tv->get());  
01332         if(selTrks[i].track().vz()==RTv.vz()) {vmatch=iv;}
01333       }
01334       iv++;
01335     }
01336 
01337     double tz=(selTrks[i].stateAtBeamLine().trackStateAtPCA()).position().z();
01338     double tantheta=tan((selTrks[i].stateAtBeamLine().trackStateAtPCA()).momentum().theta());
01339     double tdz0= selTrks[i].track().dzError();
01340     double tdz2= pow(selTrks[i].track().dzError(),2)+ (pow(vertexBeamSpot_.BeamWidthX(),2)+pow(vertexBeamSpot_.BeamWidthY(),2))/pow(tantheta,2);
01341     
01342     if(vmatch>-1){
01343       cout << "["<<setw(2)<<vmatch<<"]";
01344     }else{
01345       //int status=theTrackFilter.status(selTrks[i]);
01346       int status=0;
01347       if(status==0){
01348         cout <<"    ";
01349       }else{
01350         if(status&0x1){cout << "i";}else{cout << ".";};
01351         if(status&0x2){cout << "c";}else{cout << ".";};
01352         if(status&0x4){cout << "h";}else{cout << ".";};
01353         if(status&0x8){cout << "q";}else{cout << ".";};
01354       }
01355     }
01356     cout  <<  setw (8) << fixed << setprecision(4)<<  tz << " +/-" <<  setw (6)<< sqrt(tdz2);
01357     
01358 
01359     // track quality and hit information, see DataFormats/TrackReco/interface/HitPattern.h
01360     if(selTrks[i].track().quality(reco::TrackBase::highPurity)){ cout << " *";}else{cout <<"  ";}
01361     if(selTrks[i].track().hitPattern().hasValidHitInFirstPixelBarrel()){cout <<"+";}else{cout << "-";}
01362     cout << setw(1) << selTrks[i].track().hitPattern().pixelBarrelLayersWithMeasurement();
01363     cout << setw(1) << selTrks[i].track().hitPattern().pixelEndcapLayersWithMeasurement(); 
01364     cout << setw(1) << hex << selTrks[i].track().hitPattern().trackerLayersWithMeasurement()-selTrks[i].track().hitPattern().pixelLayersWithMeasurement()<<dec;
01365     cout << "-" << setw(1)<<hex <<selTrks[i].track().trackerExpectedHitsOuter().numberOfHits() << dec;
01366 
01367     
01368     Measurement1D IP=selTrks[i].stateAtBeamLine().transverseImpactParameter();
01369     cout << setw (8) << IP.value() << "+/-" << setw (6) << IP.error();
01370     if(selTrks[i].track().ptError()<1){
01371       cout << " " << setw(8) << setprecision(2)  << selTrks[i].track().pt()*selTrks[i].track().charge();
01372     }else{
01373       cout << " " << setw(7) << setprecision(1)  << selTrks[i].track().pt()*selTrks[i].track().charge() << "*";
01374       //cout << "+/-" << setw(6)<< setprecision(2) << selTrks[i].track().ptError();
01375     }
01376     cout << " " << setw(5) << setprecision(2) << selTrks[i].track().phi()
01377          << " " << setw(5) << setprecision(2) << selTrks[i].track().eta() ;
01378 
01379 
01380 
01381     // print MC info, if available
01382     if(simEvt.size()>0){
01383       reco::Track t=selTrks[i].track();
01384       try{
01385         TrackingParticleRef tpr = z2tp_[t.vz()];
01386         const TrackingVertex *parentVertex= tpr->parentVertex().get();
01387         //double vx=parentVertex->position().x(); // problems with tpr->vz()
01388         //double vy=parentVertex->position().y(); work in progress
01389         double vz=parentVertex->position().z();
01390         cout << " " << tpr->eventId().event();
01391         cout << " " << setw(5) << tpr->pdgId();
01392         cout << " " << setw(8) << setprecision(4) << vz;
01393       }catch (...){
01394         cout << " not matched";
01395       }
01396     }else{
01397       //    cout << "  " << rectosim[i];
01398       if(rectosim[i]>0){
01399         if(tsim[rectosim[i]].type==0){  cout << " prim " ;}else{cout << " sec  ";}
01400         cout << " " << setw(5) << tsim[rectosim[i]].pdg;
01401         cout << " " << setw(8) << setprecision(4) << tsim[rectosim[i]].zvtx;
01402         cout << " " << setw(8) << setprecision(4) << tsim[rectosim[i]].zdcap;
01403         cout << " " << setw(8) << setprecision(4) << tsim[rectosim[i]].ddcap;
01404         double zvtxpull=(tz-tsim[rectosim[i]].zvtx)/sqrt(tdz2);
01405         cout << setw(6) << setprecision(1) << zvtxpull;
01406         double zdcapull=(tz-tsim[rectosim[i]].zdcap)/tdz0;
01407         cout << setw(6) << setprecision(1) << zdcapull;
01408         double dszpull=(selTrks[i].track().dsz()-tsim[rectosim[i]].par[4])/selTrks[i].track().dszError();
01409         cout << setw(6) << setprecision(1) << dszpull;
01410       }
01411     }
01412     cout << endl;
01413   }
01414   delete rectosim;
01415 }
01416 
01417 
01418 void PrimaryVertexAnalyzer4PU::matchRecTracksToVertex(simPrimaryVertex & pv, 
01419                                                    const std::vector<SimPart > & tsim,
01420                                                    const edm::Handle<reco::TrackCollection> & recTrks)
01421 {
01422   // find all recTracks that belong to this simulated vertex (not just the ones that are used in
01423   // matching recVertex)
01424 
01425   std::cout << "dump rec tracks: " << std::endl;
01426   int irec=0;
01427   for(reco::TrackCollection::const_iterator t=recTrks->begin();
01428       t!=recTrks->end(); ++t){
01429     reco::TrackBase::ParameterVector  p = t->parameters();
01430     std::cout  << irec++ << ") " << p <<  std::endl;
01431   }
01432 
01433   std::cout << "match sim tracks: " << std::endl;
01434   pv.matchedRecTrackIndex.clear();
01435   pv.nMatchedTracks=0;
01436   int isim=0;
01437   for(std::vector<SimPart>::const_iterator s=tsim.begin();
01438       s!=tsim.end(); ++s){
01439     std::cout  << isim++ << " " << s->par;// << std::endl;
01440     int imatch=-1;
01441     int irec=0;
01442     for(reco::TrackCollection::const_iterator t=recTrks->begin();
01443         t!=recTrks->end(); ++t){
01444       reco::TrackBase::ParameterVector  p = t->parameters();
01445       if (match(s->par,p)){     imatch=irec; }
01446       irec++;
01447     }
01448     pv.matchedRecTrackIndex.push_back(imatch);
01449     if(imatch>-1){ 
01450       pv.nMatchedTracks++; 
01451       std::cout << " matched to rec trk" << imatch << std::endl;
01452     }else{
01453       std::cout << " not matched" << std::endl;
01454     }
01455   }
01456 }
01457 /********************************************************************************************************/
01458 
01459 
01460 
01461 
01462 
01463 
01464 /********************************************************************************************************/
01465 
01466 void PrimaryVertexAnalyzer4PU::getTc(const std::vector<reco::TransientTrack>& tracks, 
01467                                double & Tc, double & chsq, double & dzmax, double & dztrim, double & m4m2){
01468   if (tracks.size()<2){ Tc=-1; chsq=-1; dzmax=-1; dztrim=-1; m4m2=-1; return;}
01469 
01470   double sumw=0, sumwz=0, sumww=0,sumwwz=0,sumwwzz=0;
01471   double zmin=1e10, zmin1=1e10, zmax1=-1e10, zmax=-1e10;
01472   double m4=0,m3=0,m2=0,m1=0,m0=0;
01473   for(vector<reco::TransientTrack>::const_iterator it=tracks.begin(); it!=tracks.end(); it++){
01474      double tantheta=tan(((*it).stateAtBeamLine().trackStateAtPCA()).momentum().theta());
01475      reco::BeamSpot beamspot=(it->stateAtBeamLine()).beamSpot();
01476      double z=((*it).stateAtBeamLine().trackStateAtPCA()).position().z();
01477      double dz2= pow((*it).track().dzError(),2)+pow(beamspot.BeamWidthX()/tantheta,2);
01478    //    t.dz2= pow((*it).track().dzError(),2) + pow(wxy0/tantheta,2) +  1./(1.+exp(pow(t.ip/t.dip,2)-pow(2.)))*pow(ip/tantheta,2);
01479      double w=1./dz2;  // take p=1
01480      sumw    += w;
01481      sumwz   += w*z;
01482      sumwwz  += w*w*z;;
01483      sumwwzz += w*w*z*z;
01484      sumww   += w*w;
01485      m0      += w;
01486      m1      += w*z;
01487      m2      += w*z*z;
01488      m3      += w*z*z*z;
01489      m4      += w*z*z*z*z;
01490      if(dz2<pow(0.1,2)){
01491        if(z<zmin1){zmin1=z;}    if(z<zmin){zmin1=zmin; zmin=z;}
01492        if(z>zmax1){zmax1=z;}    if(z>zmax){zmax1=zmax; zmax=z;}
01493      }
01494   }
01495   double z=sumwz/sumw;
01496   double a=sumwwzz-2*z*sumwwz+z*z*sumww;
01497   double b=sumw;
01498   if(tracks.size()>1){
01499     chsq=(m2-m0*z*z)/(tracks.size()-1);
01500     Tc=2.*a/b;
01501     m4m2=sqrt((m4-4*m3*z+6*m2*z*z-3*m1*z*z*z+m0*z*z*z*z)/(m2-2*m1*z+z*z*m0));
01502   }else{
01503     chsq=0;
01504     Tc=0;
01505     m4m2=0;
01506   }
01507   dzmax=zmax-zmin;
01508   dztrim=zmax1-zmin1;// truncated
01509 }
01510 /********************************************************************************************************/
01511 
01512 
01513 
01514 
01515 
01516 /********************************************************************************************************/
01517 bool PrimaryVertexAnalyzer4PU::truthMatchedTrack( edm::RefToBase<reco::Track> track, TrackingParticleRef & tpr)
01518 
01519 /********************************************************************************************************/
01520 // for a reco track select the matching tracking particle, always use this function to make sure we
01521 // are consistent
01522 // to get the TrackingParticle form the TrackingParticleRef, use ->get();
01523 {
01524   double f=0;
01525   try{
01526     std::vector<std::pair<TrackingParticleRef, double> > tp = r2s_[track];
01527     for (std::vector<std::pair<TrackingParticleRef, double> >::const_iterator it = tp.begin(); 
01528          it != tp.end(); ++it) {
01529       
01530       if (it->second>f){
01531         tpr=it->first;
01532         f=it->second;
01533       }
01534     }
01535   } catch (Exception event) {
01536     // silly way of testing whether track is in r2s_
01537   }
01538   
01539   // sanity check on track parameters?
01540   
01541   return (f>0.5);
01542 }
01543 /********************************************************************************************************/
01544 
01545 
01546 
01547 
01548 
01549 
01550 /********************************************************************************************************/
01551 std::vector< edm::RefToBase<reco::Track> >  PrimaryVertexAnalyzer4PU::getTruthMatchedVertexTracks(
01552                                        const reco::Vertex& v
01553                                        )
01554 // for vertex v get a list of tracks for which truth matching is available 
01555 /********************************************************************************************************/
01556 {
01557   std::vector<  edm::RefToBase<reco::Track> > b;
01558   TrackingParticleRef tpr;
01559 
01560   for(trackit_t tv=v.tracks_begin(); tv!=v.tracks_end(); tv++){
01561     edm::RefToBase<reco::Track> track=*tv;
01562     if (truthMatchedTrack(track, tpr)){
01563       b.push_back(*tv);
01564     }
01565   }
01566 
01567 
01568   return b;
01569 }
01570 /********************************************************************************************************/
01571 
01572 
01573 
01574 
01575 
01576 /********************************************************************************************************/
01577 std::vector<PrimaryVertexAnalyzer4PU::SimEvent> PrimaryVertexAnalyzer4PU::getSimEvents
01578 (
01579  // const Event& iEvent, const EventSetup& iSetup,
01580  edm::Handle<TrackingParticleCollection>  TPCollectionH,
01581  edm::Handle<TrackingVertexCollection>  TVCollectionH,
01582  edm::Handle<View<Track> > trackCollectionH
01583  ){
01584 
01585   const TrackingParticleCollection* simTracks = TPCollectionH.product();
01586   const View<Track>  tC = *(trackCollectionH.product());
01587 
01588 
01589   vector<SimEvent> simEvt;
01590   map<EncodedEventId, unsigned int> eventIdToEventMap;
01591   map<EncodedEventId, unsigned int>::iterator id;
01592   bool dumpTP=false;
01593   for(TrackingParticleCollection::const_iterator it=simTracks->begin(); it!=simTracks->end(); it++){
01594     
01595     if( fabs(it->parentVertex().get()->position().z())>100.) continue; // skip funny entries @ -13900
01596 
01597     unsigned int event=0;  //note, this is no longer the same as eventId().event()
01598     id=eventIdToEventMap.find(it->eventId());
01599     if (id==eventIdToEventMap.end()){
01600 
01601       // new event here
01602       SimEvent e;
01603       e.eventId=it->eventId();
01604       event=simEvt.size();
01605       const TrackingVertex *parentVertex= it->parentVertex().get();
01606       if(DEBUG_){
01607         cout << "getSimEvents: ";
01608         cout << it->eventId().bunchCrossing() << "," <<  it->eventId().event() 
01609              << " z="<< it->vz() << " " 
01610              << parentVertex->eventId().bunchCrossing() << ","  <<parentVertex->eventId().event() 
01611              << " z=" << parentVertex->position().z() << endl;
01612       }
01613       if (it->eventId()==parentVertex->eventId()){
01614         //e.x=it->vx(); e.y=it->vy(); e.z=it->vz();// wrong ???
01615         e.x=parentVertex->position().x();
01616         e.y=parentVertex->position().y();
01617         e.z=parentVertex->position().z();
01618         if(e.z<-100){
01619           dumpTP=true;
01620         }
01621       }else{
01622         e.x=0; e.y=0; e.z=-88.;
01623       }
01624       simEvt.push_back(e);
01625       eventIdToEventMap[e.eventId]=event;
01626     }else{
01627       event=id->second;
01628     }
01629       
01630 
01631     simEvt[event].tp.push_back(&(*it));
01632     if( (abs(it->eta())<2.5) && (it->charge()!=0) ){
01633       simEvt[event].sumpt2+=pow(it->pt(),2); // should keep track of decays ?
01634       simEvt[event].sumpt+=it->pt(); 
01635     }
01636   }
01637 
01638   if(dumpTP){
01639     for(TrackingParticleCollection::const_iterator it=simTracks->begin(); it!=simTracks->end(); it++){
01640       std::cout << *it << std::endl;
01641     } 
01642   }
01643 
01644 
01645   for(View<Track>::size_type i=0; i<tC.size(); ++i) {
01646     RefToBase<Track> track(trackCollectionH, i);
01647     TrackingParticleRef tpr;
01648     if( truthMatchedTrack(track,tpr)){
01649 
01650       if( eventIdToEventMap.find(tpr->eventId())==eventIdToEventMap.end() ){ cout << "Bug in getSimEvents" << endl; break; }
01651 
01652       z2tp_[track.get()->vz()]=tpr;
01653 
01654       unsigned int event=eventIdToEventMap[tpr->eventId()];
01655       double ipsig=0,ipdist=0;
01656       const TrackingVertex *parentVertex= tpr->parentVertex().get();
01657       double vx=parentVertex->position().x(); // problems with tpr->vz()
01658       double vy=parentVertex->position().y();
01659       double vz=parentVertex->position().z();
01660       double d=sqrt(pow(simEvt[event].x-vx,2)+pow(simEvt[event].y-vy,2)+pow(simEvt[event].z-vz,2))*1.e4;
01661       ipdist=d;
01662       double dxy=track->dxy(vertexBeamSpot_.position());
01663       ipsig=dxy/track->dxyError();
01664 
01665 
01666       TransientTrack  t = theB_->build(tC[i]); 
01667       t.setBeamSpot(vertexBeamSpot_);   
01668       if (theTrackFilter(t)){
01669         simEvt[event].tk.push_back(t);
01670         if(ipdist<5){simEvt[event].tkprim.push_back(t);}
01671         if(ipsig<5){simEvt[event].tkprimsel.push_back(t);}
01672       }
01673       
01674     }
01675   }
01676 
01677 
01678   
01679   AdaptiveVertexFitter theFitter;
01680   cout << "SimEvents " << simEvt.size()  <<  endl;
01681   for(unsigned int i=0; i<simEvt.size(); i++){
01682 
01683     if(simEvt[i].tkprim.size()>0){
01684 
01685       getTc(simEvt[i].tkprimsel, simEvt[i].Tc, simEvt[i].chisq, simEvt[i].dzmax, simEvt[i].dztrim, simEvt[i].m4m2);
01686       TransientVertex v = theFitter.vertex(simEvt[i].tkprim, vertexBeamSpot_);
01687       if (v.isValid()){
01688         simEvt[i].xfit=v.position().x();
01689         simEvt[i].yfit=v.position().y();
01690         simEvt[i].zfit=v.position().z();
01691         //      if (simEvt[i].z<-80.){simEvt[i].z=v.position().z();} // for now
01692       }
01693     }
01694 
01695 
01696     if(DEBUG_){
01697       cout << i <<"  )   nTP="  << simEvt[i].tp.size()
01698            << "   z=" <<  simEvt[i].z
01699            << "    recTrks="  << simEvt[i].tk.size() 
01700            << "    recTrksPrim="  << simEvt[i].tkprim.size() 
01701            << "   zfit=" << simEvt[i].zfit
01702            << endl;
01703     }
01704   }
01705  
01706   return simEvt;
01707 }
01708 
01709 
01710 std::vector<PrimaryVertexAnalyzer4PU::simPrimaryVertex> PrimaryVertexAnalyzer4PU::getSimPVs(
01711                                       const Handle<HepMCProduct> evtMC)
01712 {
01713   if(DEBUG_){std::cout << "getSimPVs HepMC " << std::endl;}
01714 
01715   std::vector<PrimaryVertexAnalyzer4PU::simPrimaryVertex> simpv;
01716   const HepMC::GenEvent* evt=evtMC->GetEvent();
01717   if (evt) {
01718 //     std::cout << "process id " <<evt->signal_process_id()<<std::endl;
01719 //     std::cout <<"signal process vertex "<< ( evt->signal_process_vertex() ?
01720 //                                           evt->signal_process_vertex()->barcode() : 0 )   <<std::endl;
01721 //     std::cout <<"number of vertices " << evt->vertices_size() << std::endl;
01722 
01723 
01724     //int idx=0;
01725     for(HepMC::GenEvent::vertex_const_iterator vitr= evt->vertices_begin();
01726         vitr != evt->vertices_end(); ++vitr ) 
01727       { // loop for vertex ...
01728 
01729         HepMC::FourVector pos = (*vitr)->position();
01730         //      if (pos.t()>0) { continue;} // skip secondary vertices, doesn't work for some samples
01731 
01732         if (fabs(pos.z())>1000) continue;  // skip funny junk vertices
01733 
01734         bool hasMotherVertex=false;
01735         //std::cout << "mothers" << std::endl;
01736         for ( HepMC::GenVertex::particle_iterator
01737               mother  = (*vitr)->particles_begin(HepMC::parents);
01738               mother != (*vitr)->particles_end(HepMC::parents);
01739               ++mother ) {
01740           HepMC::GenVertex * mv=(*mother)->production_vertex();
01741           if (mv) {hasMotherVertex=true;}
01742           //std::cout << "\t"; (*mother)->print();
01743         }
01744         if(hasMotherVertex) {continue;}
01745 
01746 
01747         // could be a new vertex, check  all primaries found so far to avoid multiple entries
01748         const double mm=0.1;  
01749         simPrimaryVertex sv(pos.x()*mm,pos.y()*mm,pos.z()*mm);
01750         simPrimaryVertex *vp=NULL;  // will become non-NULL if a vertex is found and then point to it
01751         for(std::vector<simPrimaryVertex>::iterator v0=simpv.begin();
01752             v0!=simpv.end(); v0++){
01753           if( (fabs(sv.x-v0->x)<1e-5) && (fabs(sv.y-v0->y)<1e-5) && (fabs(sv.z-v0->z)<1e-5)){
01754             vp=&(*v0);
01755             break;
01756           }
01757         }
01758         if(!vp){
01759           // this is a new vertex
01760           //std::cout << "this is a new vertex" << sv.x << " " << sv.y << " " << sv.z <<std::endl;
01761           simpv.push_back(sv);
01762           vp=&simpv.back();
01763 //      }else{
01764 //        std::cout << "this is not a new vertex" << std::endl;
01765         }
01766 
01767         
01768         // store the gen vertex barcode with this simpv
01769         vp->genVertex.push_back((*vitr)->barcode());
01770 
01771 
01772         // collect final state descendants and sum up momenta etc
01773         for ( HepMC::GenVertex::particle_iterator
01774               daughter  = (*vitr)->particles_begin(HepMC::descendants);
01775               daughter != (*vitr)->particles_end(HepMC::descendants);
01776               ++daughter ) {
01777           //std::cout << "checking daughter  type " << (*daughter)->pdg_id() << " final :" <<isFinalstateParticle(*daughter) << std::endl;
01778           if (isFinalstateParticle(*daughter)){ 
01779             if ( find(vp->finalstateParticles.begin(), vp->finalstateParticles.end(),(*daughter)->barcode())
01780                  == vp->finalstateParticles.end()){
01781               vp->finalstateParticles.push_back((*daughter)->barcode());
01782               HepMC::FourVector m=(*daughter)->momentum();
01783               //std::cout << "adding particle to primary " << m.px()<< " "  << m.py() << " "  << m.pz() << std::endl; 
01784               vp->ptot.setPx(vp->ptot.px()+m.px());
01785               vp->ptot.setPy(vp->ptot.py()+m.py());
01786               vp->ptot.setPz(vp->ptot.pz()+m.pz());
01787               vp->ptot.setE(vp->ptot.e()+m.e());
01788               vp->ptsq+=(m.perp())*(m.perp());
01789               // count relevant particles
01790               if ( (m.perp()>0.2) && (fabs(m.pseudoRapidity())<2.5) && isCharged( *daughter ) ){
01791                 vp->nGenTrk++;
01792               }
01793               
01794               hsimPV["rapidity"]->Fill(m.pseudoRapidity());
01795               if( (m.perp()>0.8) &&  isCharged( *daughter ) ){
01796                 hsimPV["chRapidity"]->Fill(m.pseudoRapidity());
01797               }
01798               hsimPV["pt"]->Fill(m.perp());
01799             }//new final state particle for this vertex
01800           }//daughter is a final state particle
01801         }
01802 
01803 
01804         //idx++;
01805       }
01806   }
01807   if(verbose_){
01808     cout << "------- PrimaryVertexAnalyzer4PU simPVs -------" <<  endl;
01809     for(std::vector<simPrimaryVertex>::iterator v0=simpv.begin();
01810         v0!=simpv.end(); v0++){
01811       cout << "z=" << v0->z 
01812            << "  px=" << v0->ptot.px()
01813            << "  py=" << v0->ptot.py()
01814            << "  pz=" << v0->ptot.pz() 
01815            << "  pt2="<< v0->ptsq 
01816            << endl;
01817     }
01818     cout << "-----------------------------------------------" << endl;
01819   }
01820   return simpv;
01821 }
01822 
01823 
01824 
01825 
01826 
01827 
01828 
01829 
01830 /* get sim pv from TrackingParticles/TrackingVertex */
01831 std::vector<PrimaryVertexAnalyzer4PU::simPrimaryVertex> PrimaryVertexAnalyzer4PU::getSimPVs(
01832                                                                                           const edm::Handle<TrackingVertexCollection> tVC
01833                                                                                           )
01834 {
01835   std::vector<PrimaryVertexAnalyzer4PU::simPrimaryVertex> simpv;
01836   //std::cout <<"number of vertices " << tVC->size() << std::endl;
01837 
01838   if(DEBUG_){std::cout << "getSimPVs TrackingVertexCollection " << std::endl;}
01839 
01840   for (TrackingVertexCollection::const_iterator v = tVC -> begin(); v != tVC -> end(); ++v) {
01841 
01842     if(DEBUG_){
01843       std::cout << (v->eventId()).event() << v -> position() << v->g4Vertices().size() <<" "  <<v->genVertices().size() <<  "   t=" <<v->position().t()*1.e12 <<"    ==0:" <<(v->position().t()>0) << std::endl;
01844       for( TrackingVertex::g4v_iterator gv=v->g4Vertices_begin(); gv!=v->g4Vertices_end(); gv++){
01845         std::cout << *gv << std::endl;
01846       }
01847       std::cout << "----------" << std::endl;
01848     }
01849  
01850     //    bool hasMotherVertex=false;
01851     if ((unsigned int) v->eventId().event()<simpv.size()) continue;
01852         //if (v->position().t()>0) { continue;} // skip secondary vertices (obsolete + doesn't work)
01853     if (fabs(v->position().z())>1000) continue;  // skip funny junk vertices
01854     
01855     // could be a new vertex, check  all primaries found so far to avoid multiple entries
01856     const double mm=1.0; // for tracking vertices
01857     simPrimaryVertex sv(v->position().x()*mm,v->position().y()*mm,v->position().z()*mm);
01858 
01859     //cout << "sv: " << (v->eventId()).event() << endl;
01860     sv.eventId=v->eventId();
01861 
01862     for (TrackingParticleRefVector::iterator iTrack = v->daughterTracks_begin(); iTrack != v->daughterTracks_end(); ++iTrack){
01863       //cout <<((**iTrack).eventId()).event() << " ";  // an iterator of Refs, dereference twice. Cool eyh?
01864       sv.eventId=(**iTrack).eventId();
01865     }
01866     //cout <<endl;
01867     simPrimaryVertex *vp=NULL;  // will become non-NULL if a vertex is found and then point to it
01868     for(std::vector<simPrimaryVertex>::iterator v0=simpv.begin();
01869         v0!=simpv.end(); v0++){
01870       if( (sv.eventId==v0->eventId) && (fabs(sv.x-v0->x)<1e-5) && (fabs(sv.y-v0->y)<1e-5) && (fabs(sv.z-v0->z)<1e-5)){
01871         vp=&(*v0);
01872         break;
01873       }
01874     }
01875     if(!vp){
01876       // this is a new vertex
01877       if(DEBUG_){std::cout << "this is a new vertex " << sv.eventId.event() << "   "  << sv.x << " " << sv.y << " " << sv.z <<std::endl;}
01878       simpv.push_back(sv);
01879       vp=&simpv.back();
01880     }else{
01881       if(DEBUG_){std::cout << "this is not a new vertex"  << sv.x << " " << sv.y << " " << sv.z <<std::endl;}
01882     }
01883 
01884 
01885     // Loop over daughter track(s)
01886     if(DEBUG_){
01887       for (TrackingVertex::tp_iterator iTP = v -> daughterTracks_begin(); iTP != v -> daughterTracks_end(); ++iTP) {
01888         std::cout << "  Daughter momentum:      " << (*(*iTP)).momentum();
01889         std::cout << "  Daughter type     " << (*(*iTP)).pdgId();
01890         std::cout << std::endl;
01891       }
01892     }
01893   }
01894   if(DEBUG_){  
01895     cout << "------- PrimaryVertexAnalyzer4PU simPVs from TrackingVertices -------" <<  endl; 
01896     for(std::vector<simPrimaryVertex>::iterator v0=simpv.begin();
01897         v0!=simpv.end(); v0++){
01898       cout << "z=" << v0->z << "  event=" << v0->eventId.event() << endl;
01899     }
01900     cout << "-----------------------------------------------" << endl;
01901   }
01902   return simpv;
01903 }
01904 
01905 
01906 
01907 
01908 
01909 
01910 // ------------ method called to produce the data  ------------
01911 void
01912 PrimaryVertexAnalyzer4PU::analyze(const Event& iEvent, const EventSetup& iSetup)
01913 {
01914   
01915   std::vector<simPrimaryVertex> simpv;  //  a list of primary MC vertices
01916   std::vector<SimPart> tsim;
01917   std::string mcproduct="generator";  // starting with 3_1_0 pre something
01918 
01919   eventcounter_++;
01920   run_             = iEvent.id().run();
01921   luminosityBlock_ = iEvent.luminosityBlock();
01922   event_           = iEvent.id().event();
01923   bunchCrossing_   = iEvent.bunchCrossing();
01924   orbitNumber_     = iEvent.orbitNumber();
01925 
01926   dumpThisEvent_ = false;
01927 
01928 
01929 
01930   if(verbose_){
01931     std::cout << endl 
01932               << "PrimaryVertexAnalyzer4PU::analyze   event counter=" << eventcounter_
01933               << " Run=" << run_ << "  LumiBlock " << luminosityBlock_ << "  event  " << event_
01934               << " bx=" << bunchCrossing_ <<  " orbit=" << orbitNumber_ 
01935       //<< " selected = " << good
01936               << std::endl;
01937   }
01938 
01939 
01940    try{
01941     iSetup.getData(pdt_);
01942   }catch(const Exception&){
01943     std::cout << "Some problem occurred with the particle data table. This may not work !" <<std::endl;
01944   }
01945 
01946   Handle<reco::VertexCollection> recVtxs;
01947   bool bnoBS=iEvent.getByLabel("offlinePrimaryVertices", recVtxs);
01948   
01949   Handle<reco::VertexCollection> recVtxsBS;
01950   bool bBS=iEvent.getByLabel("offlinePrimaryVerticesWithBS", recVtxsBS);
01951   
01952   Handle<reco::VertexCollection> recVtxsDA;
01953   bool bDA=iEvent.getByLabel("offlinePrimaryVerticesDA", recVtxsDA);
01954 
01955 //   Handle<reco::VertexCollection> recVtxsPIX;
01956 //   bool bPIX=iEvent.getByLabel("pixelVertices", recVtxsPIX);
01957 //   bPIX=false;
01958 
01959 //   Handle<reco::VertexCollection> recVtxsMVF;
01960 //   bool bMVF=iEvent.getByLabel("offlinePrimaryVerticesMVF", recVtxsMVF);
01961 
01962   Handle<reco::TrackCollection> recTrks;
01963   iEvent.getByLabel(recoTrackProducer_, recTrks);
01964 
01965 
01966   int nhighpurity=0, ntot=0;
01967   for(reco::TrackCollection::const_iterator t=recTrks->begin(); t!=recTrks->end(); ++t){  
01968     ntot++;
01969     if(t->quality(reco::TrackBase::highPurity)) nhighpurity++;
01970   } 
01971   if(ntot>10)  hnoBS["highpurityTrackFraction"]->Fill(float(nhighpurity)/float(ntot));
01972   if((recoTrackProducer_=="generalTracks")&&(nhighpurity<0.25*ntot)){
01973     if(verbose_){ cout << "rejected, " << nhighpurity << " highpurity  out of  " << ntot << "  total tracks "<< endl<< endl;}
01974     return;
01975   }
01976 
01977 
01978 
01979   
01980 
01981   if(iEvent.getByType(recoBeamSpotHandle_)){
01982     vertexBeamSpot_= *recoBeamSpotHandle_;
01983     wxy2_=pow(vertexBeamSpot_.BeamWidthX(),2)+pow(vertexBeamSpot_.BeamWidthY(),2);
01984     Fill(hsimPV, "xbeam",vertexBeamSpot_.x0()); Fill(hsimPV, "wxbeam",vertexBeamSpot_.BeamWidthX());
01985     Fill(hsimPV, "ybeam",vertexBeamSpot_.y0()); Fill(hsimPV, "wybeam",vertexBeamSpot_.BeamWidthY());
01986     Fill(hsimPV, "zbeam",vertexBeamSpot_.z0());// Fill("wzbeam",vertexBeamSpot_.BeamWidthZ());
01987   }else{
01988     cout << " beamspot not found, using dummy " << endl;
01989     vertexBeamSpot_=reco::BeamSpot();// dummy
01990   }
01991 
01992 
01993   if(bnoBS){
01994     if((recVtxs->begin()->isValid())&&(recVtxs->begin()->ndof()>1)&&(recVtxs->begin()->ndof()>(0.0*recVtxs->begin()->tracksSize()))){  // was 5 and 0.2
01995       Fill(hnoBS,"xrecBeamvsdxXBS",recVtxs->begin()->xError(),recVtxs->begin()->x()-vertexBeamSpot_.x0());
01996       Fill(hnoBS,"yrecBeamvsdyXBS",recVtxs->begin()->yError(),recVtxs->begin()->y()-vertexBeamSpot_.y0());
01997 
01998       if(printXBS_) {
01999         cout << Form("XBS %10d %5d %10d  %4d   %lu %5.2f    %8f %8f       %8f %8f      %8f %8f",
02000                       run_,luminosityBlock_,event_,bunchCrossing_,
02001                       (unsigned long)(recVtxs->begin()->tracksSize()), recVtxs->begin()->ndof(),
02002                       recVtxs->begin()->x(),               recVtxs->begin()->xError(), 
02003                       recVtxs->begin()->y(),               recVtxs->begin()->yError(), 
02004                       recVtxs->begin()->z(),               recVtxs->begin()->zError()
02005                      ) << endl; 
02006       }
02007 
02008     }
02009   }
02010 
02011  
02012   // for the associator
02013   Handle<View<Track> > trackCollectionH;
02014   iEvent.getByLabel(recoTrackProducer_,trackCollectionH);
02015 
02016   Handle<HepMCProduct> evtMC;
02017 
02018   Handle<SimVertexContainer> simVtxs;
02019   iEvent.getByLabel( simG4_, simVtxs);
02020   
02021   Handle<SimTrackContainer> simTrks;
02022   iEvent.getByLabel( simG4_, simTrks);
02023 
02024 
02025 
02026 
02027 
02028   edm::Handle<TrackingParticleCollection>  TPCollectionH ;
02029   edm::Handle<TrackingVertexCollection>    TVCollectionH ;
02030   bool gotTP=iEvent.getByLabel("mergedtruth","MergedTrackTruth",TPCollectionH);
02031   bool gotTV=iEvent.getByLabel("mergedtruth","MergedTrackTruth",TVCollectionH);
02032 
02033 
02034   iSetup.get<TransientTrackRecord>().get("TransientTrackBuilder",theB_);
02035   fBfield_=((*theB_).field()->inTesla(GlobalPoint(0.,0.,0.))).z();
02036 
02037  
02038   vector<SimEvent> simEvt;
02039   if (gotTP && gotTV ){
02040 
02041     edm::ESHandle<TrackAssociatorBase> theHitsAssociator;
02042     iSetup.get<TrackAssociatorRecord>().get("TrackAssociatorByHits",theHitsAssociator);
02043     associatorByHits_ = (TrackAssociatorBase *) theHitsAssociator.product();
02044     r2s_ =   associatorByHits_->associateRecoToSim (trackCollectionH,TPCollectionH, &iEvent ); 
02045     //simEvt=getSimEvents(iEvent, TPCollectionH, TVCollectionH, trackCollectionH);
02046     simEvt=getSimEvents(TPCollectionH, TVCollectionH, trackCollectionH);
02047 
02048     if (simEvt.size()==0){
02049       cout << " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
02050       cout << " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
02051       cout << " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
02052       cout << " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
02053       cout << " !!!!!!!!!!!!!!!!!!!!!!   got TrackingParticles but no simEvt   !!!!!!!!!!!!!!!!!" << endl;
02054       cout << " dumping Tracking particles " << endl;
02055       const TrackingParticleCollection* simTracks = TPCollectionH.product();
02056       for(TrackingParticleCollection::const_iterator it=simTracks->begin(); it!=simTracks->end(); it++){
02057         cout << *it << endl;
02058       }
02059       cout << " dumping Tracking Vertices " << endl;
02060       const TrackingVertexCollection* tpVtxs = TVCollectionH.product();
02061       for(TrackingVertexCollection::const_iterator iv=tpVtxs->begin(); iv!=tpVtxs->end(); iv++){
02062         cout << *iv << endl;
02063       }
02064       if(iEvent.getByLabel(mcproduct,evtMC)){
02065         cout << "dumping simTracks" << endl;
02066         for(SimTrackContainer::const_iterator t=simTrks->begin();  t!=simTrks->end(); ++t){
02067           cout << *t << endl;
02068         }
02069         cout << "dumping simVertexes" << endl;
02070         for(SimVertexContainer::const_iterator vv=simVtxs->begin();  
02071             vv!=simVtxs->end(); 
02072             ++vv){
02073           cout << *vv << endl;
02074         }
02075       }else{
02076         cout << "no hepMC" << endl;
02077       }
02078       cout << " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
02079 
02080       const HepMC::GenEvent* evt=evtMC->GetEvent();
02081       if(evt){
02082         std::cout << "process id " <<evt->signal_process_id()<<std::endl;
02083         std::cout <<"signal process vertex "<< ( evt->signal_process_vertex() ?
02084                                                  evt->signal_process_vertex()->barcode() : 0 )   <<std::endl;
02085         std::cout <<"number of vertices " << evt->vertices_size() << std::endl;
02086         evt->print();
02087       }else{
02088         cout << "no event in HepMC" << endl;
02089       }
02090       cout << " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
02091 
02092     }
02093   }
02094 
02095 
02096   
02097 
02098   if(gotTV){
02099 
02100     if(verbose_){
02101       cout << "Found Tracking Vertices " << endl;
02102     }
02103     simpv=getSimPVs(TVCollectionH);
02104     
02105 
02106   }else if(iEvent.getByLabel(mcproduct,evtMC)){
02107 
02108     simpv=getSimPVs(evtMC);
02109 
02110     if(verbose_){
02111       cout << "Using HepMCProduct " << endl;
02112       std::cout << "simtrks " << simTrks->size() << std::endl;
02113     }
02114     tsim = PrimaryVertexAnalyzer4PU::getSimTrkParameters(simTrks, simVtxs, simUnit_);
02115     
02116   }else{
02117     // if(verbose_({cout << "No MC info at all" << endl;}
02118   }
02119 
02120 
02121 
02122 
02123   // get the beam spot from the appropriate dummy vertex, if available
02124   for(reco::VertexCollection::const_iterator v=recVtxs->begin(); 
02125       v!=recVtxs->end(); ++v){
02126     if ((v->ndof()==-3) && (v->chi2()==0) ){ 
02127       myBeamSpot=math::XYZPoint(v->x(), v->y(), v->z());
02128     }
02129   }
02130 
02131   
02132 
02133 
02134   hsimPV["nsimvtx"]->Fill(simpv.size());
02135   for(std::vector<simPrimaryVertex>::iterator vsim=simpv.begin();
02136        vsim!=simpv.end(); vsim++){
02137     if(doMatching_){  
02138       matchRecTracksToVertex(*vsim, tsim, recTrks); // hepmc, based on track parameters
02139      }
02140 
02141      hsimPV["nbsimtksinvtx"]->Fill(vsim->nGenTrk);
02142      hsimPV["xsim"]->Fill(vsim->x*simUnit_);
02143      hsimPV["ysim"]->Fill(vsim->y*simUnit_);
02144      hsimPV["zsim"]->Fill(vsim->z*simUnit_);
02145      hsimPV["xsim1"]->Fill(vsim->x*simUnit_);
02146      hsimPV["ysim1"]->Fill(vsim->y*simUnit_);
02147      hsimPV["zsim1"]->Fill(vsim->z*simUnit_);
02148      Fill(hsimPV,"xsim2",vsim->x*simUnit_,vsim==simpv.begin());
02149      Fill(hsimPV,"ysim2",vsim->y*simUnit_,vsim==simpv.begin());
02150      Fill(hsimPV,"zsim2",vsim->z*simUnit_,vsim==simpv.begin());
02151      hsimPV["xsim2"]->Fill(vsim->x*simUnit_);
02152      hsimPV["ysim2"]->Fill(vsim->y*simUnit_);
02153      hsimPV["zsim2"]->Fill(vsim->z*simUnit_);
02154      hsimPV["xsim3"]->Fill(vsim->x*simUnit_);
02155      hsimPV["ysim3"]->Fill(vsim->y*simUnit_);
02156      hsimPV["zsim3"]->Fill(vsim->z*simUnit_);
02157      hsimPV["xsimb"]->Fill(vsim->x*simUnit_-vertexBeamSpot_.x0());
02158      hsimPV["ysimb"]->Fill(vsim->y*simUnit_-vertexBeamSpot_.y0());
02159      hsimPV["zsimb"]->Fill(vsim->z*simUnit_-vertexBeamSpot_.z0());
02160      hsimPV["xsimb1"]->Fill(vsim->x*simUnit_-vertexBeamSpot_.x0());
02161      hsimPV["ysimb1"]->Fill(vsim->y*simUnit_-vertexBeamSpot_.y0());
02162      hsimPV["zsimb1"]->Fill(vsim->z*simUnit_-vertexBeamSpot_.z0());
02163   }
02164 
02165 
02166 
02167 
02168    
02169    if(bnoBS){
02170      analyzeVertexCollection(hnoBS, recVtxs, recTrks, simpv,"noBS");
02171      analyzeVertexCollectionTP(hnoBS, recVtxs, recTrks, simEvt,"noBS");
02172    }
02173    if(bBS){
02174      analyzeVertexCollection(hBS, recVtxsBS, recTrks, simpv,"BS");
02175      analyzeVertexCollectionTP(hBS, recVtxsBS, recTrks, simEvt,"BS");
02176    }
02177    if(bDA){
02178      analyzeVertexCollection(hDA, recVtxsDA, recTrks, simpv,"DA");
02179      analyzeVertexCollectionTP(hDA, recVtxsDA, recTrks, simEvt,"DA");
02180    }
02181 //    if(bPIX){
02182 //      analyzeVertexCollection(hPIX, recVtxsPIX, recTrks, simpv,"PIX");
02183 //      analyzeVertexCollectionTP(hPIX, recVtxsPIX, recTrks, simEvt,"PIX");
02184 //    }
02185 
02186 
02187 
02188    if((dumpThisEvent_&& (dumpcounter_<100)) ||(verbose_ && (eventcounter_<ndump_))){
02189      cout << endl << "Event dump" << endl
02190           << "event counter=" << eventcounter_
02191           << " Run=" << run_ << "  LumiBlock " << luminosityBlock_ << "  event  " << event_
02192           << " bx=" << bunchCrossing_ <<  " orbit=" << orbitNumber_ 
02193           << std::endl;
02194      dumpcounter_++;
02195 
02196      //evtMC->GetEvent()->print();
02197      //printRecTrks(recTrks);  // very verbose !!
02198      
02199 //      if (bPIX) printRecVtxs(recVtxsPIX,"pixel vertices");
02200      if (bnoBS) {printRecVtxs(recVtxs,"Offline without Beamspot");}
02201      if (bnoBS && (!bDA)){ printPVTrks(recTrks, recVtxs, tsim, simEvt, false);}
02202      if (bBS) printRecVtxs(recVtxsBS,"Offline with Beamspot");
02203      if (bDA) {
02204        printRecVtxs(recVtxsDA,"Offline DA");
02205        printPVTrks(recTrks, recVtxsDA, tsim, simEvt, false);
02206      }
02207      if (dumpcounter_<2){cout << "beamspot " << vertexBeamSpot_ << endl;}
02208    }
02209 
02210   if(verbose_){
02211     std::cout << std::endl;
02212   }
02213 }
02214 
02215 namespace {
02216 bool lt(const std::pair<double,unsigned int>& a,const std::pair<double,unsigned int>& b ){
02217   return a.first<b.first;
02218 }
02219 }
02220 
02221 /***************************************************************************************/
02222 void PrimaryVertexAnalyzer4PU::printEventSummary(std::map<std::string, TH1*> & h,
02223                                                  const edm::Handle<reco::VertexCollection> recVtxs,
02224                                                  const edm::Handle<reco::TrackCollection> recTrks, 
02225                                                  vector<SimEvent> & simEvt,
02226                                                  const string message){
02227   // make a readable summary of the vertex finding if the TrackingParticles are availabe
02228   if (simEvt.size()==0){return;}
02229 
02230 
02231   // sort vertices in z ... for nicer printout
02232 
02233   vector< pair<double,unsigned int> >  zrecv;
02234   for(unsigned int idx=0; idx<recVtxs->size(); idx++){
02235     if ( (recVtxs->at(idx).ndof()<0) || (recVtxs->at(idx).chi2()<=0) ) continue;  // skip clusters 
02236     zrecv.push_back( make_pair(recVtxs->at(idx).z(),idx) );
02237   }
02238   stable_sort(zrecv.begin(),zrecv.end(),lt);
02239 
02240   // same for simulated vertices
02241   vector< pair<double,unsigned int> >  zsimv;
02242   for(unsigned int idx=0; idx<simEvt.size(); idx++){
02243     zsimv.push_back(make_pair(simEvt[idx].z, idx));
02244   }
02245   stable_sort(zsimv.begin(), zsimv.end(),lt);
02246 
02247 
02248 
02249 
02250   cout << "---------------------------" << endl;
02251   cout << "event counter = " << eventcounter_ << "   " << message << endl;
02252   cout << "---------------------------" << endl;
02253   cout << " z[cm]       rec -->    ";
02254   cout.precision(4);
02255   for(vector< pair<double,unsigned int> >::iterator itrec=zrecv.begin(); itrec!=zrecv.end(); itrec++){
02256     cout << setw(7) << fixed << itrec->first;
02257     if (itrec->second==0){cout << "*" ;}else{cout << " " ;}
02258   }
02259   cout << endl;
02260   cout << "                        ";
02261   for(vector< pair<double,unsigned int> >::iterator itrec=zrecv.begin(); itrec!=zrecv.end(); itrec++){
02262     cout << setw(7) << fixed << recVtxs->at(itrec->second).tracksSize();
02263     if (itrec->second==0){cout << "*" ;}else{cout << " " ;}
02264   }
02265   cout << "   rec tracks" << endl;
02266   cout << "                        ";
02267   map<unsigned int, int> truthMatchedVertexTracks;
02268   for(vector< pair<double,unsigned int> >::iterator itrec=zrecv.begin(); itrec!=zrecv.end(); itrec++){
02269     truthMatchedVertexTracks[itrec->second]=getTruthMatchedVertexTracks(recVtxs->at(itrec->second)).size();
02270     cout << setw(7) << fixed << truthMatchedVertexTracks[itrec->second];
02271     if (itrec->second==0){cout << "*" ;}else{cout << " " ;}
02272   }
02273   cout << "   truth matched " << endl;
02274 
02275   cout << "sim ------- trk  prim ----" << endl;
02276 
02277 
02278 
02279   map<unsigned int, unsigned int> rvmatch; // reco vertex matched to sim vertex  (sim to rec)
02280   map<unsigned int, double > nmatch;  // highest number of truth-matched tracks of ev found in a recvtx
02281   map<unsigned int, double > purity;  // highest purity of a rec vtx (i.e. highest number of tracks from the same simvtx)
02282   map<unsigned int, double > wpurity;  // same for the sum of weights
02283 
02284   for(vector< pair<double,unsigned int> >::iterator itrec=zrecv.begin(); itrec!=zrecv.end(); itrec++){
02285     purity[itrec->second]=0.;
02286     wpurity[itrec->second]=0.;
02287   }
02288 
02289   for(vector< pair<double,unsigned int> >::iterator itsim=zsimv.begin(); itsim!=zsimv.end(); itsim++){
02290     SimEvent* ev =&(simEvt[itsim->second]);
02291 
02292 
02293     cout.precision(4);
02294     if (itsim->second==0){
02295       cout << setw(8) << fixed << ev->z << ")*" << setw(5) << ev->tk.size() << setw(5) << ev->tkprim.size() << "  | ";
02296     }else{
02297       cout << setw(8) << fixed << ev->z << ") " << setw(5) << ev->tk.size() << setw(5) << ev->tkprim.size() << "  | ";
02298     }
02299 
02300     nmatch[itsim->second]=0;  // highest number of truth-matched tracks of ev found in a recvtx
02301     double matchpurity=0,matchwpurity=0;
02302 
02303     for(vector< pair<double,unsigned int> >::iterator itrec=zrecv.begin(); itrec!=zrecv.end(); itrec++){
02304       const reco::Vertex *v = &(recVtxs->at(itrec->second));
02305 
02306       // count tracks found in both, sim and rec
02307       double n=0,wt=0;
02308       for(vector<TransientTrack>::iterator te=ev->tk.begin(); te!=ev->tk.end(); te++){
02309         const reco::Track&  RTe=te->track();
02310          for(trackit_t tv=v->tracks_begin(); tv!=v->tracks_end(); tv++){
02311            const reco::Track & RTv=*(tv->get());  
02312            if(RTe.vz()==RTv.vz()) {n++; wt+=v->trackWeight(*tv);}
02313         }
02314       }
02315       cout << setw(7) << int(n)<< " ";
02316 
02317       if (n > nmatch[itsim->second]){
02318         nmatch[itsim->second]=n;
02319         rvmatch[itsim->second]=itrec->second;
02320         matchpurity=n/truthMatchedVertexTracks[itrec->second];
02321         matchwpurity=wt/truthMatchedVertexTracks[itrec->second];
02322       }
02323 
02324       if(n > purity[itrec->second]){
02325         purity[itrec->second]=n;
02326       }
02327 
02328       if(wt > wpurity[itrec->second]){
02329         wpurity[itrec->second]=wt;
02330       }
02331 
02332     }// end of reco vertex loop
02333 
02334     cout << "  | ";
02335     if  (nmatch[itsim->second]>0 ){
02336       if(matchpurity>0.5){
02337         cout << "found  ";
02338       }else{
02339         cout << "merged ";
02340       } 
02341       cout << "  max eff. = "  << setw(8) << nmatch[itsim->second]/ev->tk.size() << " p=" << matchpurity << " w=" << matchwpurity <<  endl;
02342     }else{
02343       if(ev->tk.size()==0){
02344         cout  << " invisible" << endl;
02345       }else if (ev->tk.size()==1){
02346         cout << "single track " << endl;
02347       }else{
02348         cout << "lost " << endl;
02349       }
02350     }
02351   }
02352   cout << "---------------------------" << endl;
02353 
02354   //  the purity of the reconstructed vertex
02355   cout << "               purity   ";
02356   for(vector< pair<double,unsigned int> >::iterator itrec=zrecv.begin(); itrec!=zrecv.end(); itrec++){
02357     cout << setw(7) << fixed << purity[itrec->second]/truthMatchedVertexTracks[itrec->second];
02358     if (itrec->second==0){cout << "*" ;}else{cout << " " ;}
02359   }
02360   cout << endl;
02361 
02362 //   //  classification of reconstructed vertex fake/real
02363 //   cout << "                        ";
02364 //   for(vector< pair<double,unsigned int> >::iterator itrec=zrecv.begin(); itrec!=zrecv.end(); itrec++){
02365 //     cout << setw(7) << fixed << purity[itrec->second]/truthMatchedVertexTracks[itrec->second];
02366 //     if (itrec->second==0){cout << "*" ;}else{cout << " " ;}
02367 //   }
02368 //   cout << endl;
02369   cout << "---------------------------" << endl;
02370 
02371 
02372 
02373 
02374   // list problematic tracks
02375   for(vector< pair<double,unsigned int> >::iterator itsim=zsimv.begin(); itsim!=zsimv.end(); itsim++){
02376     SimEvent* ev =&(simEvt[itsim->second]);
02377 
02378     for(vector<TransientTrack>::iterator te=ev->tk.begin(); te!=ev->tk.end(); te++){
02379       const reco::Track&  RTe=te->track();
02380       
02381       int ivassign=-1;  // will become the index of the vertex to which a track was assigned
02382       
02383       for(vector< pair<double,unsigned int> >::iterator itrec=zrecv.begin(); itrec!=zrecv.end(); itrec++){
02384         const reco::Vertex *v = &(recVtxs->at(itrec->second));
02385 
02386         for(trackit_t tv=v->tracks_begin(); tv!=v->tracks_end(); tv++){
02387           const reco::Track & RTv=*(tv->get());  
02388           if(RTe.vz()==RTv.vz()) {ivassign=itrec->second;}
02389         }
02390       }
02391       double tantheta=tan((te->stateAtBeamLine().trackStateAtPCA()).momentum().theta());
02392       reco::BeamSpot beamspot=(te->stateAtBeamLine()).beamSpot();
02393       //double z=(te->stateAtBeamLine().trackStateAtPCA()).position().z();
02394       double dz2= pow(RTe.dzError(),2)+pow(beamspot.BeamWidthX()/tantheta,2);
02395       
02396       if(ivassign==(int)rvmatch[itsim->second]){
02397         Fill(h,"correctlyassigned",RTe.eta(),RTe.pt());
02398         Fill(h,"ptcat",RTe.pt());
02399         Fill(h,"etacat",RTe.eta());
02400         Fill(h,"phicat",RTe.phi());
02401         Fill(h,"dzcat",sqrt(dz2));
02402       }else{
02403         Fill(h,"misassigned",RTe.eta(),RTe.pt());
02404         Fill(h,"ptmis",RTe.pt());
02405         Fill(h,"etamis",RTe.eta());
02406         Fill(h,"phimis",RTe.phi());
02407         Fill(h,"dzmis",sqrt(dz2));
02408         cout << "vertex " << setw(8) << fixed << ev->z;
02409 
02410         if (ivassign<0){
02411           cout << " track lost                ";
02412           // for some clusterizers there shouldn't be any lost tracks,
02413           // are there differences in the track selection?
02414         }else{
02415           cout << " track misassigned " << setw(8) << fixed << recVtxs->at(ivassign).z();
02416         }
02417 
02418         cout << "  track z=" << setw(8) << fixed  << RTe.vz() << "+/-" << RTe.dzError() << "  pt=" <<  setw(8) << fixed<< RTe.pt() << "  eta=" << setw(8) << fixed << RTe.eta()<< " sel=" <<theTrackFilter(*te);
02419 
02420         //
02421         //cout << " ztrack=" << te->track().vz();
02422         TrackingParticleRef tpr = z2tp_[te->track().vz()];
02423         double zparent=tpr->parentVertex().get()->position().z();
02424         if(zparent==ev->z) {
02425           cout << " prim";
02426         }else{
02427           cout << " sec ";
02428         }
02429         cout << "  id=" << tpr->pdgId();
02430         cout << endl;
02431 
02432         //
02433       }
02434     }// next simvertex-track
02435 
02436   }//next simvertex
02437 
02438   cout << "---------------------------" << endl;
02439 
02440 }
02441 /***************************************************************************************/
02442 
02443 
02444 
02445 
02446 /***************************************************************************************/
02447 void PrimaryVertexAnalyzer4PU::analyzeVertexCollectionTP(std::map<std::string, TH1*> & h,
02448                                const edm::Handle<reco::VertexCollection> recVtxs,
02449                                const edm::Handle<reco::TrackCollection> recTrks, 
02450                                                         vector<SimEvent> & simEvt,
02451                                                         const string message){
02452   
02453   //  cout <<"PrimaryVertexAnalyzer4PU::analyzeVertexCollectionTP size=" << simEvt.size() << endl;
02454   if(simEvt.size()==0)return;
02455 
02456   printEventSummary(h, recVtxs,recTrks,simEvt,message);
02457 
02458   //const int iSignal=0;  
02459   EncodedEventId iSignal=simEvt[0].eventId;
02460   Fill(h,"npu0",simEvt.size());
02461 
02462 
02463   for(vector<SimEvent>::iterator ev=simEvt.begin(); ev!=simEvt.end(); ev++){
02464     Fill(h,"Tc",    ev->Tc,    ev==simEvt.begin());
02465     Fill(h,"Chisq", ev->chisq, ev==simEvt.begin());
02466     if(ev->chisq>0)Fill(h,"logChisq", log(ev->chisq), ev==simEvt.begin());
02467     Fill(h,"dzmax", ev->dzmax, ev==simEvt.begin());
02468     Fill(h,"dztrim",ev->dztrim,ev==simEvt.begin());
02469     Fill(h,"m4m2",  ev->m4m2,  ev==simEvt.begin());
02470     if(ev->Tc>0){  Fill(h,"logTc",log(ev->Tc)/log(10.),ev==simEvt.begin());}
02471     
02472 
02473     for(vector<SimEvent>::iterator ev2=ev+1; ev2!=simEvt.end(); ev2++){
02474       vector<TransientTrack> xt;
02475       if((ev->tkprimsel.size()>0)&&(ev2->tkprimsel.size()>0)&&(ev->tkprimsel.size()+ev2->tkprimsel.size())>1){
02476         xt.insert (xt.end() ,ev->tkprimsel.begin(),ev->tkprimsel.end());
02477         xt.insert (xt.end() ,ev2->tkprimsel.begin(),ev2->tkprimsel.end());
02478         double xTc,xChsq,xDzmax,xDztrim,xm4m2;
02479         getTc(xt, xTc, xChsq, xDzmax, xDztrim,xm4m2);
02480         if(xTc>0){
02481           Fill(h,"xTc",xTc,ev==simEvt.begin());
02482           Fill(h,"logxTc",   log(xTc)/log(10),ev==simEvt.begin());
02483           Fill(h,"xChisq",   xChsq,ev==simEvt.begin());
02484           if(xChsq>0){Fill(h,"logxChisq",   log(xChsq),ev==simEvt.begin());};
02485           Fill(h,"xdzmax",   xDzmax,ev==simEvt.begin());
02486           Fill(h,"xdztrim",  xDztrim,ev==simEvt.begin());
02487           Fill(h,"xm4m2",    xm4m2,ev==simEvt.begin());
02488           
02489         }
02490       }
02491     }
02492   }
02493   
02494   // --------------------------------------- count actual rec vtxs ----------------------
02495   int nrecvtxs=0;//, nrecvtxs1=0, nrecvtxs2=0;
02496   for(reco::VertexCollection::const_iterator v=recVtxs->begin(); 
02497       v!=recVtxs->end(); ++v){
02498     if ( (v->isFake()) || (v->ndof()<0) || (v->chi2()<=0) ) continue;  // skip clusters 
02499     nrecvtxs++;
02500   }
02501 
02502   // --------------------------------------- fill the track assignment matrix ----------------------
02503   for(vector<SimEvent>::iterator ev=simEvt.begin(); ev!=simEvt.end(); ev++){
02504     ev->ntInRecVz.clear();  // just in case
02505     ev->zmatch=-99.;
02506     ev->nmatch=0;
02507     for(reco::VertexCollection::const_iterator v=recVtxs->begin(); 
02508         v!=recVtxs->end(); ++v){
02509       double n=0, wt=0;
02510       for(vector<TransientTrack>::iterator te=ev->tk.begin(); te!=ev->tk.end(); te++){
02511         const reco::Track&  RTe=te->track();
02512         for(trackit_t tv=v->tracks_begin(); tv!=v->tracks_end(); tv++){
02513           const reco::Track & RTv=*(tv->get());  
02514           if(RTe.vz()==RTv.vz()) {n++; wt+=v->trackWeight(*tv);}
02515         }
02516       }
02517       ev->ntInRecVz[v->z()]=n;
02518       if (n > ev->nmatch){ ev->nmatch=n; ev->zmatch=v->z(); ev->zmatch=v->z(); }
02519     }
02520   }
02521   
02522     // call a vertex a fake if for every sim vertex there is another recvertex containing more tracks
02523     // from that sim vertex than the current recvertex
02524   double nfake=0;
02525   for(reco::VertexCollection::const_iterator v=recVtxs->begin(); 
02526       v!=recVtxs->end(); ++v){
02527     bool matched=false;
02528     for(vector<SimEvent>::iterator ev=simEvt.begin(); ev!=simEvt.end(); ev++){
02529       if ((ev->nmatch>0)&&(ev->zmatch==v->z())){
02530         matched=true;
02531       }
02532     }
02533     if(!matched && !v->isFake()) {
02534       nfake++;
02535       cout << " fake rec vertex at z=" << v->z() << endl;
02536       // some histograms of fake vertex properties here
02537       Fill(h,"unmatchedVtxZ",v->z());
02538       Fill(h,"unmatchedVtxNdof",v->ndof());
02539     }
02540   }
02541   if(nrecvtxs>0){
02542     Fill(h,"unmatchedVtx",nfake);
02543     Fill(h,"unmatchedVtxFrac",nfake/nrecvtxs);
02544   }
02545 
02546   // --------------------------------------- match rec to sim ---------------------------------------
02547   for(reco::VertexCollection::const_iterator v=recVtxs->begin(); 
02548       v!=recVtxs->end(); ++v){
02549 
02550     if ( (v->ndof()<0) || (v->chi2()<=0) ) continue;  // skip clusters 
02551     double  nmatch=-1;      // highest number of tracks in recvtx v found in any event
02552     EncodedEventId evmatch;
02553     bool matchFound=false;
02554     double nmatchvtx=0;     // number of simvtcs contributing to recvtx v
02555 
02556     for(vector<SimEvent>::iterator ev=simEvt.begin(); ev!=simEvt.end(); ev++){
02557 
02558       double n=0;  // number of tracks that are in both, the recvtx v and the event ev
02559       for(vector<TransientTrack>::iterator te=ev->tk.begin(); te!=ev->tk.end(); te++){
02560 
02561         const reco::Track&  RTe=te->track();
02562          for(trackit_t tv=v->tracks_begin(); tv!=v->tracks_end(); tv++){
02563            const reco::Track & RTv=*(tv->get());  
02564            if(RTe.vz()==RTv.vz()){ n++;}
02565         }
02566       }     
02567 
02568       // find the best match in terms of the highest number of tracks 
02569       // from a simvertex in this rec vertex
02570       if (n > nmatch){
02571         nmatch=n;
02572         evmatch=ev->eventId;
02573         matchFound=true;
02574       }
02575       if(n>0){
02576         nmatchvtx++;
02577       }
02578     }
02579 
02580     double nmatchany=getTruthMatchedVertexTracks(*v).size();  
02581     if (matchFound && (nmatchany>0)){
02582       //           highest number of tracks in recvtx matched to (the same) sim vertex
02583       // purity := -----------------------------------------------------------------
02584       //                  number of truth matched tracks in this recvtx
02585       double purity =nmatch/nmatchany; 
02586       Fill(h,"recmatchPurity",purity);
02587       if(v==recVtxs->begin()){
02588         Fill(h,"recmatchPurityTag",purity, (bool)(evmatch==iSignal));
02589       }else{
02590         Fill(h,"recmatchPuritynoTag",purity,(bool)(evmatch==iSignal));
02591       }
02592     }
02593     Fill(h,"recmatchvtxs",nmatchvtx);
02594     if(v==recVtxs->begin()){
02595       Fill(h,"recmatchvtxsTag",nmatchvtx);
02596     }else{
02597       Fill(h,"recmatchvtxsnoTag",nmatchvtx);
02598     }
02599 
02600 
02601      
02602   } // recvtx loop
02603   Fill(h,"nrecv",nrecvtxs);
02604 
02605 
02606   // --------------------------------------- match sim to rec  ---------------------------------------
02607 
02608   int npu1=0, npu2=0;
02609 
02610   for(vector<SimEvent>::iterator ev=simEvt.begin(); ev!=simEvt.end(); ev++){
02611 
02612     if(ev->tk.size()>0) npu1++;
02613     if(ev->tk.size()>1) npu2++;
02614 
02615     bool isSignal= ev->eventId==iSignal;
02616     
02617     Fill(h,"nRecTrkInSimVtx",(double) ev->tk.size(),isSignal);
02618     Fill(h,"nPrimRecTrkInSimVtx",(double) ev->tkprim.size(),isSignal);
02619     Fill(h,"sumpt2rec",sqrt(ev->sumpt2rec),isSignal);
02620     Fill(h,"sumpt2",sqrt(ev->sumpt2),isSignal);
02621     Fill(h,"sumpt",sqrt(ev->sumpt),isSignal);
02622 
02623     double nRecVWithTrk=0;  // vertices with tracks from this simvertex
02624     double  nmatch=0, ntmatch=0, zmatch=-99;
02625 
02626     for(reco::VertexCollection::const_iterator v=recVtxs->begin(); 
02627         v!=recVtxs->end(); ++v){
02628       if ( (v->ndof()<-1) || (v->chi2()<=0) ) continue;  // skip clusters 
02629       // count tracks found in both, sim and rec
02630       double n=0, wt=0;
02631       for(vector<TransientTrack>::iterator te=ev->tk.begin(); te!=ev->tk.end(); te++){
02632         const reco::Track&  RTe=te->track();
02633         for(trackit_t tv=v->tracks_begin(); tv!=v->tracks_end(); tv++){
02634            const reco::Track & RTv=*(tv->get());  
02635            if(RTe.vz()==RTv.vz()) {n++; wt+=v->trackWeight(*tv);}
02636         }
02637       }
02638 
02639       if(n>0){  nRecVWithTrk++; }
02640       if (n > nmatch){
02641         nmatch=n; ntmatch=v->tracksSize(); zmatch=v->position().z();
02642       }
02643       
02644     }// end of reco vertex loop
02645 
02646 
02647     // nmatch is the highest number of tracks from this sim vertex found in a single reco-vertex
02648     if(ev->tk.size()>0){ Fill(h,"trkAssignmentEfficiency", nmatch/ev->tk.size(), isSignal); };
02649     if(ev->tkprim.size()>0){ Fill(h,"primtrkAssignmentEfficiency", nmatch/ev->tkprim.size(), isSignal); };
02650 
02651     // matched efficiency = efficiency for finding a reco vertex with > 50% of the simvertexs reconstructed tracks
02652 
02653     double ntsim=ev->tk.size(); // may be better to use the number of primary tracks here ?
02654     double matchpurity=nmatch/ntmatch;
02655 
02656     if(ntsim>0){
02657 
02658       Fill(h,"matchVtxFraction",nmatch/ntsim,isSignal);
02659       if(nmatch/ntsim>=0.5){
02660         Fill(h,"matchVtxEfficiency",1.,isSignal);
02661         if(ntsim>1){Fill(h,"matchVtxEfficiency2",1.,isSignal);}
02662         if(matchpurity>0.5){Fill(h,"matchVtxEfficiency5",1.,isSignal);}
02663       }else{
02664         Fill(h,"matchVtxEfficiency",0.,isSignal);
02665         if(ntsim>1){Fill(h,"matchVtxEfficiency2",0.,isSignal);}
02666         Fill(h,"matchVtxEfficiency5",0.,isSignal);  // no (matchpurity>5) here !!
02667         if(isSignal){
02668         cout << "Signal vertex not matched " <<  message << "  event=" << eventcounter_ << " nmatch=" << nmatch << "  ntsim=" << ntsim << endl;
02669         }
02670       }
02671     } // ntsim >0
02672 
02673 
02674     if(zmatch>-99){
02675       Fill(h,"matchVtxZ",zmatch-ev->z);
02676       Fill(h,"matchVtxZ",zmatch-ev->z,isSignal);
02677       Fill(h,"matchVtxZCum",fabs(zmatch-ev->z));
02678       Fill(h,"matchVtxZCum",fabs(zmatch-ev->z),isSignal);
02679     }else{
02680       Fill(h,"matchVtxZCum",1.0);
02681       Fill(h,"matchVtxZCum",1.0,isSignal);
02682     }
02683     if(fabs(zmatch-ev->z)<zmatch_){
02684       Fill(h,"matchVtxEfficiencyZ",1.,isSignal);
02685     }else{
02686       Fill(h,"matchVtxEfficiencyZ",0.,isSignal);
02687     }   
02688     
02689     if(ntsim>0) Fill(h, "matchVtxEfficiencyZ1", fabs(zmatch-ev->z)<zmatch_ , isSignal);
02690     if(ntsim>1) Fill(h, "matchVtxEfficiencyZ2", fabs(zmatch-ev->z)<zmatch_ , isSignal);
02691 
02692 
02693     Fill(h,"vtxMultiplicity",nRecVWithTrk,isSignal);
02694 
02695     // efficiency vs number of tracks, use your favorite definition of efficiency here
02696     //if(nmatch>=0.5*ntmatch){  // purity
02697     if(fabs(zmatch-ev->z)<zmatch_){  //  zmatch
02698       Fill(h,"vtxFindingEfficiencyVsNtrk",(double) ev->tk.size(),1.);
02699        if(isSignal){
02700          Fill(h,"vtxFindingEfficiencyVsNtrkSignal",ev->tk.size(),1.);
02701       }else{
02702         Fill(h,"vtxFindingEfficiencyVsNtrkPU",(double) ev->tk.size(),1.);
02703       }
02704     }else{
02705       Fill(h,"vtxFindingEfficiencyVsNtrk",(double) ev->tk.size(),0.);
02706       if(isSignal){
02707         Fill(h,"vtxFindingEfficiencyVsNtrkSignal",(double) ev->tk.size(),1.);
02708       }else{
02709         Fill(h,"vtxFindingEfficiencyVsNtrkPU",(double) ev->tk.size(),1.);
02710       }
02711     }
02712 
02713     
02714   }
02715   
02716   Fill(h,"npu1",npu1);
02717   Fill(h,"npu2",npu2);
02718 
02719   Fill(h,"nrecvsnpu",npu1,float(nrecvtxs));
02720   Fill(h,"nrecvsnpu2",npu2,float(nrecvtxs));
02721 
02722   // ---------------------------------------  sim-signal vs rec-tag  ---------------------------------------
02723   SimEvent* ev=&(simEvt[0]);
02724   const reco::Vertex* v=&(*recVtxs->begin());
02725 
02726   double n=0;
02727   for(vector<TransientTrack>::iterator te=ev->tk.begin(); te!=ev->tk.end(); te++){
02728     const reco::Track&  RTe=te->track();
02729     for(trackit_t tv=v->tracks_begin(); tv!=v->tracks_end(); tv++){
02730       const reco::Track & RTv=*(tv->get());  
02731       if(RTe.vz()==RTv.vz()) {n++;}
02732     }
02733   }
02734   
02735   cout << "Number of tracks in reco tagvtx " << v->tracksSize() << endl;
02736   cout << "Number of selected tracks in sim event vtx " << ev->tk.size() << "    (prim=" << ev->tkprim.size() << ")"<<endl;
02737   cout << "Number of tracks in both         " << n << endl;
02738   double ntruthmatched=getTruthMatchedVertexTracks(*v).size();
02739   if (ntruthmatched>0){
02740     cout << "TrackPurity = "<< n/ntruthmatched <<endl;
02741     Fill(h,"TagVtxTrkPurity",n/ntruthmatched);
02742   }
02743   if (ev->tk.size()>0){
02744     cout << "TrackEfficiency = "<< n/ev->tk.size() <<endl;
02745     Fill(h,"TagVtxTrkEfficiency",n/ev->tk.size());
02746   }
02747 }
02748 
02749 /***************************************************************************************/
02750 
02751 
02752 
02753 
02754 
02755 
02756 /***************************************************************************************/
02757 
02758 void PrimaryVertexAnalyzer4PU::analyzeVertexCollection(std::map<std::string, TH1*> & h,
02759                                                  const Handle<reco::VertexCollection> recVtxs,
02760                                                  const Handle<reco::TrackCollection> recTrks, 
02761                                                  std::vector<simPrimaryVertex> & simpv,
02762                                                        const std::string message)
02763 {
02764   //cout <<"PrimaryVertexAnalyzer4PU::analyzeVertexCollection (HepMC), simpvs=" << simpv.size() << endl;
02765   int nrectrks=recTrks->size();
02766   int nrecvtxs=recVtxs->size();
02767   int nseltrks=-1; 
02768   reco::TrackCollection selTrks;   // selected tracks
02769   reco::TrackCollection lostTrks;  // selected but lost tracks (part of dropped clusters)
02770 
02771   // extract dummy vertices representing clusters
02772   reco::VertexCollection clusters;
02773   reco::Vertex allSelected;
02774   double cpufit=0;
02775   double cpuclu=0;
02776   for(reco::VertexCollection::const_iterator v=recVtxs->begin(); 
02777       v!=recVtxs->end(); ++v){
02778     if ( (fabs(v->ndof()+3.)<0.0001) && (v->chi2()<=0) ){ 
02779       // this dummy vertex is for the full event
02780       allSelected=(*v);
02781       nseltrks=(allSelected.tracksSize());
02782       nrecvtxs--;
02783       cpuclu=-v->chi2();
02784       continue;
02785     }else if( (fabs(v->ndof()+2.)<0.0001) && (v->chi2()==0) ){
02786       // this is a cluster, not a vertex
02787       clusters.push_back(*v);
02788       Fill(h,"cpuvsntrk",(double) v->tracksSize(),fabs(v->y()));
02789       cpufit+=fabs(v->y());
02790       Fill(h,"nclutrkall",(double) v->tracksSize());
02791       Fill(h,"selstat",v->x());
02792       //Fill(h,"nclutrkvtx",);// see below
02793       nrecvtxs--;
02794     }
02795   }
02796   Fill(h,"cpuclu",cpuclu);
02797   Fill(h,"cpufit",cpufit);
02798   Fill(h,"cpucluvsntrk",nrectrks, cpuclu);
02799   
02800 
02801   
02802   if(simpv.size()>0){//this is mc
02803     double dsimrecx=0.;
02804     double dsimrecy=0.;//0.0011;
02805     double dsimrecz=0.;//0.0012;
02806     
02807     // vertex matching and efficiency bookkeeping
02808     int nsimtrk=0;
02809     for(std::vector<simPrimaryVertex>::iterator vsim=simpv.begin();
02810         vsim!=simpv.end(); vsim++){
02811       
02812       
02813       nsimtrk+=vsim->nGenTrk;
02814       // look for a matching reconstructed vertex
02815       vsim->recVtx=NULL;
02816       vsim->cluster=-1;
02817       
02818       for(reco::VertexCollection::const_iterator vrec=recVtxs->begin();  vrec!=recVtxs->end(); ++vrec){
02819 
02820         if( vrec->isFake() ) {
02821           continue;  // skip fake vertices (=beamspot)
02822           cout << "fake vertex" << endl;
02823         }
02824 
02825         if( vrec->ndof()<0. )continue;  // skip dummy clusters, if any
02826         //        if ( matchVertex(*vsim,*vrec) ){
02827 
02828         // if the matching critera are fulfilled, accept the rec-vertex that is closest in z
02829         if(    ((vsim->recVtx) && (fabs(vsim->recVtx->position().z()-vsim->z-dsimrecz)>fabs(vrec->z()-vsim->z-dsimrecz)))
02830                || (!vsim->recVtx) )
02831           {
02832             vsim->recVtx=&(*vrec);
02833 
02834             // find the corresponding cluster
02835             for(unsigned int iclu=0; iclu<clusters.size(); iclu++){
02836               if( fabs(clusters[iclu].position().z()-vrec->position().z()) < 0.001 ){
02837                 vsim->cluster=iclu;
02838                 vsim->nclutrk=clusters[iclu].position().y();
02839               }
02840             }
02841           }
02842 
02843         // the following only works in MC samples without pile-up
02844         if ((simpv.size()==1) && ( fabs(vsim->recVtx->position().z()-vsim->z-dsimrecz)>zmatch_ )){
02845             // now we have a recvertex without a matching simvertex, I would call this fake 
02846             // however, the G4 info does not contain pile-up
02847             Fill(h,"fakeVtxZ",vrec->z());
02848             if (vrec->ndof()>=0.5) Fill(h,"fakeVtxZNdofgt05",vrec->z());
02849             if (vrec->ndof()>=2.0) Fill(h,"fakeVtxZNdofgt2",vrec->z());
02850             Fill(h,"fakeVtxNdof",vrec->ndof());
02851             //Fill(h,"fakeVtxNdof1",vrec->ndof());
02852             Fill(h,"fakeVtxNtrk",vrec->tracksSize());
02853             if(vrec->tracksSize()==2){  Fill(h,"fake2trkchi2vsndof",vrec->ndof(),vrec->chi2());   }
02854             if(vrec->tracksSize()==3){  Fill(h,"fake3trkchi2vsndof",vrec->ndof(),vrec->chi2());   }
02855             if(vrec->tracksSize()==4){  Fill(h,"fake4trkchi2vsndof",vrec->ndof(),vrec->chi2());   }
02856             if(vrec->tracksSize()==5){  Fill(h,"fake5trkchi2vsndof",vrec->ndof(),vrec->chi2());   }
02857           }
02858       }
02859       
02860 
02861       Fill(h,"nsimtrk",float(nsimtrk));
02862       Fill(h,"nsimtrk",float(nsimtrk),vsim==simpv.begin());
02863       Fill(h,"nrecsimtrk",float(vsim->nMatchedTracks));
02864       Fill(h,"nrecnosimtrk",float(nsimtrk-vsim->nMatchedTracks));
02865       
02866       // histogram properties of matched vertices
02867       if (vsim->recVtx && ( fabs(vsim->recVtx->z()-vsim->z*simUnit_)<zmatch_ )){
02868         
02869         if(verbose_){std::cout <<"primary matched " << message << " " << setw(8) << setprecision(4) << vsim->x << " " << vsim->y << " " << vsim->z << std:: endl;}
02870         Fill(h,"matchedVtxNdof", vsim->recVtx->ndof());
02871         // residuals an pulls with respect to simulated vertex
02872         Fill(h,"resx", vsim->recVtx->x()-vsim->x*simUnit_ );
02873         Fill(h,"resy", vsim->recVtx->y()-vsim->y*simUnit_ );
02874         Fill(h,"resz", vsim->recVtx->z()-vsim->z*simUnit_ );
02875         Fill(h,"resz10", vsim->recVtx->z()-vsim->z*simUnit_ );
02876         Fill(h,"pullx", (vsim->recVtx->x()-vsim->x*simUnit_)/vsim->recVtx->xError() );
02877         Fill(h,"pully", (vsim->recVtx->y()-vsim->y*simUnit_)/vsim->recVtx->yError() );
02878         Fill(h,"pullz", (vsim->recVtx->z()-vsim->z*simUnit_)/vsim->recVtx->zError() );
02879         Fill(h,"resxr", vsim->recVtx->x()-vsim->x*simUnit_-dsimrecx);
02880         Fill(h,"resyr", vsim->recVtx->y()-vsim->y*simUnit_-dsimrecy );
02881         Fill(h,"reszr", vsim->recVtx->z()-vsim->z*simUnit_-dsimrecz);
02882         Fill(h,"pullxr", (vsim->recVtx->x()-vsim->x*simUnit_-dsimrecx)/vsim->recVtx->xError() );
02883         Fill(h,"pullyr", (vsim->recVtx->y()-vsim->y*simUnit_-dsimrecy)/vsim->recVtx->yError() );
02884         Fill(h,"pullzr", (vsim->recVtx->z()-vsim->z*simUnit_-dsimrecz)/vsim->recVtx->zError() );
02885 
02886 
02887 
02888         // efficiency with zmatch within 500 um (or whatever zmatch is)
02889         Fill(h,"eff", 1.);
02890         if(simpv.size()==1){
02891           if (vsim->recVtx==&(*recVtxs->begin())){
02892             Fill(h,"efftag", 1.); 
02893           }else{
02894             Fill(h,"efftag", 0.); 
02895             cout << "signal vertex not tagged " << message << " " << eventcounter_ << endl;
02896             // call XXClusterizerInZ.vertices(seltrks,3)
02897             
02898           }
02899         }
02900         
02901         Fill(h,"effvsptsq",vsim->ptsq,1.);
02902         Fill(h,"effvsnsimtrk",vsim->nGenTrk,1.);
02903         Fill(h,"effvsnrectrk",nrectrks,1.);
02904         Fill(h,"effvsnseltrk",nseltrks,1.);
02905         Fill(h,"effvsz",vsim->z*simUnit_,1.);
02906         Fill(h,"effvsz2",vsim->z*simUnit_,1.);
02907         Fill(h,"effvsr",sqrt(vsim->x*vsim->x+vsim->y*vsim->y)*simUnit_,1.);
02908         
02909 
02910       }else{  // no matching rec vertex found for this simvertex
02911         
02912         bool plapper=verbose_ && vsim->nGenTrk;
02913         if(plapper){
02914           // be quiet about invisble vertices
02915           std::cout << "primary not found "  << message << " " << eventcounter_ << "  x=" <<vsim->x*simUnit_ << "  y=" << vsim->y*simUnit_  << " z=" << vsim->z*simUnit_  << " nGenTrk=" << vsim->nGenTrk << std::endl;
02916         }
02917         int mistype=0;
02918         if (vsim->recVtx){
02919           if(plapper){
02920             std::cout << "nearest recvertex at " << vsim->recVtx->z() << "   dz=" << vsim->recVtx->z()-vsim->z*simUnit_ << std::endl;
02921           }
02922           
02923           if (fabs(vsim->recVtx->z()-vsim->z*simUnit_)<0.2 ){
02924             Fill(h,"effvsz2",vsim->z*simUnit_,1.);
02925           }
02926           
02927           if (fabs(vsim->recVtx->z()-vsim->z*simUnit_)<0.5 ){
02928             if(verbose_){std::cout << "type 1, lousy z vertex" << std::endl;}
02929             Fill(h,"zlost1", vsim->z*simUnit_,1.);
02930             mistype=1;
02931           }else{
02932             if(plapper){std::cout << "type 2a no vertex anywhere near" << std::endl;}
02933             mistype=2;
02934           }
02935         }else{// no recVtx at all
02936           mistype=2;
02937           if(plapper){std::cout << "type 2b, no vertex at all" << std::endl;}
02938         }
02939         
02940         if(mistype==2){
02941           int selstat=-3;
02942           // no matching vertex found, is there a cluster?
02943           for(unsigned int iclu=0; iclu<clusters.size(); iclu++){
02944             if( fabs(clusters[iclu].position().z()-vsim->z*simUnit_) < 0.1 ){
02945               selstat=int(clusters[iclu].position().x()+0.1);
02946               if(verbose_){std::cout << "matching cluster found with selstat=" << clusters[iclu].position().x() << std::endl;}
02947             }
02948           }
02949           if (selstat==0){
02950             if(plapper){std::cout << "vertex rejected (distance to beam)" << std::endl;}
02951             Fill(h,"zlost3", vsim->z*simUnit_,1.);
02952           }else if(selstat==-1){
02953             if(plapper) {std::cout << "vertex invalid" << std::endl;}
02954             Fill(h,"zlost4", vsim->z*simUnit_,1.);
02955           }else if(selstat==1){
02956             if(plapper){std::cout << "vertex accepted, this cannot be right!!!!!!!!!!" << std::endl;}
02957           }else if(selstat==-2){
02958             if(plapper){std::cout << "dont know what this means !!!!!!!!!!" << std::endl;}
02959           }else if(selstat==-3){
02960             if(plapper){std::cout << "no matching cluster found " << std::endl;}
02961             Fill(h,"zlost2", vsim->z*simUnit_,1.);
02962           }else{
02963             if(plapper){std::cout << "dont know what this means either !!!!!!!!!!" << selstat << std::endl;}
02964           }
02965         }//
02966         
02967         
02968         Fill(h,"eff", 0.);
02969         if(simpv.size()==1){ Fill(h,"efftag", 0.); }
02970         
02971         Fill(h,"effvsptsq",vsim->ptsq,0.);
02972         Fill(h,"effvsnsimtrk",float(vsim->nGenTrk),0.);
02973         Fill(h,"effvsnrectrk",nrectrks,0.);
02974         Fill(h,"effvsnseltrk",nseltrks,0.);
02975         Fill(h,"effvsz",vsim->z*simUnit_,0.);
02976         Fill(h,"effvsr",sqrt(vsim->x*vsim->x+vsim->y*vsim->y)*simUnit_,0.);
02977         
02978       } // no recvertex for this simvertex
02979 
02980     }
02981 
02982     // end of sim/rec matching
02983    
02984      
02985    // purity of event vertex tags
02986     if (recVtxs->size()>0){
02987       Double_t dz=(*recVtxs->begin()).z() - (*simpv.begin()).z*simUnit_;
02988       Fill(h,"zdistancetag",dz);
02989       Fill(h,"abszdistancetag",fabs(dz));
02990       if( fabs(dz)<zmatch_){
02991         Fill(h,"puritytag",1.);
02992       }else{
02993         // bad tag: the true primary was more than 500 um (or zmatch) away from the tagged primary
02994         Fill(h,"puritytag",0.);
02995       }
02996     }
02997     
02998   }else{
02999     //if(verbose_) cout << "PrimaryVertexAnalyzer4PU::analyzeVertexCollection:  simPV is empty!" << endl;
03000   }
03001 
03002 
03003   //******* the following code does not require MC and will/should work for data **********
03004 
03005 
03006   Fill(h,"bunchCrossing",bunchCrossing_);
03007   if(recTrks->size()>0)  Fill(h,"bunchCrossingLogNtk",bunchCrossing_,log(recTrks->size())/log(10.));
03008   
03009   // -----------------  reconstructed tracks  ------------------------
03010   // the list of selected tracks can only be correct if the selection parameterset  and track collection
03011   // is the same that was used for the reconstruction
03012 
03013   int nt=0;
03014   for(reco::TrackCollection::const_iterator t=recTrks->begin();
03015       t!=recTrks->end(); ++t){
03016     if((recVtxs->size()>0) && (recVtxs->begin()->isValid())){
03017       fillTrackHistos(h,"all",*t,&(*recVtxs->begin()));
03018     }else{
03019       fillTrackHistos(h,"all",*t);
03020     }
03021     if(recTrks->size()>100)    fillTrackHistos(h,"M",*t);
03022 
03023 
03024 
03025     TransientTrack  tt = theB_->build(&(*t));  tt.setBeamSpot(vertexBeamSpot_);
03026     if  (theTrackFilter(tt)){
03027       selTrks.push_back(*t);
03028       fillTrackHistos(h,"sel",*t);
03029       int foundinvtx=0;
03030       int nvtemp=-1;
03031       for(reco::VertexCollection::const_iterator v=recVtxs->begin(); 
03032           v!=recVtxs->end(); ++v){
03033         nvtemp++;
03034         if(( v->isFake()) || (v->ndof()<-2) ) break;
03035         for(trackit_t tv=v->tracks_begin(); tv!=v->tracks_end(); tv++ ){
03036           if( ((**tv).vz()==t->vz()&&((**tv).phi()==t->phi())) ) {
03037             foundinvtx++;
03038           }
03039         }
03040         
03041       }
03042       if(foundinvtx==0){
03043         fillTrackHistos(h,"sellost",*t);
03044       }else if(foundinvtx>1){
03045         cout << "hmmmm " << foundinvtx << endl;
03046       }
03047     }
03048     nt++;
03049   }
03050 
03051 
03052   if (nseltrks<0){
03053     nseltrks=selTrks.size();
03054   }else if( ! (nseltrks==(int)selTrks.size()) ){
03055     std::cout << "Warning: inconsistent track selection !" << std::endl;
03056   }
03057 
03058 
03059 
03060   // fill track histograms of vertex tracks
03061   int nrec=0,  nrec0=0, nrec8=0, nrec2=0, nrec4=0;
03062   for(reco::VertexCollection::const_iterator v=recVtxs->begin(); 
03063       v!=recVtxs->end(); ++v){
03064     
03065     if (! (v->isFake()) && v->ndof()>0 && v->chi2()>0 ){
03066       nrec++;
03067       if (v->ndof()>0) nrec0++;
03068       if (v->ndof()>8) nrec8++;
03069       if (v->ndof()>2) nrec2++;
03070       if (v->ndof()>4) nrec4++;
03071       for(trackit_t t=v->tracks_begin(); t!=v->tracks_end(); t++){
03072         if(v==recVtxs->begin()){
03073           fillTrackHistos(h,"tagged",**t,  &(*v));
03074         }else{
03075           fillTrackHistos(h,"untagged",**t,  &(*v));
03076         }
03077 
03078         Float_t wt=v->trackWeight(*t);
03079         //dumpHitInfo(**t); cout << "  w=" << wt << endl;
03080         Fill(h,"trackWt",wt);
03081         if(wt>0.5){
03082           fillTrackHistos(h,"wgt05",**t, &(*v));
03083           if(v->ndof()>4) fillTrackHistos(h,"ndof4",**t, &(*v));
03084         }else{
03085           fillTrackHistos(h,"wlt05",**t, &(*v));
03086         }
03087       }
03088     }
03089   }
03090 
03091 
03092   // bachelor tracks (only available through clusters right now)
03093   for(unsigned int iclu=0; iclu<clusters.size(); iclu++){
03094     if (clusters[iclu].tracksSize()==1){
03095       for(trackit_t t = clusters[iclu].tracks_begin(); 
03096           t!=clusters[iclu].tracks_end(); t++){
03097         fillTrackHistos(h,"bachelor",**t);
03098       }
03099     }
03100   }
03101 
03102 
03103   // -----------------  reconstructed vertices  ------------------------
03104 
03105   // event 
03106   Fill(h,"szRecVtx",recVtxs->size());
03107   Fill(h,"nclu",clusters.size());
03108   Fill(h,"nseltrk",nseltrks);
03109   Fill(h,"nrectrk",nrectrks);
03110   Fill(h,"nrecvtx",nrec);
03111   Fill(h,"nrecvtx2",nrec2);
03112   Fill(h,"nrecvtx4",nrec4);
03113   Fill(h,"nrecvtx8",nrec8);
03114 
03115   if(nrec>0){
03116     Fill(h,"eff0vsntrec",nrectrks,1.);
03117     Fill(h,"eff0vsntsel",nseltrks,1.);
03118   }else{
03119     Fill(h,"eff0vsntrec",nrectrks,0.);
03120     Fill(h,"eff0vsntsel",nseltrks,0.);
03121     if((nseltrks>1)&&(verbose_)){
03122       cout << Form("PrimaryVertexAnalyzer4PU: %s may have lost a vertex  %10d  %10d     %4d / %4d ",message.c_str(),run_, event_, nrectrks,nseltrks) << endl;
03123       dumpThisEvent_=true;
03124     }
03125   }
03126   if(nrec0>0) { Fill(h,"eff0ndof0vsntsel",nseltrks,1.);}else{ Fill(h,"eff0ndof0vsntsel",nseltrks,0.);}
03127   if(nrec2>0) { Fill(h,"eff0ndof2vsntsel",nseltrks,1.);}else{ Fill(h,"eff0ndof2vsntsel",nseltrks,0.);}
03128   if(nrec4>0) { Fill(h,"eff0ndof4vsntsel",nseltrks,1.);}else{ Fill(h,"eff0ndof4vsntsel",nseltrks,0.);}
03129   if(nrec8>0) { Fill(h,"eff0ndof8vsntsel",nseltrks,1.);}else{ Fill(h,"eff0ndof8vsntsel",nseltrks,0.);}
03130 
03131   if((nrec>1)&&(DEBUG_)) {
03132     cout << "multivertex event" << endl;
03133     dumpThisEvent_=true;
03134   }
03135 
03136   if((nrectrks>10)&&(nseltrks<3)){
03137     cout << "small fraction of selected tracks "  << endl;
03138     dumpThisEvent_=true;
03139   }
03140 
03141   // properties of events without a vertex
03142   if((nrec==0)||(recVtxs->begin()->isFake())){
03143     Fill(h,"nrectrk0vtx",nrectrks);
03144     Fill(h,"nseltrk0vtx",nseltrks);
03145     Fill(h,"nclu0vtx",clusters.size());
03146   }
03147 
03148 
03149   //  properties of (valid) vertices
03150   double ndof2=-10,ndof1=-10, zndof1=0, zndof2=0;
03151   for(reco::VertexCollection::const_iterator v=recVtxs->begin(); 
03152       v!=recVtxs->end(); ++v){
03153     if(v->isFake()){ Fill(h,"isFake",1.);}else{ Fill(h,"isFake",0.);}
03154     if(v->isFake()||((v->ndof()<0)&&(v->ndof()>-3))){ Fill(h,"isFake1",1.);}else{ Fill(h,"isFake1",0.);}
03155 
03156     if((v->isFake())||(v->ndof()<0)) continue;
03157     if(v->ndof()>ndof1){ ndof2=ndof1; zndof2=zndof1; ndof1=v->ndof(); zndof1=v->position().z();}
03158     else if(v->ndof()>ndof2){ ndof2=v->ndof(); zndof2=v->position().z();}
03159 
03160 
03161     // some special histogram for two track vertices
03162     if(v->tracksSize()==2){
03163       const TrackBaseRef& t1= *(v->tracks_begin());
03164       const TrackBaseRef& t2=*(v->tracks_begin()+1);
03165       bool os=(t1->charge()*t2->charge()<0);
03166       double dphi=t1->phi()-t2->phi(); if (dphi<0) dphi+=2*M_PI;
03167       double m12=sqrt(pow( sqrt(pow(0.139,2)+pow( t1->p(),2)) +sqrt(pow(0.139,2)+pow( t2->p(),2)) ,2)
03168                              -pow(t1->px()+t2->px(),2)
03169                              -pow(t1->py()+t2->py(),2)
03170                              -pow(t1->pz()+t2->pz(),2)
03171                     );
03172       if(os){
03173         Fill(h,"2trkdetaOS",t1->eta()-t2->eta());
03174         Fill(h,"2trkmassOS",m12);
03175       }else{
03176         Fill(h,"2trkdetaSS",t1->eta()-t2->eta());
03177         Fill(h,"2trkmassSS",m12);
03178       }
03179       Fill(h,"2trkdphi",dphi);
03180       Fill(h,"2trkseta",t1->eta()+t2->eta());
03181       if(fabs(dphi-M_PI)<0.1)      Fill(h,"2trksetacurl",t1->eta()+t2->eta());
03182       if(fabs(t1->eta()+t2->eta())<0.1) Fill(h,"2trkdphicurl",dphi);
03183       // fill separately for extra vertices
03184       if(v!=recVtxs->begin()){
03185         if(os){
03186           Fill(h,"2trkdetaOSPU",t1->eta()-t2->eta());
03187           Fill(h,"2trkmassOSPU",m12);
03188         }else{
03189           Fill(h,"2trkdetaSSPU",t1->eta()-t2->eta());
03190           Fill(h,"2trkmassSSPU",m12);
03191         }
03192         Fill(h,"2trkdphiPU",dphi);
03193         Fill(h,"2trksetaPU",t1->eta()+t2->eta());
03194         if(fabs(dphi-M_PI)<0.1)      Fill(h,"2trksetacurlPU",t1->eta()+t2->eta());
03195         if(fabs(t1->eta()+t2->eta())<0.1) Fill(h,"2trkdphicurlPU",dphi);
03196       }
03197     }
03198 
03199 
03200     Fill(h,"trkchi2vsndof",v->ndof(),v->chi2());
03201     if(v->ndof()>0){    Fill(h,"trkchi2overndof",v->chi2()/v->ndof()); }
03202     if(v->tracksSize()==2){  Fill(h,"2trkchi2vsndof",v->ndof(),v->chi2());   }
03203     if(v->tracksSize()==3){  Fill(h,"3trkchi2vsndof",v->ndof(),v->chi2());   }
03204     if(v->tracksSize()==4){  Fill(h,"4trkchi2vsndof",v->ndof(),v->chi2());   }
03205     if(v->tracksSize()==5){  Fill(h,"5trkchi2vsndof",v->ndof(),v->chi2());   }
03206 
03207     Fill(h,"nbtksinvtx",v->tracksSize());
03208     Fill(h,"nbtksinvtx2",v->tracksSize());
03209     Fill(h,"vtxchi2",v->chi2());
03210     Fill(h,"vtxndf",v->ndof());
03211     Fill(h,"vtxprob",ChiSquaredProbability(v->chi2() ,v->ndof()));
03212     Fill(h,"vtxndfvsntk",v->tracksSize(), v->ndof());
03213     Fill(h,"vtxndfoverntk",v->ndof()/v->tracksSize());
03214     Fill(h,"vtxndf2overntk",(v->ndof()+2)/v->tracksSize());
03215     Fill(h,"zrecvsnt",v->position().z(),float(nrectrks));
03216     if(nrectrks>100){
03217       Fill(h,"zrecNt100",v->position().z());
03218     }
03219 
03220     if(v->ndof()>2.0){  // enter only vertices that really contain tracks
03221       Fill(h,"xrec",v->position().x());
03222       Fill(h,"yrec",v->position().y());
03223       Fill(h,"zrec",v->position().z());
03224       Fill(h,"xrec1",v->position().x());
03225       Fill(h,"yrec1",v->position().y());
03226       Fill(h,"zrec1",v->position().z());
03227       Fill(h,"xrec2",v->position().x());
03228       Fill(h,"yrec2",v->position().y());
03229       Fill(h,"zrec2",v->position().z());
03230       Fill(h,"xrec3",v->position().x());
03231       Fill(h,"yrec3",v->position().y());
03232       Fill(h,"zrec3",v->position().z());
03233       Fill(h,"xrecb",v->position().x()-vertexBeamSpot_.x0());
03234       Fill(h,"yrecb",v->position().y()-vertexBeamSpot_.y0());
03235       Fill(h,"zrecb",v->position().z()-vertexBeamSpot_.z0());
03236       Fill(h,"xrecBeam",v->position().x()-vertexBeamSpot_.x0());
03237       Fill(h,"yrecBeam",v->position().y()-vertexBeamSpot_.y0());
03238       Fill(h,"zrecBeam",v->position().z()-vertexBeamSpot_.z0());
03239       Fill(h,"xrecBeamPull",(v->position().x()-vertexBeamSpot_.x0())/sqrt(pow(v->xError(),2)+pow(vertexBeamSpot_.BeamWidthX(),2)));
03240       Fill(h,"yrecBeamPull",(v->position().y()-vertexBeamSpot_.y0())/sqrt(pow(v->yError(),2)+pow(vertexBeamSpot_.BeamWidthY(),2)));
03241       
03242       Fill(h,"xrecBeamvsdx",v->xError(),v->position().x()-vertexBeamSpot_.x0());
03243       Fill(h,"yrecBeamvsdy",v->yError(),v->position().y()-vertexBeamSpot_.y0());
03244       Fill(h,"xrecBeamvsdxR2",v->position().x()-vertexBeamSpot_.x0(),v->xError());
03245       Fill(h,"yrecBeamvsdyR2",v->position().y()-vertexBeamSpot_.y0(),v->yError());
03246       Fill(h,"xrecBeam2vsdx2prof",pow(v->xError(),2),pow(v->position().x()-vertexBeamSpot_.x0(),2));
03247       Fill(h,"yrecBeam2vsdy2prof",pow(v->yError(),2),pow(v->position().y()-vertexBeamSpot_.y0(),2));
03248       Fill(h,"xrecBeamvsdx2",pow(v->xError(),2),pow(v->position().x()-vertexBeamSpot_.x0(),2));
03249       Fill(h,"yrecBeamvsdy2",pow(v->yError(),2),pow(v->position().y()-vertexBeamSpot_.y0(),2));
03250       Fill(h,"xrecBeamvsz",v->position().z(),v->position().x()-vertexBeamSpot_.x0());
03251       Fill(h,"yrecBeamvsz",v->position().z(),v->position().y()-vertexBeamSpot_.y0());
03252       Fill(h,"xrecBeamvszprof",v->position().z(),v->position().x()-vertexBeamSpot_.x0());
03253       Fill(h,"yrecBeamvszprof",v->position().z(),v->position().y()-vertexBeamSpot_.y0());
03254       Fill(h,"xrecBeamvsdxprof",v->xError(),v->position().x()-vertexBeamSpot_.x0());
03255       Fill(h,"yrecBeamvsdyprof",v->yError(),v->position().y()-vertexBeamSpot_.y0());
03256       
03257       
03258       Fill(h,"errx",v->xError());
03259       Fill(h,"erry",v->yError());
03260       Fill(h,"errz",v->zError());
03261       double vxx=v->covariance(0,0);
03262       double vyy=v->covariance(1,1);
03263       double vxy=v->covariance(1,0);
03264       double dv=0.25*(vxx+vyy)*(vxx+vyy-(vxx*vyy-vxy*vxy));
03265       if(dv>0){
03266         double l1=0.5*(vxx+vyy)+sqrt(dv);
03267         Fill(h,"err1",sqrt(l1));
03268         double l2=sqrt(0.5*(vxx+vyy)-sqrt(dv));
03269         if(l2>0) Fill(h,"err2",sqrt(l2));
03270       }
03271       
03272       
03273       // look at the tagged vertex separately
03274       if (v==recVtxs->begin()){
03275         Fill(h,"nbtksinvtxTag",v->tracksSize());
03276         Fill(h,"nbtksinvtxTag2",v->tracksSize());
03277         Fill(h,"xrectag",v->position().x());
03278         Fill(h,"yrectag",v->position().y());
03279         Fill(h,"zrectag",v->position().z());
03280       }else{
03281         Fill(h,"nbtksinvtxPU",v->tracksSize());
03282         Fill(h,"nbtksinvtxPU2",v->tracksSize());
03283       }
03284         
03285       // vertex resolution vs number of tracks
03286       Fill(h,"xresvsntrk",v->tracksSize(),v->xError());
03287       Fill(h,"yresvsntrk",v->tracksSize(),v->yError());
03288       Fill(h,"zresvsntrk",v->tracksSize(),v->zError());
03289       
03290     }
03291     
03292     // cluster properties (if available)
03293     for(unsigned int iclu=0; iclu<clusters.size(); iclu++){
03294       if( fabs(clusters[iclu].position().z()-v->position().z()) < 0.0001 ){
03295         Fill(h,"nclutrkvtx",clusters[iclu].tracksSize());
03296       }
03297     }
03298     
03299 
03300         
03301     //  properties of (valid) neighbour vertices
03302     reco::VertexCollection::const_iterator v1=v;     v1++;
03303     for(; v1!=recVtxs->end(); ++v1){
03304       if((v1->isFake())||(v1->ndof()<0)) continue;
03305       Fill(h,"zdiffrec",v->position().z()-v1->position().z());
03306 //       if(fabs(v->position().z()-v1->position().z())>1){
03307 //      cout << message << " zdiffrec=" << v->position().z()-v1->position().z() << " " << v->ndof() << " " << v1->ndof() << endl;
03308 //      dumpThisEvent_=true;
03309 //       }
03310 
03311       double z0=v->position().z()-vertexBeamSpot_.z0();
03312       double z1=v1->position().z()-vertexBeamSpot_.z0();
03313       Fill(h,"zPUcand",z0);     Fill(h,"zPUcand",z1);
03314       Fill(h,"ndofPUcand",v->ndof()); Fill(h,"ndofPUcand",v1->ndof());
03315       
03316       Fill(h,"zdiffvsz",z1-z0,0.5*(z1+z0));
03317 
03318       if ((v->ndof()>2) && (v1->ndof()>2)){
03319         Fill(h,"zdiffrec2",v->position().z()-v1->position().z());
03320         Fill(h,"zPUcand2",z0);
03321         Fill(h,"zPUcand2",z1);
03322         Fill(h,"ndofPUcand2",v->ndof());
03323         Fill(h,"ndofPUcand2",v1->ndof());
03324         Fill(h,"zvszrec2",z0, z1);
03325         Fill(h,"pzvspz2",TMath::Freq(z0/2.16),TMath::Freq(z1/2.16) );
03326       }
03327       
03328       if ((v->ndof()>4) && (v1->ndof()>4)){
03329         Fill(h,"zdiffvsz4",z1-z0,0.5*(z1+z0));
03330         Fill(h,"zdiffrec4",v->position().z()-v1->position().z());
03331         Fill(h,"zvszrec4",z0, z1);
03332         Fill(h,"pzvspz4",TMath::Freq(z0/2.16),TMath::Freq(z1/2.16) );
03333         //cout << "ndof4 pu-candidate " << run_ << " " << event_ << endl ;
03334         if(fabs(z0-z1)>1.0){
03335           Fill(h,"xbeamPUcand",v->position().x()-vertexBeamSpot_.x0());
03336           Fill(h,"ybeamPUcand",v->position().y()-vertexBeamSpot_.y0());
03337           Fill(h,"xbeamPullPUcand",(v->position().x()-vertexBeamSpot_.x0())/v->xError());
03338           Fill(h,"ybeamPullPUcand",(v->position().y()-vertexBeamSpot_.y0())/v->yError());
03339           //Fill(h,"sumwOverNtkPUcand",sumw/v->tracksSize());
03340           //Fill(h,"sumwOverNtkPUcand",sumw/v1->tracksSize());
03341           Fill(h,"ndofOverNtkPUcand",v->ndof()/v->tracksSize());
03342           Fill(h,"ndofOverNtkPUcand",v1->ndof()/v1->tracksSize());
03343           Fill(h,"xbeamPUcand",v1->position().x()-vertexBeamSpot_.x0());
03344           Fill(h,"ybeamPUcand",v1->position().y()-vertexBeamSpot_.y0());
03345           Fill(h,"xbeamPullPUcand",(v1->position().x()-vertexBeamSpot_.x0())/v1->xError());
03346           Fill(h,"ybeamPullPUcand",(v1->position().y()-vertexBeamSpot_.y0())/v1->yError());
03347           Fill(h,"zPUcand4",z0);
03348           Fill(h,"zPUcand4",z1);
03349           Fill(h,"ndofPUcand4",v->ndof());
03350           Fill(h,"ndofPUcand4",v1->ndof());
03351           for(trackit_t t=v->tracks_begin(); t!=v->tracks_end(); t++){ if(v->trackWeight(*t)>0.5) fillTrackHistos(h,"PUcand",**t, &(*v));  }
03352           for(trackit_t t=v1->tracks_begin(); t!=v1->tracks_end(); t++){ if(v1->trackWeight(*t)>0.5) fillTrackHistos(h,"PUcand",**t, &(*v1));   }
03353         }
03354         }
03355       
03356       if ((v->ndof()>4) && (v1->ndof()>2) && (v1->ndof()<4)){
03357         for(trackit_t t=v1->tracks_begin(); t!=v1->tracks_end(); t++){ if(v1->trackWeight(*t)>0.5) fillTrackHistos(h,"PUfake",**t, &(*v1));   }
03358       }
03359       
03360       if ((v->ndof()>8) && (v1->ndof()>8)){
03361         Fill(h,"zdiffrec8",v->position().z()-v1->position().z());
03362         if(dumpPUcandidates_ && fabs(z0-z1)>1.0){
03363           cout << "PU candidate " << run_ << " " << event_ << " " << message <<  " zdiff=" <<z0-z1 << endl;
03364 //      cerr << "PU candidate " << run_ << " "<<  event_ << " " << message <<  endl;
03365           dumpThisEvent_=true;
03366         }
03367       }
03368 
03369     }
03370     
03371     // test track links, use reconstructed vertices
03372       bool problem = false;
03373       Fill(h,"nans",1.,std::isnan(v->position().x())*1.);
03374       Fill(h,"nans",2.,std::isnan(v->position().y())*1.);
03375       Fill(h,"nans",3.,std::isnan(v->position().z())*1.);
03376       
03377       int index = 3;
03378       for (int i = 0; i != 3; i++) {
03379         for (int j = i; j != 3; j++) {
03380           index++;
03381           Fill(h,"nans",index*1., std::isnan(v->covariance(i, j))*1.);
03382           if (std::isnan(v->covariance(i, j))) problem = true;
03383           // in addition, diagonal element must be positive
03384           if (j == i && v->covariance(i, j) < 0) {
03385             Fill(h,"nans",index*1., 1.);
03386             problem = true;
03387           }
03388         }
03389       }
03390       
03391       try {
03392         for(trackit_t t = v->tracks_begin(); 
03393             t!=v->tracks_end(); t++) {
03394           // illegal charge
03395           if ( (**t).charge() < -1 || (**t).charge() > 1 ) {
03396             Fill(h,"tklinks",0.);
03397           }
03398           else {
03399             Fill(h,"tklinks",1.);
03400           }
03401         }
03402       } catch (...) {
03403         // exception thrown when trying to use linked track
03404         Fill(h,"tklinks",0.);
03405       }
03406 
03407       if (problem) {
03408         // analyze track parameter covariance definiteness
03409         double data[25];
03410         try {
03411           int itk = 0;
03412           for(trackit_t t = v->tracks_begin(); 
03413               t!=v->tracks_end(); t++) {
03414             std::cout << "Track " << itk++ << std::endl;
03415             int i2 = 0;
03416             for (int i = 0; i != 5; i++) {
03417               for (int j = 0; j != 5; j++) {
03418                 data[i2] = (**t).covariance(i, j);
03419                 std::cout << std:: scientific << data[i2] << " ";
03420                 i2++;
03421               }
03422               std::cout << std::endl;
03423             }
03424             gsl_matrix_view m 
03425               = gsl_matrix_view_array (data, 5, 5);
03426             
03427             gsl_vector *eval = gsl_vector_alloc (5);
03428             gsl_matrix *evec = gsl_matrix_alloc (5, 5);
03429             
03430             gsl_eigen_symmv_workspace * w = 
03431               gsl_eigen_symmv_alloc (5);
03432             
03433             gsl_eigen_symmv (&m.matrix, eval, evec, w);
03434             
03435             gsl_eigen_symmv_free (w);
03436             
03437             gsl_eigen_symmv_sort (eval, evec, 
03438                                   GSL_EIGEN_SORT_ABS_ASC);
03439             
03440             // print sorted eigenvalues
03441           {
03442             int i;
03443             for (i = 0; i < 5; i++) {
03444               double eval_i 
03445                 = gsl_vector_get (eval, i);
03446               //gsl_vector_view evec_i 
03447               //        = gsl_matrix_column (evec, i);
03448               
03449               printf ("eigenvalue = %g\n", eval_i);
03450               //              printf ("eigenvector = \n");
03451               //              gsl_vector_fprintf (stdout, 
03452               //                                  &evec_i.vector, "%g");
03453             }
03454           }
03455           }
03456         }
03457       catch (...) {
03458         // exception thrown when trying to use linked track
03459         break;
03460       }// catch()
03461       }// if (problem)
03462 
03463 
03464     
03465   }  // vertex loop (v)
03466 
03467 
03468   // 2nd highest ndof
03469   if (ndof2>0){
03470       Fill(h,"ndofnr2",ndof2); 
03471       if(fabs(zndof1-zndof2)>1) Fill(h,"ndofnr2d1cm",ndof2); 
03472       if(fabs(zndof1-zndof2)>2) Fill(h,"ndofnr2d2cm",ndof2); 
03473   }
03474 
03475 
03476 }
03477