CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_5_3_9_patch3/src/DPGAnalysis/SiStripTools/plugins/TrackerDpgAnalysis.cc

Go to the documentation of this file.
00001 // -*- C++ -*-
00002 //
00003 // Package:    DPGAnalysis
00004 // Class:      TrackerDpgAnalysis
00005 // 
00013 //
00014 // Original Author:  Christophe DELAERE
00015 //         Created:  Tue Sep 23 02:11:44 CEST 2008
00016 //         Revised:  Thu Nov 26 10:00:00 CEST 2009
00017 // part of the code was inspired by https://cmssw.cvs.cern.ch/cgi-bin/cmssw.cgi/UserCode/YGao/LhcTrackAnalyzer/
00018 // part of the code was inspired by 
00019 // other inputs from Andrea Giammanco, Gaelle Boudoul, Andrea Venturi, Steven Lowette, Gavril Giurgiu
00020 // $Id: TrackerDpgAnalysis.cc,v 1.12 2011/07/21 21:15:03 venturia Exp $
00021 //
00022 //
00023 
00024 // system include files
00025 #include <memory>
00026 #include <iostream>
00027 #include <limits>
00028 #include <utility>
00029 #include <vector>
00030 #include <algorithm>
00031 #include <functional>
00032 #include <string.h>
00033 #include <sstream>
00034 #include <fstream>
00035 
00036 // root include files
00037 #include "TTree.h"
00038 #include "TFile.h"
00039 
00040 // user include files
00041 #include "FWCore/Framework/interface/Frameworkfwd.h"
00042 #include "FWCore/Framework/interface/EDAnalyzer.h"
00043 #include "FWCore/Framework/interface/Event.h"
00044 #include "FWCore/Framework/interface/MakerMacros.h"
00045 #include "FWCore/Framework/interface/ESHandle.h"
00046 #include "FWCore/Utilities/interface/InputTag.h"
00047 #include "FWCore/ParameterSet/interface/ParameterSet.h"
00048 #include "FWCore/ServiceRegistry/interface/Service.h"
00049 #include "CommonTools/UtilAlgos/interface/TFileService.h"
00050 #include "CommonTools/TrackerMap/interface/TrackerMap.h"
00051 #include <CondFormats/SiStripObjects/interface/FedChannelConnection.h>
00052 #include <CondFormats/SiStripObjects/interface/SiStripFedCabling.h>
00053 #include <CondFormats/DataRecord/interface/SiStripFedCablingRcd.h>
00054 #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h"
00055 #include "Geometry/Records/interface/TrackerDigiGeometryRecord.h"
00056 #include "Geometry/CommonDetUnit/interface/GeomDetType.h"
00057 #include "Geometry/CommonDetUnit/interface/GeomDetUnit.h"
00058 #include <Geometry/CommonTopologies/interface/Topology.h>
00059 #include <Geometry/CommonTopologies/interface/StripTopology.h>
00060 #include <Geometry/TrackerGeometryBuilder/interface/PixelGeomDetUnit.h>
00061 #include <Geometry/CommonTopologies/interface/PixelTopology.h>
00062 #include "DataFormats/Common/interface/Ref.h"
00063 #include "DataFormats/DetId/interface/DetId.h"
00064 #include "DataFormats/SiStripCluster/interface/SiStripCluster.h"
00065 #include "DataFormats/TrackerRecHit2D/interface/SiStripRecHit2DCollection.h"
00066 #include "DataFormats/TrackerRecHit2D/interface/SiStripMatchedRecHit2DCollection.h"
00067 #include "DataFormats/GeometryVector/interface/LocalVector.h"
00068 #include "DataFormats/SiStripCommon/interface/SiStripEventSummary.h"
00069 #include <DataFormats/TrackerRecHit2D/interface/SiPixelRecHit.h>
00070 #include <DataFormats/SiStripDetId/interface/SiStripDetId.h>
00071 #include <DataFormats/SiStripDetId/interface/TIBDetId.h>
00072 #include <DataFormats/SiStripDetId/interface/TIDDetId.h>
00073 #include <DataFormats/SiStripDetId/interface/TOBDetId.h>
00074 #include <DataFormats/SiStripDetId/interface/TECDetId.h>
00075 #include <DataFormats/SiPixelCluster/interface/SiPixelCluster.h>
00076 #include <DataFormats/TrackReco/interface/TrackFwd.h>
00077 #include <DataFormats/TrackReco/interface/Track.h>
00078 #include "DataFormats/TrackReco/interface/DeDxData.h"
00079 #include <DataFormats/TrackerRecHit2D/interface/SiTrackerMultiRecHit.h>
00080 #include <DataFormats/TrackerRecHit2D/interface/SiStripRecHit2D.h>
00081 #include <DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerReadoutRecord.h>
00082 #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerReadoutSetupFwd.h"
00083 #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerReadoutSetup.h"
00084 #include <DataFormats/L1GlobalTrigger/interface/L1GtFdlWord.h>
00085 #include <DataFormats/Common/interface/TriggerResults.h>
00086 #include "DataFormats/VertexReco/interface/Vertex.h"
00087 #include "DataFormats/VertexReco/interface/VertexFwd.h"  
00088 #include "DataFormats/BeamSpot/interface/BeamSpot.h"
00089 #include "HLTrigger/HLTcore/interface/HLTConfigProvider.h"
00090 #include <MagneticField/Engine/interface/MagneticField.h>
00091 #include <MagneticField/Records/interface/IdealMagneticFieldRecord.h>
00092 #include <RecoTracker/TransientTrackingRecHit/interface/TSiStripRecHit2DLocalPos.h>
00093 #include <RecoTracker/TransientTrackingRecHit/interface/TSiTrackerMultiRecHit.h>
00094 #include <RecoTracker/TransientTrackingRecHit/interface/TSiPixelRecHit.h>
00095 #include <RecoTracker/TransientTrackingRecHit/interface/TSiStripRecHit1D.h>
00096 #include "RecoVertex/VertexPrimitives/interface/TransientVertex.h"
00097 #include <TrackingTools/TransientTrackingRecHit/interface/TransientTrackingRecHit.h>
00098 #include <TrackingTools/PatternTools/interface/Trajectory.h>
00099 #include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h"
00100 #include "TrackingTools/PatternTools/interface/TrajTrackAssociation.h"
00101 #include <RecoLocalTracker/SiStripClusterizer/interface/SiStripClusterInfo.h>
00102 
00103 // topology
00104 #include "DPGAnalysis/SiStripTools/interface/EventShape.h"
00105 
00106 //
00107 // class decleration
00108 //
00109 typedef math::XYZPoint Point;
00110 
00111 class TrackerDpgAnalysis : public edm::EDAnalyzer {
00112    public:
00113       explicit TrackerDpgAnalysis(const edm::ParameterSet&);
00114       ~TrackerDpgAnalysis();
00115 
00116    protected:
00117       std::vector<double> onTrackAngles(edm::Handle<edmNew::DetSetVector<SiStripCluster> >&,const std::vector<Trajectory>& );
00118       void insertMeasurement(std::multimap<const uint32_t,std::pair<LocalPoint,double> >&, const TransientTrackingRecHit*,double);
00119       std::vector<int> onTrack(edm::Handle<edmNew::DetSetVector<SiStripCluster> >&,const reco::TrackCollection&, uint32_t );
00120       void insertMeasurement(std::multimap<const uint32_t,std::pair<int,int> >&, const TrackingRecHit*,int);
00121       std::map<size_t,int> inVertex(const reco::TrackCollection&, const reco::VertexCollection&, uint32_t);
00122       std::vector<std::pair<double,double> > onTrackAngles(edm::Handle<edmNew::DetSetVector<SiPixelCluster> >&,const std::vector<Trajectory>& );
00123       void insertMeasurement(std::multimap<const uint32_t,std::pair<LocalPoint,std::pair<double,double> > >&, const TransientTrackingRecHit*,double,double);
00124       std::vector<int> onTrack(edm::Handle<edmNew::DetSetVector<SiPixelCluster> >&,const reco::TrackCollection&, uint32_t );
00125       void insertMeasurement(std::multimap<const uint32_t,std::pair<std::pair<float, float>,int> >&, const TrackingRecHit*,int);
00126       std::string toStringName(uint32_t);
00127       std::string toStringId(uint32_t);
00128       double sumPtSquared(const reco::Vertex&);
00129       float delay(const SiStripEventSummary&);
00130       std::map<uint32_t,float> delay(const std::vector<std::string>&);
00131 
00132    private:
00133       virtual void beginRun(const edm::Run&, const edm::EventSetup&);
00134       virtual void analyze(const edm::Event&, const edm::EventSetup&);
00135       virtual void endJob() ;
00136 
00137       // ----------member data ---------------------------
00138       static const int nMaxPVs_ = 50;
00139       edm::InputTag clusterLabel_, pixelclusterLabel_, dedx1Label_, dedx2Label_, dedx3Label_, pixelVertexLabel_, 
00140                     vertexLabel_, bsLabel_, L1Label_, HLTLabel_;
00141       std::vector<edm::InputTag> trackLabel_;
00142       edm::ESHandle<SiStripFedCabling> cabling_;
00143       edm::ESHandle<TrackerGeometry> tracker_;
00144       std::multimap<const uint32_t,const FedChannelConnection*> connections_;
00145       bool functionality_offtrackClusters_, functionality_ontrackClusters_, functionality_pixclusters_, functionality_pixvertices_, 
00146            functionality_missingHits_, functionality_tracks_, functionality_vertices_, functionality_events_;
00147       TTree* clusters_;
00148       TTree* pixclusters_;
00149       std::vector<TTree*> tracks_;
00150       std::vector<TTree*> missingHits_;
00151       TTree* vertices_;
00152       TTree* pixelVertices_;
00153       TTree* event_;
00154       TTree* psumap_;
00155       TTree* readoutmap_;
00156       bool onTrack_;
00157       uint32_t vertexid_, eventid_, runid_;
00158       uint32_t globalvertexid_;
00159       uint32_t *globaltrackid_, *trackid_;
00160       float globalX_, globalY_, globalZ_;
00161       float measX_, measY_, errorX_, errorY_;
00162       float angle_, maxCharge_;
00163       float clCorrectedCharge_, clCorrectedSignalOverNoise_;
00164       float clNormalizedCharge_, clNormalizedNoise_, clSignalOverNoise_;
00165       float clBareNoise_, clBareCharge_;
00166       float clWidth_, clPosition_, thickness_, stripLength_, distance_;
00167       float eta_, phi_, chi2_;
00168       float dedx1_, dedx2_, dedx3_;
00169       uint32_t detid_, dcuId_, type_;
00170       uint16_t fecCrate_, fecSlot_, fecRing_, ccuAdd_, ccuChan_, lldChannel_, fedId_, fedCh_, fiberLength_;
00171       uint32_t nclusters_, npixClusters_, nclustersOntrack_, npixClustersOntrack_, dedxNoM_, quality_, foundhits_, lostHits_, ndof_;
00172       uint32_t *ntracks_, *ntrajs_;
00173       float *lowPixelProbabilityFraction_;
00174       uint32_t nVertices_, nPixelVertices_, nLayers_,foundhitsStrips_,foundhitsPixels_,losthitsStrips_,losthitsPixels_;
00175       uint32_t nTracks_pvtx_;
00176       uint32_t clSize_, clSizeX_, clSizeY_;
00177       float fBz_, clPositionX_, clPositionY_, alpha_, beta_, chargeCorr_;
00178       float recx_pvtx_, recy_pvtx_, recz_pvtx_,
00179             recx_err_pvtx_, recy_err_pvtx_, recz_err_pvtx_, sumptsq_pvtx_;
00180       float pterr_, etaerr_, phierr_;
00181       float dz_, dzerr_, dzCorr_, dxy_, dxyerr_, dxyCorr_;
00182       float qoverp_, xPCA_, yPCA_, zPCA_, trkWeightpvtx_;
00183       bool isValid_pvtx_, isFake_pvtx_;
00184       float charge_, p_, pt_;
00185       float bsX0_, bsY0_, bsZ0_, bsSigmaZ_, bsDxdz_, bsDydz_;
00186       float thrustValue_, thrustX_, thrustY_, thrustZ_, sphericity_, planarity_, aplanarity_, delay_;
00187       bool L1DecisionBits_[192], L1TechnicalBits_[64], HLTDecisionBits_[256];
00188       uint32_t orbit_, orbitL1_, bx_, store_, time_;
00189       uint16_t lumiSegment_, physicsDeclared_;
00190       char *moduleName_, *moduleId_, *PSUname_;
00191       std::string cablingFileName_;
00192       std::vector<std::string> delayFileNames_;
00193       edm::ParameterSet pset_;
00194       std::vector<std::string>  hlNames_;  // name of each HLT algorithm
00195       HLTConfigProvider hltConfig_;        // to get configuration for L1s/Pre
00196 
00197 };
00198 
00199 //
00200 // constructors and destructor
00201 //
00202 TrackerDpgAnalysis::TrackerDpgAnalysis(const edm::ParameterSet& iConfig):hltConfig_()
00203 {
00204    // members
00205    moduleName_ = new char[256];
00206    moduleId_   = new char[256];
00207    PSUname_    = new char[256];
00208    pset_ = iConfig;
00209 
00210    // enable/disable functionalities
00211    functionality_offtrackClusters_ = iConfig.getUntrackedParameter<bool>("keepOfftrackClusters",true);
00212    functionality_ontrackClusters_  = iConfig.getUntrackedParameter<bool>("keepOntrackClusters",true);
00213    functionality_pixclusters_      = iConfig.getUntrackedParameter<bool>("keepPixelClusters",true);
00214    functionality_pixvertices_      = iConfig.getUntrackedParameter<bool>("keepPixelVertices",true);
00215    functionality_missingHits_      = iConfig.getUntrackedParameter<bool>("keepMissingHits",true);
00216    functionality_tracks_           = iConfig.getUntrackedParameter<bool>("keepTracks",true);
00217    functionality_vertices_         = iConfig.getUntrackedParameter<bool>("keepVertices",true);
00218    functionality_events_           = iConfig.getUntrackedParameter<bool>("keepEvents",true);
00219 
00220    // parameters
00221    clusterLabel_      = iConfig.getParameter<edm::InputTag>("ClustersLabel");
00222    pixelclusterLabel_ = iConfig.getParameter<edm::InputTag>("PixelClustersLabel");
00223    trackLabel_        = iConfig.getParameter<std::vector<edm::InputTag> >("TracksLabel");
00224    dedx1Label_        = iConfig.getParameter<edm::InputTag>("DeDx1Label");
00225    dedx2Label_        = iConfig.getParameter<edm::InputTag>("DeDx2Label");
00226    dedx3Label_        = iConfig.getParameter<edm::InputTag>("DeDx3Label");
00227    vertexLabel_       = iConfig.getParameter<edm::InputTag>("vertexLabel");
00228    pixelVertexLabel_  = iConfig.getParameter<edm::InputTag>("pixelVertexLabel");
00229    bsLabel_           = iConfig.getParameter<edm::InputTag>("beamSpotLabel");
00230    L1Label_           = iConfig.getParameter<edm::InputTag>("L1Label");
00231    HLTLabel_          = iConfig.getParameter<edm::InputTag>("HLTLabel");
00232 
00233    // initialize arrays
00234    ntracks_ = new uint32_t[trackLabel_.size()];
00235    ntrajs_ = new uint32_t[trackLabel_.size()];
00236    globaltrackid_  = new uint32_t[trackLabel_.size()];
00237    trackid_ = new uint32_t[trackLabel_.size()];
00238    lowPixelProbabilityFraction_ = new float[trackLabel_.size()];
00239    globalvertexid_ = iConfig.getParameter<uint32_t>("InitalCounter");
00240    for(size_t i = 0; i<trackLabel_.size();++i) { 
00241      ntracks_[i]=0; 
00242      ntrajs_[i]=0; 
00243      globaltrackid_[i]=iConfig.getParameter<uint32_t>("InitalCounter"); 
00244      trackid_[i]=0;
00245      lowPixelProbabilityFraction_[i]=0;
00246    }
00247 
00248    // create output
00249    edm::Service<TFileService> fileService;
00250    TFileDirectory* dir = new TFileDirectory(fileService->mkdir("trackerDPG"));
00251    
00252    // create a TTree for clusters
00253    clusters_ = dir->make<TTree>("clusters","cluster information");
00254    clusters_->Branch("eventid",&eventid_,"eventid/i");
00255    clusters_->Branch("runid",&runid_,"runid/i");
00256    for(size_t i = 0; i<trackLabel_.size(); ++i) {
00257      char buffer1[256];
00258      char buffer2[256];
00259      sprintf(buffer1,"trackid%lu",(unsigned long)i);
00260      sprintf(buffer2,"trackid%lu/i",(unsigned long)i);
00261      clusters_->Branch(buffer1,trackid_+i,buffer2);
00262    }
00263    clusters_->Branch("onTrack",&onTrack_,"onTrack/O");
00264    clusters_->Branch("clWidth",&clWidth_,"clWidth/F");
00265    clusters_->Branch("clPosition",&clPosition_,"clPosition/F");
00266    clusters_->Branch("clglobalX",&globalX_,"clglobalX/F");
00267    clusters_->Branch("clglobalY",&globalY_,"clglobalY/F");
00268    clusters_->Branch("clglobalZ",&globalZ_,"clglobalZ/F");
00269    clusters_->Branch("angle",&angle_,"angle/F");
00270    clusters_->Branch("thickness",&thickness_,"thickness/F");
00271    clusters_->Branch("maxCharge",&maxCharge_,"maxCharge/F");
00272    clusters_->Branch("clNormalizedCharge",&clNormalizedCharge_,"clNormalizedCharge/F");
00273    clusters_->Branch("clNormalizedNoise",&clNormalizedNoise_,"clNormalizedNoise/F");
00274    clusters_->Branch("clSignalOverNoise",&clSignalOverNoise_,"clSignalOverNoise/F");
00275    clusters_->Branch("clCorrectedCharge",&clCorrectedCharge_,"clCorrectedCharge/F");
00276    clusters_->Branch("clCorrectedSignalOverNoise",&clCorrectedSignalOverNoise_,"clCorrectedSignalOverNoise/F");
00277    clusters_->Branch("clBareCharge",&clBareCharge_,"clBareCharge/F");
00278    clusters_->Branch("clBareNoise",&clBareNoise_,"clBareNoise/F");
00279    clusters_->Branch("stripLength",&stripLength_,"stripLength/F");
00280    clusters_->Branch("detid",&detid_,"detid/i");
00281    clusters_->Branch("lldChannel",&lldChannel_,"lldChannel/s");
00282 
00283    // create a TTree for pixel clusters
00284    pixclusters_ = dir->make<TTree>("pixclusters","pixel cluster information");
00285    pixclusters_->Branch("eventid",&eventid_,"eventid/i");
00286    pixclusters_->Branch("runid",&runid_,"runid/i");
00287    for(size_t i = 0; i<trackLabel_.size(); ++i) {
00288      char buffer1[256];
00289      char buffer2[256];
00290      sprintf(buffer1,"trackid%lu",(unsigned long)i);
00291      sprintf(buffer2,"trackid%lu/i",(unsigned long)i);
00292      pixclusters_->Branch(buffer1,trackid_+i,buffer2);
00293    }
00294    pixclusters_->Branch("onTrack",&onTrack_,"onTrack/O");
00295    pixclusters_->Branch("clPositionX",&clPositionX_,"clPositionX/F");
00296    pixclusters_->Branch("clPositionY",&clPositionY_,"clPositionY/F");
00297    pixclusters_->Branch("clSize",&clSize_,"clSize/i");
00298    pixclusters_->Branch("clSizeX",&clSizeX_,"clSizeX/i");
00299    pixclusters_->Branch("clSizeY",&clSizeY_,"clSizeY/i");
00300    pixclusters_->Branch("alpha",&alpha_,"alpha/F");
00301    pixclusters_->Branch("beta",&beta_,"beta/F");
00302    pixclusters_->Branch("charge",&charge_,"charge/F");
00303    pixclusters_->Branch("chargeCorr",&chargeCorr_,"chargeCorr/F");
00304    pixclusters_->Branch("clglobalX",&globalX_,"clglobalX/F");
00305    pixclusters_->Branch("clglobalY",&globalY_,"clglobalY/F");
00306    pixclusters_->Branch("clglobalZ",&globalZ_,"clglobalZ/F");
00307    pixclusters_->Branch("detid",&detid_,"detid/i");
00308    
00309    // create a tree for tracks
00310    for(size_t i = 0; i<trackLabel_.size(); ++i) {
00311      char buffer1[256];
00312      char buffer2[256];
00313      sprintf(buffer1,"tracks%lu",(unsigned long)i);
00314      sprintf(buffer2,"track%lu information",(unsigned long)i);
00315      TTree* thetracks_ = dir->make<TTree>(buffer1,buffer2);
00316      sprintf(buffer1,"trackid%lu",(unsigned long)i);
00317      sprintf(buffer2,"trackid%lu/i",(unsigned long)i);
00318      thetracks_->Branch(buffer1,globaltrackid_+i,buffer2);
00319      thetracks_->Branch("eventid",&eventid_,"eventid/i");
00320      thetracks_->Branch("runid",&runid_,"runid/i");
00321      thetracks_->Branch("chi2",&chi2_,"chi2/F");
00322      thetracks_->Branch("eta",&eta_,"eta/F");
00323      thetracks_->Branch("etaerr",&etaerr_,"etaerr/F");
00324      thetracks_->Branch("phi",&phi_,"phi/F");
00325      thetracks_->Branch("phierr",&phierr_,"phierr/F");
00326      thetracks_->Branch("dedx1",&dedx1_,"dedx1/F");
00327      thetracks_->Branch("dedx2",&dedx2_,"dedx2/F");
00328      thetracks_->Branch("dedx3",&dedx3_,"dedx3/F");
00329      thetracks_->Branch("dedxNoM",&dedxNoM_,"dedxNoM/i");
00330      thetracks_->Branch("charge",&charge_,"charge/F");
00331      thetracks_->Branch("quality",&quality_,"quality/i");
00332      thetracks_->Branch("foundhits",&foundhits_,"foundhits/i");
00333      thetracks_->Branch("lostHits",&lostHits_,"lostHits/i");
00334      thetracks_->Branch("foundhitsStrips",&foundhitsStrips_,"foundhitsStrips/i");
00335      thetracks_->Branch("foundhitsPixels",&foundhitsPixels_,"foundhitsPixels/i");
00336      thetracks_->Branch("losthitsStrips",&losthitsStrips_,"losthitsStrips/i");
00337      thetracks_->Branch("losthitsPixels",&losthitsPixels_,"losthitsPixels/i");
00338      thetracks_->Branch("p",&p_,"p/F");
00339      thetracks_->Branch("pt",&pt_,"pt/F");
00340      thetracks_->Branch("pterr",&pterr_,"pterr/F");
00341      thetracks_->Branch("ndof",&ndof_,"ndof/i");
00342      thetracks_->Branch("dz",&dz_,"dz/F");
00343      thetracks_->Branch("dzerr",&dzerr_,"dzerr/F");
00344      thetracks_->Branch("dzCorr",&dzCorr_,"dzCorr/F");
00345      thetracks_->Branch("dxy",&dxy_,"dxy/F");
00346      thetracks_->Branch("dxyerr",&dxyerr_,"dxyerr/F");
00347      thetracks_->Branch("dxyCorr",&dxyCorr_,"dxyCorr/F");
00348      thetracks_->Branch("qoverp",&qoverp_,"qoverp/F");
00349      thetracks_->Branch("xPCA",&xPCA_,"xPCA/F");
00350      thetracks_->Branch("yPCA",&yPCA_,"yPCA/F");
00351      thetracks_->Branch("zPCA",&zPCA_,"zPCA/F");
00352      thetracks_->Branch("nLayers",&nLayers_,"nLayers/i");
00353      thetracks_->Branch("trkWeightpvtx",&trkWeightpvtx_,"trkWeightpvtx/F");
00354      thetracks_->Branch("vertexid",&vertexid_,"vertexid/i");
00355      tracks_.push_back(thetracks_);
00356    }
00357 
00358    // create a tree for missing hits
00359    for(size_t i = 0; i<trackLabel_.size(); ++i) {
00360      char buffer1[256];
00361      char buffer2[256];
00362      sprintf(buffer1,"misingHits%lu",(unsigned long)i);
00363      sprintf(buffer2,"missing hits from track collection %lu",(unsigned long)i);
00364      TTree* themissingHits_ = dir->make<TTree>(buffer1,buffer2);
00365      sprintf(buffer1,"trackid%lu",(unsigned long)i);
00366      sprintf(buffer2,"trackid%lu/i",(unsigned long)i);
00367      themissingHits_->Branch(buffer1,globaltrackid_+i,buffer2);
00368      themissingHits_->Branch("eventid",&eventid_,"eventid/i");
00369      themissingHits_->Branch("runid",&runid_,"runid/i");
00370      themissingHits_->Branch("detid",&detid_,"detid/i");
00371      themissingHits_->Branch("type",&type_,"type/i");
00372      themissingHits_->Branch("localX",&clPositionX_,"localX/F");
00373      themissingHits_->Branch("localY",&clPositionY_,"localY/F");
00374      themissingHits_->Branch("globalX",&globalX_,"globalX/F");
00375      themissingHits_->Branch("globalY",&globalY_,"globalY/F");
00376      themissingHits_->Branch("globalZ",&globalZ_,"globalZ/F");
00377      themissingHits_->Branch("measX",&measX_,"measX/F");
00378      themissingHits_->Branch("measY",&measY_,"measY/F");
00379      themissingHits_->Branch("errorX",&errorX_,"errorX/F");
00380      themissingHits_->Branch("errorY",&errorY_,"errorY/F");
00381      missingHits_.push_back(themissingHits_);
00382    }
00383 
00384    // create a tree for the vertices
00385    vertices_ = dir->make<TTree>("vertices","vertex information");
00386    vertices_->Branch("vertexid",&globalvertexid_,"vertexid/i");
00387    vertices_->Branch("eventid",&eventid_,"eventid/i");
00388    vertices_->Branch("runid",&runid_,"runid/i");
00389    vertices_->Branch("nTracks",&nTracks_pvtx_,"nTracks/i");
00390    vertices_->Branch("sumptsq",&sumptsq_pvtx_,"sumptsq/F");
00391    vertices_->Branch("isValid",&isValid_pvtx_,"isValid/O");
00392    vertices_->Branch("isFake",&isFake_pvtx_,"isFake/O");
00393    vertices_->Branch("recx",&recx_pvtx_,"recx/F");
00394    vertices_->Branch("recy",&recy_pvtx_,"recy/F");
00395    vertices_->Branch("recz",&recz_pvtx_,"recz/F");
00396    vertices_->Branch("recx_err",&recx_err_pvtx_,"recx_err/F");
00397    vertices_->Branch("recy_err",&recy_err_pvtx_,"recy_err/F");
00398    vertices_->Branch("recz_err",&recz_err_pvtx_,"recz_err/F");
00399 
00400    // create a tree for the vertices
00401    pixelVertices_ = dir->make<TTree>("pixelVertices","pixel vertex information");
00402    pixelVertices_->Branch("eventid",&eventid_,"eventid/i");
00403    pixelVertices_->Branch("runid",&runid_,"runid/i");
00404    pixelVertices_->Branch("nTracks",&nTracks_pvtx_,"nTracks/i");
00405    pixelVertices_->Branch("sumptsq",&sumptsq_pvtx_,"sumptsq/F");
00406    pixelVertices_->Branch("isValid",&isValid_pvtx_,"isValid/O");
00407    pixelVertices_->Branch("isFake",&isFake_pvtx_,"isFake/O");
00408    pixelVertices_->Branch("recx",&recx_pvtx_,"recx/F");
00409    pixelVertices_->Branch("recy",&recy_pvtx_,"recy/F");
00410    pixelVertices_->Branch("recz",&recz_pvtx_,"recz/F");
00411    pixelVertices_->Branch("recx_err",&recx_err_pvtx_,"recx_err/F");
00412    pixelVertices_->Branch("recy_err",&recy_err_pvtx_,"recy_err/F");
00413    pixelVertices_->Branch("recz_err",&recz_err_pvtx_,"recz_err/F");
00414 
00415    // create a tree for the events
00416    event_ = dir->make<TTree>("events","event information");
00417    event_->Branch("eventid",&eventid_,"eventid/i");
00418    event_->Branch("runid",&runid_,"runid/i");
00419    event_->Branch("L1DecisionBits",L1DecisionBits_,"L1DecisionBits[192]/O");
00420    event_->Branch("L1TechnicalBits",L1TechnicalBits_,"L1TechnicalBits[64]/O");
00421    event_->Branch("orbit",&orbit_,"orbit/i");
00422    event_->Branch("orbitL1",&orbitL1_,"orbitL1/i");
00423    event_->Branch("bx",&bx_,"bx/i");
00424    event_->Branch("store",&store_,"store/i");
00425    event_->Branch("time",&time_,"time/i");
00426    event_->Branch("delay",&delay_,"delay/F");
00427    event_->Branch("lumiSegment",&lumiSegment_,"lumiSegment/s");
00428    event_->Branch("physicsDeclared",&physicsDeclared_,"physicsDeclared/s");
00429    event_->Branch("HLTDecisionBits",HLTDecisionBits_,"HLTDecisionBits[256]/O");
00430    char buffer[256];
00431    sprintf(buffer,"ntracks[%lu]/i",(unsigned long)trackLabel_.size());
00432    event_->Branch("ntracks",ntracks_,buffer);
00433    sprintf(buffer,"ntrajs[%lu]/i",(unsigned long)trackLabel_.size());
00434    event_->Branch("ntrajs",ntrajs_,buffer);
00435    sprintf(buffer,"lowPixelProbabilityFraction[%lu]/F",(unsigned long)trackLabel_.size());
00436    event_->Branch("lowPixelProbabilityFraction",lowPixelProbabilityFraction_,buffer);
00437    event_->Branch("nclusters",&nclusters_,"nclusters/i");
00438    event_->Branch("npixClusters",&npixClusters_,"npixClusters/i");
00439    event_->Branch("nclustersOntrack",&nclustersOntrack_,"nclustersOntrack/i");
00440    event_->Branch("npixClustersOntrack",&npixClustersOntrack_,"npixClustersOntrack/i");
00441    event_->Branch("bsX0",&bsX0_,"bsX0/F");
00442    event_->Branch("bsY0",&bsY0_,"bsY0/F");
00443    event_->Branch("bsZ0",&bsZ0_,"bsZ0/F");
00444    event_->Branch("bsSigmaZ",&bsSigmaZ_,"bsSigmaZ/F");
00445    event_->Branch("bsDxdz",&bsDxdz_,"bsDxdz/F");
00446    event_->Branch("bsDydz",&bsDydz_,"bsDydz/F");
00447    event_->Branch("nVertices",&nVertices_,"nVertices/i");
00448    event_->Branch("thrustValue",&thrustValue_,"thrustValue/F");
00449    event_->Branch("thrustX",&thrustX_,"thrustX/F");
00450    event_->Branch("thrustY",&thrustY_,"thrustY/F");
00451    event_->Branch("thrustZ",&thrustZ_,"thrustZ/F");
00452    event_->Branch("sphericity",&sphericity_,"sphericity/F");
00453    event_->Branch("planarity",&planarity_,"planarity/F");
00454    event_->Branch("aplanarity",&aplanarity_,"aplanarity/F");
00455    event_->Branch("MagneticField",&fBz_,"MagneticField/F");
00456    
00457    // cabling
00458    cablingFileName_ = iConfig.getUntrackedParameter<std::string>("PSUFileName","PSUmapping.csv");
00459    delayFileNames_  = iConfig.getUntrackedParameter<std::vector<std::string> >("DelayFileNames",std::vector<std::string>(0));
00460    psumap_ = dir->make<TTree>("psumap","PSU map");
00461    psumap_->Branch("PSUname",PSUname_,"PSUname/C");
00462    psumap_->Branch("dcuId",&dcuId_,"dcuId/i");
00463    readoutmap_ = dir->make<TTree>("readoutMap","cabling map");
00464    readoutmap_->Branch("detid",&detid_,"detid/i");
00465    readoutmap_->Branch("dcuId",&dcuId_,"dcuId/i");
00466    readoutmap_->Branch("fecCrate",&fecCrate_,"fecCrate/s");
00467    readoutmap_->Branch("fecSlot",&fecSlot_,"fecSlot/s");
00468    readoutmap_->Branch("fecRing",&fecRing_,"fecRing/s");
00469    readoutmap_->Branch("ccuAdd",&ccuAdd_,"ccuAdd/s");
00470    readoutmap_->Branch("ccuChan",&ccuChan_,"ccuChan/s");
00471    readoutmap_->Branch("lldChannel",&lldChannel_,"lldChannel/s");
00472    readoutmap_->Branch("fedId",&fedId_,"fedId/s");
00473    readoutmap_->Branch("fedCh",&fedCh_,"fedCh/s");
00474    readoutmap_->Branch("fiberLength",&fiberLength_,"fiberLength/s");
00475    readoutmap_->Branch("moduleName",moduleName_,"moduleName/C");
00476    readoutmap_->Branch("moduleId",moduleId_,"moduleId/C");
00477    readoutmap_->Branch("delay",&delay_,"delay/F");
00478    readoutmap_->Branch("globalX",&globalX_,"globalX/F");
00479    readoutmap_->Branch("globalY",&globalY_,"globalY/F");
00480    readoutmap_->Branch("globalZ",&globalZ_,"globalZ/F");
00481 }
00482 
00483 TrackerDpgAnalysis::~TrackerDpgAnalysis()
00484 {
00485   delete[] moduleName_;
00486   delete[] moduleId_;
00487 }
00488 
00489 //
00490 // member functions
00491 //
00492 
00493 // ------------ method called to for each event  ------------
00494 void
00495 TrackerDpgAnalysis::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup)
00496 {
00497    using namespace edm;
00498    using namespace reco;
00499    using namespace std;
00500    using reco::TrackCollection;
00501    
00502    // load event info
00503    eventid_     = iEvent.id().event();
00504    runid_       = iEvent.id().run();
00505    bx_          = iEvent.eventAuxiliary().bunchCrossing();
00506    orbit_       = iEvent.eventAuxiliary().orbitNumber();
00507    store_       = iEvent.eventAuxiliary().storeNumber();
00508    time_        = iEvent.eventAuxiliary().time().value();
00509    lumiSegment_ = iEvent.eventAuxiliary().luminosityBlock();
00510 
00511    // Retrieve commissioning information from "event summary", when available (for standard fine delay)
00512    edm::Handle<SiStripEventSummary> summary;
00513    iEvent.getByLabel( "siStripDigis", summary );
00514    if(summary.isValid())
00515      delay_ = delay(*summary.product());
00516    else
00517      delay_ = 0.;
00518 
00519    // -- Magnetic field
00520    ESHandle<MagneticField> MF;
00521    iSetup.get<IdealMagneticFieldRecord>().get(MF);
00522    const MagneticField* theMagneticField = MF.product();
00523    fBz_   = fabs(theMagneticField->inTesla(GlobalPoint(0,0,0)).z());
00524 
00525    // load trigger info
00526    edm::Handle<L1GlobalTriggerReadoutRecord> gtrr_handle;
00527    iEvent.getByLabel(L1Label_, gtrr_handle);
00528    L1GlobalTriggerReadoutRecord const* gtrr = gtrr_handle.product();
00529    L1GtFdlWord fdlWord = gtrr->gtFdlWord();
00530    DecisionWord L1decision = fdlWord.gtDecisionWord();
00531    for(int bit=0;bit<128;++bit) {
00532      L1DecisionBits_[bit] = L1decision[bit];
00533    }
00534    DecisionWordExtended L1decisionE = fdlWord.gtDecisionWordExtended();
00535    for(int bit=0;bit<64;++bit) {
00536      L1DecisionBits_[bit+128] = L1decisionE[bit];
00537    }
00538    TechnicalTriggerWord L1technical = fdlWord.gtTechnicalTriggerWord();
00539    for(int bit=0;bit<64;++bit) {
00540      L1TechnicalBits_[bit] = L1technical[bit];
00541    }
00542    orbitL1_ = fdlWord.orbitNr();
00543    physicsDeclared_ = fdlWord.physicsDeclared();
00544    edm::Handle<edm::TriggerResults> trh;
00545    iEvent.getByLabel(HLTLabel_, trh);
00546    size_t ntrh = trh->size();
00547    for(size_t bit=0;bit<256;++bit)
00548      HLTDecisionBits_[bit] = bit<ntrh ? (bool)(trh->accept(bit)): false;
00549      
00550    // load beamspot
00551    edm::Handle<reco::BeamSpot> recoBeamSpotHandle;
00552    iEvent.getByLabel(bsLabel_,recoBeamSpotHandle);
00553    reco::BeamSpot bs = *recoBeamSpotHandle; 
00554    const Point beamSpot = recoBeamSpotHandle.isValid() ? 
00555                            Point(recoBeamSpotHandle->x0(), recoBeamSpotHandle->y0(), recoBeamSpotHandle->z0()) : 
00556                            Point(0, 0, 0);
00557    if(recoBeamSpotHandle.isValid()) {
00558      bsX0_ = bs.x0();
00559      bsY0_ = bs.y0();
00560      bsZ0_ = bs.z0();
00561      bsSigmaZ_ = bs.sigmaZ();
00562      bsDxdz_ = bs.dxdz();
00563      bsDydz_ = bs.dydz();
00564    } else { 
00565      bsX0_ = 0.;
00566      bsY0_ = 0.;
00567      bsZ0_ = 0.;
00568      bsSigmaZ_ = 0.;
00569      bsDxdz_ = 0.;
00570      bsDydz_ = 0.;
00571    }
00572    
00573    // load primary vertex
00574    static const reco::VertexCollection s_empty_vertexColl;
00575    edm::Handle<reco::VertexCollection> vertexCollectionHandle;
00576    iEvent.getByLabel(vertexLabel_,vertexCollectionHandle);
00577    const reco::VertexCollection vertexColl = *(vertexCollectionHandle.product());
00578    nVertices_ = 0;
00579    for(reco::VertexCollection::const_iterator v=vertexColl.begin(); 
00580        v!=vertexColl.end(); ++v) {
00581      if(v->isValid() && !v->isFake()) ++nVertices_;
00582    }
00583 
00584    // load pixel vertices
00585    // Pixel vertices are handled as primary vertices, but not linked to tracks.
00586     edm::Handle<reco::VertexCollection>  pixelVertexCollectionHandle;
00587     iEvent.getByLabel(pixelVertexLabel_, pixelVertexCollectionHandle);
00588     const reco::VertexCollection pixelVertexColl = *(pixelVertexCollectionHandle.product());
00589     nPixelVertices_ = pixelVertexColl.size();
00590    
00591    // load the clusters
00592    edm::Handle<edmNew::DetSetVector<SiStripCluster> > clusters;
00593    iEvent.getByLabel(clusterLabel_,clusters);
00594    edm::Handle<edmNew::DetSetVector<SiPixelCluster> > pixelclusters;
00595    iEvent.getByLabel(pixelclusterLabel_,pixelclusters  );
00596    
00597    // load dedx info
00598    Handle<ValueMap<DeDxData> > dEdx1Handle;
00599    Handle<ValueMap<DeDxData> > dEdx2Handle;
00600    Handle<ValueMap<DeDxData> > dEdx3Handle;
00601    try {iEvent.getByLabel(dedx1Label_, dEdx1Handle);} catch (...) {;}
00602    try {iEvent.getByLabel(dedx2Label_, dEdx2Handle);} catch (...) {;}
00603    try {iEvent.getByLabel(dedx3Label_, dEdx3Handle);} catch (...) {;}
00604    const ValueMap<DeDxData> dEdxTrack1 = *dEdx1Handle.product();
00605    const ValueMap<DeDxData> dEdxTrack2 = *dEdx2Handle.product();
00606    const ValueMap<DeDxData> dEdxTrack3 = *dEdx3Handle.product();
00607    
00608    // load track collections
00609    std::vector<reco::TrackCollection> trackCollection;
00610    std::vector<edm::Handle<reco::TrackCollection> > trackCollectionHandle;
00611    trackCollectionHandle.resize(trackLabel_.size());
00612    size_t index = 0;
00613    for(std::vector<edm::InputTag>::const_iterator label = trackLabel_.begin();label!=trackLabel_.end();++label,++index) {
00614      try {iEvent.getByLabel(*label,trackCollectionHandle[index]);} catch (...) {;}
00615      trackCollection.push_back(*trackCollectionHandle[index].product());
00616      ntracks_[index] = trackCollection[index].size();
00617    }
00618 
00619    // load the trajectory collections
00620    std::vector<std::vector<Trajectory> > trajectoryCollection;
00621    std::vector<edm::Handle<std::vector<Trajectory> > > trajectoryCollectionHandle;
00622    trajectoryCollectionHandle.resize(trackLabel_.size());
00623    index = 0;
00624    for(std::vector<edm::InputTag>::const_iterator label = trackLabel_.begin();label!=trackLabel_.end();++label,++index) {
00625      try {iEvent.getByLabel(*label,trajectoryCollectionHandle[index]);} catch (...) {;}
00626      trajectoryCollection.push_back(*trajectoryCollectionHandle[index].product());
00627      ntrajs_[index] = trajectoryCollection[index].size();
00628    }
00629 
00630    // load the tracks/traj association maps
00631    std::vector<TrajTrackAssociationCollection> TrajToTrackMap;
00632    Handle<TrajTrackAssociationCollection> trajTrackAssociationHandle;
00633    for(std::vector<edm::InputTag>::const_iterator label = trackLabel_.begin();label!=trackLabel_.end();++label) {
00634      try {iEvent.getByLabel(*label,trajTrackAssociationHandle);} catch (...) {;}
00635      TrajToTrackMap.push_back(*trajTrackAssociationHandle.product());
00636    }
00637      
00638    // sanity check
00639    if(!(trackCollection.size()>0 && trajectoryCollection.size()>0)) return;
00640 
00641    // build the reverse map tracks -> vertex
00642    std::vector<std::map<size_t,int> > trackVertices;
00643    for(size_t i=0;i<trackLabel_.size();++i) {
00644      trackVertices.push_back(inVertex(trackCollection[0], vertexColl, globalvertexid_+1));
00645    }
00646 
00647    // iterate over vertices
00648    if(functionality_vertices_) {
00649      for(reco::VertexCollection::const_iterator v=vertexColl.begin(); 
00650          v!=vertexColl.end(); ++v) {
00651        nTracks_pvtx_ = v->tracksSize();        
00652        sumptsq_pvtx_ = sumPtSquared(*v);
00653        isValid_pvtx_ = int(v->isValid());
00654        isFake_pvtx_ =  int(v->isFake());
00655        recx_pvtx_ = v->x();
00656        recy_pvtx_ = v->y();
00657        recz_pvtx_ = v->z();
00658        recx_err_pvtx_ = v->xError();
00659        recy_err_pvtx_ = v->yError();
00660        recz_err_pvtx_ = v->zError();
00661        globalvertexid_++;
00662        vertices_->Fill();
00663      }
00664    }
00665 
00666    // iterate over pixel vertices
00667    if(functionality_pixvertices_) {
00668      for(reco::VertexCollection::const_iterator v=pixelVertexColl.begin(); 
00669          v!=pixelVertexColl.end(); ++v) {
00670        nTracks_pvtx_ = v->tracksSize();        
00671        sumptsq_pvtx_ = sumPtSquared(*v);
00672        isValid_pvtx_ = int(v->isValid());
00673        isFake_pvtx_ =  int(v->isFake());
00674        recx_pvtx_ = v->x();
00675        recy_pvtx_ = v->y();
00676        recz_pvtx_ = v->z();
00677        recx_err_pvtx_ = v->xError();
00678        recy_err_pvtx_ = v->yError();
00679        recz_err_pvtx_ = v->zError();
00680        pixelVertices_->Fill();
00681      }
00682    }
00683 
00684    // determine if each cluster is on a track or not, and record the local angle
00685    // to do this, we use the first track/traj collection
00686    std::vector<double> clusterOntrackAngles = onTrackAngles(clusters,trajectoryCollection[0]);
00687    std::vector<std::pair<double,double> > pixclusterOntrackAngles = onTrackAngles(pixelclusters,trajectoryCollection[0]);
00688    
00689 /*
00690   // iterate over trajectories
00691   // note: when iterating over trajectories, it might be simpler to use the tracks/trajectories association map
00692   for(std::vector<Trajectory>::const_iterator traj = trajVec.begin(); traj< trajVec.end(); ++traj) {
00693   }
00694   // loop over all rechits from trajectories
00695   //iterate over trajectories
00696   for(std::vector<Trajectory>::const_iterator traj = trajVec.begin(); traj< trajVec.end(); ++traj) {
00697     Trajectory::DataContainer measurements = traj->measurements();
00698     // iterate over measurements
00699     for(Trajectory::DataContainer::iterator meas = measurements.begin(); meas!= measurements.end(); ++meas) {
00700     } 
00701   }
00702 */
00703 
00704    // determine if each cluster is on a track or not, and record the trackid
00705    std::vector< std::vector<int> > stripClusterOntrackIndices;
00706    for(size_t i = 0; i<trackLabel_.size(); ++i) {
00707      stripClusterOntrackIndices.push_back(onTrack(clusters,trackCollection[i],globaltrackid_[i]+1));
00708    }
00709    std::vector< std::vector<int> > pixelClusterOntrackIndices;
00710    for(size_t i = 0; i<trackLabel_.size(); ++i) {
00711      pixelClusterOntrackIndices.push_back(onTrack(pixelclusters,trackCollection[i],globaltrackid_[i]+1));
00712    }
00713    nclustersOntrack_    = count_if(stripClusterOntrackIndices[0].begin(),stripClusterOntrackIndices[0].end(),bind2nd(not_equal_to<int>(), -1));
00714    npixClustersOntrack_ = count_if(pixelClusterOntrackIndices[0].begin(),pixelClusterOntrackIndices[0].end(),bind2nd(not_equal_to<int>(), -1));
00715    
00716    // iterate over tracks
00717    for (size_t coll = 0; coll<trackCollection.size(); ++coll) {
00718      uint32_t n_hits_barrel=0;
00719      uint32_t n_hits_lowprob=0;
00720      for(TrajTrackAssociationCollection::const_iterator it = TrajToTrackMap[coll].begin(); it!=TrajToTrackMap[coll].end(); ++it) {
00721        reco::TrackRef itTrack  = it->val;
00722        edm::Ref<std::vector<Trajectory> > traj  = it->key; // bug to find type of the key
00723        eta_   = itTrack->eta();
00724        phi_   = itTrack->phi();
00725        try { // not all track collections have the dedx info... indeed at best one.
00726          dedxNoM_ = dEdxTrack1[itTrack].numberOfMeasurements();
00727          dedx1_ = dEdxTrack1[itTrack].dEdx();
00728          dedx2_ = dEdxTrack2[itTrack].dEdx();
00729          dedx3_ = dEdxTrack3[itTrack].dEdx();
00730        } catch (...) {
00731          dedxNoM_ = 0;
00732          dedx1_ = 0.;
00733          dedx2_ = 0.;
00734          dedx3_ = 0.;
00735        }
00736        charge_ = itTrack->charge();
00737        quality_ = itTrack->qualityMask();
00738        foundhits_ = itTrack->found();
00739        lostHits_  = itTrack->lost();
00740        foundhitsStrips_ = itTrack->hitPattern().numberOfValidStripHits();
00741        foundhitsPixels_ = itTrack->hitPattern().numberOfValidPixelHits();
00742        losthitsStrips_  = itTrack->hitPattern().numberOfLostStripHits();
00743        losthitsPixels_  = itTrack->hitPattern().numberOfLostPixelHits();
00744        p_ = itTrack->p();
00745        pt_ = itTrack->pt();
00746        chi2_  = itTrack->chi2();
00747        ndof_ = (uint32_t)itTrack->ndof();
00748        dz_ = itTrack->dz();
00749        dzerr_ = itTrack->dzError();
00750        dzCorr_ = itTrack->dz(beamSpot);
00751        dxy_ = itTrack->dxy();
00752        dxyerr_ = itTrack->dxyError();
00753        dxyCorr_ = itTrack->dxy(beamSpot);
00754        pterr_ = itTrack->ptError();
00755        etaerr_ = itTrack->etaError();
00756        phierr_ = itTrack->phiError();
00757        qoverp_ = itTrack->qoverp();
00758        xPCA_ = itTrack->vertex().x();
00759        yPCA_ = itTrack->vertex().y();
00760        zPCA_ = itTrack->vertex().z();
00761        nLayers_ = uint32_t(itTrack->hitPattern().trackerLayersWithMeasurement());
00762        try { // only one track collection (at best) is connected to the main vertex
00763          if(vertexColl.size()>0 && !vertexColl.begin()->isFake()) {
00764            trkWeightpvtx_ =  vertexColl.begin()->trackWeight(itTrack);
00765          } else
00766            trkWeightpvtx_ = 0.;
00767        } catch (...) {
00768          trkWeightpvtx_ = 0.;
00769        }
00770        globaltrackid_[coll]++;
00771        std::map<size_t,int>::const_iterator theV = trackVertices[coll].find(itTrack.key());
00772        vertexid_ = (theV!=trackVertices[coll].end()) ? theV->second : 0;
00773        // add missing hits (separate tree, common strip + pixel)
00774        Trajectory::DataContainer const & measurements = traj->measurements();
00775        if(functionality_missingHits_) {
00776          for(Trajectory::DataContainer::const_iterator it = measurements.begin(); it!=measurements.end(); ++it) {
00777            TrajectoryMeasurement::ConstRecHitPointer rechit = it->recHit();
00778            if(!rechit->isValid()) {
00779              // detid
00780              detid_ = rechit->geographicalId();
00781              // status
00782              type_ = rechit->getType();
00783              // position
00784              LocalPoint local = it->predictedState().localPosition();
00785              clPositionX_ = local.x();
00786              clPositionY_ = local.y();
00787              // global position
00788              GlobalPoint global = it->predictedState().globalPosition();
00789              globalX_ = global.x();
00790              globalY_ = global.y();
00791              globalZ_ = global.z();
00792              // position in the measurement frame
00793              measX_ = 0;
00794              measY_ = 0;
00795              if(type_ != TrackingRecHit::inactive ) {
00796                const GeomDetUnit* gdu = static_cast<const GeomDetUnit*>(tracker_->idToDetUnit(detid_));
00797                if(gdu && gdu->type().isTracker()) {
00798                  const Topology& topo = gdu->topology();
00799                  MeasurementPoint meas = topo.measurementPosition(local);
00800                  measX_ = meas.x();
00801                  measY_ = meas.y();
00802                }
00803              }
00804              // local error
00805              LocalError error = it->predictedState().localError().positionError();
00806              errorX_ = error.xx();
00807              errorY_ = error.yy();
00808              // fill
00809              missingHits_[coll]->Fill();
00810            }
00811          }
00812        }
00813        // compute the fraction of low probability pixels... will be added to the event tree
00814        for(trackingRecHit_iterator it = itTrack->recHitsBegin(); it!=itTrack->recHitsEnd(); ++it) {
00815             const TrackingRecHit* hit = &(**it);
00816             const SiPixelRecHit* pixhit = dynamic_cast<const SiPixelRecHit*>(hit);
00817             if(pixhit) {
00818                DetId detId = pixhit->geographicalId();
00819                if(detId.subdetId()==PixelSubdetector::PixelBarrel) {
00820                  ++n_hits_barrel;
00821                  double proba = pixhit->clusterProbability(0);
00822                  if(proba<=0.0) ++n_hits_lowprob;
00823                }
00824             }
00825        }
00826        // fill the track tree
00827        if(functionality_tracks_) tracks_[coll]->Fill();
00828      }
00829      lowPixelProbabilityFraction_[coll] = n_hits_barrel>0 ? (float)n_hits_lowprob/n_hits_barrel : -1.;
00830    }
00831    
00832    // iterate over clusters
00833    nclusters_ = 0;
00834    std::vector<double>::const_iterator angleIt = clusterOntrackAngles.begin();
00835    uint32_t localCounter = 0;
00836    for (edmNew::DetSetVector<SiStripCluster>::const_iterator DSViter=clusters->begin(); DSViter!=clusters->end();DSViter++ ) {
00837      edmNew::DetSet<SiStripCluster>::const_iterator begin=DSViter->begin();
00838      edmNew::DetSet<SiStripCluster>::const_iterator end  =DSViter->end();
00839      uint32_t detid = DSViter->id();
00840      nclusters_ += DSViter->size();
00841      if(functionality_offtrackClusters_||functionality_ontrackClusters_) {
00842        for(edmNew::DetSet<SiStripCluster>::const_iterator iter=begin;iter!=end;++iter,++angleIt,++localCounter) {
00843          SiStripClusterInfo* siStripClusterInfo = new SiStripClusterInfo(*iter,iSetup,detid,std::string("")); //string = quality label
00844          // general quantities
00845          for(size_t i=0; i< trackLabel_.size(); ++i) {
00846            trackid_[i] = stripClusterOntrackIndices[i][localCounter];
00847          }
00848          onTrack_ = (trackid_[0] != (uint32_t)-1);
00849          clWidth_ = siStripClusterInfo->width();
00850          clPosition_ = siStripClusterInfo->baryStrip();
00851          angle_ = *angleIt;
00852          thickness_ =  ((((DSViter->id()>>25)&0x7f)==0xd) ||
00853                        ((((DSViter->id()>>25)&0x7f)==0xe) && (((DSViter->id()>>5)&0x7)>4))) ? 500 : 300;
00854          stripLength_ = static_cast<const StripGeomDetUnit*>(tracker_->idToDet(detid))->specificTopology().stripLength();
00855          int nstrips  = static_cast<const StripGeomDetUnit*>(tracker_->idToDet(detid))->specificTopology().nstrips();
00856          maxCharge_ = siStripClusterInfo->maxCharge();
00857          // signal and noise with gain corrections
00858          clNormalizedCharge_ = siStripClusterInfo->charge() ;
00859          clNormalizedNoise_  = siStripClusterInfo->noiseRescaledByGain() ;
00860          clSignalOverNoise_  = siStripClusterInfo->signalOverNoise() ;
00861          // signal and noise with gain corrections and angle corrections
00862          clCorrectedCharge_ = clNormalizedCharge_ * fabs(cos(angle_)); // corrected for track angle
00863          clCorrectedSignalOverNoise_ = clSignalOverNoise_ * fabs(cos(angle_)); // corrected for track angle
00864          // signal and noise without gain corrections
00865          clBareNoise_  = siStripClusterInfo->noise();
00866          clBareCharge_ = clSignalOverNoise_*clBareNoise_;
00867          // global position
00868          const StripGeomDetUnit* sgdu = static_cast<const StripGeomDetUnit*>(tracker_->idToDet(detid));
00869          Surface::GlobalPoint gp = sgdu->surface().toGlobal(sgdu->specificTopology().localPosition(MeasurementPoint(clPosition_,0)));
00870          globalX_ = gp.x();
00871          globalY_ = gp.y();
00872          globalZ_ = gp.z();
00873          // cabling
00874          detid_ = detid;
00875          lldChannel_ = 1+(int(floor(iter->barycenter()))/256);
00876          if(lldChannel_==2 && nstrips==512) lldChannel_=3;
00877          if((functionality_offtrackClusters_&&!onTrack_)||(functionality_ontrackClusters_&&onTrack_)) clusters_->Fill();
00878          delete siStripClusterInfo;
00879        }
00880      }
00881    }
00882    
00883    // iterate over pixel clusters
00884    npixClusters_ = 0;
00885    std::vector<std::pair<double,double> >::const_iterator pixAngleIt = pixclusterOntrackAngles.begin();
00886    localCounter = 0;
00887    for (edmNew::DetSetVector<SiPixelCluster>::const_iterator DSViter=pixelclusters->begin(); DSViter!=pixelclusters->end();DSViter++ ) {
00888      edmNew::DetSet<SiPixelCluster>::const_iterator begin=DSViter->begin();
00889      edmNew::DetSet<SiPixelCluster>::const_iterator end  =DSViter->end();
00890      uint32_t detid = DSViter->id();
00891      npixClusters_ += DSViter->size();
00892      if(functionality_pixclusters_) {
00893        for(edmNew::DetSet<SiPixelCluster>::const_iterator iter=begin;iter!=end;++iter,++pixAngleIt,++localCounter) {
00894          // general quantities
00895          for(size_t i=0; i< trackLabel_.size(); ++i) {
00896            trackid_[i] = pixelClusterOntrackIndices[i][localCounter];
00897          }
00898          onTrack_ = (trackid_[0] != (uint32_t)-1);
00899          clPositionX_ = iter->x();
00900          clPositionY_ = iter->y();
00901          clSize_  = iter->size();
00902          clSizeX_ = iter->sizeX();
00903          clSizeY_ = iter->sizeY();
00904          alpha_ = pixAngleIt->first;
00905          beta_  = pixAngleIt->second;
00906          charge_ = (iter->charge())/1000.;
00907          chargeCorr_ = charge_ * sqrt( 1.0 / ( 1.0/pow( tan(alpha_), 2 ) + 1.0/pow( tan(beta_), 2 ) + 1.0 ))/1000.;
00908          // global position
00909          const PixelGeomDetUnit* pgdu = static_cast<const PixelGeomDetUnit*>(tracker_->idToDet(detid));
00910          Surface::GlobalPoint gp = pgdu->surface().toGlobal(pgdu->specificTopology().localPosition(MeasurementPoint(clPositionX_,clPositionY_)));
00911          globalX_ = gp.x();
00912          globalY_ = gp.y();
00913          globalZ_ = gp.z();
00914          // cabling
00915          detid_ = detid;
00916          // fill
00917          pixclusters_->Fill();
00918        }
00919      }
00920    }
00921 
00922    // topological quantities - uses the first track collection
00923    EventShape shape(trackCollection[0]);
00924    math::XYZTLorentzVectorF thrust = shape.thrust();
00925    thrustValue_ = thrust.t();
00926    thrustX_ = thrust.x();
00927    thrustY_ = thrust.y();
00928    thrustZ_ = thrust.z();
00929    sphericity_ = shape.sphericity();
00930    planarity_  = shape.planarity();
00931    aplanarity_ = shape.aplanarity();
00932    
00933    // fill event tree
00934    if(functionality_events_) event_->Fill();
00935   
00936 }
00937 
00938 // ------------ method called once each job just before starting event loop  ------------
00939 void 
00940 TrackerDpgAnalysis::beginRun(const edm::Run& iRun, const edm::EventSetup& iSetup)
00941 {
00942 
00943    //geometry
00944    iSetup.get<TrackerDigiGeometryRecord>().get(tracker_);
00945 
00946    //HLT names
00947    bool changed (true);
00948    if (hltConfig_.init(iRun,iSetup,HLTLabel_.process(),changed)) {
00949      if (changed) {
00950        hlNames_=hltConfig_.triggerNames();
00951      }
00952    }
00953    int i=0;
00954    for(std::vector<std::string>::const_iterator it = hlNames_.begin(); it<hlNames_.end();++it) {
00955      std::cout << (i++) << " = " << (*it) << std::endl;
00956    } 
00957 
00958    // read the delay offsets for each device from input files
00959    // this is only for the so-called "random delay" run
00960    std::map<uint32_t,float> delayMap = delay(delayFileNames_);
00961    TrackerMap tmap("Delays");
00962 
00963    // cabling I (readout)
00964    iSetup.get<SiStripFedCablingRcd>().get( cabling_ );
00965    const std::vector< uint16_t > & feds = cabling_->feds() ;
00966    for(std::vector< uint16_t >::const_iterator fedid = feds.begin();fedid<feds.end();++fedid) {
00967      const std::vector< FedChannelConnection > & connections = cabling_->connections(*fedid);
00968      for(std::vector< FedChannelConnection >::const_iterator conn=connections.begin();conn<connections.end();++conn) {
00969        // Fill the "old" map to be used for lookup during analysis
00970        if(conn->isConnected())
00971          connections_.insert(std::make_pair(conn->detId(),new FedChannelConnection(*conn)));
00972        // Fill the standalone tree (once for all)
00973        if(conn->isConnected()) {
00974          detid_ = conn->detId();
00975          strncpy(moduleName_,toStringName(detid_).c_str(),256);
00976          strncpy(moduleId_,toStringId(detid_).c_str(),256);
00977          lldChannel_ = conn->lldChannel();
00978          dcuId_ = conn->dcuId();
00979          fecCrate_ = conn->fecCrate();
00980          fecSlot_ = conn->fecSlot();
00981          fecRing_ = conn->fecRing();
00982          ccuAdd_ = conn->ccuAddr();
00983          ccuChan_ = conn->ccuChan();
00984          fedId_ = conn->fedId();
00985          fedCh_ = conn->fedCh();
00986          fiberLength_ = conn->fiberLength();
00987          delay_ = delayMap[dcuId_];
00988          const StripGeomDetUnit* sgdu = static_cast<const StripGeomDetUnit*>(tracker_->idToDet(detid_));
00989          Surface::GlobalPoint gp = sgdu->surface().toGlobal(LocalPoint(0,0));
00990          globalX_ = gp.x();
00991          globalY_ = gp.y();
00992          globalZ_ = gp.z();
00993          readoutmap_->Fill();
00994          tmap.fill_current_val(detid_,delay_);
00995        }
00996      }
00997    }
00998    if(delayMap.size()) tmap.save(true, 0, 0, "delaymap.png");
00999 
01000    // cabling II (DCU map)
01001    ifstream cablingFile(cablingFileName_.c_str());
01002    if(cablingFile.is_open()) {
01003      char buffer[1024];
01004      cablingFile.getline(buffer,1024);
01005      while(!cablingFile.eof()) {
01006        std::istringstream line(buffer);
01007        std::string name;
01008        // one line contains the PSU name + all dcuids connected to it.
01009        line >> name;
01010        strncpy(PSUname_,name.c_str(),256);
01011        while(!line.eof()) {
01012          line >> dcuId_;
01013          psumap_->Fill();
01014        }
01015        cablingFile.getline(buffer,1024);
01016      }
01017    } else {
01018      edm::LogWarning("BadConfig") << " The PSU file does not exist. The psumap tree will not be filled."
01019                                   << std::endl << " Looking for " << cablingFileName_.c_str() << "." 
01020                                   << std::endl << " Please specify a valid filename through the PSUFileName untracked parameter.";
01021    }
01022 }
01023 
01024 // ------------ method called once each job just after ending the event loop  ------------
01025 void 
01026 TrackerDpgAnalysis::endJob() {
01027   for(size_t i = 0; i<tracks_.size();++i) {
01028     char buffer[256];
01029     sprintf(buffer,"trackid%lu",(unsigned long)i);
01030     if(tracks_[i]->GetEntries()) tracks_[i]->BuildIndex(buffer,"eventid");
01031   }
01032   /* not needed: missing hits is a high-level quantity
01033   for(size_t i = 0; i<missingHits_.size();++i) {
01034     char buffer[256];
01035     sprintf(buffer,"trackid%lu",(unsigned long)i);
01036     if(missingHits_[i]->GetEntries()) missingHits_[i]->BuildIndex(buffer);
01037   }
01038   */
01039   if(vertices_->GetEntries()) vertices_->BuildIndex("vertexid","eventid");
01040   if(event_->GetEntries()) event_->BuildIndex("runid","eventid");
01041   if(psumap_->GetEntries()) psumap_->BuildIndex("dcuId");
01042   if(readoutmap_->GetEntries()) readoutmap_->BuildIndex("detid","lldChannel");
01043 }
01044 
01045 std::vector<double> TrackerDpgAnalysis::onTrackAngles(edm::Handle<edmNew::DetSetVector<SiStripCluster> >& clusters,
01046                                                        const std::vector<Trajectory>& trajVec )
01047 {
01048   std::vector<double> result;
01049   // first, build a list of positions and angles on trajectories
01050   std::multimap<const uint32_t,std::pair<LocalPoint,double> > onTrackPositions;
01051   for(std::vector<Trajectory>::const_iterator traj = trajVec.begin(); traj< trajVec.end(); ++traj) {
01052     Trajectory::DataContainer measurements = traj->measurements();
01053     for(Trajectory::DataContainer::iterator meas = measurements.begin(); meas!= measurements.end(); ++meas) {
01054       double tla = meas->updatedState().localDirection().theta();
01055       insertMeasurement(onTrackPositions,&(*(meas->recHit())),tla);
01056     } 
01057   }
01058   // then loop over the clusters to check
01059   double angle = 0.;
01060   for (edmNew::DetSetVector<SiStripCluster>::const_iterator DSViter=clusters->begin(); DSViter!=clusters->end();DSViter++ ) {
01061     edmNew::DetSet<SiStripCluster>::const_iterator begin=DSViter->begin();
01062     edmNew::DetSet<SiStripCluster>::const_iterator end  =DSViter->end();
01063     std::pair< std::multimap<uint32_t,std::pair<LocalPoint,double> >::const_iterator,
01064                std::multimap<uint32_t,std::pair<LocalPoint,double> >::const_iterator> range =  
01065       onTrackPositions.equal_range(DSViter->id());
01066     const GeomDetUnit* gdu = static_cast<const GeomDetUnit*>(tracker_->idToDet(DSViter->id()));
01067     for(edmNew::DetSet<SiStripCluster>::const_iterator iter=begin;iter!=end;++iter) {
01068       angle = 0.;
01069       for(std::multimap<uint32_t,std::pair<LocalPoint,double> >::const_iterator cl = range.first; cl!= range.second; ++cl) {
01070         if(fabs(gdu->topology().measurementPosition(cl->second.first).x()-iter->barycenter())<2) {
01071           angle = cl->second.second;
01072         }
01073       }
01074       result.push_back(angle);
01075     }
01076   }
01077   return result;
01078 }
01079 
01080 void TrackerDpgAnalysis::insertMeasurement(std::multimap<const uint32_t,std::pair<LocalPoint,double> >& collection,const TransientTrackingRecHit* hit , double tla)
01081 {
01082       if(!hit) return;
01083       const TSiTrackerMultiRecHit* multihit=dynamic_cast<const TSiTrackerMultiRecHit*>(hit);
01084       const TSiStripRecHit2DLocalPos* singlehit=dynamic_cast<const TSiStripRecHit2DLocalPos*>(hit);
01085       const TSiStripRecHit1D* hit1d=dynamic_cast<const TSiStripRecHit1D*>(hit);
01086       if(hit1d) { //...->33X
01087         collection.insert(std::make_pair(hit1d->geographicalId().rawId(),std::make_pair(hit1d->localPosition(),tla)));
01088       } else if(singlehit) { // 41X->...
01089         collection.insert(std::make_pair(singlehit->geographicalId().rawId(),std::make_pair(singlehit->localPosition(),tla)));
01090       }
01091       else if(multihit){
01092         std::vector< const TrackingRecHit * > childs = multihit->recHits();
01093         for(std::vector<const TrackingRecHit*>::const_iterator it=childs.begin();it!=childs.end();++it) {
01094            insertMeasurement(collection,dynamic_cast<const TransientTrackingRecHit*>(*it),tla);
01095         }
01096       }
01097 }
01098 
01099 std::vector<int> TrackerDpgAnalysis::onTrack(edm::Handle<edmNew::DetSetVector<SiStripCluster> >& clusters,
01100                                               const reco::TrackCollection& trackVec, uint32_t firstTrack )
01101 {
01102   std::vector<int> result;
01103   // first, build a list of positions and trackid on tracks
01104   std::multimap<const uint32_t,std::pair<int,int> > onTrackPositions;
01105   uint32_t trackid = firstTrack;
01106   for(reco::TrackCollection::const_iterator itTrack = trackVec.begin(); itTrack!=trackVec.end();++itTrack,++trackid) {
01107     for(trackingRecHit_iterator it = itTrack->recHitsBegin(); it!=itTrack->recHitsEnd(); ++it) {
01108       const TrackingRecHit* hit = &(**it);
01109       insertMeasurement(onTrackPositions,hit,trackid);
01110     }
01111   }
01112   // then loop over the clusters to check
01113   int thetrackid = -1;
01114   for (edmNew::DetSetVector<SiStripCluster>::const_iterator DSViter=clusters->begin(); DSViter!=clusters->end();DSViter++ ) {
01115     edmNew::DetSet<SiStripCluster>::const_iterator begin=DSViter->begin();
01116     edmNew::DetSet<SiStripCluster>::const_iterator end  =DSViter->end();
01117     std::pair< std::multimap<uint32_t,std::pair<int,int> >::const_iterator,
01118                std::multimap<uint32_t,std::pair<int,int> >::const_iterator> range =  
01119       onTrackPositions.equal_range(DSViter->id());
01120     for(edmNew::DetSet<SiStripCluster>::const_iterator iter=begin;iter!=end;++iter) {
01121       thetrackid = -1;
01122       for(std::multimap<uint32_t,std::pair<int,int> >::const_iterator cl = range.first; cl!= range.second; ++cl) {
01123         if(fabs(cl->second.first-iter->barycenter())<2) {
01124           thetrackid = cl->second.second;
01125         }
01126       }
01127       result.push_back(thetrackid);
01128     }
01129   }
01130   return result;
01131 }
01132 
01133 void TrackerDpgAnalysis::insertMeasurement(std::multimap<const uint32_t,std::pair<int, int> >& collection,const TrackingRecHit* hit , int trackid)
01134 {
01135       if(!hit) return;
01136       const SiTrackerMultiRecHit* multihit=dynamic_cast<const SiTrackerMultiRecHit*>(hit);
01137       const SiStripRecHit2D* singlehit=dynamic_cast<const SiStripRecHit2D*>(hit);
01138       const SiStripRecHit1D* hit1d=dynamic_cast<const SiStripRecHit1D*>(hit);
01139       if(hit1d) { // 41X->...
01140         collection.insert(std::make_pair(hit1d->geographicalId().rawId(),std::make_pair(int(hit1d->cluster()->barycenter()),trackid)));
01141       } else if(singlehit) { //...->33X
01142         collection.insert(std::make_pair(singlehit->geographicalId().rawId(),std::make_pair(int(singlehit->cluster()->barycenter()),trackid)));
01143       }
01144       else if(multihit){
01145         std::vector< const TrackingRecHit * > childs = multihit->recHits();
01146         for(std::vector<const TrackingRecHit*>::const_iterator it=childs.begin();it!=childs.end();++it) {
01147            insertMeasurement(collection,*it,trackid);
01148         }
01149       }
01150 }
01151 
01152 std::map<size_t,int> TrackerDpgAnalysis::inVertex(const reco::TrackCollection& tracks, const reco::VertexCollection& vertices, uint32_t firstVertex)
01153 {
01154   // build reverse map track -> vertex
01155   std::map<size_t,int> output;
01156   uint32_t vertexid = firstVertex; 
01157   for(reco::VertexCollection::const_iterator v = vertices.begin(); v!=vertices.end(); ++v,++vertexid) {
01158     reco::Vertex::trackRef_iterator it = v->tracks_begin();
01159     reco::Vertex::trackRef_iterator lastTrack = v->tracks_end();
01160     for(;it!=lastTrack;++it) {
01161       output[it->key()] = vertexid;
01162     }
01163   }
01164   return output;
01165 }
01166 
01167 std::vector<std::pair<double,double> > TrackerDpgAnalysis::onTrackAngles(edm::Handle<edmNew::DetSetVector<SiPixelCluster> >& clusters,
01168                                                                           const std::vector<Trajectory>& trajVec )
01169 {
01170   std::vector<std::pair<double,double> > result;
01171   // first, build a list of positions and angles on trajectories
01172   std::multimap<const uint32_t,std::pair<LocalPoint,std::pair<double,double> > > onTrackPositions;
01173   for(std::vector<Trajectory>::const_iterator traj = trajVec.begin(); traj< trajVec.end(); ++traj) {
01174     Trajectory::DataContainer measurements = traj->measurements();
01175     for(Trajectory::DataContainer::iterator meas = measurements.begin(); meas!= measurements.end(); ++meas) {
01176       LocalVector localDir = meas->updatedState().localDirection();
01177       double alpha = atan2(localDir.z(), localDir.x());
01178       double beta  = atan2(localDir.z(), localDir.y());
01179       insertMeasurement(onTrackPositions,&(*(meas->recHit())),alpha,beta);
01180     } 
01181   }
01182   // then loop over the clusters to check
01183   double alpha = 0.;
01184   double beta  = 0.;
01185   for (edmNew::DetSetVector<SiPixelCluster>::const_iterator DSViter=clusters->begin(); DSViter!=clusters->end();DSViter++ ) {
01186     edmNew::DetSet<SiPixelCluster>::const_iterator begin=DSViter->begin();
01187     edmNew::DetSet<SiPixelCluster>::const_iterator end  =DSViter->end();
01188     for(edmNew::DetSet<SiPixelCluster>::const_iterator iter=begin;iter!=end;++iter) {
01189       alpha = 0.;
01190       beta  = 0.;
01191       std::pair< std::multimap<uint32_t,std::pair<LocalPoint,std::pair<double, double> > >::const_iterator,
01192                  std::multimap<uint32_t,std::pair<LocalPoint,std::pair<double, double> > >::const_iterator> range =  
01193           onTrackPositions.equal_range(DSViter->id());
01194       const GeomDetUnit* gdu = static_cast<const GeomDetUnit*>(tracker_->idToDet(DSViter->id()));
01195       for(std::multimap<uint32_t,std::pair<LocalPoint,std::pair<double, double> > >::const_iterator cl = range.first; cl!= range.second; ++cl) {
01196         if(fabs(gdu->topology().measurementPosition(cl->second.first).x()-iter->x())<2 &&
01197            fabs(gdu->topology().measurementPosition(cl->second.first).y()-iter->y())<2    ) {
01198           alpha = cl->second.second.first;
01199           beta  = cl->second.second.second;
01200         }
01201       }
01202       result.push_back(std::make_pair(alpha,beta));
01203     }
01204   }
01205   return result;
01206 }
01207 
01208 void TrackerDpgAnalysis::insertMeasurement(std::multimap<const uint32_t,std::pair<LocalPoint,std::pair<double,double> > >& collection,const TransientTrackingRecHit* hit , double alpha, double beta)
01209 {
01210       if(!hit) return;
01211       const TSiPixelRecHit* pixhit = dynamic_cast<const TSiPixelRecHit*>(hit);
01212       if(pixhit) {
01213         collection.insert(std::make_pair(pixhit->geographicalId().rawId(),std::make_pair(pixhit->localPosition(),std::make_pair(alpha,beta))));
01214       }
01215 }
01216 
01217 std::vector<int> TrackerDpgAnalysis::onTrack(edm::Handle<edmNew::DetSetVector<SiPixelCluster> >& clusters,
01218                                               const reco::TrackCollection& trackVec, uint32_t firstTrack )
01219 {
01220   std::vector<int> result;
01221   // first, build a list of positions and trackid on tracks
01222   std::multimap<const uint32_t,std::pair<std::pair<float, float>,int> > onTrackPositions;
01223   uint32_t trackid = firstTrack;
01224   for(reco::TrackCollection::const_iterator itTrack = trackVec.begin(); itTrack!=trackVec.end();++itTrack,++trackid) {
01225     for(trackingRecHit_iterator it = itTrack->recHitsBegin(); it!=itTrack->recHitsEnd(); ++it) {
01226       const TrackingRecHit* hit = &(**it);
01227       insertMeasurement(onTrackPositions,hit,trackid);
01228     }
01229   }
01230   // then loop over the clusters to check
01231   int thetrackid = -1;
01232   for (edmNew::DetSetVector<SiPixelCluster>::const_iterator DSViter=clusters->begin(); DSViter!=clusters->end();DSViter++ ) {
01233     edmNew::DetSet<SiPixelCluster>::const_iterator begin=DSViter->begin();
01234     edmNew::DetSet<SiPixelCluster>::const_iterator end  =DSViter->end();
01235     for(edmNew::DetSet<SiPixelCluster>::const_iterator iter=begin;iter!=end;++iter) {
01236       thetrackid = -1;
01237       std::pair< std::multimap<uint32_t,std::pair<std::pair<float, float>,int> >::const_iterator,
01238                  std::multimap<uint32_t,std::pair<std::pair<float, float>,int> >::const_iterator> range =  
01239           onTrackPositions.equal_range(DSViter->id());
01240       for(std::multimap<uint32_t,std::pair<std::pair<float, float>,int> >::const_iterator cl = range.first; cl!= range.second; ++cl) {
01241         if((fabs(cl->second.first.first-iter->x())<2)&&(fabs(cl->second.first.second-iter->y())<2)) {
01242           thetrackid = cl->second.second;
01243         }
01244       }
01245       result.push_back(thetrackid);
01246     }
01247   }
01248   return result;
01249 }
01250 
01251 void TrackerDpgAnalysis::insertMeasurement(std::multimap<const uint32_t,std::pair<std::pair<float, float>, int> >& collection,const TrackingRecHit* hit , int trackid)
01252 {
01253       if(!hit) return;
01254       const SiPixelRecHit* pixhit = dynamic_cast<const SiPixelRecHit*>(hit);
01255       if(pixhit) {
01256         collection.insert(std::make_pair(pixhit->geographicalId().rawId(),std::make_pair(std::make_pair(pixhit->cluster()->x(),pixhit->cluster()->y()),trackid)));
01257         }
01258 }
01259 
01260 std::string TrackerDpgAnalysis::toStringName(uint32_t rawid) {
01261    SiStripDetId detid(rawid);
01262    std::string out;
01263    std::stringstream output;
01264    switch(detid.subDetector()) {
01265      case 3:
01266      {
01267        output << "TIB";
01268        TIBDetId tib(rawid);
01269        output << (tib.isZPlusSide() ? "+" : "-");
01270        output << " layer ";
01271        output << tib.layerNumber();
01272        output << ", string ";
01273        output << tib.stringNumber();
01274        output << (tib.isExternalString() ? " external" : " internal");
01275        output << ", module ";
01276        output << tib.moduleNumber();
01277        if(tib.isDoubleSide()) {
01278          output << " (double)";
01279        } else {
01280          output << (tib.isRPhi() ? " (rphi)" : " (stereo)");
01281        }
01282        break;
01283      }
01284      case 4:
01285      {
01286        output << "TID";
01287        TIDDetId tid(rawid);
01288        output << (tid.isZPlusSide() ? "+" : "-");
01289        output << " disk ";
01290        output << tid.diskNumber();
01291        output << ", ring ";
01292        output << tid.ringNumber();
01293        output << (tid.isFrontRing() ? " front" : " back");
01294        output << ", module ";
01295        output << tid.moduleNumber();
01296        if(tid.isDoubleSide()) {
01297          output << " (double)";
01298        } else {
01299          output << (tid.isRPhi() ? " (rphi)" : " (stereo)");
01300        }
01301        break;
01302      }
01303      case 5:
01304      {
01305        output << "TOB";
01306        TOBDetId tob(rawid);
01307        output << (tob.isZPlusSide() ? "+" : "-");
01308        output << " layer ";
01309        output << tob.layerNumber();
01310        output << ", rod ";
01311        output << tob.rodNumber();
01312        output << ", module ";
01313        output << tob.moduleNumber();
01314        if(tob.isDoubleSide()) {
01315          output << " (double)";
01316        } else {
01317          output << (tob.isRPhi() ? " (rphi)" : " (stereo)");
01318        }
01319        break;
01320      }
01321      case 6:
01322      {
01323        output << "TEC";
01324        TECDetId tec(rawid);
01325        output << (tec.isZPlusSide() ? "+" : "-");
01326        output << " disk ";
01327        output << tec.wheelNumber();
01328        output << " sector ";
01329        output << tec.petalNumber();
01330        output << (tec.isFrontPetal() ? " Front Petal" : " Back Petal");
01331        output << ", module ";
01332        output << tec.ringNumber();
01333        output << tec.moduleNumber();
01334        if(tec.isDoubleSide()) {
01335          output << " (double)";
01336        } else {
01337          output << (tec.isRPhi() ? " (rphi)" : " (stereo)");
01338        }
01339        break;
01340      }
01341      default:
01342      {
01343        output << "UNKNOWN";
01344      }
01345    }
01346    out = output.str();
01347    return out;
01348 }
01349 
01350 std::string TrackerDpgAnalysis::toStringId(uint32_t rawid) {
01351    std::string out;
01352    std::stringstream output;
01353    output << rawid << " (0x" << std::hex << rawid << std::dec << ")";
01354    out = output.str();
01355    return out;
01356 }
01357 
01358 double TrackerDpgAnalysis::sumPtSquared(const reco::Vertex & v)  {
01359   double sum = 0.;
01360   double pT;
01361   for (reco::Vertex::trackRef_iterator it = v.tracks_begin(); it != v.tracks_end(); it++) {
01362     pT = (**it).pt();
01363     sum += pT*pT;
01364   }
01365   return sum;
01366 }
01367 
01368 float TrackerDpgAnalysis::delay(const SiStripEventSummary& summary) {
01369   float delay = const_cast<SiStripEventSummary&>(summary).ttcrx();
01370   uint32_t latencyCode = (const_cast<SiStripEventSummary&>(summary).layerScanned()>>24)&0xff;
01371   int latencyShift = latencyCode & 0x3f;             // number of bunch crossings between current value and start of scan... must be positive
01372   if(latencyShift>32) latencyShift -=64;             // allow negative values: we cover [-32,32].. should not be needed.
01373   if((latencyCode>>6)==2) latencyShift -= 3;         // layer in deconv, rest in peak
01374   if((latencyCode>>6)==1) latencyShift += 3;         // layer in peak, rest in deconv
01375   float correctedDelay = delay - (latencyShift*25.); // shifts the delay so that 0 corresponds to the current settings.
01376   return correctedDelay;
01377 }
01378 
01379 std::map<uint32_t,float> TrackerDpgAnalysis::delay(const std::vector<std::string>& files) {
01380    // prepare output
01381    uint32_t dcuid;
01382    float delay;
01383    std::map<uint32_t,float> delayMap;
01384    //iterator over input files
01385    for(std::vector<std::string>::const_iterator file=files.begin();file<files.end();++file){
01386      // open the file
01387      std::ifstream cablingFile(file->c_str());
01388      if(cablingFile.is_open()) {
01389        char buffer[1024];
01390        // read one line
01391        cablingFile.getline(buffer,1024);
01392        while(!cablingFile.eof()) {
01393          std::string line(buffer);
01394          size_t pos = line.find("dcuid");
01395          // one line containing dcuid
01396          if(pos != std::string::npos) {
01397            // decode dcuid
01398            std::string dcuids = line.substr(pos+7,line.find(" ",pos)-pos-8);
01399            std::istringstream dcuidstr(dcuids);
01400            dcuidstr >> std::hex >> dcuid;
01401            // decode delay
01402            pos = line.find("difpll");
01403            std::string diffs = line.substr(pos+8,line.find(" ",pos)-pos-9);
01404            std::istringstream diffstr(diffs);
01405            diffstr >> delay;
01406            // fill the map
01407            delayMap[dcuid] = delay;
01408          }
01409          // iterate
01410          cablingFile.getline(buffer,1024);
01411        }
01412      } else {
01413        edm::LogWarning("BadConfig") << " The delay file does not exist. The delay map will not be filled properly."
01414                                     << std::endl << " Looking for " << file->c_str() << "." 
01415                                     << std::endl << " Please specify valid filenames through the DelayFileNames untracked parameter.";
01416      }
01417    }
01418    return delayMap;
01419 }
01420 
01421 //define this as a plug-in
01422 DEFINE_FWK_MODULE(TrackerDpgAnalysis);