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