CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
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 == 0) {
100  return;
101  }
102  TKey *index = (TKey *)m_list->First();
103  if(index == 0) {
104  }
105  if( index != 0 )
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 != 0);
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(std::vector<Alignable*>::const_iterator
180  it=theAlignables.begin(); it!=theAlignables.end(); it++) {
181  Alignable* ali=(*it);
182  // Alignment parameters
183  // AlignmentParameters* par = ali->alignmentParameters();
184  edm::LogInfo("Alignment") << "now apply params";
186  // set these parameters 'valid'
187  ali->alignmentParameters()->setValid(true);
188 
189  }
190 
191  edm::LogWarning("Alignment") << "[MuonMillepedeAlgorithm] Writing aligned parameters to file: " << theAlignables.size();
192 
193  TFile *theFile = new TFile(collec_f.c_str(), "recreate");
194  theFile->cd();
195  std::map<std::string, AlgebraicMatrix *>::iterator invCov_it = map_invCov.begin();
196  std::map<std::string, AlgebraicMatrix *>::iterator weightRes_it = map_weightRes.begin();
197  std::map<std::string, AlgebraicMatrix *>::iterator n_it = map_N.begin();
198  for(; n_it != map_N.end(); ++invCov_it, ++weightRes_it, ++n_it)
199  {
200  TMatrixD tmat_invcov(0,0);
201  this->toTMat(invCov_it->second, &tmat_invcov);
202  TMatrixD tmat_weightres(0,0);
203  this->toTMat(weightRes_it->second, &tmat_weightres);
204  TMatrixD tmat_n(0,0);
205  this->toTMat(n_it->second, &tmat_n);
206 
207  tmat_invcov.Write(invCov_it->first.c_str());
208  tmat_weightres.Write(weightRes_it->first.c_str());
209  tmat_n.Write(n_it->first.c_str());
210  }
211 
212  theFile->Write();
213  theFile->Close();
214 
215  }
216 
217 
218  void MuonMillepedeAlgorithm::toTMat(AlgebraicMatrix *am_mat, TMatrixD *tmat_mat)
219  {
220  tmat_mat->ResizeTo(am_mat->num_row(), am_mat->num_col());
221  for(int c_i = 0; c_i < am_mat->num_row(); ++c_i) {
222  for(int c_j = 0; c_j < am_mat->num_col(); ++c_j) {
223  (*tmat_mat)(c_i, c_j) = (*am_mat)[c_i][c_j];
224  }
225  }
226  }
227 
228 
229 
230  // Run the algorithm on trajectories and tracks -------------------------------
231 
233  {
234 
235  if( isCollectionJob )
236  {
237  return;
238  }
239 
240 
241  // loop over tracks
242  //int t_counter = 0;
244  for( ConstTrajTrackPairCollection::const_iterator it=tracks.begin();
245  it!=tracks.end();it++) {
246 
247  const Trajectory* traj = (*it).first;
248  const reco::Track* track = (*it).second;
249 
250  float pt = track->pt();
251  float eta = track->eta();
252  float phi = track->phi();
253  float chi2n = track->normalizedChi2();
254  //int ndof = track->ndof();
255  int nhit = track->numberOfValidHits();
256 
257  if (0) edm::LogInfo("Alignment") << "New track pt,eta,phi,chi2n,hits: " << pt <<","<< eta <<","<< phi <<","<< chi2n << ","<<nhit;
258 
259  //Accept or not accept the track
260  if( pt > ptCut && chi2n < chi2nCut )
261  {
262 
263 
264  std::vector<const TransientTrackingRecHit*> hitvec;
265  std::vector<TrajectoryStateOnSurface> tsosvec;
266 
267  std::vector<TrajectoryMeasurement> measurements = traj->measurements();
268 
269  //In this loop the measurements and hits are extracted and put on two vectors
270  for (std::vector<TrajectoryMeasurement>::iterator im=measurements.begin();
271  im!=measurements.end(); im++)
272  {
273  TrajectoryMeasurement meas = *im;
274  const TransientTrackingRecHit* hit = &(*meas.recHit());
275  //We are not very strict at this point
277  {
278  //***Forward
280  if (tsos.isValid())
281  {
282  hitvec.push_back(hit);
283  tsosvec.push_back(tsos);
284  }
285  }
286  }
287 
288  // transform RecHit vector to AlignableDet vector
289  std::vector <AlignableDetOrUnitPtr> alidetvec =
291 
292  // get concatenated alignment parameters for list of alignables
295 
296  std::vector<TrajectoryStateOnSurface>::const_iterator itsos=tsosvec.begin();
297  std::vector<const TransientTrackingRecHit*>::const_iterator ihit=hitvec.begin();
298 
299 
300  //int ch_counter = 0;
301 
302  while (itsos != tsosvec.end())
303  {
304  // get AlignableDet for this hit
305  const GeomDet* det=(*ihit)->det();
306  AlignableDetOrUnitPtr alidet =
308 
309  // get relevant Alignable
310  Alignable* ali=aap.alignableFromAlignableDet(alidet);
311 
312  //To be sure that the ali is not null and that it's a DT segment
313  if ( ali!=0 && (*ihit)->geographicalId().subdetId() == 1)
314  {
315  DTChamberId m_Chamber(det->geographicalId());
316  //Station 4 does not contain Theta SL
317  if((*ihit)->dimension() == 4 || ((*ihit)->dimension() == 2 && m_Chamber.station() == 4))
318  //if((*ihit)->dimension() == 4)
319  {
320  edm::LogInfo("Alignment") << "Entrando";
321 
322  AlignmentParameters* params = ali->alignmentParameters();
323 
324  edm::LogInfo("Alignment") << "Entrando";
325  //(dx/dz,dy/dz,x,y) for a 4DSegment
326  AlgebraicVector ihit4D = (*ihit)->parameters();
327 
328  //The innerMostState always contains the Z
329  //(q/pt,dx/dz,dy/dz,x,y)
330  AlgebraicVector5 alivec = (*itsos).localParameters().mixedFormatVector();
331 
332  //The covariance matrix follows the sequence
333  //(q/pt,dx/dz,dy/dz,x,y) but we reorder to
334  //(x,y,dx/dz,dy/dz)
335  AlgebraicSymMatrix55 rawCovMat = (*itsos).localError().matrix();
336  AlgebraicMatrix CovMat(4,4);
337  int m_index[] = {2,3,0,1};
338  for(int c_ei = 0; c_ei < 4; ++c_ei)
339  {
340  for(int c_ej = 0; c_ej < 4; ++c_ej)
341  {
342  CovMat[m_index[c_ei]][m_index[c_ej]] = rawCovMat(c_ei+1,c_ej+1);
343  }
344  }
345 
346  int inv_check;
347  //printM(CovMat);
348  CovMat.invert(inv_check);
349  if (inv_check != 0) {
350  edm::LogError("Alignment") << "Covariance Matrix inversion failed";
351  return;
352  }
353 
354 
355 
356  //The order is changed to:
357  // (x,0,dx/dz,0) MB4 Chamber
358  // (x,y,dx/dz,dy/dz) Not MB4 Chamber
359  AlgebraicMatrix residuals(4,1);
360  if(m_Chamber.station() == 4)
361  {
362  //Filling Residuals
363  residuals[0][0] = ihit4D[2]-alivec[3];
364  residuals[1][0] = 0.0;
365  residuals[2][0] = ihit4D[0]-alivec[1];
366  residuals[3][0] = 0.0;
367  //The error in the Theta coord is set to infinite
368  CovMat[1][0] = 0.0; CovMat[1][1] = 0.0; CovMat[1][2] = 0.0;
369  CovMat[1][3] = 0.0; CovMat[0][1] = 0.0; CovMat[2][1] = 0.0;
370  CovMat[3][1] = 0.0; CovMat[3][0] = 0.0; CovMat[3][2] = 0.0;
371  CovMat[3][3] = 0.0; CovMat[0][3] = 0.0; CovMat[2][3] = 0.0;
372  }
373  else
374  {
375  //Filling Residuals
376  residuals[0][0] = ihit4D[2]-alivec[3];
377  residuals[1][0] = ihit4D[3]-alivec[4];
378  residuals[2][0] = ihit4D[0]-alivec[1];
379  residuals[3][0] = ihit4D[1]-alivec[2];
380  }
381 
382  // Derivatives
383  AlgebraicMatrix derivsAux = params->selectedDerivatives(*itsos,alidet);
384 
385  std::vector<bool> mb4_mask;
386  std::vector<bool> selection;
387  //To be checked
388  mb4_mask.push_back(true); mb4_mask.push_back(false); mb4_mask.push_back(true);
389  mb4_mask.push_back(true); mb4_mask.push_back(true); mb4_mask.push_back(false);
390  selection.push_back(true); selection.push_back(true); selection.push_back(false);
391  selection.push_back(false); selection.push_back(false); selection.push_back(false);
392  int nAlignParam = 0;
393  if(m_Chamber.station() == 4)
394  {
395  for(int icor = 0; icor < 6; ++icor)
396  {
397  if(mb4_mask[icor] && selection[icor]) nAlignParam++;
398  }
399  }
400  else
401  {
402  nAlignParam = derivsAux.num_row();
403  }
404 
405  AlgebraicMatrix derivs(nAlignParam, 4);
406  if(m_Chamber.station() == 4)
407  {
408  int der_c = 0;
409  for(int icor = 0; icor < 6; ++icor)
410  {
411  if(mb4_mask[icor] && selection[icor])
412  {
413  for(int ccor = 0; ccor < 4; ++ccor)
414  {
415  derivs[der_c][ccor] = derivsAux[icor][ccor];
416  ++der_c;
417  }
418  }
419  }
420  }
421  else
422  {
423  derivs = derivsAux;
424  }
425 
426 
427  //for(int co = 0; co < derivs.num_row(); ++co)
428  //{
429  // for(int ci = 0; ci < derivs.num_col(); ++ci)
430  // {
431  // edm::LogInfo("Alignment") << "Derivatives: " << co << " " << ci << " " << derivs[co][ci] << " ";
432  // }
433  //}
434 
435  AlgebraicMatrix derivsT = derivs.T();
436  AlgebraicMatrix invCov = derivs*CovMat*derivsT;
437  AlgebraicMatrix weightRes = derivs*CovMat*residuals;
438 
439  //this->printM(derivs);
440  //this->printM(CovMat);
441  //this->printM(residuals);
442 
443  char name[40];
444  snprintf(name, sizeof(name),
445  "Chamber_%d_%d_%d", m_Chamber.wheel(), m_Chamber.station(), m_Chamber.sector());
446  std::string chamId(name);
447  //MB4 need a special treatment
448  /*AlgebraicMatrix invCovMB4(2,2);
449  AlgebraicMatrix weightResMB4(2,1);
450  if( m_Chamber.station() == 4 )
451  {
452  int m_index_2[] = {0,2};
453  for(int c_i = 0; c_i < 2; ++c_i)
454  {
455  weightResMB4[c_i][0] = weightRes[m_index_2[c_i]][0];
456  for(int c_j = 0; c_j < 2; ++c_j)
457  {
458  invCovMB4[c_i][c_j] = invCov[m_index_2[c_i]][m_index_2[c_j]];
459  }
460  }
461  this->updateInfo(invCovMB4, weightResMB4, residuals, chamId);
462  }
463  else
464  {
465  this->updateInfo(invCov, weightRes, residuals, chamId);
466  }*/
467  this->updateInfo(invCov, weightRes, residuals, chamId);
468  }
469  }
470  itsos++;
471  ihit++;
472  }
473  }
474  } // end of track loop
475 
476  }
477 
478 
479  //Auxiliar
481  {
482  //for(int i = 0; i < m.num_row(); ++i)
483  // {
484  // for(int j = 0; j < m.num_col(); ++j)
485  // {
486  // std::cout << m[i][j] << " ";
487  // }
488  // std::cout << std::endl;
489  //}
490  }
491 
493  AlgebraicMatrix m_weightRes,
494  AlgebraicMatrix m_res,
495  std::string id)
496  {
497 
498 
499 
500  std::string id_invCov = id + "_invCov";
501  std::string id_weightRes = id + "_weightRes";
502  std::string id_n = id + "_N";
503 
504  edm::LogInfo("Alignment") << "Entrando";
505 
506  std::map<std::string, AlgebraicMatrix *>::iterator node = map_invCov.find(id_invCov);
507  if(node == map_invCov.end())
508  {
509  AlgebraicMatrix *f_invCov = new AlgebraicMatrix(m_invCov.num_row(), m_invCov.num_col());
510  AlgebraicMatrix *f_weightRes = new AlgebraicMatrix(m_weightRes.num_row(), m_weightRes.num_col());
511  AlgebraicMatrix *f_n = new AlgebraicMatrix(1,1);
512 
513  map_invCov.insert(make_pair(id_invCov, f_invCov));
514  map_weightRes.insert(make_pair(id_weightRes, f_weightRes));
515  map_N.insert(make_pair(id_n, f_n));
516 
517  for(int iCount = 0; iCount < 4; ++iCount)
518  {
519  char name[40];
520  snprintf(name, sizeof(name), "%s_var_%d", id.c_str(), iCount);
521  std::string idName(name);
522  float range = 5.0;
523  //if( iCount == 0 || iCount == 1 ) {
524  // range = 0.01;
525  //}
526  TH1D *histo = fs->make<TH1D>(idName.c_str(), idName.c_str(), 200, -range, range );
527  histoMap.insert(make_pair(idName, histo));
528  }
529  }
530 
531  *map_invCov[id_invCov] = *map_invCov[id_invCov] + m_invCov;
532  *map_weightRes[id_weightRes] = *map_weightRes[id_weightRes] + m_weightRes;
533  (*map_N[id_n])[0][0]++;
534 
535  for(int iCount = 0; iCount < 4; ++iCount)
536  {
537  char name[40];
538  snprintf(name, sizeof(name), "%s_var_%d", id.c_str(), iCount);
539  std::string idName(name);
540  histoMap[idName]->Fill(m_res[iCount][0]);
541  }
542  }
543 
544 
545 
547 
T getParameter(std::string const &) const
std::map< std::string, AlgebraicMatrix * > map_weightRes
AlignableNavigator * theAlignableDetAccessor
void run(const edm::EventSetup &setup, const EventInfo &eventInfo)
Run the algorithm.
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:111
TrajectoryStateOnSurface forwardPredictedState() const
Access to forward predicted state (from fitter or builder)
selection
main part
Definition: corrVsCorr.py:98
Alignable * alignableFromAlignableDet(AlignableDetOrUnitPtr adet) const
Get relevant Alignable from AlignableDet.
double phi() const
azimuthal angle of momentum vector
Definition: TrackBase.h:139
ConstRecHitPointer recHit() const
void applyParameters(void)
Obsolete: Use AlignableNavigator::alignableDetFromDetId and alignableFromAlignableDet.
ROOT::Math::SMatrix< double, 5, 5, ROOT::Math::MatRepSym< double, 5 > > AlgebraicSymMatrix55
T eta() const
AlignmentParameters * alignmentParameters() const
Get the AlignmentParameters.
Definition: Alignable.h:57
edm::Service< TFileService > fs
tuple node
Definition: Node.py:50
const ConstTrajTrackPairCollection & trajTrackPairs() const
void toTMat(AlgebraicMatrix *, TMatrixD *)
define event information passed to algorithms
DataContainer const & measurements() const
Definition: Trajectory.h:203
double eta() const
pseudorapidity of momentum vector
Definition: TrackBase.h:141
CLHEP::HepMatrix AlgebraicMatrix
void setValid(bool v)
Set validity flag.
double pt() const
track transverse momentum
Definition: TrackBase.h:131
MuonMillepedeAlgorithm(const edm::ParameterSet &cfg)
Constructor.
DetId geographicalId() const
The label of this GeomDet.
Definition: GeomDet.h:72
unsigned short numberOfValidHits() const
number of valid hits found
Definition: TrackBase.h:232
void terminate(void)
Call at end of job.
CLHEP::HepVector AlgebraicVector
ROOT::Math::SVector< double, 5 > AlgebraicVector5
void updateInfo(AlgebraicMatrix, AlgebraicMatrix, AlgebraicMatrix, std::string)
tuple tracks
Definition: testEve_cfg.py:39
AlignmentParameterStore * theAlignmentParameterStore
CompositeAlignmentParameters selectParameters(const std::vector< AlignableDet * > &alignabledets) const
bool isValid() const
void initialize(const edm::EventSetup &setup, AlignableTracker *tracker, AlignableMuon *muon, AlignableExtras *extras, AlignmentParameterStore *store)
Call at beginning of job.
std::map< std::string, AlgebraicMatrix * > map_N
std::vector< AlignableDetOrUnitPtr > alignablesFromHits(const std::vector< const TransientTrackingRecHit * > &hitvec)
Returns vector AlignableDetOrUnitPtr for given vector of Hits.
T * make() const
make new ROOT object
std::map< std::string, TH1D * > histoMap
#define DEFINE_EDM_PLUGIN(factory, type, name)
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...
std::vector< Alignable * > theAlignables
Constructor of the full muon geometry.
Definition: AlignableMuon.h:36
void printM(AlgebraicMatrix)
void setup(std::vector< TH2F > &depth, std::string name, std::string units="")
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
Definition: DDAxes.h:10