CMS 3D CMS Logo

DTVDriftCalibration.cc
Go to the documentation of this file.
1 
2 /*
3  * See header file for a description of this class.
4  *
5  * \author M. Giunta
6  */
7 
11 
16 
19 
22 
25 
28 
29 /* C++ Headers */
30 #include <map>
31 #include <iostream>
32 #include <fstream>
33 #include <string>
34 #include <sstream>
35 #include "TFile.h"
36 #include "TH1.h"
37 #include "TF1.h"
38 #include "TROOT.h"
39 
40 using namespace std;
41 using namespace edm;
42 using namespace dttmaxenums;
43 
45  : // Get the synchronizer
46  theDTGeomToken{esConsumes()},
47  theSync{DTTTrigSyncFactory::get()->create(pset.getParameter<string>("tTrigMode"),
48  pset.getParameter<ParameterSet>("tTrigModeConfig"),
49  consumesCollector())}
50 
51 {
52  edm::ConsumesCollector collector(consumesCollector());
53  select_ = std::make_unique<DTSegmentSelector>(pset, collector);
54 
55  // The name of the 4D rec hits collection
56  theRecHits4DToken = (consumes<DTRecSegment4DCollection>(pset.getParameter<InputTag>("recHits4DLabel")));
57 
58  // The root file which will contain the histos
59  string rootFileName = pset.getUntrackedParameter<string>("rootFileName");
60  theFile = new TFile(rootFileName.c_str(), "RECREATE");
61  theFile->cd();
62 
63  debug = pset.getUntrackedParameter<bool>("debug", false);
64 
65  theFitter = std::make_unique<DTMeanTimerFitter>(theFile);
66  if (debug)
67  theFitter->setVerbosity(1);
68 
69  hChi2 = new TH1F("hChi2", "Chi squared tracks", 100, 0, 100);
70  h2DSegmRPhi = new h2DSegm("SLRPhi");
71  h2DSegmRZ = new h2DSegm("SLRZ");
72  h4DSegmAllCh = new h4DSegm("AllCh");
73  histograms_.bookHistos();
74 
75  findVDriftAndT0 = pset.getUntrackedParameter<bool>("fitAndWrite", false);
76 
77  // Chamber/s to calibrate
78  theCalibChamber = pset.getUntrackedParameter<string>("calibChamber", "All");
79 
80  // the txt file which will contain the calibrated constants
81  theVDriftOutputFile = pset.getUntrackedParameter<string>("vDriftFileName");
82 
83  // get parameter set for DTCalibrationMap constructor
84  theCalibFilePar = pset.getUntrackedParameter<ParameterSet>("calibFileConfig");
85 
86  // the granularity to be used for tMax
87  string tMaxGranularity = pset.getUntrackedParameter<string>("tMaxGranularity", "bySL");
88 
89  writeLegacyVDriftDB = pset.getParameter<bool>("writeLegacyVDriftDB");
90 
91  // Enforce it to be by SL since rest is not implemented
92  if (tMaxGranularity != "bySL") {
93  LogError("Calibration") << "[DTVDriftCalibration] tMaxGranularity will be fixed to bySL.";
94  tMaxGranularity = "bySL";
95  }
96  // Initialize correctly the enum which specify the granularity for the calibration
97  if (tMaxGranularity == "bySL") {
98  theGranularity = bySL;
99  } else if (tMaxGranularity == "byChamber") {
100  theGranularity = byChamber;
101  } else if (tMaxGranularity == "byPartition") {
102  theGranularity = byPartition;
103  } else
104  throw cms::Exception("Configuration")
105  << "[DTVDriftCalibration] Check parameter tMaxGranularity: " << tMaxGranularity << " option not available";
106 
107  LogVerbatim("Calibration") << "[DTVDriftCalibration]Constructor called!";
108 }
109 
111  theFile->Close();
112  LogVerbatim("Calibration") << "[DTVDriftCalibration]Destructor called!";
113 }
114 
116  LogTrace("Calibration") << "--- [DTVDriftCalibration] Event analysed #Run: " << event.id().run()
117  << " #Event: " << event.id().event();
118  theFile->cd();
119  DTChamberId chosenChamberId;
120 
121  if (theCalibChamber != "All") {
122  stringstream linestr;
123  int selWheel, selStation, selSector;
124  linestr << theCalibChamber;
125  linestr >> selWheel >> selStation >> selSector;
126  chosenChamberId = DTChamberId(selWheel, selStation, selSector);
127  LogTrace("Calibration") << "chosen chamber " << chosenChamberId;
128  }
129 
130  // Get the DT Geometry
131  const DTGeometry& dtGeom = eventSetup.getData(theDTGeomToken);
132 
133  // Get the rechit collection from the event
134  Handle<DTRecSegment4DCollection> all4DSegments;
135  event.getByToken(theRecHits4DToken, all4DSegments);
136 
137  // Set the event setup in the Synchronizer
138  theSync->setES(eventSetup);
139 
140  // Loop over segments by chamber
142  for (chamberIdIt = all4DSegments->id_begin(); chamberIdIt != all4DSegments->id_end(); ++chamberIdIt) {
143  // Get the chamber from the setup
144  const DTChamber* chamber = dtGeom.chamber(*chamberIdIt);
145  LogTrace("Calibration") << "Chamber Id: " << *chamberIdIt;
146 
147  // Calibrate just the chosen chamber/s
148  if ((theCalibChamber != "All") && ((*chamberIdIt) != chosenChamberId))
149  continue;
150 
151  // Get the range for the corresponding ChamberId
152  DTRecSegment4DCollection::range range = all4DSegments->get((*chamberIdIt));
153 
154  // Loop over the rechits of this DetUnit
155  for (DTRecSegment4DCollection::const_iterator segment = range.first; segment != range.second; ++segment) {
156  if (!(*segment).hasZed() && !(*segment).hasPhi()) {
157  LogError("Calibration") << "4D segment without Z and Phi segments";
158  continue;
159  }
160 
161  LogTrace("Calibration") << "Segment local pos (in chamber RF): " << (*segment).localPosition()
162  << "\nSegment global pos: " << chamber->toGlobal((*segment).localPosition());
163 
164  if (!((*select_)(*segment, event, eventSetup)))
165  continue;
166 
167  LocalPoint phiSeg2DPosInCham;
168  LocalVector phiSeg2DDirInCham;
169  map<DTSuperLayerId, vector<DTRecHit1D> > hitsBySLMap;
170  if ((*segment).hasPhi()) {
171  const DTChamberRecSegment2D* phiSeg = (*segment).phiSegment(); // phiSeg lives in the chamber RF
172  phiSeg2DPosInCham = phiSeg->localPosition();
173  phiSeg2DDirInCham = phiSeg->localDirection();
174  vector<DTRecHit1D> phiHits = phiSeg->specificRecHits();
175  for (vector<DTRecHit1D>::const_iterator hit = phiHits.begin(); hit != phiHits.end(); ++hit) {
176  DTWireId wireId = (*hit).wireId();
177  DTSuperLayerId slId = wireId.superlayerId();
178  hitsBySLMap[slId].push_back(*hit);
179  }
180  }
181  // Get the Theta 2D segment and plot the angle in the chamber RF
182  LocalVector zSeg2DDirInCham;
183  LocalPoint zSeg2DPosInCham;
184  if ((*segment).hasZed()) {
185  const DTSLRecSegment2D* zSeg = (*segment).zSegment(); // zSeg lives in the SL RF
186  const DTSuperLayer* sl = chamber->superLayer(zSeg->superLayerId());
187  zSeg2DPosInCham = chamber->toLocal(sl->toGlobal((*zSeg).localPosition()));
188  zSeg2DDirInCham = chamber->toLocal(sl->toGlobal((*zSeg).localDirection()));
189  hitsBySLMap[zSeg->superLayerId()] = zSeg->specificRecHits();
190  }
191 
192  LocalPoint segment4DLocalPos = (*segment).localPosition();
193  LocalVector segment4DLocalDir = (*segment).localDirection();
194  double chiSquare = ((*segment).chi2() / (*segment).degreesOfFreedom());
195 
196  hChi2->Fill(chiSquare);
197  if ((*segment).hasPhi())
198  h2DSegmRPhi->Fill(phiSeg2DPosInCham.x(), phiSeg2DDirInCham.x() / phiSeg2DDirInCham.z());
199  if ((*segment).hasZed())
200  h2DSegmRZ->Fill(zSeg2DPosInCham.y(), zSeg2DDirInCham.y() / zSeg2DDirInCham.z());
201 
202  if ((*segment).hasZed() && (*segment).hasPhi())
203  h4DSegmAllCh->Fill(segment4DLocalPos.x(),
204  segment4DLocalPos.y(),
205  atan(segment4DLocalDir.x() / segment4DLocalDir.z()) * 180. / Geom::pi(),
206  atan(segment4DLocalDir.y() / segment4DLocalDir.z()) * 180. / Geom::pi(),
207  180 - segment4DLocalDir.theta() * 180. / Geom::pi());
208  else if ((*segment).hasPhi())
209  h4DSegmAllCh->Fill(segment4DLocalPos.x(),
210  atan(segment4DLocalDir.x() / segment4DLocalDir.z()) * 180. / Geom::pi());
211  else if ((*segment).hasZed())
212  LogWarning("Calibration") << "4d segment with only Z";
213 
214  //loop over the segments
215  for (map<DTSuperLayerId, vector<DTRecHit1D> >::const_iterator slIdAndHits = hitsBySLMap.begin();
216  slIdAndHits != hitsBySLMap.end();
217  ++slIdAndHits) {
218  if (slIdAndHits->second.size() < 3)
219  continue;
220  DTSuperLayerId slId = slIdAndHits->first;
221 
222  // Create the DTTMax, that computes the 4 TMax
223  DTTMax slSeg(slIdAndHits->second,
224  *(chamber->superLayer(slIdAndHits->first)),
225  chamber->toGlobal((*segment).localDirection()),
226  chamber->toGlobal((*segment).localPosition()),
227  *theSync,
228  histograms_);
229 
230  if (theGranularity == bySL) {
231  vector<const TMax*> tMaxes = slSeg.getTMax(slId);
232  DTWireId wireId(slId, 0, 0);
233  theFile->cd();
234  cellInfo* cell = theWireIdAndCellMap[wireId];
235  if (cell == nullptr) {
236  TString name = (((((TString) "TMax" + (long)slId.wheel()) + (long)slId.station()) + (long)slId.sector()) +
237  (long)slId.superLayer());
238  cell = new cellInfo(name);
239  theWireIdAndCellMap[wireId] = cell;
240  }
241  cell->add(tMaxes);
242  cell->update(); // FIXME to reset the counter to avoid triple counting, which actually is not used...
243  } else {
244  LogWarning("Calibration") << "[DTVDriftCalibration] ###Warning: the chosen granularity is not implemented "
245  "yet, only bySL available!";
246  }
247  // to be implemented: granularity different from bySL
248 
249  // else if (theGranularity == byPartition) {
250  // // Use the custom granularity defined by partition();
251  // // in this case, add() should be called once for each Tmax of each layer
252  // // and triple counting should be avoided within add()
253  // vector<cellInfo*> cells;
254  // for (int i=1; i<=4; i++) {
255  // const DTTMax::InfoLayer* iLayer = slSeg.getInfoLayer(i);
256  // if(iLayer == 0) continue;
257  // cellInfo * cell = partition(iLayer->idWire);
258  // cells.push_back(cell);
259  // vector<const TMax*> tMaxes = slSeg.getTMax(iLayer->idWire);
260  // cell->add(tMaxes);
261  // }
262  // //reset the counter to avoid triple counting
263  // for (vector<cellInfo*>::const_iterator i = cells.begin();
264  // i!= cells.end(); i++) {
265  // (*i)->update();
266  // }
267  // }
268  }
269  }
270  }
271 }
272 
274  theFile->cd();
275  gROOT->GetList()->Write();
276  h2DSegmRPhi->Write();
277  h2DSegmRZ->Write();
278  h4DSegmAllCh->Write();
279  hChi2->Write();
280  // Instantiate a DTCalibrationMap object if you want to calculate the calibration constants
281  DTCalibrationMap calibValuesFile(theCalibFilePar);
282  // Create the object to be written to DB
283  std::unique_ptr<DTMtime> mTime;
284  std::unique_ptr<DTRecoConditions> vDrift;
285  if (writeLegacyVDriftDB) {
286  mTime = std::make_unique<DTMtime>();
287  } else {
288  vDrift = std::make_unique<DTRecoConditions>();
289  vDrift->setFormulaExpr("[0]");
290  //vDriftNewMap->setFormulaExpr("[0]*(1-[1]*x)"); // add parametrization for dependency along Y
291  vDrift->setVersion(1);
292  }
293 
294  // write the TMax histograms of each SL to the root file
295  if (theGranularity == bySL) {
296  for (map<DTWireId, cellInfo*>::const_iterator wireCell = theWireIdAndCellMap.begin();
297  wireCell != theWireIdAndCellMap.end();
298  ++wireCell) {
299  cellInfo* cell = theWireIdAndCellMap[(*wireCell).first];
300  hTMaxCell* cellHists = cell->getHists();
301  theFile->cd();
302  cellHists->Write();
303  if (findVDriftAndT0) { // if TRUE: evaluate calibration constants from TMax hists filled in this job
304  // evaluate v_drift and sigma from the TMax histograms
305  DTWireId wireId = (*wireCell).first;
306  vector<float> newConstants;
307  TString N = (((((TString) "TMax" + (long)wireId.wheel()) + (long)wireId.station()) + (long)wireId.sector()) +
308  (long)wireId.superLayer());
309  vector<float> vDriftAndReso = theFitter->evaluateVDriftAndReso(N);
310 
311  // Don't write the constants for the SL if the vdrift was not computed
312  if (vDriftAndReso.front() == -1)
313  continue;
314  const DTCalibrationMap::CalibConsts* oldConstants = calibValuesFile.getConsts(wireId);
315  if (oldConstants != nullptr) {
316  newConstants.push_back((*oldConstants)[0]);
317  newConstants.push_back((*oldConstants)[1]);
318  newConstants.push_back((*oldConstants)[2]);
319  } else {
320  newConstants.push_back(-1);
321  newConstants.push_back(-1);
322  newConstants.push_back(-1);
323  }
324  for (int ivd = 0; ivd <= 5; ivd++) {
325  // 0=vdrift, 1=reso, 2=(3deltat0-2deltat0), 3=(2deltat0-1deltat0),
326  // 4=(1deltat0-0deltat0), 5=deltat0 from hists with max entries,
327  newConstants.push_back(vDriftAndReso[ivd]);
328  }
329 
330  calibValuesFile.addCell(calibValuesFile.getKey(wireId), newConstants);
331 
332  // vdrift is cm/ns , resolution is cm
333  if (writeLegacyVDriftDB) {
334  mTime->set((wireId.layerId()).superlayerId(), vDriftAndReso[0], vDriftAndReso[1], DTVelocityUnits::cm_per_ns);
335  } else {
336  vector<double> params = {vDriftAndReso[0]};
337  vDrift->set(wireId, params);
338  }
339  LogTrace("Calibration") << " SL: " << (wireId.layerId()).superlayerId() << " vDrift = " << vDriftAndReso[0]
340  << " reso = " << vDriftAndReso[1];
341  }
342  }
343  }
344 
345  // to be implemented: granularity different from bySL
346 
347  // if(theGranularity == "byChamber") {
348  // const vector<DTChamber*> chambers = dMap.chambers();
349 
350  // // Loop over all chambers
351  // for(vector<MuBarChamber*>::const_iterator chamber = chambers.begin();
352  // chamber != chambers.end(); chamber ++) {
353  // MuBarChamberId chamber_id = (*chamber)->id();
354  // MuBarDigiParameters::Key wire_id(chamber_id, 0, 0, 0);
355  // vector<float> newConstants;
356  // vector<float> vDriftAndReso = evaluateVDriftAndReso(wire_id, f);
357  // const CalibConsts* oldConstants = digiParams.getConsts(wire_id);
358  // if(oldConstants !=0) {
359  // newConstants = *oldConstants;
360  // newConstants.push_back(vDriftAndReso[0]);
361  // newConstants.push_back(vDriftAndReso[1]);
362  // newConstants.push_back(vDriftAndReso[2]);
363  // newConstants.push_back(vDriftAndReso[3]);
364  // } else {
365  // newConstants.push_back(-1);
366  // newConstants.push_back(-1);
367  // newConstants.push_back(vDriftAndReso[0]);
368  // newConstants.push_back(vDriftAndReso[1]);
369  // newConstants.push_back(vDriftAndReso[2]);
370  // newConstants.push_back(vDriftAndReso[3]);
371  // }
372  // digiParams.addCell(wire_id, newConstants);
373  // }
374  // }
375 
376  // Write values to a table
377  calibValuesFile.writeConsts(theVDriftOutputFile);
378 
379  LogVerbatim("Calibration") << "[DTVDriftCalibration]Writing vdrift object to DB!";
380 
381  // Write the vdrift object to DB
382  if (writeLegacyVDriftDB) {
383  string record = "DTMtimeRcd";
384  DTCalibDBUtils::writeToDB<DTMtime>(record, *mTime);
385  } else {
386  DTCalibDBUtils::writeToDB<DTRecoConditions>("DTRecoConditionsVdriftRcd", *vDrift);
387  }
388 }
389 
390 // to be implemented: granularity different from bySL
391 
392 // // Create partitions
393 // DTVDriftCalibration::cellInfo* DTVDriftCalibration::partition(const DTWireId& wireId) {
394 // for( map<MuBarWireId, cellInfo*>::const_iterator iter =
395 // mapCellTmaxPart.begin(); iter != mapCellTmaxPart.end(); iter++) {
396 // // Divide wires per SL (with phi symmetry)
397 // if(iter->first.wheel() == wireId.wheel() &&
398 // iter->first.station() == wireId.station() &&
399 // // iter->first.sector() == wireId.sector() && // phi symmetry!
400 // iter->first.superlayer() == wireId.superlayer()) {
401 // return iter->second;
402 // }
403 // }
404 // cellInfo * result = new cellInfo("dummy string"); // FIXME: change constructor; create tree?
405 // mapCellTmaxPart.insert(make_pair(wireId, result));
406 // return result;
407 //}
408 
409 void DTVDriftCalibration::cellInfo::add(const vector<const TMax*>& _tMaxes) {
410  vector<const TMax*> tMaxes = _tMaxes;
411  float tmax123 = -1.;
412  float tmax124 = -1.;
413  float tmax134 = -1.;
414  float tmax234 = -1.;
415  SigmaFactor s124 = noR;
416  SigmaFactor s134 = noR;
417  unsigned t0_123 = 0;
418  unsigned t0_124 = 0;
419  unsigned t0_134 = 0;
420  unsigned t0_234 = 0;
421  unsigned hSubGroup = 0;
422  for (vector<const TMax*>::const_iterator it = tMaxes.begin(); it != tMaxes.end(); ++it) {
423  if (*it == nullptr) {
424  continue;
425  } else {
426  //FIXME check cached,
427  if (addedCells.size() == 4 || find(addedCells.begin(), addedCells.end(), (*it)->cells) != addedCells.end()) {
428  continue;
429  }
430  addedCells.push_back((*it)->cells);
431  SigmaFactor sigma = (*it)->sigma;
432  float t = (*it)->t;
433  TMaxCells cells = (*it)->cells;
434  unsigned t0Factor = (*it)->t0Factor;
435  hSubGroup = (*it)->hSubGroup;
436  if (t < 0.)
437  continue;
438  switch (cells) {
439  case notInit:
440  cout << "Error: no cell type assigned to TMax" << endl;
441  break;
442  case c123:
443  tmax123 = t;
444  t0_123 = t0Factor;
445  break;
446  case c124:
447  tmax124 = t;
448  s124 = sigma;
449  t0_124 = t0Factor;
450  break;
451  case c134:
452  tmax134 = t;
453  s134 = sigma;
454  t0_134 = t0Factor;
455  break;
456  case c234:
457  tmax234 = t;
458  t0_234 = t0Factor;
459  break;
460  }
461  }
462  }
463  //add entries to the TMax histograms
464  histos->Fill(tmax123, tmax124, tmax134, tmax234, s124, s134, t0_123, t0_124, t0_134, t0_234, hSubGroup);
465 }
Log< level::Info, true > LogVerbatim
int station() const
Return the station number.
Definition: DTChamberId.h:42
const edm::ESGetToken< DTGeometry, MuonGeometryRecord > theDTGeomToken
std::pair< const_iterator, const_iterator > range
iterator range
Definition: RangeMap.h:50
LocalPoint localPosition() const override
local position in SL frame
int superLayer() const
Return the superlayer number.
LocalVector localDirection() const override
the local direction in SL frame
TMaxGranularity theGranularity
T z() const
Definition: PV3DBase.h:61
std::unique_ptr< DTTTrigBaseSync > theSync
Definition: DTTMax.h:31
void Fill(float x, float y, float phi, float theta, float impact)
Definition: vDriftHistos.h:40
identifier iterator
Definition: RangeMap.h:130
void Fill(float pos, float localAngle)
Definition: vDriftHistos.h:91
void Write()
Definition: vDriftHistos.h:96
Log< level::Error, false > LogError
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
Definition: FindCaloHit.cc:19
std::vector< const TMax * > getTMax(const DTWireId &idWire)
Definition: DTTMax.cc:303
#define LogTrace(id)
C::const_iterator const_iterator
constant access iterator type
Definition: RangeMap.h:43
std::map< DTWireId, cellInfo * > theWireIdAndCellMap
T x() const
Definition: PV3DBase.h:59
T y() const
Definition: PV3DBase.h:60
edm::ParameterSet theCalibFilePar
const CalibConsts * getConsts(DTWireId wireId) const
std::vector< float > CalibConsts
void addCell(Key wireId, const CalibConsts &calibConst)
edm::EDGetTokenT< DTRecSegment4DCollection > theRecHits4DToken
Key getKey(DTWireId wireId) const
void Write()
Definition: vDriftHistos.h:463
DTSuperLayerId superLayerId() const
The id of the superlayer on which reside the segment.
GlobalPoint toGlobal(const Local2DPoint &lp) const
Conversion to the global R.F. from the R.F. of the GeomDet.
Definition: GeomDet.h:49
std::unique_ptr< DTMeanTimerFitter > theFitter
void Fill(float tmax123, float tmax124, float tmax134, float tmax234, dttmaxenums::SigmaFactor s124, dttmaxenums::SigmaFactor s134, unsigned t0_123, unsigned t0_124, unsigned t0_134, unsigned t0_234, unsigned hSubGroup)
Definition: vDriftHistos.h:209
caConstants::TupleMultiplicity const CAHitNtupletGeneratorKernelsGPU::HitToTuple const cms::cuda::AtomicPairCounter GPUCACell const *__restrict__ cells
#define debug
Definition: HDRShower.cc:19
#define N
Definition: blowfish.cc:9
~DTVDriftCalibration() override
Destructor.
dtcalibration::Histograms histograms_
std::unique_ptr< DTSegmentSelector > select_
std::vector< DTRecHit1D > specificRecHits() const
Access to specific components.
void analyze(const edm::Event &event, const edm::EventSetup &eventSetup) override
void writeConsts(const std::string &outputFileName) const
int wheel() const
Return the wheel number.
Definition: DTChamberId.h:39
HLT enums.
int sector() const
Definition: DTChamberId.h:49
DTVDriftCalibration(const edm::ParameterSet &pset)
Constructor.
DTSuperLayerId superlayerId() const
Return the corresponding SuperLayerId.
Definition: DTLayerId.h:45
void add(const std::vector< const TMax *> &tMaxes)
std::vector< dttmaxenums::TMaxCells > addedCells
#define get
DTLayerId layerId() const
Return the corresponding LayerId.
Definition: DTWireId.h:45
Log< level::Warning, false > LogWarning
constexpr double pi()
Definition: Pi.h:31
const DTChamber * chamber(const DTChamberId &id) const
Return a DTChamber given its id.
Definition: DTGeometry.cc:90
void Write()
Definition: vDriftHistos.h:51
Definition: event.py:1
Geom::Theta< T > theta() const
Definition: PV3DBase.h:72