test
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  if (eventInfo.clusterValueMap()) {
818  // check from the PrescalingMap if the hit was taken.
819  // If not skip to the next TM
820  // bool hitTaken=false;
821  AlignmentClusterFlag myflag;
822 
823  int subDet = hit->geographicalId().subdetId();
824  //take the actual RecHit out of the Transient one
825  const TrackingRecHit *rechit=hit->hit();
826  if (subDet>2) { // AM: if possible use enum instead of hard-coded value
827  const std::type_info &type = typeid(*rechit);
828 
829  if (type == typeid(SiStripRecHit1D)) {
830 
831  const SiStripRecHit1D* stripHit1D = dynamic_cast<const SiStripRecHit1D*>(rechit);
832  if (stripHit1D) {
833  SiStripRecHit1D::ClusterRef stripclust(stripHit1D->cluster());
834  // myflag=PrescMap[stripclust];
835  myflag = (*eventInfo.clusterValueMap())[stripclust];
836  } else {
837  edm::LogError("HIPAlignmentAlgorithm")
838  << "ERROR in <HIPAlignmentAlgorithm::run>: Dynamic cast of Strip RecHit failed! "
839  << "TypeId of the RecHit: " << className(*hit) <<std::endl;
840  }
841 
842  }//end if type = SiStripRecHit1D
843  else if(type == typeid(SiStripRecHit2D)){
844 
845  const SiStripRecHit2D* stripHit2D = dynamic_cast<const SiStripRecHit2D*>(rechit);
846  if (stripHit2D) {
847  SiStripRecHit2D::ClusterRef stripclust(stripHit2D->cluster());
848  // myflag=PrescMap[stripclust];
849  myflag = (*eventInfo.clusterValueMap())[stripclust];
850  } else {
851  edm::LogError("HIPAlignmentAlgorithm")
852  << "ERROR in <HIPAlignmentAlgorithm::run>: Dynamic cast of Strip RecHit failed! "
853  // << "TypeId of the TTRH: " << className(*ttrhit) << std::endl;
854  << "TypeId of the TTRH: " << className(*hit) << std::endl;
855  }
856  } //end if type == SiStripRecHit2D
857  } //end if hit from strips
858  else {
859  const SiPixelRecHit* pixelhit= dynamic_cast<const SiPixelRecHit*>(rechit);
860  if (pixelhit) {
861  SiPixelClusterRefNew pixelclust(pixelhit->cluster());
862  // myflag=PrescMap[pixelclust];
863  myflag = (*eventInfo.clusterValueMap())[pixelclust];
864  }
865  else {
866  edm::LogError("HIPAlignmentAlgorithm")
867  << "ERROR in <HIPAlignmentAlgorithm::run>: Dynamic cast of Pixel RecHit failed! "
868  // << "TypeId of the TTRH: " << className(*ttrhit) << std::endl;
869  << "TypeId of the TTRH: " << className(*hit) << std::endl;
870  }
871  } //end 'else' it is a pixel hit
872  // bool hitTaken=myflag.isTaken();
873  if (!myflag.isTaken()) {
874  continue;
875  }
876  }//end if Prescaled Hits
878 
880  meas.backwardPredictedState());
881 
882  if(tsos.isValid()){
883  // hitvec.push_back(ttrhit);
884  hitvec.push_back(hit);
885  tsosvec.push_back(tsos);
886  }
887 
888  } //hit valid
889  }
890 
891  // transform RecHit vector to AlignableDet vector
892  std::vector <AlignableDetOrUnitPtr> alidetvec = theAlignableDetAccessor->alignablesFromHits(hitvec);
893 
894  // get concatenated alignment parameters for list of alignables
896 
897  std::vector<TrajectoryStateOnSurface>::const_iterator itsos=tsosvec.begin();
898  std::vector<const TransientTrackingRecHit*>::const_iterator ihit=hitvec.begin();
899 
900  // loop over vectors(hit,tsos)
901  while (itsos != tsosvec.end()) {
902 
903  // get AlignableDet for this hit
904  const GeomDet* det = (*ihit)->det();
905  // int subDet= (*ihit)->geographicalId().subdetId();
906  uint32_t nhitDim = (*ihit)->dimension();
907 
909 
910  // get relevant Alignable
911  Alignable* ali = aap.alignableFromAlignableDet(alidet);
912 
913  if (ali!=0) {
914 
915  const TrajectoryStateOnSurface & tsos=*itsos;
916 
917 // LocalVector v = tsos.localDirection();
918 // double proj_z = v.dot(LocalVector(0,0,1));
919 
920 //In fact, sin_theta=Abs(mom_z)
921  double mom_x = tsos.localDirection().x();
922  double mom_y = tsos.localDirection().y();
923  double mom_z = tsos.localDirection().z();
924  double sin_theta = TMath::Abs(mom_z) / sqrt(pow(mom_x,2)+pow(mom_y,2)+pow(mom_z,2) );
925  double angle = TMath::ASin(sin_theta);
926 
927 
928 //Make cut on hit impact angle, reduce collision hits perpendicular to modules
929  if(IsCollision)
930  { if (angle>col_cut)ihitwt=0;}
931  else
932  { if (angle<cos_cut)ihitwt=0;}
933  m_angle = angle;
934  m_sinTheta = sin_theta;
935  m_detId = ali->id();
936  m_hitwt = ihitwt;
937 
938  if (theFillTrackMonitoring) hitTree->Fill();
939 
940  if ((nhitDim==1)&&(ihitwt!=0)) {
941  processHit1D(alidet, ali, *itsos, *ihit, ihitwt);
942  } else if ((nhitDim==2)&&(ihitwt!=0)) {
943  processHit2D(alidet, ali, *itsos, *ihit, ihitwt);
944  }
945  }
946 
947  itsos++;
948  ihit++;
949  }
950  } // end of track loop
951 
952  // fill eventwise root tree (with prescale defined in pset)
955  //edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::run] theCurrentPrescale="<<theCurrentPrescale;
956  if (theCurrentPrescale<=0) {
957  theTree->Fill();
959  }
960  }
961 }
962 
963 // ----------------------------------------------------------------------------
964 
966 {
967  int result;
968 
969  std::ifstream inIterFile(filename.c_str(), std::ios::in);
970  if (!inIterFile) {
971  edm::LogError("Alignment") << "[HIPAlignmentAlgorithm::readIterationFile] ERROR! "
972  << "Unable to open Iteration file";
973  result = -1;
974  }
975  else {
976  inIterFile >> result;
977  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::readIterationFile] "
978  << "Read last iteration number from file: " << result;
979  }
980  inIterFile.close();
981 
982  return result;
983 }
984 
985 // ----------------------------------------------------------------------------
986 
988 {
989  std::ofstream outIterFile((filename.c_str()), std::ios::out);
990  if (!outIterFile) {
991  edm::LogError("Alignment") << "[HIPAlignmentAlgorithm::writeIterationFile] ERROR: Unable to write Iteration file";
992  }
993  else {
994  outIterFile << iter;
995  edm::LogWarning("Alignment") <<"[HIPAlignmentAlgorithm::writeIterationFile] writing iteration number to file: " << iter;
996  }
997  outIterFile.close();
998 }
999 
1000 
1001 // ----------------------------------------------------------------------------
1002 // set alignment position error
1003 
1005 {
1006 
1007 
1008  // Check if user wants to override APE
1009  if ( !theApplyAPE )
1010  {
1011  edm::LogWarning("Alignment") <<"[HIPAlignmentAlgorithm::setAlignmentPositionError] No APE applied";
1012  return; // NO APE APPLIED
1013  }
1014 
1015 
1016  edm::LogWarning("Alignment") <<"[HIPAlignmentAlgorithm::setAlignmentPositionError] Apply APE!";
1017 
1018  double apeSPar[3], apeRPar[3];
1019  for (std::vector<std::pair<std::vector<Alignable*>, std::vector<double> > >::const_iterator alipars = theAPEParameters.begin();
1020  alipars != theAPEParameters.end();
1021  ++alipars) {
1022  const std::vector<Alignable*> &alignables = alipars->first;
1023  const std::vector<double> &pars = alipars->second;
1024 
1025  apeSPar[0] = pars[0];
1026  apeSPar[1] = pars[1];
1027  apeSPar[2] = pars[2];
1028  apeRPar[0] = pars[3];
1029  apeRPar[1] = pars[4];
1030  apeRPar[2] = pars[5];
1031 
1032  double function = pars[6];
1033 
1034  // Printout for debug
1035  printf("APE: %u alignables\n", (unsigned int)alignables.size());
1036  for ( int i=0; i<21; ++i ) {
1037  double apelinstest=calcAPE(apeSPar,i,0.);
1038  double apeexpstest=calcAPE(apeSPar,i,1.);
1039  double apestepstest=calcAPE(apeSPar,i,2.);
1040  double apelinrtest=calcAPE(apeRPar,i,0.);
1041  double apeexprtest=calcAPE(apeRPar,i,1.);
1042  double apesteprtest=calcAPE(apeRPar,i,2.);
1043  printf("APE: iter slin sexp sstep rlin rexp rstep: %5d %12.5f %12.5f %12.5f %12.5f %12.5f %12.5f \n",
1044  i,apelinstest,apeexpstest,apestepstest, apelinrtest,apeexprtest,apesteprtest);
1045  }
1046 
1047  // set APE
1048  double apeshift=calcAPE(apeSPar,theIteration,function);
1049  double aperot =calcAPE(apeRPar,theIteration,function);
1050  theAlignmentParameterStore->setAlignmentPositionError( alignables, apeshift, aperot );
1051  }
1052 
1053 }
1054 
1055 // ----------------------------------------------------------------------------
1056 // calculate APE
1057 
1058 double
1059 HIPAlignmentAlgorithm::calcAPE(double* par, int iter, double function)
1060 {
1061  double diter=(double)iter;
1062 
1063  // The following floating-point equality check is safe because this
1064  // "0." and this "1." are generated by the compiler, in the very
1065  // same file. Whatever approximization scheme it uses to turn "1."
1066  // into 0.9999999999998 in the HIPAlignmentAlgorithm::initialize is
1067  // also used here. If I'm wrong, you'll get an assertion.
1068  if (function == 0.) {
1069  return std::max(par[1],par[0]+((par[1]-par[0])/par[2])*diter);
1070  }
1071  else if (function == 1.) {
1072  return std::max(0.,par[0]*(exp(-pow(diter,par[1])/par[2])));
1073  }
1074  else if (function == 2.) {
1075  int ipar2 = (int) par[2];
1076  int step = iter/ipar2;
1077  double dstep = (double) step;
1078  return std::max(0.0, par[0] - par[1]*dstep);
1079  }
1080  else assert(false); // should have been caught in the constructor
1081 }
1082 
1083 
1084 // ----------------------------------------------------------------------------
1085 // book root trees
1086 
1088 {
1089  TString tname="T1";
1090  char iterString[5];
1091  snprintf(iterString, sizeof(iterString), "%i",theIteration);
1092  tname.Append("_");
1093  tname.Append(iterString);
1094 
1095  // create ROOT files
1096  if (theFillTrackMonitoring) {
1097  theFile = new TFile(outfile.c_str(),"update");
1098  theFile->cd();
1099 
1100  // book event-wise ROOT Tree
1101 
1102  TString tname_hit="T1_hit";
1103  tname_hit.Append("_");
1104  tname_hit.Append(iterString);
1105 
1106  theTree = new TTree(tname,"Eventwise tree");
1107 
1108  //theTree->Branch("Run", &m_Run, "Run/I");
1109  //theTree->Branch("Event", &m_Event, "Event/I");
1110  theTree->Branch("Ntracks", &m_Ntracks, "Ntracks/I");
1111  theTree->Branch("Nhits", m_Nhits, "Nhits[Ntracks]/I");
1112  theTree->Branch("nhPXB", m_nhPXB, "nhPXB[Ntracks]/I");
1113  theTree->Branch("nhPXF", m_nhPXF, "nhPXF[Ntracks]/I");
1114  theTree->Branch("nhTIB", m_nhTIB, "nhTIB[Ntracks]/I");
1115  theTree->Branch("nhTOB", m_nhTOB, "nhTOB[Ntracks]/I");
1116  theTree->Branch("nhTID", m_nhTID, "nhTID[Ntracks]/I");
1117  theTree->Branch("nhTEC", m_nhTEC, "nhTEC[Ntracks]/I");
1118  theTree->Branch("Pt", m_Pt, "Pt[Ntracks]/F");
1119  theTree->Branch("P", m_P, "P[Ntracks]/F");
1120  theTree->Branch("Eta", m_Eta, "Eta[Ntracks]/F");
1121  theTree->Branch("Phi", m_Phi, "Phi[Ntracks]/F");
1122  theTree->Branch("Chi2n", m_Chi2n, "Chi2n[Ntracks]/F");
1123  theTree->Branch("d0", m_d0, "d0[Ntracks]/F");
1124  theTree->Branch("dz", m_dz, "dz[Ntracks]/F");
1125  theTree->Branch("wt", m_wt, "wt[Ntracks]/F");
1126 
1127  hitTree = new TTree(tname_hit,"Hitwise tree");
1128  hitTree->Branch("Id", &m_detId, "Id/i");
1129  hitTree->Branch("sinTheta", &m_sinTheta, "sinTheta/F");
1130  hitTree->Branch("hitImpactAngle", &m_angle, "hitImpactAngle/F");
1131  hitTree->Branch("wt", &m_hitwt,"wt/F");
1132  }
1133  // book Alignable-wise ROOT Tree
1134 
1135  theFile2 = new TFile(outfile2.c_str(),"update");
1136  theFile2->cd();
1137 
1138  theTree2 = new TTree("T2","Alignablewise tree");
1139 
1140  theTree2->Branch("Nhit", &m2_Nhit, "Nhit/I");
1141  theTree2->Branch("Type", &m2_Type, "Type/I");
1142  theTree2->Branch("Layer", &m2_Layer, "Layer/I");
1143  theTree2->Branch("Xpos", &m2_Xpos, "Xpos/F");
1144  theTree2->Branch("Ypos", &m2_Ypos, "Ypos/F");
1145  theTree2->Branch("Zpos", &m2_Zpos, "Zpos/F");
1146  theTree2->Branch("Eta", &m2_Eta, "Eta/F");
1147  theTree2->Branch("Phi", &m2_Phi, "Phi/F");
1148  theTree2->Branch("Id", &m2_Id, "Id/i");
1149  theTree2->Branch("ObjId", &m2_ObjId, "ObjId/I");
1150 
1151  // book survey-wise ROOT Tree only if survey is enabled
1152  if (theLevels.size() > 0){
1153 
1154  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::bookRoot] Survey trees booked.";
1155  theFile3 = new TFile(ssurveyfile.c_str(),"update");
1156  theFile3->cd();
1157  theTree3 = new TTree(tname, "Survey Tree");
1158  theTree3->Branch("Id", &m3_Id, "Id/i");
1159  theTree3->Branch("ObjId", &m3_ObjId, "ObjId/I");
1160  theTree3->Branch("Par", &m3_par, "Par[6]/F");
1161  }
1162 
1163  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::bookRoot] Root trees booked.";
1164 
1165 }
1166 
1167 // ----------------------------------------------------------------------------
1168 // fill alignable-wise root tree
1169 
1171 {
1172  using std::setw;
1173  theFile2->cd();
1174 
1175  int naligned=0;
1176 
1177  //Retrieve tracker topology from geometry
1178  edm::ESHandle<TrackerTopology> tTopoHandle;
1179 // iSetup.get<IdealGeometryRecord>().get(tTopoHandle);
1180  iSetup.get<TrackerTopologyRcd>().get(tTopoHandle);
1181 
1182  const TrackerTopology* const tTopo = tTopoHandle.product();
1183 
1184  for (std::vector<Alignable*>::const_iterator it=theAlignables.begin();
1185  it!=theAlignables.end();
1186  ++it) {
1187  Alignable* ali = (*it);
1189 
1190  // consider only those parameters classified as 'valid'
1191  if (dap->isValid()) {
1192 
1193  // get number of hits from user variable
1194  HIPUserVariables* uservar = dynamic_cast<HIPUserVariables*>(dap->userVariables());
1195  m2_Nhit = uservar->nhit;
1196 
1197  // get type/layer
1198  std::pair<int,int> tl = theAlignmentParameterStore->typeAndLayer(ali, tTopo);
1199  m2_Type = tl.first;
1200  m2_Layer = tl.second;
1201 
1202  // get identifier (as for IO)
1203  m2_Id = ali->id();
1204  m2_ObjId = ali->alignableObjectId();
1205 
1206  // get position
1207  GlobalPoint pos = ali->surface().position();
1208  m2_Xpos = pos.x();
1209  m2_Ypos = pos.y();
1210  m2_Zpos = pos.z();
1211  m2_Eta = pos.eta();
1212  m2_Phi = pos.phi();
1213 
1214  AlgebraicVector pars = dap->parameters();
1215 
1216  if (verbose) {
1217  edm::LogVerbatim("Alignment")
1218  << "------------------------------------------------------------------------\n"
1219  << " ALIGNABLE: " << setw(6) << naligned
1220  << '\n'
1221  << "hits: " << setw(4) << m2_Nhit
1222  << " type: " << setw(4) << m2_Type
1223  << " layer: " << setw(4) << m2_Layer
1224  << " id: " << setw(4) << m2_Id
1225  << " objId: " << setw(4) << m2_ObjId
1226  << '\n'
1227  << std::fixed << std::setprecision(5)
1228  << "x,y,z: "
1229  << setw(12) << m2_Xpos
1230  << setw(12) << m2_Ypos
1231  << setw(12) << m2_Zpos
1232  << " eta,phi: "
1233  << setw(12) << m2_Eta
1234  << setw(12) << m2_Phi
1235  << '\n'
1236  << "params: "
1237  << setw(12) << pars[0]
1238  << setw(12) << pars[1]
1239  << setw(12) << pars[2]
1240  << setw(12) << pars[3]
1241  << setw(12) << pars[4]
1242  << setw(12) << pars[5];
1243  }
1244 
1245  naligned++;
1246  theTree2->Fill();
1247  }
1248  }
1249 }
1250 
1251 // ----------------------------------------------------------------------------
1252 
1253 bool HIPAlignmentAlgorithm::calcParameters(Alignable* ali , int setDet, double start, double step)
1254 {
1255  // Alignment parameters
1257  // access user variables
1258  HIPUserVariables* uservar = dynamic_cast<HIPUserVariables*>(par->userVariables());
1259  int nhit = uservar->nhit;
1260  // The following variable is needed for the extended 1D/2D hit fix using
1261  // matrix shrinkage and expansion
1262  // int hitdim = uservar->hitdim;
1263 
1264  edm::LogWarning("Alignment") << "Processing Detector"<<ali->id() ;
1265 
1266  if ( (setDet==0) && (nhit < theMinimumNumberOfHits)) {
1267  par->setValid(false);
1268  edm::LogWarning("Alignment") << "nhit="<<nhit<<" too small,skip!" ;
1269  return false;
1270  }
1271 
1272  AlgebraicSymMatrix jtvj = uservar->jtvj;
1273  AlgebraicVector jtve = uservar->jtve;
1274 
1275 
1276  // these are the alignment corrections+covariance (for selected params)
1277 
1278 
1279  int npar = jtve.num_row();
1280  AlgebraicVector params(npar);
1281  AlgebraicVector paramerr(npar);
1282  AlgebraicSymMatrix cov(npar*npar);
1283 
1284  if (setDet!=0) {
1285  if (params.num_row()!=1){
1286  edm::LogError("Alignment") << "For scanning, please only turn on one parameter! check common_cff_py.txt";
1287  return false;
1288  }
1289  if (theIteration==1) params[0] = start;
1290  else params[0]=step;
1291  }
1292 
1293 // edm::LogWarning("Alignment") << "parameters " << params;
1294 
1295  // errors of parameters
1296 
1297  if (setDet==0){
1298  int ierr;
1299  AlgebraicSymMatrix jtvjinv = jtvj.inverse(ierr);
1300 
1301  if (ierr !=0) {
1302  edm::LogError("Alignment") << "Matrix inversion failed!";
1303  return false;
1304  }
1305  params = - (jtvjinv * jtve);
1306  cov = jtvjinv;
1307 
1308 // edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::CalcParameters]: parameters before RelErrCut= " << params;
1309 // edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::CalcParameters]: cov= " << cov;
1310  AlgebraicVector relerr(npar);
1311  for (int i=0;i<npar;i++) {
1312  if (fabs(cov[i][i])>0) paramerr[i] = sqrt(fabs(cov[i][i]));
1313  else paramerr[i] = params[i];
1314  if (params[i]!=0) relerr[i] = fabs(paramerr[i]/params[i]);
1315  else relerr[i]=0;
1316  if (relerr[i] >= theMaxRelParameterError) {
1317 // edm::LogWarning("Alignment") << "RelError="<<relerr[i]<<"too large!" ;
1318  params[i] = 0;
1319  paramerr[i]=0;
1320  }
1321  }
1322  }
1323 
1324  if (setDet!=0)
1325  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::CalcParameters]: parameters = " << params;
1326 
1327  uservar->alipar=params;
1328  uservar->alierr=paramerr;
1329 
1330  AlignmentParameters* parnew = par->cloneFromSelected(params,cov);
1331  ali->setAlignmentParameters(parnew);
1332  parnew->setValid(true);
1333 
1334  return true;
1335 }
1336 
1337 //-----------------------------------------------------------------------------
1338 
1340 {
1341  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::collector] called for iteration "
1342  << theIteration << std::endl;
1343 
1344  HIPUserVariablesIORoot HIPIO;
1345 
1346 
1347  for (int ijob=1;ijob<=theCollectorNJobs;ijob++) {
1348 
1349  edm::LogWarning("Alignment") << "reading uservar for job " << ijob;
1350 
1351  std::stringstream ss;
1352  std::string str;
1353  ss << ijob;
1354  ss >> str;
1355  std::string uvfile = theCollectorPath+"/job"+str+"/IOUserVariables.root";
1356 
1357  std::vector<AlignmentUserVariables*> uvarvec =
1358  HIPIO.readHIPUserVariables(theAlignables, uvfile.c_str(),
1359  theIteration, ioerr);
1360 
1361  if (ioerr!=0) {
1362  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::collector] could not read user variable files for job "
1363  << ijob;
1364  continue;
1365  }
1366 
1367  // add
1368  std::vector<AlignmentUserVariables*> uvarvecadd;
1369  std::vector<AlignmentUserVariables*>::const_iterator iuvarnew=uvarvec.begin();
1370  for (std::vector<Alignable*>::const_iterator it=theAlignables.begin();
1371  it!=theAlignables.end();
1372  ++it) {
1373  Alignable* ali = *it;
1375 
1376  HIPUserVariables* uvarold = dynamic_cast<HIPUserVariables*>(ap->userVariables());
1377  HIPUserVariables* uvarnew = dynamic_cast<HIPUserVariables*>(*iuvarnew);
1378 
1379  HIPUserVariables* uvar = uvarold->clone();
1380  if (uvarnew!=0) {
1381  //edm::LogWarning("Alignment") << "[collector-job"<<ijob<<"]alignables:old_nhit:"<<(uvarold->nhit)<<" new_nhit:"<<(uvarnew->nhit);
1382 
1383  uvar->nhit = (uvarold->nhit)+(uvarnew->nhit);
1384  uvar->jtvj = (uvarold->jtvj)+(uvarnew->jtvj);
1385  uvar->jtve = (uvarold->jtve)+(uvarnew->jtve);
1386  uvar->alichi2 = (uvarold->alichi2)+(uvarnew->alichi2);
1387  uvar->alindof = (uvarold->alindof)+(uvarnew->alindof);
1388  delete uvarnew;
1389  }
1390 
1391  uvarvecadd.push_back(uvar);
1392  iuvarnew++;
1393  }
1394 
1396 
1397  //fill Eventwise Tree
1398  if (theFillTrackMonitoring) {
1399  uvfile = theCollectorPath+"/job"+str+"/HIPAlignmentEvents.root";
1400  edm::LogWarning("Alignment") << "Added to the tree "
1401  << fillEventwiseTree(uvfile.c_str(), theIteration, ioerr)
1402  << "tracks";
1403  }
1404 
1405  }//end loop on jobs
1406 }
1407 
1408 //------------------------------------------------------------------------------------
1409 
1410 int HIPAlignmentAlgorithm::fillEventwiseTree(const char* filename, int iter, int ierr)
1411 {
1412  int totntrk = 0;
1413  char treeName[64];
1414  snprintf(treeName, sizeof(treeName), "T1_%d", iter);
1415 //CY: hit tree
1416  char hitTreeName[64];
1417  snprintf(hitTreeName, sizeof(hitTreeName), "T1_hit_%d", iter);
1418 
1419 
1420  //open the file "HIPAlignmentEvents.root" in the job directory
1421  TFile *jobfile = new TFile(filename, "READ");
1422  //grab the tree corresponding to this iteration
1423  TTree *jobtree = (TTree*)jobfile->Get(treeName);
1424  TTree *hittree = (TTree*)jobfile->Get(hitTreeName);
1425  //address and read the variables
1426  static const int nmaxtrackperevent = 1000;
1427  int jobNtracks, jobNhitspertrack[nmaxtrackperevent], jobnhPXB[nmaxtrackperevent], jobnhPXF[nmaxtrackperevent],jobnhTIB[nmaxtrackperevent], jobnhTOB[nmaxtrackperevent],jobnhTID[nmaxtrackperevent], jobnhTEC[nmaxtrackperevent];
1428  float jobP[nmaxtrackperevent], jobPt[nmaxtrackperevent], jobEta[nmaxtrackperevent] , jobPhi[nmaxtrackperevent];
1429  float jobd0[nmaxtrackperevent],jobwt[nmaxtrackperevent], jobdz[nmaxtrackperevent] , jobChi2n[nmaxtrackperevent];
1430  float jobsinTheta,jobHitWt,jobangle;
1431  align::ID jobDetId;
1432 
1433  jobtree->SetBranchAddress("Ntracks", &jobNtracks);
1434  jobtree->SetBranchAddress("Nhits", jobNhitspertrack);
1435  jobtree->SetBranchAddress("nhPXB", jobnhPXB);
1436  jobtree->SetBranchAddress("nhPXF", jobnhPXF);
1437  jobtree->SetBranchAddress("nhTIB", jobnhTIB);
1438  jobtree->SetBranchAddress("nhTOB", jobnhTOB);
1439  jobtree->SetBranchAddress("nhTID", jobnhTID);
1440  jobtree->SetBranchAddress("nhTEC", jobnhTEC);
1441  jobtree->SetBranchAddress("Pt", jobPt);
1442  jobtree->SetBranchAddress("P", jobP);
1443  jobtree->SetBranchAddress("d0", jobd0);
1444  jobtree->SetBranchAddress("dz", jobdz);
1445  jobtree->SetBranchAddress("Eta", jobEta);
1446  jobtree->SetBranchAddress("Phi", jobPhi);
1447  jobtree->SetBranchAddress("Chi2n", jobChi2n);
1448  jobtree->SetBranchAddress("wt", jobwt);
1449 
1450 // CY: hit info
1451  hittree->SetBranchAddress("sinTheta", &jobsinTheta);
1452  hittree->SetBranchAddress("HitImpactAngle", &jobangle);
1453  hittree->SetBranchAddress("Id", &jobDetId);
1454  hittree->SetBranchAddress("wt", &jobHitWt);
1455 
1456  int ievent = 0;
1457  for (ievent=0;ievent<jobtree->GetEntries();++ievent) {
1458  jobtree->GetEntry(ievent);
1459 
1460  //fill the collector tree with them
1461 
1462  // TO BE IMPLEMENTED: a prescale factor like in run()
1463  m_Ntracks = jobNtracks;
1464  int ntrk = 0;
1465  while (ntrk<m_Ntracks) {
1466  if (ntrk<MAXREC) {
1467  totntrk = ntrk+1;
1468  m_Nhits[ntrk] = jobNhitspertrack[ntrk];
1469  m_Pt[ntrk] = jobPt[ntrk];
1470  m_P[ntrk] = jobP[ntrk];
1471  m_nhPXB[ntrk] = jobnhPXB[ntrk];
1472  m_nhPXF[ntrk] = jobnhPXF[ntrk];
1473  m_nhTIB[ntrk] = jobnhTIB[ntrk];
1474  m_nhTOB[ntrk] = jobnhTOB[ntrk];
1475  m_nhTID[ntrk] = jobnhTID[ntrk];
1476  m_nhTEC[ntrk] = jobnhTEC[ntrk];
1477  m_Eta[ntrk] = jobEta[ntrk];
1478  m_Phi[ntrk] = jobPhi[ntrk];
1479  m_Chi2n[ntrk] = jobChi2n[ntrk];
1480  m_d0[ntrk] = jobd0[ntrk];
1481  m_dz[ntrk] = jobdz[ntrk];
1482  m_wt[ntrk] = jobwt[ntrk];
1483  }//end if j<MAXREC
1484  else{
1485  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::fillEventwiseTree] Number of tracks in Eventwise tree exceeds MAXREC: "
1486  << m_Ntracks << " Skipping exceeding tracks.";
1487  ntrk = m_Ntracks+1;
1488  }
1489  ++ntrk;
1490  }//end while loop
1491  theTree->Fill();
1492  }//end loop on i - entries in the job tree
1493 
1494  int ihit = 0;
1495  for (ihit=0;ihit<hittree->GetEntries();++ihit) {
1496  hittree->GetEntry(ihit);
1497  m_angle = jobangle;
1498  m_sinTheta = jobsinTheta;
1499  m_detId = jobDetId;
1500  m_hitwt=jobHitWt;
1501  hitTree->Fill();
1502  }
1503 
1504  //clean up
1505  delete jobtree;
1506  delete hittree;
1507  delete jobfile;
1508 
1509  return totntrk;
1510 }//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 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:84
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:196
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
step
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