CMS 3D CMS Logo

PedeSteerer.cc

Go to the documentation of this file.
00001 
00011 #include "PedeSteerer.h"
00012 #include "PedeLabeler.h"
00013 
00014 #include "FWCore/MessageLogger/interface/MessageLogger.h"
00015 
00016 #include "Alignment/CommonAlignment/interface/Alignable.h"
00017 #include <boost/cstdint.hpp> 
00018 #include "Alignment/CommonAlignment/interface/AlignableObjectId.h"
00019 #include "Alignment/CommonAlignment/interface/Utilities.h"
00020 #include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentParameterStore.h"
00021 #include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentParameterSelector.h"
00022 #include "Alignment/CommonAlignmentAlgorithm/interface/SelectionUserVariables.h"
00023 #include "Alignment/CommonAlignmentParametrization/interface/RigidBodyAlignmentParameters.h"
00024 
00025 #include "Alignment/TrackerAlignment/interface/TrackerAlignableId.h"
00026 // for 'type identification' as Alignable
00027 #include "Alignment/TrackerAlignment/interface/AlignableTracker.h"
00028 #include "Alignment/MuonAlignment/interface/AlignableMuon.h"
00029 // GF doubts the need of these includes from include checker campaign:
00030 #include <FWCore/Framework/interface/EventSetup.h> 
00031 #include <Geometry/CommonDetUnit/interface/GeomDetUnit.h> 
00032 #include <Geometry/CommonDetUnit/interface/GeomDetType.h> 
00033 #include <DataFormats/GeometrySurface/interface/LocalError.h> 
00034 #include <Geometry/DTGeometry/interface/DTLayer.h> 
00035 // end of doubt
00036 
00037 #include "DataFormats/GeometryVector/interface/GlobalPoint.h"
00038 
00039 #include <fstream>
00040 #include <sstream>
00041 #include <algorithm>
00042 
00043 // from ROOT
00044 #include <TSystem.h>
00045 #include <TMath.h>
00046 
00047 PedeSteerer::PedeSteerer(AlignableTracker *aliTracker, AlignableMuon *aliMuon,
00048                          AlignmentParameterStore *store, const PedeLabeler *labels,
00049                          const edm::ParameterSet &config, const std::string &defaultDir,
00050                          bool noSteerFiles) :
00051   myParameterStore(store), myLabels(labels), myConfig(config),
00052   myDirectory(myConfig.getUntrackedParameter<std::string>("fileDir")),
00053   myNoSteerFiles(noSteerFiles),
00054   myParameterSign(myConfig.getUntrackedParameter<int>("parameterSign")),
00055   theCoordMaster(0)
00056 {
00057   if (myParameterSign != 1 && myParameterSign != -1) {
00058     cms::Exception("BadConfig") << "Expect PedeSteerer.parameterSign = +/-1, "
00059                                 << "found " << myParameterSign << ".";
00060   }
00061 
00062   // Correct directory, needed before asking for fileName(..):
00063   if (myDirectory.empty()) myDirectory = defaultDir;
00064   if (!myDirectory.empty() && myDirectory.find_last_of('/') != myDirectory.size() - 1) {
00065     myDirectory += '/'; // directory may need '/'
00066   }
00067 
00068   const std::vector<Alignable*> &alis = myParameterStore->alignables();
00069   if (!this->checkParameterChoices(alis)) {} // anyway thrown exception
00070 
00071   // Coordinate system selection and correction before everything
00072   theCoordDefiners = this->selectCoordinateAlis(alis);
00073   if (!theCoordDefiners.empty()) { // Create steering with constraints to define coordinate system:
00074     theCoordMaster = aliTracker; // Both tracker and muon have global coordinates, though...
00075     if (!theCoordMaster) theCoordMaster = aliMuon; // ...which coordinates should not really matter anyway.
00076     // FIXME: With both tracker and muon, only tracker will be shifted in correctToReferenceSystem!
00077     // Could be fixed by introducing AlignableComposite with both, but must prevent double deletion.
00078     // If this has 'global frame', correctToReferenceSystem can use globalParameters (as it does)
00079     this->correctToReferenceSystem(); // really before 'defineCoordinates'?
00080   } 
00081 
00082 }
00083 
00084 //___________________________________________________________________________
00085 PedeSteerer::~PedeSteerer()
00086 {
00087 }
00088 
00089 //_________________________________________________________________________
00090 bool PedeSteerer::isNoHiera(const Alignable* ali) const
00091 {
00092   return (myNoHieraCollection.find(ali) != myNoHieraCollection.end());
00093 }
00094 
00095 //_________________________________________________________________________
00096 double PedeSteerer::cmsToPedeFactor(unsigned int parNum) const
00097 {
00098   return 1.; // mmh, otherwise would need to FIXME hierarchyConstraint...
00099 
00100   switch (parNum) {
00101   case RigidBodyAlignmentParameters::dx:
00102   case RigidBodyAlignmentParameters::dy:
00103     return 1000.; // cm to mum *1/10 to get smaller values
00104   case RigidBodyAlignmentParameters::dz:
00105     return 2500.;   // cm to mum *1/4 
00106   case RigidBodyAlignmentParameters::dalpha:
00107   case RigidBodyAlignmentParameters::dbeta:
00108     return 1000.; // rad to mrad (no first guess for sensitivity yet)
00109   case RigidBodyAlignmentParameters::dgamma:
00110     return 10000.; // rad to mrad *10 to get larger values
00111   default:
00112     return 1.;
00113   }
00114 }
00115 
00116 //_________________________________________________________________________
00117 unsigned int PedeSteerer::buildNoHierarchyCollection(const std::vector<Alignable*> &alis)
00118 {
00119   myNoHieraCollection.clear();  // just in case of re-use...
00120 
00121   for (std::vector<Alignable*>::const_iterator iAli = alis.begin() ; iAli != alis.end(); ++iAli) {
00122     AlignmentParameters *params = (*iAli)->alignmentParameters();
00123     SelectionUserVariables *selVar = dynamic_cast<SelectionUserVariables*>(params->userVariables());
00124     if (!selVar) continue;
00125     // Now check whether taking out of hierarchy is selected - must be consistent!
00126     unsigned int numNoHieraPar = 0;
00127     unsigned int numHieraPar = 0;
00128     for (unsigned int iParam = 0; static_cast<int>(iParam) < params->size(); ++iParam) {
00129       const char selector = selVar->fullSelection()[iParam];
00130       if (selector == 'C' || selector == 'F' || selector == 'H') {
00131         ++numNoHieraPar;
00132       } else if (selector == 'c' || selector == 'f' || selector == '1' || selector == 'r') {
00133         ++numHieraPar;
00134       } // else ... accept '0' as undetermined
00135     }
00136     if (numNoHieraPar) { // Selected to be taken out.
00137       if (numHieraPar) { // Inconsistent: Some parameters still in hierarchy ==> exception!
00138         throw cms::Exception("BadConfig") 
00139           << "[PedeSteerer::buildNoHierarchyCollection] All active parameters of alignables to be "
00140           << " taken out of the hierarchy must be marked with capital letters 'C', 'F' or 'H'!";
00141       }
00142       bool isInHiera = false; // Check whether Alignable is really part of hierarchy:
00143       Alignable *mother = *iAli;
00144       while ((mother = mother->mother())) {
00145         if (mother->alignmentParameters()) isInHiera = true; // could 'break;', but loop is short
00146       }
00147       // Complain, but keep collection short if not in hierarchy:
00148       if (isInHiera) myNoHieraCollection.insert(*iAli);
00149       else edm::LogWarning("Alignment") << "@SUB=PedeSteerer::buildNoHierarchyCollection"
00150                                         << "Alignable not in hierarchy, no need to remove it!";
00151     }
00152   } // end loop on alignables
00153 
00154   return myNoHieraCollection.size();
00155 }
00156 
00157 //_________________________________________________________________________
00158 bool PedeSteerer::checkParameterChoices(const std::vector<Alignable*> &alis) const
00159 {
00160   for (std::vector<Alignable*>::const_iterator iAli = alis.begin() ; iAli != alis.end(); ++iAli) {
00161     AlignmentParameters *paras = (*iAli)->alignmentParameters();
00162     SelectionUserVariables *selVar = dynamic_cast<SelectionUserVariables*>(paras->userVariables());
00163     if (!selVar) continue;
00164     for (unsigned int iParam = 0; static_cast<int>(iParam) < paras->size(); ++iParam) {
00165       const char sel = selVar->fullSelection()[iParam];
00166       if (sel != 'f' && sel != 'F' && sel != 'c' && sel != 'C' &&
00167           sel != '0' && sel != '1' && sel != 'H' && sel != 'r') {
00168         throw cms::Exception("BadConfig")
00169           << "[PedeSteerer::unknownParameterChoices] " 
00170           << "Unexpected parameter selector '" << sel
00171           << "', use \n'f/F' (fix),\n'c/C' (fix at correct pos.),\n'1/H' (free),\n"
00172           << "'r' (free, but defining reference system) or \n'0' (ignore).\n"
00173           << "Capital letters mean that the Alignable is taken out of a possible hierarchy,\n"
00174           << "but must be used consistently for all its parameters.";
00175         return false; // unreached
00176       }
00177     }
00178   }
00179 
00180   return true;
00181 }
00182 
00183 //_________________________________________________________________________
00184 std::pair<unsigned int, unsigned int>
00185 PedeSteerer::fixParameters(const std::vector<Alignable*> &alis, const std::string &fileName)
00186 {
00187   // return number of parameters fixed at 0. and fixed at original position 
00188   std::pair<unsigned int, unsigned int> numFixNumFixCor(0, 0);
00189 
00190   std::ofstream *filePtr = 0;
00191 
00192   for (std::vector<Alignable*>::const_iterator iAli = alis.begin() ; iAli != alis.end(); ++iAli) {
00193     AlignmentParameters *params = (*iAli)->alignmentParameters();
00194     SelectionUserVariables *selVar = dynamic_cast<SelectionUserVariables*>(params->userVariables());
00195     if (!selVar) continue;
00196 
00197     for (unsigned int iParam = 0; static_cast<int>(iParam) < params->size(); ++iParam) {
00198       int whichFix = this->fixParameter(*iAli, iParam, selVar->fullSelection()[iParam], filePtr,
00199                                         fileName);
00200       if (whichFix == 1) {
00201         ++(numFixNumFixCor.first);
00202       } else if (whichFix == -1) {
00203         ++(numFixNumFixCor.second);
00204       }
00205     }
00206   }
00207 
00208   delete filePtr; // automatically flushes, no problem if NULL ptr.   
00209 
00210   return numFixNumFixCor;
00211 }
00212 
00213 //_________________________________________________________________________
00214 int PedeSteerer::fixParameter(Alignable *ali, unsigned int iParam, char selector,
00215                               std::ofstream* &filePtr, const std::string &fileName)
00216 {
00217   int result = 0;
00218   float fixAt = 0.;
00219   if (selector == 'c' || selector == 'C') {
00220     fixAt = -this->parameterSign() * RigidBodyAlignmentParameters(ali, true).parameters()[iParam];
00221     result = -1;
00222   } else if (selector == 'f' || selector == 'F') {
00223     result = 1;
00224   }
00225 
00226   if (result) {
00227     if (!filePtr) {
00228       filePtr = this->createSteerFile(fileName, true);
00229       (*filePtr) << "Parameter\n";
00230     }
00231     std::ofstream &file = *filePtr;
00232 
00233     const unsigned int aliLabel = myLabels->alignableLabel(ali);
00234     file << myLabels->parameterLabel(aliLabel, iParam) << "  " 
00235          << fixAt * this->cmsToPedeFactor(iParam) << " -1.0";
00236     if (0) { // debug
00237       const GlobalPoint position(ali->globalPosition());
00238       file << "* eta " << position.eta() << ", z " << position.z()
00239            << ", r " << position.perp() << ", phi " << position.phi();
00240     }
00241     file << "\n";
00242   }
00243 
00244   return result;
00245 }
00246 
00247 //_________________________________________________________________________
00248 std::vector<Alignable*> PedeSteerer::selectCoordinateAlis(const std::vector<Alignable*> &alis) const
00249 {
00250   std::vector<Alignable*> coordAlis;
00251 
00252   for (std::vector<Alignable*>::const_iterator iAli = alis.begin() ; iAli != alis.end(); ++iAli) {
00253     AlignmentParameters *params = (*iAli)->alignmentParameters();
00254     SelectionUserVariables *selVar = dynamic_cast<SelectionUserVariables*>(params->userVariables());
00255     if (!selVar) continue;
00256     unsigned int refParam = 0;
00257     unsigned int nonRefParam = 0;
00258     for (unsigned int iParam = 0; static_cast<int>(iParam) < params->size(); ++iParam) {
00259       const char selector = selVar->fullSelection()[iParam];
00260       if (selector == 'r') {
00261         ++refParam;
00262       } else if (selector != '0' && selector != 'f') { // allow also 'c'?
00263         ++nonRefParam;
00264       }
00265     }
00266     // Check whether some 'r' selection string. If yes and selection makes sense, add to result:
00267     if (refParam) {
00268       if (nonRefParam) {
00269         throw cms::Exception("BadConfig") 
00270           << "[PedeSteerer::selectCoordinateAlis] All active parameters of alignables defining "
00271           << "the coordinate system must be marked with 'r' (or fixed, 'f')!";
00272       } else {
00273         Alignable *mother = *iAli;
00274         while ((mother = mother->mother())) {
00275           if (mother->alignmentParameters()) {
00276             throw cms::Exception("BadConfig") << "[PedeSteerer::selectCoordinateAlis] "
00277                                               << "Alignables defining the coordinate system must "
00278                                               << "be highest level!";
00279           }
00280         }
00281         coordAlis.push_back(*iAli);
00282       }
00283     }
00284   } // end loop on alignables
00285 
00286   return coordAlis;
00287 }
00288 
00289 
00290 //_________________________________________________________________________
00291 void PedeSteerer::defineCoordinates(const std::vector<Alignable*> &alis, Alignable *aliMaster,
00292                                     const std::string &fileName)
00293 {
00294   std::ofstream *filePtr = this->createSteerFile(fileName, true);
00295   (*filePtr) << "* Constraints to define coordinate system:\n";
00296   if (!aliMaster || aliMaster->alignmentParameters()) {
00297     throw cms::Exception("BadConfig")
00298       << "[PedeSteerer::defineCoordinates] " << "No master alignable or it has parameters!";
00299   }
00300   AlignmentParameters *par = new RigidBodyAlignmentParameters(aliMaster, false);
00301   aliMaster->setAlignmentParameters(par); // hierarchyConstraint needs parameters
00302   this->hierarchyConstraint(aliMaster, alis, *filePtr);
00303   aliMaster->setAlignmentParameters(0); // erase dummy parameters
00304 
00305   delete filePtr; // automatically flushes, no problem if NULL ptr.   
00306 }
00307 
00308 //_________________________________________________________________________
00309 void PedeSteerer::correctToReferenceSystem()
00310 {
00311   typedef RigidBodyAlignmentParameters RbPars;
00312   if (!theCoordMaster || theCoordDefiners.empty()) return; // nothing was defined
00313 
00314   std::vector<Alignable*> definerDets; // or ...DetUnits
00315   for (std::vector<Alignable*>::iterator it = theCoordDefiners.begin(), iE = theCoordDefiners.end();
00316        it != iE; ++it) {// find lowest level objects of alignables that define the coordinate system
00317     const std::vector<Alignable*> &comp = (*it)->deepComponents();
00318     definerDets.insert(definerDets.end(), comp.begin(), comp.end());
00319   }
00320 
00321   for (unsigned int iLoop = 0; ; ++iLoop) { // iterate: shifts and rotations are not independent
00322     AlgebraicVector meanPars(RbPars::N_PARAM);
00323     for (std::vector<Alignable*>::iterator it = definerDets.begin(), iE = definerDets.end();
00324          it != iE; ++it) { // sum up mean displacements/misrotations:
00325       meanPars += RbPars(*it, true).globalParameters();// requires theCoordMaster has global frame
00326     }
00327     meanPars /= definerDets.size();
00328     const align::Scalar squareSum = meanPars.normsq();
00329 
00330     if (squareSum < 1.e-20) break; // sqrt(1.e-20)=1.e-10: close enough to stop iterating
00331     if (iLoop == 0) {
00332       edm::LogInfo("Alignment") << "@SUB=PedeSteerer::correctToReferenceSystem"
00333                                 << "Loop " << iLoop << " "
00334                                 << "Mean misalignment of dets of defined coordinate system"
00335                                 << (squareSum < 1.e-20 ? ":" :
00336                                     " (will be iteratively corrected to < 1.e-10):") << meanPars;
00337     }
00338     if (iLoop >=5) { // 3 iterations should be safe, use 5 for 'more' safety...
00339         edm::LogError("Alignment") << "@SUB=PedeSteerer::correctToReferenceSystem"
00340                                    << "No convergence in " << iLoop << " iterations, " 
00341                                    << "remaining misalignment: " << meanPars;
00342       break;
00343     }
00344 
00345     const GlobalVector globalShift(meanPars[RbPars::dx],meanPars[RbPars::dy],meanPars[RbPars::dz]);
00346     align::EulerAngles globalAngles(3);
00347     globalAngles[0] = meanPars[RbPars::dalpha];
00348     globalAngles[1] = meanPars[RbPars::dbeta];
00349     globalAngles[2] = meanPars[RbPars::dgamma];
00350     theCoordMaster->move(-globalShift); // sign to revert
00351     theCoordMaster->rotateInGlobalFrame(align::toMatrix(-globalAngles)); // sign to revert
00352   }
00353   
00354 }
00355 
00356 //_________________________________________________________________________
00357 unsigned int PedeSteerer::hierarchyConstraints(const std::vector<Alignable*> &alis,
00358                                                const std::string &fileName)
00359 {
00360   std::ofstream *filePtr = 0;
00361 
00362   unsigned int nConstraints = 0;
00363   std::vector<Alignable*> aliDaughts;
00364   for (std::vector<Alignable*>::const_iterator iA = alis.begin(), iEnd = alis.end();
00365        iA != iEnd; ++iA) {
00366     aliDaughts.clear();
00367     if (!(*iA)->firstCompsWithParams(aliDaughts)) {
00368       static AlignableObjectId objId; // static since costly constructor FIXME?
00369       edm::LogWarning("Alignment") << "@SUB=PedeSteerer::hierarchyConstraints"
00370                                    << "Some but not all daughters of "
00371                                    << objId. typeToName((*iA)->alignableObjectId())
00372                                    << " with params!";
00373     }
00374 //     edm::LogInfo("Alignment") << "@SUB=PedeSteerer::hierarchyConstraints"
00375 //                            << aliDaughts.size() << " ali param components";
00376     if (aliDaughts.empty()) continue;
00377 //     edm::LogInfo("Alignment") << "@SUB=PedeSteerer::hierarchyConstraints"
00378 //                            << aliDaughts.size() << " alignable components ("
00379 //                            << (*iA)->size() << " in total) for " 
00380 //                            << aliId.alignableTypeName(*iA) 
00381 //                            << ", layer " << aliId.typeAndLayerFromAlignable(*iA).second
00382 //                            << ", position " << (*iA)->globalPosition()
00383 //                            << ", r = " << (*iA)->globalPosition().perp();
00384     if (!filePtr) filePtr = this->createSteerFile(fileName, true);
00385     ++nConstraints;
00386     this->hierarchyConstraint(*iA, aliDaughts, *filePtr);
00387   }
00388 
00389   delete filePtr; // automatically flushes, no problem if NULL ptr.   
00390 
00391   return nConstraints;
00392 }
00393 
00394 //_________________________________________________________________________
00395 void PedeSteerer::hierarchyConstraint(const Alignable *ali,
00396                                       const std::vector<Alignable*> &components,
00397                                       std::ofstream &file) const
00398 {
00399   static AlignableObjectId objId; // static since costly constructor FIXME?
00400 
00401   typedef AlignmentParameterStore::ParameterId ParameterId;
00402   typedef std::vector<Alignable*>::size_type IndexType;
00403 
00404   std::vector<std::vector<ParameterId> > paramIdsVec;
00405   std::vector<std::vector<float> > factorsVec;
00406   const bool allConstr = false; // true; // make configurable?
00407   static bool first = true;
00408   if (allConstr && first) {
00409     edm::LogWarning("Alignment") << "@SUB=PedeSteerer::hierarchyConstraint"
00410                                  << "changed to use all 6 constraints";
00411     first = false;
00412   }
00413   if (!myParameterStore->hierarchyConstraints(ali, components, paramIdsVec, factorsVec, allConstr)){
00414     edm::LogWarning("Alignment") << "@SUB=PedeSteerer::hierarchyConstraint"
00415                                  << "Problems from store.";
00416   }
00417 
00418   for (unsigned int iConstr = 0; iConstr < paramIdsVec.size(); ++iConstr) {
00419     std::ostringstream aConstr;
00420 
00421     const std::vector<ParameterId> &parIds = paramIdsVec[iConstr];
00422     const std::vector<float> &factors = factorsVec[iConstr];
00423     // parIds.size() == factors.size() granted by myParameterStore->hierarchyConstraints
00424     for (unsigned int iParam = 0; iParam < parIds.size(); ++iParam) {
00425       Alignable *aliSubComp = parIds[iParam].first;
00426       const unsigned int compParNum = parIds[iParam].second;
00427       if (this->isNoHiera(aliSubComp)) {
00428         if (0) aConstr << "* Taken out of hierarchy: "; // conflict with !aConstr.str().empty()
00429         else continue;
00430       }
00431       const unsigned int aliLabel = myLabels->alignableLabel(aliSubComp);
00432       const unsigned int paramLabel = myLabels->parameterLabel(aliLabel, compParNum);
00433       // FIXME: multiply by cmsToPedeFactor(subcomponent)/cmsToPedeFactor(mother) (or vice a versa?)
00434       aConstr << paramLabel << "    " << factors[iParam];
00435       if (true) { // debug
00436         const TrackerAlignableId aliId;
00437 
00438         aConstr << "   ! for param " << compParNum << " of a " 
00439 //              << aliId.alignableTypeName(aliSubComp) 
00440                 << objId.typeToName(aliSubComp->alignableObjectId())
00441                 << " (label " << aliLabel << ")";
00442       }
00443       aConstr << "\n";
00444     } // end loop on params
00445 
00446     if (!aConstr.str().empty()) {
00447       if (true) { //debug
00448         const TrackerAlignableId aliId;
00449         file << "\n* Nr. " << iConstr << " of a '"
00450              << objId.typeToName(ali->alignableObjectId()) << "' (label "
00451              << myLabels->alignableLabel(const_cast<Alignable*>(ali)) // ugly cast: FIXME!
00452              << "), layer " << aliId.typeAndLayerFromDetId(ali->id()).second
00453              << ", position " << ali->globalPosition()
00454              << ", r = " << ali->globalPosition().perp();
00455       }
00456       file << "\nConstraint   0.\n" << aConstr.str(); // in future 'Wconstraint'?
00457     }
00458   } // end loop on constraints
00459 }
00460 
00461 //_________________________________________________________________________
00462 unsigned int PedeSteerer::presigmas(const std::vector<edm::ParameterSet> &cffPresi,
00463                                     const std::string &fileName,
00464                                     const std::vector<Alignable*> &alis,
00465                                     AlignableTracker *aliTracker, AlignableMuon *aliMuon)
00466 {
00467   // We loop on given PSet's, each containing a parameter selection and the presigma value
00468   // The resulting presigmas are stored in a map with Alignable* as key.
00469   // This map, 'fileName' and 'alis' are passed further to create the steering file.
00470 
00471   AlignmentParameterSelector selector(aliTracker, aliMuon);  
00472   AlignablePresigmasMap aliPresiMap; // map to store alis with presigmas of their parameters 
00473   for (std::vector<edm::ParameterSet>::const_iterator iSet = cffPresi.begin(), iE = cffPresi.end();
00474        iSet != iE; ++iSet) { // loop on individual PSets defining ali-params with their presigma
00475     selector.clear();
00476     selector.addSelections((*iSet).getParameter<edm::ParameterSet>("Selector"));
00477     const std::vector<Alignable*> &alis = selector.selectedAlignables();
00478     const std::vector<std::vector<char> > &sels =  selector.selectedParameters();
00479     const float presigma = (*iSet).getParameter<double>("presigma");
00480     if (presigma <= 0.) { // given presigma > 0., 0. later used if not (yet) chosen for parameter
00481       throw cms::Exception("BadConfig")
00482         << "[PedeSteerer::presigmas]: Pre-sigma must be > 0., but is " << presigma << ".";
00483     }
00484     // now loop on alis of present selection
00485     for (unsigned int iAli = 0; iAli < alis.size(); ++iAli) {
00486       std::vector<float> &presigmas = aliPresiMap[alis[iAli]]; // existing or empty, so ensure length:
00487       if (presigmas.size() < sels[iAli].size()) presigmas.resize(sels[iAli].size(), 0.);
00488       for (unsigned int iParam = 0; iParam < sels[iAli].size(); ++iParam) { // loop on parameters
00489         if (sels[iAli][iParam] != '0') { // all but '0' means to apply the chosen presigma
00490           if (presigmas[iParam] != 0.) { // reset forbidden (would make it order dependent!)
00491             throw cms::Exception("BadConfig")
00492               << "[PedeSteerer::presigmas]: Try to set pre-sigma " << presigma << ", but already "
00493               << "set " << presigmas[iParam] << " (for a " 
00494               << AlignableObjectId().typeToName(alis[iAli]->alignableObjectId()) << ").";
00495           }
00496           presigmas[iParam] = presigma;
00497         } // end if selected for presigma
00498       } // end loop on params
00499     } // end loop on alignables for given selection and presigma
00500   } // end loop on PSets 
00501 
00502   if (aliPresiMap.empty()) return 0;
00503   else return this->presigmasFile(fileName, alis, aliPresiMap);
00504 }
00505 
00506 //_________________________________________________________________________
00507 unsigned int PedeSteerer::presigmasFile(const std::string &fileName,
00508                                         const std::vector<Alignable*> &alis,
00509                                         const AlignablePresigmasMap &aliPresiMap)
00510 {
00511   // Check if 'alis' are in aliPresiMap, 
00512   // if yes apply presigma - but NOT if parameter is fixed!
00513   std::ofstream *filePtr = 0;
00514   const AlignableObjectId aliObjId;
00515 
00516   unsigned int nPresiParam = 0;
00517   for (std::vector<Alignable*>::const_iterator iAli = alis.begin(), iAliE = alis.end();
00518        iAli != iAliE; ++iAli) {
00519     // Any presigma chosen for alignable?
00520     AlignablePresigmasMap::const_iterator presigmasIt = aliPresiMap.find(*iAli);
00521     if (presigmasIt == aliPresiMap.end()) continue; // no presigma chosen for alignable
00522 
00523     // Why does the following not work? It does with CMSSW_1_3_X on SLC3...
00524     // const AlignablePresigmasMap::data_type &presigmas = presigmasIt->second;
00525     const std::vector<float> &presigmas = presigmasIt->second; // I want to hide float or double...
00526     for (unsigned int iParam = 0; iParam < presigmas.size(); ++iParam) {
00527       // Now check whether a presigma value > 0. chosen: 
00528       if (presigmas[iParam] <= 0.) continue; // must be positive, '<' checked above
00529       // Do not apply presigma to inactive or fixed values.
00530       if (!(*iAli)->alignmentParameters()->selector()[iParam]) continue;
00531       SelectionUserVariables *selVar 
00532         = dynamic_cast<SelectionUserVariables*>((*iAli)->alignmentParameters()->userVariables());
00533       const char selChar = (selVar ? selVar->fullSelection()[iParam] : '1');
00534       if (selChar == 'f' || selChar == 'F' || selChar == 'c' || selChar == 'C') continue;
00535       // Finally create and write steering file:
00536       if (!filePtr) {
00537         filePtr = this->createSteerFile(fileName, true);
00538         (*filePtr) << "* Presigma values for active parameters: \nParameter\n";
00539       }
00540       const unsigned int aliLabel = myLabels->alignableLabel(*iAli);
00541       (*filePtr) << myLabels->parameterLabel(aliLabel, iParam) << "   0.   " 
00542                  << presigmas[iParam] * fabs(this->cmsToPedeFactor(iParam)) 
00543                  << "  ! for a " << aliObjId.typeToName((*iAli)->alignableObjectId()) << '\n';
00544       ++nPresiParam;
00545     } // end loop on parameters for alignables with chosen presigmas
00546   } // end loop on alignables
00547 
00548   delete filePtr; // close properly file
00549   return nPresiParam;
00550 }
00551 
00552 //_________________________________________________________________________
00553 std::ofstream* PedeSteerer::createSteerFile(const std::string &name, bool addToList)
00554 {
00555   const std::string realName(myNoSteerFiles ? "/dev/null" : name.c_str());
00556 
00557   std::ofstream *result = new std::ofstream(realName.c_str(), std::ios::out);
00558   if (!result || !result->is_open()) {
00559     delete result; // needed before exception in case just open failed
00560     throw cms::Exception("FileOpenProblem") << "[PedeSteerer::createSteerFile]" 
00561                                             << "Could not open " << realName 
00562                                             << " as output file.";
00563   } else if (addToList) {
00564     mySteeringFiles.push_back(realName); // keep track
00565   }
00566 
00567   return result;
00568 }
00569 
00570 
00571 //_________________________________________________________________________
00572 std::string PedeSteerer::fileName(const std::string &addendum) const
00573 {
00574 
00575   std::string name(myDirectory);
00576   name += myConfig.getParameter<std::string>("steerFile");
00577   name += addendum;
00578   name += ".txt";
00579 
00580   return name;
00581 }
00582 
00583 //___________________________________________________________________________
00584 void PedeSteerer::buildSubSteer(AlignableTracker *aliTracker, AlignableMuon *aliMuon)
00585 {
00586   const std::vector<Alignable*> &alis = myParameterStore->alignables();
00587 
00588   if (theCoordMaster && !theCoordDefiners.empty()) {
00589     const std::string nameCoordFile(this->fileName("Coord"));
00590     this->defineCoordinates(theCoordDefiners, theCoordMaster, nameCoordFile);
00591     edm::LogInfo("Alignment") << "@SUB=PedeSteerer::buildSubSteer" 
00592                               << theCoordDefiners.size() << " highest level objects define the "
00593                               << "coordinate system, steering file " << nameCoordFile << ".";
00594   }
00595 
00596   const std::string nameFixFile(this->fileName("FixPara"));
00597   const std::pair<unsigned int, unsigned int> nFixFixCor(this->fixParameters(alis, nameFixFile));
00598   if (nFixFixCor.first != 0 || nFixFixCor.second != 0) {
00599     edm::LogInfo("Alignment") << "@SUB=PedeSteerer::buildSubSteer" 
00600                               << nFixFixCor.first << " parameters fixed at 0. and "
00601                               << nFixFixCor.second << " at 'original' position, "
00602                               << "steering file " << nameFixFile << ".";
00603   } 
00604 
00605   if (this->buildNoHierarchyCollection(alis)) { // before hierarchyConstraints(..)
00606     edm::LogInfo("Alignment") << "@SUB=PedeSteerer::buildSubSteer"
00607                               << myNoHieraCollection.size()<<" alignables taken out of hierarchy.";
00608   }
00609 
00610   const std::string nameHierarchyFile(this->fileName("Hierarchy"));
00611   unsigned int nConstraint = this->hierarchyConstraints(alis, nameHierarchyFile);
00612   if (nConstraint) {
00613     edm::LogInfo("Alignment") << "@SUB=PedeSteerer::buildSubSteer" 
00614                               << "Hierarchy constraints for " << nConstraint << " alignables, "
00615                               << "steering file " << nameHierarchyFile << ".";
00616   }
00617 
00618   const std::string namePresigmaFile(this->fileName("Presigma"));
00619   unsigned int nPresigma = 
00620     this->presigmas(myConfig.getParameter<std::vector<edm::ParameterSet> >("Presigmas"),
00621                     namePresigmaFile, alis, aliTracker, aliMuon);
00622   if (nPresigma) {
00623     edm::LogInfo("Alignment") << "@SUB=PedeSteerer::buildSubSteer" 
00624                               << "Presigma values set for " << nPresigma << " parameters, "
00625                               << "steering file " << namePresigmaFile << ".";
00626   }
00627 
00628   // Delete all SelectionUserVariables now? They will anyway be overwritten by MillePedeVariables...
00629 }
00630 
00631 //_________________________________________________________________________
00632 std::string PedeSteerer::buildMasterSteer(const std::vector<std::string> &binaryFiles)
00633 {
00634   const std::string nameMasterSteer(this->fileName("Master"));
00635   std::ofstream *mainSteerPtr = this->createSteerFile(nameMasterSteer, false);
00636   if (!mainSteerPtr) return "";
00637 
00638   // add steering files to master steering file
00639   std::ofstream &mainSteerRef = *mainSteerPtr;
00640   for (unsigned int iFile = 0; iFile < mySteeringFiles.size(); ++iFile) {
00641     mainSteerRef << mySteeringFiles[iFile] << "\n";
00642   }
00643 
00644   // add binary files to master steering file
00645   mainSteerRef << "\nCfiles\n";
00646   for (unsigned int iFile = 0; iFile < binaryFiles.size(); ++iFile) {
00647     mainSteerRef << binaryFiles[iFile] << "\n";
00648   }
00649 
00650   // add method
00651   mainSteerRef << "\nmethod  " << myConfig.getParameter<std::string>("method") << "\n";
00652 
00653   // add further options
00654   const std::vector<std::string> opt(myConfig.getParameter<std::vector<std::string> >("options"));
00655   mainSteerRef << "\n* Outlier treatment and other options \n";
00656   for (unsigned int i = 0; i < opt.size(); ++i) {
00657     mainSteerRef << opt[i] << "\n";
00658   }
00659 
00660   delete mainSteerPtr;  // close (and flush) again
00661 
00662   return nameMasterSteer;
00663 }
00664 
00665 //_________________________________________________________________________
00666 bool PedeSteerer::runPede(const std::string &masterSteer) const
00667 {
00668   if (masterSteer.empty()) {
00669     edm::LogError("Alignment") << "@SUB=PedeSteerer::runPede" << "Empty master steer file, stop";
00670     return false;
00671   }
00672 
00673   std::string command(myConfig.getUntrackedParameter<std::string>("pedeCommand"));
00674   (command += " ") += masterSteer;
00675   const std::string dump(myConfig.getUntrackedParameter<std::string>("pedeDump"));
00676   if (!dump.empty()) {
00677     command += " > ";
00678     (command += myDirectory) += dump;
00679   }
00680 
00681   edm::LogInfo("Alignment") << "@SUB=PedeSteerer::runPede" << "Start running " << command;
00682   // FIXME: Recommended interface to system commands?
00683   int shellReturn = gSystem->Exec(command.c_str());
00684   if (shellReturn) {
00685     edm::LogError("Alignment") << "@SUB=PedeSteerer::runPede" << "Command returns " << shellReturn;
00686   } else {
00687     edm::LogInfo("Alignment") << "@SUB=PedeSteerer::runPede" << "Command returns " << shellReturn;
00688   }
00689 
00690   return !shellReturn;
00691 }

Generated on Tue Jun 9 17:24:11 2009 for CMSSW by  doxygen 1.5.4