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