test
CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
MillePedeAlignmentAlgorithm.cc
Go to the documentation of this file.
1 
12 
16 
18 
22 #include "Alignment/MillePedeAlignmentAlgorithm/src/Mille.h" // 'unpublished' interface located in src
27 
30 
34 
38 
39 // includes to make known that they inherit from Alignable:
43 
47 
53 
59 
61 
62 #include <fstream>
63 #include <sstream>
64 #include <algorithm>
65 #include <sys/stat.h>
66 
67 #include <TMath.h>
68 #include <TMatrixDSymEigen.h>
72 
73 // Includes for PXB survey
80 
82 
83 using namespace gbl;
84 
85 
86 // Constructor ----------------------------------------------------------------
87 //____________________________________________________
90  theConfig(cfg),
91  theMode(this->decodeMode(theConfig.getUntrackedParameter<std::string>("mode"))),
92  theDir(theConfig.getUntrackedParameter<std::string>("fileDir")),
93  theAlignmentParameterStore(nullptr),
94  theAlignables(),
95  theMinNumHits(cfg.getParameter<unsigned int>("minNumHits")),
96  theMaximalCor2D(cfg.getParameter<double>("max2Dcorrelation")),
97  theLastWrittenIov(0),
98  theGblDoubleBinary(cfg.getParameter<bool>("doubleBinary")),
99  runAtPCL_(cfg.getParameter<bool>("runAtPCL")),
100  ignoreHitsWithoutGlobalDerivatives_(cfg.getParameter<bool>("ignoreHitsWithoutGlobalDerivatives"))
101 {
102  if (!theDir.empty() && theDir.find_last_of('/') != theDir.size()-1) theDir += '/';// may need '/'
103  edm::LogInfo("Alignment") << "@SUB=MillePedeAlignmentAlgorithm" << "Start in mode '"
105  << "' with output directory '" << theDir << "'.";
106  if (this->isMode(myMilleBit)) {
107  theMille = std::make_unique<Mille>((theDir + theConfig.getParameter<std::string>("binaryFile")).c_str());// add ', false);' for text output);
108  // use same file for GBL
109  theBinary = std::make_unique<MilleBinary>((theDir + theConfig.getParameter<std::string>("binaryFile")).c_str(), theGblDoubleBinary);
110  }
111 }
112 
113 // Destructor ----------------------------------------------------------------
114 //____________________________________________________
116 {
117 }
118 
119 // Call at beginning of job ---------------------------------------------------
120 //____________________________________________________
124 {
125  if (muon) {
126  edm::LogWarning("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::initialize"
127  << "Running with AlignabeMuon not yet tested.";
128  }
129 
130  // temporary fix to avoid corrupted database output
131  if (!runAtPCL_) {
134  const auto& iov_alignments =
135  setup.get<TrackerAlignmentRcd>().validityInterval();
136  const auto& iov_surfaces =
137  setup.get<TrackerSurfaceDeformationRcd>().validityInterval();
138  const auto& iov_errors =
139  setup.get<TrackerAlignmentErrorExtendedRcd>().validityInterval();
140  if (iov_alignments.first().eventID().run() != MIN_VAL ||
141  iov_alignments.last().eventID().run() != MAX_VAL) {
142  throw cms::Exception("DatabaseError")
143  << "@SUB=MillePedeAlignmentAlgorithm::initialize"
144  << "\nTrying to apply " << setup.get<TrackerAlignmentRcd>().key().name()
145  << " with multiple IOVs in tag.\n"
146  << "Validity range is "
147  << iov_alignments.first().eventID().run() << " - "
148  << iov_alignments.last().eventID().run();
149  }
150  if (iov_surfaces.first().eventID().run() != MIN_VAL ||
151  iov_surfaces.last().eventID().run() != MAX_VAL) {
152  throw cms::Exception("DatabaseError")
153  << "@SUB=MillePedeAlignmentAlgorithm::initialize"
154  << "\nTrying to apply "
155  << setup.get<TrackerSurfaceDeformationRcd>().key().name()
156  << " with multiple IOVs in tag.\n"
157  << "Validity range is "
158  << iov_surfaces.first().eventID().run() << " - "
159  << iov_surfaces.last().eventID().run();
160  }
161  if (iov_errors.first().eventID().run() != MIN_VAL ||
162  iov_errors.last().eventID().run() != MAX_VAL) {
163  throw cms::Exception("DatabaseError")
164  << "@SUB=MillePedeAlignmentAlgorithm::initialize"
165  << "\nTrying to apply "
166  << setup.get<TrackerAlignmentErrorExtendedRcd>().key().name()
167  << " with multiple IOVs in tag.\n"
168  << "Validity range is "
169  << iov_errors.first().eventID().run() << " - "
170  << iov_errors.last().eventID().run();
171  }
172  }
173 
174 
175  //Retrieve tracker topology from geometry
176  edm::ESHandle<TrackerTopology> tTopoHandle;
177  setup.get<TrackerTopologyRcd>().get(tTopoHandle);
178  const TrackerTopology* const tTopo = tTopoHandle.product();
179 
180  theAlignableNavigator = std::make_unique<AlignableNavigator>(extras, tracker, muon);
182  theAlignables = theAlignmentParameterStore->alignables();
183 
184  edm::ParameterSet pedeLabelerCfg(theConfig.getParameter<edm::ParameterSet>("pedeLabeler"));
185  edm::VParameterSet RunRangeSelectionVPSet(theConfig.getUntrackedParameter<edm::VParameterSet>("RunRangeSelection"));
186  pedeLabelerCfg.addUntrackedParameter<edm::VParameterSet>("RunRangeSelection",
187  RunRangeSelectionVPSet);
188 
189  std::string labelerPlugin = "PedeLabeler";
190  if (RunRangeSelectionVPSet.size()>0) {
191  labelerPlugin = "RunRangeDependentPedeLabeler";
192  if (pedeLabelerCfg.exists("plugin")) {
193  std::string labelerPluginCfg = pedeLabelerCfg.getParameter<std::string>("plugin");
194  if ((labelerPluginCfg!="PedeLabeler" && labelerPluginCfg!="RunRangeDependentPedeLabeler") ||
195  pedeLabelerCfg.getUntrackedParameter<edm::VParameterSet>("parameterInstances").size()>0) {
196  throw cms::Exception("BadConfig")
197  << "MillePedeAlignmentAlgorithm::initialize"
198  << "both RunRangeSelection and generic labeler specified in config file. "
199  << "Please get rid of either one of them.\n";
200  }
201  }
202  } else {
203  if (pedeLabelerCfg.exists("plugin")) {
204  labelerPlugin = pedeLabelerCfg.getParameter<std::string>("plugin");
205  }
206  }
207 
208  if (!pedeLabelerCfg.exists("plugin")) {
209  pedeLabelerCfg.addUntrackedParameter<std::string>("plugin", labelerPlugin);
210  }
211 
212  edm::LogInfo("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::initialize"
213  << "Using plugin '" << labelerPlugin << "' to generate labels.";
214 
215  thePedeLabels = std::unique_ptr<PedeLabelerBase>(PedeLabelerPluginFactory::get()
216  ->create(labelerPlugin,
217  PedeLabelerBase::TopLevelAlignables(tracker, muon, extras),
218  pedeLabelerCfg));
219 
220  // 1) Create PedeSteerer: correct alignable positions for coordinate system selection
221  edm::ParameterSet pedeSteerCfg(theConfig.getParameter<edm::ParameterSet>("pedeSteerer"));
222  thePedeSteer = std::make_unique<PedeSteerer>(tracker, muon, extras,
224  pedeSteerCfg, theDir, !this->isMode(myPedeSteerBit));
225 
226  // 2) If requested, directly read in and apply result of previous pede run,
227  // assuming that correction from 1) was also applied to create the result:
228  const std::vector<edm::ParameterSet> mprespset
229  (theConfig.getParameter<std::vector<edm::ParameterSet> >("pedeReaderInputs"));
230  if (!mprespset.empty()) {
231  edm::LogInfo("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::initialize"
232  << "Apply " << mprespset.end() - mprespset.begin()
233  << " previous MillePede constants from 'pedeReaderInputs'.";
234  }
235 
236  // FIXME: add selection of run range via 'pedeReaderInputs'
237  // Note: Results for parameters of IntegratedCalibration's cannot be treated...
238  RunRange runrange(cond::timeTypeSpecs[cond::runnumber].beginValue,
240  for (std::vector<edm::ParameterSet>::const_iterator iSet = mprespset.begin(), iE = mprespset.end();
241  iSet != iE; ++iSet) {
242  // This read will ignore calibrations as long as they are not yet passed to Millepede
243  // during/before initialize(..) - currently addCalibrations(..) is called later in AlignmentProducer
244  if (!this->readFromPede((*iSet), false, runrange)) { // false: do not erase SelectionUserVariables
245  throw cms::Exception("BadConfig")
246  << "MillePedeAlignmentAlgorithm::initialize: Problems reading input constants of "
247  << "pedeReaderInputs entry " << iSet - mprespset.begin() << '.';
248  }
249  theAlignmentParameterStore->applyParameters();
250  // Needed to shut up later warning from checkAliParams:
251  theAlignmentParameterStore->resetParameters();
252  }
253 
254  // 3) Now create steerings with 'final' start position:
255  thePedeSteer->buildSubSteer(tracker, muon, extras);
256 
257  // After (!) 1-3 of PedeSteerer which uses the SelectionUserVariables attached to the parameters:
258  this->buildUserVariables(theAlignables); // for hit statistics and/or pede result
259 
260  if (this->isMode(myMilleBit)) {
261  if (!theConfig.getParameter<std::vector<std::string> >("mergeBinaryFiles").empty() ||
262  !theConfig.getParameter<std::vector<std::string> >("mergeTreeFiles").empty()) {
263  throw cms::Exception("BadConfig")
264  << "'vstring mergeTreeFiles' and 'vstring mergeBinaryFiles' must be empty for "
265  << "modes running mille.";
266  }
267  const std::string moniFile(theConfig.getUntrackedParameter<std::string>("monitorFile"));
268  if (moniFile.size()) theMonitor = std::make_unique<MillePedeMonitor>(tTopo, (theDir + moniFile).c_str());
269 
270  // Get trajectory factory. In case nothing found, FrameWork will throw...
271  const edm::ParameterSet fctCfg(theConfig.getParameter<edm::ParameterSet>("TrajectoryFactory"));
272  const std::string fctName(fctCfg.getParameter<std::string>("TrajectoryFactoryName"));
273  theTrajectoryFactory = std::unique_ptr<TrajectoryFactoryBase>(TrajectoryFactoryPlugin::get()
274  ->create(fctName, fctCfg));
275  }
276 
277  if (this->isMode(myPedeSteerBit)) {
278  // Get config for survey and set flag accordingly
279  const edm::ParameterSet pxbSurveyCfg(theConfig.getParameter<edm::ParameterSet>("surveyPixelBarrel"));
280  theDoSurveyPixelBarrel = pxbSurveyCfg.getParameter<bool>("doSurvey");
281  if (theDoSurveyPixelBarrel) this->addPxbSurvey(pxbSurveyCfg);
282  }
283 }
284 
285 //____________________________________________________
287  return true;
288 }
289 
290 //____________________________________________________
291 bool MillePedeAlignmentAlgorithm::addCalibrations(const std::vector<IntegratedCalibrationBase*> &iCals)
292 {
293  theCalibrations.insert(theCalibrations.end(), iCals.begin(), iCals.end());
294  thePedeLabels->addCalibrations(iCals);
295  return true;
296 }
297 
298 //_____________________________________________________________________________
300 {
301  if (isMode(myMilleBit)) {
302  return true;
303  } else {
304  return false;
305  }
306 }
307 
308 //____________________________________________________
310 {
311  if (this->isMode(myPedeReadBit)) {
312  // restore initial positions, rotations and deformations
314 
315  // Needed to shut up later warning from checkAliParams:
317  // To avoid that they keep values from previous IOV if no new one in pede result
319 
320  if (!this->readFromPede(theConfig.getParameter<edm::ParameterSet>("pedeReader"), true, runrange)) {
321  edm::LogError("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::setParametersForRunRange"
322  << "Problems reading pede result, but applying!";
323  }
325 
326  this->doIO(++theLastWrittenIov); // pre-increment!
327  }
328 
329  return true;
330 }
331 
332 // Call at end of job ---------------------------------------------------------
333 //____________________________________________________
335 {
336  terminate();
337 }
339 {
340  theMille.reset(); // delete to close binary before running pede below (flush would be enough...)
341  theBinary.reset();
342 
343  std::vector<std::string> files;
344  if (this->isMode(myMilleBit) || !theConfig.getParameter<std::string>("binaryFile").empty()) {
345  files.push_back(theDir + theConfig.getParameter<std::string>("binaryFile"));
346  } else {
347  const std::vector<std::string> plainFiles(theConfig.getParameter<std::vector<std::string> >("mergeBinaryFiles"));
348  files = getExistingFormattedFiles(plainFiles, theDir);
349  // Do some logging:
350  std::string filesForLogOutput;
351  for (const auto& file: files) filesForLogOutput += " " + file + ",";
352  if (filesForLogOutput.length() != 0) filesForLogOutput.pop_back();
353  edm::LogInfo("Alignment")
354  << "Based on the config parameter mergeBinaryFiles, using the following "
355  << "files as input (assigned weights are indicated by ' -- <weight>'):"
356  << filesForLogOutput;
357  }
358 
359  // cache all positions, rotations and deformations
361 
362  const std::string masterSteer(thePedeSteer->buildMasterSteer(files));// do only if myPedeSteerBit?
363  if (this->isMode(myPedeRunBit)) {
364  thePedeSteer->runPede(masterSteer);
365  }
366 
367  // parameters from pede are not yet applied,
368  // so we can still write start positions (but with hit statistics in case of mille):
369  this->doIO(0);
370  theLastWrittenIov = 0;
371 }
372 
373 std::vector<std::string> MillePedeAlignmentAlgorithm::getExistingFormattedFiles(const std::vector<std::string>& plainFiles, const std::string& theDir) {
374  std::vector<std::string> files;
375  for (const auto& plainFile: plainFiles) {
376  std::string theInputFileName = plainFile;
377  int theNumber = 0;
378  while (true) {
379  // Create a formatted version of the filename, with growing numbers
380  // If the parameter doesn't contain a formatting directive, it just stays unchanged
381  char theNumberedInputFileName[200];
382  sprintf(theNumberedInputFileName, theInputFileName.c_str(), theNumber);
383  std::string theCompleteInputFileName = theDir + theNumberedInputFileName;
384  const auto endOfStrippedFileName = theCompleteInputFileName.rfind(" --");
385  const auto strippedInputFileName = theCompleteInputFileName.substr(0, endOfStrippedFileName);
386  // Check if the file exists
387  struct stat buffer;
388  if (stat (strippedInputFileName.c_str(), &buffer) == 0) {
389  // If the file exists, add it to the list
390  files.push_back(theCompleteInputFileName);
391  if (theNumberedInputFileName == theInputFileName) {
392  // If the filename didn't contain a formatting directive, no reason to look any further, break out of the loop
393  break;
394  } else {
395  // Otherwise look for the next number
396  theNumber++;
397  }
398  } else {
399  // The file doesn't exist, break out of the loop
400  break;
401  }
402  }
403  // warning if unformatted (-> theNumber stays at 0) does not exist
404  if (theNumber == 0 && (files.size() == 0 || files.back() != plainFile)) {
405  edm::LogWarning("Alignment")
406  << "The input file '" << plainFile << "' does not exist.";
407  }
408  }
409  return files;
410 }
411 
412 // Run the algorithm on trajectories and tracks -------------------------------
413 //____________________________________________________
415 {
416  if (!this->isMode(myMilleBit)) return; // no theMille created...
417  const auto& tracks = eventInfo.trajTrackPairs();
418 
419  if (theMonitor) { // monitor input tracks
420  for (const auto& iTrajTrack: tracks) {
421  theMonitor->fillTrack(iTrajTrack.second);
422  }
423  }
424 
425  const RefTrajColl trajectories(theTrajectoryFactory->trajectories(setup, tracks, eventInfo.beamSpot()));
426 
427  // Now loop over ReferenceTrajectoryCollection
428  unsigned int refTrajCount = 0; // counter for track monitoring
429  const auto tracksPerTraj = theTrajectoryFactory->tracksPerTrajectory();
430  for (auto iRefTraj = trajectories.cbegin(), iRefTrajE = trajectories.cend();
431  iRefTraj != iRefTrajE; ++iRefTraj, ++refTrajCount) {
432 
433  RefTrajColl::value_type refTrajPtr = *iRefTraj;
434  if (theMonitor) theMonitor->fillRefTrajectory(refTrajPtr);
435 
436  const auto nHitXy = this->addReferenceTrajectory(setup, eventInfo, refTrajPtr);
437 
438  if (theMonitor && (nHitXy.first || nHitXy.second)) {
439  // if trajectory used (i.e. some hits), fill monitoring
440  const auto offset = tracksPerTraj*refTrajCount;
441  for (unsigned int iTrack = 0; iTrack < tracksPerTraj; ++iTrack) {
442  theMonitor->fillUsedTrack(tracks[offset+iTrack].second,
443  nHitXy.first, nHitXy.second);
444  }
445  }
446 
447  } // end of reference trajectory and track loop
448 }
449 
450 //____________________________________________________
451 std::pair<unsigned int, unsigned int>
453  const EventInfo &eventInfo,
454  const RefTrajColl::value_type &refTrajPtr)
455 {
456  std::pair<unsigned int, unsigned int> hitResultXy(0,0);
457  if (refTrajPtr->isValid()) {
458 
459 
460  // GblTrajectory?
461  if (refTrajPtr->gblInput().size() > 0) {
462  // by construction: number of GblPoints == number of recHits or == zero !!!
463  unsigned int iHit = 0;
464  unsigned int numPointsWithMeas = 0;
465  std::vector<GblPoint>::iterator itPoint;
466  std::vector<std::pair<std::vector<GblPoint>, TMatrixD> > theGblInput = refTrajPtr->gblInput();
467  for (unsigned int iTraj = 0; iTraj < refTrajPtr->gblInput().size(); ++iTraj) {
468  for (itPoint = refTrajPtr->gblInput()[iTraj].first.begin(); itPoint < refTrajPtr->gblInput()[iTraj].first.end(); ++itPoint) {
469  if (this->addGlobalData(setup, eventInfo, refTrajPtr, iHit++, *itPoint) < 0) return hitResultXy;
470  if (itPoint->hasMeasurement() >= 1) ++numPointsWithMeas;
471  }
472  }
473  hitResultXy.first = numPointsWithMeas;
474  // check #hits criterion
475  if (hitResultXy.first == 0 || hitResultXy.first < theMinNumHits) return hitResultXy;
476  // construct GBL trajectory
477  if (refTrajPtr->gblInput().size() == 1) {
478  // from single track
479  GblTrajectory aGblTrajectory( refTrajPtr->gblInput()[0].first, refTrajPtr->nominalField() != 0 );
480  // GBL fit trajectory
481  /*double Chi2;
482  int Ndf;
483  double lostWeight;
484  aGblTrajectory.fit(Chi2, Ndf, lostWeight);
485  std::cout << " GblFit: " << Chi2 << ", " << Ndf << ", " << lostWeight << std::endl; */
486  // write to MP binary file
487  if (aGblTrajectory.isValid() && aGblTrajectory.getNumPoints() >= theMinNumHits) aGblTrajectory.milleOut(*theBinary);
488  }
489  if (refTrajPtr->gblInput().size() == 2) {
490  // from TwoBodyDecay
491  GblTrajectory aGblTrajectory( refTrajPtr->gblInput(), refTrajPtr->gblExtDerivatives(), refTrajPtr->gblExtMeasurements(), refTrajPtr->gblExtPrecisions() );
492  // write to MP binary file
493  if (aGblTrajectory.isValid() && aGblTrajectory.getNumPoints() >= theMinNumHits) aGblTrajectory.milleOut(*theBinary);
494  }
495  } else {
496  // to add hits if all fine:
497  std::vector<AlignmentParameters*> parVec(refTrajPtr->recHits().size());
498  // collect hit statistics, assuming that there are no y-only hits
499  std::vector<bool> validHitVecY(refTrajPtr->recHits().size(), false);
500  // Use recHits from ReferenceTrajectory (since they have the right order!):
501  for (unsigned int iHit = 0; iHit < refTrajPtr->recHits().size(); ++iHit) {
502  const int flagXY = this->addMeasurementData(setup, eventInfo, refTrajPtr, iHit, parVec[iHit]);
503 
504  if (flagXY < 0) { // problem
505  hitResultXy.first = 0;
506  break;
507  } else { // hit is fine, increase x/y statistics
508  if (flagXY >= 1) ++hitResultXy.first;
509  validHitVecY[iHit] = (flagXY >= 2);
510  }
511  } // end loop on hits
512 
513  // add virtual measurements
514  for (unsigned int iVirtualMeas = 0; iVirtualMeas < refTrajPtr->numberOfVirtualMeas(); ++iVirtualMeas) {
515  this->addVirtualMeas(refTrajPtr, iVirtualMeas);
516  }
517 
518  // kill or end 'track' for mille, depends on #hits criterion
519  if (hitResultXy.first == 0 || hitResultXy.first < theMinNumHits) {
520  theMille->kill();
521  hitResultXy.first = hitResultXy.second = 0; //reset
522  } else {
523  theMille->end();
524  // add x/y hit count to MillePedeVariables of parVec,
525  // returning number of y-hits of the reference trajectory
526  hitResultXy.second = this->addHitCount(parVec, validHitVecY);
527  //
528  }
529  }
530 
531  } // end if valid trajectory
532 
533  return hitResultXy;
534 }
535 
536 //____________________________________________________
537 unsigned int
538 MillePedeAlignmentAlgorithm::addHitCount(const std::vector<AlignmentParameters*> &parVec,
539  const std::vector<bool> &validHitVecY) const
540 {
541  // Loop on all hit information in the input arrays and count valid y-hits:
542  unsigned int nHitY = 0;
543  for (unsigned int iHit = 0; iHit < validHitVecY.size(); ++iHit) {
544  Alignable *ali = (parVec[iHit] ? parVec[iHit]->alignable() : 0);
545  // Loop upwards on hierarchy of alignables to add hits to all levels
546  // that are currently aligned. If only a non-selected alignable was hit,
547  // (i.e. flagXY == 0 in addReferenceTrajectory(..)), there is no loop at all...
548  while (ali) {
550  if (pars) { // otherwise hierarchy level not selected
551  // cast ensured by previous checks:
552  MillePedeVariables *mpVar = static_cast<MillePedeVariables*>(pars->userVariables());
553  // every hit has an x-measurement, cf. addReferenceTrajectory(..):
554  mpVar->increaseHitsX();
555  if (validHitVecY[iHit]) {
556  mpVar->increaseHitsY();
557  if (pars == parVec[iHit]) ++nHitY; // do not count hits twice
558  }
559  }
560  ali = ali->mother();
561  }
562  }
563 
564  return nHitY;
565 }
566 
567 //____________________________________________________
569  const edm::EventSetup &setup)
570 {
571  if(runInfo.tkLasBeams() && runInfo.tkLasBeamTsoses()){
572  // LAS beam treatment
573  this->addLaserData(eventInfo, *(runInfo.tkLasBeams()), *(runInfo.tkLasBeamTsoses()));
574  }
575  if(this->isMode(myMilleBit)) theMille->flushOutputFile();
576 }
577 
578 // Implementation of endRun that DOES get called. (Because we need it.)
580  if(this->isMode(myMilleBit)) theMille->flushOutputFile();
581 }
582 
583 //____________________________________________________
585 {
586  if (!runAtPCL_) return;
587  if(this->isMode(myMilleBit)) theMille->resetOutputFile();
588 }
589 
590 //____________________________________________________
592 {
593  if (!runAtPCL_) return;
594  if(this->isMode(myMilleBit)) theMille->flushOutputFile();
595 }
596 
597 
598 //____________________________________________________
600  const EventInfo &eventInfo,
602  unsigned int iHit,
603  AlignmentParameters *&params)
604 {
605  params = 0;
606  theFloatBufferX.clear();
607  theFloatBufferY.clear();
608  theIntBuffer.clear();
609 
610  const TrajectoryStateOnSurface &tsos = refTrajPtr->trajectoryStates()[iHit];
611  const ConstRecHitPointer &recHitPtr = refTrajPtr->recHits()[iHit];
612  // ignore invalid hits
613  if (!recHitPtr->isValid()) return 0;
614 
615  // First add the derivatives from IntegratedCalibration's,
616  // should even be OK if problems for "usual" derivatives from Alignables
617  this->globalDerivativesCalibration(recHitPtr, tsos, setup, eventInfo, // input
619 
620  // get AlignableDet/Unit for this hit
621  AlignableDetOrUnitPtr alidet(theAlignableNavigator->alignableFromDetId(recHitPtr->geographicalId()));
622 
623  if (!this->globalDerivativesHierarchy(eventInfo,
624  tsos, alidet, alidet, theFloatBufferX, // 2x alidet, sic!
625  theFloatBufferY, theIntBuffer, params)) {
626  return -1; // problem
628  return 0; // empty for X: no alignable for hit, nor calibrations
629  } else {
630  // store measurement even if no alignable or calibrations
631  // -> measurement used for pede-internal track-fit
632  return this->callMille(refTrajPtr, iHit, theIntBuffer, theFloatBufferX, theFloatBufferY);
633  }
634 }
635 
636 //____________________________________________________
637 
640  unsigned int iHit, GblPoint &gblPoint)
641 {
642  AlignmentParameters* params = 0;
643  std::vector<double> theDoubleBufferX, theDoubleBufferY;
644  theDoubleBufferX.clear();
645  theDoubleBufferY.clear();
646  theIntBuffer.clear();
647  int iret = 0;
648 
649  const TrajectoryStateOnSurface &tsos = refTrajPtr->trajectoryStates()[iHit];
650  const ConstRecHitPointer &recHitPtr = refTrajPtr->recHits()[iHit];
651  // ignore invalid hits
652  if (!recHitPtr->isValid()) return 0;
653 
654  // get AlignableDet/Unit for this hit
655  AlignableDetOrUnitPtr alidet(theAlignableNavigator->alignableFromDetId(recHitPtr->geographicalId()));
656 
657  if (!this->globalDerivativesHierarchy(eventInfo,
658  tsos, alidet, alidet, theDoubleBufferX, // 2x alidet, sic!
659  theDoubleBufferY, theIntBuffer, params)) {
660  return -1; // problem
661  }
662  //calibration parameters
663  int globalLabel;
664  std::vector<IntegratedCalibrationBase::ValuesIndexPair> derivs;
665  for (auto iCalib = theCalibrations.begin(); iCalib != theCalibrations.end(); ++iCalib) {
666  // get all derivatives of this calibration // const unsigned int num =
667  (*iCalib)->derivatives(derivs, *recHitPtr, tsos, setup, eventInfo);
668  for (auto iValuesInd = derivs.begin(); iValuesInd != derivs.end(); ++iValuesInd) {
669  // transfer label and x/y derivatives
670  globalLabel = thePedeLabels->calibrationLabel(*iCalib, iValuesInd->second);
671  if (globalLabel > 0 && globalLabel <= 2147483647) {
672  theIntBuffer.push_back(globalLabel);
673  theDoubleBufferX.push_back(iValuesInd->first.first);
674  theDoubleBufferY.push_back(iValuesInd->first.second);
675  } else {
676  edm::LogError("Alignment")
677  << "@SUB=MillePedeAlignmentAlgorithm::addGlobalData"
678  << "Invalid label " << globalLabel << " <= 0 or > 2147483647";
679  }
680  }
681  }
682  unsigned int numGlobals = theIntBuffer.size();
683  if (numGlobals > 0)
684  {
685  TMatrixD globalDer(2,numGlobals);
686  for (unsigned int i = 0; i < numGlobals; ++i) {
687  globalDer(0,i) = theDoubleBufferX[i];
688  globalDer(1,i) = theDoubleBufferY[i];
689  }
690  gblPoint.addGlobals( theIntBuffer, globalDer );
691  iret = 1;
692  }
693  return iret;
694 }
695 
696 //____________________________________________________
699  const TrajectoryStateOnSurface &tsos,
700  Alignable *ali, const AlignableDetOrUnitPtr &alidet,
701  std::vector<float> &globalDerivativesX,
702  std::vector<float> &globalDerivativesY,
703  std::vector<int> &globalLabels,
704  AlignmentParameters *&lowestParams) const
705 {
706  // derivatives and labels are recursively attached
707  if (!ali) return true; // no mother might be OK
708 
709  if (false && theMonitor && alidet != ali) theMonitor->fillFrameToFrame(alidet, ali);
710 
711  AlignmentParameters *params = ali->alignmentParameters();
712 
713  if (params) {
714  if (!lowestParams) lowestParams = params; // set parameters of lowest level
715 
716  bool hasSplitParameters = thePedeLabels->hasSplitParameters(ali);
717  const unsigned int alignableLabel = thePedeLabels->alignableLabel(ali);
718 
719  if (0 == alignableLabel) { // FIXME: what about regardAllHits in Markus' code?
720  edm::LogWarning("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::globalDerivativesHierarchy"
721  << "Label not found, skip Alignable.";
722  return false;
723  }
724 
725  const std::vector<bool> &selPars = params->selector();
726  const AlgebraicMatrix derivs(params->derivatives(tsos, alidet));
727 
728  // cols: 2, i.e. x&y, rows: parameters, usually RigidBodyAlignmentParameters::N_PARAM
729  for (unsigned int iSel = 0; iSel < selPars.size(); ++iSel) {
730  if (selPars[iSel]) {
731  globalDerivativesX.push_back(derivs[iSel][kLocalX]
732  /thePedeSteer->cmsToPedeFactor(iSel));
733  if (hasSplitParameters==true) {
734  globalLabels.push_back(thePedeLabels->parameterLabel(ali, iSel, eventInfo, tsos));
735  } else {
736  globalLabels.push_back(thePedeLabels->parameterLabel(alignableLabel, iSel));
737  }
738  globalDerivativesY.push_back(derivs[iSel][kLocalY]
739  /thePedeSteer->cmsToPedeFactor(iSel));
740  }
741  }
742  // Exclude mothers if Alignable selected to be no part of a hierarchy:
743  if (thePedeSteer->isNoHiera(ali)) return true;
744  }
745  // Call recursively for mother, will stop if mother == 0:
746  return this->globalDerivativesHierarchy(eventInfo,
747  tsos, ali->mother(), alidet,
748  globalDerivativesX, globalDerivativesY,
749  globalLabels, lowestParams);
750 }
751 
752 //____________________________________________________
755  const TrajectoryStateOnSurface &tsos,
756  Alignable *ali, const AlignableDetOrUnitPtr &alidet,
757  std::vector<double> &globalDerivativesX,
758  std::vector<double> &globalDerivativesY,
759  std::vector<int> &globalLabels,
760  AlignmentParameters *&lowestParams) const
761 {
762  // derivatives and labels are recursively attached
763  if (!ali) return true; // no mother might be OK
764 
765  if (false && theMonitor && alidet != ali) theMonitor->fillFrameToFrame(alidet, ali);
766 
767  AlignmentParameters *params = ali->alignmentParameters();
768 
769  if (params) {
770  if (!lowestParams) lowestParams = params; // set parameters of lowest level
771 
772  bool hasSplitParameters = thePedeLabels->hasSplitParameters(ali);
773  const unsigned int alignableLabel = thePedeLabels->alignableLabel(ali);
774 
775  if (0 == alignableLabel) { // FIXME: what about regardAllHits in Markus' code?
776  edm::LogWarning("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::globalDerivativesHierarchy"
777  << "Label not found, skip Alignable.";
778  return false;
779  }
780 
781  const std::vector<bool> &selPars = params->selector();
782  const AlgebraicMatrix derivs(params->derivatives(tsos, alidet));
783  int globalLabel;
784 
785  // cols: 2, i.e. x&y, rows: parameters, usually RigidBodyAlignmentParameters::N_PARAM
786  for (unsigned int iSel = 0; iSel < selPars.size(); ++iSel) {
787  if (selPars[iSel]) {
788  if (hasSplitParameters==true) {
789  globalLabel = thePedeLabels->parameterLabel(ali, iSel, eventInfo, tsos);
790  } else {
791  globalLabel = thePedeLabels->parameterLabel(alignableLabel, iSel);
792  }
793  if (globalLabel > 0 && globalLabel <= 2147483647) {
794  globalLabels.push_back(globalLabel);
795  globalDerivativesX.push_back(derivs[iSel][kLocalX] / thePedeSteer->cmsToPedeFactor(iSel));
796  globalDerivativesY.push_back(derivs[iSel][kLocalY] / thePedeSteer->cmsToPedeFactor(iSel));
797  } else {
798  edm::LogError("Alignment")
799  << "@SUB=MillePedeAlignmentAlgorithm::globalDerivativesHierarchy"
800  << "Invalid label " << globalLabel << " <= 0 or > 2147483647";
801  }
802  }
803  }
804  // Exclude mothers if Alignable selected to be no part of a hierarchy:
805  if (thePedeSteer->isNoHiera(ali)) return true;
806  }
807  // Call recursively for mother, will stop if mother == 0:
808  return this->globalDerivativesHierarchy(eventInfo,
809  tsos, ali->mother(), alidet,
810  globalDerivativesX, globalDerivativesY,
811  globalLabels, lowestParams);
812 }
813 
814 //____________________________________________________
817  const TrajectoryStateOnSurface &tsos,
818  const edm::EventSetup &setup, const EventInfo &eventInfo,
819  std::vector<float> &globalDerivativesX,
820  std::vector<float> &globalDerivativesY,
821  std::vector<int> &globalLabels) const
822 {
823  std::vector<IntegratedCalibrationBase::ValuesIndexPair> derivs;
824  for (auto iCalib = theCalibrations.begin(); iCalib != theCalibrations.end(); ++iCalib) {
825  // get all derivatives of this calibration // const unsigned int num =
826  (*iCalib)->derivatives(derivs, *recHit, tsos, setup, eventInfo);
827  for (auto iValuesInd = derivs.begin(); iValuesInd != derivs.end(); ++iValuesInd) {
828  // transfer label and x/y derivatives
829  globalLabels.push_back(thePedeLabels->calibrationLabel(*iCalib, iValuesInd->second));
830  globalDerivativesX.push_back(iValuesInd->first.first);
831  globalDerivativesY.push_back(iValuesInd->first.second);
832  }
833  }
834 }
835 
836 // //____________________________________________________
837 // void MillePedeAlignmentAlgorithm
838 // ::callMille(const ReferenceTrajectoryBase::ReferenceTrajectoryPtr &refTrajPtr,
839 // unsigned int iTrajHit, MeasurementDirection xOrY,
840 // const std::vector<float> &globalDerivatives, const std::vector<int> &globalLabels)
841 // {
842 // const unsigned int xyIndex = iTrajHit*2 + xOrY;
843 // // FIXME: here for residuum and sigma we could use KALMAN-Filter results
844 // const float residuum =
845 // refTrajPtr->measurements()[xyIndex] - refTrajPtr->trajectoryPositions()[xyIndex];
846 // const float covariance = refTrajPtr->measurementErrors()[xyIndex][xyIndex];
847 // const float sigma = (covariance > 0. ? TMath::Sqrt(covariance) : 0.);
848 
849 // const AlgebraicMatrix &locDerivMatrix = refTrajPtr->derivatives();
850 
851 // std::vector<float> localDerivs(locDerivMatrix.num_col());
852 // for (unsigned int i = 0; i < localDerivs.size(); ++i) {
853 // localDerivs[i] = locDerivMatrix[xyIndex][i];
854 // }
855 
856 // // &(vector[0]) is valid - as long as vector is not empty
857 // // cf. http://www.parashift.com/c++-faq-lite/containers.html#faq-34.3
858 // theMille->mille(localDerivs.size(), &(localDerivs[0]),
859 // globalDerivatives.size(), &(globalDerivatives[0]), &(globalLabels[0]),
860 // residuum, sigma);
861 // if (theMonitor) {
862 // theMonitor->fillDerivatives(refTrajPtr->recHits()[iTrajHit],localDerivs, globalDerivatives,
863 // (xOrY == kLocalY));
864 // theMonitor->fillResiduals(refTrajPtr->recHits()[iTrajHit],
865 // refTrajPtr->trajectoryStates()[iTrajHit],
866 // iTrajHit, residuum, sigma, (xOrY == kLocalY));
867 // }
868 // }
869 
870 //____________________________________________________
872 {
873  // FIXME: Check whether this is a reliable and recommended way to find out...
874 
875  if (recHit->dimension() < 2) {
876  return false; // some muon and TIB/TOB stuff really has RecHit1D
877  } else if (recHit->detUnit()) { // detunit in strip is 1D, in pixel 2D
878  return recHit->detUnit()->type().isTrackerPixel();
879  } else { // stereo strips (FIXME: endcap trouble due to non-parallel strips (wedge sensors)?)
880  if (dynamic_cast<const ProjectedSiStripRecHit2D*>(recHit->hit())) { // check persistent hit
881  // projected: 1D measurement on 'glued' module
882  return false;
883  } else {
884  return true;
885  }
886  }
887 }
888 
889 //__________________________________________________________________________________________________
890 bool MillePedeAlignmentAlgorithm::readFromPede(const edm::ParameterSet &mprespset, bool setUserVars,
891  const RunRange &runrange)
892 {
893  bool allEmpty = this->areEmptyParams(theAlignables);
894 
895  PedeReader reader(mprespset, *thePedeSteer, *thePedeLabels, runrange);
896  std::vector<Alignable*> alis;
897  bool okRead = reader.read(alis, setUserVars); // also may set params of IntegratedCalibration's
898  bool numMatch = true;
899 
900  std::stringstream out;
901  out << "Read " << alis.size() << " alignables";
902  if (alis.size() != theAlignables.size()) {
903  out << " while " << theAlignables.size() << " in store";
904  numMatch = false; // FIXME: Should we check one by one? Or transfer 'alis' to the store?
905  }
906  if (!okRead) out << ", but problems in reading";
907  if (!allEmpty) out << ", possibly overwriting previous settings";
908  out << ".";
909 
910  if (okRead && allEmpty) {
911  if (numMatch) { // as many alignables with result as trying to align
912  edm::LogInfo("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::readFromPede" << out.str();
913  } else if (alis.size()) { // dead module do not get hits and no pede result
914  edm::LogWarning("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::readFromPede" << out.str();
915  } else { // serious problem: no result read - and not all modules can be dead...
916  edm::LogError("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::readFromPede" << out.str();
917  return false;
918  }
919  return true;
920  }
921  // the rest is not OK:
922  edm::LogError("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::readFromPede" << out.str();
923  return false;
924 }
925 
926 //__________________________________________________________________________________________________
927 bool MillePedeAlignmentAlgorithm::areEmptyParams(const std::vector<Alignable*> &alignables) const
928 {
929 
930  for (std::vector<Alignable*>::const_iterator iAli = alignables.begin();
931  iAli != alignables.end(); ++iAli) {
932  const AlignmentParameters *params = (*iAli)->alignmentParameters();
933  if (params) {
934  const AlgebraicVector &parVec(params->parameters());
935  const AlgebraicMatrix &parCov(params->covariance());
936  for (int i = 0; i < parVec.num_row(); ++i) {
937  if (parVec[i] != 0.) return false;
938  for (int j = i; j < parCov.num_col(); ++j) {
939  if (parCov[i][j] != 0.) return false;
940  }
941  }
942  }
943  }
944 
945  return true;
946 }
947 
948 //__________________________________________________________________________________________________
950 {
951  unsigned int result = 0;
952 
953  const std::string outFilePlain(theConfig.getParameter<std::string>("treeFile"));
954  if (outFilePlain.empty()) {
955  edm::LogInfo("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::doIO"
956  << "treeFile parameter empty => skip writing for 'loop' " << loop;
957  return result;
958  }
959 
960  const std::string outFile(theDir + outFilePlain);
961 
962  AlignmentIORoot aliIO;
963  int ioerr = 0;
964  if (loop == 0) {
965  aliIO.writeAlignableOriginalPositions(theAlignables, outFile.c_str(), loop, false, ioerr);
966  if (ioerr) {
967  edm::LogError("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::doIO"
968  << "Problem " << ioerr << " in writeAlignableOriginalPositions";
969  ++result;
970  }
971  } else if (loop == 1) {
972  // only for first iov add hit counts, else 2x, 3x,... number of hits in IOV 2, 3,...
973  const std::vector<std::string> inFiles
974  (theConfig.getParameter<std::vector<std::string> >("mergeTreeFiles"));
975  const std::vector<std::string> binFiles
976  (theConfig.getParameter<std::vector<std::string> >("mergeBinaryFiles"));
977  if (inFiles.size() != binFiles.size()) {
978  edm::LogWarning("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::doIO"
979  << "'vstring mergeTreeFiles' and 'vstring mergeBinaryFiles' "
980  << "differ in size";
981  }
982  this->addHitStatistics(0, outFile, inFiles); // add hit info from tree 0 in 'infiles'
983  }
984  MillePedeVariablesIORoot millePedeIO;
985  millePedeIO.writeMillePedeVariables(theAlignables, outFile.c_str(), loop, false, ioerr);
986  if (ioerr) {
987  edm::LogError("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::doIO"
988  << "Problem " << ioerr << " writing MillePedeVariables";
989  ++result;
990  }
991 
992  aliIO.writeOrigRigidBodyAlignmentParameters(theAlignables, outFile.c_str(), loop, false, ioerr);
993  if (ioerr) {
994  edm::LogError("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::doIO" << "Problem " << ioerr
995  << " in writeOrigRigidBodyAlignmentParameters, " << loop;
996  ++result;
997  }
998  aliIO.writeAlignableAbsolutePositions(theAlignables, outFile.c_str(), loop, false, ioerr);
999  if (ioerr) {
1000  edm::LogError("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::doIO" << "Problem " << ioerr
1001  << " in writeAlignableAbsolutePositions, " << loop;
1002  ++result;
1003  }
1004 
1005  return result;
1006 }
1007 
1008 //__________________________________________________________________________________________________
1009 void MillePedeAlignmentAlgorithm::buildUserVariables(const std::vector<Alignable*> &alis) const
1010 {
1011  for (std::vector<Alignable*>::const_iterator iAli = alis.begin(); iAli != alis.end(); ++iAli) {
1012  AlignmentParameters *params = (*iAli)->alignmentParameters();
1013  if (!params) {
1014  throw cms::Exception("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::buildUserVariables"
1015  << "No parameters for alignable";
1016  }
1017  MillePedeVariables *userVars = dynamic_cast<MillePedeVariables*>(params->userVariables());
1018  if (userVars) { // Just re-use existing, keeping label and numHits:
1019  for (unsigned int iPar = 0; iPar < userVars->size(); ++iPar) {
1020  // if (params->hierarchyLevel() > 0) {
1021  //std::cout << params->hierarchyLevel() << "\nBefore: " << userVars->parameter()[iPar];
1022  // }
1023  userVars->setAllDefault(iPar);
1024  //std::cout << "\nAfter: " << userVars->parameter()[iPar] << std::endl;
1025  }
1026  } else { // Nothing yet or erase wrong type:
1027  userVars = new MillePedeVariables(params->size(), thePedeLabels->alignableLabel(*iAli));
1028  params->setUserVariables(userVars);
1029  }
1030  }
1031 }
1032 
1033 //__________________________________________________________________________________________________
1035 {
1036  if (mode == "full") {
1038  } else if (mode == "mille") {
1039  return myMilleBit; // + myPedeSteerBit; // sic! Including production of steerig file. NO!
1040  } else if (mode == "pede") {
1042  } else if (mode == "pedeSteer") {
1043  return myPedeSteerBit;
1044  } else if (mode == "pedeRun") {
1045  return myPedeSteerBit + myPedeRunBit + myPedeReadBit; // sic! Including steering and reading of result.
1046  } else if (mode == "pedeRead") {
1047  return myPedeReadBit;
1048  }
1049 
1050  throw cms::Exception("BadConfig")
1051  << "Unknown mode '" << mode
1052  << "', use 'full', 'mille', 'pede', 'pedeRun', 'pedeSteer' or 'pedeRead'.";
1053 
1054  return 0;
1055 }
1056 
1057 //__________________________________________________________________________________________________
1059  const std::vector<std::string> &inFiles) const
1060 {
1061  bool allOk = true;
1062  int ierr = 0;
1063  MillePedeVariablesIORoot millePedeIO;
1064  for (std::vector<std::string>::const_iterator iFile = inFiles.begin();
1065  iFile != inFiles.end(); ++iFile) {
1066  const std::string inFile(theDir + *iFile);
1067  const std::vector<AlignmentUserVariables*> mpVars =
1068  millePedeIO.readMillePedeVariables(theAlignables, inFile.c_str(), fromIov, ierr);
1069  if (ierr || !this->addHits(theAlignables, mpVars)) {
1070  edm::LogError("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::addHitStatistics"
1071  << "Error " << ierr << " reading from " << inFile
1072  << ", tree " << fromIov << ", or problems in addHits";
1073  allOk = false;
1074  }
1075  for (std::vector<AlignmentUserVariables*>::const_iterator i = mpVars.begin();
1076  i != mpVars.end(); ++i) {
1077  delete *i; // clean created objects
1078  }
1079  }
1080 
1081  return allOk;
1082 }
1083 
1084 //__________________________________________________________________________________________________
1085 bool MillePedeAlignmentAlgorithm::addHits(const std::vector<Alignable*> &alis,
1086  const std::vector<AlignmentUserVariables*> &mpVars) const
1087 {
1088  bool allOk = (mpVars.size() == alis.size());
1089  std::vector<AlignmentUserVariables*>::const_iterator iUser = mpVars.begin();
1090  for (std::vector<Alignable*>::const_iterator iAli = alis.begin();
1091  iAli != alis.end() && iUser != mpVars.end(); ++iAli, ++iUser) {
1092  MillePedeVariables *mpVarNew = dynamic_cast<MillePedeVariables*>(*iUser);
1093  AlignmentParameters *ps = (*iAli)->alignmentParameters();
1094  MillePedeVariables *mpVarOld = (ps ? dynamic_cast<MillePedeVariables*>(ps->userVariables()) : 0);
1095  if (!mpVarNew || !mpVarOld || mpVarOld->size() != mpVarNew->size()) {
1096  allOk = false;
1097  continue; // FIXME error etc.?
1098  }
1099 
1100  mpVarOld->increaseHitsX(mpVarNew->hitsX());
1101  mpVarOld->increaseHitsY(mpVarNew->hitsY());
1102  }
1103 
1104  return allOk;
1105 }
1106 
1107 //__________________________________________________________________________________________________
1108 void MillePedeAlignmentAlgorithm::makeGlobDerivMatrix(const std::vector<float> &globalDerivativesx,
1109  const std::vector<float> &globalDerivativesy,
1110  TMatrixF &aGlobalDerivativesM)
1111 {
1112 
1113  for (unsigned int i = 0; i < globalDerivativesx.size(); ++i) {
1114  aGlobalDerivativesM(0,i) = globalDerivativesx[i];
1115  aGlobalDerivativesM(1,i) = globalDerivativesy[i];
1116  }
1117 }
1118 
1119 //__________________________________________________________________________________________________
1121 (TMatrixDSym &aHitCovarianceM, TMatrixF &aLocalDerivativesM, TMatrixF &aHitResidualsM,
1122  TMatrixF &aGlobalDerivativesM) const
1123 {
1124  TMatrixDSymEigen myDiag(aHitCovarianceM);
1125  TMatrixD aTranfoToDiagonalSystem = myDiag.GetEigenVectors();
1126  TMatrixD aTranfoToDiagonalSystemInv = myDiag.GetEigenVectors( );
1127  TMatrixF aTranfoToDiagonalSystemInvF = myDiag.GetEigenVectors( );
1128  TMatrixD aMatrix = aTranfoToDiagonalSystemInv.Invert() * aHitCovarianceM * aTranfoToDiagonalSystem;
1129  // Tranformation of matrix M is done by A^T*M*A, not A^{-1}*M*A.
1130  // But here A^T == A^{-1}, so we would only save CPU by Transpose()...
1131  // FIXME this - I guess simply use T(), not Transpose()...
1132  // TMatrixD aMatrix = aTranfoToDiagonalSystemInv.Transpose() * aHitCovarianceM
1133  // * aTranfoToDiagonalSystem;
1134  aHitCovarianceM = TMatrixDSym(2, aMatrix.GetMatrixArray());
1135  aTranfoToDiagonalSystemInvF.Invert();
1136  //edm::LogInfo("Alignment") << "NEW HIT loca in matrix"<<aLocalDerivativesM(0,0);
1137  aLocalDerivativesM = aTranfoToDiagonalSystemInvF * aLocalDerivativesM;
1138 
1139  //edm::LogInfo("Alignment") << "NEW HIT loca in matrix after diag:"<<aLocalDerivativesM(0,0);
1140  aHitResidualsM = aTranfoToDiagonalSystemInvF * aHitResidualsM;
1141  if (aGlobalDerivativesM.GetNoElements() > 0) {
1142  // diagnoalize only if measurement depends on alignables or calibrations
1143  aGlobalDerivativesM = aTranfoToDiagonalSystemInvF * aGlobalDerivativesM;
1144  }
1145 }
1146 
1147 //__________________________________________________________________________________________________
1150  unsigned int iVirtualMeas, TMatrixDSym &aHitCovarianceM,
1151  TMatrixF &aHitResidualsM, TMatrixF &aLocalDerivativesM)
1152 {
1153  // This Method is valid for 1D measurements only
1154 
1155  const unsigned int xIndex = iVirtualMeas + refTrajPtr->numberOfHitMeas();
1156  // Covariance into a TMatrixDSym
1157 
1158  //aHitCovarianceM = new TMatrixDSym(1);
1159  aHitCovarianceM(0,0)=refTrajPtr->measurementErrors()[xIndex][xIndex];
1160 
1161  //theHitResidualsM= new TMatrixF(1,1);
1162  aHitResidualsM(0,0)= refTrajPtr->measurements()[xIndex];
1163 
1164  // Local Derivatives into a TMatrixDSym (to use matrix operations)
1165  const AlgebraicMatrix &locDerivMatrix = refTrajPtr->derivatives();
1166  // theLocalDerivativeNumber = locDerivMatrix.num_col();
1167 
1168  //theLocalDerivativesM = new TMatrixF(1,locDerivMatrix.num_col());
1169  for (int i = 0; i < locDerivMatrix.num_col(); ++i) {
1170  aLocalDerivativesM(0,i) = locDerivMatrix[xIndex][i];
1171  }
1172 }
1173 
1174 //__________________________________________________________________________________________________
1177  unsigned int iTrajHit, TMatrixDSym &aHitCovarianceM,
1178  TMatrixF &aHitResidualsM, TMatrixF &aLocalDerivativesM)
1179 {
1180  // This Method is valid for 2D measurements only
1181 
1182  const unsigned int xIndex = iTrajHit*2;
1183  const unsigned int yIndex = iTrajHit*2+1;
1184  // Covariance into a TMatrixDSym
1185 
1186  //aHitCovarianceM = new TMatrixDSym(2);
1187  aHitCovarianceM(0,0)=refTrajPtr->measurementErrors()[xIndex][xIndex];
1188  aHitCovarianceM(0,1)=refTrajPtr->measurementErrors()[xIndex][yIndex];
1189  aHitCovarianceM(1,0)=refTrajPtr->measurementErrors()[yIndex][xIndex];
1190  aHitCovarianceM(1,1)=refTrajPtr->measurementErrors()[yIndex][yIndex];
1191 
1192  //theHitResidualsM= new TMatrixF(2,1);
1193  aHitResidualsM(0,0)= refTrajPtr->measurements()[xIndex] - refTrajPtr->trajectoryPositions()[xIndex];
1194  aHitResidualsM(1,0)= refTrajPtr->measurements()[yIndex] - refTrajPtr->trajectoryPositions()[yIndex];
1195 
1196  // Local Derivatives into a TMatrixDSym (to use matrix operations)
1197  const AlgebraicMatrix &locDerivMatrix = refTrajPtr->derivatives();
1198  // theLocalDerivativeNumber = locDerivMatrix.num_col();
1199 
1200  //theLocalDerivativesM = new TMatrixF(2,locDerivMatrix.num_col());
1201  for (int i = 0; i < locDerivMatrix.num_col(); ++i) {
1202  aLocalDerivativesM(0,i) = locDerivMatrix[xIndex][i];
1203  aLocalDerivativesM(1,i) = locDerivMatrix[yIndex][i];
1204  }
1205 }
1206 
1207 //__________________________________________________________________________________________________
1210  unsigned int iTrajHit, const std::vector<int> &globalLabels,
1211  const std::vector<float> &globalDerivativesX,
1212  const std::vector<float> &globalDerivativesY)
1213 {
1214  const ConstRecHitPointer aRecHit(refTrajPtr->recHits()[iTrajHit]);
1215 
1216  if((aRecHit)->dimension() == 1) {
1217  return this->callMille1D(refTrajPtr, iTrajHit, globalLabels, globalDerivativesX);
1218  } else {
1219  return this->callMille2D(refTrajPtr, iTrajHit, globalLabels,
1220  globalDerivativesX, globalDerivativesY);
1221  }
1222 }
1223 
1224 
1225 //__________________________________________________________________________________________________
1228  unsigned int iTrajHit, const std::vector<int> &globalLabels,
1229  const std::vector<float> &globalDerivativesX)
1230 {
1231  const ConstRecHitPointer aRecHit(refTrajPtr->recHits()[iTrajHit]);
1232  const unsigned int xIndex = iTrajHit*2; // the even ones are local x
1233 
1234  // local derivatives
1235  const AlgebraicMatrix &locDerivMatrix = refTrajPtr->derivatives();
1236  const int nLocal = locDerivMatrix.num_col();
1237  std::vector<float> localDerivatives(nLocal);
1238  for (unsigned int i = 0; i < localDerivatives.size(); ++i) {
1239  localDerivatives[i] = locDerivMatrix[xIndex][i];
1240  }
1241 
1242  // residuum and error
1243  float residX = refTrajPtr->measurements()[xIndex] - refTrajPtr->trajectoryPositions()[xIndex];
1244  float hitErrX = TMath::Sqrt(refTrajPtr->measurementErrors()[xIndex][xIndex]);
1245 
1246  // number of global derivatives
1247  const int nGlobal = globalDerivativesX.size();
1248 
1249  // &(localDerivatives[0]) etc. are valid - as long as vector is not empty
1250  // cf. http://www.parashift.com/c++-faq-lite/containers.html#faq-34.3
1251  theMille->mille(nLocal, &(localDerivatives[0]), nGlobal, &(globalDerivativesX[0]),
1252  &(globalLabels[0]), residX, hitErrX);
1253 
1254  if (theMonitor) {
1255  theMonitor->fillDerivatives(aRecHit, &(localDerivatives[0]), nLocal,
1256  &(globalDerivativesX[0]), nGlobal, &(globalLabels[0]));
1257  theMonitor->fillResiduals(aRecHit, refTrajPtr->trajectoryStates()[iTrajHit],
1258  iTrajHit, residX, hitErrX, false);
1259  }
1260 
1261  return 1;
1262 }
1263 
1264 //__________________________________________________________________________________________________
1267  unsigned int iTrajHit, const std::vector<int> &globalLabels,
1268  const std::vector<float> &globalDerivativesx,
1269  const std::vector<float> &globalDerivativesy)
1270 {
1271  const ConstRecHitPointer aRecHit(refTrajPtr->recHits()[iTrajHit]);
1272 
1273  if((aRecHit)->dimension() != 2) {
1274  edm::LogError("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::callMille2D"
1275  << "You try to call method for 2D hits for a "
1276  << (aRecHit)->dimension()
1277  << "D Hit. Hit gets ignored!";
1278  return -1;
1279  }
1280 
1281  TMatrixDSym aHitCovarianceM(2);
1282  TMatrixF aHitResidualsM(2,1);
1283  TMatrixF aLocalDerivativesM(2, refTrajPtr->derivatives().num_col());
1284  // below method fills above 3 matrices
1285  this->addRefTrackData2D(refTrajPtr, iTrajHit, aHitCovarianceM,aHitResidualsM,aLocalDerivativesM);
1286  TMatrixF aGlobalDerivativesM(2,globalDerivativesx.size());
1287  this->makeGlobDerivMatrix(globalDerivativesx, globalDerivativesy, aGlobalDerivativesM);
1288 
1289  // calculates correlation between Hit measurements
1290  // FIXME: Should take correlation (and resulting transformation) from original hit,
1291  // not 2x2 matrix from ReferenceTrajectory: That can come from error propagation etc.!
1292  const double corr = aHitCovarianceM(0,1) / sqrt(aHitCovarianceM(0,0) * aHitCovarianceM(1,1));
1293  if (theMonitor) theMonitor->fillCorrelations2D(corr, aRecHit);
1294  bool diag = false; // diagonalise only tracker TID, TEC
1295  switch(aRecHit->geographicalId().subdetId()) {
1296  case SiStripDetId::TID:
1297  case SiStripDetId::TEC:
1298  if (aRecHit->geographicalId().det() == DetId::Tracker && TMath::Abs(corr) > theMaximalCor2D) {
1299  this->diagonalize(aHitCovarianceM, aLocalDerivativesM, aHitResidualsM, aGlobalDerivativesM);
1300  diag = true;
1301  }
1302  break;
1303  default:;
1304  }
1305 
1306  float newResidX = aHitResidualsM(0,0);
1307  float newResidY = aHitResidualsM(1,0);
1308  float newHitErrX = TMath::Sqrt(aHitCovarianceM(0,0));
1309  float newHitErrY = TMath::Sqrt(aHitCovarianceM(1,1));
1310  float *newLocalDerivsX = aLocalDerivativesM[0].GetPtr();
1311  float *newLocalDerivsY = aLocalDerivativesM[1].GetPtr();
1312  float *newGlobDerivsX = aGlobalDerivativesM[0].GetPtr();
1313  float *newGlobDerivsY = aGlobalDerivativesM[1].GetPtr();
1314  const int nLocal = aLocalDerivativesM.GetNcols();
1315  const int nGlobal = aGlobalDerivativesM.GetNcols();
1316 
1317  if (diag && (newHitErrX > newHitErrY)) { // also for 2D hits?
1318  // measurement with smaller error is x-measurement (for !is2D do not fill y-measurement):
1319  std::swap(newResidX, newResidY);
1320  std::swap(newHitErrX, newHitErrY);
1321  std::swap(newLocalDerivsX, newLocalDerivsY);
1322  std::swap(newGlobDerivsX, newGlobDerivsY);
1323  }
1324 
1325  // &(globalLabels[0]) is valid - as long as vector is not empty
1326  // cf. http://www.parashift.com/c++-faq-lite/containers.html#faq-34.3
1327  theMille->mille(nLocal, newLocalDerivsX, nGlobal, newGlobDerivsX,
1328  &(globalLabels[0]), newResidX, newHitErrX);
1329 
1330  if (theMonitor) {
1331  theMonitor->fillDerivatives(aRecHit, newLocalDerivsX, nLocal, newGlobDerivsX, nGlobal,
1332  &(globalLabels[0]));
1333  theMonitor->fillResiduals(aRecHit, refTrajPtr->trajectoryStates()[iTrajHit],
1334  iTrajHit, newResidX, newHitErrX, false);
1335  }
1336  const bool isReal2DHit = this->is2D(aRecHit); // strip is 1D (except matched hits)
1337  if (isReal2DHit) {
1338  theMille->mille(nLocal, newLocalDerivsY, nGlobal, newGlobDerivsY,
1339  &(globalLabels[0]), newResidY, newHitErrY);
1340  if (theMonitor) {
1341  theMonitor->fillDerivatives(aRecHit, newLocalDerivsY, nLocal, newGlobDerivsY, nGlobal,
1342  &(globalLabels[0]));
1343  theMonitor->fillResiduals(aRecHit, refTrajPtr->trajectoryStates()[iTrajHit],
1344  iTrajHit, newResidY, newHitErrY, true);// true: y
1345  }
1346  }
1347 
1348  return (isReal2DHit ? 2 : 1);
1349 }
1350 
1351 //__________________________________________________________________________________________________
1353 ::addVirtualMeas(const ReferenceTrajectoryBase::ReferenceTrajectoryPtr &refTrajPtr, unsigned int iVirtualMeas)
1354 {
1355  TMatrixDSym aHitCovarianceM(1);
1356  TMatrixF aHitResidualsM(1,1);
1357  TMatrixF aLocalDerivativesM(1, refTrajPtr->derivatives().num_col());
1358  // below method fills above 3 'matrices'
1359  this->addRefTrackVirtualMeas1D(refTrajPtr, iVirtualMeas, aHitCovarianceM, aHitResidualsM, aLocalDerivativesM);
1360 
1361  // no global parameters (use dummy 0)
1362  TMatrixF aGlobalDerivativesM(1,1);
1363  aGlobalDerivativesM(0,0) = 0;
1364 
1365  float newResidX = aHitResidualsM(0,0);
1366  float newHitErrX = TMath::Sqrt(aHitCovarianceM(0,0));
1367  float *newLocalDerivsX = aLocalDerivativesM[0].GetPtr();
1368  float *newGlobDerivsX = aGlobalDerivativesM[0].GetPtr();
1369  const int nLocal = aLocalDerivativesM.GetNcols();
1370  const int nGlobal = 0;
1371 
1372  theMille->mille(nLocal, newLocalDerivsX, nGlobal, newGlobDerivsX,
1373  &nGlobal, newResidX, newHitErrX);
1374 }
1375 
1376 //____________________________________________________
1378  const TkFittedLasBeamCollection &lasBeams,
1379  const TsosVectorCollection &lasBeamTsoses)
1380 {
1381  TsosVectorCollection::const_iterator iTsoses = lasBeamTsoses.begin();
1382  for(TkFittedLasBeamCollection::const_iterator iBeam = lasBeams.begin(), iEnd = lasBeams.end();
1383  iBeam != iEnd; ++iBeam, ++iTsoses){ // beam/tsoses parallel!
1384 
1385  edm::LogInfo("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::addLaserData"
1386  << "Beam " << iBeam->getBeamId() << " with "
1387  << iBeam->parameters().size() << " parameters and "
1388  << iBeam->getData().size() << " hits.\n There are "
1389  << iTsoses->size() << " TSOSes.";
1390 
1391  this->addLasBeam(eventInfo, *iBeam, *iTsoses);
1392  }
1393 }
1394 
1395 //____________________________________________________
1397  const TkFittedLasBeam &lasBeam,
1398  const std::vector<TrajectoryStateOnSurface> &tsoses)
1399 {
1400  AlignmentParameters *dummyPtr = 0; // for globalDerivativesHierarchy()
1401  std::vector<float> lasLocalDerivsX; // buffer for local derivatives
1402  const unsigned int beamLabel = thePedeLabels->lasBeamLabel(lasBeam.getBeamId());// for global par
1403 
1404  for (unsigned int iHit = 0; iHit < tsoses.size(); ++iHit) {
1405  if (!tsoses[iHit].isValid()) continue;
1406  // clear buffer
1407  theFloatBufferX.clear();
1408  theFloatBufferY.clear();
1409  theIntBuffer.clear();
1410  lasLocalDerivsX.clear();
1411  // get alignables and global parameters
1412  const SiStripLaserRecHit2D &hit = lasBeam.getData()[iHit];
1413  AlignableDetOrUnitPtr lasAli(theAlignableNavigator->alignableFromDetId(hit.getDetId()));
1414  this->globalDerivativesHierarchy(eventInfo,
1415  tsoses[iHit], lasAli, lasAli,
1417  // fill derivatives vector from derivatives matrix
1418  for (unsigned int nFitParams = 0;
1419  nFitParams < static_cast<unsigned int>(lasBeam.parameters().size());
1420  ++nFitParams) {
1421  const float derivative = lasBeam.derivatives()[iHit][nFitParams];
1422  if (nFitParams < lasBeam.firstFixedParameter()) { // first local beam parameters
1423  lasLocalDerivsX.push_back(derivative);
1424  } else { // now global ones
1425  const unsigned int numPar = nFitParams - lasBeam.firstFixedParameter();
1426  theIntBuffer.push_back(thePedeLabels->parameterLabel(beamLabel, numPar));
1427  theFloatBufferX.push_back(derivative);
1428  }
1429  } // end loop over parameters
1430 
1431  const float residual = hit.localPosition().x() - tsoses[iHit].localPosition().x();
1432  // error from file or assume 0.003
1433  const float error = 0.003; // hit.localPositionError().xx(); sqrt???
1434 
1435  theMille->mille(lasLocalDerivsX.size(), &(lasLocalDerivsX[0]), theFloatBufferX.size(),
1436  &(theFloatBufferX[0]), &(theIntBuffer[0]), residual, error);
1437  } // end of loop over hits
1438 
1439  theMille->end();
1440 }
1441 
1443 {
1444  // do some printing, if requested
1445  const bool doOutputOnStdout(pxbSurveyCfg.getParameter<bool>("doOutputOnStdout"));
1446  if (doOutputOnStdout) {
1447  edm::LogInfo("Alignment")
1448  << "@SUB=MillePedeAlignmentAlgorithm::addPxbSurvey"
1449  << "# Output from addPxbSurvey follows below because "
1450  << "doOutputOnStdout is set to True";
1451  }
1452 
1453  // instantiate a dicer object
1454  SurveyPxbDicer dicer(pxbSurveyCfg.getParameter<std::vector<edm::ParameterSet> >("toySurveyParameters"), pxbSurveyCfg.getParameter<unsigned int>("toySurveySeed"));
1455  std::ofstream outfile(pxbSurveyCfg.getUntrackedParameter<std::string>("toySurveyFile").c_str());
1456 
1457  // read data from file
1458  std::vector<SurveyPxbImageLocalFit> measurements;
1459  std::string filename(pxbSurveyCfg.getParameter<edm::FileInPath>("infile").fullPath());
1461 
1462  // loop over photographs (=measurements) and perform the fit
1463  for(std::vector<SurveyPxbImageLocalFit>::size_type i=0; i!=measurements.size(); i++)
1464  {
1465  if (doOutputOnStdout) {
1466  edm::LogInfo("Alignment")
1467  << "@SUB=MillePedeAlignmentAlgorithm::addPxbSurvey"
1468  << "Module " << i << ": ";
1469  }
1470 
1471  // get the Alignables and their surfaces
1472  AlignableDetOrUnitPtr mod1(theAlignableNavigator->alignableFromDetId(measurements[i].getIdFirst()));
1473  AlignableDetOrUnitPtr mod2(theAlignableNavigator->alignableFromDetId(measurements[i].getIdSecond()));
1474  const AlignableSurface& surf1 = mod1->surface();
1475  const AlignableSurface& surf2 = mod2->surface();
1476 
1477  // the position of the fiducial points in local frame of a PXB module
1478  const LocalPoint fidpoint0(-0.91,+3.30);
1479  const LocalPoint fidpoint1(+0.91,+3.30);
1480  const LocalPoint fidpoint2(+0.91,-3.30);
1481  const LocalPoint fidpoint3(-0.91,-3.30);
1482 
1483  // We choose the local frame of the first module as reference,
1484  // so take the fidpoints of the second module and calculate their
1485  // positions in the reference frame
1486  const GlobalPoint surf2point0(surf2.toGlobal(fidpoint0));
1487  const GlobalPoint surf2point1(surf2.toGlobal(fidpoint1));
1488  const LocalPoint fidpoint0inSurf1frame(surf1.toLocal(surf2point0));
1489  const LocalPoint fidpoint1inSurf1frame(surf1.toLocal(surf2point1));
1490 
1491  // Create the vector for the fit
1493  fidpointvec.push_back(fidpoint0inSurf1frame);
1494  fidpointvec.push_back(fidpoint1inSurf1frame);
1495  fidpointvec.push_back(fidpoint2);
1496  fidpointvec.push_back(fidpoint3);
1497 
1498  // if toy survey is requested, dice the values now
1499  if (pxbSurveyCfg.getParameter<bool>("doToySurvey"))
1500  {
1501  dicer.doDice(fidpointvec,measurements[i].getIdPair(), outfile);
1502  }
1503 
1504  // do the fit
1505  measurements[i].doFit(fidpointvec, thePedeLabels->alignableLabel(mod1), thePedeLabels->alignableLabel(mod2));
1506  SurveyPxbImageLocalFit::localpars_t a; // local pars from fit
1507  a = measurements[i].getLocalParameters();
1508  const SurveyPxbImageLocalFit::value_t chi2 = measurements[i].getChi2();
1509 
1510  // do some reporting, if requested
1511  if (doOutputOnStdout)
1512  {
1513  edm::LogInfo("Alignment")
1514  << "@SUB=MillePedeAlignmentAlgorithm::addPxbSurvey"
1515  << "a: " << a[0] << ", " << a[1] << ", " << a[2] << ", " << a[3]
1516  << " S= " << sqrt(a[2]*a[2]+a[3]*a[3])
1517  << " phi= " << atan(a[3]/a[2])
1518  << " chi2= " << chi2 << std::endl;
1519  }
1520  if (theMonitor)
1521  {
1522  theMonitor->fillPxbSurveyHistsChi2(chi2);
1523  theMonitor->fillPxbSurveyHistsLocalPars(a[0],a[1],sqrt(a[2]*a[2]+a[3]*a[3]),atan(a[3]/a[2]));
1524  }
1525 
1526  // pass the results from the local fit to mille
1528  {
1529  theMille->mille((int)measurements[i].getLocalDerivsSize(),
1530  measurements[i].getLocalDerivsPtr(j),
1531  (int)measurements[i].getGlobalDerivsSize(),
1532  measurements[i].getGlobalDerivsPtr(j),
1533  measurements[i].getGlobalDerivsLabelPtr(j),
1534  measurements[i].getResiduum(j),
1535  measurements[i].getSigma(j));
1536  }
1537  theMille->end();
1538  }
1539  outfile.close();
1540 }
1541 
virtual bool processesEvents() override
Returns whether MP should process events in the current configuration.
unsigned int hitsX() const
get number of hits for x-measurement
const TimeTypeSpecs timeTypeSpecs[]
Definition: Time.cc:22
T getParameter(std::string const &) const
unsigned int firstFixedParameter() const
GBL trajectory.
Definition: GblTrajectory.h:26
void globalDerivativesCalibration(const TransientTrackingRecHit::ConstRecHitPointer &recHit, const TrajectoryStateOnSurface &tsos, const edm::EventSetup &setup, const EventInfo &eventInfo, std::vector< float > &globalDerivativesX, std::vector< float > &globalDerivativesY, std::vector< int > &globalLabels) const
adding derivatives from integrated calibrations
T getUntrackedParameter(std::string const &, T const &) const
std::vector< AlignmentUserVariables * > readMillePedeVariables(const std::vector< Alignable * > &alivec, const char *filename, int iter, int &ierr)
int i
Definition: DBlmapReader.cc:9
unsigned int size() const
number of parameters
void resetParameters(void)
reset parameters, correlations, user variables
virtual bool supportsCalibrations() override
Returns whether MP supports calibrations.
std::unique_ptr< MillePedeMonitor > theMonitor
tuple cfg
Definition: looper.py:293
void increaseHitsX(unsigned int add=1)
increase hits for x-measurement
bool read(std::vector< Alignable * > &alignables, bool setUserVars)
Definition: PedeReader.cc:52
virtual bool setParametersForRunRange(const RunRange &runrange) override
Derivative< X, A >::type derivative(const A &_)
Definition: Derivative.h:18
virtual void endRun(const EventInfo &, const EndRunInfo &, const edm::EventSetup &)
Run on run products, e.g. TkLAS.
std::vector< coord_t > fidpoint_t
void increaseHitsY(unsigned int add=1)
increase hits for y-measurement
Time_t beginValue
Definition: Time.h:45
std::vector< Alignable * > theAlignables
virtual void endLuminosityBlock(const edm::EventSetup &) override
called at end of luminosity block
TrajectoryFactoryBase::ReferenceTrajectoryCollection RefTrajColl
std::vector< ParameterSet > VParameterSet
Definition: ParameterSet.h:33
std::unique_ptr< TrajectoryFactoryBase > theTrajectoryFactory
void writeAlignableOriginalPositions(const align::Alignables &alivec, const char *filename, int iter, bool validCheck, int &ierr)
write Alignable original (before misalignment) absolute positions
std::unique_ptr< gbl::MilleBinary > theBinary
const Time_t MIN_VAL(0)
int addGlobalData(const edm::EventSetup &setup, const EventInfo &eventInfo, const ReferenceTrajectoryBase::ReferenceTrajectoryPtr &refTrajPtr, unsigned int iHit, gbl::GblPoint &gblPoint)
bool exists(std::string const &parameterName) const
checks if a parameter exists
bool globalDerivativesHierarchy(const EventInfo &eventInfo, const TrajectoryStateOnSurface &tsos, Alignable *ali, const AlignableDetOrUnitPtr &alidet, std::vector< float > &globalDerivativesX, std::vector< float > &globalDerivativesY, std::vector< int > &globalLabels, AlignmentParameters *&lowestParams) const
recursively adding derivatives and labels, false if problems
void restoreCachedTransformations(void)
restore the previously cached position, rotation and other parameters
void applyParameters(void)
Obsolete: Use AlignableNavigator::alignableDetFromDetId and alignableFromAlignableDet.
std::vector< std::string > getExistingFormattedFiles(const std::vector< std::string > &plainFiles, const std::string &theDir)
unsigned int addHitCount(const std::vector< AlignmentParameters * > &parVec, const std::vector< bool > &validHitVecY) const
int loop
CMSSW
virtual LocalPoint localPosition() const
virtual bool addCalibrations(const std::vector< IntegratedCalibrationBase * > &iCals) override
Pass integrated calibrations to Millepede (they are not owned by Millepede!)
const AlgebraicMatrix & derivatives() const
matrix of local derivatives: columns are parameters, rows are hits
const std::vector< bool > & selector(void) const
Get alignment parameter selector vector.
int callMille2D(const ReferenceTrajectoryBase::ReferenceTrajectoryPtr &refTrajPtr, unsigned int iTrajHit, const std::vector< int > &globalLabels, const std::vector< float > &globalDerivativesx, const std::vector< float > &globalDerivativesy)
std::pair< RunNumber, RunNumber > RunRange
#define nullptr
uint16_t size_type
void addLasBeam(const EventInfo &eventInfo, const TkFittedLasBeam &lasBeam, const std::vector< TrajectoryStateOnSurface > &tsoses)
AlignmentParameters * alignmentParameters() const
Get the AlignmentParameters.
Definition: Alignable.h:57
const ConstTrajTrackPairCollection & trajTrackPairs() const
define event information passed to algorithms
tuple result
Definition: mps_fire.py:84
unsigned int doIO(int loop) const
int callMille(const ReferenceTrajectoryBase::ReferenceTrajectoryPtr &refTrajPtr, unsigned int iTrajHit, const std::vector< int > &globalLabels, const std::vector< float > &globalDerivativesX, const std::vector< float > &globalDerivativesY)
calls callMille1D or callMille2D
TransientTrackingRecHit::ConstRecHitPointer ConstRecHitPointer
U second(std::pair< T, U > const &p)
const AlgebraicVector & parameters(void) const
Get alignment parameters.
virtual void beginLuminosityBlock(const edm::EventSetup &) override
called at begin of luminosity block (resets Mille binary in mille mode)
std::string doDice(const fidpoint_t &fidpointvec, const idPair_t &id, const bool rotate=false)
AlignmentUserVariables * userVariables(void) const
Get pointer to user variables.
int callMille1D(const ReferenceTrajectoryBase::ReferenceTrajectoryPtr &refTrajPtr, unsigned int iTrajHit, const std::vector< int > &globalLabels, const std::vector< float > &globalDerivativesX)
calls Mille for 1D hits
void addLaserData(const EventInfo &eventInfo, const TkFittedLasBeamCollection &tkLasBeams, const TsosVectorCollection &tkLasBeamTsoses)
int addMeasurementData(const edm::EventSetup &setup, const EventInfo &eventInfo, const ReferenceTrajectoryBase::ReferenceTrajectoryPtr &refTrajPtr, unsigned int iHit, AlignmentParameters *&params)
bool isMode(unsigned int testMode) const
align::RotationType toLocal(const align::RotationType &) const
Return in local frame a rotation given in global frame.
virtual AlgebraicMatrix derivatives(const TrajectoryStateOnSurface &tsos, const AlignableDetOrUnitPtr &alidet) const =0
Get derivatives of selected parameters.
CLHEP::HepMatrix AlgebraicMatrix
const std::vector< Scalar > & parameters() const
parallel to derivatives()
std::shared_ptr< TrackingRecHit const > ConstRecHitPointer
void swap(edm::DataFrameContainer &lhs, edm::DataFrameContainer &rhs)
T sqrt(T t)
Definition: SSEVec.h:18
bool is2D(HitType hitType)
unsigned int getBeamId(void) const
return the full beam identifier
Definition: TkLasBeam.h:25
AlignmentParameterStore * theAlignmentParameterStore
directory for all kind of files
unsigned int hitsY() const
get number of hits for y-measurement
T Abs(T a)
Definition: MathUtil.h:49
bool is2D(const TransientTrackingRecHit::ConstRecHitPointer &recHit) const
true if hit belongs to 2D detector (currently tracker specific)
void diagonalize(TMatrixDSym &aHitCovarianceM, TMatrixF &aLocalDerivativesM, TMatrixF &aHitResidualsM, TMatrixF &theGlobalDerivativesM) const
int j
Definition: DBlmapReader.cc:9
std::unique_ptr< PedeLabelerBase > thePedeLabels
const TkFittedLasBeamCollection * tkLasBeams() const
std::unique_ptr< PedeSteerer > thePedeSteer
void addGlobals(const std::vector< int > &aLabels, const TMatrixD &aDerivatives)
Add global derivatives to a point.
Definition: GblPoint.cc:298
virtual void terminate() override
Called at end of job.
string key
FastSim: produces sample of signal events, overlayed with premixed minbias events.
virtual void initialize(const edm::EventSetup &setup, AlignableTracker *tracker, AlignableMuon *muon, AlignableExtras *extras, AlignmentParameterStore *store) override
Called at beginning of job.
const AlignableSurface & surface() const
Return the Surface (global position and orientation) of the object.
Definition: Alignable.h:131
JetCorrectorParameters corr
Definition: classes.h:5
bool addHits(const std::vector< Alignable * > &alis, const std::vector< AlignmentUserVariables * > &mpVars) const
std::vector< ConstRecHitPointer > ConstRecHitContainer
void writeMillePedeVariables(const std::vector< Alignable * > &alivec, const char *filename, int iter, bool validCheck, int &ierr)
bool addHitStatistics(int fromLoop, const std::string &outFile, const std::vector< std::string > &inFiles) const
bool areEmptyParams(const std::vector< Alignable * > &alignables) const
void addVirtualMeas(const ReferenceTrajectoryBase::ReferenceTrajectoryPtr &refTrajPtr, unsigned int iVirtualMeas)
adds data for virtual measurements from reference trajectory
bool readFromPede(const edm::ParameterSet &mprespset, bool setUserVars, const RunRange &runrange)
read pede input defined by &#39;psetName&#39;, flag to create/not create MillePedeVariables ...
CLHEP::HepVector AlgebraicVector
std::pair< unsigned int, unsigned int > addReferenceTrajectory(const edm::EventSetup &setup, const EventInfo &eventInfo, const ReferenceTrajectoryBase::ReferenceTrajectoryPtr &refTrajPtr)
fill mille for a trajectory, returning number of x/y hits ([0,0] if &#39;bad&#39; trajectory) ...
std::vector< ReferenceTrajectoryPtr > ReferenceTrajectoryCollection
const SiStripDetId & getDetId(void) const
void addRefTrackData2D(const ReferenceTrajectoryBase::ReferenceTrajectoryPtr &refTrajPtr, unsigned int iTrajHit, TMatrixDSym &aHitCovarianceM, TMatrixF &aHitResidualsM, TMatrixF &aLocalDerivativesM)
adds data from reference trajectory from a specific Hit
void milleOut(MilleBinary &aMille)
Write valid trajectory to Millepede-II binary file.
void setUserVariables(AlignmentUserVariables *auv)
Set pointer to user variables.
std::vector< IntegratedCalibrationBase * > theCalibrations
int size(void) const
Get number of parameters.
void makeGlobDerivMatrix(const std::vector< float > &globalDerivativesx, const std::vector< float > &globalDerivativesy, TMatrixF &aGlobalDerivativesM)
tuple tracks
Definition: testEve_cfg.py:39
void addUntrackedParameter(std::string const &name, T const &value)
Definition: ParameterSet.h:208
Class to hold one picture of the BPix survey.
const T & get() const
Definition: EventSetup.h:56
T const * product() const
Definition: ESHandle.h:86
std::vector< value_t > localpars_t
virtual void run(const edm::EventSetup &setup, const EventInfo &eventInfo) override
Run the algorithm on trajectories and tracks.
void buildUserVariables(const std::vector< Alignable * > &alignables) const
add MillePedeVariables for each AlignmentParameters (exception if no parameters...)
MillePedeAlignmentAlgorithm(const edm::ParameterSet &cfg)
Constructor.
virtual ~MillePedeAlignmentAlgorithm()
Destructor.
std::vector< TkFittedLasBeam > TkFittedLasBeamCollection
double a
Definition: hdecay.h:121
const reco::BeamSpot & beamSpot() const
align::GlobalPoints toGlobal(const align::LocalPoints &) const
Return in global coord given a set of local points.
void cacheTransformations(void)
cache the current position, rotation and other parameters
tuple filename
Definition: lut2db_cfg.py:20
TransientTrackingRecHit::ConstRecHitContainer ConstRecHitContainer
void addRefTrackVirtualMeas1D(const ReferenceTrajectoryBase::ReferenceTrajectoryPtr &refTrajPtr, unsigned int iVirtualMeas, TMatrixDSym &aHitCovarianceM, TMatrixF &aHitResidualsM, TMatrixF &aLocalDerivativesM)
adds data for a specific virtual measurement from reference trajectory
static const count_t nMsrmts
void writeAlignableAbsolutePositions(const align::Alignables &alivec, const char *filename, int iter, bool validCheck, int &ierr)
write Alignable current absolute positions
void addPxbSurvey(const edm::ParameterSet &pxbSurveyCfg)
add measurement data from PXB survey
unsigned int decodeMode(const std::string &mode) const
std::string fullPath() const
Definition: FileInPath.cc:184
std::unique_ptr< AlignableNavigator > theAlignableNavigator
Time_t endValue
Definition: Time.h:46
const std::vector< SiStripLaserRecHit2D > & getData(void) const
access the collection of hits
Definition: TkLasBeam.h:28
void writeOrigRigidBodyAlignmentParameters(const align::Alignables &alivec, const char *filename, int iter, bool validCheck, int &ierr)
write RigidBodyAlignmentParameters as applied on top of original positions
std::vector< std::vector< TrajectoryStateOnSurface > > TsosVectorCollection
define run information passed to algorithms (in endRun)
const TsosVectorCollection * tkLasBeamTsoses() const
might be null!
const AlgebraicSymMatrix & covariance(void) const
Get parameter covariance matrix.
Constructor of the full muon geometry.
Definition: AlignableMuon.h:36
uint32_t dimension(pat::CandKinResolution::Parametrization parametrization)
Returns the number of free parameters in a parametrization (3 or 4)
Alignable * mother() const
Return pointer to container alignable (if any)
Definition: Alignable.h:90
const Time_t MAX_VAL(std::numeric_limits< Time_t >::max())
tuple size
Write out results.
T get(const Candidate &c)
Definition: component.h:55
bool setAllDefault(unsigned int nParam)
set default values for all data concerning nParam (false if nParam out of range)
Point on trajectory.
Definition: GblPoint.h:46