CMS 3D CMS Logo

MuonMillepedeAlgorithm.cc
Go to the documentation of this file.
1  #include <fstream>
2 
3  #include "TFile.h"
4  #include "TTree.h"
5  #include "TKey.h"
6 
11 
12 
15 
28 
30 
32 
33 
34  // Constructor ----------------------------------------------------------------
35 
38  {
39 
40  // parse parameters
41 
42  edm::LogWarning("Alignment") << "[MuonMillepedeAlgorithm] constructed.";
43 
44 
45  collec_f = cfg.getParameter<std::string>( "CollectionFile" );
46 
47  isCollectionJob = cfg.getParameter<bool>( "isCollectionJob" );
48 
49  collec_path = cfg.getParameter<std::string>( "collectionPath" );
50 
51  collec_number = cfg.getParameter<int>( "collectionNumber" );
52 
53  outputCollName = cfg.getParameter<std::string>( "outputCollName" );
54 
55  ptCut = cfg.getParameter<double>( "ptCut" );
56 
57  chi2nCut = cfg.getParameter<double>( "chi2nCut" );
58 
59 
60  }
61 
62  // Call at beginning of job ---------------------------------------------------
63 
64  void
67  AlignableExtras* extras,
69  {
70 
71  edm::LogWarning("Alignment") << "[MuonMillepedeAlgorithm] Initializing...";
72 
73  // accessor Det->AlignableDet
74  theAlignableDetAccessor = new AlignableNavigator(tracker, muon);
75 
76  // set alignmentParameterStore
78 
79  // get alignables
81 
82  }
83 
85  {
86 
87  std::map<std::string, TMatrixD *> map;
88 
89  for(int c_job = 0; c_job < collec_number; ++c_job)
90  {
91  char name_f[40];
92  snprintf(name_f, sizeof(name_f), "%s_%d/%s", collec_path.c_str(), c_job, collec_f.c_str());
93  TFile file_it(name_f);
94 
95  if(file_it.IsZombie())
96  continue;
97 
98  TList *m_list = file_it.GetListOfKeys();
99  if(m_list == nullptr) {
100  return;
101  }
102  TKey *index = (TKey *)m_list->First();
103  if(index == nullptr) {
104  }
105  if( index != nullptr )
106  {
107  do
108  {
109 
110  std::string objectName(index->GetName());
111  TMatrixD *mat = (TMatrixD *)index->ReadObj();
112  std::map<std::string, TMatrixD *>::iterator node = map.find(objectName);
113  if(node == map.end())
114  {
115  TMatrixD *n_mat = new TMatrixD(mat->GetNrows(), mat->GetNcols());
116  map.insert(make_pair(objectName, n_mat));
117  }
118  *(map[objectName]) += *mat;
119  index = (TKey*)m_list->After(index);
120  } while(index != nullptr);
121  }
122  file_it.Close();
123  }
124 
125 
126  TFile theFile2(outputCollName.c_str(), "recreate");
127  theFile2.cd();
128 
129  std::map<std::string, TMatrixD *>::iterator m_it = map.begin();
130  for(; m_it != map.end(); ++m_it)
131  {
132  if(m_it->first.find("_invCov") != std::string::npos)
133  {
134  std::string id_s = m_it->first.substr(0, m_it->first.find("_invCov"));
135  std::string id_w = id_s + "_weightRes";
136  std::string id_n = id_s + "_N";
137  std::string cov = id_s + "_cov";
138  std::string sol = id_s + "_sol";
139 
140  //Covariance calculation
141  TMatrixD invMat( m_it->second->GetNrows(), m_it->second->GetNcols());
142  invMat = *(m_it->second);
143  invMat.Invert();
144  //weighted residuals
145  TMatrixD weightMat( m_it->second->GetNcols(), 1);
146  weightMat = *(map[id_w]);
147  //Solution of the linear system
148  TMatrixD solution( m_it->second->GetNrows(), 1);
149  solution = invMat * weightMat;
150  //Number of Tracks
151  TMatrixD n(1,1);
152  n = *(map[id_n]);
153 
154  invMat.Write(cov.c_str());
155  n.Write(id_n.c_str());
156  solution.Write(sol.c_str());
157  }
158  }
159  theFile2.Write();
160  theFile2.Close();
161  }
162 
163 
164  // Call at end of job ---------------------------------------------------------
165 
167  {
168 
169  if( isCollectionJob )
170  {
171  this->collect();
172  return;
173  }
174 
175 
176  edm::LogWarning("Alignment") << "[MuonMillepedeAlgorithm] Terminating";
177 
178  // iterate over alignment parameters
179  for(const auto& ali: theAlignables) {
180  // Alignment parameters
181  // AlignmentParameters* par = ali->alignmentParameters();
182  edm::LogInfo("Alignment") << "now apply params";
184  // set these parameters 'valid'
185  ali->alignmentParameters()->setValid(true);
186 
187  }
188 
189  edm::LogWarning("Alignment") << "[MuonMillepedeAlgorithm] Writing aligned parameters to file: " << theAlignables.size();
190 
191  TFile *theFile = new TFile(collec_f.c_str(), "recreate");
192  theFile->cd();
193  std::map<std::string, AlgebraicMatrix *>::iterator invCov_it = map_invCov.begin();
194  std::map<std::string, AlgebraicMatrix *>::iterator weightRes_it = map_weightRes.begin();
195  std::map<std::string, AlgebraicMatrix *>::iterator n_it = map_N.begin();
196  for(; n_it != map_N.end(); ++invCov_it, ++weightRes_it, ++n_it)
197  {
198  TMatrixD tmat_invcov(0,0);
199  this->toTMat(invCov_it->second, &tmat_invcov);
200  TMatrixD tmat_weightres(0,0);
201  this->toTMat(weightRes_it->second, &tmat_weightres);
202  TMatrixD tmat_n(0,0);
203  this->toTMat(n_it->second, &tmat_n);
204 
205  tmat_invcov.Write(invCov_it->first.c_str());
206  tmat_weightres.Write(weightRes_it->first.c_str());
207  tmat_n.Write(n_it->first.c_str());
208  }
209 
210  theFile->Write();
211  theFile->Close();
212 
213  }
214 
215 
216  void MuonMillepedeAlgorithm::toTMat(AlgebraicMatrix *am_mat, TMatrixD *tmat_mat)
217  {
218  tmat_mat->ResizeTo(am_mat->num_row(), am_mat->num_col());
219  for(int c_i = 0; c_i < am_mat->num_row(); ++c_i) {
220  for(int c_j = 0; c_j < am_mat->num_col(); ++c_j) {
221  (*tmat_mat)(c_i, c_j) = (*am_mat)[c_i][c_j];
222  }
223  }
224  }
225 
226 
227 
228  // Run the algorithm on trajectories and tracks -------------------------------
229 
231  {
232 
233  if( isCollectionJob )
234  {
235  return;
236  }
237 
238 
239  // loop over tracks
240  //int t_counter = 0;
242  for( ConstTrajTrackPairCollection::const_iterator it=tracks.begin();
243  it!=tracks.end();it++) {
244 
245  const Trajectory* traj = (*it).first;
246  const reco::Track* track = (*it).second;
247 
248  float pt = track->pt();
249  float chi2n = track->normalizedChi2();
250 #ifdef EDM_ML_DEBUG
251  float eta = track->eta();
252  float phi = track->phi();
253  //int ndof = track->ndof();
254  int nhit = track->numberOfValidHits();
255 
256  LogDebug("Alignment")
257  << "New track pt,eta,phi,chi2n,hits: "
258  << pt << "," << eta << "," << phi << "," << chi2n << "," << nhit;
259 #endif
260 
261  //Accept or not accept the track
262  if( pt > ptCut && chi2n < chi2nCut )
263  {
264 
265 
266  std::vector<const TransientTrackingRecHit*> hitvec;
267  std::vector<TrajectoryStateOnSurface> tsosvec;
268 
269  std::vector<TrajectoryMeasurement> measurements = traj->measurements();
270 
271  //In this loop the measurements and hits are extracted and put on two vectors
272  for (std::vector<TrajectoryMeasurement>::iterator im=measurements.begin();
273  im!=measurements.end(); im++)
274  {
275  TrajectoryMeasurement meas = *im;
276  const TransientTrackingRecHit* hit = &(*meas.recHit());
277  //We are not very strict at this point
279  {
280  //***Forward
281  const TrajectoryStateOnSurface& tsos = meas.forwardPredictedState();
282  if (tsos.isValid())
283  {
284  hitvec.push_back(hit);
285  tsosvec.push_back(tsos);
286  }
287  }
288  }
289 
290  // transform RecHit vector to AlignableDet vector
291  std::vector <AlignableDetOrUnitPtr> alidetvec =
293 
294  // get concatenated alignment parameters for list of alignables
297 
298  std::vector<TrajectoryStateOnSurface>::const_iterator itsos=tsosvec.begin();
299  std::vector<const TransientTrackingRecHit*>::const_iterator ihit=hitvec.begin();
300 
301 
302  //int ch_counter = 0;
303 
304  while (itsos != tsosvec.end())
305  {
306  // get AlignableDet for this hit
307  const GeomDet* det=(*ihit)->det();
308  AlignableDetOrUnitPtr alidet =
310 
311  // get relevant Alignable
312  Alignable* ali=aap.alignableFromAlignableDet(alidet);
313 
314  //To be sure that the ali is not null and that it's a DT segment
315  if ( ali!=nullptr && (*ihit)->geographicalId().subdetId() == 1)
316  {
317  DTChamberId m_Chamber(det->geographicalId());
318  //Station 4 does not contain Theta SL
319  if((*ihit)->dimension() == 4 || ((*ihit)->dimension() == 2 && m_Chamber.station() == 4))
320  //if((*ihit)->dimension() == 4)
321  {
322  edm::LogInfo("Alignment") << "Entrando";
323 
324  AlignmentParameters* params = ali->alignmentParameters();
325 
326  edm::LogInfo("Alignment") << "Entrando";
327  //(dx/dz,dy/dz,x,y) for a 4DSegment
328  AlgebraicVector ihit4D = (*ihit)->parameters();
329 
330  //The innerMostState always contains the Z
331  //(q/pt,dx/dz,dy/dz,x,y)
332  AlgebraicVector5 alivec = (*itsos).localParameters().mixedFormatVector();
333 
334  //The covariance matrix follows the sequence
335  //(q/pt,dx/dz,dy/dz,x,y) but we reorder to
336  //(x,y,dx/dz,dy/dz)
337  AlgebraicSymMatrix55 rawCovMat = (*itsos).localError().matrix();
338  AlgebraicMatrix CovMat(4,4);
339  int m_index[] = {2,3,0,1};
340  for(int c_ei = 0; c_ei < 4; ++c_ei)
341  {
342  for(int c_ej = 0; c_ej < 4; ++c_ej)
343  {
344  CovMat[m_index[c_ei]][m_index[c_ej]] = rawCovMat(c_ei+1,c_ej+1);
345  }
346  }
347 
348  int inv_check;
349  //printM(CovMat);
350  CovMat.invert(inv_check);
351  if (inv_check != 0) {
352  edm::LogError("Alignment") << "Covariance Matrix inversion failed";
353  return;
354  }
355 
356 
357 
358  //The order is changed to:
359  // (x,0,dx/dz,0) MB4 Chamber
360  // (x,y,dx/dz,dy/dz) Not MB4 Chamber
361  AlgebraicMatrix residuals(4,1);
362  if(m_Chamber.station() == 4)
363  {
364  //Filling Residuals
365  residuals[0][0] = ihit4D[2]-alivec[3];
366  residuals[1][0] = 0.0;
367  residuals[2][0] = ihit4D[0]-alivec[1];
368  residuals[3][0] = 0.0;
369  //The error in the Theta coord is set to infinite
370  CovMat[1][0] = 0.0; CovMat[1][1] = 0.0; CovMat[1][2] = 0.0;
371  CovMat[1][3] = 0.0; CovMat[0][1] = 0.0; CovMat[2][1] = 0.0;
372  CovMat[3][1] = 0.0; CovMat[3][0] = 0.0; CovMat[3][2] = 0.0;
373  CovMat[3][3] = 0.0; CovMat[0][3] = 0.0; CovMat[2][3] = 0.0;
374  }
375  else
376  {
377  //Filling Residuals
378  residuals[0][0] = ihit4D[2]-alivec[3];
379  residuals[1][0] = ihit4D[3]-alivec[4];
380  residuals[2][0] = ihit4D[0]-alivec[1];
381  residuals[3][0] = ihit4D[1]-alivec[2];
382  }
383 
384  // Derivatives
385  AlgebraicMatrix derivsAux = params->selectedDerivatives(*itsos,alidet);
386 
387  std::vector<bool> mb4_mask;
388  std::vector<bool> selection;
389  //To be checked
390  mb4_mask.push_back(true); mb4_mask.push_back(false); mb4_mask.push_back(true);
391  mb4_mask.push_back(true); mb4_mask.push_back(true); mb4_mask.push_back(false);
392  selection.push_back(true); selection.push_back(true); selection.push_back(false);
393  selection.push_back(false); selection.push_back(false); selection.push_back(false);
394  int nAlignParam = 0;
395  if(m_Chamber.station() == 4)
396  {
397  for(int icor = 0; icor < 6; ++icor)
398  {
399  if(mb4_mask[icor] && selection[icor]) nAlignParam++;
400  }
401  }
402  else
403  {
404  nAlignParam = derivsAux.num_row();
405  }
406 
407  AlgebraicMatrix derivs(nAlignParam, 4);
408  if(m_Chamber.station() == 4)
409  {
410  int der_c = 0;
411  for(int icor = 0; icor < 6; ++icor)
412  {
413  if(mb4_mask[icor] && selection[icor])
414  {
415  for(int ccor = 0; ccor < 4; ++ccor)
416  {
417  derivs[der_c][ccor] = derivsAux[icor][ccor];
418  ++der_c;
419  }
420  }
421  }
422  }
423  else
424  {
425  derivs = derivsAux;
426  }
427 
428 
429  //for(int co = 0; co < derivs.num_row(); ++co)
430  //{
431  // for(int ci = 0; ci < derivs.num_col(); ++ci)
432  // {
433  // edm::LogInfo("Alignment") << "Derivatives: " << co << " " << ci << " " << derivs[co][ci] << " ";
434  // }
435  //}
436 
437  AlgebraicMatrix derivsT = derivs.T();
438  AlgebraicMatrix invCov = derivs*CovMat*derivsT;
439  AlgebraicMatrix weightRes = derivs*CovMat*residuals;
440 
441  //this->printM(derivs);
442  //this->printM(CovMat);
443  //this->printM(residuals);
444 
445  char name[40];
446  snprintf(name, sizeof(name),
447  "Chamber_%d_%d_%d", m_Chamber.wheel(), m_Chamber.station(), m_Chamber.sector());
448  std::string chamId(name);
449  //MB4 need a special treatment
450  /*AlgebraicMatrix invCovMB4(2,2);
451  AlgebraicMatrix weightResMB4(2,1);
452  if( m_Chamber.station() == 4 )
453  {
454  int m_index_2[] = {0,2};
455  for(int c_i = 0; c_i < 2; ++c_i)
456  {
457  weightResMB4[c_i][0] = weightRes[m_index_2[c_i]][0];
458  for(int c_j = 0; c_j < 2; ++c_j)
459  {
460  invCovMB4[c_i][c_j] = invCov[m_index_2[c_i]][m_index_2[c_j]];
461  }
462  }
463  this->updateInfo(invCovMB4, weightResMB4, residuals, chamId);
464  }
465  else
466  {
467  this->updateInfo(invCov, weightRes, residuals, chamId);
468  }*/
469  this->updateInfo(invCov, weightRes, residuals, chamId);
470  }
471  }
472  itsos++;
473  ihit++;
474  }
475  }
476  } // end of track loop
477 
478  }
479 
480 
481  //Auxiliar
483  {
484  //for(int i = 0; i < m.num_row(); ++i)
485  // {
486  // for(int j = 0; j < m.num_col(); ++j)
487  // {
488  // std::cout << m[i][j] << " ";
489  // }
490  // std::cout << std::endl;
491  //}
492  }
493 
495  const AlgebraicMatrix& m_weightRes,
496  const AlgebraicMatrix& m_res,
497  std::string id)
498  {
499 
500 
501 
502  std::string id_invCov = id + "_invCov";
503  std::string id_weightRes = id + "_weightRes";
504  std::string id_n = id + "_N";
505 
506  edm::LogInfo("Alignment") << "Entrando";
507 
508  std::map<std::string, AlgebraicMatrix *>::iterator node = map_invCov.find(id_invCov);
509  if(node == map_invCov.end())
510  {
511  AlgebraicMatrix *f_invCov = new AlgebraicMatrix(m_invCov.num_row(), m_invCov.num_col());
512  AlgebraicMatrix *f_weightRes = new AlgebraicMatrix(m_weightRes.num_row(), m_weightRes.num_col());
513  AlgebraicMatrix *f_n = new AlgebraicMatrix(1,1);
514 
515  map_invCov.insert(make_pair(id_invCov, f_invCov));
516  map_weightRes.insert(make_pair(id_weightRes, f_weightRes));
517  map_N.insert(make_pair(id_n, f_n));
518 
519  for(int iCount = 0; iCount < 4; ++iCount)
520  {
521  char name[40];
522  snprintf(name, sizeof(name), "%s_var_%d", id.c_str(), iCount);
523  std::string idName(name);
524  float range = 5.0;
525  //if( iCount == 0 || iCount == 1 ) {
526  // range = 0.01;
527  //}
528  TH1D *histo = fs->make<TH1D>(idName.c_str(), idName.c_str(), 200, -range, range );
529  histoMap.insert(make_pair(idName, histo));
530  }
531  }
532 
533  *map_invCov[id_invCov] = *map_invCov[id_invCov] + m_invCov;
534  *map_weightRes[id_weightRes] = *map_weightRes[id_weightRes] + m_weightRes;
535  (*map_N[id_n])[0][0]++;
536 
537  for(int iCount = 0; iCount < 4; ++iCount)
538  {
539  char name[40];
540  snprintf(name, sizeof(name), "%s_var_%d", id.c_str(), iCount);
541  std::string idName(name);
542  histoMap[idName]->Fill(m_res[iCount][0]);
543  }
544  }
545 
546 
547 
549 
#define LogDebug(id)
T getParameter(std::string const &) const
std::map< std::string, AlgebraicMatrix * > map_weightRes
AlignableNavigator * theAlignableDetAccessor
ConstRecHitPointer const & recHit() const
AlignableDetOrUnitPtr alignableFromGeomDet(const GeomDet *geomDet)
Returns AlignableDetOrUnitPtr corresponding to given GeomDet.
double normalizedChi2() const
chi-squared divided by n.d.o.f. (or chi-squared * 1e6 if n.d.o.f. is zero)
Definition: TrackBase.h:561
void initialize(const edm::EventSetup &setup, AlignableTracker *tracker, AlignableMuon *muon, AlignableExtras *extras, AlignmentParameterStore *store) override
Call at beginning of job.
selection
main part
Definition: corrVsCorr.py:98
def setup(process, global_tag, zero_tesla=False)
Definition: GeneralSetup.py:1
double phi() const
azimuthal angle of momentum vector
Definition: TrackBase.h:645
T * make(const Args &...args) const
make new ROOT object
Definition: TFileService.h:64
void applyParameters(void)
Obsolete: Use AlignableNavigator::alignableDetFromDetId and alignableFromAlignableDet.
ROOT::Math::SMatrix< double, 5, 5, ROOT::Math::MatRepSym< double, 5 > > AlgebraicSymMatrix55
Alignable * alignableFromAlignableDet(const AlignableDetOrUnitPtr &adet) const
Get relevant Alignable from AlignableDet.
AlignmentParameters * alignmentParameters() const
Get the AlignmentParameters.
Definition: Alignable.h:61
edm::Service< TFileService > fs
const ConstTrajTrackPairCollection & trajTrackPairs() const
void toTMat(AlgebraicMatrix *, TMatrixD *)
define event information passed to algorithms
DataContainer const & measurements() const
Definition: Trajectory.h:196
double eta() const
pseudorapidity of momentum vector
Definition: TrackBase.h:651
CLHEP::HepMatrix AlgebraicMatrix
double pt() const
track transverse momentum
Definition: TrackBase.h:621
MuonMillepedeAlgorithm(const edm::ParameterSet &cfg)
Constructor.
DetId geographicalId() const
The label of this GeomDet.
Definition: GeomDet.h:79
void updateInfo(const AlgebraicMatrix &, const AlgebraicMatrix &, const AlgebraicMatrix &, std::string)
unsigned short numberOfValidHits() const
number of valid hits found
Definition: TrackBase.h:820
TrajectoryStateOnSurface const & forwardPredictedState() const
Access to forward predicted state (from fitter or builder)
CLHEP::HepVector AlgebraicVector
void printM(const AlgebraicMatrix &)
ROOT::Math::SVector< double, 5 > AlgebraicVector5
AlignmentParameterStore * theAlignmentParameterStore
CompositeAlignmentParameters selectParameters(const std::vector< AlignableDet * > &alignabledets) const
bool isValid() const
std::map< std::string, AlgebraicMatrix * > map_N
virtual void terminate()
Called at end of job (must be implemented in derived class)
std::vector< AlignableDetOrUnitPtr > alignablesFromHits(const std::vector< const TransientTrackingRecHit * > &hitvec)
Returns vector AlignableDetOrUnitPtr for given vector of Hits.
std::map< std::string, TH1D * > histoMap
#define DEFINE_EDM_PLUGIN(factory, type, name)
eventInfo
add run, event number and lumi section
DetId geographicalId() const
bool detAndSubdetInMap(const DetId &detid) const
Given a DetId, returns true if DetIds with this detector and subdetector id are in the map (not neces...
Constructor of the full muon geometry.
Definition: AlignableMuon.h:37
align::Alignables theAlignables
void run(const edm::EventSetup &setup, const EventInfo &eventInfo) override
Run the algorithm.
const align::Alignables & alignables(void) const
get all alignables
std::vector< ConstTrajTrackPair > ConstTrajTrackPairCollection
std::map< std::string, AlgebraicMatrix * > map_invCov
virtual AlgebraicMatrix selectedDerivatives(const TrajectoryStateOnSurface &tsos, const AlignableDetOrUnitPtr &alidet) const