CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
HIPAlignmentAlgorithm.cc
Go to the documentation of this file.
1 #include <fstream>
2 
3 #include "TFile.h"
4 #include "TTree.h"
5 
8 
11 
26 
28 
29 // using namespace std;
30 
31 // Constructor ----------------------------------------------------------------
32 
35 {
36 
37  // parse parameters
38 
39  verbose = cfg.getParameter<bool>("verbosity");
40 
41  outpath = cfg.getParameter<string>("outpath");
42  outfile = cfg.getParameter<string>("outfile");
43  outfile2 = cfg.getParameter<string>("outfile2");
44  struefile = cfg.getParameter<string>("trueFile");
45  smisalignedfile = cfg.getParameter<string>("misalignedFile");
46  salignedfile = cfg.getParameter<string>("alignedFile");
47  siterationfile = cfg.getParameter<string>("iterationFile");
48  suvarfile = cfg.getParameter<string>("uvarFile");
49  sparameterfile = cfg.getParameter<string>("parameterFile");
50  ssurveyfile = cfg.getParameter<string>("surveyFile");
51 
52  outfile =outpath+outfile;//Eventwise tree
53  outfile2 =outpath+outfile2;//Alignablewise tree
54  struefile =outpath+struefile;
55  smisalignedfile=outpath+smisalignedfile;
56  salignedfile =outpath+salignedfile;
57  siterationfile =outpath+siterationfile;
58  suvarfile =outpath+suvarfile;
59  sparameterfile =outpath+sparameterfile;
60  ssurveyfile =outpath+ssurveyfile;
61 
62  // parameters for APE
63  theApplyAPE = cfg.getParameter<bool>("applyAPE");
64  theAPEParameterSet = cfg.getParameter<std::vector<edm::ParameterSet> >("apeParam");
65 
66  theMaxAllowedHitPull = cfg.getParameter<double>("maxAllowedHitPull");
67  theMinimumNumberOfHits = cfg.getParameter<int>("minimumNumberOfHits");
68  theMaxRelParameterError = cfg.getParameter<double>("maxRelParameterError");
69 
70  // for collector mode (parallel processing)
71  isCollector=cfg.getParameter<bool>("collectorActive");
72  theCollectorNJobs=cfg.getParameter<int>("collectorNJobs");
73  theCollectorPath=cfg.getParameter<string>("collectorPath");
74  theFillTrackMonitoring=cfg.getUntrackedParameter<bool>("fillTrackMonitoring");
75 
76  if (isCollector) edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm] Collector mode";
77 
78  theEventPrescale = cfg.getParameter<int>("eventPrescale");
80 
81  AlignableObjectId dummy;
82 
83  const std::vector<std::string>& levels = cfg.getUntrackedParameter<std::vector<std::string> >("surveyResiduals");
84 
85  for (unsigned int l = 0; l < levels.size(); ++l) {
86  theLevels.push_back( dummy.nameToType(levels[l]) );
87  }
88 
89  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm] constructed.";
90 
91 }
92 
93 // Call at beginning of job ---------------------------------------------------
94 
95 void
99 {
100  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm] Initializing...";
101 
102  // accessor Det->AlignableDet
103  if ( !muon )
105  else if ( !tracker )
107  else
108  theAlignableDetAccessor = new AlignableNavigator(tracker, muon);
109 
110  // set alignmentParameterStore
112 
113  // get alignables
115 
116  // clear theAPEParameters, if necessary
117  theAPEParameters.clear();
118 
119  // get APE parameters
120  if(theApplyAPE){
121  AlignmentParameterSelector selector(tracker, muon);
122  for (std::vector<edm::ParameterSet>::const_iterator setiter = theAPEParameterSet.begin();
123  setiter != theAPEParameterSet.end();
124  ++setiter) {
125  std::vector<Alignable*> alignables;
126 
127  selector.clear();
128  edm::ParameterSet selectorPSet = setiter->getParameter<edm::ParameterSet>("Selector");
129  std::vector<std::string> alignParams = selectorPSet.getParameter<std::vector<std::string> >("alignParams");
130  if (alignParams.size() == 1 && alignParams[0] == std::string("selected")) {
131  alignables = theAlignables;
132  }
133  else {
134  selector.addSelections(selectorPSet);
135  alignables = selector.selectedAlignables();
136  }
137 
138  std::vector<double> apeSPar = setiter->getParameter<std::vector<double> >("apeSPar");
139  std::vector<double> apeRPar = setiter->getParameter<std::vector<double> >("apeRPar");
140  std::string function = setiter->getParameter<std::string>("function");
141 
142  if (apeSPar.size() != 3 || apeRPar.size() != 3)
143  throw cms::Exception("BadConfig") << "apeSPar and apeRPar must have 3 values each" << std::endl;
144 
145  for (std::vector<double>::const_iterator i = apeRPar.begin(); i != apeRPar.end(); ++i) {
146  apeSPar.push_back(*i);
147  }
148 
149  if (function == std::string("linear")) {
150  apeSPar.push_back(0.); // c.f. note in calcAPE
151  }
152  else if (function == std::string("exponential")) {
153  apeSPar.push_back(1.); // c.f. note in calcAPE
154  }
155  else if (function == std::string("step")) {
156  apeSPar.push_back(2.); // c.f. note in calcAPE
157  }
158  else {
159  throw cms::Exception("BadConfig") << "APE function must be \"linear\" or \"exponential\"." << std::endl;
160  }
161 
162  theAPEParameters.push_back(std::pair<std::vector<Alignable*>, std::vector<double> >(alignables, apeSPar));
163  }
164  }
165 }
166 
167 // Call at new loop -------------------------------------------------------------
169 {
170 
171  // iterate over all alignables and attach user variables
172  for( vector<Alignable*>::const_iterator it=theAlignables.begin();
173  it!=theAlignables.end(); it++ )
174  {
175  AlignmentParameters* ap = (*it)->alignmentParameters();
176  int npar=ap->numSelected();
177  HIPUserVariables* userpar = new HIPUserVariables(npar);
178  ap->setUserVariables(userpar);
179  }
180 
181  // try to read in alignment parameters from a previous iteration
182  AlignablePositions theAlignablePositionsFromFile =
184  (char*)salignedfile.c_str(),-1,ioerr);
185 
186  int numAlignablesFromFile = theAlignablePositionsFromFile.size();
187 
188  if (numAlignablesFromFile==0) { // file not there: first iteration
189 
190  // set iteration number to 1
191  if (isCollector) theIteration=0;
192  else theIteration=1;
193  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm] File not found => iteration "<<theIteration;
194 
195  // get true (de-misaligned positions) and write to root file
196  // hardcoded iteration=1
198  (char*)struefile.c_str(),1,false,ioerr);
199 
200  // get misaligned positions and write to root file
201  // hardcoded iteration=1
203  (char*)smisalignedfile.c_str(),1,false,ioerr);
204 
205  }
206 
207  else { // there have been previous iterations
208 
209  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm] Alignables Read "
210  << numAlignablesFromFile;
211 
212  // get iteration number from file
214 
215  // increase iteration
216  theIteration++;
217  edm::LogWarning("Alignment") <<"[HIPAlignmentAlgorithm] Iteration increased by one!";
218 
219  // now apply psotions of file from prev iteration
220  edm::LogWarning("Alignment") <<"[HIPAlignmentAlgorithm] Apply positions from file ...";
222  theAlignablePositionsFromFile,ioerr);
223 
224  }
225 
226  edm::LogWarning("Alignment") <<"[HIPAlignmentAlgorithm] Current Iteration number: "
227  << theIteration;
228 
229 
230  // book root trees
231  bookRoot();
232 
233 
234  /*---------------------moved to terminate------------------------------
235  if (theLevels.size() > 0)
236  {
237  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm] Using survey constraint";
238 
239  unsigned int nAlignable = theAlignables.size();
240 
241  for (unsigned int i = 0; i < nAlignable; ++i)
242  {
243  const Alignable* ali = theAlignables[i];
244 
245  AlignmentParameters* ap = ali->alignmentParameters();
246 
247  HIPUserVariables* uservar =
248  dynamic_cast<HIPUserVariables*>(ap->userVariables());
249 
250  for (unsigned int l = 0; l < theLevels.size(); ++l)
251  {
252  SurveyResidual res(*ali, theLevels[l], true);
253 
254  if ( res.valid() )
255  {
256  AlgebraicSymMatrix invCov = res.inverseCovariance();
257 
258  // variable for tree
259  AlgebraicVector sensResid = res.sensorResidual();
260  m3_Id = ali->id();
261  m3_ObjId = theLevels[l];
262  m3_par[0] = sensResid[0]; m3_par[1] = sensResid[1]; m3_par[2] = sensResid[2];
263  m3_par[3] = sensResid[3]; m3_par[4] = sensResid[4]; m3_par[5] = sensResid[5];
264 
265  uservar->jtvj += invCov;
266  uservar->jtve += invCov * sensResid;
267 
268  theTree3->Fill();
269  }
270  }
271 
272  // align::LocalVectors residuals = res1.pointsResidual();
273 
274  // unsigned int nPoints = residuals.size();
275 
276  // for (unsigned int k = 0; k < nPoints; ++k)
277  // {
278  // AlgebraicMatrix J = term->survey()->derivatives(k);
279  // AlgebraicVector e(3); // local residual
280 
281  // const align::LocalVector& lr = residuals[k];
282 
283  // e(1) = lr.x(); e(2) = lr.y(); e(3) = lr.z();
284 
285  // uservar->jtvj += invCov1.similarity(J);
286  // uservar->jtve += J * (invCov1 * e);
287  // }
288 
289  }
290  }
291  //------------------------------------------------------*/
292 
293  // set alignment position error
295 
296  // run collector job if we are in parallel mode
297  if (isCollector) collector();
298 
299 }
300 
301 // Call at end of job ---------------------------------------------------------
302 
304 {
305 
306  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm] Terminating";
307 
308  // calculating survey residuals
309  if (theLevels.size() > 0)
310  {
311  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm] Using survey constraint";
312 
313  unsigned int nAlignable = theAlignables.size();
314 
315  for (unsigned int i = 0; i < nAlignable; ++i)
316  {
317  const Alignable* ali = theAlignables[i];
318 
320 
321  HIPUserVariables* uservar =
322  dynamic_cast<HIPUserVariables*>(ap->userVariables());
323 
324  for (unsigned int l = 0; l < theLevels.size(); ++l)
325  {
326  SurveyResidual res(*ali, theLevels[l], true);
327 
328  if ( res.valid() )
329  {
330  AlgebraicSymMatrix invCov = res.inverseCovariance();
331 
332  // variable for tree
333  AlgebraicVector sensResid = res.sensorResidual();
334  m3_Id = ali->id();
335  m3_ObjId = theLevels[l];
336  m3_par[0] = sensResid[0]; m3_par[1] = sensResid[1]; m3_par[2] = sensResid[2];
337  m3_par[3] = sensResid[3]; m3_par[4] = sensResid[4]; m3_par[5] = sensResid[5];
338 
339  uservar->jtvj += invCov;
340  uservar->jtve += invCov * sensResid;
341 
342  theTree3->Fill();
343  }
344  }
345 
346  // align::LocalVectors residuals = res1.pointsResidual();
347 
348  // unsigned int nPoints = residuals.size();
349 
350  // for (unsigned int k = 0; k < nPoints; ++k)
351  // {
352  // AlgebraicMatrix J = term->survey()->derivatives(k);
353  // AlgebraicVector e(3); // local residual
354 
355  // const align::LocalVector& lr = residuals[k];
356 
357  // e(1) = lr.x(); e(2) = lr.y(); e(3) = lr.z();
358 
359  // uservar->jtvj += invCov1.similarity(J);
360  // uservar->jtve += J * (invCov1 * e);
361  // }
362 
363  }
364  }
365 
366  // write user variables
368  HIPIO.writeHIPUserVariables (theAlignables,(char*)suvarfile.c_str(),
369  theIteration,false,ioerr);
370 
371  // now calculate alignment corrections ...
372  int ialigned=0;
373  // iterate over alignment parameters
374  for(vector<Alignable*>::const_iterator
375  it=theAlignables.begin(); it!=theAlignables.end(); it++) {
376  Alignable* ali=(*it);
377  // Alignment parameters
379 
380  // try to calculate parameters
381  bool test = calcParameters(ali);
382 
383  // if successful, apply parameters
384  if (test) {
385  edm::LogInfo("Alignment") << "now apply params";
387  // set these parameters 'valid'
388  ali->alignmentParameters()->setValid(true);
389  // increase counter
390  ialigned++;
391  }
392  else par->setValid(false);
393  }
394  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::terminate] Aligned units: " << ialigned;
395 
396  // fill alignable wise root tree
397  fillRoot();
398 
399  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm] Writing aligned parameters to file: " << theAlignables.size();
400 
401  // write new absolute positions to disk
403  (char*)salignedfile.c_str(),theIteration,false,ioerr);
404 
405  // write alignment parameters to disk
407  (char*)sparameterfile.c_str(),theIteration,false,ioerr);
408 
409  // write iteration number to file
411 
412  // write out trees and close root file
413 
414  // eventwise tree
415  theFile->cd();
416  theTree->Write();
417  delete theFile;
418 
419  if (theLevels.size() > 0){
420  theFile3->cd();
421  theTree3->Write();
422  delete theFile3;
423  }
424 
425  // alignable-wise tree is only filled once
426  if (theIteration==1) { // only for 1st iteration
427  theFile2->cd();
428  theTree2->Write();
429  delete theFile2;
430  }
431 
432 }
433 
435  const Alignable* ali,
436  const TrajectoryStateOnSurface & tsos,
438 {
439  static const unsigned int hitDim = 1;
440 
441  // get trajectory impact point
442  LocalPoint alvec = tsos.localPosition();
443  AlgebraicVector pos(hitDim);
444  pos[0] = alvec.x();
445 
446  // get impact point covariance
447  AlgebraicSymMatrix ipcovmat(hitDim);
448  ipcovmat[0][0] = tsos.localError().positionError().xx();
449 
450  // get hit local position and covariance
451  AlgebraicVector coor(hitDim);
452  coor[0] = hit->localPosition().x();
453 
454  AlgebraicSymMatrix covmat(hitDim);
455  covmat[0][0] = hit->localPositionError().xx();
456 
457  // add hit and impact point covariance matrices
458  covmat = covmat + ipcovmat;
459 
460  // calculate the x pull of this hit
461  double xpull = 0.;
462  if (covmat[0][0] != 0.) xpull = (pos[0] - coor[0])/sqrt(fabs(covmat[0][0]));
463 
464  // get Alignment Parameters
465  AlignmentParameters* params = ali->alignmentParameters();
466  // get derivatives
467  AlgebraicMatrix derivs2D = params->selectedDerivatives(tsos, alidet);
468  // calculate user parameters
469  int npar = derivs2D.num_row();
470  // std::cout << "Dumping derivsSEL: \n" << derivs2D <<std::endl;
471  AlgebraicMatrix derivs(npar, hitDim, 0);
472 
473  for (int ipar=0;ipar<npar;ipar++) {
474  for (unsigned int idim=0;idim<hitDim;idim++) {
475  derivs[ipar][idim] = derivs2D[ipar][idim];
476  }
477  }
478  // std::cout << "Dumping derivs: \n" << derivs << std::endl;
479  // invert covariance matrix
480  int ierr;
481  // if (covmat[1][1]>4.0) nhitDim = hitDim;
482 
483  covmat.invert(ierr);
484  if (ierr != 0) {
485  edm::LogError("Alignment") << "Matrix inversion failed!";
486  return false;
487  }
488 
489  bool useThisHit = (theMaxAllowedHitPull <= 0.);
490 
491  useThisHit |= (fabs(xpull) < theMaxAllowedHitPull);
492 
493  // bailing out
494  if (!useThisHit) return false;
495 
496  // std::cout << "We use this hit in " << subDet << std::endl;
497  // std::cout << "Npars= " << npar << " NhitDim=1 Size of derivs: "
498  // << derivs.num_row() << " x " << derivs.num_col() << std::endl;
499 
500  // AlgebraicMatrix jtvjtmp();
501  AlgebraicMatrix covtmp(covmat);
502  // std::cout << "Preapring JTVJTMP -> " << std::flush;
503  AlgebraicMatrix jtvjtmp(derivs * covtmp *derivs.T());
504  // std::cout << "TMP JTVJ= \n" << jtvjtmp << std::endl;
505  AlgebraicSymMatrix thisjtvj(npar);
506  AlgebraicVector thisjtve(npar);
507  // std::cout << "Preparing ThisJtVJ" << std::flush;
508  // thisjtvj = covmat.similarity(derivs);
509  thisjtvj.assign(jtvjtmp);
510  // cout<<" ThisJtVE"<<std::endl;
511  thisjtve=derivs * covmat * (pos-coor);
512 
513  AlgebraicVector hitresidual(hitDim);
514  hitresidual[0] = (pos[0] - coor[0]);
515 
516  AlgebraicMatrix hitresidualT;
517  hitresidualT = hitresidual.T();
518  // std::cout << "HitResidualT = \n" << hitresidualT << std::endl;
519 
520  // access user variables (via AlignmentParameters)
521  HIPUserVariables* uservar = dynamic_cast<HIPUserVariables*>(params->userVariables());
522  uservar->jtvj += thisjtvj;
523  uservar->jtve += thisjtve;
524  uservar->nhit++;
525  // The following variable is needed for the extended 1D/2D hit fix using
526  // matrix shrinkage and expansion
527  // uservar->hitdim = hitDim;
528 
529  //for alignable chi squared
530  float thischi2;
531  thischi2 = (hitresidualT *covmat *hitresidual)[0];
532 
533  if ( verbose && ((thischi2/ static_cast<float>(uservar->nhit)) >10.0) ) {
534  edm::LogWarning("Alignment") << "Added to Chi2 the number " << thischi2 <<" having "
535  << uservar->nhit << " dof " << std::endl << "X-resid "
536  << hitresidual[0] << " Y-resid "
537  << hitresidual[1] << std::endl << " Cov^-1 matr (covmat): [0][0]= "
538  << covmat[0][0] << " [0][1]= "
539  << covmat[0][1] << " [1][0]= "
540  << covmat[1][0] << " [1][1]= "
541  << covmat[1][1] << std::endl;
542  }
543 
544  uservar->alichi2 += thischi2; // a bit weird, but vector.transposed * matrix * vector doesn't give a double in CMSSW's opinion
545  uservar->alindof += hitDim; // 2D hits contribute twice to the ndofs
546 
547  return true;
548 }
549 
551  const Alignable* ali,
552  const TrajectoryStateOnSurface & tsos,
554 {
555  static const unsigned int hitDim = 2;
556 
557  // get trajectory impact point
558  LocalPoint alvec = tsos.localPosition();
559  AlgebraicVector pos(hitDim);
560  pos[0] = alvec.x();
561  pos[1] = alvec.y();
562 
563  // get impact point covariance
564  AlgebraicSymMatrix ipcovmat(hitDim);
565  ipcovmat[0][0] = tsos.localError().positionError().xx();
566  ipcovmat[1][1] = tsos.localError().positionError().yy();
567  ipcovmat[0][1] = tsos.localError().positionError().xy();
568 
569  // get hit local position and covariance
570  AlgebraicVector coor(hitDim);
571  coor[0] = hit->localPosition().x();
572  coor[1] = hit->localPosition().y();
573 
574  AlgebraicSymMatrix covmat(hitDim);
575  covmat[0][0] = hit->localPositionError().xx();
576  covmat[1][1] = hit->localPositionError().yy();
577  covmat[0][1] = hit->localPositionError().xy();
578 
579  // add hit and impact point covariance matrices
580  covmat = covmat + ipcovmat;
581 
582  // calculate the x pull and y pull of this hit
583  double xpull = 0.;
584  double ypull = 0.;
585  if (covmat[0][0] != 0.) xpull = (pos[0] - coor[0])/sqrt(fabs(covmat[0][0]));
586  if (covmat[1][1] != 0.) ypull = (pos[1] - coor[1])/sqrt(fabs(covmat[1][1]));
587 
588  // get Alignment Parameters
589  AlignmentParameters* params = ali->alignmentParameters();
590  // get derivatives
591  AlgebraicMatrix derivs2D = params->selectedDerivatives(tsos, alidet);
592  // calculate user parameters
593  int npar = derivs2D.num_row();
594  // std::cout << "Dumping derivsSEL: \n"<< derivs2D <<std::endl;
595  AlgebraicMatrix derivs(npar, hitDim, 0);
596 
597  for (int ipar=0;ipar<npar;ipar++) {
598  for (unsigned int idim=0;idim<hitDim;idim++) {
599  derivs[ipar][idim] = derivs2D[ipar][idim];
600  }
601  }
602  // std::cout << "Dumping derivs: \n" << derivs << std::endl;
603  // invert covariance matrix
604  int ierr;
605  // if (covmat[1][1]>4.0) nhitDim = hitDim;
606 
607  covmat.invert(ierr);
608  if (ierr != 0) {
609  edm::LogError("Alignment") << "Matrix inversion failed!";
610  return false;
611  }
612 
613  bool useThisHit = (theMaxAllowedHitPull <= 0.);
614 
615  useThisHit |= (fabs(xpull) < theMaxAllowedHitPull && fabs(ypull) < theMaxAllowedHitPull);
616 
617  // bailing out
618  if (!useThisHit) return false;
619 
620  // std::cout << "We use this hit in " << subDet << std::endl;
621  // std::cout << "Npars= " << npar << " NhitDim=2 Size of derivs: "
622  // << derivs.num_row() << " x " << derivs.num_col() << std::endl;
623 
624  // AlgebraicMatrix jtvjtmp();
625  AlgebraicMatrix covtmp(covmat);
626  // std::cout << "Preapring JTVJTMP -> " << std::flush;
627  AlgebraicMatrix jtvjtmp(derivs * covtmp *derivs.T());
628  // std::cout << "TMP JTVJ= \n" << jtvjtmp << std::endl;
629  AlgebraicSymMatrix thisjtvj(npar);
630  AlgebraicVector thisjtve(npar);
631  // std::cout << "Preparing ThisJtVJ" << std::flush;
632  // thisjtvj = covmat.similarity(derivs);
633  thisjtvj.assign(jtvjtmp);
634  // cout<<" ThisJtVE"<<std::endl;
635  thisjtve=derivs * covmat * (pos-coor);
636 
637  AlgebraicVector hitresidual(hitDim);
638  hitresidual[0] = (pos[0] - coor[0]);
639  hitresidual[1] = (pos[1] - coor[1]);
640  // if(nhitDim>1) {
641  // hitresidual[1] =0.0;
642  // nhitDim=1;
643  // }
644 
645  AlgebraicMatrix hitresidualT;
646  hitresidualT = hitresidual.T();
647  // std::cout << "HitResidualT = \n" << hitresidualT << std::endl;
648  // access user variables (via AlignmentParameters)
649  HIPUserVariables* uservar = dynamic_cast<HIPUserVariables*>(params->userVariables());
650  uservar->jtvj += thisjtvj;
651  uservar->jtve += thisjtve;
652  uservar->nhit++;
653  // The following variable is needed for the extended 1D/2D hit fix using
654  // matrix shrinkage and expansion
655  // uservar->hitdim = hitDim;
656 
657  //for alignable chi squared
658  float thischi2;
659  thischi2 = (hitresidualT *covmat *hitresidual)[0];
660 
661  if ( verbose && ((thischi2/ static_cast<float>(uservar->nhit)) >10.0) ) {
662  edm::LogWarning("Alignment") << "Added to Chi2 the number " << thischi2 <<" having "
663  << uservar->nhit << " dof " << std::endl << "X-resid "
664  << hitresidual[0] << " Y-resid "
665  << hitresidual[1] << std::endl << " Cov^-1 matr (covmat): [0][0]= "
666  << covmat[0][0] << " [0][1]= "
667  << covmat[0][1] << " [1][0]= "
668  << covmat[1][0] << " [1][1]= "
669  << covmat[1][1] << std::endl;
670  }
671 
672  uservar->alichi2 += thischi2; // a bit weird, but vector.transposed * matrix * vector doesn't give a double in CMSSW's opinion
673  uservar->alindof += hitDim; // 2D hits contribute twice to the ndofs
674 
675  return true;
676 }
677 
678 // Run the algorithm on trajectories and tracks -------------------------------
680 {
681  if (isCollector) return;
682 
683  TrajectoryStateCombiner tsoscomb;
684 
685  // AM: not really needed
686  // AM: m_Ntracks = 0 should be sufficient
687  int itr=0;
688  m_Ntracks=0;
689  for(itr=0;itr<MAXREC;++itr){
690  m_Nhits[itr]=0;
691  m_Pt[itr]=-5.0;
692  m_P[itr]=-5.0;
693  m_nhPXB[itr]=0;
694  m_nhPXF[itr]=0;
695  m_Eta[itr]=-99.0;
696  m_Phi[itr]=-4.0;
697  m_Chi2n[itr]=-11.0;
698  m_d0[itr]=-999;
699  m_dz[itr]=-999;
700  }
701  itr=0;
702 
703  // AM: what is this needed for?
704  theFile->cd();
705 
706  // loop over tracks
708  for (ConstTrajTrackPairCollection::const_iterator it=tracks.begin();
709  it!=tracks.end();
710  ++it) {
711 
712  const Trajectory* traj = (*it).first;
713  const reco::Track* track = (*it).second;
714 
715  float pt = track->pt();
716  float eta = track->eta();
717  float phi = track->phi();
718  float p = track->p();
719  float chi2n = track->normalizedChi2();
720  int nhit = track->numberOfValidHits();
721  float d0 = track->d0();
722  float dz = track->dz();
723 
724  int nhpxb = track->hitPattern().numberOfValidPixelBarrelHits();
725  int nhpxf = track->hitPattern().numberOfValidPixelEndcapHits();
726 
727  if (verbose) edm::LogInfo("Alignment") << "New track pt,eta,phi,chi2n,hits: "
728  << pt << ","
729  << eta << ","
730  << phi << ","
731  << chi2n << ","
732  << nhit;
733  // edm::LogWarning("Alignment") << "New track pt,eta,phi,chi2n,hits: "
734  // << pt << ","
735  // << eta << ","
736  // << phi << ","
737  // << chi2n << ","
738  // << nhit;
739 
740  // fill track parameters in root tree
741  if (itr<MAXREC) {
742  m_Nhits[itr]=nhit;
743  m_Pt[itr]=pt;
744  m_P[itr]=p;
745  m_Eta[itr]=eta;
746  m_Phi[itr]=phi;
747  m_Chi2n[itr]=chi2n;
748  m_nhPXB[itr]=nhpxb;
749  m_nhPXF[itr]=nhpxf;
750  m_d0[itr]=d0;
751  m_dz[itr]=dz;
752  itr++;
753  m_Ntracks=itr;
754  }
755  // AM: Can be simplified
756 
757  vector<const TransientTrackingRecHit*> hitvec;
758  vector<TrajectoryStateOnSurface> tsosvec;
759 
760  // loop over measurements
761  vector<TrajectoryMeasurement> measurements = traj->measurements();
762  for (vector<TrajectoryMeasurement>::iterator im=measurements.begin();
763  im!=measurements.end();
764  ++im) {
765 
766  TrajectoryMeasurement meas = *im;
767 
768  // const TransientTrackingRecHit* ttrhit = &(*meas.recHit());
769  // const TrackingRecHit *hit = ttrhit->hit();
770  const TransientTrackingRecHit* hit = &(*meas.recHit());
771 
773 
774  // this is the updated state (including the current hit)
775  // TrajectoryStateOnSurface tsos=meas.updatedState();
776  // combine fwd and bwd predicted state to get state
777  // which excludes current hit
778 
780  bool skiphit = false;
781  if (eventInfo.clusterValueMap()) {
782  // check from the PrescalingMap if the hit was taken.
783  // If not skip to the next TM
784  // bool hitTaken=false;
785  AlignmentClusterFlag myflag;
786 
787  int subDet = hit->geographicalId().subdetId();
788  //take the actual RecHit out of the Transient one
789  const TrackingRecHit *rechit=hit->hit();
790  if (subDet>2) { // AM: if possible use enum instead of hard-coded value
791  const std::type_info &type = typeid(*rechit);
792 
793  if (type == typeid(SiStripRecHit1D)) {
794 
795  const SiStripRecHit1D* stripHit1D = dynamic_cast<const SiStripRecHit1D*>(rechit);
796  if (stripHit1D) {
797  SiStripRecHit1D::ClusterRef stripclust(stripHit1D->cluster());
798  // myflag=PrescMap[stripclust];
799  myflag = (*eventInfo.clusterValueMap())[stripclust];
800  } else {
801  edm::LogError("HIPAlignmentAlgorithm")
802  << "ERROR in <HIPAlignmentAlgorithm::run>: Dynamic cast of Strip RecHit failed! "
803  << "TypeId of the RecHit: " << className(*hit) <<endl;
804  }
805 
806  }//end if type = SiStripRecHit1D
807  else if(type == typeid(SiStripRecHit2D)){
808 
809  const SiStripRecHit2D* stripHit2D = dynamic_cast<const SiStripRecHit2D*>(rechit);
810  if (stripHit2D) {
811  SiStripRecHit2D::ClusterRef stripclust(stripHit2D->cluster());
812  // myflag=PrescMap[stripclust];
813  myflag = (*eventInfo.clusterValueMap())[stripclust];
814  } else {
815  edm::LogError("HIPAlignmentAlgorithm")
816  << "ERROR in <HIPAlignmentAlgorithm::run>: Dynamic cast of Strip RecHit failed! "
817  // << "TypeId of the TTRH: " << className(*ttrhit) << endl;
818  << "TypeId of the TTRH: " << className(*hit) << endl;
819  }
820  } //end if type == SiStripRecHit2D
821  } //end if hit from strips
822  else {
823  const SiPixelRecHit* pixelhit= dynamic_cast<const SiPixelRecHit*>(rechit);
824  if (pixelhit) {
825  SiPixelClusterRefNew pixelclust(pixelhit->cluster());
826  // myflag=PrescMap[pixelclust];
827  myflag = (*eventInfo.clusterValueMap())[pixelclust];
828  }
829  else {
830  edm::LogError("HIPAlignmentAlgorithm")
831  << "ERROR in <HIPAlignmentAlgorithm::run>: Dynamic cast of Pixel RecHit failed! "
832  // << "TypeId of the TTRH: " << className(*ttrhit) << endl;
833  << "TypeId of the TTRH: " << className(*hit) << endl;
834  }
835  } //end 'else' it is a pixel hit
836  // bool hitTaken=myflag.isTaken();
837  if (!myflag.isTaken()) {
838  skiphit=true;
839  //cout<<"Hit from subdet "<<rechit->geographicalId().subdetId()<<" prescaled out."<<endl;
840  continue;
841  }
842  }//end if Prescaled Hits
844  if (skiphit) {
845  throw cms::Exception("LogicError")
846  << "ERROR in <HIPAlignmentAlgorithm::run>: this hit should have been skipped!"
847  << endl;
848  }
849 
851  meas.backwardPredictedState());
852 
853  if(tsos.isValid()){
854  // hitvec.push_back(ttrhit);
855  hitvec.push_back(hit);
856  tsosvec.push_back(tsos);
857  }
858 
859  } //hit valid
860  }
861 
862  // transform RecHit vector to AlignableDet vector
863  vector <AlignableDetOrUnitPtr> alidetvec = theAlignableDetAccessor->alignablesFromHits(hitvec);
864 
865  // get concatenated alignment parameters for list of alignables
867 
868  vector<TrajectoryStateOnSurface>::const_iterator itsos=tsosvec.begin();
869  vector<const TransientTrackingRecHit*>::const_iterator ihit=hitvec.begin();
870 
871  // loop over vectors(hit,tsos)
872  while (itsos != tsosvec.end()) {
873 
874  // get AlignableDet for this hit
875  const GeomDet* det = (*ihit)->det();
876  // int subDet= (*ihit)->geographicalId().subdetId();
877  uint32_t nhitDim = (*ihit)->dimension();
878 
880 
881  // get relevant Alignable
882  Alignable* ali = aap.alignableFromAlignableDet(alidet);
883 
884  if (ali!=0) {
885  if (nhitDim==1) {
886  processHit1D(alidet, ali, *itsos, *ihit);
887  } else if (nhitDim==2) {
888  processHit2D(alidet, ali, *itsos, *ihit);
889  }
890  }
891 
892  itsos++;
893  ihit++;
894  }
895  } // end of track loop
896 
897  // fill eventwise root tree (with prescale defined in pset)
900  if (theCurrentPrescale<=0) {
901  theTree->Fill();
903  }
904  }
905 }
906 
907 // ----------------------------------------------------------------------------
908 
910 {
911  int result;
912 
913  ifstream inIterFile((char*)filename.c_str(), ios::in);
914  if (!inIterFile) {
915  edm::LogError("Alignment") << "[HIPAlignmentAlgorithm::readIterationFile] ERROR! "
916  << "Unable to open Iteration file";
917  result = -1;
918  }
919  else {
920  inIterFile >> result;
921  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::readIterationFile] "
922  << "Read last iteration number from file: " << result;
923  }
924  inIterFile.close();
925 
926  return result;
927 }
928 
929 // ----------------------------------------------------------------------------
930 
932 {
933  ofstream outIterFile((char*)(filename.c_str()), ios::out);
934  if (!outIterFile) {
935  edm::LogError("Alignment") << "[HIPAlignmentAlgorithm::writeIterationFile] ERROR: Unable to write Iteration file";
936  }
937  else {
938  outIterFile << iter;
939  edm::LogWarning("Alignment") <<"[HIPAlignmentAlgorithm::writeIterationFile] writing iteration number to file: " << iter;
940  }
941  outIterFile.close();
942 }
943 
944 
945 // ----------------------------------------------------------------------------
946 // set alignment position error
947 
949 {
950 
951 
952  // Check if user wants to override APE
953  if ( !theApplyAPE )
954  {
955  edm::LogWarning("Alignment") <<"[HIPAlignmentAlgorithm::setAlignmentPositionError] No APE applied";
956  return; // NO APE APPLIED
957  }
958 
959 
960  edm::LogWarning("Alignment") <<"[HIPAlignmentAlgorithm::setAlignmentPositionError] Apply APE!";
961 
962  double apeSPar[3], apeRPar[3];
963  for (std::vector<std::pair<std::vector<Alignable*>, std::vector<double> > >::const_iterator alipars = theAPEParameters.begin();
964  alipars != theAPEParameters.end();
965  ++alipars) {
966  const std::vector<Alignable*> &alignables = alipars->first;
967  const std::vector<double> &pars = alipars->second;
968 
969  apeSPar[0] = pars[0];
970  apeSPar[1] = pars[1];
971  apeSPar[2] = pars[2];
972  apeRPar[0] = pars[3];
973  apeRPar[1] = pars[4];
974  apeRPar[2] = pars[5];
975 
976  double function = pars[6];
977 
978  // Printout for debug
979  printf("APE: %u alignables\n", (unsigned int)alignables.size());
980  for ( int i=0; i<21; ++i ) {
981  double apelinstest=calcAPE(apeSPar,i,0.);
982  double apeexpstest=calcAPE(apeSPar,i,1.);
983  double apelinrtest=calcAPE(apeRPar,i,0.);
984  double apeexprtest=calcAPE(apeRPar,i,1.);
985  printf("APE: iter slin sexp rlin rexp: %5d %12.5f %12.5f %12.5f %12.5f\n",
986  i,apelinstest,apeexpstest,apelinrtest,apeexprtest);
987  }
988 
989  // set APE
990  double apeshift=calcAPE(apeSPar,theIteration,function);
991  double aperot =calcAPE(apeRPar,theIteration,function);
992  theAlignmentParameterStore->setAlignmentPositionError( alignables, apeshift, aperot );
993  }
994 
995 }
996 
997 // ----------------------------------------------------------------------------
998 // calculate APE
999 
1000 double
1001 HIPAlignmentAlgorithm::calcAPE(double* par, int iter, double function)
1002 {
1003  double diter=(double)iter;
1004 
1005  // The following floating-point equality check is safe because this
1006  // "0." and this "1." are generated by the compiler, in the very
1007  // same file. Whatever approximization scheme it uses to turn "1."
1008  // into 0.9999999999998 in the HIPAlignmentAlgorithm::initialize is
1009  // also used here. If I'm wrong, you'll get an assertion.
1010  if (function == 0.) {
1011  return max(par[1],par[0]+((par[1]-par[0])/par[2])*diter);
1012  }
1013  else if (function == 1.) {
1014  return max(0.,par[0]*(exp(-pow(diter,par[1])/par[2])));
1015  }
1016  else if (function == 2.) {
1017  int ipar2 = (int) par[2];
1018  int step = iter/ipar2;
1019  double dstep = (double) step;
1020  return max(0.0, par[0] - par[1]*dstep);
1021  }
1022  else assert(false); // should have been caught in the constructor
1023 }
1024 
1025 
1026 // ----------------------------------------------------------------------------
1027 // book root trees
1028 
1030 {
1031  // create ROOT files
1032  theFile = new TFile(outfile.c_str(),"update");
1033  theFile->cd();
1034 
1035  // book event-wise ROOT Tree
1036 
1037  TString tname="T1";
1038  char iterString[5];
1039  snprintf(iterString, sizeof(iterString), "%i",theIteration);
1040  tname.Append("_");
1041  tname.Append(iterString);
1042 
1043  theTree = new TTree(tname,"Eventwise tree");
1044 
1045  //theTree->Branch("Run", &m_Run, "Run/I");
1046  //theTree->Branch("Event", &m_Event, "Event/I");
1047  theTree->Branch("Ntracks", &m_Ntracks, "Ntracks/I");
1048  theTree->Branch("Nhits", m_Nhits, "Nhits[Ntracks]/I");
1049  theTree->Branch("nhPXB", m_nhPXB, "nhPXB[Ntracks]/I");
1050  theTree->Branch("nhPXF", m_nhPXF, "nhPXF[Ntracks]/I");
1051  theTree->Branch("Pt", m_Pt, "Pt[Ntracks]/F");
1052  theTree->Branch("P", m_P, "P[Ntracks]/F");
1053  theTree->Branch("Eta", m_Eta, "Eta[Ntracks]/F");
1054  theTree->Branch("Phi", m_Phi, "Phi[Ntracks]/F");
1055  theTree->Branch("Chi2n", m_Chi2n, "Chi2n[Ntracks]/F");
1056  theTree->Branch("d0", m_d0, "d0[Ntracks]/F");
1057  theTree->Branch("dz", m_dz, "dz[Ntracks]/F");
1058 
1059  // book Alignable-wise ROOT Tree
1060 
1061  theFile2 = new TFile(outfile2.c_str(),"update");
1062  theFile2->cd();
1063 
1064  theTree2 = new TTree("T2","Alignablewise tree");
1065 
1066  theTree2->Branch("Nhit", &m2_Nhit, "Nhit/I");
1067  theTree2->Branch("Type", &m2_Type, "Type/I");
1068  theTree2->Branch("Layer", &m2_Layer, "Layer/I");
1069  theTree2->Branch("Xpos", &m2_Xpos, "Xpos/F");
1070  theTree2->Branch("Ypos", &m2_Ypos, "Ypos/F");
1071  theTree2->Branch("Zpos", &m2_Zpos, "Zpos/F");
1072  theTree2->Branch("Eta", &m2_Eta, "Eta/F");
1073  theTree2->Branch("Phi", &m2_Phi, "Phi/F");
1074  theTree2->Branch("Id", &m2_Id, "Id/i");
1075  theTree2->Branch("ObjId", &m2_ObjId, "ObjId/I");
1076 
1077  // book survey-wise ROOT Tree only if survey is enabled
1078  if (theLevels.size() > 0){
1079 
1080  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::bookRoot] Survey trees booked.";
1081  theFile3 = new TFile(ssurveyfile.c_str(),"update");
1082  theFile3->cd();
1083  theTree3 = new TTree(tname, "Survey Tree");
1084  theTree3->Branch("Id", &m3_Id, "Id/i");
1085  theTree3->Branch("ObjId", &m3_ObjId, "ObjId/I");
1086  theTree3->Branch("Par", &m3_par, "Par[6]/F");
1087  }
1088 
1089  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::bookRoot] Root trees booked.";
1090 
1091 }
1092 
1093 // ----------------------------------------------------------------------------
1094 // fill alignable-wise root tree
1095 
1097 {
1098  theFile2->cd();
1099 
1100  int naligned=0;
1101 
1102  for (vector<Alignable*>::const_iterator it=theAlignables.begin();
1103  it!=theAlignables.end();
1104  ++it) {
1105  Alignable* ali = (*it);
1107 
1108  // consider only those parameters classified as 'valid'
1109  if (dap->isValid()) {
1110 
1111  // get number of hits from user variable
1112  HIPUserVariables* uservar = dynamic_cast<HIPUserVariables*>(dap->userVariables());
1113  m2_Nhit = uservar->nhit;
1114 
1115  // get type/layer
1116  std::pair<int,int> tl = theAlignmentParameterStore->typeAndLayer(ali);
1117  m2_Type = tl.first;
1118  m2_Layer = tl.second;
1119 
1120  // get identifier (as for IO)
1121  m2_Id = ali->id();
1122  m2_ObjId = ali->alignableObjectId();
1123 
1124  // get position
1125  GlobalPoint pos = ali->surface().position();
1126  m2_Xpos = pos.x();
1127  m2_Ypos = pos.y();
1128  m2_Zpos = pos.z();
1129  m2_Eta = pos.eta();
1130  m2_Phi = pos.phi();
1131 
1132  AlgebraicVector pars = dap->parameters();
1133 
1134  if (verbose) {
1135  edm::LogVerbatim("Alignment")
1136  << "------------------------------------------------------------------------\n"
1137  << " ALIGNABLE: " << setw(6) << naligned
1138  << '\n'
1139  << "hits: " << setw(4) << m2_Nhit
1140  << " type: " << setw(4) << m2_Type
1141  << " layer: " << setw(4) << m2_Layer
1142  << " id: " << setw(4) << m2_Id
1143  << " objId: " << setw(4) << m2_ObjId
1144  << '\n'
1145  << fixed << setprecision(5)
1146  << "x,y,z: "
1147  << setw(12) << m2_Xpos
1148  << setw(12) << m2_Ypos
1149  << setw(12) << m2_Zpos
1150  << " eta,phi: "
1151  << setw(12) << m2_Eta
1152  << setw(12) << m2_Phi
1153  << '\n'
1154  << "params: "
1155  << setw(12) << pars[0]
1156  << setw(12) << pars[1]
1157  << setw(12) << pars[2]
1158  << setw(12) << pars[3]
1159  << setw(12) << pars[4]
1160  << setw(12) << pars[5];
1161  }
1162 
1163  naligned++;
1164  theTree2->Fill();
1165  }
1166  }
1167 }
1168 
1169 // ----------------------------------------------------------------------------
1170 
1172 {
1173  // Alignment parameters
1175  // access user variables
1176  HIPUserVariables* uservar = dynamic_cast<HIPUserVariables*>(par->userVariables());
1177  int nhit = uservar->nhit;
1178  // The following variable is needed for the extended 1D/2D hit fix using
1179  // matrix shrinkage and expansion
1180  // int hitdim = uservar->hitdim;
1181 
1182  if (nhit < theMinimumNumberOfHits) {
1183  par->setValid(false);
1184  return false;
1185  }
1186 
1187  AlgebraicSymMatrix jtvj = uservar->jtvj;
1188  AlgebraicVector jtve = uservar->jtve;
1189 
1190  // Shrink input in case of 1D hits and 'v' selected
1191  // in alignment parameters
1192  // if (hitdim==1 && selector[1]==true) {
1193  // int iremove = 1;
1194  // if (selector[0]==false) iremove--;
1195 
1196  // AlgebraicSymMatrix tempjtvj(jtvj.num_row()-1);
1197  // int nr = 0, nc = 0;
1198  // for (int r=0;r<jtvj.num_row();r++) {
1199  // if (r==iremove) continue;
1200  // nc = 0;
1201  // for (int c=0;c<jtvj.num_col();c++) {
1202  // if (c==iremove) continue;
1203  // tempjtvj[nr][nc] = jtvj[r][c];
1204  // nc++;
1205  // }
1206  // nr++;
1207  // }
1208  // jtvj = tempjtvj;
1209 
1210  // AlgebraicVector tempjtve(jtve.num_row()-1);
1211  // nr = 0;
1212  // for (int r=0;r<jtve.num_row();r++) {
1213  // if (r==iremove) continue;
1214  // tempjtve[nr] = jtve[r];
1215  // nr++;
1216  // }
1217  // jtve = tempjtve;
1218  // }
1219 
1220  int ierr;
1221  AlgebraicSymMatrix jtvjinv = jtvj.inverse(ierr);
1222 
1223  if (ierr !=0) {
1224  edm::LogError("Alignment") << "Matrix inversion failed!";
1225  return false;
1226  }
1227 
1228  // these are the alignment corrections+covariance (for selected params)
1229  AlgebraicVector params = - (jtvjinv * jtve);
1230  AlgebraicSymMatrix cov = jtvjinv;
1231 
1232  edm::LogInfo("Alignment") << "parameters " << params;
1233 
1234  // errors of parameters
1235  int npar = params.num_row();
1236  AlgebraicVector paramerr(npar);
1237  AlgebraicVector relerr(npar);
1238  for (int i=0;i<npar;i++) {
1239  if (abs(cov[i][i])>0) paramerr[i] = sqrt(abs(cov[i][i]));
1240  else paramerr[i] = params[i];
1241  relerr[i] = abs(paramerr[i]/params[i]);
1242  if (relerr[i] >= theMaxRelParameterError) {
1243  params[i] = 0;
1244  paramerr[i]=0;
1245  }
1246  }
1247 
1248  // expand output in case of 1D hits and 'v' selected
1249  // in alignment parameters
1250  // if (hitdim==1 && selector[1]==true) {
1251  // int iremove = 1;
1252  // if (selector[0]==false) iremove--;
1253 
1254  // AlgebraicSymMatrix tempcov(cov.num_row()+1,0);
1255  // int nr = 0, nc = 0;
1256  // for (int r=0;r<cov.num_row();r++) {
1257  // if (r==iremove) nr++;
1258  // nc = 0;
1259  // for (int c=0;c<cov.num_col();c++) {
1260  // if (c==iremove) nc++;
1261  // tempcov[nr][nc] = cov[r][c];
1262  // nc++;
1263  // }
1264  // nr++;
1265  // }
1266  // cov = tempcov;
1267 
1268  // AlgebraicVector tempparams(params.num_row()+1,0);
1269  // nr = 0;
1270  // for (int r=0;r<params.num_row();r++) {
1271  // if (r==iremove) nr++;
1272  // tempparams[nr] = params[r];
1273  // nr++;
1274  // }
1275  // params = tempparams;
1276  // }
1277 
1278  // store alignment parameters
1279  AlignmentParameters* parnew = par->cloneFromSelected(params,cov);
1280  ali->setAlignmentParameters(parnew);
1281  parnew->setValid(true);
1282 
1283  return true;
1284 }
1285 
1286 //-----------------------------------------------------------------------------
1287 
1289 {
1290  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::collector] called for iteration "
1291  << theIteration << std::endl;
1292 
1293  HIPUserVariablesIORoot HIPIO;
1294 
1295  for (int ijob=1;ijob<=theCollectorNJobs;ijob++) {
1296 
1297  edm::LogWarning("Alignment") << "reading uservar for job " << ijob;
1298 
1299  stringstream ss;
1300  string str;
1301  ss << ijob;
1302  ss >> str;
1303  string uvfile = theCollectorPath+"/job"+str+"/IOUserVariables.root";
1304 
1305  vector<AlignmentUserVariables*> uvarvec =
1306  HIPIO.readHIPUserVariables(theAlignables, (char*)uvfile.c_str(),
1307  theIteration, ioerr);
1308 
1309  if (ioerr!=0) {
1310  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::collector] could not read user variable files for job "
1311  << ijob;
1312  continue;
1313  }
1314 
1315  // add
1316  vector<AlignmentUserVariables*> uvarvecadd;
1317  vector<AlignmentUserVariables*>::const_iterator iuvarnew=uvarvec.begin();
1318  for (vector<Alignable*>::const_iterator it=theAlignables.begin();
1319  it!=theAlignables.end();
1320  ++it) {
1321  Alignable* ali = *it;
1323 
1324  HIPUserVariables* uvarold = dynamic_cast<HIPUserVariables*>(ap->userVariables());
1325  HIPUserVariables* uvarnew = dynamic_cast<HIPUserVariables*>(*iuvarnew);
1326 
1327  HIPUserVariables* uvar = uvarold->clone();
1328  if (uvarnew!=0) {
1329  uvar->nhit = (uvarold->nhit)+(uvarnew->nhit);
1330  uvar->jtvj = (uvarold->jtvj)+(uvarnew->jtvj);
1331  uvar->jtve = (uvarold->jtve)+(uvarnew->jtve);
1332  uvar->alichi2 = (uvarold->alichi2)+(uvarnew->alichi2);
1333  uvar->alindof = (uvarold->alindof)+(uvarnew->alindof);
1334  delete uvarnew;
1335  }
1336 
1337  uvarvecadd.push_back(uvar);
1338  iuvarnew++;
1339  }
1340 
1342 
1343  //fill Eventwise Tree
1344  if (theFillTrackMonitoring) {
1345  uvfile = theCollectorPath+"/job"+str+"/HIPAlignmentEvents.root";
1346  edm::LogWarning("Alignment") << "Added to the tree "
1347  << fillEventwiseTree(uvfile.c_str(), theIteration, ioerr)
1348  << "tracks";
1349  }
1350 
1351  }//end loop on jobs
1352 }
1353 
1354 //------------------------------------------------------------------------------------
1355 
1356 int HIPAlignmentAlgorithm::fillEventwiseTree(const char* filename, int iter, int ierr)
1357 {
1358  int totntrk = 0;
1359  char treeName[64];
1360  snprintf(treeName, sizeof(treeName), "T1_%d", iter);
1361  //open the file "HIPAlignmentEvents.root" in the job directory
1362  TFile *jobfile = new TFile(filename, "READ");
1363  //grab the tree corresponding to this iteration
1364  TTree *jobtree = (TTree*)jobfile->Get(treeName);
1365  //address and read the variables
1366  static const int nmaxtrackperevent = 1000;
1367  int jobNtracks, jobNhitspertrack[nmaxtrackperevent], jobnhPXB[nmaxtrackperevent], jobnhPXF[nmaxtrackperevent];
1368  float jobP[nmaxtrackperevent], jobPt[nmaxtrackperevent], jobEta[nmaxtrackperevent] , jobPhi[nmaxtrackperevent];
1369  float jobd0[nmaxtrackperevent], jobdz[nmaxtrackperevent] , jobChi2n[nmaxtrackperevent];
1370 
1371  jobtree->SetBranchAddress("Ntracks", &jobNtracks);
1372  jobtree->SetBranchAddress("Nhits", jobNhitspertrack);
1373  jobtree->SetBranchAddress("nhPXB", jobnhPXB);
1374  jobtree->SetBranchAddress("nhPXF", jobnhPXF);
1375  jobtree->SetBranchAddress("Pt", jobPt);
1376  jobtree->SetBranchAddress("P", jobP);
1377  jobtree->SetBranchAddress("d0", jobd0);
1378  jobtree->SetBranchAddress("dz", jobdz);
1379  jobtree->SetBranchAddress("Eta", jobEta);
1380  jobtree->SetBranchAddress("Phi", jobPhi);
1381  jobtree->SetBranchAddress("Chi2n", jobChi2n);
1382  int ievent = 0;
1383  for (ievent=0;ievent<jobtree->GetEntries();++ievent) {
1384  jobtree->GetEntry(ievent);
1385 
1386  //fill the collector tree with them
1387 
1388  // TO BE IMPLEMENTED: a prescale factor like in run()
1389  m_Ntracks = jobNtracks;
1390  int ntrk = 0;
1391  while (ntrk<m_Ntracks) {
1392  if (ntrk<MAXREC) {
1393  totntrk = ntrk+1;
1394  m_Nhits[ntrk] = jobNhitspertrack[ntrk];
1395  m_Pt[ntrk] = jobPt[ntrk];
1396  m_P[ntrk] = jobP[ntrk];
1397  m_nhPXB[ntrk] = jobnhPXB[ntrk];
1398  m_nhPXF[ntrk] = jobnhPXF[ntrk];
1399  m_Eta[ntrk] = jobEta[ntrk];
1400  m_Phi[ntrk] = jobPhi[ntrk];
1401  m_Chi2n[ntrk] = jobChi2n[ntrk];
1402  m_d0[ntrk] = jobd0[ntrk];
1403  m_dz[ntrk] = jobdz[ntrk];
1404  }//end if j<MAXREC
1405  else{
1406  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::fillEventwiseTree] Number of tracks in Eventwise tree exceeds MAXREC: "
1407  << m_Ntracks << " Skipping exceeding tracks.";
1408  ntrk = m_Ntracks+1;
1409  }
1410  ++ntrk;
1411  }//end while loop
1412  theTree->Fill();
1413  }//end loop on i - entries in the job tree
1414 
1415  //clean up
1416  delete jobtree;
1417  delete jobfile;
1418 
1419  return totntrk;
1420 }//end fillEventwiseTree
ClusterRef cluster() const
void attachUserVariables(const align::Alignables &alivec, const std::vector< AlignmentUserVariables * > &uvarvec, int &ierr)
Attach User Variables to given alignables.
double p() const
momentum vector magnitude
Definition: TrackBase.h:129
type
Definition: HCALResponse.h:22
T getParameter(std::string const &) const
align::ID id() const
Return the ID of Alignable, i.e. DetId of &#39;first&#39; component GeomDet(Unit).
Definition: Alignable.h:180
T getUntrackedParameter(std::string const &, T const &) const
int i
Definition: DBlmapReader.cc:9
float xx() const
Definition: LocalError.h:24
double d0() const
dxy parameter in perigee convention (d0 = - dxy)
Definition: TrackBase.h:123
AlignableDetOrUnitPtr alignableFromGeomDet(const GeomDet *geomDet)
Returns AlignableDetOrUnitPtr corresponding to given GeomDet.
AlignmentParameterStore * theAlignmentParameterStore
list step
Definition: launcher.py:15
bool calcParameters(Alignable *ali)
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
TSOS combine(const TSOS &pTsos1, const TSOS &pTsos2) const
int fillEventwiseTree(const char *filename, int iter, int ierr)
TrajectoryStateOnSurface forwardPredictedState() const
Access to forward predicted state (from fitter or builder)
void setAlignmentPositionError(const align::Alignables &alivec, double valshift, double valrot)
Set Alignment position error.
void writeAlignableOriginalPositions(const align::Alignables &alivec, const char *filename, int iter, bool validCheck, int &ierr)
write Alignable original (before misalignment) absolute positions
align::StructureType m2_ObjId
Geom::Phi< T > phi() const
Definition: PV3DBase.h:68
T y() const
Definition: PV3DBase.h:62
Alignable * alignableFromAlignableDet(AlignableDetOrUnitPtr adet) const
Get relevant Alignable from AlignableDet.
virtual const TrackingRecHit * hit() const =0
#define abs(x)
Definition: mlp_lapack.h:159
double phi() const
azimuthal angle of momentum vector
Definition: TrackBase.h:139
ConstRecHitPointer recHit() const
void writeIterationFile(std::string filename, int iter)
void applyParameters(void)
Obsolete: Use AlignableNavigator::alignableDetFromDetId and alignableFromAlignableDet.
AlgebraicVector jtve
T eta() const
HIPUserVariables * clone(void) const
void applyAlignableAbsolutePositions(const align::Alignables &alis, const AlignablePositions &newpos, int &ierr)
apply absolute positions to alignables
LocalError positionError() const
AlignmentParameters * alignmentParameters() const
Get the AlignmentParameters.
Definition: Alignable.h:57
const ConstTrajTrackPairCollection & trajTrackPairs() const
define event information passed to algorithms
void writeHIPUserVariables(const Alignables &alivec, const char *filename, int iter, bool validCheck, int &ierr)
AlgebraicSymMatrix jtvj
std::vector< std::pair< std::vector< Alignable * >, std::vector< double > > > theAPEParameters
const AlgebraicVector & parameters(void) const
Get alignment parameters.
DataContainer const & measurements() const
Definition: Trajectory.h:203
AlignmentUserVariables * userVariables(void) const
Get pointer to user variables.
AlignablePositions readAlignableAbsolutePositions(const align::Alignables &alivec, const char *filename, int iter, int &ierr)
read Alignable current absolute positions
float xy() const
Definition: LocalError.h:25
void clear()
remove all selected Alignables and geometrical restrictions
double eta() const
pseudorapidity of momentum vector
Definition: TrackBase.h:141
double calcAPE(double *par, int iter, double function)
void startNewLoop(void)
Called at start of new loop.
int numberOfValidPixelBarrelHits() const
Definition: HitPattern.h:570
std::vector< AlignmentUserVariables * > readHIPUserVariables(const Alignables &alivec, const char *filename, int iter, int &ierr)
void setAlignmentParameters(AlignmentParameters *dap)
Set the AlignmentParameters.
Definition: Alignable.cc:81
CLHEP::HepMatrix AlgebraicMatrix
HIPAlignmentAlgorithm(const edm::ParameterSet &cfg)
Constructor.
float yy() const
Definition: LocalError.h:26
const T & max(const T &a, const T &b)
void setValid(bool v)
Set validity flag.
T sqrt(T t)
Definition: SSEVec.h:46
double pt() const
track transverse momentum
Definition: TrackBase.h:131
T z() const
Definition: PV3DBase.h:63
tuple result
Definition: query.py:137
void initialize(const edm::EventSetup &setup, AlignableTracker *tracker, AlignableMuon *muon, AlignableExtras *extras, AlignmentParameterStore *store)
Call at beginning of job.
virtual StructureType alignableObjectId() const =0
Return the alignable type identifier.
AlignableNavigator * theAlignableDetAccessor
Allows conversion between type and name, and vice-versa.
ClusterRef cluster() const
int readIterationFile(std::string filename)
unsigned short numberOfValidHits() const
number of valid hits found
Definition: TrackBase.h:232
const LocalTrajectoryError & localError() const
const HitPattern & hitPattern() const
Access the hit pattern, indicating in which Tracker layers the track has hits.
Definition: TrackBase.h:223
int subdetId() const
get the contents of the subdetector field (not cast into any detector&#39;s numbering enum) ...
Definition: DetId.h:39
const AlignableSurface & surface() const
Return the Surface (global position and orientation) of the object.
Definition: Alignable.h:126
double dz() const
dz parameter (= dsz/cos(lambda)). This is the track z0 w.r.t (0,0,0) only if the refPoint is close to...
Definition: TrackBase.h:127
tuple out
Definition: dbtoconf.py:99
const align::Alignables & selectedAlignables() const
vector of alignables selected so far
int numSelected(void) const
Get number of selected parameters.
CLHEP::HepVector AlgebraicVector
bool processHit1D(const AlignableDetOrUnitPtr alidet, const Alignable *ali, const TrajectoryStateOnSurface &tsos, const TransientTrackingRecHit *hit)
void setUserVariables(AlignmentUserVariables *auv)
Set pointer to user variables.
tuple tracks
Definition: testEve_cfg.py:39
virtual LocalError localPositionError() const =0
ClusterRef cluster() const
Definition: SiPixelRecHit.h:41
void writeAlignmentParameters(const align::Alignables &alivec, const char *filename, int iter, bool validCheck, int &ierr)
write AlignmentParameters
CompositeAlignmentParameters selectParameters(const std::vector< AlignableDet * > &alignabledets) const
AlgebraicSymMatrix inverseCovariance() const
Get inverse of survey covariance wrt given structure type in constructor.
bool isValid() const
std::vector< edm::ParameterSet > theAPEParameterSet
align::StructureType m3_ObjId
align::StructureType nameToType(const std::string &name) const
Convert name to type.
int numberOfValidPixelEndcapHits() const
Definition: HitPattern.h:574
T eta() const
Definition: PV3DBase.h:75
AlgebraicVector sensorResidual() const
std::vector< AlignableDetOrUnitPtr > alignablesFromHits(const std::vector< const TransientTrackingRecHit * > &hitvec)
Returns vector AlignableDetOrUnitPtr for given vector of Hits.
const AliClusterValueMap * clusterValueMap() const
bool isValid(void) const
Get validity flag.
tuple filename
Definition: lut2db_cfg.py:20
bool processHit2D(const AlignableDetOrUnitPtr alidet, const Alignable *ali, const TrajectoryStateOnSurface &tsos, const TransientTrackingRecHit *hit)
CLHEP::HepSymMatrix AlgebraicSymMatrix
unsigned int addSelections(const edm::ParameterSet &pSet)
void terminate(void)
Call at end of job.
std::vector< AlignableAbsData > AlignablePositions
Definition: AlignableData.h:51
void writeAlignableAbsolutePositions(const align::Alignables &alivec, const char *filename, int iter, bool validCheck, int &ierr)
write Alignable current absolute positions
DetId geographicalId() const
virtual AlignmentParameters * cloneFromSelected(const AlgebraicVector &par, const AlgebraicSymMatrix &cov) const =0
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:36
T x() const
Definition: PV3DBase.h:61
virtual LocalPoint localPosition() const =0
const PositionType & position() const
std::vector< align::StructureType > theLevels
void setup(std::vector< TH2F > &depth, std::string name, std::string units="")
std::vector< Alignable * > theAlignables
bool valid() const
Power< A, B >::type pow(const A &a, const B &b)
Definition: Power.h:40
TrajectoryStateOnSurface backwardPredictedState() const
Access to backward predicted state (from smoother)
const align::Alignables & alignables(void) const
get all alignables
std::vector< ConstTrajTrackPair > ConstTrajTrackPairCollection
std::string className(const T &t)
Definition: ClassName.h:30
std::pair< int, int > typeAndLayer(const Alignable *ali) const
Obtain type and layer from Alignable.
Our base class.
Definition: SiPixelRecHit.h:22
void run(const edm::EventSetup &setup, const EventInfo &eventInfo)
Run the algorithm.
virtual AlgebraicMatrix selectedDerivatives(const TrajectoryStateOnSurface &tsos, const AlignableDetOrUnitPtr &alidet) const
Definition: DDAxes.h:10