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  align::Alignables 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::make_pair(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  align::Alignables 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 (const auto& it: theAlignables){
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 ...";
325  theAlignmentParameterStore->applyAlignableAbsolutePositions(theAlignables, theAlignablePositionsFromFile, ioerr);
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 (const auto& ali: theAlignables){
400  AlignmentParameters* par = ali->alignmentParameters();
401 
402  if (SetScanDet.at(0)!=0){
403  edm::LogWarning("Alignment") << "********Starting Scan*********";
404  edm::LogWarning("Alignment") <<"det ID="<<SetScanDet.at(0)<<", starting position="<<SetScanDet.at(1)<<", step="<<SetScanDet.at(2)<<", currentDet = "<<ali->id();
405  }
406 
407  if ((SetScanDet.at(0)!=0)&&(SetScanDet.at(0)!=1)&&(ali->id()!=SetScanDet.at(0))) continue;
408 
409  bool test = calcParameters(ali, SetScanDet.at(0), SetScanDet.at(1), SetScanDet.at(2));
410  if (test){
411  if (dynamic_cast<AlignableDetUnit*>(ali)!=nullptr){
412  std::vector<std::pair<int, SurfaceDeformation*>> pairs;
413  ali->surfaceDeformationIdPairs(pairs);
414  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::terminate" << "The alignable contains " << pairs.size() << " surface deformations";
415  }
416  else edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::terminate" << "The alignable cannot contain surface deformations";
417 
419  // set these parameters 'valid'
420  ali->alignmentParameters()->setValid(true);
421  // increase counter
422  ialigned++;
423  }
424  else par->setValid(false);
425  }
426  //end looping over alignables
427 
428  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::terminate] Aligned units: " << ialigned;
429 
430  // fill alignable wise root tree
431  fillAlignablesMonitor(iSetup);
432 
433  edm::LogWarning("Alignment")
434  << "[HIPAlignmentAlgorithm] Writing aligned parameters to file: " << theAlignables.size()
435  << ", for Iteration " << theIteration;
436 
437 
438  // write user variables
439  if (isCollector) HIPIO.writeHIPUserVariables(theAlignables, suvarfile.c_str(), theIteration, false, ioerr);
440 
441  // write new absolute positions to disk
442  theIO.writeAlignableAbsolutePositions(theAlignables, salignedfile.c_str(), theIteration, false, ioerr);
443 
444  // write alignment parameters to disk
445  //theIO.writeAlignmentParameters(theAlignables,
446  // sparameterfile.c_str(),theIteration,false,ioerr);
447 
448  // write iteration number to file
450 
451  // write out trees and close root file
452  // Survey tree
453  if (theSurveyIORootFile!=nullptr){
454  theSurveyIORootFile->cd();
455  if (theSurveyTree!=nullptr) theSurveyTree->Write();
456  delete theSurveyTree;
457  theSurveyTree=nullptr;
458  theSurveyIORootFile->Close();
459  }
460  // Alignable-wise tree is only filled once at iteration 1
461  if (theAlignablesMonitorIORootFile!=nullptr){
463  if (theAlignablesMonitorTree!=nullptr) theAlignablesMonitorTree->Write();
465  theAlignablesMonitorTree=nullptr;
467  }
468  // Eventwise and hitwise monitoring trees
469  if (theTrackHitMonitorIORootFile!=nullptr){
471  if (theTrackMonitorTree!=nullptr){
472  theTrackMonitorTree->Write();
473  delete theTrackMonitorTree;
474  theTrackMonitorTree=nullptr;
475  }
476  if (theHitMonitorTree!=nullptr){
477  theHitMonitorTree->Write();
478  delete theHitMonitorTree;
479  theHitMonitorTree=nullptr;
480  }
482  }
483 }
484 
486  const AlignableDetOrUnitPtr& alidet,
487  const Alignable* ali,
488  const HIPAlignableSpecificParameters* alispecifics,
489  const TrajectoryStateOnSurface& tsos,
491  double hitwt
492  ){
493  static const unsigned int hitDim = 1;
494 
495  // get trajectory impact point
496  LocalPoint alvec = tsos.localPosition();
497  AlgebraicVector pos(hitDim);
498  pos[0] = alvec.x();
499 
500  // get impact point covariance
501  AlgebraicSymMatrix ipcovmat(hitDim);
502  ipcovmat[0][0] = tsos.localError().positionError().xx();
503 
504  // get hit local position and covariance
505  AlgebraicVector coor(hitDim);
506  coor[0] = hit->localPosition().x();
507 
508  AlgebraicSymMatrix covmat(hitDim);
509  covmat[0][0] = hit->localPositionError().xx();
510 
511  // add hit and impact point covariance matrices
512  covmat = covmat + ipcovmat;
513 
514  // calculate the x pull of this hit
515  double xpull = 0.;
516  if (covmat[0][0] != 0.) xpull = (pos[0] - coor[0])/sqrt(fabs(covmat[0][0]));
517 
518  // get Alignment Parameters
519  AlignmentParameters* params = ali->alignmentParameters();
520  HIPUserVariables* uservar = dynamic_cast<HIPUserVariables*>(params->userVariables());
521  uservar->datatype = theDataGroup;
522  // get derivatives
523  AlgebraicMatrix derivs2D = params->selectedDerivatives(tsos, alidet);
524  // calculate user parameters
525  int npar = derivs2D.num_row();
526  AlgebraicMatrix derivs(npar, hitDim, 0); // This is jT
527 
528  for (int ipar=0; ipar<npar; ipar++){
529  for (unsigned int idim=0; idim<hitDim; idim++){
530  derivs[ipar][idim] = derivs2D[ipar][idim];
531  }
532  }
533 
534  // invert covariance matrix
535  int ierr;
536  covmat.invert(ierr);
537  if (ierr != 0){
538  edm::LogError("Alignment") << "@SUB=HIPAlignmentAlgorithm::processHit1D" << "Cov. matrix inversion failed!";
539  return false;
540  }
541 
542  double maxHitPullThreshold = (!theApplyCutsPerComponent ? defaultAlignableSpecs.maxHitPull : alispecifics->maxHitPull);
543  bool useThisHit = (maxHitPullThreshold < 0.);
544  useThisHit |= (fabs(xpull) < maxHitPullThreshold);
545  if (!useThisHit){
546  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::processHit2D" << "Hit pull (x) " << xpull << " fails the cut " << maxHitPullThreshold;
547  return false;
548  }
549 
550  AlgebraicMatrix covtmp(covmat);
551  AlgebraicMatrix jtvjtmp(derivs * covtmp *derivs.T());
552  AlgebraicSymMatrix thisjtvj(npar);
553  AlgebraicVector thisjtve(npar);
554  thisjtvj.assign(jtvjtmp);
555  thisjtve=derivs * covmat * (pos-coor);
556 
557  AlgebraicVector hitresidual(hitDim);
558  hitresidual[0] = (pos[0] - coor[0]);
559 
560  AlgebraicMatrix hitresidualT;
561  hitresidualT = hitresidual.T();
562 
563  uservar->jtvj += hitwt*thisjtvj;
564  uservar->jtve += hitwt*thisjtve;
565  uservar->nhit++;
566 
567  //for alignable chi squared
568  float thischi2;
569  thischi2 = hitwt*(hitresidualT *covmat *hitresidual)[0];
570 
571  if (verbose && (thischi2/ static_cast<float>(uservar->nhit))>10.)
572  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::processHit1D] Added to Chi2 the number " << thischi2 << " having "
573  << uservar->nhit << " ndof"
574  << ", X-resid " << hitresidual[0]
575  << ", Cov^-1 matr (covmat):"
576  << " [0][0] = " << covmat[0][0];
577 
578  uservar->alichi2 += thischi2;
579  uservar->alindof += hitDim;
580 
581  return true;
582 }
583 
585  const AlignableDetOrUnitPtr& alidet,
586  const Alignable* ali,
587  const HIPAlignableSpecificParameters* alispecifics,
588  const TrajectoryStateOnSurface& tsos,
590  double hitwt
591  ){
592  static const unsigned int hitDim = 2;
593 
594  // get trajectory impact point
595  LocalPoint alvec = tsos.localPosition();
596  AlgebraicVector pos(hitDim);
597  pos[0] = alvec.x();
598  pos[1] = alvec.y();
599 
600  // get impact point covariance
601  AlgebraicSymMatrix ipcovmat(hitDim);
602  ipcovmat[0][0] = tsos.localError().positionError().xx();
603  ipcovmat[1][1] = tsos.localError().positionError().yy();
604  ipcovmat[0][1] = tsos.localError().positionError().xy();
605 
606  // get hit local position and covariance
607  AlgebraicVector coor(hitDim);
608  coor[0] = hit->localPosition().x();
609  coor[1] = hit->localPosition().y();
610 
611  AlgebraicSymMatrix covmat(hitDim);
612  covmat[0][0] = hit->localPositionError().xx();
613  covmat[1][1] = hit->localPositionError().yy();
614  covmat[0][1] = hit->localPositionError().xy();
615 
616  // add hit and impact point covariance matrices
617  covmat = covmat + ipcovmat;
618 
619  // calculate the x pull and y pull of this hit
620  double xpull = 0.;
621  double ypull = 0.;
622  if (covmat[0][0] != 0.) xpull = (pos[0] - coor[0])/sqrt(fabs(covmat[0][0]));
623  if (covmat[1][1] != 0.) ypull = (pos[1] - coor[1])/sqrt(fabs(covmat[1][1]));
624 
625  // get Alignment Parameters
626  AlignmentParameters* params = ali->alignmentParameters();
627  HIPUserVariables* uservar = dynamic_cast<HIPUserVariables*>(params->userVariables());
628  uservar->datatype = theDataGroup;
629  // get derivatives
630  AlgebraicMatrix derivs2D = params->selectedDerivatives(tsos, alidet);
631  // calculate user parameters
632  int npar = derivs2D.num_row();
633  AlgebraicMatrix derivs(npar, hitDim, 0); // This is jT
634 
635  for (int ipar=0; ipar<npar; ipar++){
636  for (unsigned int idim=0; idim<hitDim; idim++){
637  derivs[ipar][idim] = derivs2D[ipar][idim];
638  }
639  }
640 
641  // invert covariance matrix
642  int ierr;
643  covmat.invert(ierr);
644  if (ierr != 0){
645  edm::LogError("Alignment") << "@SUB=HIPAlignmentAlgorithm::processHit2D" << "Cov. matrix inversion failed!";
646  return false;
647  }
648 
649  double maxHitPullThreshold = (!theApplyCutsPerComponent ? defaultAlignableSpecs.maxHitPull : alispecifics->maxHitPull);
650  bool useThisHit = (maxHitPullThreshold < 0.);
651  useThisHit |= (fabs(xpull) < maxHitPullThreshold && fabs(ypull) < maxHitPullThreshold);
652  if (!useThisHit){
653  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::processHit2D" << "Hit pull (x,y) " << xpull << " , " << ypull << " fails the cut " << maxHitPullThreshold;
654  return false;
655  }
656 
657  AlgebraicMatrix covtmp(covmat);
658  AlgebraicMatrix jtvjtmp(derivs * covtmp *derivs.T());
659  AlgebraicSymMatrix thisjtvj(npar);
660  AlgebraicVector thisjtve(npar);
661  thisjtvj.assign(jtvjtmp);
662  thisjtve=derivs * covmat * (pos-coor);
663 
664  AlgebraicVector hitresidual(hitDim);
665  hitresidual[0] = (pos[0] - coor[0]);
666  hitresidual[1] = (pos[1] - coor[1]);
667 
668  AlgebraicMatrix hitresidualT;
669  hitresidualT = hitresidual.T();
670 
671  uservar->jtvj += hitwt*thisjtvj;
672  uservar->jtve += hitwt*thisjtve;
673  uservar->nhit++;
674 
675  //for alignable chi squared
676  float thischi2;
677  thischi2 = hitwt*(hitresidualT *covmat *hitresidual)[0];
678 
679  if (verbose && (thischi2/ static_cast<float>(uservar->nhit))>10.)
680  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::processHit2D] Added to Chi2 the number " << thischi2 << " having "
681  << uservar->nhit << " ndof"
682  << ", X-resid " << hitresidual[0]
683  << ", Y-resid " << hitresidual[1]
684  << ", Cov^-1 matr (covmat):"
685  << " [0][0] = " << covmat[0][0]
686  << " [0][1] = " << covmat[0][1]
687  << " [1][0] = " << covmat[1][0]
688  << " [1][1] = " << covmat[1][1];
689 
690  uservar->alichi2 += thischi2;
691  uservar->alindof += hitDim;
692 
693  return true;
694 }
695 
696 // Run the algorithm on trajectories and tracks -------------------------------
698  if (isCollector) return;
699 
700  TrajectoryStateCombiner tsoscomb;
701 
702  m_Ntracks=0;
703  // hit info
704  m_sinTheta =0;
705  m_angle = 0;
706  m_detId =0;
707  m_hitwt=1;
709 
710  // loop over tracks
712  for (ConstTrajTrackPairCollection::const_iterator it=tracks.begin(); it!=tracks.end(); ++it){
713  const Trajectory* traj = (*it).first;
714  const reco::Track* track = (*it).second;
715 
716  float pt = track->pt();
717  float eta = track->eta();
718  float phi = track->phi();
719  float p = track->p();
720  float chi2n = track->normalizedChi2();
721  int nhit = track->numberOfValidHits();
722  float d0 = track->d0();
723  float dz = track->dz();
724 
725  int nhpxb = track->hitPattern().numberOfValidPixelBarrelHits();
726  int nhpxf = track->hitPattern().numberOfValidPixelEndcapHits();
727  int nhtib = track->hitPattern().numberOfValidStripTIBHits();
728  int nhtob = track->hitPattern().numberOfValidStripTOBHits();
729  int nhtid = track->hitPattern().numberOfValidStripTIDHits();
730  int nhtec = track->hitPattern().numberOfValidStripTECHits();
731 
732  if (verbose) edm::LogInfo("Alignment")
733  << "New track pt,eta,phi,chi2n,hits: "
734  << pt << ","
735  << eta << ","
736  << phi << ","
737  << chi2n << ","
738  << nhit;
739 
740  double ihitwt = 1;
741  double trkwt = 1;
742  if (trackWt){
743  trkwt=Scale;
744  // Reweight by the specified eta distribution
745  if (uniEta) trkwt *= theEtaFormula->Eval(fabs(eta));
746  }
747  if (trackPs){
748  double r = gRandom->Rndm();
749  if (trkwt < r) continue;
750  }
751  else if (trackWt) ihitwt=trkwt;
752 
753  // fill track parameters in root tree
754  {
755  m_Nhits.push_back(nhit);
756  m_Pt.push_back(pt);
757  m_P.push_back(p);
758  m_Eta.push_back(eta);
759  m_Phi.push_back(phi);
760  m_Chi2n.push_back(chi2n);
761  m_nhPXB.push_back(nhpxb);
762  m_nhPXF.push_back(nhpxf);
763  m_nhTIB.push_back(nhtib);
764  m_nhTOB.push_back(nhtob);
765  m_nhTID.push_back(nhtid);
766  m_nhTEC.push_back(nhtec);
767  m_d0.push_back(d0);
768  m_dz.push_back(dz);
769  m_wt.push_back(ihitwt);
770  m_Ntracks++;
771  }
772 
773  std::vector<const TransientTrackingRecHit*> hitvec;
774  std::vector<TrajectoryStateOnSurface> tsosvec;
775 
776  // loop over measurements
777  std::vector<TrajectoryMeasurement> measurements = traj->measurements();
778  for (std::vector<TrajectoryMeasurement>::iterator im=measurements.begin(); im!=measurements.end(); ++im){
779 
780  TrajectoryMeasurement meas = *im;
781 
782  // const TransientTrackingRecHit* ttrhit = &(*meas.recHit());
783  // const TrackingRecHit *hit = ttrhit->hit();
784  const TransientTrackingRecHit* hit = &(*meas.recHit());
785 
786  if (hit->isValid() && theAlignableDetAccessor->detAndSubdetInMap(hit->geographicalId())){
787  // this is the updated state (including the current hit)
788  // TrajectoryStateOnSurface tsos=meas.updatedState();
789  // combine fwd and bwd predicted state to get state
790  // which excludes current hit
791 
793  if (eventInfo.clusterValueMap()){
794  // check from the PrescalingMap if the hit was taken.
795  // If not skip to the next TM
796  // bool hitTaken=false;
797  AlignmentClusterFlag myflag;
798 
799  int subDet = hit->geographicalId().subdetId();
800  //take the actual RecHit out of the Transient one
801  const TrackingRecHit *rechit=hit->hit();
802  if (subDet>2){ // AM: if possible use enum instead of hard-coded value
803  const std::type_info &type = typeid(*rechit);
804 
805  if (type == typeid(SiStripRecHit1D)){
806 
807  const SiStripRecHit1D* stripHit1D = dynamic_cast<const SiStripRecHit1D*>(rechit);
808  if (stripHit1D){
809  SiStripRecHit1D::ClusterRef stripclust(stripHit1D->cluster());
810  // myflag=PrescMap[stripclust];
811  myflag = (*eventInfo.clusterValueMap())[stripclust];
812  }
813  else edm::LogError("HIPAlignmentAlgorithm")
814  << "ERROR in <HIPAlignmentAlgorithm::run>: Dynamic cast of Strip RecHit failed! "
815  << "TypeId of the RecHit: " << className(*hit);
816  }//end if type = SiStripRecHit1D
817  else if (type == typeid(SiStripRecHit2D)){
818 
819  const SiStripRecHit2D* stripHit2D = dynamic_cast<const SiStripRecHit2D*>(rechit);
820  if (stripHit2D){
821  SiStripRecHit2D::ClusterRef stripclust(stripHit2D->cluster());
822  // myflag=PrescMap[stripclust];
823  myflag = (*eventInfo.clusterValueMap())[stripclust];
824  }
825  else edm::LogError("HIPAlignmentAlgorithm")
826  << "ERROR in <HIPAlignmentAlgorithm::run>: Dynamic cast of Strip RecHit failed! "
827  << "TypeId of the TTRH: " << className(*hit);
828  } //end if type == SiStripRecHit2D
829  } //end if hit from strips
830  else{
831  const SiPixelRecHit* pixelhit= dynamic_cast<const SiPixelRecHit*>(rechit);
832  if (pixelhit){
833  SiPixelClusterRefNew pixelclust(pixelhit->cluster());
834  // myflag=PrescMap[pixelclust];
835  myflag = (*eventInfo.clusterValueMap())[pixelclust];
836  }
837  else edm::LogError("HIPAlignmentAlgorithm")
838  << "ERROR in <HIPAlignmentAlgorithm::run>: Dynamic cast of Pixel RecHit failed! "
839  << "TypeId of the TTRH: " << className(*hit);
840  } //end 'else' it is a pixel hit
841  if (!myflag.isTaken()) continue;
842  }//end if Prescaled Hits
844 
845  TrajectoryStateOnSurface tsos = tsoscomb.combine(
846  meas.forwardPredictedState(),
848  );
849 
850  if (tsos.isValid()){
851  hitvec.push_back(hit);
852  tsosvec.push_back(tsos);
853  }
854 
855  } //hit valid
856  }
857 
858  // transform RecHit vector to AlignableDet vector
859  std::vector<AlignableDetOrUnitPtr> alidetvec = theAlignableDetAccessor->alignablesFromHits(hitvec);
860 
861  // get concatenated alignment parameters for list of alignables
863 
864  std::vector<TrajectoryStateOnSurface>::const_iterator itsos=tsosvec.begin();
865  std::vector<const TransientTrackingRecHit*>::const_iterator ihit=hitvec.begin();
866 
867  // loop over vectors(hit,tsos)
868  while (itsos != tsosvec.end()){
869  // get AlignableDet for this hit
870  const GeomDet* det = (*ihit)->det();
871  // int subDet= (*ihit)->geographicalId().subdetId();
872  uint32_t nhitDim = (*ihit)->dimension();
873 
874  AlignableDetOrUnitPtr alidet = theAlignableDetAccessor->alignableFromGeomDet(det);
875 
876  // get relevant Alignable
877  Alignable* ali = aap.alignableFromAlignableDet(alidet);
878 
879  if (ali!=nullptr){
880  const HIPAlignableSpecificParameters* alispecifics = findAlignableSpecs(ali);
881  const TrajectoryStateOnSurface& tsos = *itsos;
882 
883  // LocalVector v = tsos.localDirection();
884  // double proj_z = v.dot(LocalVector(0,0,1));
885 
886  //In fact, sin_theta=Abs(mom_z)
887  double mom_x = tsos.localDirection().x();
888  double mom_y = tsos.localDirection().y();
889  double mom_z = tsos.localDirection().z();
890  double sin_theta = TMath::Abs(mom_z) / sqrt(pow(mom_x, 2)+pow(mom_y, 2)+pow(mom_z, 2));
891  double angle = TMath::ASin(sin_theta);
892 
893  //Make cut on hit impact angle, reduce collision hits perpendicular to modules
894  if (IsCollision){ if (angle>col_cut)ihitwt=0; }
895  else{ if (angle<cos_cut)ihitwt=0; }
896  m_angle = angle;
897  m_sinTheta = sin_theta;
898  m_detId = ali->id();
899 
900  // Check pixel XY and Q probabilities
901  m_hasHitProb = false;
902  m_probXY=-1;
903  m_probQ=-1;
904  m_rawQualityWord=9999;
905  if ((*ihit)->hit()!=nullptr){
906  const SiPixelRecHit* pixhit = dynamic_cast<const SiPixelRecHit*>((*ihit)->hit());
907  if (pixhit!=nullptr){
908  m_hasHitProb = pixhit->hasFilledProb();
909  if (m_hasHitProb){
910  // Prob X, Y are deprecated
911  m_probXY=pixhit->probabilityXY();
912  m_probQ=pixhit->probabilityQ();
914  if (alispecifics->applyPixelProbCut){
915  bool probXYgood = (m_probXY>=alispecifics->minPixelProbXY && m_probXY<=alispecifics->maxPixelProbXY);
916  bool probQgood = (m_probQ>=alispecifics->minPixelProbQ && m_probQ<=alispecifics->maxPixelProbQ);
917  bool probXYQgood;
918  if (alispecifics->usePixelProbXYOrProbQ) probXYQgood = (probXYgood || probQgood);
919  else probXYQgood = (probXYgood && probQgood);
920  if (!probXYQgood) ihitwt=0;
921  }
922  }
923  }
924  }
925 
926  m_hitwt = ihitwt;
927  if (ihitwt!=0.){
928  bool hitProcessed=false;
929  switch (nhitDim){
930  case 1:
931  hitProcessed=processHit1D(alidet, ali, alispecifics, tsos, *ihit, ihitwt);
932  break;
933  case 2:
934  hitProcessed=processHit2D(alidet, ali, alispecifics, tsos, *ihit, ihitwt);
935  break;
936  default:
937  edm::LogError("HIPAlignmentAlgorithm")
938  << "ERROR in <HIPAlignmentAlgorithm::run>: Number of hit dimensions = "
939  << nhitDim << " is not supported!"
940  << std::endl;
941  break;
942  }
944  }
945  }
946 
947  itsos++;
948  ihit++;
949  }
950  } // end of track loop
951 
952  // fill eventwise root tree (with prescale defined in pset)
954 }
955 
956 // ----------------------------------------------------------------------------
958  int result;
959 
960  std::ifstream inIterFile(filename.c_str(), std::ios::in);
961  if (!inIterFile) {
962  edm::LogError("Alignment") << "[HIPAlignmentAlgorithm::readIterationFile] ERROR! "
963  << "Unable to open Iteration file";
964  result = -1;
965  }
966  else {
967  inIterFile >> result;
968  edm::LogWarning("Alignment") << "[HIPAlignmentAlgorithm::readIterationFile] "
969  << "Read last iteration number from file: " << result;
970  }
971  inIterFile.close();
972 
973  return result;
974 }
975 
976 // ----------------------------------------------------------------------------
978  std::ofstream outIterFile((filename.c_str()), std::ios::out);
979  if (!outIterFile) edm::LogError("Alignment")
980  << "[HIPAlignmentAlgorithm::writeIterationFile] ERROR: Unable to write Iteration file";
981  else{
982  outIterFile << iter;
983  edm::LogWarning("Alignment") <<"[HIPAlignmentAlgorithm::writeIterationFile] writing iteration number to file: " << iter;
984  }
985  outIterFile.close();
986 }
987 
988 // ----------------------------------------------------------------------------
989 // set alignment position error
991  // Check if user wants to override APE
992  if (!theApplyAPE){
993  edm::LogInfo("Alignment") <<"[HIPAlignmentAlgorithm::setAlignmentPositionError] No APE applied";
994  return; // NO APE APPLIED
995  }
996 
997  edm::LogInfo("Alignment") <<"[HIPAlignmentAlgorithm::setAlignmentPositionError] Apply APE!";
998 
999  double apeSPar[3], apeRPar[3];
1000  for (const auto& alipars: theAPEParameters) {
1001  const auto& alignables = alipars.first;
1002  const auto& pars = alipars.second;
1003 
1004  apeSPar[0] = pars[0];
1005  apeSPar[1] = pars[1];
1006  apeSPar[2] = pars[2];
1007  apeRPar[0] = pars[3];
1008  apeRPar[1] = pars[4];
1009  apeRPar[2] = pars[5];
1010 
1011  int function = pars[6];
1012 
1013  // Printout for debug
1014  printf("APE: %u alignables\n", (unsigned int)alignables.size());
1015  for (int i=0; i<21; ++i) {
1016  double apelinstest=calcAPE(apeSPar, i, 0);
1017  double apeexpstest=calcAPE(apeSPar, i, 1);
1018  double apestepstest=calcAPE(apeSPar, i, 2);
1019  double apelinrtest=calcAPE(apeRPar, i, 0);
1020  double apeexprtest=calcAPE(apeRPar, i, 1);
1021  double apesteprtest=calcAPE(apeRPar, i, 2);
1022  printf("APE: iter slin sexp sstep rlin rexp rstep: %5d %12.5f %12.5f %12.5f %12.5f %12.5f %12.5f \n",
1023  i, apelinstest, apeexpstest, apestepstest, apelinrtest, apeexprtest, apesteprtest);
1024  }
1025 
1026  // set APE
1027  double apeshift = calcAPE(apeSPar, theIteration, function);
1028  double aperot = calcAPE(apeRPar, theIteration, function);
1029  theAlignmentParameterStore->setAlignmentPositionError(alignables, apeshift, aperot);
1030  }
1031 }
1032 
1033 // ----------------------------------------------------------------------------
1034 // calculate APE
1035 double HIPAlignmentAlgorithm::calcAPE(double* par, int iter, int function){
1036  double diter=(double)iter;
1037  if (function == 0) return std::max(par[1], par[0]+((par[1]-par[0])/par[2])*diter);
1038  else if (function == 1) return std::max(0., par[0]*(exp(-pow(diter, par[1])/par[2])));
1039  else if (function == 2){
1040  int ipar2 = (int)par[2];
1041  int step = iter/ipar2;
1042  double dstep = (double)step;
1043  return std::max(0., par[0] - par[1]*dstep);
1044  }
1045  else assert(false); // should have been caught in the constructor
1046 }
1047 
1048 // ----------------------------------------------------------------------------
1049 // book root trees
1051  // create ROOT files
1053  theTrackHitMonitorIORootFile = TFile::Open(theMonitorConfig.outfile.c_str(), "update");
1055  // book event-wise ROOT Tree
1057  TString tname=Form("T1_%i", theIteration);
1058  theTrackMonitorTree = new TTree(tname, "Eventwise tree");
1059  //theTrackMonitorTree->Branch("Run", &m_Run, "Run/I");
1060  //theTrackMonitorTree->Branch("Event", &m_Event, "Event/I");
1061  theTrackMonitorTree->Branch("Ntracks", &m_Ntracks);
1062  theTrackMonitorTree->Branch("Nhits", &m_Nhits);
1063  theTrackMonitorTree->Branch("DataType", &m_datatype);
1064  theTrackMonitorTree->Branch("nhPXB", &m_nhPXB);
1065  theTrackMonitorTree->Branch("nhPXF", &m_nhPXF);
1066  theTrackMonitorTree->Branch("nhTIB", &m_nhTIB);
1067  theTrackMonitorTree->Branch("nhTOB", &m_nhTOB);
1068  theTrackMonitorTree->Branch("nhTID", &m_nhTID);
1069  theTrackMonitorTree->Branch("nhTEC", &m_nhTEC);
1070  theTrackMonitorTree->Branch("Pt", &m_Pt);
1071  theTrackMonitorTree->Branch("P", &m_P);
1072  theTrackMonitorTree->Branch("Eta", &m_Eta);
1073  theTrackMonitorTree->Branch("Phi", &m_Phi);
1074  theTrackMonitorTree->Branch("Chi2n", &m_Chi2n);
1075  theTrackMonitorTree->Branch("d0", &m_d0);
1076  theTrackMonitorTree->Branch("dz", &m_dz);
1077  theTrackMonitorTree->Branch("wt", &m_wt);
1078  }
1079  // book hit-wise ROOT Tree
1081  TString tname_hit=Form("T1_hit_%i", theIteration);
1082  theHitMonitorTree = new TTree(tname_hit, "Hitwise tree");
1083  theHitMonitorTree->Branch("Id", &m_detId, "Id/i");
1084  theHitMonitorTree->Branch("DataType", &m_datatype);
1085  theHitMonitorTree->Branch("sinTheta", &m_sinTheta);
1086  theHitMonitorTree->Branch("impactAngle", &m_angle);
1087  theHitMonitorTree->Branch("wt", &m_hitwt);
1088  theHitMonitorTree->Branch("probPresent", &m_hasHitProb);
1089  theHitMonitorTree->Branch("probXY", &m_probXY);
1090  theHitMonitorTree->Branch("probQ", &m_probQ);
1091  theHitMonitorTree->Branch("qualityWord", &m_rawQualityWord);
1092  }
1093  }
1094 
1095  // book alignable-wise ROOT Tree
1096  if (isCollector){
1097  TString tname=Form("T2_%i", theIteration);
1098  theAlignablesMonitorIORootFile = TFile::Open(outfile2.c_str(), "update");
1100  theAlignablesMonitorTree = new TTree(tname, "Alignablewise tree");
1101  theAlignablesMonitorTree->Branch("Id", &m2_Id, "Id/i");
1102  theAlignablesMonitorTree->Branch("ObjId", &m2_ObjId, "ObjId/I");
1103  theAlignablesMonitorTree->Branch("Nhit", &m2_Nhit);
1104  theAlignablesMonitorTree->Branch("DataType", &m2_datatype);
1105  theAlignablesMonitorTree->Branch("Type", &m2_Type);
1106  theAlignablesMonitorTree->Branch("Layer", &m2_Layer);
1107  theAlignablesMonitorTree->Branch("Xpos", &m2_Xpos);
1108  theAlignablesMonitorTree->Branch("Ypos", &m2_Ypos);
1109  theAlignablesMonitorTree->Branch("Zpos", &m2_Zpos);
1110  theAlignablesMonitorTree->Branch("DeformationsType", &m2_dtype, "DeformationsType/I");
1111  theAlignablesMonitorTree->Branch("NumDeformations", &m2_nsurfdef);
1112  theAlignablesMonitorTree->Branch("Deformations", &m2_surfDef);
1113  }
1114 
1115  // book survey-wise ROOT Tree only if survey is enabled
1116  if (!theLevels.empty()){
1117  TString tname=Form("T3_%i", theIteration);
1118  theSurveyIORootFile = TFile::Open(ssurveyfile.c_str(), "update");
1119  theSurveyIORootFile->cd();
1120  theSurveyTree = new TTree(tname, "Survey Tree");
1121  theSurveyTree->Branch("Id", &m3_Id, "Id/i");
1122  theSurveyTree->Branch("ObjId", &m3_ObjId, "ObjId/I");
1123  theSurveyTree->Branch("Par", &m3_par, "Par[6]/F");
1124  edm::LogInfo("Alignment") << "[HIPAlignmentAlgorithm::bookRoot] Survey trees booked.";
1125  }
1126  edm::LogInfo("Alignment") << "[HIPAlignmentAlgorithm::bookRoot] Root trees booked.";
1127 }
1128 
1129 // ----------------------------------------------------------------------------
1130 // fill alignable-wise root tree
1132  if (theAlignablesMonitorIORootFile==(TFile*)nullptr) return;
1133  using std::setw;
1135 
1136  int naligned=0;
1137 
1138  //Retrieve tracker topology from geometry
1139  edm::ESHandle<TrackerTopology> tTopoHandle;
1140  // iSetup.get<IdealGeometryRecord>().get(tTopoHandle);
1141  iSetup.get<TrackerTopologyRcd>().get(tTopoHandle);
1142 
1143  const TrackerTopology* const tTopo = tTopoHandle.product();
1144 
1145  for (const auto& ali: theAlignables){
1146  AlignmentParameters* dap = ali->alignmentParameters();
1147 
1148  // consider only those parameters classified as 'valid'
1149  if (dap->isValid()){
1150  // get number of hits from user variable
1151  HIPUserVariables* uservar = dynamic_cast<HIPUserVariables*>(dap->userVariables());
1152  m2_Nhit = uservar->nhit;
1153  m2_datatype = uservar->datatype;
1154 
1155  // get type/layer
1156  std::pair<int, int> tl = theAlignmentParameterStore->typeAndLayer(ali, tTopo);
1157  m2_Type = tl.first;
1158  m2_Layer = tl.second;
1159 
1160  // get identifier (as for IO)
1161  m2_Id = ali->id();
1162  m2_ObjId = ali->alignableObjectId();
1163 
1164  // get position
1165  GlobalPoint pos = ali->surface().position();
1166  m2_Xpos = pos.x();
1167  m2_Ypos = pos.y();
1168  m2_Zpos = pos.z();
1169 
1170  m2_surfDef.clear();
1171  {
1172  std::vector<std::pair<int, SurfaceDeformation*> > dali_id_pairs;
1173  SurfaceDeformation* dali_obj=nullptr;
1175  std::vector<double> dali;
1176  if (1 == ali->surfaceDeformationIdPairs(dali_id_pairs)){
1177  dali_obj = dali_id_pairs[0].second;
1178  dali = dali_obj->parameters();
1179  dtype = (SurfaceDeformationFactory::Type)dali_obj->type();
1180  }
1181  for (auto& dit : dali) m2_surfDef.push_back((float)dit);
1182  m2_dtype = dtype;
1183  m2_nsurfdef = m2_surfDef.size();
1184  }
1185 
1186  if (verbose){
1187  AlgebraicVector pars = dap->parameters();
1188  edm::LogVerbatim("Alignment")
1189  << "------------------------------------------------------------------------\n"
1190  << " ALIGNABLE: " << setw(6) << naligned
1191  << '\n'
1192  << "hits: " << setw(4) << m2_Nhit
1193  << " type: " << setw(4) << m2_Type
1194  << " layer: " << setw(4) << m2_Layer
1195  << " id: " << setw(4) << m2_Id
1196  << " objId: " << setw(4) << m2_ObjId
1197  << '\n'
1198  << std::fixed << std::setprecision(5)
1199  << "x,y,z: "
1200  << setw(12) << m2_Xpos
1201  << setw(12) << m2_Ypos
1202  << setw(12) << m2_Zpos
1203  << "\nDeformations type, nDeformations: "
1204  << setw(12) << m2_dtype
1205  << setw(12) << m2_nsurfdef
1206  << '\n'
1207  << "params: "
1208  << setw(12) << pars[0]
1209  << setw(12) << pars[1]
1210  << setw(12) << pars[2]
1211  << setw(12) << pars[3]
1212  << setw(12) << pars[4]
1213  << setw(12) << pars[5];
1214  }
1215 
1216  naligned++;
1217  if (theAlignablesMonitorTree!=nullptr) theAlignablesMonitorTree->Fill();
1218  }
1219  }
1220 }
1221 
1222 // ----------------------------------------------------------------------------
1223 bool HIPAlignmentAlgorithm::calcParameters(Alignable* ali, int setDet, double start, double step){
1224  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::calcParameters" << "Begin: Processing detector " << ali->id();
1225 
1226  // Alignment parameters
1228  const HIPAlignableSpecificParameters* alispecifics = findAlignableSpecs(ali);
1229  // access user variables
1230  HIPUserVariables* uservar = dynamic_cast<HIPUserVariables*>(par->userVariables());
1231  int nhit = uservar->nhit;
1232  // The following variable is needed for the extended 1D/2D hit fix using
1233  // matrix shrinkage and expansion
1234  // int hitdim = uservar->hitdim;
1235 
1236  // Test nhits
1237  int minHitThreshold = (!theApplyCutsPerComponent ? defaultAlignableSpecs.minNHits : alispecifics->minNHits);
1238  if (!isCollector) minHitThreshold=1;
1239  if (setDet==0 && nhit<minHitThreshold){
1240  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::calcParameters" << "Skipping detector " << ali->id() << " because number of hits = " << nhit << " <= " << minHitThreshold;
1241  par->setValid(false);
1242  return false;
1243  }
1244 
1245  AlgebraicSymMatrix jtvj = uservar->jtvj;
1246  AlgebraicVector jtve = uservar->jtve;
1247 
1248  // these are the alignment corrections+covariance (for selected params)
1249  int npar = jtve.num_row();
1250  AlgebraicVector params(npar);
1251  AlgebraicVector paramerr(npar);
1252  AlgebraicSymMatrix cov(npar);
1253 
1254  // errors of parameters
1255  if (isCollector){
1256  if (setDet==0){
1257  int ierr;
1258  AlgebraicSymMatrix jtvjinv = jtvj.inverse(ierr);
1259  if (ierr!=0){
1260  edm::LogError("Alignment") << "@SUB=HIPAlignmentAlgorithm::calcParameters" << "Matrix inversion failed!";
1261  return false;
1262  }
1263  params = -(jtvjinv * jtve);
1264  cov = jtvjinv;
1265 
1266  double minRelErrThreshold = (!theApplyCutsPerComponent ? defaultAlignableSpecs.minRelParError : alispecifics->minRelParError);
1267  double maxRelErrThreshold = (!theApplyCutsPerComponent ? defaultAlignableSpecs.maxRelParError : alispecifics->maxRelParError);
1268  for (int i=0; i<npar; i++){
1269  double relerr=0;
1270  if (fabs(cov[i][i])>0.) paramerr[i] = sqrt(fabs(cov[i][i]));
1271  else paramerr[i] = params[i];
1272  if (params[i]!=0.) relerr = fabs(paramerr[i]/params[i]);
1273  if ((maxRelErrThreshold>=0. && relerr>maxRelErrThreshold) || relerr<minRelErrThreshold){
1274  edm::LogWarning("Alignment")
1275  << "@SUB=HIPAlignmentAlgorithm::calcParameters" << "RelError = " << relerr
1276  << " > " << maxRelErrThreshold << " or < " << minRelErrThreshold
1277  << ". Setting param = paramerr = 0 for component " << i;
1278  params[i]=0;
1279  paramerr[i]=0;
1280  }
1281  }
1282  }
1283  else{
1284  if (params.num_row()!=1){
1285  edm::LogError("Alignment") << "@SUB=HIPAlignmentAlgorithm::calcParameters" << "For scanning, please only turn on one parameter! check common_cff_py.txt";
1286  return false;
1287  }
1288  if (theIteration==1) params[0] = start;
1289  else params[0]=step;
1290  edm::LogWarning("Alignment") << "@SUB=HIPAlignmentAlgorithm::calcParameters" << "Parameters = " << params;
1291  }
1292  }
1293 
1294  uservar->alipar=params;
1295  uservar->alierr=paramerr;
1296 
1297  AlignmentParameters* parnew = par->cloneFromSelected(params, cov);
1298  ali->setAlignmentParameters(parnew);
1299  parnew->setValid(true);
1300 
1301  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::calcParameters" << "End: Processing detector " << ali->id();
1302 
1303  return true;
1304 }
1305 
1306 //-----------------------------------------------------------------------------
1308  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::collector" << "Called for iteration " << theIteration;
1309 
1310  std::vector<std::string> monitorFileList;
1311  HIPUserVariablesIORoot HIPIO;
1312 
1313  typedef int pawt_t;
1314  std::unordered_map<Alignable*, std::unordered_map<int, pawt_t> > ali_datatypecountpair_map;
1315  if (rewgtPerAli){
1316  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.";
1317  // Counting step for per-alignable reweighting
1318  for (int ijob=1; ijob<=theCollectorNJobs; ijob++){
1319  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::collector" << "Pre-reading uservar for job " << ijob;
1320 
1321  std::string str = std::to_string(ijob);
1322  std::string uvfile = theCollectorPath+"/job"+str+"/"+suvarfilecore;
1323 
1324  std::vector<AlignmentUserVariables*> uvarvec = HIPIO.readHIPUserVariables(theAlignables, uvfile.c_str(), theIteration, ioerr);
1325  if (uvarvec.size()!=theAlignables.size()) edm::LogWarning("Alignment")
1326  << "@SUB=HIPAlignmentAlgorithm::collector"
1327  << "Number of alignables = " << theAlignables.size() << " is not the same as number of user variables = " << uvarvec.size()
1328  << ". A mismatch might occur!";
1329  if (ioerr!=0){
1330  edm::LogError("Alignment") << "@SUB=HIPAlignmentAlgorithm::collector" << "Could not read user variable files for job " << ijob << " in iteration " << theIteration;
1331  continue;
1332  }
1333  std::vector<AlignmentUserVariables*>::const_iterator iuvar=uvarvec.begin(); // This vector should have 1-to-1 correspondence with the alignables vector
1334  for (const auto& ali: theAlignables){
1335  // No need for the user variables already attached to the alignables
1336  // Just count from what you read.
1337  HIPUserVariables* uvar = dynamic_cast<HIPUserVariables*>(*iuvar);
1338  if (uvar!=nullptr){
1339  int alijobdtype = uvar->datatype;
1340  pawt_t alijobnhits = uvar->nhit;
1341  if (ali_datatypecountpair_map.find(ali)==ali_datatypecountpair_map.end()){ // This is a new alignable
1342  std::unordered_map<int, pawt_t> newmap;
1343  ali_datatypecountpair_map[ali] = newmap;
1344  ali_datatypecountpair_map[ali][alijobdtype] = alijobnhits;
1345  }
1346  else{ // Alignable already exists in the map
1347  std::unordered_map<int, pawt_t>& theMap = ali_datatypecountpair_map[ali];
1348  if (theMap.find(alijobdtype)==theMap.end()) theMap[alijobdtype]=alijobnhits;
1349  else theMap[alijobdtype] += alijobnhits;
1350  }
1351  delete uvar; // Delete new user variables as they are added
1352  }
1353  iuvar++;
1354  } // End loop over alignables
1355  } // End loop over subjobs
1356  }
1357 
1358  for (int ijob=1; ijob<=theCollectorNJobs; ijob++){
1359  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::collector" << "Reading uservar for job " << ijob;
1360 
1361  std::string str = std::to_string(ijob);
1362  std::string uvfile = theCollectorPath+"/job"+str+"/"+suvarfilecore;
1363 
1364  std::vector<AlignmentUserVariables*> uvarvec = HIPIO.readHIPUserVariables(theAlignables, uvfile.c_str(), theIteration, ioerr);
1365  if (uvarvec.size()!=theAlignables.size()) edm::LogWarning("Alignment")
1366  << "@SUB=HIPAlignmentAlgorithm::collector"
1367  << "Number of alignables = " << theAlignables.size() << " is not the same as number of user variables = " << uvarvec.size()
1368  << ". A mismatch might occur!";
1369 
1370  if (ioerr!=0){
1371  edm::LogError("Alignment") << "@SUB=HIPAlignmentAlgorithm::collector" << "Could not read user variable files for job " << ijob << " in iteration " << theIteration;
1372  continue;
1373  }
1374 
1375  // add
1376  std::vector<AlignmentUserVariables*> uvarvecadd;
1377  std::vector<AlignmentUserVariables*>::const_iterator iuvarnew=uvarvec.begin();
1378  for (const auto& ali: theAlignables){
1379  AlignmentParameters* ap = ali->alignmentParameters();
1380 
1381  HIPUserVariables* uvarold = dynamic_cast<HIPUserVariables*>(ap->userVariables());
1382  HIPUserVariables* uvarnew = dynamic_cast<HIPUserVariables*>(*iuvarnew);
1383 
1384  HIPUserVariables* uvar = uvarold->clone();
1385  uvar->datatype=theDataGroup; // Set the data type of alignable to that specified for the collector job (-2 by default)
1386 
1387  if (uvarnew!=nullptr){
1388  double peraliwgt=1;
1389  if (rewgtPerAli){
1390  int alijobdtype = uvarnew->datatype;
1391  if (
1392  ali_datatypecountpair_map.find(ali)!=ali_datatypecountpair_map.end()
1393  &&
1394  ali_datatypecountpair_map[ali].find(alijobdtype)!=ali_datatypecountpair_map[ali].end()
1395  ){
1396  peraliwgt = ali_datatypecountpair_map[ali][alijobdtype];
1397  unsigned int nNonZeroTypes=0;
1398  pawt_t sumwgts=0;
1399  for (auto it=ali_datatypecountpair_map[ali].cbegin(); it!=ali_datatypecountpair_map[ali].cend(); ++it){
1400  sumwgts+=it->second;
1401  if (it->second!=pawt_t(0)) nNonZeroTypes++;
1402  }
1403  edm::LogInfo("Alignment") << "@SUB=HIPAlignmentAlgorithm::collector"
1404  << "Reweighting detector " << ali->id() << " / " << ali->alignableObjectId()
1405  << " for data type " << alijobdtype << " by " << sumwgts << "/" << peraliwgt << "/" << nNonZeroTypes;
1406  peraliwgt=((nNonZeroTypes==0 || peraliwgt==double(0)) ? double(1) : double((double(sumwgts))/peraliwgt/(double(nNonZeroTypes))));
1407  }
1408  else if (ali_datatypecountpair_map.find(ali)!=ali_datatypecountpair_map.end())
1409  edm::LogError("Alignment") << "@SUB=HIPAlignmentAlgorithm::collector"
1410  << "Could not find data type " << alijobdtype << " for detector " << ali->id() << " / " << ali->alignableObjectId();
1411  else
1412  edm::LogError("Alignment") << "@SUB=HIPAlignmentAlgorithm::collector"
1413  << "Could not find detector " << ali->id() << " / " << ali->alignableObjectId()
1414  << " in the map ali_datatypecountpair_map";
1415  }
1416 
1417  uvar->nhit = (uvarold->nhit) + (uvarnew->nhit);
1418  uvar->jtvj = (uvarold->jtvj) + peraliwgt*(uvarnew->jtvj);
1419  uvar->jtve = (uvarold->jtve) + peraliwgt*(uvarnew->jtve);
1420  uvar->alichi2 = (uvarold->alichi2) + peraliwgt*(uvarnew->alichi2);
1421  uvar->alindof = (uvarold->alindof) + (uvarnew->alindof);
1422 
1423  delete uvarnew; // Delete new user variables as they are added
1424  }
1425 
1426  uvarvecadd.push_back(uvar);
1427  iuvarnew++;
1428  }
1429 
1430  theAlignmentParameterStore->attachUserVariables(theAlignables, uvarvecadd, ioerr);
1431 
1432  // fill Eventwise Tree
1433  if (doTrackHitMonitoring){
1434  uvfile = theCollectorPath+"/job"+str+"/"+theMonitorConfig.outfilecore;
1435  monitorFileList.push_back(uvfile);
1436  }
1437  } // end loop on jobs
1438 
1439  // Collect monitor (eventwise and hitwise) trees
1440  if (doTrackHitMonitoring) collectMonitorTrees(monitorFileList);
1441 
1442 }
1443 
1444 //------------------------------------------------------------------------------------
1445 void HIPAlignmentAlgorithm::collectMonitorTrees(const std::vector<std::string>& filenames){
1446  if (!doTrackHitMonitoring) return;
1447  if (!isCollector) throw cms::Exception("LogicError")
1448  << "[HIPAlignmentAlgorithm::collectMonitorTrees] Called in non-collector mode."
1449  << std::endl;
1450 
1451  TString theTrackMonitorTreeName=Form("T1_%i", theIteration);
1452  TString theHitMonitorTreeName=Form("T1_hit_%i", theIteration);
1453 
1454  std::vector<TFile*> finputlist;
1455  TList* eventtrees = new TList;
1456  TList* hittrees = new TList;
1457  for (std::string const& filename : filenames){
1458  TFile* finput = TFile::Open(filename.c_str(), "read");
1459  if (finput!=nullptr){
1460  TTree* tmptree;
1462  tmptree=nullptr;
1463  tmptree = (TTree*)finput->Get(theTrackMonitorTreeName);
1464  if (tmptree!=nullptr) eventtrees->Add(tmptree);
1465  }
1467  tmptree=nullptr;
1468  tmptree = (TTree*)finput->Get(theHitMonitorTreeName);
1469  if (tmptree!=nullptr) hittrees->Add((TTree*)finput->Get(theHitMonitorTreeName));
1470  }
1471  finputlist.push_back(finput);
1472  }
1473  }
1474 
1475  if (theTrackHitMonitorIORootFile!=nullptr){ // This should never happen
1476  edm::LogError("Alignment") << "@SUB=HIPAlignmentAlgorithm::collectMonitorTrees"
1477  << "Monitor file is already open while it is not supposed to be!";
1478  delete theTrackMonitorTree; theTrackMonitorTree=nullptr;
1479  delete theHitMonitorTree; theHitMonitorTree=nullptr;
1481  }
1482  theTrackHitMonitorIORootFile = TFile::Open(theMonitorConfig.outfile.c_str(), "update");
1484  if (eventtrees->GetSize()>0) theTrackMonitorTree = TTree::MergeTrees(eventtrees);
1485  if (hittrees->GetSize()>0) theHitMonitorTree = TTree::MergeTrees(hittrees);
1486  // Leave it to HIPAlignmentAlgorithm::terminate to write the trees and close theTrackHitMonitorIORootFile
1487 
1488  delete hittrees;
1489  delete eventtrees;
1490  for (TFile*& finput : finputlist) finput->Close();
1491 
1492  // Rename the trees to standard names
1493  if (theTrackMonitorTree!=nullptr) theTrackMonitorTree->SetName(theTrackMonitorTreeName);
1494  if (theHitMonitorTree!=nullptr) theHitMonitorTree->SetName(theHitMonitorTreeName);
1495 }
1496 
1497 //-----------------------------------------------------------------------------------
1499  if (ali!=nullptr){
1500  for (std::vector<HIPAlignableSpecificParameters>::iterator it=theAlignableSpecifics.begin(); it!=theAlignableSpecifics.end(); it++){
1501  if (it->matchAlignable(ali)) return &(*it);
1502  }
1503  edm::LogInfo("Alignment") << "[HIPAlignmentAlgorithm::findAlignableSpecs] Alignment object with id " << ali->id() << " / " << ali->alignableObjectId() << " could not be found. Returning default.";
1504  }
1505  return &defaultAlignableSpecs;
1506 }
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
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:6
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
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.
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:128
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
AlignablePositions readAlignableAbsolutePositions(const align::Alignables &alivec, const char *filename, int iter, int &ierr) override
read Alignable current absolute positions
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:38
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:59
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_
void writeAlignableAbsolutePositions(const align::Alignables &alivec, const char *filename, int iter, bool validCheck, int &ierr) override
write Alignable current absolute positions
int numberOfValidStripTIBHits() const
Definition: HitPattern.h:858
std::vector< edm::ParameterSet > theAPEParameterSet
align::StructureType m3_ObjId
std::unique_ptr< TFormula > theEtaFormula
std::vector< Alignable * > Alignables
Definition: Utilities.h:32
int numberOfValidPixelEndcapHits() const
Definition: HitPattern.h:848
std::vector< int > m_nhPXF
std::string outfile
align::Alignables theAlignables
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
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
std::vector< std::pair< align::Alignables, std::vector< double > > > theAPEParameters
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
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