CMS 3D CMS Logo

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