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  edm::LogWarning("Alignment") << "@SUB=PedeSteerer::hierarchyConstraints"
450  << "Some but not all daughters of "
451  << AlignableObjectId::idToString((*iA)->alignableObjectId())
452  << " with params!";
453  }
454 // edm::LogInfo("Alignment") << "@SUB=PedeSteerer::hierarchyConstraints"
455 // << aliDaughts.size() << " ali param components";
456  if (aliDaughts.empty()) continue;
457 // edm::LogInfo("Alignment") << "@SUB=PedeSteerer::hierarchyConstraints"
458 // << aliDaughts.size() << " alignable components ("
459 // << (*iA)->size() << " in total) for "
460 // << aliId.alignableTypeName(*iA)
461 // << ", layer " << aliId.typeAndLayerFromAlignable(*iA).second
462 // << ", position " << (*iA)->globalPosition()
463 // << ", r = " << (*iA)->globalPosition().perp();
464  if (!filePtr) filePtr = this->createSteerFile(fileName, true);
465  ++nConstraints;
466  this->hierarchyConstraint(*iA, aliDaughts, *filePtr);
467  }
468 
469  delete filePtr; // automatically flushes, no problem if NULL ptr.
470 
471  return nConstraints;
472 }
473 
474 //_________________________________________________________________________
476  const std::vector<Alignable*> &components,
477  std::ofstream &file) const
478 {
479  typedef AlignmentParameterStore::ParameterId ParameterId;
480 
481  std::vector<std::vector<ParameterId> > paramIdsVec;
482  std::vector<std::vector<double> > factorsVec;
483  const bool allConstr = false; // true; // make configurable?
484  static bool first = true;
485  if (allConstr && first) {
486  edm::LogWarning("Alignment") << "@SUB=PedeSteerer::hierarchyConstraint"
487  << "changed to use all 6 constraints";
488  first = false;
489  }
490  if (!myParameterStore->hierarchyConstraints(ali, components, paramIdsVec, factorsVec, allConstr,
492  edm::LogWarning("Alignment") << "@SUB=PedeSteerer::hierarchyConstraint"
493  << "Problems from store.";
494  }
495 
496  for (unsigned int iConstr = 0; iConstr < paramIdsVec.size(); ++iConstr) {
497  std::ostringstream aConstr;
498 
499  const std::vector<ParameterId> &parIds = paramIdsVec[iConstr];
500  const std::vector<double> &factors = factorsVec[iConstr];
501  unsigned int nParPerConstr = 0; // keep track of used factor/parId pair
502  // parIds.size() == factors.size() granted by myParameterStore->hierarchyConstraints
503  for (unsigned int iParam = 0; iParam < parIds.size(); ++iParam) {
504  Alignable *aliSubComp = parIds[iParam].first;
505  const unsigned int compParNum = parIds[iParam].second;
506  if (this->isNoHiera(aliSubComp)) {
507  if (myIsSteerFileDebug) aConstr << "* Taken out of hierarchy: ";
508  continue;
509  }
510  const unsigned int aliLabel = myLabels->alignableLabel(aliSubComp);
511  const unsigned int paramLabel = myLabels->parameterLabel(aliLabel, compParNum);
512  // FIXME: multiply by cmsToPedeFactor(subcomponent)/cmsToPedeFactor(mother) (or vice a versa?)
513  aConstr << paramLabel << " " << factors[iParam];
514  if (myIsSteerFileDebug) { // debug
515  aConstr << " ! for param " << compParNum << " of a "
516  << AlignableObjectId::idToString(aliSubComp->alignableObjectId()) << " at "
517  << aliSubComp->globalPosition() << ", r=" << aliSubComp->globalPosition().perp();
518  }
519  aConstr << "\n";
520  ++nParPerConstr; // OK, we used one.
521  } // end loop on params
522 
523  //
524  if (nParPerConstr && nParPerConstr >= theMinHieraParPerConstr) { // Enough to make sense?
525  if (myIsSteerFileDebug) { //debug
526  file << "\n* Nr. " << iConstr << " of a '"
527  << AlignableObjectId::idToString(ali->alignableObjectId()) << "' (label "
528  << myLabels->alignableLabel(const_cast<Alignable*>(ali)) // ugly cast: FIXME!
529  << "), position " << ali->globalPosition()
530  << ", r = " << ali->globalPosition().perp();
531  }
532  file << "\nConstraint 0.\n" << aConstr.str(); // in future 'Wconstraint'?
533  } else if (nParPerConstr > 0) { // no warning for trivial case...
534  edm::LogWarning("Alignment") << "@SUB=PedeSteerer::hierarchyConstraint"
535  << "Skip constraint on " << nParPerConstr
536  << " parameter(s):\n" << aConstr.str();
537  }
538  } // end loop on constraints
539 }
540 
541 //_________________________________________________________________________
542 unsigned int PedeSteerer::presigmas(const std::vector<edm::ParameterSet> &cffPresi,
543  const std::string &fileName,
544  const std::vector<Alignable*> &alis,
545  AlignableTracker *aliTracker, AlignableMuon *aliMuon, AlignableExtras *aliExtras)
546 {
547  // We loop on given PSet's, each containing a parameter selection and the presigma value
548  // The resulting presigmas are stored in a map with Alignable* as key.
549  // This map, 'fileName' and 'alis' are passed further to create the steering file.
550 
551  AlignmentParameterSelector selector(aliTracker, aliMuon, aliExtras);
552  AlignablePresigmasMap aliPresiMap; // map to store alis with presigmas of their parameters
553  for (std::vector<edm::ParameterSet>::const_iterator iSet = cffPresi.begin(), iE = cffPresi.end();
554  iSet != iE; ++iSet) { // loop on individual PSets defining ali-params with their presigma
555  selector.clear();
556  selector.addSelections((*iSet).getParameter<edm::ParameterSet>("Selector"));
557  const std::vector<Alignable*> &alis = selector.selectedAlignables();
558  const std::vector<std::vector<char> > &sels = selector.selectedParameters();
559  const float presigma = (*iSet).getParameter<double>("presigma");
560  if (presigma <= 0.) { // given presigma > 0., 0. later used if not (yet) chosen for parameter
561  throw cms::Exception("BadConfig")
562  << "[PedeSteerer::presigmas]: Pre-sigma must be > 0., but is " << presigma << ".";
563  }
564  // now loop on alis of present selection
565  for (unsigned int iAli = 0; iAli < alis.size(); ++iAli) {
566  std::vector<float> &presigmas = aliPresiMap[alis[iAli]]; // existing or empty, so ensure length:
567  if (presigmas.size() < sels[iAli].size()) presigmas.resize(sels[iAli].size(), 0.);
568  for (unsigned int iParam = 0; iParam < sels[iAli].size(); ++iParam) { // loop on parameters
569  if (sels[iAli][iParam] != '0') { // all but '0' means to apply the chosen presigma
570  if (presigmas[iParam] != 0.) { // reset forbidden (would make it order dependent!)
571  throw cms::Exception("BadConfig")
572  << "[PedeSteerer::presigmas]: Try to set pre-sigma " << presigma << ", but already "
573  << "set " << presigmas[iParam] << " (for a "
574  << AlignableObjectId::idToString(alis[iAli]->alignableObjectId()) << ").";
575  }
576  presigmas[iParam] = presigma;
577  } // end if selected for presigma
578  } // end loop on params
579  } // end loop on alignables for given selection and presigma
580  } // end loop on PSets
581 
582  if (aliPresiMap.empty()) return 0;
583  else return this->presigmasFile(fileName, alis, aliPresiMap);
584 }
585 
586 //_________________________________________________________________________
588  const std::vector<Alignable*> &alis,
589  const AlignablePresigmasMap &aliPresiMap)
590 {
591  // Check if 'alis' are in aliPresiMap,
592  // if yes apply presigma - but NOT if parameter is fixed!
593  std::ofstream *filePtr = 0;
594 
595  unsigned int nPresiParam = 0;
596  for (std::vector<Alignable*>::const_iterator iAli = alis.begin(), iAliE = alis.end();
597  iAli != iAliE; ++iAli) {
598  // Any presigma chosen for alignable?
599  AlignablePresigmasMap::const_iterator presigmasIt = aliPresiMap.find(*iAli);
600  if (presigmasIt == aliPresiMap.end()) continue; // no presigma chosen for alignable
601 
602  // Why does the following not work? It does with CMSSW_1_3_X on SLC3...
603  // const AlignablePresigmasMap::data_type &presigmas = presigmasIt->second;
604  const std::vector<float> &presigmas = presigmasIt->second; // I want to hide float or double...
605  for (unsigned int iParam = 0; iParam < presigmas.size(); ++iParam) {
606  // Now check whether a presigma value > 0. chosen:
607  if (presigmas[iParam] <= 0.) continue; // must be positive, '<' checked above
608  // Do not apply presigma to inactive or fixed values.
609  if (!(*iAli)->alignmentParameters()->selector()[iParam]) continue;
610  SelectionUserVariables *selVar
611  = dynamic_cast<SelectionUserVariables*>((*iAli)->alignmentParameters()->userVariables());
612  const char selChar = (selVar ? selVar->fullSelection()[iParam] : '1');
613  if (selChar == 'f' || selChar == 'F' || selChar == 'c' || selChar == 'C') continue;
614  // Finally create and write steering file:
615  if (!filePtr) {
616  filePtr = this->createSteerFile(fileName, true);
617  (*filePtr) << "* Presigma values for active parameters: \nParameter\n";
618  }
619  const unsigned int aliLabel = myLabels->alignableLabel(*iAli);
620  (*filePtr) << myLabels->parameterLabel(aliLabel, iParam) << " 0. "
621  << presigmas[iParam] * fabs(this->cmsToPedeFactor(iParam));
622  if (myIsSteerFileDebug) {
623  (*filePtr) << " ! for a " << AlignableObjectId::idToString((*iAli)->alignableObjectId());
624  }
625  (*filePtr) << '\n';
626 
627  ++nPresiParam;
628  } // end loop on parameters for alignables with chosen presigmas
629  } // end loop on alignables
630 
631  delete filePtr; // close properly file
632  return nPresiParam;
633 }
634 
635 //_________________________________________________________________________
636 std::ofstream* PedeSteerer::createSteerFile(const std::string &name, bool addToList)
637 {
638  const std::string realName(myNoSteerFiles ? "/dev/null" : name.c_str());
639 
640  std::ofstream *result = new std::ofstream(realName.c_str(), std::ios::out);
641  if (!result || !result->is_open()) {
642  delete result; // needed before exception in case just open failed
643  throw cms::Exception("FileOpenProblem") << "[PedeSteerer::createSteerFile]"
644  << "Could not open " << realName
645  << " as output file.";
646  } else if (addToList) {
647  mySteeringFiles.push_back(realName); // keep track
648  }
649 
650  return result;
651 }
652 
653 
654 //_________________________________________________________________________
656 {
657 
659  name += myConfig.getParameter<std::string>("steerFile");
660  name += addendum;
661  name += ".txt";
662 
663  return name;
664 }
665 
666 //___________________________________________________________________________
668 {
669  const std::vector<Alignable*> &alis = myParameterStore->alignables();
670 
671  if (theCoordMaster && !theCoordDefiners.empty()) {
672  const std::string nameCoordFile(this->fileName("Coord"));
673  this->defineCoordinates(theCoordDefiners, theCoordMaster, nameCoordFile);
674  edm::LogInfo("Alignment") << "@SUB=PedeSteerer::buildSubSteer"
675  << theCoordDefiners.size() << " highest level objects define the "
676  << "coordinate system, steering file " << nameCoordFile << ".";
677  }
678 
679  const std::string nameFixFile(this->fileName("FixPara"));
680  const std::pair<unsigned int, unsigned int> nFixFixCor(this->fixParameters(alis, nameFixFile));
681  if (nFixFixCor.first != 0 || nFixFixCor.second != 0) {
682  edm::LogInfo("Alignment") << "@SUB=PedeSteerer::buildSubSteer"
683  << nFixFixCor.first << " parameters fixed at 0. and "
684  << nFixFixCor.second << " at 'original' position, "
685  << "steering file " << nameFixFile << ".";
686  }
687 
688  if (this->buildNoHierarchyCollection(alis)) { // before hierarchyConstraints(..)
689  edm::LogInfo("Alignment") << "@SUB=PedeSteerer::buildSubSteer"
690  << myNoHieraCollection.size()<<" alignables taken out of hierarchy.";
691  }
692 
693  const std::string nameHierarchyFile(this->fileName("Hierarchy"));
694  unsigned int nConstraint = this->hierarchyConstraints(alis, nameHierarchyFile);
695  if (nConstraint) {
696  edm::LogInfo("Alignment") << "@SUB=PedeSteerer::buildSubSteer"
697  << "Hierarchy constraints for " << nConstraint << " alignables, "
698  << "steering file " << nameHierarchyFile << ".";
699  }
700 
701  const std::string namePresigmaFile(this->fileName("Presigma"));
702  unsigned int nPresigma =
703  this->presigmas(myConfig.getParameter<std::vector<edm::ParameterSet> >("Presigmas"),
704  namePresigmaFile, alis, aliTracker, aliMuon, aliExtras);
705  if (nPresigma) {
706  edm::LogInfo("Alignment") << "@SUB=PedeSteerer::buildSubSteer"
707  << "Presigma values set for " << nPresigma << " parameters, "
708  << "steering file " << namePresigmaFile << ".";
709  }
710 
711  // Delete all SelectionUserVariables now? They will anyway be overwritten by MillePedeVariables...
712 }
713 
714 //_________________________________________________________________________
715 std::string PedeSteerer::buildMasterSteer(const std::vector<std::string> &binaryFiles)
716 {
717  const std::string nameMasterSteer(this->fileName("Master"));
718  std::ofstream *mainSteerPtr = this->createSteerFile(nameMasterSteer, false);
719  if (!mainSteerPtr) return "";
720 
721  // add external steering files, if any
722  std::vector<std::string> addfiles = myConfig.getParameter<std::vector<std::string> >("additionalSteerFiles");
723  mySteeringFiles.insert(mySteeringFiles.end(),
724  addfiles.begin(),
725  addfiles.end());
726 
727  // add steering files to master steering file
728  std::ofstream &mainSteerRef = *mainSteerPtr;
729  for (unsigned int iFile = 0; iFile < mySteeringFiles.size(); ++iFile) {
730  mainSteerRef << mySteeringFiles[iFile] << "\n";
731  }
732 
733  // add binary files to master steering file
734  mainSteerRef << "\nCfiles\n";
735  for (unsigned int iFile = 0; iFile < binaryFiles.size(); ++iFile) {
736  mainSteerRef << binaryFiles[iFile] << "\n";
737  }
738 
739  // add method
740  mainSteerRef << "\nmethod " << myConfig.getParameter<std::string>("method") << "\n";
741 
742  // add further options
743  const std::vector<std::string> opt(myConfig.getParameter<std::vector<std::string> >("options"));
744  mainSteerRef << "\n* Outlier treatment and other options \n";
745  for (unsigned int i = 0; i < opt.size(); ++i) {
746  mainSteerRef << opt[i] << "\n";
747  }
748 
749  delete mainSteerPtr; // close (and flush) again
750 
751  return nameMasterSteer;
752 }
753 
754 //_________________________________________________________________________
755 int PedeSteerer::runPede(const std::string &masterSteer) const
756 {
757  if (masterSteer.empty()) {
758  edm::LogError("Alignment") << "@SUB=PedeSteerer::runPede" << "Empty master steer file, stop";
759  return 0; //false;
760  }
761 
763  (command += " ") += masterSteer;
765  if (!dump.empty()) {
766  command += " > ";
767  (command += myDirectory) += dump;
768  }
769 
770  edm::LogInfo("Alignment") << "@SUB=PedeSteerer::runPede" << "Start running " << command;
771  // FIXME: Recommended interface to system commands?
772  int shellReturn = gSystem->Exec(command.c_str());
773  edm::LogInfo("Alignment") << "@SUB=PedeSteerer::runPede" << "Command returns " << shellReturn;
774 
775  return shellReturn;
776 }
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:72
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: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:587
std::string myDirectory
Definition: PedeSteerer.h:118
virtual void move(const GlobalVector &displacement)=0
Movement with respect to the global reference frame.
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:636
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:755
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:542
tuple result
Definition: query.py:137
virtual StructureType alignableObjectId() const =0
Return the alignable type identifier.
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:715
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:475
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:667
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:655
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()
static const char * idToString(align::StructureType type)
Constructor of the full muon geometry.
Definition: AlignableMuon.h:36
T x() const
Definition: PV3DBase.h:62
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