CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_6_1_2_SLHC2_patch1/src/Alignment/CommonAlignmentProducer/plugins/AlignmentProducer.cc

Go to the documentation of this file.
00001 
00002 
00003 
00004 
00005 
00006 
00007 
00008 #include "AlignmentProducer.h"
00009 #include "FWCore/Framework/interface/LooperFactory.h" 
00010 #include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentParameterBuilder.h" 
00011 #include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentParameterStore.h" 
00012 #include "Alignment/CommonAlignment/interface/Alignable.h" 
00013 
00014 #include "TrackingTools/PatternTools/interface/TrajTrackAssociation.h"
00015 
00016 // System include files
00017 #include <memory>
00018 #include <sstream>
00019 
00020 // Framework
00021 #include "FWCore/MessageLogger/interface/MessageLogger.h"
00022 #include "FWCore/Framework/interface/Event.h"
00023 #include "FWCore/Framework/interface/EventSetup.h"
00024 #include "FWCore/Framework/interface/ESTransientHandle.h"
00025 #include "FWCore/Framework/interface/Run.h"
00026 
00027 #include "FWCore/Utilities/interface/Parse.h"
00028 
00029 // Conditions database
00030 #include "FWCore/ServiceRegistry/interface/Service.h"
00031 #include "CondCore/DBOutputService/interface/PoolDBOutputService.h"
00032 
00033 // Geometry
00034 #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h"
00035 #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeomBuilderFromGeometricDet.h"
00036 #include "Geometry/DTGeometry/interface/DTGeometry.h"
00037 #include "Geometry/CSCGeometry/interface/CSCGeometry.h"
00038 #include "Geometry/Records/interface/MuonNumberingRecord.h"
00039 #include "Geometry/DTGeometryBuilder/src/DTGeometryBuilderFromDDD.h"
00040 #include "Geometry/CSCGeometryBuilder/src/CSCGeometryBuilderFromDDD.h"
00041 #include "Geometry/TrackingGeometryAligner/interface/GeometryAligner.h"
00042 #include "CondFormats/AlignmentRecord/interface/TrackerAlignmentRcd.h"
00043 #include "CondFormats/AlignmentRecord/interface/TrackerAlignmentErrorRcd.h"
00044 #include "CondFormats/AlignmentRecord/interface/TrackerSurfaceDeformationRcd.h"
00045 #include "CondFormats/AlignmentRecord/interface/DTAlignmentRcd.h"
00046 #include "CondFormats/AlignmentRecord/interface/DTAlignmentErrorRcd.h"
00047 #include "CondFormats/AlignmentRecord/interface/CSCAlignmentRcd.h"
00048 #include "CondFormats/AlignmentRecord/interface/CSCAlignmentErrorRcd.h"
00049 #include "CondFormats/AlignmentRecord/interface/TrackerSurveyRcd.h"
00050 #include "CondFormats/AlignmentRecord/interface/TrackerSurveyErrorRcd.h"
00051 #include "CondFormats/AlignmentRecord/interface/DTSurveyRcd.h"
00052 #include "CondFormats/AlignmentRecord/interface/DTSurveyErrorRcd.h"
00053 #include "CondFormats/AlignmentRecord/interface/CSCSurveyRcd.h"
00054 #include "CondFormats/AlignmentRecord/interface/CSCSurveyErrorRcd.h"
00055 #include "CondFormats/AlignmentRecord/interface/GlobalPositionRcd.h"
00056 #include "CondFormats/Alignment/interface/DetectorGlobalPosition.h"
00057 
00058 // Tracking, LAS and cluster flag map (fwd is enough!) 
00059 #include "DataFormats/BeamSpot/interface/BeamSpot.h"
00060 #include "DataFormats/Alignment/interface/AliClusterValueMapFwd.h"
00061 #include "DataFormats/Alignment/interface/TkFittedLasBeamCollectionFwd.h"
00062 #include "Alignment/LaserAlignment/interface/TsosVectorCollection.h"
00063 
00064 // Alignment
00065 #include "CondFormats/Alignment/interface/SurveyErrors.h"
00066 #include "Alignment/TrackerAlignment/interface/TrackerScenarioBuilder.h"
00067 #include "Alignment/MuonAlignment/interface/MuonScenarioBuilder.h"
00068 #include "Alignment/CommonAlignment/interface/SurveyDet.h"
00069 #include "Alignment/CommonAlignmentParametrization/interface/RigidBodyAlignmentParameters.h"
00070 #include "Alignment/CommonAlignmentParametrization/interface/BeamSpotAlignmentParameters.h"
00071 #include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentAlgorithmPluginFactory.h"
00072 #include "Alignment/CommonAlignmentAlgorithm/interface/IntegratedCalibrationPluginFactory.h"
00073 #include "Alignment/CommonAlignmentMonitor/interface/AlignmentMonitorPluginFactory.h"
00074 #include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentParameterSelector.h"
00075 
00076 //_____________________________________________________________________________
00077 AlignmentProducer::AlignmentProducer(const edm::ParameterSet& iConfig) :
00078   theAlignmentAlgo(0), theAlignmentParameterStore(0),
00079   theAlignableExtras(0), theAlignableTracker(0), theAlignableMuon(0), 
00080   globalPositions_(0),
00081   nevent_(0), theParameterSet(iConfig),
00082   theMaxLoops( iConfig.getUntrackedParameter<unsigned int>("maxLoops") ),
00083   stNFixAlignables_(iConfig.getParameter<int>("nFixAlignables") ),
00084   stRandomShift_(iConfig.getParameter<double>("randomShift")),
00085   stRandomRotation_(iConfig.getParameter<double>("randomRotation")),
00086   applyDbAlignment_( iConfig.getUntrackedParameter<bool>("applyDbAlignment")),
00087   checkDbAlignmentValidity_( iConfig.getUntrackedParameter<bool>("checkDbAlignmentValidity")),
00088   doMisalignmentScenario_(iConfig.getParameter<bool>("doMisalignmentScenario")),
00089   saveToDB_(iConfig.getParameter<bool>("saveToDB")),
00090   saveApeToDB_(iConfig.getParameter<bool>("saveApeToDB")),
00091   saveDeformationsToDB_(iConfig.getParameter<bool>("saveDeformationsToDB")),
00092   doTracker_( iConfig.getUntrackedParameter<bool>("doTracker") ),
00093   doMuon_( iConfig.getUntrackedParameter<bool>("doMuon") ),
00094   useExtras_( iConfig.getUntrackedParameter<bool>("useExtras") ),
00095   useSurvey_( iConfig.getParameter<bool>("useSurvey") ),
00096   tjTkAssociationMapTag_(iConfig.getParameter<edm::InputTag>("tjTkAssociationMapTag")),
00097   beamSpotTag_(iConfig.getParameter<edm::InputTag>("beamSpotTag")),
00098   tkLasBeamTag_(iConfig.getParameter<edm::InputTag>("tkLasBeamTag")),
00099   clusterValueMapTag_(iConfig.getParameter<edm::InputTag>("hitPrescaleMapTag"))
00100 {
00101   edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::AlignmentProducer";
00102 
00103   // Tell the framework what data is being produced
00104   if (doTracker_) {
00105      setWhatProduced(this, &AlignmentProducer::produceTracker);
00106   }
00107   if (doMuon_) {
00108      setWhatProduced(this, &AlignmentProducer::produceDT);
00109      setWhatProduced(this, &AlignmentProducer::produceCSC);
00110   }
00111 
00112   // Create the alignment algorithm
00113   edm::ParameterSet algoConfig = iConfig.getParameter<edm::ParameterSet>( "algoConfig" );
00114   edm::VParameterSet iovSelection = iConfig.getParameter<edm::VParameterSet>( "RunRangeSelection" );
00115   algoConfig.addUntrackedParameter<edm::VParameterSet>( "RunRangeSelection", iovSelection );
00116   std::string algoName = algoConfig.getParameter<std::string>( "algoName" );
00117   theAlignmentAlgo = AlignmentAlgorithmPluginFactory::get( )->create( algoName, algoConfig  );
00118 
00119   // Check if found
00120   if ( !theAlignmentAlgo )
00121         throw cms::Exception("BadConfig") << "Couldn't find algorithm called " << algoName;
00122 
00123   // Now create monitors:
00124   edm::ParameterSet monitorConfig = iConfig.getParameter<edm::ParameterSet>( "monitorConfig" );
00125   std::vector<std::string> monitors = monitorConfig.getUntrackedParameter<std::vector<std::string> >( "monitors" );
00126   for (std::vector<std::string>::const_iterator miter = monitors.begin();  miter != monitors.end();  ++miter) {
00127     AlignmentMonitorBase* newMonitor = AlignmentMonitorPluginFactory::get()->create(*miter, monitorConfig.getUntrackedParameter<edm::ParameterSet>(*miter));
00128 
00129     if (!newMonitor) throw cms::Exception("BadConfig") << "Couldn't find monitor named " << *miter;
00130 
00131     theMonitors.push_back(newMonitor);
00132   }
00133 
00134   // Finally create integrated calibrations:
00135   edm::VParameterSet calibrations = iConfig.getParameter<edm::VParameterSet>("calibrations");
00136   for (auto iCalib = calibrations.begin(); iCalib != calibrations.end(); ++iCalib) {
00137     const std::string name(iCalib->getParameter<std::string>("calibrationName"));
00138     theCalibrations.push_back(IntegratedCalibrationPluginFactory::get()->create(name, *iCalib));
00139     // exception comes from line before: if (!theCalibrations.back()) throw cms::Exception(..) << ..;
00140   }
00141 
00142 }
00143 
00144 
00145 //_____________________________________________________________________________
00146 // Delete new objects
00147 AlignmentProducer::~AlignmentProducer()
00148 {
00149   delete theAlignmentAlgo;
00150 
00151   // Delete monitors as well??
00152 
00153   for (auto iCal = theCalibrations.begin(); iCal != theCalibrations.end(); ++iCal) {
00154     delete *iCal; // delete integrated calibration pointed to by (*iCal)
00155   }
00156 
00157   delete theAlignmentParameterStore;
00158   delete theAlignableExtras;
00159   delete theAlignableTracker;
00160   delete theAlignableMuon;
00161 
00162   delete globalPositions_;
00163 }
00164 
00165 
00166 //_____________________________________________________________________________
00167 // Produce tracker geometry
00168 boost::shared_ptr<TrackerGeometry>
00169 AlignmentProducer::produceTracker( const TrackerDigiGeometryRecord& iRecord )
00170 {
00171   edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::produceTracker";
00172   return theTracker;
00173 }
00174 
00175 //_____________________________________________________________________________
00176 // Produce muonDT geometry
00177 boost::shared_ptr<DTGeometry>
00178 AlignmentProducer::produceDT( const MuonGeometryRecord& iRecord )
00179 {
00180   edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::produceDT";
00181   return theMuonDT;
00182 }
00183 
00184 //_____________________________________________________________________________
00185 // Produce muonCSC geometry
00186 boost::shared_ptr<CSCGeometry>
00187 AlignmentProducer::produceCSC( const MuonGeometryRecord& iRecord )
00188 {
00189   edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::produceCSC";
00190   return theMuonCSC;  
00191 }
00192 
00193 
00194 //_____________________________________________________________________________
00195 // Initialize algorithm
00196 void AlignmentProducer::beginOfJob( const edm::EventSetup& iSetup )
00197 {
00198   edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::beginOfJob";
00199 
00200   // Create the geometries from the ideal geometries (first time only)
00201   this->createGeometries_( iSetup );
00202   
00203   // Retrieve and apply alignments, if requested (requires DB setup)
00204   if ( applyDbAlignment_ ) {
00205     // we need GlobalPositionRcd - and have to keep track for later removal
00206     // before writing again to DB...
00207     edm::ESHandle<Alignments> globalPositionRcd;
00208     iSetup.get<GlobalPositionRcd>().get(globalPositionRcd);
00209     globalPositions_ = new Alignments(*globalPositionRcd);
00210 
00211     if ( doTracker_ ) {     // apply to tracker
00212       this->applyDB<TrackerGeometry,TrackerAlignmentRcd,TrackerAlignmentErrorRcd>
00213         (&(*theTracker), iSetup,  
00214          align::DetectorGlobalPosition(*globalPositions_, DetId(DetId::Tracker)));
00215       this->applyDB<TrackerGeometry,TrackerSurfaceDeformationRcd>(&(*theTracker), iSetup);
00216     }
00217     
00218     if ( doMuon_ ) { // apply to tracker
00219       this->applyDB<DTGeometry,DTAlignmentRcd,DTAlignmentErrorRcd>
00220         (&(*theMuonDT), iSetup,
00221          align::DetectorGlobalPosition(*globalPositions_, DetId(DetId::Muon)));
00222       this->applyDB<CSCGeometry,CSCAlignmentRcd,CSCAlignmentErrorRcd>
00223         (&(*theMuonCSC), iSetup,
00224          align::DetectorGlobalPosition(*globalPositions_, DetId(DetId::Muon)));
00225     }
00226   }
00227 
00228   // Create alignable tracker and muon 
00229   if (doTracker_) {
00230     theAlignableTracker = new AlignableTracker( &(*theTracker) );
00231   }
00232 
00233   if (doMuon_) {
00234      theAlignableMuon = new AlignableMuon( &(*theMuonDT), &(*theMuonCSC) );
00235   }
00236 
00237   if (useExtras_) {
00238     theAlignableExtras = new AlignableExtras();
00239   }
00240 
00241   // Create alignment parameter builder
00242   edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::beginOfJob" 
00243                             << "Creating AlignmentParameterBuilder";
00244   edm::ParameterSet aliParamBuildCfg = 
00245     theParameterSet.getParameter<edm::ParameterSet>("ParameterBuilder");
00246   AlignmentParameterBuilder alignmentParameterBuilder(theAlignableTracker,
00247                                                       theAlignableMuon,
00248                                                       theAlignableExtras,
00249                                                       aliParamBuildCfg );
00250   // Fix alignables if requested
00251   if (stNFixAlignables_>0) alignmentParameterBuilder.fixAlignables(stNFixAlignables_);
00252 
00253   // Get list of alignables
00254   Alignables theAlignables = alignmentParameterBuilder.alignables();
00255   edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::beginOfJob" 
00256                             << "got " << theAlignables.size() << " alignables";
00257 
00258   // Create AlignmentParameterStore 
00259   edm::ParameterSet aliParamStoreCfg = 
00260     theParameterSet.getParameter<edm::ParameterSet>("ParameterStore");
00261   theAlignmentParameterStore = new AlignmentParameterStore(theAlignables, aliParamStoreCfg);
00262   edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::beginOfJob" 
00263                             << "AlignmentParameterStore created!";
00264 
00265   // Apply misalignment scenario to alignable tracker and muon if requested
00266   // WARNING: this assumes scenarioConfig can be passed to both muon and tracker
00267   if (doMisalignmentScenario_ && (doTracker_ || doMuon_)) {
00268     edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::beginOfJob" 
00269                               << "Applying misalignment scenario to "
00270                               << (doTracker_ ? "tracker" : "")
00271                               << (doMuon_    ? (doTracker_ ? " and muon" : "muon") : ".");
00272     edm::ParameterSet scenarioConfig 
00273       = theParameterSet.getParameter<edm::ParameterSet>( "MisalignmentScenario" );
00274     if (doTracker_) {
00275       TrackerScenarioBuilder scenarioBuilder( theAlignableTracker );
00276       scenarioBuilder.applyScenario( scenarioConfig );
00277     }
00278     if (doMuon_) {
00279       MuonScenarioBuilder muonScenarioBuilder( theAlignableMuon );
00280       muonScenarioBuilder.applyScenario( scenarioConfig );
00281     }
00282   } else {
00283     edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::beginOfJob" 
00284                               << "NOT applying misalignment scenario!";
00285   }
00286 
00287   // Apply simple misalignment
00288   const std::string sParSel(theParameterSet.getParameter<std::string>("parameterSelectorSimple"));
00289   this->simpleMisalignment_(theAlignables, sParSel, stRandomShift_, stRandomRotation_, true);
00290 
00291   // Initialize alignment algorithm and integrated calibration and pass the latter to algorithm
00292   theAlignmentAlgo->initialize( iSetup, 
00293                                 theAlignableTracker, theAlignableMuon, theAlignableExtras,
00294                                 theAlignmentParameterStore );
00295   for (auto iCal = theCalibrations.begin(); iCal != theCalibrations.end(); ++iCal) {
00296     (*iCal)->beginOfJob(theAlignableTracker, theAlignableMuon, theAlignableExtras);
00297   }
00298   // Not all algorithms support calibrations - so do not pass empty vector
00299   // and throw if non-empty and not supported:
00300   if (!theCalibrations.empty() && !theAlignmentAlgo->addCalibrations(theCalibrations)) {
00301     throw cms::Exception("BadConfig") << "[AlignmentProducer::beginOfJob]\n"
00302                                       << "Configured " << theCalibrations.size() << " calibration(s) "
00303                                       << "for algorithm not supporting it.";
00304   }
00305 
00306   for (std::vector<AlignmentMonitorBase*>::const_iterator monitor = theMonitors.begin();
00307        monitor != theMonitors.end();  ++monitor) {
00308      (*monitor)->beginOfJob(theAlignableTracker, theAlignableMuon, theAlignmentParameterStore);
00309   }
00310 }
00311 
00312 //_____________________________________________________________________________
00313 // Terminate algorithm
00314 void AlignmentProducer::endOfJob()
00315 {
00316   edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::endOfJob";
00317 
00318   for (std::vector<AlignmentMonitorBase*>::const_iterator monitor = theMonitors.begin();  monitor != theMonitors.end();  ++monitor) {
00319      (*monitor)->endOfJob();
00320   }
00321 
00322   if (0 == nevent_) {
00323     edm::LogError("Alignment") << "@SUB=AlignmentProducer::endOfJob" << "Did not process any "
00324                                << "events in last loop, do not dare to store to DB.";
00325   } else {
00326     
00327     // Expand run ranges and make them unique
00328     edm::VParameterSet runRangeSelectionVPSet(theParameterSet.getParameter<edm::VParameterSet>("RunRangeSelection"));
00329     RunRanges uniqueRunRanges(this->makeNonOverlappingRunRanges(runRangeSelectionVPSet));
00330     if (uniqueRunRanges.empty()) { // create dummy IOV
00331       const RunRange runRange(cond::timeTypeSpecs[cond::runnumber].beginValue,
00332                               cond::timeTypeSpecs[cond::runnumber].endValue);
00333       uniqueRunRanges.push_back(runRange);
00334     }
00335 
00336     std::vector<AlgebraicVector> beamSpotParameters;
00337 
00338     for (RunRanges::const_iterator iRunRange = uniqueRunRanges.begin();
00339          iRunRange != uniqueRunRanges.end();
00340          ++iRunRange) {
00341 
00342       theAlignmentAlgo->setParametersForRunRange(*iRunRange);
00343 
00344       // Save alignments to database
00345       if (saveToDB_ || saveApeToDB_ || saveDeformationsToDB_)
00346         this->writeForRunRange((*iRunRange).first);
00347       
00348       // Deal with extra alignables, e.g. beam spot
00349       if (theAlignableExtras) {
00350         Alignables &alis = theAlignableExtras->beamSpot();
00351         if (!alis.empty()) {
00352           BeamSpotAlignmentParameters *beamSpotAliPars = dynamic_cast<BeamSpotAlignmentParameters*>(alis[0]->alignmentParameters());
00353           beamSpotParameters.push_back(beamSpotAliPars->parameters());
00354         }
00355       }
00356     }
00357     
00358     if (theAlignableExtras) {
00359       std::ostringstream bsOutput;
00360       
00361       std::vector<AlgebraicVector>::const_iterator itPar = beamSpotParameters.begin();
00362       for (RunRanges::const_iterator iRunRange = uniqueRunRanges.begin();
00363            iRunRange != uniqueRunRanges.end();
00364            ++iRunRange, ++itPar) {
00365         bsOutput << "Run range: " << (*iRunRange).first << " - " << (*iRunRange).second << "\n";
00366         bsOutput << "  Displacement: x=" << (*itPar)[0] << ", y=" << (*itPar)[1] << "\n"; 
00367         bsOutput << "  Slope: dx/dz=" << (*itPar)[2] << ", dy/dz=" << (*itPar)[3] << "\n"; 
00368       }
00369       
00370       edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::endOfJob"
00371                                 << "Parameters for alignable beamspot:\n"
00372                                 << bsOutput.str();
00373     }
00374 
00375     for (auto iCal = theCalibrations.begin(); iCal != theCalibrations.end(); ++iCal) {
00376       (*iCal)->endOfJob();
00377     }
00378 
00379   }
00380 }
00381 
00382 //_____________________________________________________________________________
00383 // Called at beginning of loop
00384 void AlignmentProducer::startingNewLoop(unsigned int iLoop )
00385 {
00386   edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::startingNewLoop" 
00387                             << "Starting loop number " << iLoop;
00388 
00389   nevent_ = 0;
00390 
00391   theAlignmentAlgo->startNewLoop();
00392   // FIXME: Should this be done in algorithm::startNewLoop()??
00393   for (auto iCal = theCalibrations.begin(); iCal != theCalibrations.end(); ++iCal) {
00394     (*iCal)->startNewLoop();
00395   }
00396 
00397   for (std::vector<AlignmentMonitorBase*>::const_iterator monitor = theMonitors.begin();  monitor != theMonitors.end();  ++monitor) {
00398      (*monitor)->startingNewLoop();
00399   }
00400 
00401   edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::startingNewLoop" 
00402                             << "Now physically apply alignments to  geometry...";
00403 
00404 
00405   // Propagate changes to reconstruction geometry (from initialisation or iteration)
00406   GeometryAligner aligner;
00407   if ( doTracker_ ) {
00408     std::auto_ptr<Alignments> alignments(theAlignableTracker->alignments());
00409     std::auto_ptr<AlignmentErrors> alignmentErrors(theAlignableTracker->alignmentErrors());
00410     aligner.applyAlignments<TrackerGeometry>( &(*theTracker),&(*alignments),&(*alignmentErrors), AlignTransform() ); // don't apply global a second time!
00411     std::auto_ptr<AlignmentSurfaceDeformations> aliDeforms(theAlignableTracker->surfaceDeformations());
00412     aligner.attachSurfaceDeformations<TrackerGeometry>(&(*theTracker), &(*aliDeforms));
00413 
00414   }
00415   if ( doMuon_ ) {
00416     std::auto_ptr<Alignments>      dtAlignments(       theAlignableMuon->dtAlignments());
00417     std::auto_ptr<AlignmentErrors> dtAlignmentErrors(  theAlignableMuon->dtAlignmentErrors());
00418     std::auto_ptr<Alignments>      cscAlignments(      theAlignableMuon->cscAlignments());
00419     std::auto_ptr<AlignmentErrors> cscAlignmentErrors( theAlignableMuon->cscAlignmentErrors());
00420 
00421     aligner.applyAlignments<DTGeometry>( &(*theMuonDT), &(*dtAlignments), &(*dtAlignmentErrors), AlignTransform() ); // don't apply global a second time!
00422     aligner.applyAlignments<CSCGeometry>( &(*theMuonCSC), &(*cscAlignments), &(*cscAlignmentErrors), AlignTransform() ); // nope!
00423   }
00424 }
00425 
00426 
00427 //_____________________________________________________________________________
00428 // Called at end of loop
00429 edm::EDLooper::Status 
00430 AlignmentProducer::endOfLoop(const edm::EventSetup& iSetup, unsigned int iLoop)
00431 {
00432 
00433   if (0 == nevent_) {
00434     // beginOfJob is usually called by the framework in the first event of the first loop
00435     // (a hack: beginOfJob needs the EventSetup that is not well defined without an event)
00436     // and the algorithms rely on the initialisations done in beginOfJob. We cannot call 
00437     // this->beginOfJob(iSetup); here either since that will access the EventSetup to get
00438     // some geometry information that is not defined either without having seen an event.
00439     edm::LogError("Alignment") << "@SUB=AlignmentProducer::endOfLoop" 
00440                                << "Did not process any events in loop " << iLoop
00441                                << ", stop processing without terminating algorithm.";
00442     return kStop;
00443   }
00444 
00445   edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::endOfLoop" 
00446                             << "Ending loop " << iLoop << ", terminating algorithm.";
00447 
00448   theAlignmentAlgo->terminate();
00449   // FIXME: Should this be done in algorithm::terminate()??
00450   for (auto iCal = theCalibrations.begin(); iCal != theCalibrations.end(); ++iCal) {
00451     (*iCal)->endOfLoop();
00452   }
00453 
00454   for (std::vector<AlignmentMonitorBase*>::const_iterator monitor = theMonitors.begin();  monitor != theMonitors.end();  ++monitor) {
00455      (*monitor)->endOfLoop(iSetup);
00456   }
00457 
00458   if ( iLoop == theMaxLoops-1 || iLoop >= theMaxLoops ) return kStop;
00459   else return kContinue;
00460 }
00461 
00462 //_____________________________________________________________________________
00463 // Called at each event
00464 edm::EDLooper::Status 
00465 AlignmentProducer::duringLoop( const edm::Event& event, 
00466                                const edm::EventSetup& setup )
00467 {
00468   ++nevent_;
00469 
00470   // reading in survey records
00471   this->readInSurveyRcds(setup);
00472         
00473   // Printout event number
00474   for ( int i=10; i<10000000; i*=10 )
00475     if ( nevent_<10*i && (nevent_%i)==0 )
00476       edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::duringLoop" 
00477                                 << "Events processed: " << nevent_;
00478   
00479   // Retrieve trajectories and tracks from the event
00480   // -> merely skip if collection is empty
00481   edm::Handle<TrajTrackAssociationCollection> m_TrajTracksMap;
00482   if (event.getByLabel(tjTkAssociationMapTag_, m_TrajTracksMap)) {
00483     
00484     // Form pairs of trajectories and tracks
00485     ConstTrajTrackPairCollection trajTracks;
00486     for ( TrajTrackAssociationCollection::const_iterator iPair = m_TrajTracksMap->begin();
00487           iPair != m_TrajTracksMap->end(); ++iPair) {
00488       trajTracks.push_back( ConstTrajTrackPair( &(*(*iPair).key), &(*(*iPair).val) ) );
00489     }
00490     edm::Handle<reco::BeamSpot> beamSpot;
00491     event.getByLabel(beamSpotTag_, beamSpot);
00492 
00493     if (nevent_==1 && theAlignableExtras) {
00494       edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::duringLoop"
00495                                 << "initializing AlignableBeamSpot" << std::endl;
00496       theAlignableExtras->initializeBeamSpot(beamSpot->x0(), beamSpot->y0(), beamSpot->z0(),
00497                                              beamSpot->dxdz(), beamSpot->dydz());
00498     }
00499 
00500     // Run the alignment algorithm with its input
00501     const AliClusterValueMap *clusterValueMapPtr = 0;
00502     if(clusterValueMapTag_.encode().size()){//check that the input tag is not empty
00503       edm::Handle<AliClusterValueMap> clusterValueMap;
00504       event.getByLabel(clusterValueMapTag_, clusterValueMap);
00505       clusterValueMapPtr = &(*clusterValueMap);
00506     }
00507 
00508     const AlignmentAlgorithmBase::EventInfo eventInfo(event.id(), trajTracks, *beamSpot,
00509                                                       clusterValueMapPtr);
00510     theAlignmentAlgo->run(setup, eventInfo);
00511 
00512 
00513     for (std::vector<AlignmentMonitorBase*>::const_iterator monitor = theMonitors.begin();
00514          monitor != theMonitors.end();  ++monitor) {
00515       (*monitor)->duringLoop(event, setup, trajTracks); // forward eventInfo?
00516     }
00517   } else {
00518     edm::LogError("Alignment") << "@SUB=AlignmentProducer::duringLoop" 
00519                                << "No track collection found: skipping event";
00520   }
00521   
00522 
00523   return kContinue;
00524 }
00525 
00526 // ----------------------------------------------------------------------------
00527 void AlignmentProducer::beginRun(const edm::Run &run, const edm::EventSetup &setup)
00528 {
00529   theAlignmentAlgo->beginRun(setup); // do not forward edm::Run...
00530 }
00531 
00532 // ----------------------------------------------------------------------------
00533 void AlignmentProducer::endRun(const edm::Run &run, const edm::EventSetup &setup)
00534 {
00535   // call with or without las beam info...
00536   typedef AlignmentAlgorithmBase::EndRunInfo EndRunInfo;
00537   if (tkLasBeamTag_.encode().size()) { // non-empty InputTag
00538     edm::Handle<TkFittedLasBeamCollection> lasBeams;
00539     edm::Handle<TsosVectorCollection> tsoses;
00540     run.getByLabel(tkLasBeamTag_, lasBeams);
00541     run.getByLabel(tkLasBeamTag_, tsoses);
00542     
00543     theAlignmentAlgo->endRun(EndRunInfo(run.id(), &(*lasBeams), &(*tsoses)), setup);
00544   } else {
00545     edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::endRun"
00546                               << "No Tk LAS beams to forward to algorithm.";
00547     theAlignmentAlgo->endRun(EndRunInfo(run.id(), 0, 0), setup);
00548   }
00549 }
00550 
00551 // ----------------------------------------------------------------------------
00552 void AlignmentProducer::beginLuminosityBlock(const edm::LuminosityBlock &lumiBlock,
00553                                     const edm::EventSetup &setup)
00554 {
00555   theAlignmentAlgo->beginLuminosityBlock(setup); // do not forward edm::LuminosityBlock
00556 }
00557 
00558 // ----------------------------------------------------------------------------
00559 void AlignmentProducer::endLuminosityBlock(const edm::LuminosityBlock &lumiBlock,
00560                                   const edm::EventSetup &setup)
00561 {
00562   theAlignmentAlgo->endLuminosityBlock(setup); // do not forward edm::LuminosityBlock
00563 }
00564 
00565 // ----------------------------------------------------------------------------
00566 
00567 void AlignmentProducer::simpleMisalignment_(const Alignables &alivec, const std::string &selection, 
00568                                             float shift, float rot, bool local)
00569 {
00570 
00571   std::ostringstream output; // collecting output
00572 
00573   if (shift > 0. || rot > 0.) {
00574     output << "Adding random flat shift of max size " << shift
00575            << " and adding random flat rotation of max size " << rot <<" to ";
00576 
00577     std::vector<bool> commSel(0);
00578     if (selection != "-1") {
00579       AlignmentParameterSelector aSelector(0,0); // no alignable needed here...
00580       const std::vector<char> cSel(aSelector.convertParamSel(selection));
00581       if (cSel.size() < RigidBodyAlignmentParameters::N_PARAM) {
00582         throw cms::Exception("BadConfig") 
00583           << "[AlignmentProducer::simpleMisalignment_]\n"
00584           << "Expect selection string '" << selection << "' to be at least of length " 
00585           << RigidBodyAlignmentParameters::N_PARAM << " or to be '-1'.\n"
00586           << "(Most probably you have to adjust the parameter 'parameterSelectorSimple'.)";
00587       }
00588       for (std::vector<char>::const_iterator cIter = cSel.begin(); cIter != cSel.end(); ++cIter) {
00589         commSel.push_back(*cIter == '0' ? false : true);
00590       }
00591       output << "parameters defined by (" << selection 
00592              << "), representing (x,y,z,alpha,beta,gamma),";
00593     } else {
00594       output << "the active parameters of each alignable,";
00595     }
00596     output << " in " << (local ? "local" : "global") << " frame.";
00597 
00598     for (std::vector<Alignable*>::const_iterator it = alivec.begin(); it != alivec.end(); ++it) {
00599       Alignable* ali=(*it);
00600       std::vector<bool> mysel(commSel.empty() ? ali->alignmentParameters()->selector() : commSel);
00601       
00602       if (std::abs(shift)>0.00001) {
00603         double s0 = 0., s1 = 0., s2 = 0.;
00604         if (mysel[RigidBodyAlignmentParameters::dx]) s0 = shift * double(random()%1000-500)/500.;
00605         if (mysel[RigidBodyAlignmentParameters::dy]) s1 = shift * double(random()%1000-500)/500.;
00606         if (mysel[RigidBodyAlignmentParameters::dz]) s2 = shift * double(random()%1000-500)/500.;
00607         
00608         if (local) ali->move( ali->surface().toGlobal(align::LocalVector(s0,s1,s2)) );
00609         else       ali->move( align::GlobalVector(s0,s1,s2) );
00610 
00611       //AlignmentPositionError ape(dx,dy,dz);
00612       //ali->addAlignmentPositionError(ape);
00613       }
00614 
00615       if (std::abs(rot)>0.00001) {
00616         align::EulerAngles r(3);
00617         if (mysel[RigidBodyAlignmentParameters::dalpha]) r(1)=rot*double(random()%1000-500)/500.;
00618         if (mysel[RigidBodyAlignmentParameters::dbeta])  r(2)=rot*double(random()%1000-500)/500.;
00619         if (mysel[RigidBodyAlignmentParameters::dgamma]) r(3)=rot*double(random()%1000-500)/500.;
00620 
00621         const align::RotationType mrot = align::toMatrix(r);
00622         if (local) ali->rotateInLocalFrame(mrot);
00623         else       ali->rotateInGlobalFrame(mrot);
00624         
00625       //ali->addAlignmentPositionErrorFromRotation(mrot);
00626       }
00627     } // end loop on alignables
00628   } else {
00629     output << "No simple misalignment added!";
00630   }
00631   edm::LogInfo("Alignment")  << "@SUB=AlignmentProducer::simpleMisalignment_" << output.str();
00632 }
00633 
00634 
00635 //__________________________________________________________________________________________________
00636 void AlignmentProducer::createGeometries_( const edm::EventSetup& iSetup )
00637 {
00638    edm::ESTransientHandle<DDCompactView> cpv;
00639    iSetup.get<IdealGeometryRecord>().get( cpv );
00640 
00641    if (doTracker_) {
00642      edm::ESHandle<GeometricDet> geometricDet;
00643      iSetup.get<IdealGeometryRecord>().get( geometricDet );
00644      TrackerGeomBuilderFromGeometricDet trackerBuilder;
00645      theTracker = boost::shared_ptr<TrackerGeometry>( trackerBuilder.build(&(*geometricDet), theParameterSet ));
00646    }
00647 
00648    if (doMuon_) {
00649      edm::ESHandle<MuonDDDConstants> mdc;
00650      iSetup.get<MuonNumberingRecord>().get(mdc);
00651      DTGeometryBuilderFromDDD DTGeometryBuilder;
00652      CSCGeometryBuilderFromDDD CSCGeometryBuilder;
00653      theMuonDT = boost::shared_ptr<DTGeometry>(new DTGeometry );
00654      DTGeometryBuilder.build( theMuonDT, &(*cpv), *mdc);
00655      theMuonCSC = boost::shared_ptr<CSCGeometry>( new CSCGeometry );
00656      CSCGeometryBuilder.build( theMuonCSC, &(*cpv), *mdc );
00657    }
00658 }
00659 
00660 void AlignmentProducer::addSurveyInfo_(Alignable* ali)
00661 {
00662   const std::vector<Alignable*>& comp = ali->components();
00663 
00664   unsigned int nComp = comp.size();
00665 
00666   for (unsigned int i = 0; i < nComp; ++i) addSurveyInfo_(comp[i]);
00667 
00668   const SurveyError& error = theSurveyErrors->m_surveyErrors[theSurveyIndex];
00669 
00670   if ( ali->id() != error.rawId() ||
00671        ali->alignableObjectId() != error.structureType() )
00672   {
00673     throw cms::Exception("DatabaseError")
00674       << "Error reading survey info from DB. Mismatched id!";
00675   }
00676 
00677   const CLHEP::Hep3Vector&  pos = theSurveyValues->m_align[theSurveyIndex].translation();
00678   const CLHEP::HepRotation& rot = theSurveyValues->m_align[theSurveyIndex].rotation();
00679 
00680   AlignableSurface surf( align::PositionType( pos.x(), pos.y(), pos.z() ),
00681                          align::RotationType( rot.xx(), rot.xy(), rot.xz(),
00682                                               rot.yx(), rot.yy(), rot.yz(),
00683                                               rot.zx(), rot.zy(), rot.zz() ) );
00684 
00685   surf.setWidth( ali->surface().width() );
00686   surf.setLength( ali->surface().length() );
00687 
00688   ali->setSurvey( new SurveyDet( surf, error.matrix() ) );
00689 
00690   ++theSurveyIndex;
00691 }
00692 
00693 void AlignmentProducer::readInSurveyRcds( const edm::EventSetup& iSetup ){
00694         
00695   // Get Survey Rcds and add Survey Info
00696   if ( doTracker_ && useSurvey_ ){
00697     bool tkSurveyBool = watchTkSurveyRcd_.check(iSetup);
00698     bool tkSurveyErrBool = watchTkSurveyErrRcd_.check(iSetup);
00699     edm::LogInfo("Alignment") << "watcher tksurveyrcd: " << tkSurveyBool;
00700     edm::LogInfo("Alignment") << "watcher tksurveyerrrcd: " << tkSurveyErrBool;
00701     if ( tkSurveyBool || tkSurveyErrBool){
00702       
00703       edm::LogInfo("Alignment") << "ADDING THE SURVEY INFORMATION";
00704       edm::ESHandle<Alignments> surveys;
00705       edm::ESHandle<SurveyErrors> surveyErrors;
00706       
00707       iSetup.get<TrackerSurveyRcd>().get(surveys);
00708       iSetup.get<TrackerSurveyErrorRcd>().get(surveyErrors);
00709       
00710       theSurveyIndex  = 0;
00711       theSurveyValues = &*surveys;
00712       theSurveyErrors = &*surveyErrors;
00713       addSurveyInfo_(theAlignableTracker);
00714     }
00715   }
00716   
00717   if ( doMuon_ && useSurvey_) {
00718     bool DTSurveyBool = watchTkSurveyRcd_.check(iSetup);
00719     bool DTSurveyErrBool = watchTkSurveyErrRcd_.check(iSetup);
00720     bool CSCSurveyBool = watchTkSurveyRcd_.check(iSetup);
00721     bool CSCSurveyErrBool = watchTkSurveyErrRcd_.check(iSetup);
00722     
00723     if ( DTSurveyBool || DTSurveyErrBool || CSCSurveyBool || CSCSurveyErrBool ){
00724       edm::ESHandle<Alignments> dtSurveys;
00725       edm::ESHandle<SurveyErrors> dtSurveyErrors;
00726       edm::ESHandle<Alignments> cscSurveys;
00727       edm::ESHandle<SurveyErrors> cscSurveyErrors;
00728       
00729       iSetup.get<DTSurveyRcd>().get(dtSurveys);
00730       iSetup.get<DTSurveyErrorRcd>().get(dtSurveyErrors);
00731       iSetup.get<CSCSurveyRcd>().get(cscSurveys);
00732       iSetup.get<CSCSurveyErrorRcd>().get(cscSurveyErrors);
00733       
00734       theSurveyIndex  = 0;
00735       theSurveyValues = &*dtSurveys;
00736       theSurveyErrors = &*dtSurveyErrors;
00737       std::vector<Alignable*> barrels = theAlignableMuon->DTBarrel();
00738       for (std::vector<Alignable*>::const_iterator iter = barrels.begin();  iter != barrels.end();  ++iter) {
00739         addSurveyInfo_(*iter);
00740       }
00741       
00742       theSurveyIndex  = 0;
00743       theSurveyValues = &*cscSurveys;
00744       theSurveyErrors = &*cscSurveyErrors;
00745       std::vector<Alignable*> endcaps = theAlignableMuon->CSCEndcaps();
00746       for (std::vector<Alignable*>::const_iterator iter = endcaps.begin();  iter != endcaps.end();  ++iter) {
00747         addSurveyInfo_(*iter);
00748       }
00749     }
00750   }
00751 
00752 }
00753 
00754 
00756 // a templated method - but private, so not accessible from outside
00757 // ==> does not have to be in header file
00758 template<class G, class Rcd, class ErrRcd>
00759 void AlignmentProducer::applyDB(G* geometry, const edm::EventSetup &iSetup,
00760                                 const AlignTransform &globalCoordinates) const
00761 {
00762   // 'G' is the geometry class for that DB should be applied,
00763   // 'Rcd' is the record class for its Alignments 
00764   // 'ErrRcd' is the record class for its AlignmentErrors
00765   // 'globalCoordinates' are global transformation for this geometry
00766 
00767   const Rcd & record = iSetup.get<Rcd>();
00768   if (checkDbAlignmentValidity_) {
00769     const edm::ValidityInterval & validity = record.validityInterval();
00770     const edm::IOVSyncValue first = validity.first();
00771     const edm::IOVSyncValue last = validity.last();
00772     if (first!=edm::IOVSyncValue::beginOfTime() ||
00773         last!=edm::IOVSyncValue::endOfTime()) {
00774       throw cms::Exception("DatabaseError")
00775         << "@SUB=AlignmentProducer::applyDB"
00776         << "\nTrying to apply "
00777         << record.key().name()
00778         << " with multiple IOVs in tag.\n"
00779         << "Validity range is "
00780         << first.eventID().run() << " - " << last.eventID().run();
00781     }
00782   }
00783 
00784   edm::ESHandle<Alignments> alignments;
00785   record.get(alignments);
00786 
00787   edm::ESHandle<AlignmentErrors> alignmentErrors;
00788   iSetup.get<ErrRcd>().get(alignmentErrors);
00789 
00790   GeometryAligner aligner;
00791   aligner.applyAlignments<G>(geometry, &(*alignments), &(*alignmentErrors),
00792                              globalCoordinates);
00793 }
00794 
00795 
00797 // a templated method - but private, so not accessible from outside
00798 // ==> does not have to be in header file
00799 template<class G, class DeformationRcd>
00800 void AlignmentProducer::applyDB(G* geometry, const edm::EventSetup &iSetup) const
00801 {
00802   // 'G' is the geometry class for that DB should be applied,
00803   // 'DeformationRcd' is the record class for its surface deformations 
00804 
00805   const DeformationRcd & record = iSetup.get<DeformationRcd>();
00806   if (checkDbAlignmentValidity_) {
00807     const edm::ValidityInterval & validity = record.validityInterval();
00808     const edm::IOVSyncValue first = validity.first();
00809     const edm::IOVSyncValue last = validity.last();
00810     if (first!=edm::IOVSyncValue::beginOfTime() ||
00811         last!=edm::IOVSyncValue::endOfTime()) {
00812       throw cms::Exception("DatabaseError")
00813         << "@SUB=AlignmentProducer::applyDB"
00814         << "\nTrying to apply "
00815         << record.key().name()
00816         << " with multiple IOVs in tag.\n"
00817         << "Validity range is "
00818         << first.eventID().run() << " - " << last.eventID().run();
00819     }
00820   }
00821   edm::ESHandle<AlignmentSurfaceDeformations> surfaceDeformations;
00822   record.get(surfaceDeformations);
00823 
00824   GeometryAligner aligner;
00825   aligner.attachSurfaceDeformations<G>(geometry, &(*surfaceDeformations));
00826 }
00827 
00829 void AlignmentProducer::writeForRunRange(cond::Time_t time)
00830 {
00831   if ( doTracker_ ) { // first tracker
00832     const AlignTransform *trackerGlobal = 0; // will be 'removed' from constants 
00833     if (globalPositions_) { // i.e. applied before in applyDB
00834       trackerGlobal = &align::DetectorGlobalPosition(*globalPositions_,
00835                                                      DetId(DetId::Tracker));
00836     }
00837         
00838     Alignments *alignments = theAlignableTracker->alignments();
00839     AlignmentErrors *alignmentErrors = theAlignableTracker->alignmentErrors();
00840     this->writeDB(alignments, "TrackerAlignmentRcd",
00841                   alignmentErrors, "TrackerAlignmentErrorRcd", trackerGlobal,
00842                   time);        
00843   }
00844       
00845   if ( doMuon_ ) { // now muon
00846     const AlignTransform *muonGlobal = 0; // will be 'removed' from constants 
00847     if (globalPositions_) { // i.e. applied before in applyDB
00848       muonGlobal = &align::DetectorGlobalPosition(*globalPositions_,
00849                                                   DetId(DetId::Muon));
00850     }
00851     // Get alignments+errors, first DT - ownership taken over by writeDB(..), so no delete
00852     Alignments      *alignments       = theAlignableMuon->dtAlignments();
00853     AlignmentErrors *alignmentErrors  = theAlignableMuon->dtAlignmentErrors();
00854     this->writeDB(alignments, "DTAlignmentRcd",
00855                   alignmentErrors, "DTAlignmentErrorRcd", muonGlobal,
00856                   time);
00857     
00858     // Get alignments+errors, now CSC - ownership taken over by writeDB(..), so no delete
00859     alignments       = theAlignableMuon->cscAlignments();
00860     alignmentErrors  = theAlignableMuon->cscAlignmentErrors();
00861     this->writeDB(alignments, "CSCAlignmentRcd",
00862                   alignmentErrors, "CSCAlignmentErrorRcd", muonGlobal,
00863                   time);
00864   }
00865       
00866   // Save surface deformations to database
00867   if (saveDeformationsToDB_ && doTracker_) {
00868     AlignmentSurfaceDeformations *alignmentSurfaceDeformations = theAlignableTracker->surfaceDeformations();
00869     this->writeDB(alignmentSurfaceDeformations, "TrackerSurfaceDeformationRcd", time);
00870   }
00871 }
00872 
00874 void AlignmentProducer::writeDB(Alignments *alignments,
00875                                 const std::string &alignRcd,
00876                                 AlignmentErrors *alignmentErrors,
00877                                 const std::string &errRcd,
00878                                 const AlignTransform *globalCoordinates,
00879                                 cond::Time_t time) const
00880 {
00881   Alignments * tempAlignments = alignments;
00882   AlignmentErrors * tempAlignmentErrors = alignmentErrors;
00883 
00884   // Call service
00885   edm::Service<cond::service::PoolDBOutputService> poolDb;
00886   if (!poolDb.isAvailable()) { // Die if not available
00887     delete tempAlignments;      // promised to take over ownership...
00888     delete tempAlignmentErrors; // dito
00889     throw cms::Exception("NotAvailable") << "PoolDBOutputService not available";
00890   }
00891 
00892   if (globalCoordinates  // happens only if (applyDbAlignment_ == true)
00893       && globalCoordinates->transform() != AlignTransform::Transform::Identity) {
00894 
00895     tempAlignments = new Alignments();            // temporary storage for
00896     tempAlignmentErrors = new AlignmentErrors();  // final alignments and errors
00897 
00898     GeometryAligner aligner;
00899     aligner.removeGlobalTransform(alignments, alignmentErrors,
00900                                   *globalCoordinates,
00901                                   tempAlignments, tempAlignmentErrors);
00902     
00903     delete alignments;       // have to delete original alignments
00904     delete alignmentErrors;  // same thing for the errors
00905 
00906     edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::writeDB"
00907                               << "globalCoordinates removed from alignments (" << alignRcd
00908                               << ") and errors (" << alignRcd << ").";
00909   }
00910   
00911   if (saveToDB_) {
00912     edm::LogInfo("Alignment") << "Writing Alignments for run " << time
00913                               << " to " << alignRcd << ".";
00914     poolDb->writeOne<Alignments>(tempAlignments, time, alignRcd);
00915   } else { // poolDb->writeOne(..) takes over 'alignments' ownership,...
00916     delete tempAlignments; // ...otherwise we have to delete, as promised!
00917   }
00918 
00919   if (saveApeToDB_) {
00920     edm::LogInfo("Alignment") << "Writing AlignmentErrors for run " << time
00921                               << " to " << errRcd << ".";
00922     poolDb->writeOne<AlignmentErrors>(tempAlignmentErrors, time, errRcd);
00923   } else { // poolDb->writeOne(..) takes over 'alignmentErrors' ownership,...
00924     delete tempAlignmentErrors; // ...otherwise we have to delete, as promised!
00925   }
00926 }
00927 
00928 
00930 void AlignmentProducer::writeDB(AlignmentSurfaceDeformations *alignmentSurfaceDeformations,
00931                                 const std::string &surfaceDeformationRcd,
00932                                 cond::Time_t time) const
00933 {
00934   // Call service
00935   edm::Service<cond::service::PoolDBOutputService> poolDb;
00936   if (!poolDb.isAvailable()) { // Die if not available
00937     delete alignmentSurfaceDeformations; // promised to take over ownership...
00938     throw cms::Exception("NotAvailable") << "PoolDBOutputService not available";
00939   }
00940   
00941   if (saveDeformationsToDB_) {
00942     edm::LogInfo("Alignment") << "Writing AlignmentSurfaceDeformations for run " << time
00943                               << " to " << surfaceDeformationRcd  << ".";
00944     poolDb->writeOne<AlignmentSurfaceDeformations>(alignmentSurfaceDeformations, time,
00945                                                    surfaceDeformationRcd);
00946   } else { // poolDb->writeOne(..) takes over 'surfaceDeformation' ownership,...
00947     delete alignmentSurfaceDeformations; // ...otherwise we have to delete, as promised!
00948   }
00949 }
00950 
00951 AlignmentProducer::RunRanges
00952 AlignmentProducer::makeNonOverlappingRunRanges(const edm::VParameterSet& RunRangeSelectionVPSet)
00953 {
00954   static bool oldRunRangeSelectionWarning = false;
00955 
00956   const RunNumber beginValue = cond::timeTypeSpecs[cond::runnumber].beginValue;
00957   const RunNumber endValue = cond::timeTypeSpecs[cond::runnumber].endValue;
00958   
00959   RunRanges uniqueRunRanges;
00960   if (!RunRangeSelectionVPSet.empty()) {
00961 
00962     std::map<RunNumber,RunNumber> uniqueFirstRunNumbers;
00963     
00964     for (std::vector<edm::ParameterSet>::const_iterator ipset = RunRangeSelectionVPSet.begin();
00965          ipset != RunRangeSelectionVPSet.end();
00966          ++ipset) {
00967       const std::vector<std::string> RunRangeStrings = (*ipset).getParameter<std::vector<std::string> >("RunRanges");
00968       for (std::vector<std::string>::const_iterator irange = RunRangeStrings.begin();
00969            irange != RunRangeStrings.end();
00970            ++irange) {
00971         
00972         if ((*irange).find(':')==std::string::npos) {
00973           
00974           RunNumber first = beginValue;
00975           long int temp = strtol((*irange).c_str(), 0, 0);
00976           if (temp!=-1) first = temp;
00977           uniqueFirstRunNumbers[first] = first;
00978           
00979         } else {
00980           
00981           if (!oldRunRangeSelectionWarning) {
00982             edm::LogWarning("BadConfig") << "@SUB=AlignmentProducer::makeNonOverlappingRunRanges"
00983                                          << "Config file contains old format for 'RunRangeSelection'. Only the start run\n"
00984                                          << "number is used internally. The number of the last run is ignored and can be\n"
00985                                          << "safely removed from the config file.\n";
00986             oldRunRangeSelectionWarning = true;
00987           }
00988           
00989           std::vector<std::string> tokens = edm::tokenize(*irange, ":");
00990           long int temp;
00991           RunNumber first = beginValue;
00992           temp = strtol(tokens[0].c_str(), 0, 0);
00993           if (temp!=-1) first = temp;
00994           uniqueFirstRunNumbers[first] = first;
00995         }
00996       }
00997     }
00998 
00999     for (std::map<RunNumber,RunNumber>::iterator iFirst = uniqueFirstRunNumbers.begin();
01000          iFirst!=uniqueFirstRunNumbers.end();
01001          ++iFirst) {
01002       uniqueRunRanges.push_back(std::pair<RunNumber,RunNumber>((*iFirst).first, endValue));
01003     }
01004     for (unsigned int i = 0;i<uniqueRunRanges.size()-1;++i) {
01005       uniqueRunRanges[i].second = uniqueRunRanges[i+1].first - 1;
01006     }
01007     
01008   } else {
01009         
01010     uniqueRunRanges.push_back(std::pair<RunNumber,RunNumber>(beginValue, endValue));
01011     
01012   }
01013   
01014   return uniqueRunRanges;
01015 }
01016 
01017 DEFINE_FWK_LOOPER( AlignmentProducer );