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