CMS 3D CMS Logo

HIPAlignmentAlgorithm.cc
Go to the documentation of this file.
1 #include <fstream>
2 #include <unordered_map>
3 
4 #include "TFile.h"
5 #include "TTree.h"
6 #include "TList.h"
7 #include "TRandom.h"
8 #include "TMath.h"
9 
15 
18 
35 
41 
43 
44 
45 // Constructor ----------------------------------------------------------------
47  const edm::ParameterSet& cfg
48  ) :
50  verbose(cfg.getParameter<bool>("verbosity")),
51  theMonitorConfig(cfg),
52  doTrackHitMonitoring(theMonitorConfig.fillTrackMonitoring || theMonitorConfig.fillTrackHitMonitoring),
53  defaultAlignableSpecs((Alignable*)nullptr),
54  surveyResiduals_(cfg.getUntrackedParameter<std::vector<std::string> >("surveyResiduals")),
55  theTrackHitMonitorIORootFile(nullptr),
56  theTrackMonitorTree(nullptr),
57  theHitMonitorTree(nullptr),
58  theAlignablesMonitorIORootFile(nullptr),
59  theAlignablesMonitorTree(nullptr),
60  theSurveyIORootFile(nullptr),
61  theSurveyTree(nullptr)
62 {
63  // parse parameters
64  outpath = cfg.getParameter<std::string>("outpath");
65  outfile2 = cfg.getParameter<std::string>("outfile2");
66  struefile = cfg.getParameter<std::string>("trueFile");
67  smisalignedfile = cfg.getParameter<std::string>("misalignedFile");
68  salignedfile = cfg.getParameter<std::string>("alignedFile");
69  siterationfile = cfg.getParameter<std::string>("iterationFile");
71  sparameterfile = cfg.getParameter<std::string>("parameterFile");
72  ssurveyfile = cfg.getParameter<std::string>("surveyFile");
73 
74  outfile2 =outpath+outfile2;//Alignablewise tree
75  struefile =outpath+struefile;
76  smisalignedfile=outpath+smisalignedfile;
77  salignedfile =outpath+salignedfile;
78  siterationfile =outpath+siterationfile;
79  suvarfile =outpath+suvarfile;
81  ssurveyfile =outpath+ssurveyfile;
82 
83  // parameters for APE
84  theApplyAPE = cfg.getParameter<bool>("applyAPE");
85  theAPEParameterSet = cfg.getParameter<std::vector<edm::ParameterSet> >("apeParam");
86 
87  themultiIOV = cfg.getParameter<bool>("multiIOV");
88  theIOVrangeSet = cfg.getParameter<std::vector<unsigned> >("IOVrange");
89 
90  defaultAlignableSpecs.minNHits = cfg.getParameter<int>("minimumNumberOfHits");;
91  defaultAlignableSpecs.minRelParError = cfg.getParameter<double>("minRelParameterError");
92  defaultAlignableSpecs.maxRelParError = cfg.getParameter<double>("maxRelParameterError");
93  defaultAlignableSpecs.maxHitPull = cfg.getParameter<double>("maxAllowedHitPull");
94  theApplyCutsPerComponent = cfg.getParameter<bool>("applyCutsPerComponent");
95  theCutsPerComponent = cfg.getParameter<std::vector<edm::ParameterSet> >("cutsPerComponent");
96 
97  // for collector mode (parallel processing)
98  isCollector=cfg.getParameter<bool>("collectorActive");
99  theCollectorNJobs=cfg.getParameter<int>("collectorNJobs");
100  theCollectorPath=cfg.getParameter<std::string>("collectorPath");
101 
102  if (isCollector) edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::HIPAlignmentAlgorithm" << "Collector mode";
103 
104  trackPs = cfg.getParameter<bool>("UsePreSelection");
105  theDataGroup = cfg.getParameter<int>("DataGroup");
106  trackWt = cfg.getParameter<bool>("UseReweighting");
107  Scale = cfg.getParameter<double>("Weight");
108  uniEta = trackWt && cfg.getParameter<bool>("UniformEta");
109  uniEtaFormula = cfg.getParameter<std::string>("UniformEtaFormula");
110  if (uniEtaFormula.empty()){
111  edm::LogWarning("Alignment") << "@SUB=HIPAlignmentAlgorithm::HIPAlignmentAlgorithm" << "Uniform eta formula is empty! Resetting to 1.";
112  uniEtaFormula="1";
113  }
114  theEtaFormula = std::make_unique<TFormula>(uniEtaFormula.c_str());
115  rewgtPerAli = trackWt && cfg.getParameter<bool>("ReweightPerAlignable");
116  IsCollision = cfg.getParameter<bool>("isCollision");
117  SetScanDet=cfg.getParameter<std::vector<double> >("setScanDet");
118  col_cut = cfg.getParameter<double>("CLAngleCut");
119  cos_cut = cfg.getParameter<double>("CSAngleCut");
120 
121  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::HIPAlignmentAlgorithm" << "Constructed";
122 }
123 
124 // Call at beginning of job ---------------------------------------------------
126  const edm::EventSetup& setup,
129  ){
130  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::initialize" << "Initializing...";
131 
132  alignableObjectId_ = std::make_unique<AlignableObjectId>(
134  );
135 
136  for (const auto& level: surveyResiduals_) theLevels.push_back(alignableObjectId_->stringToId(level));
137 
138  edm::ESHandle<Alignments> globalPositionRcd;
139 
140  const edm::ValidityInterval & validity = setup.get<TrackerAlignmentRcd>().validityInterval();
141  const edm::IOVSyncValue first1 = validity.first();
142  unsigned int firstrun = first1.eventID().run();
143  if (themultiIOV){
144  if (theIOVrangeSet.size()!=1){
145  bool findMatchIOV=false;
146  for (unsigned int iovl = 0; iovl < theIOVrangeSet.size(); iovl++){
147  if (firstrun == theIOVrangeSet.at(iovl)){
148  std::string iovapp = std::to_string(firstrun);
149  iovapp.append(".root");
150  iovapp.insert(0, "_");
151  salignedfile.replace(salignedfile.end()-5, salignedfile.end(), iovapp);
152  siterationfile.replace(siterationfile.end()-5, siterationfile.end(), iovapp);
153  //sparameterfile.replace(sparameterfile.end()-5, sparameterfile.end(),iovapp);
154  if (isCollector){
155  outfile2.replace(outfile2.end()-5, outfile2.end(), iovapp);
156  ssurveyfile.replace(ssurveyfile.end()-5, ssurveyfile.end(), iovapp);
157  suvarfile.replace(suvarfile.end()-5, suvarfile.end(), iovapp);
158  }
159 
160  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::initialize" << "Found the IOV file matching IOV first run " << firstrun;
161  findMatchIOV=true;
162  break;
163  }
164  }
165  if (!findMatchIOV) edm::LogError("Alignment") << "@SUB=HIPAlignmentAlgorithm::initialize" << "Didn't find the IOV file matching IOV first run " << firstrun << " from the validity interval";
166  }
167  else{
168  std::string iovapp = std::to_string(theIOVrangeSet.at(0));
169  iovapp.append(".root");
170  iovapp.insert(0, "_");
171  salignedfile.replace(salignedfile.end()-5, salignedfile.end(), iovapp);
172  siterationfile.replace(siterationfile.end()-5, siterationfile.end(), iovapp);
173  }
174  }
175 
176  // accessor Det->AlignableDet
177  theAlignableDetAccessor = std::make_unique<AlignableNavigator>(extras, tracker, muon);
178  if (extras!=nullptr) edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::initialize" << "AlignableNavigator initialized with AlignableExtras";
179 
180  // set alignmentParameterStore
182 
183  // get alignables
185 
186  // Config flags that specify different detectors
187  {
188  AlignmentParameterSelector selector(tracker, muon, extras);
189 
190  // APE parameters, clear if necessary
191  theAPEParameters.clear();
192  if (theApplyAPE){
193  for (std::vector<edm::ParameterSet>::const_iterator setiter = theAPEParameterSet.begin(); setiter != theAPEParameterSet.end(); ++setiter){
194  std::vector<Alignable*> alignables;
195 
196  selector.clear();
197  edm::ParameterSet selectorPSet = setiter->getParameter<edm::ParameterSet>("Selector");
198  std::vector<std::string> alignParams = selectorPSet.getParameter<std::vector<std::string> >("alignParams");
199  if (alignParams.size()==1 && alignParams[0] == std::string("selected")) alignables = theAlignables;
200  else{
201  selector.addSelections(selectorPSet);
202  alignables = selector.selectedAlignables();
203  }
204 
205  std::vector<double> apeSPar = setiter->getParameter<std::vector<double> >("apeSPar");
206  std::vector<double> apeRPar = setiter->getParameter<std::vector<double> >("apeRPar");
207  std::string function = setiter->getParameter<std::string>("function");
208 
209  if (apeSPar.size()!=3 || apeRPar.size()!=3)
210  throw cms::Exception("BadConfig")
211  << "apeSPar and apeRPar must have 3 values each"
212  << std::endl;
213 
214  for (std::vector<double>::const_iterator i = apeRPar.begin(); i != apeRPar.end(); ++i) apeSPar.push_back(*i);
215 
216  if (function == std::string("linear")) apeSPar.push_back(0); // c.f. note in calcAPE
217  else if (function == std::string("exponential")) apeSPar.push_back(1); // c.f. note in calcAPE
218  else if (function == std::string("step")) apeSPar.push_back(2); // c.f. note in calcAPE
219  else throw cms::Exception("BadConfig") << "APE function must be \"linear\", \"exponential\", or \"step\"." << std::endl;
220 
221  theAPEParameters.push_back(std::pair<std::vector<Alignable*>, std::vector<double> >(alignables, apeSPar));
222  }
223  }
224 
225  // Relative error per component instead of overall relative error
226  theAlignableSpecifics.clear();
228  for (std::vector<edm::ParameterSet>::const_iterator setiter = theCutsPerComponent.begin(); setiter != theCutsPerComponent.end(); ++setiter){
229  std::vector<Alignable*> alignables;
230 
231  selector.clear();
232  edm::ParameterSet selectorPSet = setiter->getParameter<edm::ParameterSet>("Selector");
233  std::vector<std::string> alignParams = selectorPSet.getParameter<std::vector<std::string> >("alignParams");
234  if (alignParams.size()==1 && alignParams[0] == std::string("selected")) alignables = theAlignables;
235  else{
236  selector.addSelections(selectorPSet);
237  alignables = selector.selectedAlignables();
238  }
239 
240  double minRelParError = setiter->getParameter<double>("minRelParError");
241  double maxRelParError = setiter->getParameter<double>("maxRelParError");
242  int minNHits = setiter->getParameter<int>("minNHits");
243  double maxHitPull = setiter->getParameter<double>("maxHitPull");
244  bool applyPixelProbCut = setiter->getParameter<bool>("applyPixelProbCut");
245  bool usePixelProbXYOrProbQ = setiter->getParameter<bool>("usePixelProbXYOrProbQ");
246  double minPixelProbXY = setiter->getParameter<double>("minPixelProbXY");
247  double maxPixelProbXY = setiter->getParameter<double>("maxPixelProbXY");
248  double minPixelProbQ = setiter->getParameter<double>("minPixelProbQ");
249  double maxPixelProbQ = setiter->getParameter<double>("maxPixelProbQ");
250  for (auto& ali : alignables){
251  HIPAlignableSpecificParameters alispecs(ali);
252  alispecs.minRelParError = minRelParError;
253  alispecs.maxRelParError = maxRelParError;
254  alispecs.minNHits = minNHits;
255  alispecs.maxHitPull = maxHitPull;
256 
257  alispecs.applyPixelProbCut = applyPixelProbCut;
258  alispecs.usePixelProbXYOrProbQ = usePixelProbXYOrProbQ;
259  alispecs.minPixelProbXY = minPixelProbXY;
260  alispecs.maxPixelProbXY = maxPixelProbXY;
261  alispecs.minPixelProbQ = minPixelProbQ;
262  alispecs.maxPixelProbQ = maxPixelProbQ;
263 
264  theAlignableSpecifics.push_back(alispecs);
265  edm::LogInfo("Alignment")
266  << "@SUB=HIPAlignmentAlgorithm::initialize"
267  << "Alignment specifics acquired for detector " << alispecs.id() << " / " << alispecs.objId()
268  << ":\n"
269  << " - minRelParError = " << alispecs.minRelParError << "\n"
270  << " - maxRelParError = " << alispecs.maxRelParError << "\n"
271  << " - minNHits = " << alispecs.minNHits << "\n"
272  << " - maxHitPull = " << alispecs.maxHitPull << "\n"
273  << " - applyPixelProbCut = " << alispecs.applyPixelProbCut << "\n"
274  << " - usePixelProbXYOrProbQ = " << alispecs.usePixelProbXYOrProbQ << "\n"
275  << " - minPixelProbXY = " << alispecs.minPixelProbXY << "\n"
276  << " - maxPixelProbXY = " << alispecs.maxPixelProbXY << "\n"
277  << " - minPixelProbQ = " << alispecs.minPixelProbQ << "\n"
278  << " - maxPixelProbQ = " << alispecs.maxPixelProbQ
279  ;
280  }
281  }
282  }
283 
284  }
285 
286 }
287 
288 // Call at new loop -------------------------------------------------------------
290  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::startNewLoop" << "Begin";
291 
292  // iterate over all alignables and attach user variables
293  for (std::vector<Alignable*>::const_iterator it=theAlignables.begin(); it!=theAlignables.end(); it++){
294  AlignmentParameters* ap = (*it)->alignmentParameters();
295  int npar=ap->numSelected();
296  HIPUserVariables* userpar = new HIPUserVariables(npar);
297  ap->setUserVariables(userpar);
298  }
299 
300  // try to read in alignment parameters from a previous iteration
301  AlignablePositions theAlignablePositionsFromFile = theIO.readAlignableAbsolutePositions(theAlignables, salignedfile.c_str(), -1, ioerr);
302  int numAlignablesFromFile = theAlignablePositionsFromFile.size();
303  if (numAlignablesFromFile==0){ // file not there: first iteration
304  // set iteration number to 1 when needed
305  if (isCollector) theIteration=0;
306  else theIteration=1;
307  edm::LogWarning("Alignment") << "@SUB=HIPAlignmentAlgorithm::startNewLoop" << "IO alignables file not found for iteration " << theIteration;
308  }
309  else{ // there have been previous iterations
310  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::startNewLoop" << "Alignables Read " << numAlignablesFromFile;
311 
312  // get iteration number from file
314  // Where is the target for this?
316 
317  // increase iteration
318  if (ioerr==0){
319  theIteration++;
320  edm::LogWarning("Alignment") << "@SUB=HIPAlignmentAlgorithm::startNewLoop" << "Iteration increased by one and is now " << theIteration;
321  }
322 
323  // now apply psotions of file from prev iteration
324  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::startNewLoop" << "Apply positions from file ...";
326  }
327 
328  edm::LogWarning("Alignment") << "@SUB=HIPAlignmentAlgorithm::startNewLoop" << "Current Iteration number: " << theIteration;
329 
330 
331  // book root trees
332  bookRoot();
333 
334  // set alignment position error
336 
337  // run collector job if we are in parallel mode
338  if (isCollector) collector();
339 
340  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::startNewLoop" << "End";
341 }
342 
343 // Call at end of job ---------------------------------------------------------
345  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm] Terminating";
346 
347  // calculating survey residuals
348  if (!theLevels.empty()){
349  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm] Using survey constraint";
350 
351  unsigned int nAlignable = theAlignables.size();
352  edm::ESHandle<TrackerTopology> tTopoHandle;
353  iSetup.get<IdealGeometryRecord>().get(tTopoHandle);
354  const TrackerTopology* const tTopo = tTopoHandle.product();
355  for (unsigned int i = 0; i < nAlignable; ++i){
356  const Alignable* ali = theAlignables[i];
358  HIPUserVariables* uservar = dynamic_cast<HIPUserVariables*>(ap->userVariables());
359  int nhit = uservar->nhit;
360 
361  // get position
362  std::pair<int, int> tl = theAlignmentParameterStore->typeAndLayer(ali, tTopo);
363  int tmp_Type = tl.first;
364  int tmp_Layer = tl.second;
365  GlobalPoint pos = ali->surface().position();
366  float tmpz = pos.z();
367  if (nhit< 1500 || (tmp_Type==5 && tmp_Layer==4 && fabs(tmpz)>90)){ // FIXME: Needs revision for hardcoded consts
368  for (unsigned int l = 0; l < theLevels.size(); ++l){
369  SurveyResidual res(*ali, theLevels[l], true);
370 
371  if (res.valid()){
372  AlgebraicSymMatrix invCov = res.inverseCovariance();
373 
374  // variable for tree
375  AlgebraicVector sensResid = res.sensorResidual();
376  m3_Id = ali->id();
377  m3_ObjId = theLevels[l];
378  m3_par[0] = sensResid[0]; m3_par[1] = sensResid[1]; m3_par[2] = sensResid[2];
379  m3_par[3] = sensResid[3]; m3_par[4] = sensResid[4]; m3_par[5] = sensResid[5];
380 
381  uservar->jtvj += invCov;
382  uservar->jtve += invCov * sensResid;
383 
384  if (theSurveyTree!=nullptr) theSurveyTree->Fill();
385  }
386  }
387  }
388  }
389  }
390 
391  // write user variables
393  // don't store userVariable in main, to save time
395 
396  // now calculate alignment corrections...
397  int ialigned=0;
398  // iterate over alignment parameters
399  for (std::vector<Alignable*>::const_iterator it=theAlignables.begin(); it!=theAlignables.end(); it++){
400  Alignable* ali=(*it);
402 
403  if (SetScanDet.at(0)!=0){
404  edm::LogWarning("Alignment") << "********Starting Scan*********";
405  edm::LogWarning("Alignment") <<"det ID="<<SetScanDet.at(0)<<", starting position="<<SetScanDet.at(1)<<", step="<<SetScanDet.at(2)<<", currentDet = "<<ali->id();
406  }
407 
408  if ((SetScanDet.at(0)!=0)&&(SetScanDet.at(0)!=1)&&(ali->id()!=SetScanDet.at(0))) continue;
409 
410  bool test = calcParameters(ali, SetScanDet.at(0), SetScanDet.at(1), SetScanDet.at(2));
411  if (test){
412  if (dynamic_cast<AlignableDetUnit*>(ali)!=nullptr){
413  std::vector<std::pair<int, SurfaceDeformation*>> pairs;
414  ali->surfaceDeformationIdPairs(pairs);
415  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::terminate" << "The alignable contains " << pairs.size() << " surface deformations";
416  }
417  else edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::terminate" << "The alignable cannot contain surface deformations";
418 
420  // set these parameters 'valid'
421  ali->alignmentParameters()->setValid(true);
422  // increase counter
423  ialigned++;
424  }
425  else par->setValid(false);
426  }
427  //end looping over alignables
428 
429  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::terminate] Aligned units: " << ialigned;
430 
431  // fill alignable wise root tree
432  fillAlignablesMonitor(iSetup);
433 
434  edm::LogWarning("Alignment")
435  << "[HIPAlignmentAlgorithm] Writing aligned parameters to file: " << theAlignables.size()
436  << ", for Iteration " << theIteration;
437 
438 
439  // write user variables
441 
442  // write new absolute positions to disk
444 
445  // write alignment parameters to disk
446  //theIO.writeAlignmentParameters(theAlignables,
447  // sparameterfile.c_str(),theIteration,false,ioerr);
448 
449  // write iteration number to file
451 
452  // write out trees and close root file
453  // Survey tree
454  if (theSurveyIORootFile!=nullptr){
455  theSurveyIORootFile->cd();
456  if (theSurveyTree!=nullptr) theSurveyTree->Write();
457  delete theSurveyTree;
458  theSurveyTree=nullptr;
459  theSurveyIORootFile->Close();
460  }
461  // Alignable-wise tree is only filled once at iteration 1
462  if (theAlignablesMonitorIORootFile!=nullptr){
464  if (theAlignablesMonitorTree!=nullptr) theAlignablesMonitorTree->Write();
466  theAlignablesMonitorTree=nullptr;
468  }
469  // Eventwise and hitwise monitoring trees
470  if (theTrackHitMonitorIORootFile!=nullptr){
472  if (theTrackMonitorTree!=nullptr){
473  theTrackMonitorTree->Write();
474  delete theTrackMonitorTree;
475  theTrackMonitorTree=nullptr;
476  }
477  if (theHitMonitorTree!=nullptr){
478  theHitMonitorTree->Write();
479  delete theHitMonitorTree;
480  theHitMonitorTree=nullptr;
481  }
483  }
484 }
485 
487  const AlignableDetOrUnitPtr& alidet,
488  const Alignable* ali,
489  const HIPAlignableSpecificParameters* alispecifics,
490  const TrajectoryStateOnSurface& tsos,
492  double hitwt
493  ){
494  static const unsigned int hitDim = 1;
495 
496  // get trajectory impact point
497  LocalPoint alvec = tsos.localPosition();
498  AlgebraicVector pos(hitDim);
499  pos[0] = alvec.x();
500 
501  // get impact point covariance
502  AlgebraicSymMatrix ipcovmat(hitDim);
503  ipcovmat[0][0] = tsos.localError().positionError().xx();
504 
505  // get hit local position and covariance
506  AlgebraicVector coor(hitDim);
507  coor[0] = hit->localPosition().x();
508 
509  AlgebraicSymMatrix covmat(hitDim);
510  covmat[0][0] = hit->localPositionError().xx();
511 
512  // add hit and impact point covariance matrices
513  covmat = covmat + ipcovmat;
514 
515  // calculate the x pull of this hit
516  double xpull = 0.;
517  if (covmat[0][0] != 0.) xpull = (pos[0] - coor[0])/sqrt(fabs(covmat[0][0]));
518 
519  // get Alignment Parameters
520  AlignmentParameters* params = ali->alignmentParameters();
521  HIPUserVariables* uservar = dynamic_cast<HIPUserVariables*>(params->userVariables());
522  uservar->datatype = theDataGroup;
523  // get derivatives
524  AlgebraicMatrix derivs2D = params->selectedDerivatives(tsos, alidet);
525  // calculate user parameters
526  int npar = derivs2D.num_row();
527  AlgebraicMatrix derivs(npar, hitDim, 0); // This is jT
528 
529  for (int ipar=0; ipar<npar; ipar++){
530  for (unsigned int idim=0; idim<hitDim; idim++){
531  derivs[ipar][idim] = derivs2D[ipar][idim];
532  }
533  }
534 
535  // invert covariance matrix
536  int ierr;
537  covmat.invert(ierr);
538  if (ierr != 0){
539  edm::LogError("Alignment") << "@SUB=HIPAlignmentAlgorithm::processHit1D" << "Cov. matrix inversion failed!";
540  return false;
541  }
542 
543  double maxHitPullThreshold = (!theApplyCutsPerComponent ? defaultAlignableSpecs.maxHitPull : alispecifics->maxHitPull);
544  bool useThisHit = (maxHitPullThreshold < 0.);
545  useThisHit |= (fabs(xpull) < maxHitPullThreshold);
546  if (!useThisHit){
547  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::processHit2D" << "Hit pull (x) " << xpull << " fails the cut " << maxHitPullThreshold;
548  return false;
549  }
550 
551  AlgebraicMatrix covtmp(covmat);
552  AlgebraicMatrix jtvjtmp(derivs * covtmp *derivs.T());
553  AlgebraicSymMatrix thisjtvj(npar);
554  AlgebraicVector thisjtve(npar);
555  thisjtvj.assign(jtvjtmp);
556  thisjtve=derivs * covmat * (pos-coor);
557 
558  AlgebraicVector hitresidual(hitDim);
559  hitresidual[0] = (pos[0] - coor[0]);
560 
561  AlgebraicMatrix hitresidualT;
562  hitresidualT = hitresidual.T();
563 
564  uservar->jtvj += hitwt*thisjtvj;
565  uservar->jtve += hitwt*thisjtve;
566  uservar->nhit++;
567 
568  //for alignable chi squared
569  float thischi2;
570  thischi2 = hitwt*(hitresidualT *covmat *hitresidual)[0];
571 
572  if (verbose && (thischi2/ static_cast<float>(uservar->nhit))>10.)
573  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::processHit1D] Added to Chi2 the number " << thischi2 << " having "
574  << uservar->nhit << " ndof"
575  << ", X-resid " << hitresidual[0]
576  << ", Cov^-1 matr (covmat):"
577  << " [0][0] = " << covmat[0][0];
578 
579  uservar->alichi2 += thischi2;
580  uservar->alindof += hitDim;
581 
582  return true;
583 }
584 
586  const AlignableDetOrUnitPtr& alidet,
587  const Alignable* ali,
588  const HIPAlignableSpecificParameters* alispecifics,
589  const TrajectoryStateOnSurface& tsos,
591  double hitwt
592  ){
593  static const unsigned int hitDim = 2;
594 
595  // get trajectory impact point
596  LocalPoint alvec = tsos.localPosition();
597  AlgebraicVector pos(hitDim);
598  pos[0] = alvec.x();
599  pos[1] = alvec.y();
600 
601  // get impact point covariance
602  AlgebraicSymMatrix ipcovmat(hitDim);
603  ipcovmat[0][0] = tsos.localError().positionError().xx();
604  ipcovmat[1][1] = tsos.localError().positionError().yy();
605  ipcovmat[0][1] = tsos.localError().positionError().xy();
606 
607  // get hit local position and covariance
608  AlgebraicVector coor(hitDim);
609  coor[0] = hit->localPosition().x();
610  coor[1] = hit->localPosition().y();
611 
612  AlgebraicSymMatrix covmat(hitDim);
613  covmat[0][0] = hit->localPositionError().xx();
614  covmat[1][1] = hit->localPositionError().yy();
615  covmat[0][1] = hit->localPositionError().xy();
616 
617  // add hit and impact point covariance matrices
618  covmat = covmat + ipcovmat;
619 
620  // calculate the x pull and y pull of this hit
621  double xpull = 0.;
622  double ypull = 0.;
623  if (covmat[0][0] != 0.) xpull = (pos[0] - coor[0])/sqrt(fabs(covmat[0][0]));
624  if (covmat[1][1] != 0.) ypull = (pos[1] - coor[1])/sqrt(fabs(covmat[1][1]));
625 
626  // get Alignment Parameters
627  AlignmentParameters* params = ali->alignmentParameters();
628  HIPUserVariables* uservar = dynamic_cast<HIPUserVariables*>(params->userVariables());
629  uservar->datatype = theDataGroup;
630  // get derivatives
631  AlgebraicMatrix derivs2D = params->selectedDerivatives(tsos, alidet);
632  // calculate user parameters
633  int npar = derivs2D.num_row();
634  AlgebraicMatrix derivs(npar, hitDim, 0); // This is jT
635 
636  for (int ipar=0; ipar<npar; ipar++){
637  for (unsigned int idim=0; idim<hitDim; idim++){
638  derivs[ipar][idim] = derivs2D[ipar][idim];
639  }
640  }
641 
642  // invert covariance matrix
643  int ierr;
644  covmat.invert(ierr);
645  if (ierr != 0){
646  edm::LogError("Alignment") << "@SUB=HIPAlignmentAlgorithm::processHit2D" << "Cov. matrix inversion failed!";
647  return false;
648  }
649 
650  double maxHitPullThreshold = (!theApplyCutsPerComponent ? defaultAlignableSpecs.maxHitPull : alispecifics->maxHitPull);
651  bool useThisHit = (maxHitPullThreshold < 0.);
652  useThisHit |= (fabs(xpull) < maxHitPullThreshold && fabs(ypull) < maxHitPullThreshold);
653  if (!useThisHit){
654  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::processHit2D" << "Hit pull (x,y) " << xpull << " , " << ypull << " fails the cut " << maxHitPullThreshold;
655  return false;
656  }
657 
658  AlgebraicMatrix covtmp(covmat);
659  AlgebraicMatrix jtvjtmp(derivs * covtmp *derivs.T());
660  AlgebraicSymMatrix thisjtvj(npar);
661  AlgebraicVector thisjtve(npar);
662  thisjtvj.assign(jtvjtmp);
663  thisjtve=derivs * covmat * (pos-coor);
664 
665  AlgebraicVector hitresidual(hitDim);
666  hitresidual[0] = (pos[0] - coor[0]);
667  hitresidual[1] = (pos[1] - coor[1]);
668 
669  AlgebraicMatrix hitresidualT;
670  hitresidualT = hitresidual.T();
671 
672  uservar->jtvj += hitwt*thisjtvj;
673  uservar->jtve += hitwt*thisjtve;
674  uservar->nhit++;
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.)
681  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::processHit2D] Added to Chi2 the number " << thischi2 << " having "
682  << uservar->nhit << " ndof"
683  << ", X-resid " << hitresidual[0]
684  << ", Y-resid " << hitresidual[1]
685  << ", Cov^-1 matr (covmat):"
686  << " [0][0] = " << covmat[0][0]
687  << " [0][1] = " << covmat[0][1]
688  << " [1][0] = " << covmat[1][0]
689  << " [1][1] = " << covmat[1][1];
690 
691  uservar->alichi2 += thischi2;
692  uservar->alindof += hitDim;
693 
694  return true;
695 }
696 
697 // Run the algorithm on trajectories and tracks -------------------------------
699  if (isCollector) return;
700 
701  TrajectoryStateCombiner tsoscomb;
702 
703  m_Ntracks=0;
704  // hit info
705  m_sinTheta =0;
706  m_angle = 0;
707  m_detId =0;
708  m_hitwt=1;
710 
711  // loop over tracks
713  for (ConstTrajTrackPairCollection::const_iterator it=tracks.begin(); it!=tracks.end(); ++it){
714  const Trajectory* traj = (*it).first;
715  const reco::Track* track = (*it).second;
716 
717  float pt = track->pt();
718  float eta = track->eta();
719  float phi = track->phi();
720  float p = track->p();
721  float chi2n = track->normalizedChi2();
722  int nhit = track->numberOfValidHits();
723  float d0 = track->d0();
724  float dz = track->dz();
725 
726  int nhpxb = track->hitPattern().numberOfValidPixelBarrelHits();
727  int nhpxf = track->hitPattern().numberOfValidPixelEndcapHits();
728  int nhtib = track->hitPattern().numberOfValidStripTIBHits();
729  int nhtob = track->hitPattern().numberOfValidStripTOBHits();
730  int nhtid = track->hitPattern().numberOfValidStripTIDHits();
731  int nhtec = track->hitPattern().numberOfValidStripTECHits();
732 
733  if (verbose) edm::LogInfo("Alignment")
734  << "New track pt,eta,phi,chi2n,hits: "
735  << pt << ","
736  << eta << ","
737  << phi << ","
738  << chi2n << ","
739  << nhit;
740 
741  double ihitwt = 1;
742  double trkwt = 1;
743  if (trackWt){
744  trkwt=Scale;
745  // Reweight by the specified eta distribution
746  if (uniEta) trkwt *= theEtaFormula->Eval(fabs(eta));
747  }
748  if (trackPs){
749  double r = gRandom->Rndm();
750  if (trkwt < r) continue;
751  }
752  else if (trackWt) ihitwt=trkwt;
753 
754  // fill track parameters in root tree
755  {
756  m_Nhits.push_back(nhit);
757  m_Pt.push_back(pt);
758  m_P.push_back(p);
759  m_Eta.push_back(eta);
760  m_Phi.push_back(phi);
761  m_Chi2n.push_back(chi2n);
762  m_nhPXB.push_back(nhpxb);
763  m_nhPXF.push_back(nhpxf);
764  m_nhTIB.push_back(nhtib);
765  m_nhTOB.push_back(nhtob);
766  m_nhTID.push_back(nhtid);
767  m_nhTEC.push_back(nhtec);
768  m_d0.push_back(d0);
769  m_dz.push_back(dz);
770  m_wt.push_back(ihitwt);
771  m_Ntracks++;
772  }
773 
774  std::vector<const TransientTrackingRecHit*> hitvec;
775  std::vector<TrajectoryStateOnSurface> tsosvec;
776 
777  // loop over measurements
778  std::vector<TrajectoryMeasurement> measurements = traj->measurements();
779  for (std::vector<TrajectoryMeasurement>::iterator im=measurements.begin(); im!=measurements.end(); ++im){
780 
781  TrajectoryMeasurement meas = *im;
782 
783  // const TransientTrackingRecHit* ttrhit = &(*meas.recHit());
784  // const TrackingRecHit *hit = ttrhit->hit();
785  const TransientTrackingRecHit* hit = &(*meas.recHit());
786 
787  if (hit->isValid() && theAlignableDetAccessor->detAndSubdetInMap(hit->geographicalId())){
788  // this is the updated state (including the current hit)
789  // TrajectoryStateOnSurface tsos=meas.updatedState();
790  // combine fwd and bwd predicted state to get state
791  // which excludes current hit
792 
794  if (eventInfo.clusterValueMap()){
795  // check from the PrescalingMap if the hit was taken.
796  // If not skip to the next TM
797  // bool hitTaken=false;
798  AlignmentClusterFlag myflag;
799 
800  int subDet = hit->geographicalId().subdetId();
801  //take the actual RecHit out of the Transient one
802  const TrackingRecHit *rechit=hit->hit();
803  if (subDet>2){ // AM: if possible use enum instead of hard-coded value
804  const std::type_info &type = typeid(*rechit);
805 
806  if (type == typeid(SiStripRecHit1D)){
807 
808  const SiStripRecHit1D* stripHit1D = dynamic_cast<const SiStripRecHit1D*>(rechit);
809  if (stripHit1D){
810  SiStripRecHit1D::ClusterRef stripclust(stripHit1D->cluster());
811  // myflag=PrescMap[stripclust];
812  myflag = (*eventInfo.clusterValueMap())[stripclust];
813  }
814  else edm::LogError("HIPAlignmentAlgorithm")
815  << "ERROR in <HIPAlignmentAlgorithm::run>: Dynamic cast of Strip RecHit failed! "
816  << "TypeId of the RecHit: " << className(*hit);
817  }//end if type = SiStripRecHit1D
818  else if (type == typeid(SiStripRecHit2D)){
819 
820  const SiStripRecHit2D* stripHit2D = dynamic_cast<const SiStripRecHit2D*>(rechit);
821  if (stripHit2D){
822  SiStripRecHit2D::ClusterRef stripclust(stripHit2D->cluster());
823  // myflag=PrescMap[stripclust];
824  myflag = (*eventInfo.clusterValueMap())[stripclust];
825  }
826  else edm::LogError("HIPAlignmentAlgorithm")
827  << "ERROR in <HIPAlignmentAlgorithm::run>: Dynamic cast of Strip RecHit failed! "
828  << "TypeId of the TTRH: " << className(*hit);
829  } //end if type == SiStripRecHit2D
830  } //end if hit from strips
831  else{
832  const SiPixelRecHit* pixelhit= dynamic_cast<const SiPixelRecHit*>(rechit);
833  if (pixelhit){
834  SiPixelClusterRefNew pixelclust(pixelhit->cluster());
835  // myflag=PrescMap[pixelclust];
836  myflag = (*eventInfo.clusterValueMap())[pixelclust];
837  }
838  else edm::LogError("HIPAlignmentAlgorithm")
839  << "ERROR in <HIPAlignmentAlgorithm::run>: Dynamic cast of Pixel RecHit failed! "
840  << "TypeId of the TTRH: " << className(*hit);
841  } //end 'else' it is a pixel hit
842  if (!myflag.isTaken()) continue;
843  }//end if Prescaled Hits
845 
846  TrajectoryStateOnSurface tsos = tsoscomb.combine(
847  meas.forwardPredictedState(),
849  );
850 
851  if (tsos.isValid()){
852  hitvec.push_back(hit);
853  tsosvec.push_back(tsos);
854  }
855 
856  } //hit valid
857  }
858 
859  // transform RecHit vector to AlignableDet vector
860  std::vector<AlignableDetOrUnitPtr> alidetvec = theAlignableDetAccessor->alignablesFromHits(hitvec);
861 
862  // get concatenated alignment parameters for list of alignables
864 
865  std::vector<TrajectoryStateOnSurface>::const_iterator itsos=tsosvec.begin();
866  std::vector<const TransientTrackingRecHit*>::const_iterator ihit=hitvec.begin();
867 
868  // loop over vectors(hit,tsos)
869  while (itsos != tsosvec.end()){
870  // get AlignableDet for this hit
871  const GeomDet* det = (*ihit)->det();
872  // int subDet= (*ihit)->geographicalId().subdetId();
873  uint32_t nhitDim = (*ihit)->dimension();
874 
875  AlignableDetOrUnitPtr alidet = theAlignableDetAccessor->alignableFromGeomDet(det);
876 
877  // get relevant Alignable
878  Alignable* ali = aap.alignableFromAlignableDet(alidet);
879 
880  if (ali!=nullptr){
881  const HIPAlignableSpecificParameters* alispecifics = findAlignableSpecs(ali);
882  const TrajectoryStateOnSurface& tsos = *itsos;
883 
884  // LocalVector v = tsos.localDirection();
885  // double proj_z = v.dot(LocalVector(0,0,1));
886 
887  //In fact, sin_theta=Abs(mom_z)
888  double mom_x = tsos.localDirection().x();
889  double mom_y = tsos.localDirection().y();
890  double mom_z = tsos.localDirection().z();
891  double sin_theta = TMath::Abs(mom_z) / sqrt(pow(mom_x, 2)+pow(mom_y, 2)+pow(mom_z, 2));
892  double angle = TMath::ASin(sin_theta);
893 
894  //Make cut on hit impact angle, reduce collision hits perpendicular to modules
895  if (IsCollision){ if (angle>col_cut)ihitwt=0; }
896  else{ if (angle<cos_cut)ihitwt=0; }
897  m_angle = angle;
898  m_sinTheta = sin_theta;
899  m_detId = ali->id();
900 
901  // Check pixel XY and Q probabilities
902  m_hasHitProb = false;
903  m_probXY=-1;
904  m_probQ=-1;
905  m_rawQualityWord=9999;
906  if ((*ihit)->hit()!=nullptr){
907  const SiPixelRecHit* pixhit = dynamic_cast<const SiPixelRecHit*>((*ihit)->hit());
908  if (pixhit!=nullptr){
909  m_hasHitProb = pixhit->hasFilledProb();
910  if (m_hasHitProb){
911  // Prob X, Y are deprecated
912  m_probXY=pixhit->probabilityXY();
913  m_probQ=pixhit->probabilityQ();
915  if (alispecifics->applyPixelProbCut){
916  bool probXYgood = (m_probXY>=alispecifics->minPixelProbXY && m_probXY<=alispecifics->maxPixelProbXY);
917  bool probQgood = (m_probQ>=alispecifics->minPixelProbQ && m_probQ<=alispecifics->maxPixelProbQ);
918  bool probXYQgood;
919  if (alispecifics->usePixelProbXYOrProbQ) probXYQgood = (probXYgood || probQgood);
920  else probXYQgood = (probXYgood && probQgood);
921  if (!probXYQgood) ihitwt=0;
922  }
923  }
924  }
925  }
926 
927  m_hitwt = ihitwt;
928  if (ihitwt!=0.){
929  bool hitProcessed=false;
930  switch (nhitDim){
931  case 1:
932  hitProcessed=processHit1D(alidet, ali, alispecifics, tsos, *ihit, ihitwt);
933  break;
934  case 2:
935  hitProcessed=processHit2D(alidet, ali, alispecifics, tsos, *ihit, ihitwt);
936  break;
937  default:
938  edm::LogError("HIPAlignmentAlgorithm")
939  << "ERROR in <HIPAlignmentAlgorithm::run>: Number of hit dimensions = "
940  << nhitDim << " is not supported!"
941  << std::endl;
942  break;
943  }
945  }
946  }
947 
948  itsos++;
949  ihit++;
950  }
951  } // end of track loop
952 
953  // fill eventwise root tree (with prescale defined in pset)
955 }
956 
957 // ----------------------------------------------------------------------------
959  int result;
960 
961  std::ifstream inIterFile(filename.c_str(), std::ios::in);
962  if (!inIterFile) {
963  edm::LogError("Alignment") << "[HIPAlignmentAlgorithm::readIterationFile] ERROR! "
964  << "Unable to open Iteration file";
965  result = -1;
966  }
967  else {
968  inIterFile >> result;
969  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::readIterationFile] "
970  << "Read last iteration number from file: " << result;
971  }
972  inIterFile.close();
973 
974  return result;
975 }
976 
977 // ----------------------------------------------------------------------------
979  std::ofstream outIterFile((filename.c_str()), std::ios::out);
980  if (!outIterFile) edm::LogError("Alignment")
981  << "[HIPAlignmentAlgorithm::writeIterationFile] ERROR: Unable to write Iteration file";
982  else{
983  outIterFile << iter;
984  edm::LogWarning("Alignment") <<"[HIPAlignmentAlgorithm::writeIterationFile] writing iteration number to file: " << iter;
985  }
986  outIterFile.close();
987 }
988 
989 // ----------------------------------------------------------------------------
990 // set alignment position error
992  // Check if user wants to override APE
993  if (!theApplyAPE){
994  edm::LogInfo("Alignment") <<"[HIPAlignmentAlgorithm::setAlignmentPositionError] No APE applied";
995  return; // NO APE APPLIED
996  }
997 
998  edm::LogInfo("Alignment") <<"[HIPAlignmentAlgorithm::setAlignmentPositionError] Apply APE!";
999 
1000  double apeSPar[3], apeRPar[3];
1001  for (std::vector<std::pair<std::vector<Alignable*>, std::vector<double> > >::const_iterator alipars = theAPEParameters.begin(); alipars != theAPEParameters.end(); ++alipars) {
1002  const std::vector<Alignable*> &alignables = alipars->first;
1003  const std::vector<double> &pars = alipars->second;
1004 
1005  apeSPar[0] = pars[0];
1006  apeSPar[1] = pars[1];
1007  apeSPar[2] = pars[2];
1008  apeRPar[0] = pars[3];
1009  apeRPar[1] = pars[4];
1010  apeRPar[2] = pars[5];
1011 
1012  int function = pars[6];
1013 
1014  // Printout for debug
1015  printf("APE: %u alignables\n", (unsigned int)alignables.size());
1016  for (int i=0; i<21; ++i) {
1017  double apelinstest=calcAPE(apeSPar, i, 0);
1018  double apeexpstest=calcAPE(apeSPar, i, 1);
1019  double apestepstest=calcAPE(apeSPar, i, 2);
1020  double apelinrtest=calcAPE(apeRPar, i, 0);
1021  double apeexprtest=calcAPE(apeRPar, i, 1);
1022  double apesteprtest=calcAPE(apeRPar, i, 2);
1023  printf("APE: iter slin sexp sstep rlin rexp rstep: %5d %12.5f %12.5f %12.5f %12.5f %12.5f %12.5f \n",
1024  i, apelinstest, apeexpstest, apestepstest, apelinrtest, apeexprtest, apesteprtest);
1025  }
1026 
1027  // set APE
1028  double apeshift = calcAPE(apeSPar, theIteration, function);
1029  double aperot = calcAPE(apeRPar, theIteration, function);
1030  theAlignmentParameterStore->setAlignmentPositionError(alignables, apeshift, aperot);
1031  }
1032 }
1033 
1034 // ----------------------------------------------------------------------------
1035 // calculate APE
1036 double HIPAlignmentAlgorithm::calcAPE(double* par, int iter, int function){
1037  double diter=(double)iter;
1038  if (function == 0) return std::max(par[1], par[0]+((par[1]-par[0])/par[2])*diter);
1039  else if (function == 1) return std::max(0., par[0]*(exp(-pow(diter, par[1])/par[2])));
1040  else if (function == 2){
1041  int ipar2 = (int)par[2];
1042  int step = iter/ipar2;
1043  double dstep = (double)step;
1044  return std::max(0., par[0] - par[1]*dstep);
1045  }
1046  else assert(false); // should have been caught in the constructor
1047 }
1048 
1049 // ----------------------------------------------------------------------------
1050 // book root trees
1052  // create ROOT files
1054  theTrackHitMonitorIORootFile = TFile::Open(theMonitorConfig.outfile.c_str(), "update");
1056  // book event-wise ROOT Tree
1058  TString tname=Form("T1_%i", theIteration);
1059  theTrackMonitorTree = new TTree(tname, "Eventwise tree");
1060  //theTrackMonitorTree->Branch("Run", &m_Run, "Run/I");
1061  //theTrackMonitorTree->Branch("Event", &m_Event, "Event/I");
1062  theTrackMonitorTree->Branch("Ntracks", &m_Ntracks);
1063  theTrackMonitorTree->Branch("Nhits", &m_Nhits);
1064  theTrackMonitorTree->Branch("DataType", &m_datatype);
1065  theTrackMonitorTree->Branch("nhPXB", &m_nhPXB);
1066  theTrackMonitorTree->Branch("nhPXF", &m_nhPXF);
1067  theTrackMonitorTree->Branch("nhTIB", &m_nhTIB);
1068  theTrackMonitorTree->Branch("nhTOB", &m_nhTOB);
1069  theTrackMonitorTree->Branch("nhTID", &m_nhTID);
1070  theTrackMonitorTree->Branch("nhTEC", &m_nhTEC);
1071  theTrackMonitorTree->Branch("Pt", &m_Pt);
1072  theTrackMonitorTree->Branch("P", &m_P);
1073  theTrackMonitorTree->Branch("Eta", &m_Eta);
1074  theTrackMonitorTree->Branch("Phi", &m_Phi);
1075  theTrackMonitorTree->Branch("Chi2n", &m_Chi2n);
1076  theTrackMonitorTree->Branch("d0", &m_d0);
1077  theTrackMonitorTree->Branch("dz", &m_dz);
1078  theTrackMonitorTree->Branch("wt", &m_wt);
1079  }
1080  // book hit-wise ROOT Tree
1082  TString tname_hit=Form("T1_hit_%i", theIteration);
1083  theHitMonitorTree = new TTree(tname_hit, "Hitwise tree");
1084  theHitMonitorTree->Branch("Id", &m_detId, "Id/i");
1085  theHitMonitorTree->Branch("DataType", &m_datatype);
1086  theHitMonitorTree->Branch("sinTheta", &m_sinTheta);
1087  theHitMonitorTree->Branch("impactAngle", &m_angle);
1088  theHitMonitorTree->Branch("wt", &m_hitwt);
1089  theHitMonitorTree->Branch("probPresent", &m_hasHitProb);
1090  theHitMonitorTree->Branch("probXY", &m_probXY);
1091  theHitMonitorTree->Branch("probQ", &m_probQ);
1092  theHitMonitorTree->Branch("qualityWord", &m_rawQualityWord);
1093  }
1094  }
1095 
1096  // book alignable-wise ROOT Tree
1097  if (isCollector){
1098  TString tname=Form("T2_%i", theIteration);
1099  theAlignablesMonitorIORootFile = TFile::Open(outfile2.c_str(), "update");
1101  theAlignablesMonitorTree = new TTree(tname, "Alignablewise tree");
1102  theAlignablesMonitorTree->Branch("Id", &m2_Id, "Id/i");
1103  theAlignablesMonitorTree->Branch("ObjId", &m2_ObjId, "ObjId/I");
1104  theAlignablesMonitorTree->Branch("Nhit", &m2_Nhit);
1105  theAlignablesMonitorTree->Branch("DataType", &m2_datatype);
1106  theAlignablesMonitorTree->Branch("Type", &m2_Type);
1107  theAlignablesMonitorTree->Branch("Layer", &m2_Layer);
1108  theAlignablesMonitorTree->Branch("Xpos", &m2_Xpos);
1109  theAlignablesMonitorTree->Branch("Ypos", &m2_Ypos);
1110  theAlignablesMonitorTree->Branch("Zpos", &m2_Zpos);
1111  theAlignablesMonitorTree->Branch("DeformationsType", &m2_dtype, "DeformationsType/I");
1112  theAlignablesMonitorTree->Branch("NumDeformations", &m2_nsurfdef);
1113  theAlignablesMonitorTree->Branch("Deformations", &m2_surfDef);
1114  }
1115 
1116  // book survey-wise ROOT Tree only if survey is enabled
1117  if (!theLevels.empty()){
1118  TString tname=Form("T3_%i", theIteration);
1119  theSurveyIORootFile = TFile::Open(ssurveyfile.c_str(), "update");
1120  theSurveyIORootFile->cd();
1121  theSurveyTree = new TTree(tname, "Survey Tree");
1122  theSurveyTree->Branch("Id", &m3_Id, "Id/i");
1123  theSurveyTree->Branch("ObjId", &m3_ObjId, "ObjId/I");
1124  theSurveyTree->Branch("Par", &m3_par, "Par[6]/F");
1125  edm::LogInfo("Alignment") << "[HIPAlignmentAlgorithm::bookRoot] Survey trees booked.";
1126  }
1127  edm::LogInfo("Alignment") << "[HIPAlignmentAlgorithm::bookRoot] Root trees booked.";
1128 }
1129 
1130 // ----------------------------------------------------------------------------
1131 // fill alignable-wise root tree
1133  if (theAlignablesMonitorIORootFile==(TFile*)nullptr) return;
1134  using std::setw;
1136 
1137  int naligned=0;
1138 
1139  //Retrieve tracker topology from geometry
1140  edm::ESHandle<TrackerTopology> tTopoHandle;
1141  // iSetup.get<IdealGeometryRecord>().get(tTopoHandle);
1142  iSetup.get<TrackerTopologyRcd>().get(tTopoHandle);
1143 
1144  const TrackerTopology* const tTopo = tTopoHandle.product();
1145 
1146  for (std::vector<Alignable*>::const_iterator it=theAlignables.begin(); it!=theAlignables.end(); ++it){
1147  Alignable* ali = (*it);
1149 
1150  // consider only those parameters classified as 'valid'
1151  if (dap->isValid()){
1152  // get number of hits from user variable
1153  HIPUserVariables* uservar = dynamic_cast<HIPUserVariables*>(dap->userVariables());
1154  m2_Nhit = uservar->nhit;
1155  m2_datatype = uservar->datatype;
1156 
1157  // get type/layer
1158  std::pair<int, int> tl = theAlignmentParameterStore->typeAndLayer(ali, tTopo);
1159  m2_Type = tl.first;
1160  m2_Layer = tl.second;
1161 
1162  // get identifier (as for IO)
1163  m2_Id = ali->id();
1164  m2_ObjId = ali->alignableObjectId();
1165 
1166  // get position
1167  GlobalPoint pos = ali->surface().position();
1168  m2_Xpos = pos.x();
1169  m2_Ypos = pos.y();
1170  m2_Zpos = pos.z();
1171 
1172  m2_surfDef.clear();
1173  {
1174  std::vector<std::pair<int, SurfaceDeformation*> > dali_id_pairs;
1175  SurfaceDeformation* dali_obj=nullptr;
1177  std::vector<double> dali;
1178  if (1 == ali->surfaceDeformationIdPairs(dali_id_pairs)){
1179  dali_obj = dali_id_pairs[0].second;
1180  dali = dali_obj->parameters();
1181  dtype = (SurfaceDeformationFactory::Type)dali_obj->type();
1182  }
1183  for (auto& dit : dali) m2_surfDef.push_back((float)dit);
1184  m2_dtype = dtype;
1185  m2_nsurfdef = m2_surfDef.size();
1186  }
1187 
1188  if (verbose){
1189  AlgebraicVector pars = dap->parameters();
1190  edm::LogVerbatim("Alignment")
1191  << "------------------------------------------------------------------------\n"
1192  << " ALIGNABLE: " << setw(6) << naligned
1193  << '\n'
1194  << "hits: " << setw(4) << m2_Nhit
1195  << " type: " << setw(4) << m2_Type
1196  << " layer: " << setw(4) << m2_Layer
1197  << " id: " << setw(4) << m2_Id
1198  << " objId: " << setw(4) << m2_ObjId
1199  << '\n'
1200  << std::fixed << std::setprecision(5)
1201  << "x,y,z: "
1202  << setw(12) << m2_Xpos
1203  << setw(12) << m2_Ypos
1204  << setw(12) << m2_Zpos
1205  << "\nDeformations type, nDeformations: "
1206  << setw(12) << m2_dtype
1207  << setw(12) << m2_nsurfdef
1208  << '\n'
1209  << "params: "
1210  << setw(12) << pars[0]
1211  << setw(12) << pars[1]
1212  << setw(12) << pars[2]
1213  << setw(12) << pars[3]
1214  << setw(12) << pars[4]
1215  << setw(12) << pars[5];
1216  }
1217 
1218  naligned++;
1219  if (theAlignablesMonitorTree!=nullptr) theAlignablesMonitorTree->Fill();
1220  }
1221  }
1222 }
1223 
1224 // ----------------------------------------------------------------------------
1225 bool HIPAlignmentAlgorithm::calcParameters(Alignable* ali, int setDet, double start, double step){
1226  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::calcParameters" << "Begin: Processing detector " << ali->id();
1227 
1228  // Alignment parameters
1230  const HIPAlignableSpecificParameters* alispecifics = findAlignableSpecs(ali);
1231  // access user variables
1232  HIPUserVariables* uservar = dynamic_cast<HIPUserVariables*>(par->userVariables());
1233  int nhit = uservar->nhit;
1234  // The following variable is needed for the extended 1D/2D hit fix using
1235  // matrix shrinkage and expansion
1236  // int hitdim = uservar->hitdim;
1237 
1238  // Test nhits
1239  int minHitThreshold = (!theApplyCutsPerComponent ? defaultAlignableSpecs.minNHits : alispecifics->minNHits);
1240  if (!isCollector) minHitThreshold=1;
1241  if (setDet==0 && nhit<minHitThreshold){
1242  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::calcParameters" << "Skipping detector " << ali->id() << " because number of hits = " << nhit << " <= " << minHitThreshold;
1243  par->setValid(false);
1244  return false;
1245  }
1246 
1247  AlgebraicSymMatrix jtvj = uservar->jtvj;
1248  AlgebraicVector jtve = uservar->jtve;
1249 
1250  // these are the alignment corrections+covariance (for selected params)
1251  int npar = jtve.num_row();
1252  AlgebraicVector params(npar);
1253  AlgebraicVector paramerr(npar);
1254  AlgebraicSymMatrix cov(npar);
1255 
1256  // errors of parameters
1257  if (isCollector){
1258  if (setDet==0){
1259  int ierr;
1260  AlgebraicSymMatrix jtvjinv = jtvj.inverse(ierr);
1261  if (ierr!=0){
1262  edm::LogError("Alignment") << "@SUB=HIPAlignmentAlgorithm::calcParameters" << "Matrix inversion failed!";
1263  return false;
1264  }
1265  params = -(jtvjinv * jtve);
1266  cov = jtvjinv;
1267 
1268  double minRelErrThreshold = (!theApplyCutsPerComponent ? defaultAlignableSpecs.minRelParError : alispecifics->minRelParError);
1269  double maxRelErrThreshold = (!theApplyCutsPerComponent ? defaultAlignableSpecs.maxRelParError : alispecifics->maxRelParError);
1270  for (int i=0; i<npar; i++){
1271  double relerr=0;
1272  if (fabs(cov[i][i])>0.) paramerr[i] = sqrt(fabs(cov[i][i]));
1273  else paramerr[i] = params[i];
1274  if (params[i]!=0.) relerr = fabs(paramerr[i]/params[i]);
1275  if ((maxRelErrThreshold>=0. && relerr>maxRelErrThreshold) || relerr<minRelErrThreshold){
1276  edm::LogWarning("Alignment")
1277  << "@SUB=HIPAlignmentAlgorithm::calcParameters" << "RelError = " << relerr
1278  << " > " << maxRelErrThreshold << " or < " << minRelErrThreshold
1279  << ". Setting param = paramerr = 0 for component " << i;
1280  params[i]=0;
1281  paramerr[i]=0;
1282  }
1283  }
1284  }
1285  else{
1286  if (params.num_row()!=1){
1287  edm::LogError("Alignment") << "@SUB=HIPAlignmentAlgorithm::calcParameters" << "For scanning, please only turn on one parameter! check common_cff_py.txt";
1288  return false;
1289  }
1290  if (theIteration==1) params[0] = start;
1291  else params[0]=step;
1292  edm::LogWarning("Alignment") << "@SUB=HIPAlignmentAlgorithm::calcParameters" << "Parameters = " << params;
1293  }
1294  }
1295 
1296  uservar->alipar=params;
1297  uservar->alierr=paramerr;
1298 
1299  AlignmentParameters* parnew = par->cloneFromSelected(params, cov);
1300  ali->setAlignmentParameters(parnew);
1301  parnew->setValid(true);
1302 
1303  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::calcParameters" << "End: Processing detector " << ali->id();
1304 
1305  return true;
1306 }
1307 
1308 //-----------------------------------------------------------------------------
1310  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::collector" << "Called for iteration " << theIteration;
1311 
1312  std::vector<std::string> monitorFileList;
1313  HIPUserVariablesIORoot HIPIO;
1314 
1315  typedef int pawt_t;
1316  std::unordered_map<Alignable*, std::unordered_map<int, pawt_t> > ali_datatypecountpair_map;
1317  if (rewgtPerAli){
1318  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::collector" << "Per-alignable reweighting is turned on. Iterating over the parallel jobs to sum number of hits per alignable for each data type.";
1319  // Counting step for per-alignable reweighting
1320  for (int ijob=1; ijob<=theCollectorNJobs; ijob++){
1321  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::collector" << "Pre-reading uservar for job " << ijob;
1322 
1323  std::string str = std::to_string(ijob);
1324  std::string uvfile = theCollectorPath+"/job"+str+"/"+suvarfilecore;
1325 
1326  std::vector<AlignmentUserVariables*> uvarvec = HIPIO.readHIPUserVariables(theAlignables, uvfile.c_str(), theIteration, ioerr);
1327  if (uvarvec.size()!=theAlignables.size()) edm::LogWarning("Alignment")
1328  << "@SUB=HIPAlignmentAlgorithm::collector"
1329  << "Number of alignables = " << theAlignables.size() << " is not the same as number of user variables = " << uvarvec.size()
1330  << ". A mismatch might occur!";
1331  if (ioerr!=0){
1332  edm::LogError("Alignment") << "@SUB=HIPAlignmentAlgorithm::collector" << "Could not read user variable files for job " << ijob << " in iteration " << theIteration;
1333  continue;
1334  }
1335  std::vector<AlignmentUserVariables*>::const_iterator iuvar=uvarvec.begin(); // This vector should have 1-to-1 correspondence with the alignables vector
1336  for (std::vector<Alignable*>::const_iterator it=theAlignables.begin(); it!=theAlignables.end(); ++it){
1337  Alignable* ali = *it; // Need this pointer for the key of the unordered map
1338  // No need for the user variables already attached to the alignables
1339  // Just count from what you read.
1340  HIPUserVariables* uvar = dynamic_cast<HIPUserVariables*>(*iuvar);
1341  if (uvar!=nullptr){
1342  int alijobdtype = uvar->datatype;
1343  pawt_t alijobnhits = uvar->nhit;
1344  if (ali_datatypecountpair_map.find(ali)==ali_datatypecountpair_map.end()){ // This is a new alignable
1345  std::unordered_map<int, pawt_t> newmap;
1346  ali_datatypecountpair_map[ali] = newmap;
1347  ali_datatypecountpair_map[ali][alijobdtype] = alijobnhits;
1348  }
1349  else{ // Alignable already exists in the map
1350  std::unordered_map<int, pawt_t>& theMap = ali_datatypecountpair_map[ali];
1351  if (theMap.find(alijobdtype)==theMap.end()) theMap[alijobdtype]=alijobnhits;
1352  else theMap[alijobdtype] += alijobnhits;
1353  }
1354  delete uvar; // Delete new user variables as they are added
1355  }
1356  iuvar++;
1357  } // End loop over alignables
1358  } // End loop over subjobs
1359  }
1360 
1361  for (int ijob=1; ijob<=theCollectorNJobs; ijob++){
1362  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::collector" << "Reading uservar for job " << ijob;
1363 
1364  std::string str = std::to_string(ijob);
1365  std::string uvfile = theCollectorPath+"/job"+str+"/"+suvarfilecore;
1366 
1367  std::vector<AlignmentUserVariables*> uvarvec = HIPIO.readHIPUserVariables(theAlignables, uvfile.c_str(), theIteration, ioerr);
1368  if (uvarvec.size()!=theAlignables.size()) edm::LogWarning("Alignment")
1369  << "@SUB=HIPAlignmentAlgorithm::collector"
1370  << "Number of alignables = " << theAlignables.size() << " is not the same as number of user variables = " << uvarvec.size()
1371  << ". A mismatch might occur!";
1372 
1373  if (ioerr!=0){
1374  edm::LogError("Alignment") << "@SUB=HIPAlignmentAlgorithm::collector" << "Could not read user variable files for job " << ijob << " in iteration " << theIteration;
1375  continue;
1376  }
1377 
1378  // add
1379  std::vector<AlignmentUserVariables*> uvarvecadd;
1380  std::vector<AlignmentUserVariables*>::const_iterator iuvarnew=uvarvec.begin();
1381  for (std::vector<Alignable*>::const_iterator it=theAlignables.begin(); it!=theAlignables.end(); ++it){
1382  Alignable* ali = *it;
1384 
1385  HIPUserVariables* uvarold = dynamic_cast<HIPUserVariables*>(ap->userVariables());
1386  HIPUserVariables* uvarnew = dynamic_cast<HIPUserVariables*>(*iuvarnew);
1387 
1388  HIPUserVariables* uvar = uvarold->clone();
1389  uvar->datatype=theDataGroup; // Set the data type of alignable to that specified for the collector job (-2 by default)
1390 
1391  if (uvarnew!=nullptr){
1392  double peraliwgt=1;
1393  if (rewgtPerAli){
1394  int alijobdtype = uvarnew->datatype;
1395  if (
1396  ali_datatypecountpair_map.find(ali)!=ali_datatypecountpair_map.end()
1397  &&
1398  ali_datatypecountpair_map[ali].find(alijobdtype)!=ali_datatypecountpair_map[ali].end()
1399  ){
1400  peraliwgt = ali_datatypecountpair_map[ali][alijobdtype];
1401  unsigned int nNonZeroTypes=0;
1402  pawt_t sumwgts=0;
1403  for (auto it=ali_datatypecountpair_map[ali].cbegin(); it!=ali_datatypecountpair_map[ali].cend(); ++it){
1404  sumwgts+=it->second;
1405  if (it->second!=pawt_t(0)) nNonZeroTypes++;
1406  }
1407  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::collector"
1408  << "Reweighting detector " << ali->id() << " / " << ali->alignableObjectId()
1409  << " for data type " << alijobdtype << " by " << sumwgts << "/" << peraliwgt << "/" << nNonZeroTypes;
1410  peraliwgt=((nNonZeroTypes==0 || peraliwgt==double(0)) ? double(1) : double((double(sumwgts))/peraliwgt/(double(nNonZeroTypes))));
1411  }
1412  else if (ali_datatypecountpair_map.find(ali)!=ali_datatypecountpair_map.end())
1413  edm::LogError("Alignment") << "@SUB=HIPAlignmentAlgorithm::collector"
1414  << "Could not find data type " << alijobdtype << " for detector " << ali->id() << " / " << ali->alignableObjectId();
1415  else
1416  edm::LogError("Alignment") << "@SUB=HIPAlignmentAlgorithm::collector"
1417  << "Could not find detector " << ali->id() << " / " << ali->alignableObjectId()
1418  << " in the map ali_datatypecountpair_map";
1419  }
1420 
1421  uvar->nhit = (uvarold->nhit) + (uvarnew->nhit);
1422  uvar->jtvj = (uvarold->jtvj) + peraliwgt*(uvarnew->jtvj);
1423  uvar->jtve = (uvarold->jtve) + peraliwgt*(uvarnew->jtve);
1424  uvar->alichi2 = (uvarold->alichi2) + peraliwgt*(uvarnew->alichi2);
1425  uvar->alindof = (uvarold->alindof) + (uvarnew->alindof);
1426 
1427  delete uvarnew; // Delete new user variables as they are added
1428  }
1429 
1430  uvarvecadd.push_back(uvar);
1431  iuvarnew++;
1432  }
1433 
1435 
1436  // fill Eventwise Tree
1437  if (doTrackHitMonitoring){
1438  uvfile = theCollectorPath+"/job"+str+"/"+theMonitorConfig.outfilecore;
1439  monitorFileList.push_back(uvfile);
1440  }
1441  } // end loop on jobs
1442 
1443  // Collect monitor (eventwise and hitwise) trees
1444  if (doTrackHitMonitoring) collectMonitorTrees(monitorFileList);
1445 
1446 }
1447 
1448 //------------------------------------------------------------------------------------
1449 void HIPAlignmentAlgorithm::collectMonitorTrees(const std::vector<std::string>& filenames){
1450  if (!doTrackHitMonitoring) return;
1451  if (!isCollector) throw cms::Exception("LogicError")
1452  << "[HIPAlignmentAlgorithm::collectMonitorTrees] Called in non-collector mode."
1453  << std::endl;
1454 
1455  TString theTrackMonitorTreeName=Form("T1_%i", theIteration);
1456  TString theHitMonitorTreeName=Form("T1_hit_%i", theIteration);
1457 
1458  std::vector<TFile*> finputlist;
1459  TList* eventtrees = new TList;
1460  TList* hittrees = new TList;
1461  for (std::string const& filename : filenames){
1462  TFile* finput = TFile::Open(filename.c_str(), "read");
1463  if (finput!=nullptr){
1464  TTree* tmptree;
1466  tmptree=nullptr;
1467  tmptree = (TTree*)finput->Get(theTrackMonitorTreeName);
1468  if (tmptree!=nullptr) eventtrees->Add(tmptree);
1469  }
1471  tmptree=nullptr;
1472  tmptree = (TTree*)finput->Get(theHitMonitorTreeName);
1473  if (tmptree!=nullptr) hittrees->Add((TTree*)finput->Get(theHitMonitorTreeName));
1474  }
1475  finputlist.push_back(finput);
1476  }
1477  }
1478 
1479  if (theTrackHitMonitorIORootFile!=nullptr){ // This should never happen
1480  edm::LogError("Alignment") << "@SUB=HIPAlignmentAlgorithm::collectMonitorTrees"
1481  << "Monitor file is already open while it is not supposed to be!";
1482  delete theTrackMonitorTree; theTrackMonitorTree=nullptr;
1483  delete theHitMonitorTree; theHitMonitorTree=nullptr;
1485  }
1486  theTrackHitMonitorIORootFile = TFile::Open(theMonitorConfig.outfile.c_str(), "update");
1488  if (eventtrees->GetSize()>0) theTrackMonitorTree = TTree::MergeTrees(eventtrees);
1489  if (hittrees->GetSize()>0) theHitMonitorTree = TTree::MergeTrees(hittrees);
1490  // Leave it to HIPAlignmentAlgorithm::terminate to write the trees and close theTrackHitMonitorIORootFile
1491 
1492  delete hittrees;
1493  delete eventtrees;
1494  for (TFile*& finput : finputlist) finput->Close();
1495 
1496  // Rename the trees to standard names
1497  if (theTrackMonitorTree!=nullptr) theTrackMonitorTree->SetName(theTrackMonitorTreeName);
1498  if (theHitMonitorTree!=nullptr) theHitMonitorTree->SetName(theHitMonitorTreeName);
1499 }
1500 
1501 //-----------------------------------------------------------------------------------
1503  if (ali!=nullptr){
1504  for (std::vector<HIPAlignableSpecificParameters>::iterator it=theAlignableSpecifics.begin(); it!=theAlignableSpecifics.end(); it++){
1505  if (it->matchAlignable(ali)) return &(*it);
1506  }
1507  edm::LogInfo("Alignment") << "[HIPAlignmentAlgorithm::findAlignableSpecs] Alignment object with id " << ali->id() << " / " << ali->alignableObjectId() << " could not be found. Returning default.";
1508  }
1509  return &defaultAlignableSpecs;
1510 }
RunNumber_t run() const
Definition: EventID.h:39
ClusterRef cluster() const
Definition: start.py:1
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:615
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:189
std::vector< float > m_Phi
float xx() const
Definition: LocalError.h:24
bool hasFilledProb() const
std::vector< HIPAlignableSpecificParameters > theAlignableSpecifics
HIPAlignableSpecificParameters defaultAlignableSpecs
virtual int surfaceDeformationIdPairs(std::vector< std::pair< int, SurfaceDeformation * > > &) const =0
ConstRecHitPointer const & recHit() const
double d0() const
dxy parameter in perigee convention (d0 = -dxy)
Definition: TrackBase.h:597
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:561
static AlignableObjectId commonObjectIdProvider(const AlignableObjectId &, const AlignableObjectId &)
virtual std::vector< double > parameters() const =0
parameters - interpretation left to the concrete implementation
TSOS combine(const TSOS &pTsos1, const TSOS &pTsos2) const
virtual AlignmentParameters * cloneFromSelected(const AlgebraicVector &par, const AlgebraicSymMatrix &cov) const =0
HIPUserVariables * clone(void) const override
void setAlignmentPositionError(const align::Alignables &alivec, double valshift, double valrot)
Set Alignment position error.
LocalVector localDirection() const
std::vector< int > m_nhTEC
HIPAlignableSpecificParameters * findAlignableSpecs(const Alignable *ali)
void run(const edm::EventSetup &setup, const EventInfo &eventInfo) override
Run the algorithm.
static char const * tname
Definition: GTSchema.h:13
void initialize(const edm::EventSetup &setup, AlignableTracker *tracker, AlignableMuon *muon, AlignableExtras *extras, AlignmentParameterStore *store) override
Call at beginning of job.
std::vector< int > m_nhTIB
align::StructureType m2_ObjId
std::vector< float > m_wt
T y() const
Definition: PV3DBase.h:63
AlgebraicVector alipar
def setup(process, global_tag, zero_tesla=False)
Definition: GeneralSetup.py:1
virtual int type() const =0
specific type, i.e. SurfaceDeformationFactory::Type
double phi() const
azimuthal angle of momentum vector
Definition: TrackBase.h:645
void writeIterationFile(std::string filename, int iter)
void applyParameters(void)
Obsolete: Use AlignableNavigator::alignableDetFromDetId and alignableFromAlignableDet.
AlgebraicVector jtve
#define nullptr
Alignable * alignableFromAlignableDet(const AlignableDetOrUnitPtr &adet) const
Get relevant Alignable from AlignableDet.
void applyAlignableAbsolutePositions(const align::Alignables &alis, const AlignablePositions &newpos, int &ierr)
apply absolute positions to alignables
std::vector< float > m_Eta
LocalError positionError() const
int numberOfValidStripTOBHits() const
Definition: HitPattern.h:868
AlignmentParameters * alignmentParameters() const
Get the AlignmentParameters.
Definition: Alignable.h:61
Definition: Electron.h:4
std::unique_ptr< AlignableNavigator > theAlignableDetAccessor
const ConstTrajTrackPairCollection & trajTrackPairs() const
define event information passed to algorithms
std::vector< unsigned > theIOVrangeSet
void writeHIPUserVariables(const Alignables &alivec, const char *filename, int iter, bool validCheck, int &ierr)
std::vector< float > m_d0
bool calcParameters(Alignable *ali, int setDet, double start, double step)
std::vector< float > m_Pt
const bool fillTrackHitMonitoring
AlgebraicSymMatrix jtvj
std::vector< std::pair< std::vector< Alignable * >, std::vector< double > > > theAPEParameters
const AlgebraicVector & parameters(void) const
Get alignment parameters.
std::vector< int > m_Nhits
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:651
int numberOfValidPixelBarrelHits() const
Definition: HitPattern.h:843
virtual StructureType alignableObjectId() const =0
Return the alignable type identifier.
std::vector< AlignmentUserVariables * > readHIPUserVariables(const Alignables &alivec, const char *filename, int iter, int &ierr)
std::vector< float > m_Chi2n
void setAlignmentParameters(AlignmentParameters *dap)
Set the AlignmentParameters.
Definition: Alignable.cc:129
CLHEP::HepMatrix AlgebraicMatrix
HIPAlignmentAlgorithm(const edm::ParameterSet &cfg)
Constructor.
std::vector< edm::ParameterSet > theCutsPerComponent
float yy() const
Definition: LocalError.h:26
void setValid(bool v)
Set validity flag.
std::vector< float > m_P
AlgebraicVector alierr
T sqrt(T t)
Definition: SSEVec.h:18
double pt() const
track transverse momentum
Definition: TrackBase.h:621
T z() const
Definition: PV3DBase.h:64
std::vector< float > m_dz
std::vector< int > m_nhTID
T Abs(T a)
Definition: MathUtil.h:49
int numberOfValidStripTIDHits() const
Definition: HitPattern.h:863
ClusterRef cluster() const
int readIterationFile(std::string filename)
unsigned short numberOfValidHits() const
number of valid hits found
Definition: TrackBase.h:820
int numberOfValidStripTECHits() const
Definition: HitPattern.h:873
std::vector< double > SetScanDet
const LocalTrajectoryError & localError() const
virtual LocalPoint localPosition() const =0
int subdetId() const
get the contents of the subdetector field (not cast into any detector&#39;s numbering enum) ...
Definition: DetId.h:37
const bool fillTrackMonitoring
const AlignableSurface & surface() const
Return the Surface (global position and orientation) of the object.
Definition: Alignable.h:135
TrajectoryStateOnSurface const & forwardPredictedState() const
Access to forward predicted state (from fitter or builder)
void collectMonitorTrees(const std::vector< std::string > &filenames)
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:609
double calcAPE(double *par, int iter, int function)
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:446
const std::string outfilecore
ClusterRef cluster() const
Definition: SiPixelRecHit.h:49
const T & get() const
Definition: EventSetup.h:55
CompositeAlignmentParameters selectParameters(const std::vector< AlignableDet * > &alignabledets) const
AlgebraicSymMatrix inverseCovariance() const
Get inverse of survey covariance wrt given structure type in constructor.
bool isValid() const
std::unique_ptr< AlignableObjectId > alignableObjectId_
int numberOfValidStripTIBHits() const
Definition: HitPattern.h:858
std::vector< edm::ParameterSet > theAPEParameterSet
align::StructureType m3_ObjId
std::unique_ptr< TFormula > theEtaFormula
int numberOfValidPixelEndcapHits() const
Definition: HitPattern.h:848
std::vector< int > m_nhPXF
std::string outfile
virtual void terminate()
Called at end of job (must be implemented in derived class)
AlgebraicVector sensorResidual() const
std::vector< float > m2_surfDef
const AliClusterValueMap * clusterValueMap() const
HIPMonitorConfig theMonitorConfig
float probabilityXY() const
Definition: SiPixelRecHit.h:96
void fillAlignablesMonitor(const edm::EventSetup &setup)
bool isValid(void) const
Get validity flag.
CLHEP::HepSymMatrix AlgebraicSymMatrix
void startNewLoop(void) override
Called at start of new loop.
unsigned int addSelections(const edm::ParameterSet &pSet)
const std::vector< std::string > surveyResiduals_
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
bool processHit2D(const AlignableDetOrUnitPtr &alidet, const Alignable *ali, const HIPAlignableSpecificParameters *alispecifics, const TrajectoryStateOnSurface &tsos, const TrackingRecHit *hit, double hitwt)
eventInfo
add run, event number and lumi section
DetId geographicalId() const
bool processHit1D(const AlignableDetOrUnitPtr &alidet, const Alignable *ali, const HIPAlignableSpecificParameters *alispecifics, const TrajectoryStateOnSurface &tsos, const TrackingRecHit *hit, double hitwt)
const IOVSyncValue & first() const
virtual LocalError localPositionError() const =0
std::vector< int > m_nhTOB
Constructor of the full muon geometry.
Definition: AlignableMuon.h:37
T x() const
Definition: PV3DBase.h:62
std::vector< int > m_nhPXB
const PositionType & position() const
T const * product() const
Definition: ESHandle.h:86
std::vector< align::StructureType > theLevels
SiPixelRecHitQuality::QualWordType rawQualityWord() const
Definition: SiPixelRecHit.h:81
float probabilityQ() const
Definition: SiPixelRecHit.h:99
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
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
SurfaceDeformationFactory::Type m2_dtype