CMS 3D CMS Logo

PedeSteerer.cc
Go to the documentation of this file.
1 
11 #include "PedeSteerer.h"
13 
15 
17 
19 #include <boost/cstdint.hpp>
26 
28 // for 'type identification' as Alignable
32 // GF doubts the need of these includes from include checker campaign:
38 // end of doubt
39 
41 
42 #include <atomic>
43 #include <fstream>
44 #include <sstream>
45 #include <algorithm>
46 
47 // from ROOT
48 #include <TSystem.h>
49 #include <TMath.h>
50 
51 #include <iostream>
52 
53 //_________________________________________________________________________
56  const edm::ParameterSet &config, const std::string &defaultDir,
57  bool noSteerFiles) :
58  myParameterStore(store), myLabels(labels),
59  alignableObjectId_{AlignableObjectId::commonObjectIdProvider(aliTracker, aliMuon)},
62  myNoSteerFiles(noSteerFiles),
63  myIsSteerFileDebug(myConfig.getUntrackedParameter<bool>("steerFileDebug")),
64  myParameterSign(myConfig.getUntrackedParameter<int>("parameterSign")),
65  theMinHieraConstrCoeff(myConfig.getParameter<double>("minHieraConstrCoeff")),
66  theMinHieraParPerConstr(myConfig.getParameter<unsigned int>("minHieraParPerConstr")),
67  theConstrPrecision(myConfig.getParameter<unsigned int>("constrPrecision")),
68  theCoordMaster(nullptr)
69 {
70  if (myParameterSign != 1 && myParameterSign != -1) {
71  cms::Exception("BadConfig") << "Expect PedeSteerer.parameterSign = +/-1, "
72  << "found " << myParameterSign << ".";
73  }
74 
75  // Correct directory, needed before asking for fileName(..):
76  if (myDirectory.empty()) myDirectory = defaultDir;
77  if (!myDirectory.empty() && myDirectory.find_last_of('/') != myDirectory.size() - 1) {
78  myDirectory += '/'; // directory may need '/'
79  }
80 
81  const std::vector<Alignable*> &alis = myParameterStore->alignables();
82  if (!this->checkParameterChoices(alis)) {} // anyway thrown exception
83 
84  // Coordinate system selection and correction before everything
86  if (!theCoordDefiners.empty()) { // Create steering with constraints to define coordinate system:
87  // OK, some hacks:
88  // - we want a composite with global coordinates where tracker and muon are components
89  // (to call RigidBodyAl.Param.->globalParameters() in correctToReferenceSystem(..))
90  // - so we create a AlignableComposite and add tracker and muon
91  // - but the addComponent(..) method is so cute that it calculates position from
92  // daughters' deepComponents()
93  // - so we want to move it back to (0,0,0), but ali->move(..) would move daughters as well
94  // => cheat with a const_cast and move only the surface back
95  // - this hacked master object does not have a label for its parameters
96  // => some warnings if debug output selected in pedeSteer files
97  // - we must not delete our new master (little mem. leak...) since that would delete
98  // the daughters as well!
99  if (aliTracker) {
100  theCoordMaster = new AlignableComposite(aliTracker->id(), align::invalid);
101  theCoordMaster->addComponent(aliTracker);
102  } else if (aliMuon) {
103  theCoordMaster = new AlignableComposite(aliMuon->id(), align::invalid);
104  } else {
105  throw cms::Exception("BadConfig")
106  << "[PedeSteerer]" << "Cannot define global coordinate system "
107  << "with neither tracker nor muon!";
108  }
109  if (aliMuon) theCoordMaster->addComponent(aliMuon); // tracker is already added if existing
110  if (aliExtras) { // tracker and/or muon are already added if existing
111  align::Alignables allExtras = aliExtras->components();
112  for ( std::vector<Alignable*>::iterator it = allExtras.begin(); it != allExtras.end(); ++it ) {
114  }
115  }
116 
118  AlignableSurface & masterSurf = const_cast<AlignableSurface&>(theCoordMaster->surface());
119  masterSurf.move(align::GlobalVector(-tmpPos.x(),-tmpPos.y(),-tmpPos.z()));
120 
121  if (this->isCorrectToRefSystem(theCoordDefiners)) { // defined by 's' (MC): 'correct' misalignment
122  this->correctToReferenceSystem(); // really before 'defineCoordinates'?
123  }
124  }
125 
126 }
127 
128 //___________________________________________________________________________
130 {
131  // delete theCoordMaster; NO, see above
132 }
133 
134 //_________________________________________________________________________
135 bool PedeSteerer::isNoHiera(const Alignable* ali) const
136 {
137  return (myNoHieraCollection.find(ali) != myNoHieraCollection.end());
138 }
139 
140 //_________________________________________________________________________
141 double PedeSteerer::cmsToPedeFactor(unsigned int parNum) const
142 {
143  return 1.; // mmh, otherwise would need to FIXME hierarchyConstraint...
144 
145  switch (parNum) {
148  return 1000.; // cm to mum *1/10 to get smaller values
150  return 2500.; // cm to mum *1/4
153  return 1000.; // rad to mrad (no first guess for sensitivity yet)
155  return 10000.; // rad to mrad *10 to get larger values
156  default:
157  return 1.;
158  }
159 }
160 
161 //_________________________________________________________________________
162 unsigned int PedeSteerer::buildNoHierarchyCollection(const std::vector<Alignable*> &alis)
163 {
164  myNoHieraCollection.clear(); // just in case of re-use...
165 
166  for (std::vector<Alignable*>::const_iterator iAli = alis.begin() ; iAli != alis.end(); ++iAli) {
167  AlignmentParameters *params = (*iAli)->alignmentParameters();
168  SelectionUserVariables *selVar = dynamic_cast<SelectionUserVariables*>(params->userVariables());
169  if (!selVar) continue;
170  // Now check whether taking out of hierarchy is selected - must be consistent!
171  unsigned int numNoHieraPar = 0;
172  unsigned int numHieraPar = 0;
173  for (unsigned int iParam = 0; static_cast<int>(iParam) < params->size(); ++iParam) {
174  const char selector = selVar->fullSelection()[iParam];
175  if (selector == 'C' || selector == 'F' || selector == 'H') {
176  ++numNoHieraPar;
177  } else if (selector == 'c' || selector == 'f' || selector == '1' || selector == 'r'
178  || selector == 's') {
179  ++numHieraPar;
180  } // else ... accept '0' as undetermined
181  }
182  if (numNoHieraPar) { // Selected to be taken out.
183  if (numHieraPar) { // Inconsistent: Some parameters still in hierarchy ==> exception!
184  throw cms::Exception("BadConfig")
185  << "[PedeSteerer::buildNoHierarchyCollection] All active parameters of alignables to be "
186  << " taken out of the hierarchy must be marked with capital letters 'C', 'F' or 'H'!";
187  }
188  bool isInHiera = false; // Check whether Alignable is really part of hierarchy:
189  Alignable *mother = *iAli;
190  while ((mother = mother->mother())) {
191  if (mother->alignmentParameters()) isInHiera = true; // could 'break;', but loop is short
192  }
193  // Complain, but keep collection short if not in hierarchy:
194  if (isInHiera) myNoHieraCollection.insert(*iAli);
195  else edm::LogWarning("Alignment") << "@SUB=PedeSteerer::buildNoHierarchyCollection"
196  << "Alignable not in hierarchy, no need to remove it!";
197  }
198  } // end loop on alignables
199 
200  return myNoHieraCollection.size();
201 }
202 
203 //_________________________________________________________________________
204 bool PedeSteerer::checkParameterChoices(const std::vector<Alignable*> &alis) const
205 {
206  for (std::vector<Alignable*>::const_iterator iAli = alis.begin() ; iAli != alis.end(); ++iAli) {
207  AlignmentParameters *paras = (*iAli)->alignmentParameters();
208  SelectionUserVariables *selVar = dynamic_cast<SelectionUserVariables*>(paras->userVariables());
209  if (!selVar) continue;
210  for (unsigned int iParam = 0; static_cast<int>(iParam) < paras->size(); ++iParam) {
211  const char sel = selVar->fullSelection()[iParam];
212  if (sel != 'f' && sel != 'F' && sel != 'c' && sel != 'C' &&
213  sel != '0' && sel != '1' && sel != 'H' && sel != 'r' && sel != 's') {
214  throw cms::Exception("BadConfig")
215  << "[PedeSteerer::unknownParameterChoices] "
216  << "Unexpected parameter selector '" << sel
217  << "', use \n'f/F' (fix),\n'c/C' (fix at correct pos.),\n'1/H' (free),\n"
218  << "'r/s' (free, but defining reference system, trying to correct misalignment if 's')"
219  << " or \n'0' (ignore).\n"
220  << "Capital letters mean that the Alignable is taken out of a possible hierarchy,\n"
221  << "but must be used consistently for all its parameters.";
222  return false; // unreached
223  }
224  }
225  }
226 
227  return true;
228 }
229 
230 //_________________________________________________________________________
231 std::pair<unsigned int, unsigned int>
232 PedeSteerer::fixParameters(const std::vector<Alignable*> &alis, const std::string &fileName)
233 {
234  // return number of parameters fixed at 0. and fixed at original position
235  std::pair<unsigned int, unsigned int> numFixNumFixCor(0, 0);
236 
237  std::ofstream *filePtr = nullptr;
238 
239  for (std::vector<Alignable*>::const_iterator iAli = alis.begin() ; iAli != alis.end(); ++iAli) {
240 
241  AlignmentParameters *params = (*iAli)->alignmentParameters();
242  SelectionUserVariables *selVar = dynamic_cast<SelectionUserVariables*>(params->userVariables());
243  if (!selVar) continue;
244 
245  for (unsigned int iParam = 0; static_cast<int>(iParam) < params->size(); ++iParam) {
246  const unsigned int nInstances = myLabels->numberOfParameterInstances(*iAli, iParam);
247  for (unsigned int iInstance=0;iInstance<nInstances;++iInstance) {
248  int whichFix = this->fixParameter(*iAli, iInstance, iParam,
249  selVar->fullSelection()[iParam], filePtr,
250  fileName);
251  if (whichFix == 1) {
252  ++(numFixNumFixCor.first);
253  } else if (whichFix == -1) {
254  ++(numFixNumFixCor.second);
255  }
256  }
257  }
258  }
259 
260  delete filePtr; // automatically flushes, no problem if NULL ptr.
261 
262  return numFixNumFixCor;
263 }
264 
265 //_________________________________________________________________________
266 int PedeSteerer::fixParameter(Alignable *ali, unsigned int iInstance,
267  unsigned int iParam, char selector,
268  std::ofstream* &filePtr, const std::string &fileName)
269 {
270  int result = 0;
271  float fixAt = 0.;
272  if (selector == 'c' || selector == 'C') {
274  throw cms::Exception("BadConfig")
275  << "PedeSteerer::fixParameter: correction (c/C) possible only for RigidBodyParameters";
276  }
277  fixAt = -this->parameterSign() * RigidBodyAlignmentParameters(ali, true).parameters()[iParam];
278  result = -1;
279  } else if (selector == 'f' || selector == 'F') {
280  result = 1;
281  }
282 
283  if (result) {
284  if (!filePtr) {
285  filePtr = this->createSteerFile(fileName, true);
286  (*filePtr) << "Parameter\n";
287  }
288  std::ofstream &file = *filePtr;
289 
290  const unsigned int aliLabel = myLabels->alignableLabelFromParamAndInstance(ali, iParam, iInstance);
291  file << myLabels->parameterLabel(aliLabel, iParam) << " "
292  << fixAt * this->cmsToPedeFactor(iParam) << " -1.0";
293  if (myIsSteerFileDebug) { // debug
294  const GlobalPoint position(ali->globalPosition());
295  file << " * id " << ali->id() << ", eta " << position.eta() << ", z " << position.z()
296  << ", r " << position.perp() << ", phi " << position.phi();
297  }
298  file << "\n";
299  }
300 
301  return result;
302 }
303 
304 //_________________________________________________________________________
305 std::vector<Alignable*> PedeSteerer::selectCoordinateAlis(const std::vector<Alignable*> &alis) const
306 {
307  std::vector<Alignable*> coordAlis;
308 
309  for (std::vector<Alignable*>::const_iterator iAli = alis.begin() ; iAli != alis.end(); ++iAli) {
310  AlignmentParameters *params = (*iAli)->alignmentParameters();
311  SelectionUserVariables *selVar = dynamic_cast<SelectionUserVariables*>(params->userVariables());
312  if (!selVar) continue;
313  unsigned int refParam = 0;
314  unsigned int nonRefParam = 0;
315  for (unsigned int iParam = 0; static_cast<int>(iParam) < params->size(); ++iParam) {
316  const char selector = selVar->fullSelection()[iParam];
317  if (selector == 'r' || selector == 's') {
318  ++refParam;
319  } else if (selector != '0' && selector != 'f') { // allow also 'c'?
320  ++nonRefParam;
321  }
322  }
323  // Check whether some 'r/s' selection string. If yes and selection makes sense, add to result:
324  if (refParam) {
325  if (nonRefParam) {
326  throw cms::Exception("BadConfig")
327  << "[PedeSteerer::selectCoordinateAlis] All active parameters of alignables defining "
328  << "the coordinate system must be marked with 'r/s' (or fixed, 'f')!";
329  } else {
330  Alignable *mother = *iAli;
331  while ((mother = mother->mother())) {
332  if (mother->alignmentParameters()) {
333  throw cms::Exception("BadConfig") << "[PedeSteerer::selectCoordinateAlis] "
334  << "Alignables defining the coordinate system must "
335  << "be highest level!";
336  }
337  }
338  coordAlis.push_back(*iAli);
339  }
340  }
341  } // end loop on alignables
342 
343  return coordAlis;
344 }
345 
346 
347 //_________________________________________________________________________
348 void PedeSteerer::defineCoordinates(const std::vector<Alignable*> &alis, Alignable *aliMaster,
349  const std::string &fileName)
350 {
351  std::ofstream *filePtr = this->createSteerFile(fileName, true);
352  (*filePtr) << "* Constraints to define coordinate system:\n";
353  if (!aliMaster || aliMaster->alignmentParameters()) {
354  throw cms::Exception("BadConfig")
355  << "[PedeSteerer::defineCoordinates] " << "No master alignable or it has parameters!";
356  }
357  if (myIsSteerFileDebug) { // See constructor comments about hack:
358  edm::LogError("Alignment") << "@SUB=PedeSteerer::defineCoordinates"
359  << "Ignore following LogicErrors from PedeLabeler.";
360  }
361  AlignmentParameters *par = new RigidBodyAlignmentParameters(aliMaster, false);
362  aliMaster->setAlignmentParameters(par); // hierarchyConstraint needs parameters
363  this->hierarchyConstraint(aliMaster, alis, *filePtr);
364  aliMaster->setAlignmentParameters(nullptr); // erase dummy parameters
365 
366  delete filePtr; // automatically flushes, no problem if NULL ptr.
367 }
368 
369 //_________________________________________________________________________
370 bool PedeSteerer::isCorrectToRefSystem(const std::vector<Alignable*> &coordDefiners) const
371 {
372  bool doCorrect = false;
373  bool doNotCorrect = false;
374  for (std::vector<Alignable*>::const_iterator it = coordDefiners.begin(), iE=coordDefiners.end();
375  it != iE; ++it) {
376  SelectionUserVariables *selVar =
377  ((*it)->alignmentParameters() ?
378  dynamic_cast<SelectionUserVariables*>((*it)->alignmentParameters()->userVariables()) : nullptr);
379  if (!selVar) continue; // is an error!?
380 
381  for (unsigned int i = 0; i < selVar->fullSelection().size(); ++i) {
382  if (selVar->fullSelection()[i] == 'r') doNotCorrect = true;
383  else if (selVar->fullSelection()[i] == 's') doCorrect = true;
384  }
385  }
386 
387  if (doCorrect && doNotCorrect) {
388  throw cms::Exception("BadConfig")
389  << "[PedeSteerer::doCorrectToRefSystem]: Parameter selection 's' and 'r' must not coexist!";
390  }
391 
392  return doCorrect;
393 }
394 
395 //_________________________________________________________________________
397 {
398  typedef RigidBodyAlignmentParameters RbPars;
399  if (!theCoordMaster || theCoordDefiners.empty()) return; // nothing was defined
400 
401  std::vector<Alignable*> definerDets; // or ...DetUnits
402  for (std::vector<Alignable*>::iterator it = theCoordDefiners.begin(), iE = theCoordDefiners.end();
403  it != iE; ++it) {// find lowest level objects of alignables that define the coordinate system
404  const std::vector<Alignable*> &comp = (*it)->deepComponents();
405  definerDets.insert(definerDets.end(), comp.begin(), comp.end());
406  }
407 
408  for (unsigned int iLoop = 0; ; ++iLoop) { // iterate: shifts and rotations are not independent
409  AlgebraicVector meanPars(RbPars::N_PARAM);
410  for (std::vector<Alignable*>::iterator it = definerDets.begin(), iE = definerDets.end();
411  it != iE; ++it) { // sum up mean displacements/misrotations:
412  meanPars += RbPars(*it, true).globalParameters();// requires theCoordMaster has global frame
413  }
414  meanPars /= definerDets.size();
415  const align::Scalar squareSum = meanPars.normsq();
416 
417  if (squareSum < 1.e-20) break; // sqrt(1.e-20)=1.e-10: close enough to stop iterating
418  if (iLoop == 0) {
419  edm::LogInfo("Alignment") << "@SUB=PedeSteerer::correctToReferenceSystem"
420  << "Loop " << iLoop << " "
421  << "Mean misalignment of dets of defined coordinate system"
422  << (squareSum < 1.e-20 ? ":" :
423  " (will be iteratively corrected to < 1.e-10):") << meanPars;
424  }
425  if (iLoop >=5) { // 3 iterations should be safe, use 5 for 'more' safety...
426  edm::LogError("Alignment") << "@SUB=PedeSteerer::correctToReferenceSystem"
427  << "No convergence in " << iLoop << " iterations, "
428  << "remaining misalignment: " << meanPars;
429  break;
430  }
431 
432  const GlobalVector globalShift(meanPars[RbPars::dx],meanPars[RbPars::dy],meanPars[RbPars::dz]);
433  theCoordMaster->move(-globalShift); // sign to revert
434  align::EulerAngles globalAngles(3);
435  globalAngles[0] = meanPars[RbPars::dalpha];
436  globalAngles[1] = meanPars[RbPars::dbeta];
437  globalAngles[2] = meanPars[RbPars::dgamma];
438  theCoordMaster->rotateInGlobalFrame(align::toMatrix(-globalAngles)); // sign to revert
439  }
440 
441 }
442 
443 //_________________________________________________________________________
444 unsigned int PedeSteerer::hierarchyConstraints(const std::vector<Alignable*> &alis,
445  const std::string &fileName)
446 {
447  std::ofstream *filePtr = nullptr;
448 
449  unsigned int nConstraints = 0;
450  std::vector<Alignable*> aliDaughts;
451  for (std::vector<Alignable*>::const_iterator iA = alis.begin(), iEnd = alis.end();
452  iA != iEnd; ++iA) {
453  aliDaughts.clear();
454  if (!(*iA)->firstCompsWithParams(aliDaughts)) {
455  edm::LogWarning("Alignment") << "@SUB=PedeSteerer::hierarchyConstraints"
456  << "Some but not all daughters of "
457  << alignableObjectId_.idToString((*iA)->alignableObjectId())
458  << " with params!";
459  }
460  // edm::LogInfo("Alignment") << "@SUB=PedeSteerer::hierarchyConstraints"
461  // << aliDaughts.size() << " ali param components";
462  if (aliDaughts.empty()) continue;
463  // edm::LogInfo("Alignment") << "@SUB=PedeSteerer::hierarchyConstraints"
464  // << aliDaughts.size() << " alignable components ("
465  // << (*iA)->size() << " in total) for "
466  // << aliId.alignableTypeName(*iA)
467  // << ", layer " << aliId.typeAndLayerFromAlignable(*iA).second
468  // << ", position " << (*iA)->globalPosition()
469  // << ", r = " << (*iA)->globalPosition().perp();
470  if (!filePtr) filePtr = this->createSteerFile(fileName, true);
471  ++nConstraints;
472  this->hierarchyConstraint(*iA, aliDaughts, *filePtr);
473  }
474 
475  delete filePtr; // automatically flushes, no problem if NULL ptr.
476 
477  return nConstraints;
478 }
479 //_________________________________________________________________________
481  const std::vector<Alignable*> &components,
482  std::ofstream &file) const
483 {
484  typedef AlignmentParameterStore::ParameterId ParameterId;
485 
486  std::vector<std::vector<ParameterId> > paramIdsVec;
487  std::vector<std::vector<double> > factorsVec;
488  const bool allConstr = false; // true; // make configurable?
489  static std::atomic<bool> allConstrWarning{false};
490  bool expected{false};
491  if (allConstr && allConstrWarning.compare_exchange_strong(expected, true)) {
492  edm::LogWarning("Alignment") << "@SUB=PedeSteerer::hierarchyConstraint"
493  << "changed to use all 6 constraints";
494  }
495  if (!myParameterStore->hierarchyConstraints(ali, components, paramIdsVec, factorsVec, allConstr,
497  edm::LogWarning("Alignment") << "@SUB=PedeSteerer::hierarchyConstraint"
498  << "Problems from store.";
499  }
500 
501  for (unsigned int iConstr = 0; iConstr < paramIdsVec.size(); ++iConstr) {
502  std::ostringstream aConstr;
503 
504  const std::vector<ParameterId> &parIds = paramIdsVec[iConstr];
505  const std::vector<double> &factors = factorsVec[iConstr];
506  unsigned int nParPerConstr = 0; // keep track of used factor/parId pair
507  // parIds.size() == factors.size() granted by myParameterStore->hierarchyConstraints
508  for (unsigned int iParam = 0; iParam < parIds.size(); ++iParam) {
509  Alignable *aliSubComp = parIds[iParam].first;
510  const unsigned int compParNum = parIds[iParam].second;
511  if (this->isNoHiera(aliSubComp)) {
512  if (myIsSteerFileDebug) aConstr << "* Taken out of hierarchy: ";
513  continue;
514  }
515  const unsigned int aliLabel = myLabels->alignableLabel(aliSubComp);
516  const unsigned int paramLabel = myLabels->parameterLabel(aliLabel, compParNum);
517  // FIXME: multiply by cmsToPedeFactor(subcomponent)/cmsToPedeFactor(mother) (or vice a versa?)
518  if (theConstrPrecision > 0)
519  aConstr << paramLabel << " " << std::setprecision(theConstrPrecision) << factors[iParam];
520  else
521  aConstr << paramLabel << " " << factors[iParam];
522  if (myIsSteerFileDebug) { // debug
523  aConstr << " ! for param " << compParNum << " of a "
524  << alignableObjectId_.idToString(aliSubComp->alignableObjectId()) << " at "
525  << aliSubComp->globalPosition() << ", r=" << aliSubComp->globalPosition().perp();
526  }
527  aConstr << "\n";
528  ++nParPerConstr; // OK, we used one.
529  } // end loop on params
530 
531  //
532  if (nParPerConstr && nParPerConstr >= theMinHieraParPerConstr) { // Enough to make sense?
533  if (myIsSteerFileDebug) { //debug
534  file << "\n* Nr. " << iConstr << " of a '"
535  << alignableObjectId_.idToString(ali->alignableObjectId()) << "' (label "
536  << myLabels->alignableLabel(const_cast<Alignable*>(ali)) // ugly cast: FIXME!
537  << "), position " << ali->globalPosition()
538  << ", r = " << ali->globalPosition().perp();
539  }
540  file << "\nConstraint 0.\n" << aConstr.str(); // in future 'Wconstraint'?
541  } else if (nParPerConstr > 0) { // no warning for trivial case...
542  edm::LogWarning("Alignment") << "@SUB=PedeSteerer::hierarchyConstraint"
543  << "Skip constraint on " << nParPerConstr
544  << " parameter(s):\n" << aConstr.str();
545  }
546  } // end loop on constraints
547 }
548 
549 //_________________________________________________________________________
550 unsigned int PedeSteerer::presigmas(const std::vector<edm::ParameterSet> &cffPresi,
551  const std::string &fileName,
552  const std::vector<Alignable*> &alis,
553  AlignableTracker *aliTracker, AlignableMuon *aliMuon, AlignableExtras *aliExtras)
554 {
555  // We loop on given PSet's, each containing a parameter selection and the presigma value
556  // The resulting presigmas are stored in a map with Alignable* as key.
557  // This map, 'fileName' and 'alis' are passed further to create the steering file.
558 
559  AlignmentParameterSelector selector(aliTracker, aliMuon, aliExtras);
560  AlignablePresigmasMap aliPresiMap; // map to store alis with presigmas of their parameters
561  for (std::vector<edm::ParameterSet>::const_iterator iSet = cffPresi.begin(), iE = cffPresi.end();
562  iSet != iE; ++iSet) { // loop on individual PSets defining ali-params with their presigma
563  selector.clear();
564  selector.addSelections((*iSet).getParameter<edm::ParameterSet>("Selector"));
565  const std::vector<Alignable*> &alis = selector.selectedAlignables();
566  const std::vector<std::vector<char> > &sels = selector.selectedParameters();
567  const float presigma = (*iSet).getParameter<double>("presigma");
568  if (presigma <= 0.) { // given presigma > 0., 0. later used if not (yet) chosen for parameter
569  throw cms::Exception("BadConfig")
570  << "[PedeSteerer::presigmas]: Pre-sigma must be > 0., but is " << presigma << ".";
571  }
572  // now loop on alis of present selection
573  for (unsigned int iAli = 0; iAli < alis.size(); ++iAli) {
574  std::vector<float> &presigmas = aliPresiMap[alis[iAli]]; // existing or empty, so ensure length:
575  if (presigmas.size() < sels[iAli].size()) presigmas.resize(sels[iAli].size(), 0.);
576  for (unsigned int iParam = 0; iParam < sels[iAli].size(); ++iParam) { // loop on parameters
577  if (sels[iAli][iParam] != '0') { // all but '0' means to apply the chosen presigma
578  if (presigmas[iParam] != 0.) { // reset forbidden (would make it order dependent!)
579  throw cms::Exception("BadConfig")
580  << "[PedeSteerer::presigmas]: Try to set pre-sigma " << presigma << ", but already "
581  << "set " << presigmas[iParam] << " (for a "
582  << alignableObjectId_.idToString(alis[iAli]->alignableObjectId()) << ").";
583  }
584  presigmas[iParam] = presigma;
585  } // end if selected for presigma
586  } // end loop on params
587  } // end loop on alignables for given selection and presigma
588  } // end loop on PSets
589 
590  if (aliPresiMap.empty()) return 0;
591  else return this->presigmasFile(fileName, alis, aliPresiMap);
592 }
593 
594 //_________________________________________________________________________
596  const std::vector<Alignable*> &alis,
597  const AlignablePresigmasMap &aliPresiMap)
598 {
599  // Check if 'alis' are in aliPresiMap,
600  // if yes apply presigma - but NOT if parameter is fixed!
601  std::ofstream *filePtr = nullptr;
602 
603  unsigned int nPresiParam = 0;
604  for (std::vector<Alignable*>::const_iterator iAli = alis.begin(), iAliE = alis.end();
605  iAli != iAliE; ++iAli) {
606  // Any presigma chosen for alignable?
607  AlignablePresigmasMap::const_iterator presigmasIt = aliPresiMap.find(*iAli);
608  if (presigmasIt == aliPresiMap.end()) continue; // no presigma chosen for alignable
609 
610  // Why does the following not work? It does with CMSSW_1_3_X on SLC3...
611  // const AlignablePresigmasMap::data_type &presigmas = presigmasIt->second;
612  const std::vector<float> &presigmas = presigmasIt->second; // I want to hide float or double...
613  for (unsigned int iParam = 0; iParam < presigmas.size(); ++iParam) {
614  // Now check whether a presigma value > 0. chosen:
615  if (presigmas[iParam] <= 0.) continue; // must be positive, '<' checked above
616  // Do not apply presigma to inactive or fixed values.
617  if (!(*iAli)->alignmentParameters()->selector()[iParam]) continue;
618  SelectionUserVariables *selVar
619  = dynamic_cast<SelectionUserVariables*>((*iAli)->alignmentParameters()->userVariables());
620  const char selChar = (selVar ? selVar->fullSelection()[iParam] : '1');
621  if (selChar == 'f' || selChar == 'F' || selChar == 'c' || selChar == 'C') continue;
622  // Finally create and write steering file:
623  if (!filePtr) {
624  filePtr = this->createSteerFile(fileName, true);
625  (*filePtr) << "* Presigma values for active parameters: \nParameter\n";
626  }
627  const unsigned int aliLabel = myLabels->alignableLabel(*iAli);
628  (*filePtr) << myLabels->parameterLabel(aliLabel, iParam) << " 0. "
629  << presigmas[iParam] * fabs(this->cmsToPedeFactor(iParam));
630  if (myIsSteerFileDebug) {
631  (*filePtr) << " ! for a " << alignableObjectId_.idToString((*iAli)->alignableObjectId());
632  }
633  (*filePtr) << '\n';
634 
635  ++nPresiParam;
636  } // end loop on parameters for alignables with chosen presigmas
637  } // end loop on alignables
638 
639  delete filePtr; // close properly file
640  return nPresiParam;
641 }
642 
643 //_________________________________________________________________________
644 std::ofstream* PedeSteerer::createSteerFile(const std::string &name, bool addToList)
645 {
646  const std::string realName(myNoSteerFiles ? "/dev/null" : name.c_str());
647 
648  std::ofstream *result = new std::ofstream(realName.c_str(), std::ios::out);
649  if (!result || !result->is_open()) {
650  delete result; // needed before exception in case just open failed
651  throw cms::Exception("FileOpenProblem") << "[PedeSteerer::createSteerFile]"
652  << "Could not open " << realName
653  << " as output file.";
654  } else if (addToList) {
655  mySteeringFiles.push_back(realName); // keep track
656  }
657 
658  return result;
659 }
660 
661 
662 //_________________________________________________________________________
664 {
665 
667  name += myConfig.getParameter<std::string>("steerFile");
668  name += addendum;
669  name += ".txt";
670 
671  return name;
672 }
673 
674 //___________________________________________________________________________
676 {
677  const std::vector<Alignable*> &alis = myParameterStore->alignables();
678 
679  if (theCoordMaster && !theCoordDefiners.empty()) {
680  const std::string nameCoordFile(this->fileName("Coord"));
681  this->defineCoordinates(theCoordDefiners, theCoordMaster, nameCoordFile);
682  edm::LogInfo("Alignment") << "@SUB=PedeSteerer::buildSubSteer"
683  << theCoordDefiners.size() << " highest level objects define the "
684  << "coordinate system, steering file " << nameCoordFile << ".";
685  }
686 
687  const std::string nameFixFile(this->fileName("FixPara"));
688  const std::pair<unsigned int, unsigned int> nFixFixCor(this->fixParameters(alis, nameFixFile));
689  if (nFixFixCor.first != 0 || nFixFixCor.second != 0) {
690  edm::LogInfo("Alignment") << "@SUB=PedeSteerer::buildSubSteer"
691  << nFixFixCor.first << " parameters fixed at 0. and "
692  << nFixFixCor.second << " at 'original' position, "
693  << "steering file " << nameFixFile << ".";
694  }
695 
696  if (this->buildNoHierarchyCollection(alis)) { // before hierarchyConstraints(..)
697  edm::LogInfo("Alignment") << "@SUB=PedeSteerer::buildSubSteer"
698  << myNoHieraCollection.size()<<" alignables taken out of hierarchy.";
699  }
700 
701  const std::string nameHierarchyFile(this->fileName("Hierarchy"));
702  unsigned int nConstraint = this->hierarchyConstraints(alis, nameHierarchyFile);
703  if (nConstraint) {
704  edm::LogInfo("Alignment") << "@SUB=PedeSteerer::buildSubSteer"
705  << "Hierarchy constraints for " << nConstraint << " alignables, "
706  << "steering file " << nameHierarchyFile << ".";
707  }
708 
709  //construct the systematic geometry deformations
710  if(!(myConfig.getParameter<std::vector<edm::ParameterSet> >("constraints")).empty()) {
711  PedeSteererWeakModeConstraints GeometryConstraints(aliTracker,
712  myLabels,
713  myConfig.getParameter<std::vector<edm::ParameterSet> >("constraints"),
714  myConfig.getParameter<std::string>("steerFile"));
715 
716  //prepare the output files
717  //Get the data structure in which the configuration data are stored.
718  //The relation between the ostream* and the corresponding file name needs to be filled
719  auto& ConstraintsConfigContainer = GeometryConstraints.getConfigData();
720 
721  //loop over all configured constraints
722  for(auto& it: ConstraintsConfigContainer) {
723  //each level has its own constraint which means the output is stored in a separate file
724  for(const auto& ilevelsFilename: it.levelsFilenames_) {
725  it.mapFileName_.insert(std::make_pair
726  (ilevelsFilename.second,this->createSteerFile(ilevelsFilename.second,true))
727  );
728  }
729  }
730 
731  unsigned int nGeometryConstraint = GeometryConstraints.constructConstraints(alis);
732  if (nGeometryConstraint) {
733  edm::LogInfo("Alignment") << "@SUB=PedeSteerer::buildSubSteer"
734  << "Geometry constraints for " << nGeometryConstraint << " alignables.";
735  }
736  }
737 
738  const std::string namePresigmaFile(this->fileName("Presigma"));
739  unsigned int nPresigma =
740  this->presigmas(myConfig.getParameter<std::vector<edm::ParameterSet> >("Presigmas"),
741  namePresigmaFile, alis, aliTracker, aliMuon, aliExtras);
742  if (nPresigma) {
743  edm::LogInfo("Alignment") << "@SUB=PedeSteerer::buildSubSteer"
744  << "Presigma values set for " << nPresigma << " parameters, "
745  << "steering file " << namePresigmaFile << ".";
746  }
747 
748  // Delete all SelectionUserVariables now? They will anyway be overwritten by MillePedeVariables...
749 }
750 
751 //_________________________________________________________________________
752 std::string PedeSteerer::buildMasterSteer(const std::vector<std::string> &binaryFiles)
753 {
754  const std::string nameMasterSteer(this->fileName("Master"));
755  std::ofstream *mainSteerPtr = this->createSteerFile(nameMasterSteer, false);
756  if (!mainSteerPtr) return "";
757 
758  // add external steering files, if any
759  std::vector<std::string> addfiles = myConfig.getParameter<std::vector<std::string> >("additionalSteerFiles");
760  mySteeringFiles.insert(mySteeringFiles.end(),
761  addfiles.begin(),
762  addfiles.end());
763 
764  // add steering files to master steering file
765  std::ofstream &mainSteerRef = *mainSteerPtr;
766  for (unsigned int iFile = 0; iFile < mySteeringFiles.size(); ++iFile) {
767  mainSteerRef << mySteeringFiles[iFile] << "\n";
768  }
769 
770  // add binary files to master steering file
771  mainSteerRef << "\nCfiles\n";
772  for (unsigned int iFile = 0; iFile < binaryFiles.size(); ++iFile) {
773  mainSteerRef << binaryFiles[iFile] << "\n";
774  }
775 
776  // add method
777  mainSteerRef << "\nmethod " << myConfig.getParameter<std::string>("method") << "\n";
778 
779  // add further options
780  const std::vector<std::string> opt(myConfig.getParameter<std::vector<std::string> >("options"));
781  mainSteerRef << "\n* Outlier treatment and other options \n";
782  for (unsigned int i = 0; i < opt.size(); ++i) {
783  mainSteerRef << opt[i] << "\n";
784  }
785 
786  delete mainSteerPtr; // close (and flush) again
787 
788  return nameMasterSteer;
789 }
790 
791 //_________________________________________________________________________
792 int PedeSteerer::runPede(const std::string &masterSteer) const
793 {
794  if (masterSteer.empty()) {
795  edm::LogError("Alignment") << "@SUB=PedeSteerer::runPede" << "Empty master steer file, stop";
796  return 0; //false;
797  }
798 
800  (command += " ") += masterSteer;
802  if (!dump.empty()) {
803  command += " > ";
804  (command += myDirectory) += dump;
805  }
806 
807  edm::LogInfo("Alignment") << "@SUB=PedeSteerer::runPede" << "Start running " << command;
808  // FIXME: Recommended interface to system commands?
809  int shellReturn = gSystem->Exec(command.c_str());
810  edm::LogInfo("Alignment") << "@SUB=PedeSteerer::runPede" << "Command returns " << shellReturn;
811 
812  return shellReturn;
813 }
void correctToReferenceSystem()
Definition: PedeSteerer.cc:396
T getParameter(std::string const &) const
align::ID id() const
Return the ID of Alignable, i.e. DetId of &#39;first&#39; component GeomDet(Unit).
Definition: Alignable.h:189
T getUntrackedParameter(std::string const &, T const &) const
const edm::ParameterSet myConfig
Definition: PedeSteerer.h:120
bool checkParameterChoices(const std::vector< Alignable * > &alis) const
Definition: PedeSteerer.cc:204
T perp() const
Definition: PV3DBase.h:72
std::vector< Alignable * > theCoordDefiners
master coordinates, must (?) be global frame
Definition: PedeSteerer.h:133
double Scalar
Definition: Definitions.h:27
static AlignableObjectId commonObjectIdProvider(const AlignableObjectId &, const AlignableObjectId &)
std::pair< Alignable *, unsigned int > ParameterId
a single alignable parameter of an Alignable
PedeSteerer(AlignableTracker *aliTracker, AlignableMuon *aliMuon, AlignableExtras *aliExtras, AlignmentParameterStore *store, const PedeLabelerBase *labels, const edm::ParameterSet &config, const std::string &defaultDir, bool noSteerFiles)
Definition: PedeSteerer.cc:54
Alignable * theCoordMaster
Alignables deselected for hierarchy constr.
Definition: PedeSteerer.h:132
std::map< const Alignable *, std::vector< float > > AlignablePresigmasMap
Definition: PedeSteerer.h:70
T y() const
Definition: PV3DBase.h:63
void move(const GlobalVector &displacement)
unsigned int presigmasFile(const std::string &fileName, const std::vector< Alignable * > &alis, const AlignablePresigmasMap &aliPresisMap)
look for active &#39;alis&#39; in map of presigma values and create steering file
Definition: PedeSteerer.cc:595
std::string myDirectory
Definition: PedeSteerer.h:121
std::list< GeometryConstraintConfigData > & getConfigData()
virtual void move(const GlobalVector &displacement)=0
Movement with respect to the global reference frame.
Definition: config.py:1
std::set< const Alignable * > myNoHieraCollection
keeps track of created &#39;secondary&#39; steering files
Definition: PedeSteerer.h:131
bool isCorrectToRefSystem(const std::vector< Alignable * > &coordDefiners) const
Definition: PedeSteerer.cc:370
unsigned int hierarchyConstraints(const std::vector< Alignable * > &alis, const std::string &file)
Definition: PedeSteerer.cc:444
unsigned int constructConstraints(const std::vector< Alignable * > &alis)
AlignmentParameters * alignmentParameters() const
Get the AlignmentParameters.
Definition: Alignable.h:61
virtual int type() const =0
tell type (AlignmentParametersFactory::ParametersType - but no circular dependency) ...
unsigned int theMinHieraParPerConstr
min absolute value of coefficients in hierarchy constraints
Definition: PedeSteerer.h:126
int fixParameter(Alignable *ali, unsigned int iRunRange, unsigned int iParam, char selector, std::ofstream *&filePtr, const std::string &fileName)
Definition: PedeSteerer.cc:266
const AlgebraicVector & parameters(void) const
Get alignment parameters.
std::ofstream * createSteerFile(const std::string &name, bool addToList)
create and open file with name, if (addToList) append to mySteeringFiles
Definition: PedeSteerer.cc:644
AlignmentUserVariables * userVariables(void) const
Get pointer to user variables.
void clear()
remove all selected Alignables and geometrical restrictions
const std::vector< char > & fullSelection() const
virtual unsigned int numberOfParameterInstances(Alignable *alignable, int param=-1) const =0
returns the number of instances for a given parameter
virtual StructureType alignableObjectId() const =0
Return the alignable type identifier.
void setAlignmentParameters(AlignmentParameters *dap)
Set the AlignmentParameters.
Definition: Alignable.cc:129
bool hierarchyConstraints(const Alignable *aliMaster, const align::Alignables &aliComps, std::vector< std::vector< ParameterId > > &paramIdsVecOut, std::vector< std::vector< double > > &factorsVecOut, bool all, double epsilon) const
const PedeLabelerBase * myLabels
not the owner!
Definition: PedeSteerer.h:117
int runPede(const std::string &masterSteer) const
run pede, masterSteer should be as returned from buildMasterSteer(...)
Definition: PedeSteerer.cc:792
T z() const
Definition: PV3DBase.h:64
unsigned int presigmas(const std::vector< edm::ParameterSet > &cffPresi, const std::string &fileName, const std::vector< Alignable * > &alis, AlignableTracker *aliTracker, AlignableMuon *aliMuon, AlignableExtras *aliExtras)
interprete content of presigma VPSet &#39;cffPresi&#39; and call presigmasFile
Definition: PedeSteerer.cc:550
const AlignableObjectId alignableObjectId_
pointer to labeler (not the owner)
Definition: PedeSteerer.h:118
virtual unsigned int parameterLabel(unsigned int aliLabel, unsigned int parNum) const =0
returns the label for a given alignable parameter number combination
virtual void addComponent(Alignable *)=0
virtual unsigned int alignableLabelFromParamAndInstance(Alignable *alignable, unsigned int param, unsigned int instance) const =0
std::string buildMasterSteer(const std::vector< std::string > &binaryFiles)
construct (and return name of) master steering file from config, binaryFiles etc. ...
Definition: PedeSteerer.cc:752
int myParameterSign
whether or not to fill pede steering files with debug info
Definition: PedeSteerer.h:124
const AlignableSurface & surface() const
Return the Surface (global position and orientation) of the object.
Definition: Alignable.h:135
const align::Alignables & selectedAlignables() const
vector of alignables selected so far
double theMinHieraConstrCoeff
old pede versions (before May &#39;07) need a sign flip...
Definition: PedeSteerer.h:125
unsigned int theConstrPrecision
hierarchy constraints with less params are ignored
Definition: PedeSteerer.h:127
const AlignmentParameterStore * myParameterStore
Definition: PedeSteerer.h:116
CLHEP::HepVector AlgebraicVector
AlgebraicVector EulerAngles
Definition: Definitions.h:36
std::pair< unsigned int, unsigned int > fixParameters(const std::vector< Alignable * > &alignables, const std::string &file)
Definition: PedeSteerer.cc:232
bool myNoSteerFiles
directory of all files
Definition: PedeSteerer.h:122
void hierarchyConstraint(const Alignable *ali, const std::vector< Alignable * > &components, std::ofstream &file) const
Definition: PedeSteerer.cc:480
int size(void) const
Get number of parameters.
const char * idToString(align::StructureType type) const
virtual void rotateInGlobalFrame(const RotationType &rotation)=0
void buildSubSteer(AlignableTracker *aliTracker, AlignableMuon *aliMuon, AlignableExtras *aliExtras)
construct steering files about hierarchy, fixing etc. an keep track of their names ...
Definition: PedeSteerer.cc:675
virtual unsigned int alignableLabel(Alignable *alignable) const =0
std::vector< std::string > mySteeringFiles
precision for writing constraints to text file
Definition: PedeSteerer.h:129
double cmsToPedeFactor(unsigned int parNum) const
Definition: PedeSteerer.cc:141
std::string fileName(const std::string &addendum) const
full name with directory and &#39;idenitfier&#39;
Definition: PedeSteerer.cc:663
bool isNoHiera(const Alignable *ali) const
True if &#39;ali&#39; was deselected from hierarchy and any ancestor (e.g. mother) has parameters.
Definition: PedeSteerer.cc:135
std::vector< Alignable * > Alignables
Definition: Utilities.h:31
unsigned int buildNoHierarchyCollection(const std::vector< Alignable * > &alis)
Definition: PedeSteerer.cc:162
list command
Definition: mps_check.py:23
bool myIsSteerFileDebug
flag to write steering files to /dev/null
Definition: PedeSteerer.h:123
static int position[264][3]
Definition: ReadPGInfo.cc:509
RotationType toMatrix(const EulerAngles &)
Convert rotation angles about x-, y-, z-axes to matrix.
Definition: Utilities.cc:42
unsigned int addSelections(const edm::ParameterSet &pSet)
std::vector< Alignable * > selectCoordinateAlis(const std::vector< Alignable * > &alignables) const
Definition: PedeSteerer.cc:305
const PositionType & globalPosition() const
Return the global position of the object.
Definition: Alignable.h:138
const std::vector< std::vector< char > > & selectedParameters() const
vector of selection &#39;strings&#39; for alignables, parallel to selectedAlignables()
Constructor of the full muon geometry.
Definition: AlignableMuon.h:37
T x() const
Definition: PV3DBase.h:62
Alignable * mother() const
Return pointer to container alignable (if any)
Definition: Alignable.h:94
const align::Alignables & alignables(void) const
get all alignables
void defineCoordinates(const std::vector< Alignable * > &alis, Alignable *aliMaster, const std::string &fileName)
Definition: PedeSteerer.cc:348
int parameterSign() const
results from pede (and start values for pede) might need a sign flip
Definition: PedeSteerer.h:65