CMS 3D CMS Logo

DeDxDiscriminatorLearner.cc
Go to the documentation of this file.
1 // -*- C++ -*-
2 //
3 // Package: DeDxDiscriminatorLearner
4 // Class: DeDxDiscriminatorLearner
5 //
13 //
14 // Original Author: Loic Quertenmont(querten)
15 // Created: Mon October 20 10:09:02 CEST 2008
16 //
17 
18 // system include files
19 #include <memory>
20 
22 
25 
29 
30 using namespace reco;
31 using namespace std;
32 using namespace edm;
33 
36  m_tracksTag = consumes<reco::TrackCollection>(iConfig.getParameter<edm::InputTag>("tracks"));
38  consumes<TrajTrackAssociationCollection>(iConfig.getParameter<edm::InputTag>("trajectoryTrackAssociation"));
39  m_tkGeomToken = esConsumes<edm::Transition::BeginRun>();
40 
41  P_Min = iConfig.getParameter<double>("P_Min");
42  P_Max = iConfig.getParameter<double>("P_Max");
43  P_NBins = iConfig.getParameter<int>("P_NBins");
44  Path_Min = iConfig.getParameter<double>("Path_Min");
45  Path_Max = iConfig.getParameter<double>("Path_Max");
46  Path_NBins = iConfig.getParameter<int>("Path_NBins");
47  Charge_Min = iConfig.getParameter<double>("Charge_Min");
48  Charge_Max = iConfig.getParameter<double>("Charge_Max");
49  Charge_NBins = iConfig.getParameter<int>("Charge_NBins");
50 
51  MinTrackMomentum = iConfig.getUntrackedParameter<double>("minTrackMomentum", 5.0);
52  MaxTrackMomentum = iConfig.getUntrackedParameter<double>("maxTrackMomentum", 99999.0);
53  MinTrackEta = iConfig.getUntrackedParameter<double>("minTrackEta", -5.0);
54  MaxTrackEta = iConfig.getUntrackedParameter<double>("maxTrackEta", 5.0);
55  MaxNrStrips = iConfig.getUntrackedParameter<unsigned>("maxNrStrips", 255);
56  MinTrackHits = iConfig.getUntrackedParameter<unsigned>("MinTrackHits", 4);
57 
58  algoMode = iConfig.getUntrackedParameter<string>("AlgoMode", "SingleJob");
59  HistoFile = iConfig.getUntrackedParameter<string>("HistoFile", "out.root");
60  VInputFiles = iConfig.getUntrackedParameter<vector<string> >("InputFiles");
61 
62  shapetest = iConfig.getParameter<bool>("ShapeTest");
63  useCalibration = iConfig.getUntrackedParameter<bool>("UseCalibration");
64  m_calibrationPath = iConfig.getUntrackedParameter<string>("calibrationPath");
65 }
66 
68 
69 // ------------ method called once each job just before starting event loop ------------
70 
72  Charge_Vs_Path = new TH3F("Charge_Vs_Path",
73  "Charge_Vs_Path",
74  P_NBins,
75  P_Min,
76  P_Max,
77  Path_NBins,
78  Path_Min,
79  Path_Max,
81  Charge_Min,
82  Charge_Max);
83 
84  if (useCalibration && calibGains.empty()) {
85  const auto& tkGeom = iSetup.getData(m_tkGeomToken);
86 
87  m_off = tkGeom.offsetDU(GeomDetEnumerators::PixelBarrel); //index start at the first pixel
88 
90  }
91 
92  //Read the calibTree if in calibTree mode
93  if (strcmp(algoMode.c_str(), "CalibTree") == 0)
94  algoAnalyzeTheTree(iSetup);
95 }
96 
97 // ------------ method called once each job just after ending the event loop ------------
98 
100  if (strcmp(algoMode.c_str(), "MultiJob") == 0) {
101  TFile* Output = new TFile(HistoFile.c_str(), "RECREATE");
102  Charge_Vs_Path->Write();
103  Output->Write();
104  Output->Close();
105  } else if (strcmp(algoMode.c_str(), "WriteOnDB") == 0) {
106  TFile* Input = new TFile(HistoFile.c_str());
107  Charge_Vs_Path = (TH3F*)(Input->FindObjectAny("Charge_Vs_Path"))->Clone();
108  Input->Close();
109  } else if (strcmp(algoMode.c_str(), "CalibTree") == 0) {
110  TFile* Output = new TFile(HistoFile.c_str(), "RECREATE");
111  Charge_Vs_Path->Write();
112  Output->Write();
113  Output->Close();
114  TFile* Input = new TFile(HistoFile.c_str());
115  Charge_Vs_Path = (TH3F*)(Input->FindObjectAny("Charge_Vs_Path"))->Clone();
116  Input->Close();
117  }
118 }
119 
121  Handle<TrajTrackAssociationCollection> trajTrackAssociationHandle;
122  iEvent.getByToken(m_trajTrackAssociationTag, trajTrackAssociationHandle);
123 
124  edm::Handle<reco::TrackCollection> trackCollectionHandle;
125  iEvent.getByToken(m_tracksTag, trackCollectionHandle);
126 
127  unsigned track_index = 0;
128  for (TrajTrackAssociationCollection::const_iterator it = trajTrackAssociationHandle->begin();
129  it != trajTrackAssociationHandle->end();
130  ++it, track_index++) {
131  const Track& track = *it->val;
132  const Trajectory& traj = *it->key;
133 
134  if (track.eta() < MinTrackEta || track.eta() > MaxTrackEta) {
135  continue;
136  }
137  if (track.pt() < MinTrackMomentum || track.pt() > MaxTrackMomentum) {
138  continue;
139  }
140  if (track.found() < MinTrackHits) {
141  continue;
142  }
143 
144  const vector<TrajectoryMeasurement>& measurements = traj.measurements();
145  for (vector<TrajectoryMeasurement>::const_iterator it = measurements.begin(); it != measurements.end(); it++) {
146  TrajectoryStateOnSurface trajState = it->updatedState();
147  if (!trajState.isValid())
148  continue;
149 
150  const TrackingRecHit* recHit = (*it->recHit()).hit();
151  if (!recHit || !recHit->isValid())
152  continue;
153  LocalVector trackDirection = trajState.localDirection();
154  float cosine = trackDirection.z() / trackDirection.mag();
155 
156  processHit(recHit, trajState.localMomentum().mag(), cosine, trajState);
157  }
158  }
159 }
160 
162  float trackMomentum,
163  float& cosine,
164  const TrajectoryStateOnSurface& trajState) {
165  auto const& thit = static_cast<BaseTrackerRecHit const&>(*recHit);
166  if (!thit.isValid())
167  return;
168 
169  auto const& clus = thit.firstClusterRef();
170  if (!clus.isValid())
171  return;
172 
173  int NSaturating = 0;
174  if (clus.isPixel()) {
175  return;
176  } else if (clus.isStrip() && !thit.isMatched()) {
177  auto& detUnit = *(recHit->detUnit());
178  auto& cluster = clus.stripCluster();
179  if (cluster.amplitudes().size() > MaxNrStrips) {
180  return;
181  }
182  if (deDxTools::isSpanningOver2APV(cluster.firstStrip(), cluster.amplitudes().size())) {
183  return;
184  }
185  if (!deDxTools::isFarFromBorder(trajState, &detUnit)) {
186  return;
187  }
188  float pathLen = 10.0 * detUnit.surface().bounds().thickness() / fabs(cosine);
189  float chargeAbs = deDxTools::getCharge(&cluster, NSaturating, detUnit, calibGains, m_off);
190  float charge = chargeAbs / pathLen;
191  if (!shapetest || (shapetest && deDxTools::shapeSelection(cluster))) {
192  Charge_Vs_Path->Fill(trackMomentum, pathLen, charge);
193  }
194  } else if (clus.isStrip() && thit.isMatched()) {
195  const SiStripMatchedRecHit2D* matchedHit = dynamic_cast<const SiStripMatchedRecHit2D*>(recHit);
196  if (!matchedHit)
197  return;
198  const GluedGeomDet* gdet = static_cast<const GluedGeomDet*>(matchedHit->det());
199 
200  auto& detUnitM = *(gdet->monoDet());
201  auto& clusterM = matchedHit->monoCluster();
202  if (clusterM.amplitudes().size() > MaxNrStrips) {
203  return;
204  }
205  if (deDxTools::isSpanningOver2APV(clusterM.firstStrip(), clusterM.amplitudes().size())) {
206  return;
207  }
208  if (!deDxTools::isFarFromBorder(trajState, &detUnitM)) {
209  return;
210  }
211  float pathLen = 10.0 * detUnitM.surface().bounds().thickness() / fabs(cosine);
212  float chargeAbs = deDxTools::getCharge(&clusterM, NSaturating, detUnitM, calibGains, m_off);
213  float charge = chargeAbs / pathLen;
214  if (!shapetest || (shapetest && deDxTools::shapeSelection(clusterM))) {
215  Charge_Vs_Path->Fill(trackMomentum, pathLen, charge);
216  }
217 
218  auto& detUnitS = *(gdet->stereoDet());
219  auto& clusterS = matchedHit->stereoCluster();
220  if (clusterS.amplitudes().size() > MaxNrStrips) {
221  return;
222  }
223  if (deDxTools::isSpanningOver2APV(clusterS.firstStrip(), clusterS.amplitudes().size())) {
224  return;
225  }
226  if (!deDxTools::isFarFromBorder(trajState, &detUnitS)) {
227  return;
228  }
229  pathLen = 10.0 * detUnitS.surface().bounds().thickness() / fabs(cosine);
230  chargeAbs = deDxTools::getCharge(&clusterS, NSaturating, detUnitS, calibGains, m_off);
231  charge = chargeAbs / pathLen;
232  if (!shapetest || (shapetest && deDxTools::shapeSelection(clusterS))) {
233  Charge_Vs_Path->Fill(trackMomentum, pathLen, charge);
234  }
235  }
236 }
237 
238 //this function is only used when we run over a calibTree instead of running over EDM files
240  const auto& tkGeom = iSetup.getData(m_tkGeomToken);
241 
242  unsigned int NEvent = 0;
243  for (unsigned int i = 0; i < VInputFiles.size(); i++) {
244  printf("Openning file %3i/%3i --> %s\n", i + 1, (int)VInputFiles.size(), (char*)(VInputFiles[i].c_str()));
245  fflush(stdout);
246  TChain* tree = new TChain("gainCalibrationTree/tree");
247  tree->Add(VInputFiles[i].c_str());
248 
249  TString EventPrefix("");
250  TString EventSuffix("");
251 
252  TString TrackPrefix("track");
253  TString TrackSuffix("");
254 
255  TString CalibPrefix("GainCalibration");
256  TString CalibSuffix("");
257 
258  unsigned int eventnumber = 0;
259  tree->SetBranchAddress(EventPrefix + "event" + EventSuffix, &eventnumber, nullptr);
260  unsigned int runnumber = 0;
261  tree->SetBranchAddress(EventPrefix + "run" + EventSuffix, &runnumber, nullptr);
262  std::vector<bool>* TrigTech = nullptr;
263  tree->SetBranchAddress(EventPrefix + "TrigTech" + EventSuffix, &TrigTech, nullptr);
264 
265  std::vector<double>* trackchi2ndof = nullptr;
266  tree->SetBranchAddress(TrackPrefix + "chi2ndof" + TrackSuffix, &trackchi2ndof, nullptr);
267  std::vector<float>* trackp = nullptr;
268  tree->SetBranchAddress(TrackPrefix + "momentum" + TrackSuffix, &trackp, nullptr);
269  std::vector<float>* trackpt = nullptr;
270  tree->SetBranchAddress(TrackPrefix + "pt" + TrackSuffix, &trackpt, nullptr);
271  std::vector<double>* tracketa = nullptr;
272  tree->SetBranchAddress(TrackPrefix + "eta" + TrackSuffix, &tracketa, nullptr);
273  std::vector<double>* trackphi = nullptr;
274  tree->SetBranchAddress(TrackPrefix + "phi" + TrackSuffix, &trackphi, nullptr);
275  std::vector<unsigned int>* trackhitsvalid = nullptr;
276  tree->SetBranchAddress(TrackPrefix + "hitsvalid" + TrackSuffix, &trackhitsvalid, nullptr);
277 
278  std::vector<int>* trackindex = nullptr;
279  tree->SetBranchAddress(CalibPrefix + "trackindex" + CalibSuffix, &trackindex, nullptr);
280  std::vector<unsigned int>* rawid = nullptr;
281  tree->SetBranchAddress(CalibPrefix + "rawid" + CalibSuffix, &rawid, nullptr);
282  std::vector<unsigned short>* firststrip = nullptr;
283  tree->SetBranchAddress(CalibPrefix + "firststrip" + CalibSuffix, &firststrip, nullptr);
284  std::vector<unsigned short>* nstrips = nullptr;
285  tree->SetBranchAddress(CalibPrefix + "nstrips" + CalibSuffix, &nstrips, nullptr);
286  std::vector<unsigned int>* charge = nullptr;
287  tree->SetBranchAddress(CalibPrefix + "charge" + CalibSuffix, &charge, nullptr);
288  std::vector<float>* path = nullptr;
289  tree->SetBranchAddress(CalibPrefix + "path" + CalibSuffix, &path, nullptr);
290  std::vector<unsigned char>* amplitude = nullptr;
291  tree->SetBranchAddress(CalibPrefix + "amplitude" + CalibSuffix, &amplitude, nullptr);
292  std::vector<double>* gainused = nullptr;
293  tree->SetBranchAddress(CalibPrefix + "gainused" + CalibSuffix, &gainused, nullptr);
294 
295  printf("Number of Events = %i + %i = %i\n",
296  NEvent,
297  (unsigned int)tree->GetEntries(),
298  (unsigned int)(NEvent + tree->GetEntries()));
299  NEvent += tree->GetEntries();
300  printf("Progressing Bar :0%% 20%% 40%% 60%% 80%% 100%%\n");
301  printf("Looping on the Tree :");
302  int TreeStep = tree->GetEntries() / 50;
303  if (TreeStep <= 1)
304  TreeStep = 1;
305  for (unsigned int ientry = 0; ientry < tree->GetEntries(); ientry++) {
306  if (ientry % TreeStep == 0) {
307  printf(".");
308  fflush(stdout);
309  }
310  tree->GetEntry(ientry);
311 
312  int FirstAmplitude = 0;
313  for (unsigned int c = 0; c < (*path).size(); c++) {
314  FirstAmplitude += (*nstrips)[c];
315  int t = (*trackindex)[c];
316  if ((*trackpt)[t] < 5)
317  continue;
318  if ((*trackhitsvalid)[t] < 5)
319  continue;
320 
321  int Charge = 0;
322  if (useCalibration) {
323  auto& gains = calibGains[tkGeom.idToDetUnit(DetId((*rawid)[c]))->index() - m_off];
324  auto& gain = gains[(*firststrip)[c] / 128];
325  for (unsigned int s = 0; s < (*nstrips)[c]; s++) {
326  int StripCharge = (*amplitude)[FirstAmplitude - (*nstrips)[c] + s];
327  if (StripCharge < 254) {
328  StripCharge = (int)(StripCharge / gain);
329  if (StripCharge >= 1024) {
330  StripCharge = 255;
331  } else if (StripCharge >= 254) {
332  StripCharge = 254;
333  }
334  }
335  Charge += StripCharge;
336  }
337  } else {
338  Charge = (*charge)[c];
339  }
340 
341  // printf("ChargeDifference = %i Vs %i with Gain = %f\n",(*charge)[c],Charge,Gains[(*rawid)[c]]);
342  double ClusterChargeOverPath = ((double)Charge) / (*path)[c];
343  Charge_Vs_Path->Fill((*trackp)[t], (*path)[c], ClusterChargeOverPath);
344  }
345  }
346  printf("\n");
347  }
348 }
349 
350 std::unique_ptr<PhysicsTools::Calibration::HistogramD3D> DeDxDiscriminatorLearner::getNewObject() {
351  auto obj = std::make_unique<PhysicsTools::Calibration::HistogramD3D>(Charge_Vs_Path->GetNbinsX(),
352  Charge_Vs_Path->GetXaxis()->GetXmin(),
353  Charge_Vs_Path->GetXaxis()->GetXmax(),
354  Charge_Vs_Path->GetNbinsY(),
355  Charge_Vs_Path->GetYaxis()->GetXmin(),
356  Charge_Vs_Path->GetYaxis()->GetXmax(),
357  Charge_Vs_Path->GetNbinsZ(),
358  Charge_Vs_Path->GetZaxis()->GetXmin(),
359  Charge_Vs_Path->GetZaxis()->GetXmax());
360 
361  for (int ix = 0; ix <= Charge_Vs_Path->GetNbinsX() + 1; ix++) {
362  for (int iy = 0; iy <= Charge_Vs_Path->GetNbinsY() + 1; iy++) {
363  for (int iz = 0; iz <= Charge_Vs_Path->GetNbinsZ() + 1; iz++) {
364  obj->setBinContent(ix, iy, iz, Charge_Vs_Path->GetBinContent(ix, iy, iz));
365  // if(Charge_Vs_Path->GetBinContent(ix,iy)!=0)printf("%i %i %i --> %f\n",ix,iy, iz, Charge_Vs_Path->GetBinContent(ix,iy,iz));
366  }
367  }
368  }
369 
370  return obj;
371 }
372 
373 //define this as a plug-in
T getParameter(std::string const &) const
Definition: ParameterSet.h:303
void algoAnalyze(const edm::Event &, const edm::EventSetup &) override
T const & getData(const ESGetToken< T, R > &iToken) const noexcept(false)
Definition: EventSetup.h:119
std::vector< std::vector< float > > calibGains
T z() const
Definition: PV3DBase.h:61
int getCharge(const SiStripCluster *cluster, int &nSatStrip, const GeomDetUnit &detUnit, const std::vector< std::vector< float >> &calibGains, const unsigned int &m_off)
const GeomDet * det() const
DataContainer const & measurements() const
Definition: Trajectory.h:178
const_iterator end() const
last iterator over the map (read only)
T getUntrackedParameter(std::string const &, T const &) const
int iEvent
Definition: GenABIO.cc:224
Histogram3D< double > HistogramD3D
Definition: Histogram3D.h:184
void algoAnalyzeTheTree(const edm::EventSetup &iSetup)
SiStripCluster const & monoCluster() const
std::unique_ptr< PhysicsTools::Calibration::HistogramD3D > getNewObject() override
LocalVector localDirection() const
void processHit(const TrackingRecHit *recHit, float trackMomentum, float &cosine, const TrajectoryStateOnSurface &trajState)
T mag() const
Definition: PV3DBase.h:64
bool isFarFromBorder(const TrajectoryStateOnSurface &trajState, const GeomDetUnit *it)
Definition: DeDxTools.cc:426
edm::ESGetToken< TrackerGeometry, TrackerDigiGeometryRecord > m_tkGeomToken
#define DEFINE_FWK_MODULE(type)
Definition: MakerMacros.h:16
std::vector< std::string > VInputFiles
const GeomDetUnit * monoDet() const
Definition: GluedGeomDet.h:19
constexpr float gains[NGAINS]
Definition: EcalConstants.h:20
Definition: DetId.h:17
void makeCalibrationMap(const std::string &m_calibrationPath, const TrackerGeometry &tkGeom, std::vector< std::vector< float >> &calibGains, const unsigned int &m_off)
void algoBeginJob(const edm::EventSetup &) override
bool shapeSelection(const SiStripCluster &ampls)
Definition: DeDxTools.cc:13
bool isSpanningOver2APV(unsigned int FirstStrip, unsigned int ClusterSize)
Definition: DeDxTools.cc:385
const GeomDetUnit * stereoDet() const
Definition: GluedGeomDet.h:20
SiStripCluster const & stereoCluster() const
const_iterator begin() const
first iterator over the map (read only)
fixed size matrix
HLT enums.
edm::EDGetTokenT< TrajTrackAssociationCollection > m_trajTrackAssociationTag
Definition: tree.py:1
edm::EDGetTokenT< reco::TrackCollection > m_tracksTag
DeDxDiscriminatorLearner(const edm::ParameterSet &)