CMS 3D CMS Logo

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