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 //#include "MillePedeAlignmentAlgorithm.h"
13 
15 
17 // in header, too
18 // end in header, too
19 
23 #include "Mille.h" // 'unpublished' interface located in src
24 #include "PedeSteerer.h" // dito
25 #include "PedeReader.h" // dito
28 
31 
34 
38 
39 // includes to make known that they inherit from Alignable:
43 
49 
52 
54 
55 #include <fstream>
56 #include <sstream>
57 #include <algorithm>
58 
59 #include <TMath.h>
60 #include <TMatrixDSymEigen.h>
64 
65 // Includes for PXB survey
66 #include <iostream>
73 
75 
76 // Constructor ----------------------------------------------------------------
77 //____________________________________________________
80  theConfig(cfg), theMode(this->decodeMode(theConfig.getUntrackedParameter<std::string>("mode"))),
81  theDir(theConfig.getUntrackedParameter<std::string>("fileDir")),
82  theAlignmentParameterStore(0), theAlignables(), theAlignableNavigator(0),
83  theMonitor(0), theMille(0), thePedeLabels(0), thePedeSteer(0),
84  theTrajectoryFactory(0),
85  theMinNumHits(cfg.getParameter<unsigned int>("minNumHits")),
86  theMaximalCor2D(cfg.getParameter<double>("max2Dcorrelation"))
87 {
88  if (!theDir.empty() && theDir.find_last_of('/') != theDir.size()-1) theDir += '/';// may need '/'
89  edm::LogInfo("Alignment") << "@SUB=MillePedeAlignmentAlgorithm" << "Start in mode '"
90  << theConfig.getUntrackedParameter<std::string>("mode")
91  << "' with output directory '" << theDir << "'.";
92 }
93 
94 // Destructor ----------------------------------------------------------------
95 //____________________________________________________
97 {
98  delete theAlignableNavigator;
100  delete theMille;
101  theMille = 0;
102  delete theMonitor;
103  theMonitor = 0;
104  delete thePedeSteer;
105  thePedeSteer = 0;
106  delete thePedeLabels;
107  thePedeLabels = 0;
108  delete theTrajectoryFactory;
110 }
111 
112 // Call at beginning of job ---------------------------------------------------
113 //____________________________________________________
117 {
118  if (muon) {
119  edm::LogWarning("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::initialize"
120  << "Running with AlignabeMuon not yet tested.";
121  }
122 
123  theAlignableNavigator = new AlignableNavigator(extras, tracker, muon);
126 
127  edm::ParameterSet pedeLabelerCfg(theConfig.getParameter<edm::ParameterSet>("pedeLabeler"));
128  edm::VParameterSet RunRangeSelectionVPSet(theConfig.getUntrackedParameter<edm::VParameterSet>("RunRangeSelection"));
129  pedeLabelerCfg.addUntrackedParameter<edm::VParameterSet>("RunRangeSelection",
130  RunRangeSelectionVPSet);
131 
132  std::string labelerPlugin = "PedeLabeler";
133  if (RunRangeSelectionVPSet.size()>0) {
134  labelerPlugin = "RunRangeDependentPedeLabeler";
135  if (pedeLabelerCfg.exists("plugin")) {
136  std::string labelerPluginCfg = pedeLabelerCfg.getParameter<std::string>("plugin");
137  if ((labelerPluginCfg!="PedeLabeler" && labelerPluginCfg!="RunRangeDependentPedeLabeler") ||
138  pedeLabelerCfg.getUntrackedParameter<edm::VParameterSet>("parameterInstances").size()>0) {
139  throw cms::Exception("BadConfig")
140  << "MillePedeAlignmentAlgorithm::initialize"
141  << "both RunRangeSelection and generic labeler specified in config file. "
142  << "Please get rid of either one of them.\n";
143  }
144  }
145  } else {
146  if (pedeLabelerCfg.exists("plugin")) {
147  labelerPlugin = pedeLabelerCfg.getParameter<std::string>("plugin");
148  }
149  }
150 
151  if (!pedeLabelerCfg.exists("plugin")) {
152  pedeLabelerCfg.addUntrackedParameter<std::string>("plugin", labelerPlugin);
153  }
154 
155  edm::LogInfo("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::initialize"
156  << "Using plugin '" << labelerPlugin << "' to generate labels.";
157 
158  thePedeLabels = PedeLabelerPluginFactory::get()->create(labelerPlugin,
159  PedeLabelerBase::TopLevelAlignables(tracker, muon, extras),
160  pedeLabelerCfg);
161 
162  // 1) Create PedeSteerer: correct alignable positions for coordinate system selection
163  edm::ParameterSet pedeSteerCfg(theConfig.getParameter<edm::ParameterSet>("pedeSteerer"));
164  thePedeSteer = new PedeSteerer(tracker, muon, extras,
166  pedeSteerCfg, theDir, !this->isMode(myPedeSteerBit));
167 
168  // 2) If requested, directly read in and apply result of previous pede run,
169  // assuming that correction from 1) was also applied to create the result:
170  const std::vector<edm::ParameterSet> mprespset
171  (theConfig.getParameter<std::vector<edm::ParameterSet> >("pedeReaderInputs"));
172  if (!mprespset.empty()) {
173  edm::LogInfo("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::initialize"
174  << "Apply " << mprespset.end() - mprespset.begin()
175  << " previous MillePede constants from 'pedeReaderInputs'.";
176  }
177 
178  RunRange runrange(cond::timeTypeSpecs[cond::runnumber].beginValue,
180  for (std::vector<edm::ParameterSet>::const_iterator iSet = mprespset.begin(), iE = mprespset.end();
181  iSet != iE; ++iSet) {
182  if (!this->readFromPede((*iSet), false, runrange)) { // false: do not erase SelectionUserVariables
183  throw cms::Exception("BadConfig")
184  << "MillePedeAlignmentAlgorithm::initialize: Problems reading input constants of "
185  << "pedeReaderInputs entry " << iSet - mprespset.begin() << '.';
186  }
188  // Needed to shut up later warning from checkAliParams:
190  }
191 
192  // 3) Now create steerings with 'final' start position:
193  thePedeSteer->buildSubSteer(tracker, muon, extras);
194 
195  // After (!) 1-3 of PedeSteerer which uses the SelectionUserVariables attached to the parameters:
196  this->buildUserVariables(theAlignables); // for hit statistics and/or pede result
197 
198  if (this->isMode(myMilleBit)) {
199  if (!theConfig.getParameter<std::vector<std::string> >("mergeBinaryFiles").empty() ||
200  !theConfig.getParameter<std::vector<std::string> >("mergeTreeFiles").empty()) {
201  throw cms::Exception("BadConfig")
202  << "'vstring mergeTreeFiles' and 'vstring mergeBinaryFiles' must be empty for "
203  << "modes running mille.";
204  }
205  theMille = new Mille((theDir + theConfig.getParameter<std::string>("binaryFile")).c_str());// add ', false);' for text output);
206  const std::string moniFile(theConfig.getUntrackedParameter<std::string>("monitorFile"));
207  if (moniFile.size()) theMonitor = new MillePedeMonitor((theDir + moniFile).c_str());
208 
209  // Get trajectory factory. In case nothing found, FrameWork will throw...
210  const edm::ParameterSet fctCfg(theConfig.getParameter<edm::ParameterSet>("TrajectoryFactory"));
211  const std::string fctName(fctCfg.getParameter<std::string>("TrajectoryFactoryName"));
212  theTrajectoryFactory = TrajectoryFactoryPlugin::get()->create(fctName, fctCfg);
213  }
214 
215  // FIXME: for PlotMillePede hit statistics stuff we also might want doIO(0)... ?
216  if (this->isMode(myPedeSteerBit) // for pedeRun and pedeRead we might want to merge
217  || !theConfig.getParameter<std::vector<std::string> >("mergeTreeFiles").empty()) {
218  this->doIO(0);
219 
220  // Get config for survey and set flag accordingly
221  const edm::ParameterSet pxbSurveyCfg(theConfig.getParameter<edm::ParameterSet>("surveyPixelBarrel"));
222  theDoSurveyPixelBarrel = pxbSurveyCfg.getParameter<bool>("doSurvey");
223  if (theDoSurveyPixelBarrel) addPxbSurvey(pxbSurveyCfg);
224  }
225 }
226 
228 {
229  if (this->isMode(myPedeReadBit)) {
230  if (!this->readFromPede(theConfig.getParameter<edm::ParameterSet>("pedeReader"), true, runrange)) {
231  edm::LogError("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::terminate"
232  << "Problems reading pede result, but applying!";
233  }
235  }
236 }
237 
238 // Call at end of job ---------------------------------------------------------
239 //____________________________________________________
241 {
242  delete theMille;// delete to close binary before running pede below (flush would be enough...)
243  theMille = 0;
244 
245  std::vector<std::string> files;
246  if (this->isMode(myMilleBit) || !theConfig.getParameter<std::string>("binaryFile").empty()) {
247  files.push_back(theDir + theConfig.getParameter<std::string>("binaryFile"));
248  } else {
249  const std::vector<std::string> plainFiles
250  (theConfig.getParameter<std::vector<std::string> >("mergeBinaryFiles"));
251  for (std::vector<std::string>::const_iterator i = plainFiles.begin(), iEnd = plainFiles.end();
252  i != iEnd; ++i) {
253  files.push_back(theDir + *i);
254  }
255  }
256  const std::string masterSteer(thePedeSteer->buildMasterSteer(files));// do only if myPedeSteerBit?
257  if (this->isMode(myPedeRunBit)) {
258  thePedeSteer->runPede(masterSteer);
259  }
260 
261  if (this->isMode(myPedeReadBit)) {
262  RunRange runrange(cond::timeTypeSpecs[cond::runnumber].beginValue,
264  if (!this->readFromPede(theConfig.getParameter<edm::ParameterSet>("pedeReader"), true, runrange)) {
265  edm::LogError("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::terminate"
266  << "Problems reading pede result, but applying!";
267  }
269  }
270 
271  if (this->isMode(myMilleBit)) { // if mille was run, we store trees with suffix _1...
272  this->doIO(1);
273  } else if (this->isMode(myPedeReadBit)) {// if pede runs otherwise, we use _2 (=> probably merge)
274  this->doIO(2);
275  }
276 }
277 
278 // Run the algorithm on trajectories and tracks -------------------------------
279 //____________________________________________________
281 {
282  if (!this->isMode(myMilleBit)) return; // no theMille created...
284 
285  if (theMonitor) { // monitor input tracks
286  for (ConstTrajTrackPairCollection::const_iterator iTrajTrack = tracks.begin();
287  iTrajTrack != tracks.end(); ++iTrajTrack) {
288  theMonitor->fillTrack((*iTrajTrack).second);
289  }
290  }
291 
292  const RefTrajColl trajectories(theTrajectoryFactory->trajectories(setup, tracks, eventInfo.beamSpot_));
293 
294  // Now loop over ReferenceTrajectoryCollection
295  unsigned int refTrajCount = 0; // counter for track monitoring if 1 track per trajectory
296  for (RefTrajColl::const_iterator iRefTraj = trajectories.begin(), iRefTrajE = trajectories.end();
297  iRefTraj != iRefTrajE; ++iRefTraj, ++refTrajCount) {
298 
299  RefTrajColl::value_type refTrajPtr = *iRefTraj;
300  if (theMonitor) theMonitor->fillRefTrajectory(refTrajPtr);
301 
302  const std::pair<unsigned int, unsigned int> nHitXy = this->addReferenceTrajectory(eventInfo, refTrajPtr);
303 
304  if (theMonitor && (nHitXy.first || nHitXy.second)) {
305  // if track used (i.e. some hits), fill monitoring
306  // track NULL ptr if trajectories and tracks do not match
307  const reco::Track *trackPtr =
308  (trajectories.size() == tracks.size() ? tracks[refTrajCount].second : 0);
309  theMonitor->fillUsedTrack(trackPtr, nHitXy.first, nHitXy.second);
310  }
311 
312  } // end of reference trajectory and track loop
313 }
314 
315 
316 
317 //____________________________________________________
318 std::pair<unsigned int, unsigned int>
320  const RefTrajColl::value_type &refTrajPtr)
321 {
322  std::pair<unsigned int, unsigned int> hitResultXy(0,0);
323  if (refTrajPtr->isValid()) {
324 
325  // to add hits if all fine:
326  std::vector<AlignmentParameters*> parVec(refTrajPtr->recHits().size());
327  // collect hit statistics, assuming that there are no y-only hits
328  std::vector<bool> validHitVecY(refTrajPtr->recHits().size(), false);
329  // Use recHits from ReferenceTrajectory (since they have the right order!):
330  for (unsigned int iHit = 0; iHit < refTrajPtr->recHits().size(); ++iHit) {
331  const int flagXY = this->addMeasurementData(eventInfo, refTrajPtr, iHit, parVec[iHit]);
332 
333  if (flagXY < 0) { // problem
334  hitResultXy.first = 0;
335  break;
336  } else { // hit is fine, increase x/y statistics
337  if (flagXY >= 1) ++hitResultXy.first;
338  validHitVecY[iHit] = (flagXY >= 2);
339  }
340  } // end loop on hits
341 
342 // CHK add 'Multiple Scattering Measurements' for break points, broken lines
343  for (unsigned int iMsMeas = 0; iMsMeas < refTrajPtr->numberOfMsMeas(); ++iMsMeas) {
344  this->addMsMeas(refTrajPtr, iMsMeas);
345  }
346 
347  // kill or end 'track' for mille, depends on #hits criterion
348  if (hitResultXy.first == 0 || hitResultXy.first < theMinNumHits) {
349  theMille->kill();
350  hitResultXy.first = hitResultXy.second = 0; //reset
351  } else {
352  theMille->end();
353  // take care about hit statistics as well
354  for (unsigned int iHit = 0; iHit < validHitVecY.size(); ++iHit) {
355  if (!parVec[iHit]) continue; // in case a non-selected alignable was hit (flagXY == 0)
356  MillePedeVariables *mpVar = static_cast<MillePedeVariables*>(parVec[iHit]->userVariables());
357  mpVar->increaseHitsX(); // every hit has an x-measurement, cf. above...
358  if (validHitVecY[iHit]) {
359  mpVar->increaseHitsY();
360  ++hitResultXy.second;
361  }
362  }
363  }
364  } // end if valid trajectory
365 
366  return hitResultXy;
367 }
368 
369 //____________________________________________________
371  const edm::EventSetup &setup)
372 {
373  if(runInfo.tkLasBeams_ && runInfo.tkLasBeamTsoses_){
374  // LAS beam treatment
375  this->addLaserData(eventInfo, *(runInfo.tkLasBeams_), *(runInfo.tkLasBeamTsoses_));
376  }
377 }
378 
379 //____________________________________________________
382  unsigned int iHit,
383  AlignmentParameters *&params)
384 {
385  params = 0;
386  theFloatBufferX.clear();
387  theFloatBufferY.clear();
388  theIntBuffer.clear();
389 
390  const TrajectoryStateOnSurface &tsos = refTrajPtr->trajectoryStates()[iHit];
391  const ConstRecHitPointer &recHitPtr = refTrajPtr->recHits()[iHit];
392  // ignore invalid hits
393  if (!recHitPtr->isValid()) return 0;
394 
395  // get AlignableDet/Unit for this hit
396  AlignableDetOrUnitPtr alidet(theAlignableNavigator->alignableFromDetId(recHitPtr->geographicalId()));
397 
398  if (!this->globalDerivativesHierarchy(eventInfo,
399  tsos, alidet, alidet, theFloatBufferX, // 2x alidet, sic!
400  theFloatBufferY, theIntBuffer, params)) {
401  return -1; // problem
402  } else if (theFloatBufferX.empty()) {
403  return 0; // empty for X: no alignable for hit
404  } else {
405  return this->callMille(refTrajPtr, iHit, theIntBuffer, theFloatBufferX, theFloatBufferY);
406  }
407 }
408 
409 //____________________________________________________
412  const TrajectoryStateOnSurface &tsos,
413  Alignable *ali, const AlignableDetOrUnitPtr &alidet,
414  std::vector<float> &globalDerivativesX,
415  std::vector<float> &globalDerivativesY,
416  std::vector<int> &globalLabels,
417  AlignmentParameters *&lowestParams) const
418 {
419  // derivatives and labels are recursively attached
420  if (!ali) return true; // no mother might be OK
421 
422  if (false && theMonitor && alidet != ali) theMonitor->fillFrameToFrame(alidet, ali);
423 
424  AlignmentParameters *params = ali->alignmentParameters();
425 
426  if (params) {
427  if (!lowestParams) lowestParams = params; // set parameters of lowest level
428 
429  bool hasSplitParameters = thePedeLabels->hasSplitParameters(ali);
430  const unsigned int alignableLabel = thePedeLabels->alignableLabel(ali);
431 
432  if (0 == alignableLabel) { // FIXME: what about regardAllHits in Markus' code?
433  edm::LogWarning("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::globalDerivativesHierarchy"
434  << "Label not found, skip Alignable.";
435  return false;
436  }
437 
438  const std::vector<bool> &selPars = params->selector();
439  const AlgebraicMatrix derivs(params->derivatives(tsos, alidet));
440 
441  // cols: 2, i.e. x&y, rows: parameters, usually RigidBodyAlignmentParameters::N_PARAM
442  for (unsigned int iSel = 0; iSel < selPars.size(); ++iSel) {
443  if (selPars[iSel]) {
444  globalDerivativesX.push_back(derivs[iSel][kLocalX]
445  /thePedeSteer->cmsToPedeFactor(iSel));
446  if (hasSplitParameters==true) {
447  globalLabels.push_back(thePedeLabels->parameterLabel(ali, iSel, eventInfo, tsos));
448  } else {
449  globalLabels.push_back(thePedeLabels->parameterLabel(alignableLabel, iSel));
450  }
451  globalDerivativesY.push_back(derivs[iSel][kLocalY]
452  /thePedeSteer->cmsToPedeFactor(iSel));
453  }
454  }
455  // Exclude mothers if Alignable selected to be no part of a hierarchy:
456  if (thePedeSteer->isNoHiera(ali)) return true;
457  }
458  // Call recursively for mother, will stop if mother == 0:
459  return this->globalDerivativesHierarchy(eventInfo,
460  tsos, ali->mother(), alidet,
461  globalDerivativesX, globalDerivativesY,
462  globalLabels, lowestParams);
463 }
464 
465 // //____________________________________________________
466 // void MillePedeAlignmentAlgorithm
467 // ::callMille(const ReferenceTrajectoryBase::ReferenceTrajectoryPtr &refTrajPtr,
468 // unsigned int iTrajHit, MeasurementDirection xOrY,
469 // const std::vector<float> &globalDerivatives, const std::vector<int> &globalLabels)
470 // {
471 // const unsigned int xyIndex = iTrajHit*2 + xOrY;
472 // // FIXME: here for residuum and sigma we could use KALMAN-Filter results
473 // const float residuum =
474 // refTrajPtr->measurements()[xyIndex] - refTrajPtr->trajectoryPositions()[xyIndex];
475 // const float covariance = refTrajPtr->measurementErrors()[xyIndex][xyIndex];
476 // const float sigma = (covariance > 0. ? TMath::Sqrt(covariance) : 0.);
477 
478 // const AlgebraicMatrix &locDerivMatrix = refTrajPtr->derivatives();
479 
480 // std::vector<float> localDerivs(locDerivMatrix.num_col());
481 // for (unsigned int i = 0; i < localDerivs.size(); ++i) {
482 // localDerivs[i] = locDerivMatrix[xyIndex][i];
483 // }
484 
485 // // &(vector[0]) is valid - as long as vector is not empty
486 // // cf. http://www.parashift.com/c++-faq-lite/containers.html#faq-34.3
487 // theMille->mille(localDerivs.size(), &(localDerivs[0]),
488 // globalDerivatives.size(), &(globalDerivatives[0]), &(globalLabels[0]),
489 // residuum, sigma);
490 // if (theMonitor) {
491 // theMonitor->fillDerivatives(refTrajPtr->recHits()[iTrajHit],localDerivs, globalDerivatives,
492 // (xOrY == kLocalY));
493 // theMonitor->fillResiduals(refTrajPtr->recHits()[iTrajHit],
494 // refTrajPtr->trajectoryStates()[iTrajHit],
495 // iTrajHit, residuum, sigma, (xOrY == kLocalY));
496 // }
497 // }
498 
499 //____________________________________________________
501 {
502  // FIXME: Check whether this is a reliable and recommended way to find out...
503 
504  if (recHit->dimension() < 2) {
505  return false; // some muon and TIB/TOB stuff really has RecHit1D
506  } else if (recHit->detUnit()) { // detunit in strip is 1D, in pixel 2D
507  return recHit->detUnit()->type().isTrackerPixel();
508  } else { // stereo strips (FIXME: endcap trouble due to non-parallel strips (wedge sensors)?)
509  if (dynamic_cast<const ProjectedSiStripRecHit2D*>(recHit->hit())) { // check persistent hit
510  // projected: 1D measurement on 'glued' module
511  return false;
512  } else {
513  return true;
514  }
515  }
516 }
517 
518 //__________________________________________________________________________________________________
519 bool MillePedeAlignmentAlgorithm::readFromPede(const edm::ParameterSet &mprespset, bool setUserVars,
520  const RunRange &runrange)
521 {
522  bool allEmpty = this->areEmptyParams(theAlignables);
523 
524  PedeReader reader(mprespset, *thePedeSteer, *thePedeLabels, runrange);
525  std::vector<Alignable*> alis;
526  bool okRead = reader.read(alis, setUserVars);
527  bool numMatch = true;
528 
529  std::stringstream out("Read ");
530  out << alis.size() << " alignables";
531  if (alis.size() != theAlignables.size()) {
532  out << " while " << theAlignables.size() << " in store";
533  numMatch = false; // FIXME: Should we check one by one? Or transfer 'alis' to the store?
534  }
535  if (!okRead) out << ", but problems in reading";
536  if (!allEmpty) out << ", possibly overwriting previous settings";
537  out << ".";
538 
539  if (okRead && allEmpty) {
540  if (numMatch) { // as many alignables with result as trying to align
541  edm::LogInfo("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::readFromPede" << out.str();
542  } else if (alis.size()) { // dead module do not get hits and no pede result
543  edm::LogWarning("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::readFromPede" << out.str();
544  } else { // serious problem: no result read - and not all modules can be dead...
545  edm::LogError("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::readFromPede" << out.str();
546  return false;
547  }
548  return true;
549  }
550  // the rest is not OK:
551  edm::LogError("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::readFromPede" << out.str();
552  return false;
553 }
554 
555 //__________________________________________________________________________________________________
556 bool MillePedeAlignmentAlgorithm::areEmptyParams(const std::vector<Alignable*> &alignables) const
557 {
558 
559  for (std::vector<Alignable*>::const_iterator iAli = alignables.begin();
560  iAli != alignables.end(); ++iAli) {
561  const AlignmentParameters *params = (*iAli)->alignmentParameters();
562  if (params) {
563  const AlgebraicVector &parVec(params->parameters());
564  const AlgebraicMatrix &parCov(params->covariance());
565  for (int i = 0; i < parVec.num_row(); ++i) {
566  if (parVec[i] != 0.) return false;
567  for (int j = i; j < parCov.num_col(); ++j) {
568  if (parCov[i][j] != 0.) return false;
569  }
570  }
571  }
572  }
573 
574  return true;
575 }
576 
577 //__________________________________________________________________________________________________
579 {
580  unsigned int result = 0;
581 
582  const std::string outFilePlain(theConfig.getParameter<std::string>("treeFile"));
583  if (outFilePlain.empty()) {
584  edm::LogInfo("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::doIO"
585  << "treeFile parameter empty => skip writing for 'loop' " << loop;
586  return result;
587  }
588 
589  const std::string outFile(theDir + outFilePlain);
590 
591  AlignmentIORoot aliIO;
592  int ioerr = 0;
593  if (loop == 0) {
594  aliIO.writeAlignableOriginalPositions(theAlignables, outFile.c_str(), loop, false, ioerr);
595  if (ioerr) {
596  edm::LogError("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::doIO"
597  << "Problem " << ioerr << " in writeAlignableOriginalPositions";
598  ++result;
599  }
600  } else {
601  if (loop > 1) {
602  const std::vector<std::string> inFiles
603  (theConfig.getParameter<std::vector<std::string> >("mergeTreeFiles"));
604  const std::vector<std::string> binFiles
605  (theConfig.getParameter<std::vector<std::string> >("mergeBinaryFiles"));
606  if (inFiles.size() != binFiles.size()) {
607  edm::LogWarning("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::doIO"
608  << "'vstring mergeTreeFiles' and 'vstring mergeBinaryFiles' "
609  << "differ in size";
610  }
611  this->addHitStatistics(loop - 1, outFile, inFiles);
612  }
613  MillePedeVariablesIORoot millePedeIO;
614  millePedeIO.writeMillePedeVariables(theAlignables, outFile.c_str(), loop, false, ioerr);
615  if (ioerr) {
616  edm::LogError("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::doIO"
617  << "Problem " << ioerr << " writing MillePedeVariables";
618  ++result;
619  }
620 // // problem with following writeOrigRigidBodyAlignmentParameters
621 // aliIO.writeAlignmentParameters(theAlignables, outFile.c_str(), loop, false, ioerr);
622 // if (ioerr) {
623 // edm::LogError("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::doIO"
624 // << "Problem " << ioerr << " in writeAlignmentParameters, " << loop;
625 // ++result;
626 // }
627  }
628 
629  // aliIO.writeAlignmentParameters(theAlignables, ("tmp"+outFile).c_str(), loop, false, ioerr);
630  aliIO.writeOrigRigidBodyAlignmentParameters(theAlignables, outFile.c_str(), loop, false, ioerr);
631  if (ioerr) {
632  edm::LogError("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::doIO" << "Problem " << ioerr
633  << " in writeOrigRigidBodyAlignmentParameters, " << loop;
634  ++result;
635  }
636  aliIO.writeAlignableAbsolutePositions(theAlignables, outFile.c_str(), loop, false, ioerr);
637  if (ioerr) {
638  edm::LogError("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::doIO" << "Problem " << ioerr
639  << " in writeAlignableAbsolutePositions, " << loop;
640  ++result;
641  }
642  aliIO.writeAlignableRelativePositions(theAlignables, outFile.c_str(), loop, false, ioerr);
643  if (ioerr) {
644  edm::LogError("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::doIO" << "Problem " << ioerr
645  << " in writeAlignableRelativePositions, " << loop;
646  ++result;
647  }
648 
649  return result;
650 }
651 
652 //__________________________________________________________________________________________________
653 void MillePedeAlignmentAlgorithm::buildUserVariables(const std::vector<Alignable*> &alis) const
654 {
655  for (std::vector<Alignable*>::const_iterator iAli = alis.begin(); iAli != alis.end(); ++iAli) {
656  AlignmentParameters *params = (*iAli)->alignmentParameters();
657  if (!params) {
658  throw cms::Exception("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::buildUserVariables"
659  << "No parameters for alignable";
660  }
661  MillePedeVariables *userVars = new MillePedeVariables(params->size(), thePedeLabels->alignableLabel(*iAli));
662  params->setUserVariables(userVars);
663  }
664 }
665 
666 //__________________________________________________________________________________________________
667 unsigned int MillePedeAlignmentAlgorithm::decodeMode(const std::string &mode) const
668 {
669  if (mode == "full") {
671  } else if (mode == "mille") {
672  return myMilleBit; // + myPedeSteerBit; // sic! Including production of steerig file. NO!
673  } else if (mode == "pede") {
675  } else if (mode == "pedeSteer") {
676  return myPedeSteerBit;
677  } else if (mode == "pedeRun") {
678  return myPedeSteerBit + myPedeRunBit + myPedeReadBit; // sic! Including steering and reading of result.
679  } else if (mode == "pedeRead") {
680  return myPedeReadBit;
681  }
682 
683  throw cms::Exception("BadConfig")
684  << "Unknown mode '" << mode
685  << "', use 'full', 'mille', 'pede', 'pedeRun', 'pedeSteer' or 'pedeRead'.";
686 
687  return 0;
688 }
689 
690 //__________________________________________________________________________________________________
691 bool MillePedeAlignmentAlgorithm::addHitStatistics(int fromLoop, const std::string &outFile,
692  const std::vector<std::string> &inFiles) const
693 {
694  bool allOk = true;
695  int ierr = 0;
696  MillePedeVariablesIORoot millePedeIO;
697  if (inFiles.empty()) {
698  const std::vector<AlignmentUserVariables*> mpVars =
699  millePedeIO.readMillePedeVariables(theAlignables, outFile.c_str(), fromLoop, ierr);
700  if (ierr || !this->addHits(theAlignables, mpVars)) {
701  edm::LogError("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::addHitStatistics"
702  << "Error " << ierr << " reading from " << outFile
703  << ", tree " << fromLoop << ", or problems in addHits";
704  allOk = false;
705  }
706  for (std::vector<AlignmentUserVariables*>::const_iterator i = mpVars.begin();
707  i != mpVars.end(); ++i){
708  delete *i; // clean created objects
709  }
710  } else {
711  for (std::vector<std::string>::const_iterator iFile = inFiles.begin();
712  iFile != inFiles.end(); ++iFile) {
713  const std::string inFile(theDir + *iFile);
714  const std::vector<AlignmentUserVariables*> mpVars =
715  millePedeIO.readMillePedeVariables(theAlignables, inFile.c_str(), fromLoop, ierr);
716  if (ierr || !this->addHits(theAlignables, mpVars)) {
717  edm::LogError("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::addHitStatistics"
718  << "Error " << ierr << " reading from " << inFile
719  << ", tree " << fromLoop << ", or problems in addHits";
720  allOk = false;
721  }
722  for (std::vector<AlignmentUserVariables*>::const_iterator i = mpVars.begin();
723  i != mpVars.end(); ++i) {
724  delete *i; // clean created objects
725  }
726  }
727  }
728 
729  return allOk;
730 }
731 
732 //__________________________________________________________________________________________________
733 bool MillePedeAlignmentAlgorithm::addHits(const std::vector<Alignable*> &alis,
734  const std::vector<AlignmentUserVariables*> &mpVars) const
735 {
736  bool allOk = (mpVars.size() == alis.size());
737  std::vector<AlignmentUserVariables*>::const_iterator iUser = mpVars.begin();
738  for (std::vector<Alignable*>::const_iterator iAli = alis.begin();
739  iAli != alis.end() && iUser != mpVars.end(); ++iAli, ++iUser) {
740  MillePedeVariables *mpVarNew = dynamic_cast<MillePedeVariables*>(*iUser);
741  AlignmentParameters *ps = (*iAli)->alignmentParameters();
742  MillePedeVariables *mpVarOld = (ps ? dynamic_cast<MillePedeVariables*>(ps->userVariables()) : 0);
743  if (!mpVarNew || !mpVarOld || mpVarOld->size() != mpVarNew->size()) {
744  allOk = false;
745  continue; // FIXME error etc.?
746  }
747 
748  mpVarOld->increaseHitsX(mpVarNew->hitsX());
749  mpVarOld->increaseHitsY(mpVarNew->hitsY());
750  }
751 
752  return allOk;
753 }
754 
755 //__________________________________________________________________________________________________
756 void MillePedeAlignmentAlgorithm::makeGlobDerivMatrix(const std::vector<float> &globalDerivativesx,
757  const std::vector<float> &globalDerivativesy,
758  TMatrixF &aGlobalDerivativesM)
759 {
760 
761  for (unsigned int i = 0; i < globalDerivativesx.size(); ++i) {
762  aGlobalDerivativesM(0,i) = globalDerivativesx[i];
763  aGlobalDerivativesM(1,i) = globalDerivativesy[i];
764  }
765 }
766 
767 //__________________________________________________________________________________________________
769 (TMatrixDSym &aHitCovarianceM, TMatrixF &aLocalDerivativesM, TMatrixF &aHitResidualsM,
770  TMatrixF &aGlobalDerivativesM) const
771 {
772  TMatrixDSymEigen myDiag(aHitCovarianceM);
773  TMatrixD aTranfoToDiagonalSystem = myDiag.GetEigenVectors();
774  TMatrixD aTranfoToDiagonalSystemInv = myDiag.GetEigenVectors( );
775  TMatrixF aTranfoToDiagonalSystemInvF = myDiag.GetEigenVectors( );
776  TMatrixD aMatrix = aTranfoToDiagonalSystemInv.Invert() * aHitCovarianceM * aTranfoToDiagonalSystem;
777  // Tranformation of matrix M is done by A^T*M*A, not A^{-1}*M*A.
778  // But here A^T == A^{-1}, so we would only save CPU by Transpose()...
779  // FIXME this - I guess simply use T(), not Transpose()...
780  // TMatrixD aMatrix = aTranfoToDiagonalSystemInv.Transpose() * aHitCovarianceM
781  // * aTranfoToDiagonalSystem;
782  aHitCovarianceM = TMatrixDSym(2, aMatrix.GetMatrixArray());
783  aTranfoToDiagonalSystemInvF.Invert();
784  //edm::LogInfo("Alignment") << "NEW HIT loca in matrix"<<aLocalDerivativesM(0,0);
785  aLocalDerivativesM = aTranfoToDiagonalSystemInvF * aLocalDerivativesM;
786 
787  //edm::LogInfo("Alignment") << "NEW HIT loca in matrix after diag:"<<aLocalDerivativesM(0,0);
788  aHitResidualsM = aTranfoToDiagonalSystemInvF * aHitResidualsM;
789  aGlobalDerivativesM = aTranfoToDiagonalSystemInvF * aGlobalDerivativesM;
790 }
791 
792 //__________________________________________________________________________________________________
795  unsigned int iMsMeas, TMatrixDSym &aHitCovarianceM,
796  TMatrixF &aHitResidualsM, TMatrixF &aLocalDerivativesM)
797 {
798 
799  // This Method is valid for 1D measurements only
800  const unsigned int xIndex = iMsMeas + refTrajPtr->numberOfHitMeas();
801  // Covariance into a TMatrixDSym
802 
803  //aHitCovarianceM = new TMatrixDSym(1);
804  aHitCovarianceM(0,0)=refTrajPtr->measurementErrors()[xIndex][xIndex];
805 
806  //theHitResidualsM= new TMatrixF(1,1);
807  aHitResidualsM(0,0)= refTrajPtr->measurements()[xIndex];
808 
809  // Local Derivatives into a TMatrixDSym (to use matrix operations)
810  const AlgebraicMatrix &locDerivMatrix = refTrajPtr->derivatives();
811  // theLocalDerivativeNumber = locDerivMatrix.num_col();
812 
813  //theLocalDerivativesM = new TMatrixF(1,locDerivMatrix.num_col());
814  for (int i = 0; i < locDerivMatrix.num_col(); ++i) {
815  aLocalDerivativesM(0,i) = locDerivMatrix[xIndex][i];
816  }
817 }
818 
819 //__________________________________________________________________________________________________
822  unsigned int iTrajHit, TMatrixDSym &aHitCovarianceM,
823  TMatrixF &aHitResidualsM, TMatrixF &aLocalDerivativesM)
824 {
825  // This Method is valid for 2D measurements only
826 
827  const unsigned int xIndex = iTrajHit*2;
828  const unsigned int yIndex = iTrajHit*2+1;
829  // Covariance into a TMatrixDSym
830 
831  //aHitCovarianceM = new TMatrixDSym(2);
832  aHitCovarianceM(0,0)=refTrajPtr->measurementErrors()[xIndex][xIndex];
833  aHitCovarianceM(0,1)=refTrajPtr->measurementErrors()[xIndex][yIndex];
834  aHitCovarianceM(1,0)=refTrajPtr->measurementErrors()[yIndex][xIndex];
835  aHitCovarianceM(1,1)=refTrajPtr->measurementErrors()[yIndex][yIndex];
836 
837  //theHitResidualsM= new TMatrixF(2,1);
838  aHitResidualsM(0,0)= refTrajPtr->measurements()[xIndex] - refTrajPtr->trajectoryPositions()[xIndex];
839  aHitResidualsM(1,0)= refTrajPtr->measurements()[yIndex] - refTrajPtr->trajectoryPositions()[yIndex];
840 
841  // Local Derivatives into a TMatrixDSym (to use matrix operations)
842  const AlgebraicMatrix &locDerivMatrix = refTrajPtr->derivatives();
843  // theLocalDerivativeNumber = locDerivMatrix.num_col();
844 
845  //theLocalDerivativesM = new TMatrixF(2,locDerivMatrix.num_col());
846  for (int i = 0; i < locDerivMatrix.num_col(); ++i) {
847  aLocalDerivativesM(0,i) = locDerivMatrix[xIndex][i];
848  aLocalDerivativesM(1,i) = locDerivMatrix[yIndex][i];
849  }
850 }
851 
852 //__________________________________________________________________________________________________
855  unsigned int iTrajHit, const std::vector<int> &globalLabels,
856  const std::vector<float> &globalDerivativesX,
857  const std::vector<float> &globalDerivativesY)
858 {
859  const ConstRecHitPointer aRecHit(refTrajPtr->recHits()[iTrajHit]);
860 
861  if((aRecHit)->dimension() == 1) {
862  return this->callMille1D(refTrajPtr, iTrajHit, globalLabels, globalDerivativesX);
863  } else {
864  return this->callMille2D(refTrajPtr, iTrajHit, globalLabels,
865  globalDerivativesX, globalDerivativesY);
866  }
867 }
868 
869 
870 //__________________________________________________________________________________________________
873  unsigned int iTrajHit, const std::vector<int> &globalLabels,
874  const std::vector<float> &globalDerivativesX)
875 {
876  const ConstRecHitPointer aRecHit(refTrajPtr->recHits()[iTrajHit]);
877  const unsigned int xIndex = iTrajHit*2; // the even ones are local x
878 
879  // local derivatives
880  const AlgebraicMatrix &locDerivMatrix = refTrajPtr->derivatives();
881  const int nLocal = locDerivMatrix.num_col();
882  std::vector<float> localDerivatives(nLocal);
883  for (unsigned int i = 0; i < localDerivatives.size(); ++i) {
884  localDerivatives[i] = locDerivMatrix[xIndex][i];
885  }
886 
887  // residuum and error
888  float residX = refTrajPtr->measurements()[xIndex] - refTrajPtr->trajectoryPositions()[xIndex];
889  float hitErrX = TMath::Sqrt(refTrajPtr->measurementErrors()[xIndex][xIndex]);
890 
891  // number of global derivatives
892  const int nGlobal = globalDerivativesX.size();
893 
894  // &(localDerivatives[0]) etc. are valid - as long as vector is not empty
895  // cf. http://www.parashift.com/c++-faq-lite/containers.html#faq-34.3
896  theMille->mille(nLocal, &(localDerivatives[0]), nGlobal, &(globalDerivativesX[0]),
897  &(globalLabels[0]), residX, hitErrX);
898 
899  if (theMonitor) {
900  theMonitor->fillDerivatives(aRecHit, &(localDerivatives[0]), nLocal,
901  &(globalDerivativesX[0]), nGlobal, &(globalLabels[0]));
902  theMonitor->fillResiduals(aRecHit, refTrajPtr->trajectoryStates()[iTrajHit],
903  iTrajHit, residX, hitErrX, false);
904  }
905 
906  return 1;
907 }
908 
909 //__________________________________________________________________________________________________
912  unsigned int iTrajHit, const std::vector<int> &globalLabels,
913  const std::vector<float> &globalDerivativesx,
914  const std::vector<float> &globalDerivativesy)
915 {
916  const ConstRecHitPointer aRecHit(refTrajPtr->recHits()[iTrajHit]);
917 
918  if((aRecHit)->dimension() != 2) {
919  edm::LogError("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::callMille2D"
920  << "You try to call method for 2D hits for a "
921  << (aRecHit)->dimension()
922  << "D Hit. Hit gets ignored!";
923  return -1;
924  }
925 
926  TMatrixDSym aHitCovarianceM(2);
927  TMatrixF aHitResidualsM(2,1);
928  TMatrixF aLocalDerivativesM(2, refTrajPtr->derivatives().num_col());
929  // below method fills above 3 matrices
930  this->addRefTrackData2D(refTrajPtr, iTrajHit, aHitCovarianceM,aHitResidualsM,aLocalDerivativesM);
931  TMatrixF aGlobalDerivativesM(2,globalDerivativesx.size());
932  this->makeGlobDerivMatrix(globalDerivativesx, globalDerivativesy, aGlobalDerivativesM);
933 
934  // calculates correlation between Hit measurements
935  // FIXME: Should take correlation (and resulting transformation) from original hit,
936  // not 2x2 matrix from ReferenceTrajectory: That can come from error propagation etc.!
937  const double corr = aHitCovarianceM(0,1) / sqrt(aHitCovarianceM(0,0) * aHitCovarianceM(1,1));
938  if (theMonitor) theMonitor->fillCorrelations2D(corr, aRecHit);
939  bool diag = false; // diagonalise only tracker TID, TEC
940  switch(aRecHit->geographicalId().subdetId()) {
941  case SiStripDetId::TID:
942  case SiStripDetId::TEC:
943  if (aRecHit->geographicalId().det() == DetId::Tracker && TMath::Abs(corr) > theMaximalCor2D) {
944  this->diagonalize(aHitCovarianceM, aLocalDerivativesM, aHitResidualsM, aGlobalDerivativesM);
945  diag = true;
946  }
947  break;
948  default:;
949  }
950 
951  float newResidX = aHitResidualsM(0,0);
952  float newResidY = aHitResidualsM(1,0);
953  float newHitErrX = TMath::Sqrt(aHitCovarianceM(0,0));
954  float newHitErrY = TMath::Sqrt(aHitCovarianceM(1,1));
955  float *newLocalDerivsX = aLocalDerivativesM[0].GetPtr();
956  float *newLocalDerivsY = aLocalDerivativesM[1].GetPtr();
957  float *newGlobDerivsX = aGlobalDerivativesM[0].GetPtr();
958  float *newGlobDerivsY = aGlobalDerivativesM[1].GetPtr();
959  const int nLocal = aLocalDerivativesM.GetNcols();
960  const int nGlobal = aGlobalDerivativesM.GetNcols();
961 
962  if (diag && (newHitErrX > newHitErrY)) { // also for 2D hits?
963  // measurement with smaller error is x-measurement (for !is2D do not fill y-measurement):
964  std::swap(newResidX, newResidY);
965  std::swap(newHitErrX, newHitErrY);
966  std::swap(newLocalDerivsX, newLocalDerivsY);
967  std::swap(newGlobDerivsX, newGlobDerivsY);
968  }
969 
970  // &(globalLabels[0]) is valid - as long as vector is not empty
971  // cf. http://www.parashift.com/c++-faq-lite/containers.html#faq-34.3
972  theMille->mille(nLocal, newLocalDerivsX, nGlobal, newGlobDerivsX,
973  &(globalLabels[0]), newResidX, newHitErrX);
974 
975  if (theMonitor) {
976  theMonitor->fillDerivatives(aRecHit, newLocalDerivsX, nLocal, newGlobDerivsX, nGlobal,
977  &(globalLabels[0]));
978  theMonitor->fillResiduals(aRecHit, refTrajPtr->trajectoryStates()[iTrajHit],
979  iTrajHit, newResidX, newHitErrX, false);
980  }
981  const bool isReal2DHit = this->is2D(aRecHit); // strip is 1D (except matched hits)
982  if (isReal2DHit) {
983  theMille->mille(nLocal, newLocalDerivsY, nGlobal, newGlobDerivsY,
984  &(globalLabels[0]), newResidY, newHitErrY);
985  if (theMonitor) {
986  theMonitor->fillDerivatives(aRecHit, newLocalDerivsY, nLocal, newGlobDerivsY, nGlobal,
987  &(globalLabels[0]));
988  theMonitor->fillResiduals(aRecHit, refTrajPtr->trajectoryStates()[iTrajHit],
989  iTrajHit, newResidY, newHitErrY, true);// true: y
990  }
991  }
992 
993  return (isReal2DHit ? 2 : 1);
994 }
995 
996 //__________________________________________________________________________________________________
998 ::addMsMeas(const ReferenceTrajectoryBase::ReferenceTrajectoryPtr &refTrajPtr, unsigned int iMsMeas)
999 {
1000  TMatrixDSym aHitCovarianceM(1);
1001  TMatrixF aHitResidualsM(1,1);
1002  TMatrixF aLocalDerivativesM(1, refTrajPtr->derivatives().num_col());
1003  // below method fills above 3 'matrices'
1004  this->addRefTrackMsMeas1D(refTrajPtr, iMsMeas, aHitCovarianceM, aHitResidualsM, aLocalDerivativesM);
1005 
1006  // no global parameters (use dummy 0)
1007  TMatrixF aGlobalDerivativesM(1,1);
1008  aGlobalDerivativesM(0,0) = 0;
1009 
1010  float newResidX = aHitResidualsM(0,0);
1011  float newHitErrX = TMath::Sqrt(aHitCovarianceM(0,0));
1012  float *newLocalDerivsX = aLocalDerivativesM[0].GetPtr();
1013  float *newGlobDerivsX = aGlobalDerivativesM[0].GetPtr();
1014  const int nLocal = aLocalDerivativesM.GetNcols();
1015  const int nGlobal = 0;
1016 
1017  theMille->mille(nLocal, newLocalDerivsX, nGlobal, newGlobDerivsX,
1018  &nGlobal, newResidX, newHitErrX);
1019 }
1020 
1021 //____________________________________________________
1023  const TkFittedLasBeamCollection &lasBeams,
1024  const TsosVectorCollection &lasBeamTsoses)
1025 {
1026  TsosVectorCollection::const_iterator iTsoses = lasBeamTsoses.begin();
1027  for(TkFittedLasBeamCollection::const_iterator iBeam = lasBeams.begin(), iEnd = lasBeams.end();
1028  iBeam != iEnd; ++iBeam, ++iTsoses){ // beam/tsoses parallel!
1029 
1030  edm::LogInfo("Alignment") << "@SUB=MillePedeAlignmentAlgorithm::addLaserData"
1031  << "Beam " << iBeam->getBeamId() << " with "
1032  << iBeam->parameters().size() << " parameters and "
1033  << iBeam->getData().size() << " hits.\n There are "
1034  << iTsoses->size() << " TSOSes.";
1035 
1036  this->addLasBeam(eventInfo, *iBeam, *iTsoses);
1037  }
1038 }
1039 
1040 //____________________________________________________
1042  const TkFittedLasBeam &lasBeam,
1043  const std::vector<TrajectoryStateOnSurface> &tsoses)
1044 {
1045  AlignmentParameters *dummyPtr = 0; // for globalDerivativesHierarchy()
1046  std::vector<float> lasLocalDerivsX; // buffer for local derivatives
1047  const unsigned int beamLabel = thePedeLabels->lasBeamLabel(lasBeam.getBeamId());// for global par
1048 
1049  for (unsigned int iHit = 0; iHit < tsoses.size(); ++iHit) {
1050  if (!tsoses[iHit].isValid()) continue;
1051  // clear buffer
1052  theFloatBufferX.clear();
1053  theFloatBufferY.clear();
1054  theIntBuffer.clear();
1055  lasLocalDerivsX.clear();
1056  // get alignables and global parameters
1057  const SiStripLaserRecHit2D &hit = lasBeam.getData()[iHit];
1059  this->globalDerivativesHierarchy(eventInfo,
1060  tsoses[iHit], lasAli, lasAli,
1062  // fill derivatives vector from derivatives matrix
1063  for (unsigned int nFitParams = 0;
1064  nFitParams < static_cast<unsigned int>(lasBeam.parameters().size());
1065  ++nFitParams) {
1066  const float derivative = lasBeam.derivatives()[iHit][nFitParams];
1067  if (nFitParams < lasBeam.firstFixedParameter()) { // first local beam parameters
1068  lasLocalDerivsX.push_back(derivative);
1069  } else { // now global ones
1070  const unsigned int numPar = nFitParams - lasBeam.firstFixedParameter();
1071  theIntBuffer.push_back(thePedeLabels->parameterLabel(beamLabel, numPar));
1072  theFloatBufferX.push_back(derivative);
1073  }
1074  } // end loop over parameters
1075 
1076  const float residual = hit.localPosition().x() - tsoses[iHit].localPosition().x();
1077  // error from file or assume 0.003
1078  const float error = 0.003; // hit.localPositionError().xx(); sqrt???
1079 
1080  theMille->mille(lasLocalDerivsX.size(), &(lasLocalDerivsX[0]), theFloatBufferX.size(),
1081  &(theFloatBufferX[0]), &(theIntBuffer[0]), residual, error);
1082  } // end of loop over hits
1083 
1084  theMille->end();
1085 }
1086 
1088 {
1089  // do some printing, if requested
1090  const bool doOutputOnStdout(pxbSurveyCfg.getParameter<bool>("doOutputOnStdout"));
1091  if (doOutputOnStdout) std::cout << "# Output from addPxbSurvey follows below because doOutputOnStdout is set to True" << std::endl;
1092 
1093  // instantiate a dicer object
1094  SurveyPxbDicer dicer(pxbSurveyCfg.getParameter<std::vector<edm::ParameterSet> >("toySurveyParameters"), pxbSurveyCfg.getParameter<unsigned int>("toySurveySeed"));
1095  std::ofstream outfile(pxbSurveyCfg.getUntrackedParameter<std::string>("toySurveyFile").c_str());
1096 
1097  // read data from file
1098  std::vector<SurveyPxbImageLocalFit> measurements;
1099  std::string filename(pxbSurveyCfg.getParameter<edm::FileInPath>("infile").fullPath());
1100  SurveyPxbImageReader<SurveyPxbImageLocalFit> reader(filename, measurements, 800);
1101 
1102  // loop over photographs (=measurements) and perform the fit
1103  for(std::vector<SurveyPxbImageLocalFit>::size_type i=0; i!=measurements.size(); i++)
1104  {
1105  if (doOutputOnStdout) std::cout << "Module " << i << ": ";
1106 
1107  // get the Alignables and their surfaces
1108  AlignableDetOrUnitPtr mod1(theAlignableNavigator->alignableFromDetId(measurements[i].getIdFirst()));
1109  AlignableDetOrUnitPtr mod2(theAlignableNavigator->alignableFromDetId(measurements[i].getIdSecond()));
1110  const AlignableSurface& surf1 = mod1->surface();
1111  const AlignableSurface& surf2 = mod2->surface();
1112 
1113  // the position of the fiducial points in local frame of a PXB module
1114  const LocalPoint fidpoint0(-0.91,+3.30);
1115  const LocalPoint fidpoint1(+0.91,+3.30);
1116  const LocalPoint fidpoint2(+0.91,-3.30);
1117  const LocalPoint fidpoint3(-0.91,-3.30);
1118 
1119  // We choose the local frame of the first module as reference,
1120  // so take the fidpoints of the second module and calculate their
1121  // positions in the reference frame
1122  const GlobalPoint surf2point0(surf2.toGlobal(fidpoint0));
1123  const GlobalPoint surf2point1(surf2.toGlobal(fidpoint1));
1124  const LocalPoint fidpoint0inSurf1frame(surf1.toLocal(surf2point0));
1125  const LocalPoint fidpoint1inSurf1frame(surf1.toLocal(surf2point1));
1126 
1127  // Create the vector for the fit
1129  fidpointvec.push_back(fidpoint0inSurf1frame);
1130  fidpointvec.push_back(fidpoint1inSurf1frame);
1131  fidpointvec.push_back(fidpoint2);
1132  fidpointvec.push_back(fidpoint3);
1133 
1134  // if toy survey is requested, dice the values now
1135  if (pxbSurveyCfg.getParameter<bool>("doToySurvey"))
1136  {
1137  dicer.doDice(fidpointvec,measurements[i].getIdPair(), outfile);
1138  }
1139 
1140  // do the fit
1141  measurements[i].doFit(fidpointvec, thePedeLabels->alignableLabel(mod1), thePedeLabels->alignableLabel(mod2));
1142  SurveyPxbImageLocalFit::localpars_t a; // local pars from fit
1143  a = measurements[i].getLocalParameters();
1144  const SurveyPxbImageLocalFit::value_t chi2 = measurements[i].getChi2();
1145 
1146  // do some reporting, if requested
1147  if (doOutputOnStdout)
1148  {
1149  std::cout << "a: " << a[0] << ", " << a[1] << ", " << a[2] << ", " << a[3]
1150  << " S= " << sqrt(a[2]*a[2]+a[3]*a[3])
1151  << " phi= " << atan(a[3]/a[2])
1152  << " chi2= " << chi2 << std::endl;
1153  }
1154  if (theMonitor)
1155  {
1157  theMonitor->fillPxbSurveyHistsLocalPars(a[0],a[1],sqrt(a[2]*a[2]+a[3]*a[3]),atan(a[3]/a[2]));
1158  }
1159 
1160  // pass the results from the local fit to mille
1162  {
1163  theMille->mille((int)measurements[i].getLocalDerivsSize(),
1164  measurements[i].getLocalDerivsPtr(j),
1165  (int)measurements[i].getGlobalDerivsSize(),
1166  measurements[i].getGlobalDerivsPtr(j),
1167  measurements[i].getGlobalDerivsLabelPtr(j),
1168  measurements[i].getResiduum(j),
1169  measurements[i].getSigma(j));
1170  }
1171  theMille->end();
1172  }
1173  outfile.close();
1174 }
1175 
1176 
1177 /*____________________________________________________
1178 void MillePedeAlignmentAlgorithm::addBeamSpotConstraint
1179 (const ReferenceTrajectoryBase::ReferenceTrajectoryPtr &refTrajPtr,
1180  const edm::Event & iEvent )
1181 {
1182  // --- get BS from Event:
1183  const reco::BeamSpot* bSpot;
1184  edm::Handle<reco::BeamSpot> recoBeamSpotHandle;
1185  iEvent.getByType(recoBeamSpotHandle);
1186  bSpot = recoBeamSpotHandle.product();
1187 
1188  //GlobalPoint gPointBs(0.,0.,0.);
1189  GlobalPoint gPointBs(bSpot->x0(), bSpot->y0(), bSpot->z0());
1190  const TrajectoryStateOnSurface trackTsos = refTrajPtr->trajectoryStates()[0];
1191  // create a FTS from innermost TSOS:
1192  FreeTrajectoryState innerFts = *(trackTsos.freeTrajectoryState());
1193  //create a TrajectoryStateClosestToBeamLine:
1194  TrajectoryStateClosestToPointBuilder *tsctpBuilder = new TSCPBuilderNoMaterial();
1195  TrajectoryStateClosestToPoint tsctp = tsctpBuilder->operator()(trackTsos,gPointBs);
1196  FreeTrajectoryState pcaFts = tsctp.theState();
1197  edm::LogInfo("CHK") << " beamspot TSCP " << tsctp.referencePoint() << tsctp.position()
1198  << tsctp.perigeeParameters().vector();
1199  const AlgebraicVector5 perigeeVecPars = tsctp.perigeeParameters().vector();
1200 
1201  PerigeeConversions perigeeConv;
1202  const AlgebraicMatrix55& curv2perigee = perigeeConv.jacobianCurvilinear2Perigee(pcaFts);
1203  edm::LogInfo("CHK") << " beamspot C2P " << curv2perigee;
1204 
1205  //propagation
1206  AnalyticalPropagator propagator(&(innerFts.parameters().magneticField()), anyDirection);
1207  std::pair< TrajectoryStateOnSurface, double > tsosWithPath = propagator.propagateWithPath(pcaFts,trackTsos.surface());
1208  edm::LogInfo("CHK") << " beamspot s0 " << tsosWithPath.second;
1209  edm::LogInfo("CHK") << " beamspot t2c " << refTrajPtr->trajectoryToCurv();
1210  if (!tsosWithPath.first.isValid()) return;
1211 
1212  // jacobian in curvilinear frame for propagation from the end point (inner TSOS) to the starting point (PCA)
1213  AnalyticalCurvilinearJacobian curvJac( pcaFts.parameters(),
1214  tsosWithPath.first.globalPosition(),
1215  tsosWithPath.first.globalMomentum(),
1216  tsosWithPath.second );
1217  int ierr;
1218  const AlgebraicMatrix55& matCurvJac = curvJac.jacobian().Inverse(ierr);
1219  edm::LogInfo("CHK") << " beamspot CurvJac " << matCurvJac;
1220  // jacobion trajectory to curvilinear
1221  // const AlgebraicMatrix &locDerivMatrix = refTrajPtr->derivatives();
1222  const AlgebraicMatrix55& traj2curv = asSMatrix<5,5>(refTrajPtr->trajectoryToCurv());
1223  //combine the transformation jacobian:
1224  AlgebraicMatrix55 newJacobian = curv2perigee * matCurvJac * traj2curv;
1225  edm::LogInfo("CHK") << " beamspot newJac " << newJacobian;
1226 
1227  //get the Beam Spot residual
1228  const float residuumIP = -perigeeVecPars[3];
1229  const float sigmaIP = bSpot->BeamWidth();
1230  edm::LogInfo("CHK2") << " beamspot-res " << residuumIP << " " << perigeeVecPars[0] << " " << perigeeVecPars[1] << " " << perigeeVecPars[2];
1231 
1232  std::vector<float> ipLocalDerivs(5);
1233  for (unsigned int i = 0; i < ipLocalDerivs.size(); ++i) {
1234  ipLocalDerivs[i] = newJacobian(3,i);
1235  }
1236 
1237  // to be fixed: null global derivatives is right but the size is detemined from SelPar.size!
1238  std::vector<float> ipGlobalDerivs(4);
1239  for (unsigned int i = 0; i < 4; ++i) {
1240  ipGlobalDerivs[i] = 0.;
1241  }
1242  std::vector<int> ipGlobalLabels(4);
1243  for (unsigned int i = 0; i < 4; ++i) {
1244  ipGlobalLabels[i] = 0;
1245  }
1246 
1247  if(theAliBeamspot){
1248  double phi = perigeeVecPars[2];
1249  double dz = perigeeVecPars[4];
1250  ipGlobalDerivs[0] = sin(phi);
1251  ipGlobalDerivs[1] = -cos(phi);
1252  ipGlobalDerivs[2] = sin(phi)*dz;
1253  ipGlobalDerivs[3] = -cos(phi)*dz;
1254 
1255  ipGlobalLabels[0] = 250000;
1256  ipGlobalLabels[1] = 250001;
1257  ipGlobalLabels[2] = 250002;
1258  ipGlobalLabels[3] = 250003;
1259  }
1260 
1261 
1262  theMille->mille(ipLocalDerivs.size(), &(ipLocalDerivs[0]),
1263  ipGlobalDerivs.size(), &(ipGlobalDerivs[0]), &(ipGlobalLabels[0]),
1264  residuumIP, sigmaIP);
1265 
1266 
1267  // delete new objects:
1268  delete tsctpBuilder;
1269  tsctpBuilder = NULL;
1270 
1271 } */
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
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
void increaseHitsX(unsigned int add=1)
increase hits for x-measurement
bool read(std::vector< Alignable * > &alignables, bool setUserVars)
Definition: PedeReader.cc:50
void addMsMeas(const ReferenceTrajectoryBase::ReferenceTrajectoryPtr &refTrajPtr, unsigned int iMsMeas)
adds data from reference trajectory from a specific multiple scattering measurement ...
std::vector< coord_t > fidpoint_t
void increaseHitsY(unsigned int add=1)
increase hits for y-measurement
std::vector< Alignable * > theAlignables
TrajectoryFactoryBase::ReferenceTrajectoryCollection RefTrajColl
std::vector< ParameterSet > VParameterSet
Definition: ParameterSet.h:30
virtual unsigned int alignableLabel(Alignable *alignable) const =0
void writeAlignableOriginalPositions(const align::Alignables &alivec, const char *filename, int iter, bool validCheck, int &ierr)
write Alignable original (before misalignment) absolute positions
void fillPxbSurveyHistsLocalPars(const float &a0, const float &a1, const float &S, const float &phi)
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 applyParameters(void)
Obsolete: Use AlignableNavigator::alignableDetFromDetId and alignableFromAlignableDet.
virtual LocalPoint localPosition() const
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
const ConstTrajTrackPairCollection & trajTrackPairs_
const TsosVectorCollection * tkLasBeamTsoses_
might be null!
virtual unsigned int lasBeamLabel(unsigned int lasBeamId) const =0
virtual void initialize(const edm::EventSetup &setup, AlignableTracker *tracker, AlignableMuon *muon, AlignableExtras *extras, AlignmentParameterStore *store)
Call at beginning of job.
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
void fillPxbSurveyHistsChi2(const float &chi2)
virtual unsigned int parameterLabel(unsigned int aliLabel, unsigned int parNum) const =0
returns the label for a given alignable parameter number combination
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
void addRefTrackMsMeas1D(const ReferenceTrajectoryBase::ReferenceTrajectoryPtr &refTrajPtr, unsigned int iTrajHit, TMatrixDSym &aHitCovarianceM, TMatrixF &aHitResidualsM, TMatrixF &aLocalDerivativesM)
adds multiple scattering data from reference trajectory from a specific Hit
const AlgebraicVector & parameters(void) const
Get alignment parameters.
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)
list outfile
Definition: EdgesToViz.py:91
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()
void fillUsedTrack(const reco::Track *track, unsigned int nHitX, unsigned int nHitY)
void swap(edm::DataFrameContainer &lhs, edm::DataFrameContainer &rhs)
T sqrt(T t)
Definition: SSEVec.h:28
virtual void endRun(const EventInfo &eventInfo, const EndRunInfo &runInfo, const edm::EventSetup &setup)
Run on run products, e.g. TkLAS.
int runPede(const std::string &masterSteer) const
run pede, masterSteer should be as returned from buildMasterSteer(...)
Definition: PedeSteerer.cc:759
unsigned int getBeamId(void) const
return the full beam identifier
Definition: TkLasBeam.h:25
void end()
Definition: Mille.cc:129
tuple result
Definition: query.py:137
AlignmentParameterStore * theAlignmentParameterStore
directory for all kind of files
unsigned int hitsY() const
get number of hits for y-measurement
bool is2D(const TransientTrackingRecHit::ConstRecHitPointer &recHit) const
true if hit belongs to 2D detector (currently tracker specific)
virtual void setParametersForRunRange(const RunRange &runrange)
void diagonalize(TMatrixDSym &aHitCovarianceM, TMatrixF &aLocalDerivativesM, TMatrixF &aHitResidualsM, TMatrixF &theGlobalDerivativesM) const
int j
Definition: DBlmapReader.cc:9
std::string buildMasterSteer(const std::vector< std::string > &binaryFiles)
construct (and return name of) master steering file from config, binaryFiles etc. ...
Definition: PedeSteerer.cc:719
Container::value_type value_type
int addMeasurementData(const EventInfo &eventInfo, const ReferenceTrajectoryBase::ReferenceTrajectoryPtr &refTrajPtr, unsigned int iHit, AlignmentParameters *&params)
void writeAlignableRelativePositions(const align::Alignables &alivec, const char *filename, int iter, bool validCheck, int &ierr)
write Alignable relative positions (shift,rotation)
void mille(int NLC, const float *derLc, int NGL, const float *derGl, const int *label, float rMeas, float sigma)
Definition: Mille.cc:43
const AlignableSurface & surface() const
Return the Surface (global position and orientation) of the object.
Definition: Alignable.h:126
JetCorrectorParameters corr
Definition: classes.h:9
bool addHits(const std::vector< Alignable * > &alis, const std::vector< AlignmentUserVariables * > &mpVars) const
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
tuple out
Definition: dbtoconf.py:99
std::vector< ConstRecHitPointer > ConstRecHitContainer
bool areEmptyParams(const std::vector< Alignable * > &alignables) const
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::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 setUserVariables(AlignmentUserVariables *auv)
Set pointer to user variables.
void buildSubSteer(AlignableTracker *aliTracker, AlignableMuon *aliMuon, AlignableExtras *aliExtras)
construct steering files about hierarchy, fixing etc. an keep track of their names ...
Definition: PedeSteerer.cc:671
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:203
Class to hold one picture of the BPix survey.
const TkFittedLasBeamCollection * tkLasBeams_
int mode
Definition: AMPTWrapper.h:139
std::vector< value_t > localpars_t
void fillTrack(const reco::Track *track)
const int size(void) const
Get number of parameters.
virtual void run(const edm::EventSetup &setup, const EventInfo &eventInfo)
Run the algorithm on trajectories and tracks.
define run information passed to algorithms (in endRun)
void buildUserVariables(const std::vector< Alignable * > &alignables) const
add MillePedeVariables for each AlignmentParameters (exception if no parameters...)
MillePedeAlignmentAlgorithm(const edm::ParameterSet &cfg)
Constructor.
TrajectoryFactoryBase * theTrajectoryFactory
virtual ~MillePedeAlignmentAlgorithm()
Destructor.
std::vector< TkFittedLasBeam > TkFittedLasBeamCollection
double a
Definition: hdecay.h:121
align::GlobalPoints toGlobal(const align::LocalPoints &) const
Return in global coord given a set of local points.
virtual const ReferenceTrajectoryCollection trajectories(const edm::EventSetup &setup, const ConstTrajTrackPairCollection &tracks, const reco::BeamSpot &beamSpot) const =0
tuple filename
Definition: lut2db_cfg.py:20
void fillRefTrajectory(const ReferenceTrajectoryBase::ReferenceTrajectoryPtr &refTrajPtr)
Definition: Mille.h:26
TransientTrackingRecHit::ConstRecHitContainer ConstRecHitContainer
void kill()
Definition: Mille.cc:121
tuple cout
Definition: gather_cfg.py:41
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:170
std::pair< unsigned int, unsigned int > addReferenceTrajectory(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) ...
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
const AlgebraicSymMatrix & covariance(void) const
Get parameter covariance matrix.
Constructor of the full muon geometry.
Definition: AlignableMuon.h:39
uint32_t dimension(pat::CandKinResolution::Parametrization parametrization)
Returns the number of free parameters in a parametrization (3 or 4)
T x() const
Definition: PV3DBase.h:56
AlignableDetOrUnitPtr alignableFromDetId(const DetId &detid)
Returns AlignableDetOrUnitPtr corresponding to given DetId.
Alignable * mother() const
Return pointer to container alignable (if any)
Definition: Alignable.h:85
void setup(std::vector< TH2F > &depth, std::string name, std::string units="")
tuple size
Write out results.
T get(const Candidate &c)
Definition: component.h:56
const align::Alignables & alignables(void) const
get all alignables
std::vector< ConstTrajTrackPair > ConstTrajTrackPairCollection
A derivative(const A &_)
Definition: Derivative.h:18
define event information passed to algorithms
virtual void terminate()
Call at end of job.