CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
KalmanAlignmentAlgorithm.cc
Go to the documentation of this file.
1 
4 
5 // includes for alignment
10 
13 
19 
21 
24 
32 
34 
37 
38 // miscellaneous includes
40 #include "CLHEP/Random/RandGauss.h"
41 #include <fstream>
42 
43 using namespace std;
44 
45 
47  AlignmentAlgorithmBase( config ),
48  theConfiguration( config )
49 {}
50 
51 
53 
54 
58  AlignableExtras* extras,
60 {
62 
63  theMergerFlag = theConfiguration.getParameter<bool>( "MergeResults" );
64 
65  if ( theMergerFlag )
66  {
67  mergeResults();
68  } else {
69  theParameterStore = store;
70  theNavigator = new AlignableNavigator( tracker->components() );
71  theSelector = new AlignmentParameterSelector( tracker );
72 
74 
77 
79  }
80 }
81 
82 
84 {
85  if ( theMergerFlag )
86  {
87  return; // only merging mode. nothing to do here.
88  }
89 
90  cout << "[KalmanAlignmentAlgorithm::terminate] start ..." << endl;
91 
92  set< Alignable* > allAlignables;
93  vector< Alignable* > alignablesToWrite;
94 
95  AlignmentSetupCollection::const_iterator itSetup;
96  for ( itSetup = theAlignmentSetups.begin(); itSetup != theAlignmentSetups.end(); ++itSetup )
97  {
98  delete (*itSetup)->alignmentUpdator();
99 
100  const vector< Alignable* >& alignablesFromMetrics = (*itSetup)->metricsUpdator()->alignables();
101  cout << "[KalmanAlignmentAlgorithm::terminate] The metrics updator for setup \'" << (*itSetup)->id()
102  << "\' holds " << alignablesFromMetrics.size() << " alignables" << endl;
103  allAlignables.insert( alignablesFromMetrics.begin(), alignablesFromMetrics.end() );
104  }
105 
106  for ( set< Alignable* >::iterator it = allAlignables.begin(); it != allAlignables.end(); ++it )
107  {
108  AlignmentParameters* alignmentParameters = ( *it )->alignmentParameters();
109 
110  if ( alignmentParameters != 0 )
111  {
112  KalmanAlignmentUserVariables* userVariables =
113  dynamic_cast< KalmanAlignmentUserVariables* >( alignmentParameters->userVariables() );
114 
115  if ( userVariables != 0 && userVariables->numberOfUpdates() > 0 )
116  {
117  userVariables->update( true );
118  userVariables->histogramParameters( "KalmanAlignmentAlgorithm" );
119  alignablesToWrite.push_back( *it );
120  }
121  }
122  }
123 
124  if ( theConfiguration.getUntrackedParameter< bool >( "WriteAlignmentParameters", false ) )
125  {
126  AlignmentIORoot alignmentIO;
127  int ierr = 0;
128  string output = theConfiguration.getParameter< string >( "OutputFile" );
129 
130  cout << "Write data for " << alignablesToWrite.size() << " alignables ..." << endl;
131 
132  // Write output to "iteration 1", ...
133  alignmentIO.writeAlignmentParameters( alignablesToWrite, output.c_str(), 1, false, ierr );
134  // ... or, if "iteration 1" already exists, write it to "highest iteration + 1"
135  if ( ierr == -1 ) alignmentIO.writeAlignmentParameters( alignablesToWrite, output.c_str(), -1, false, ierr );
136  }
137 
139 
140  string timingLogFile = theConfiguration.getUntrackedParameter< string >( "TimingLogFile", "timing.log" );
141  cout << "The usage of TimingReport from Utilities/Timing! Timing not written to log file" << endl;
142 
143  delete theNavigator;
144 
145  cout << "[KalmanAlignmentAlgorithm::terminate] ... done." << endl;
146 }
147 
148 
150 {
151  if ( theMergerFlag ) return; // only merging mode. nothing to do here.
152 
153  static int iEvent = 1;
154  if ( iEvent % 100 == 0 ) cout << "[KalmanAlignmentAlgorithm::run] Event Nr. " << iEvent << endl;
155  iEvent++;
156 
157  edm::ESHandle< MagneticField > aMagneticField;
158  setup.get< IdealMagneticFieldRecord >().get( aMagneticField );
159 
160  try
161  {
162  // Run the refitter algorithm
164  const reco::BeamSpot &beamSpot = eventInfo.beamSpot_;
165  TrackletCollection refittedTracklets = theRefitter->refitTracks( setup, theAlignmentSetups, tracks, &beamSpot );
166 
167  // Associate tracklets to alignment setups
168  map< AlignmentSetup*, TrackletCollection > setupToTrackletMap;
169  TrackletCollection::iterator itTracklet;
170  for ( itTracklet = refittedTracklets.begin(); itTracklet != refittedTracklets.end(); ++itTracklet )
171  setupToTrackletMap[(*itTracklet)->alignmentSetup()].push_back( *itTracklet );
172 
173  // Iterate on alignment setups
174  map< AlignmentSetup*, TrackletCollection >::iterator itMap;
175  for ( itMap = setupToTrackletMap.begin(); itMap != setupToTrackletMap.end(); ++itMap )
176  {
179 
180  TrackletCollection::iterator itTracklet;
181  for ( itTracklet = itMap->second.begin(); itTracklet != itMap->second.end(); ++itTracklet )
182  {
183  tracklets.push_back( (*itTracklet)->trajTrackPair() );
184  external.push_back( (*itTracklet)->externalPrediction() );
185  }
186 
187  // Construct reference trajectories
188  ReferenceTrajectoryCollection trajectories =
189  itMap->first->trajectoryFactory()->trajectories( setup, tracklets, external, eventInfo.beamSpot_ );
190 
191  ReferenceTrajectoryCollection::iterator itTrajectories;
192 
193  // Run the alignment algorithm.
194  for ( itTrajectories = trajectories.begin(); itTrajectories != trajectories.end(); ++itTrajectories )
195  {
196  itMap->first->alignmentUpdator()->process( *itTrajectories, theParameterStore, theNavigator,
197  itMap->first->metricsUpdator(), aMagneticField.product() );
198 
199  KalmanAlignmentDataCollector::fillHistogram( "Trajectory_RecHits", (*itTrajectories)->recHits().size() );
200  }
201  }
202  }
203  catch( cms::Exception& exception )
204  {
205  cout << exception.what() << endl;
206  terminate();
207  throw exception;
208  }
209 }
210 
211 
213 {
214  // Just to be sure, set all APEs to zero ...
215  setAPEToZero();
216 
217  const edm::ParameterSet initConfig = theConfiguration.getParameter< edm::ParameterSet >( "ParameterConfig" );
218 
219  int updateGraph = initConfig.getUntrackedParameter< int >( "UpdateGraphs", 100 );
220 
221  bool addPositionError = false;// = initConfig.getUntrackedParameter< bool >( "AddPositionError", true );
222 
223  int seed = initConfig.getUntrackedParameter< int >( "RandomSeed", 1726354 );
224  CLHEP::HepRandom::createInstance();
225  CLHEP::HepRandom::setTheSeed( seed );
226 
227  bool applyXShifts = initConfig.getUntrackedParameter< bool >( "ApplyXShifts", false );
228  bool applyYShifts = initConfig.getUntrackedParameter< bool >( "ApplyYShifts", false );
229  bool applyZShifts = initConfig.getUntrackedParameter< bool >( "ApplyZShifts", false );
230  bool applyXRots = initConfig.getUntrackedParameter< bool >( "ApplyXRotations", false );
231  bool applyYRots = initConfig.getUntrackedParameter< bool >( "ApplyYRotations", false );
232  bool applyZRots = initConfig.getUntrackedParameter< bool >( "ApplyZRotations", false );
233 
234  bool applyRandomStartValues = initConfig.getUntrackedParameter< bool >( "ApplyRandomStartValues", false );
235  if ( applyRandomStartValues )
236  cout << "[KalmanAlignmentAlgorithm::initializeAlignmentParameters] ADDING RANDOM START VALUES!!!" << endl;
237 
238  bool applyCurl = initConfig.getUntrackedParameter< bool >( "ApplyCurl", false );
239  double curlConst = initConfig.getUntrackedParameter< double >( "CurlConstant", 1e-6 );
240 
241  bool applyShifts = applyXShifts || applyYShifts || applyZShifts;
242  bool applyRots = applyXRots || applyYRots || applyZRots;
243  //bool applyMisalignment = applyShifts || applyRots || applyCurl;
244 
245  AlgebraicVector displacement( 3 );
246  AlgebraicVector eulerAngles( 3 );
247 
248  AlgebraicVector startParameters( 6, 0 );
249  AlgebraicSymMatrix startError( 6, 0 );
250 
251  AlgebraicVector randSig( 6, 0 );
252 
253  vector< string > initSelection = initConfig.getParameter< vector<string> >( "InitializationSelector" );
254 
255  vector< string >::iterator itInitSel;
256  for ( itInitSel = initSelection.begin(); itInitSel != initSelection.end(); ++itInitSel )
257  {
258  const edm::ParameterSet config = initConfig.getParameter< edm::ParameterSet >( *itInitSel );
259 
260  addPositionError = initConfig.getUntrackedParameter< bool >( "AddPositionError", false );
261 
262  double xAPEError = initConfig.getUntrackedParameter< double >( "SigmaXPositionError", 2e-2 );
263  double yAPEError = initConfig.getUntrackedParameter< double >( "SigmaYPositionError", 2e-2 );
264  double zAPEError = initConfig.getUntrackedParameter< double >( "SigmaZPositionError", 2e-2 );
265 
266  double sigmaXShift = config.getUntrackedParameter< double >( "SigmaXShifts", 4e-2 );
267  double sigmaYShift = config.getUntrackedParameter< double >( "SigmaYShifts", 4e-2 );
268  double sigmaZShift = config.getUntrackedParameter< double >( "SigmaZShifts", 4e-2 );
269  double sigmaXRot = config.getUntrackedParameter< double >( "SigmaXRotations", 5e-4 );
270  double sigmaYRot = config.getUntrackedParameter< double >( "SigmaYRotations", 5e-4 );
271  double sigmaZRot = config.getUntrackedParameter< double >( "SigmaZRotations", 5e-4 );
272 
273  randSig[0] = sigmaXShift; randSig[1] = sigmaYShift; randSig[2] = sigmaZShift;
274  randSig[3] = sigmaXRot; randSig[4] = sigmaYRot; randSig[5] = sigmaZRot;
275 
276  startError[0][0] = config.getUntrackedParameter< double >( "XShiftsStartError", 4e-4 );
277  startError[1][1] = config.getUntrackedParameter< double >( "YShiftsStartError", 4e-4 );
278  startError[2][2] = config.getUntrackedParameter< double >( "ZShiftsStartError", 4e-4 );
279  startError[3][3] = config.getUntrackedParameter< double >( "XRotationsStartError", 3e-5 );
280  startError[4][4] = config.getUntrackedParameter< double >( "YRotationsStartError", 3e-5 );
281  startError[5][5] = config.getUntrackedParameter< double >( "ZRotationsStartError", 3e-5 );
282 
283  const vector< char > dummyParamSelector( 6, '0' );
284  const vector< string > alignableSelector = config.getParameter< vector<string> >( "AlignableSelection" );
285 
286  vector< string >::const_iterator itAliSel;
287  for ( itAliSel = alignableSelector.begin(); itAliSel != alignableSelector.end(); ++itAliSel )
288  {
289  theSelector->addSelection( *itAliSel, dummyParamSelector );
290  cout << "[" << *itInitSel << "] add selection: " << *itAliSel << endl;
291  }
292 
293  vector< Alignable* >::iterator itAlignable;
294  vector< Alignable* > alignables;
295  vector< Alignable* > alignablesFromSelector = theSelector->selectedAlignables();
296  for ( itAlignable = alignablesFromSelector.begin(); itAlignable != alignablesFromSelector.end(); ++itAlignable )
297  //if ( (*itAlignable)->alignmentParameters() )
298  alignables.push_back( *itAlignable );
299 
300  cout << "[" << *itInitSel << "] total number of selected alignables = " << alignables.size() << endl;
301 
302  sort( alignables.begin(), alignables.end(), *this );
303 
304  // Apply existing alignment parameters.
305  map< Alignable*, vector< AlignmentParameters* > > alignmentParametersMap;
306 
307  int iApply = 0;
308  bool readParam = config.getUntrackedParameter< bool >( "ReadParametersFromFile", false );
309  bool readCovar = config.getUntrackedParameter< bool >( "ReadCovarianceFromFile", false );
310  bool applyParam = config.getUntrackedParameter< bool >( "ApplyParametersFromFile", false );
311  bool applyCovar = config.getUntrackedParameter< bool >( "ApplyErrorFromFile", false );
312  if ( readParam || readCovar || applyParam || applyCovar )
313  {
314  string file = config.getUntrackedParameter< string >( "FileName", "Input.root" );
315  int ierr = 0;
316  int iter = 1;
317 
318  AlignmentIORoot alignmentIO;
319  while ( !ierr )
320  {
321  cout << "[" << *itInitSel << "] read alignment parameters. file / iteration = " << file << " / " << iter << endl;
322  vector< AlignmentParameters* > alignmentParameters = alignmentIO.readAlignmentParameters( alignables, file.c_str(), iter, ierr );
323  cout << "[" << *itInitSel << "] #param / ierr = " << alignmentParameters.size() << " / " << ierr << endl;
324 
325  vector< AlignmentParameters* >::iterator itParam;
326  for ( itParam = alignmentParameters.begin(); itParam != alignmentParameters.end(); ++itParam )
327  alignmentParametersMap[(*itParam)->alignable()].push_back( *itParam );
328 
329  ++iter;
330  }
331  }
332 
333  int iAlign = 0;
334 
335  for ( itAlignable = alignables.begin(); itAlignable != alignables.end(); itAlignable++ )
336  {
337  if ( (*itAlignable)->alignmentParameters() == 0 )
338  {
339  cout << "[KalmanAlignmentAlgorithm::initializeAlignmentParameters] "
340  << "alignable is not associated with alignment parameters --> skip" << endl;
341  continue;
342  }
343 
344  if ( (*itAlignable)->alignmentParameters()->type() != AlignmentParametersFactory::kRigidBody )
345  {
346  cout << "[KalmanAlignmentAlgorithm::initializeAlignmentParameters] "
347  << "alignable is not associated with rigid body alignment parameters --> skip" << endl;
348  continue;
349  }
350 
351  displacement[0] = applyXShifts ? sigmaXShift*CLHEP::RandGauss::shoot() : 0.;
352  displacement[1] = applyYShifts ? sigmaZShift*CLHEP::RandGauss::shoot() : 0.;
353  displacement[2] = applyZShifts ? sigmaYShift*CLHEP::RandGauss::shoot() : 0.;
354 
355  if ( applyShifts )
356  {
357  align::LocalVector localShift( displacement[0], displacement[1], displacement[2] );
358  align::GlobalVector globalShift = ( *itAlignable )->surface().toGlobal( localShift );
359  ( *itAlignable )->move( globalShift );
360  }
361 
362  align::EulerAngles eulerAngles( 3 );
363 
364  eulerAngles[0] = applyXRots ? sigmaXRot*CLHEP::RandGauss::shoot() : 0.;
365  eulerAngles[1] = applyYRots ? sigmaYRot*CLHEP::RandGauss::shoot() : 0.;
366  eulerAngles[2] = applyZRots ? sigmaZRot*CLHEP::RandGauss::shoot() : 0.;
367 
368  if ( applyRots )
369  {
370  align::RotationType localRotation = align::toMatrix( eulerAngles );
371  ( *itAlignable )->rotateInLocalFrame( localRotation );
372  }
373 
374  if ( applyCurl )
375  {
376  double radius = ( *itAlignable )->globalPosition().perp();
377  ( *itAlignable )->rotateAroundGlobalZ( curlConst*radius );
378  }
379 
380  if ( addPositionError )
381  {
382  LocalVector localError( sqrt(xAPEError), sqrt(yAPEError), sqrt(zAPEError) );
383  GlobalVector globalError = (*itAlignable)->surface().toGlobal( localError );
384  AlignmentPositionError ape( globalError.x(), globalError.y(), globalError.z() );
385  // FIXME (GF): The above does not seem to be a correct error transformation!
386  ( *itAlignable )->setAlignmentPositionError( ape, true ); // true: propagate down
387  }
388 
389  //AlgebraicVector trueParameters( 6 );
390  //trueParameters[0] = -displacement[0];
391  //trueParameters[1] = -displacement[1];
392  //trueParameters[2] = -displacement[2];
393  //trueParameters[3] = -eulerAngles[0];
394  //trueParameters[4] = -eulerAngles[1];
395  //trueParameters[5] = -eulerAngles[2];
396 
397  if ( (*itAlignable)->alignmentParameters() != 0 )
398  {
399  AlignmentParameters* alignmentParameters;
400  if ( readParam && readCovar )
401  {
402  if ( alignmentParametersMap.find( *itAlignable ) == alignmentParametersMap.end() )
403  {
404  //cout << "apply param and cov from FILE -> none stored, apply DEFAULT " << endl;
405  alignmentParameters = (*itAlignable)->alignmentParameters()->clone( startParameters, startError );
406  alignmentParameters->setUserVariables( new KalmanAlignmentUserVariables( *itAlignable, updateGraph ) );
407  }
408  else
409  {
410  //cout << "apply param and cov from FILE" << endl;
411  alignmentParameters = alignmentParametersMap[*itAlignable].back();
412  KalmanAlignmentUserVariables* userVariables = new KalmanAlignmentUserVariables( *itAlignable, updateGraph );
413  userVariables->update( alignmentParameters );
414  alignmentParameters->setUserVariables( userVariables );
415  }
416  }
417  else if ( readParam )
418  {
419  if ( alignmentParametersMap.find( *itAlignable ) == alignmentParametersMap.end() )
420  {
421  alignmentParameters = (*itAlignable)->alignmentParameters()->clone( startParameters, startError );
422  alignmentParameters->setUserVariables( new KalmanAlignmentUserVariables( *itAlignable, updateGraph ) );
423  }
424  else
425  {
426  AlgebraicVector parameters = alignmentParametersMap[*itAlignable].back()->parameters();
427  alignmentParameters = (*itAlignable)->alignmentParameters()->clone( parameters, startError );
428  KalmanAlignmentUserVariables* userVariables = new KalmanAlignmentUserVariables( *itAlignable, updateGraph );
429  userVariables->update( alignmentParameters );
430  alignmentParameters->setUserVariables( userVariables );
431  }
432  }
433  else
434  {
435  //cout << "apply DEFAULT param and cov" << endl;
436  alignmentParameters = (*itAlignable)->alignmentParameters()->clone( startParameters, startError );
437  //alignmentParameters = (*itAlignable)->alignmentParameters()->clone( trueParameters, startError );
438  alignmentParameters->setUserVariables( new KalmanAlignmentUserVariables( *itAlignable, updateGraph ) );
439  }
440 
441  (*itAlignable)->setAlignmentParameters( alignmentParameters );
442  //if ( applyParam ) theParameterStore->applyParameters( *itAlignable );
443 
444  if ( applyRandomStartValues )
445  {
446  cout << "applying random start values" << endl;
447 
448  AlgebraicVector randomStartParameters = alignmentParameters->parameters();
449  AlgebraicSymMatrix randomStartErrors = alignmentParameters->covariance();
450 
451  for ( int iParam = 0; iParam < randomStartParameters.num_row(); ++iParam )
452  {
453  randomStartParameters[iParam] += sqrt(randSig[iParam])*CLHEP::RandGauss::shoot();
454  //randomStartErrors[iParam][iParam] += randSig[iParam]*randSig[iParam];
455  }
456 
457  //cout << randomStartParameters << endl;
458 
459  alignmentParameters = (*itAlignable)->alignmentParameters()->clone( randomStartParameters, randomStartErrors );
460  (*itAlignable)->setAlignmentParameters( alignmentParameters );
461  }
462 
463  (*itAlignable)->alignmentParameters()->setValid( true );
464 
465  }
466 
467  if ( ( applyParam || applyCovar ) && alignmentParametersMap.find( *itAlignable ) != alignmentParametersMap.end() )
468  {
469  ++iApply;
470 
471  vector< AlignmentParameters* > allAlignmentParameters = alignmentParametersMap[*itAlignable];
472  vector< AlignmentParameters* >::iterator itParam;
473 
474  for ( itParam = allAlignmentParameters.begin(); itParam != allAlignmentParameters.end(); ++itParam )
475  applyAlignmentParameters( *itAlignable, *itParam, applyParam, applyCovar );
476 
477  if ( ( *itAlignable )->alignmentParameters() )
478  {
479  KalmanAlignmentUserVariables* userVariables =
480  dynamic_cast< KalmanAlignmentUserVariables* >( ( *itAlignable )->alignmentParameters()->userVariables() );
481  if ( userVariables ) { ++iAlign; userVariables->setAlignmentFlag( true ); }
482  }
483  }
484  }
485 
486  cout << "[" << *itInitSel << "] Set the alignment flag for " << iAlign << " alignables." << endl;
487  cout << "[" << *itInitSel << "] number of applied parameters: " << iApply << endl;
488  theSelector->clear();
489  }
490 
491 }
492 
493 
495 {
496  // Read the setups from the config-file. They define which rec-hits are refitted to tracklets and whether they are used
497  // as an external measurement or not.
498 
499  const edm::ParameterSet initConfig = theConfiguration.getParameter< edm::ParameterSet >( "AlgorithmConfig" );
500  const vector<string> selSetup = initConfig.getParameter< vector<string> >( "Setups" );
501 
502  for ( vector<string>::const_iterator itSel = selSetup.begin(); itSel != selSetup.end(); ++itSel )
503  {
504  cout << "[KalmanAlignmentAlgorithm::initializeAlignmentSetups] Add AlignmentSetup: " << *itSel << endl;
505 
506  const edm::ParameterSet confSetup = initConfig.getParameter< edm::ParameterSet >( *itSel );
507 
508  string strPropDir = confSetup.getUntrackedParameter< string >( "PropagationDirection", "alongMomentum" );
509  string strSortingDir = confSetup.getUntrackedParameter< string >( "SortingDirection", "SortInsideOut" );
510  vector<int> trackingIDs = confSetup.getParameter< vector<int> >( "Tracking" );
511  unsigned int minTrackingHits = confSetup.getUntrackedParameter< unsigned int >( "MinTrackingHits", 0 );
512 
513  string strExternalPropDir = confSetup.getUntrackedParameter< string >( "ExternalPropagationDirection", "alongMomentum" );
514  string strExternalSortingDir = confSetup.getUntrackedParameter< string >( "ExternalSortingDirection", "SortInsideOut" );
515  vector<int> externalIDs = confSetup.getParameter< vector<int> >( "External" );
516  unsigned int minExternalHits = confSetup.getUntrackedParameter< unsigned int >( "MinExternalHits", 0 );
517 
518  edm::ESHandle< TrajectoryFitter > aTrajectoryFitter;
519  string fitterName = confSetup.getUntrackedParameter< string >( "Fitter", "KFFittingSmoother" );
520  setup.get<TrajectoryFitter::Record>().get( fitterName, aTrajectoryFitter );
521 
522  double outlierEstimateCut = 5.;
523 
524  const KFFittingSmoother* aFittingSmoother = dynamic_cast< const KFFittingSmoother* >( aTrajectoryFitter.product() );
525  if ( aFittingSmoother )
526  {
527  KFTrajectoryFitter* fitter = 0;
528  KFTrajectorySmoother* smoother = 0;
530 
531  KFTrajectoryFitter* externalFitter = 0;
532  KFTrajectorySmoother* externalSmoother = 0;
533 
534  PropagationDirection fitterDir = getDirection( strPropDir );
535  PropagationDirection externalFitterDir = getDirection( strExternalPropDir );
536 
537  PropagationDirection smootherDir = oppositeDirection( fitterDir );
538  PropagationDirection externalSmootherDir = oppositeDirection( externalFitterDir );
539 
540  const KFTrajectoryFitter* aKFFitter = dynamic_cast< const KFTrajectoryFitter* >( aFittingSmoother->fitter() );
541  if ( aKFFitter )
542  {
543  PropagatorWithMaterial propagator( fitterDir, 0.106, aKFFitter->propagator()->magneticField() );
544  Chi2MeasurementEstimator estimator( 30. );
545  fitter = new KFTrajectoryFitter( &propagator, updator, &estimator );
546 // fitter = new KFTrajectoryFitter( &propagator, aKFFitter->updator(), &estimator );
547 
548  AnalyticalPropagator externalPropagator( aKFFitter->propagator()->magneticField(), externalFitterDir );
549  Chi2MeasurementEstimator externalEstimator( 1000. );
550  externalFitter = new KFTrajectoryFitter( &externalPropagator, aKFFitter->updator(), &externalEstimator );
551  }
552 
553  const KFTrajectorySmoother* aKFSmoother = dynamic_cast< const KFTrajectorySmoother* >( aFittingSmoother->smoother() );
554  if ( aKFSmoother )
555  {
556 
557  PropagatorWithMaterial propagator( smootherDir, 0.106, aKFSmoother->propagator()->magneticField() );
558  Chi2MeasurementEstimator estimator( 30. );
559  smoother = new KFTrajectorySmoother( &propagator, updator, &estimator );
560 // smoother = new KFTrajectorySmoother( &propagator, aKFFitter->updator(), &estimator );
561 
562  AnalyticalPropagator externalPropagator( aKFSmoother->propagator()->magneticField(), externalSmootherDir );
563  Chi2MeasurementEstimator externalEstimator( 1000. );
564  externalSmoother = new KFTrajectorySmoother( &externalPropagator, aKFSmoother->updator(), &externalEstimator );
565  }
566 
567  if ( fitter && smoother )
568  {
569  KFFittingSmoother* fittingSmoother = new KFFittingSmoother( *fitter, *smoother, outlierEstimateCut );
570  KFFittingSmoother* externalFittingSmoother = new KFFittingSmoother( *externalFitter, *externalSmoother );
571 // KFFittingSmoother* fittingSmoother = aFittingSmoother->clone();
572 // KFFittingSmoother* externalFittingSmoother = aFittingSmoother->clone();
573 
574  string identifier;
576 
577  config = confSetup.getParameter< edm::ParameterSet >( "TrajectoryFactory" );
578  identifier = config.getParameter< string >( "TrajectoryFactoryName" );
579  cout << "TrajectoryFactoryPlugin::get() ... " << identifier << endl;
580  TrajectoryFactoryBase* trajectoryFactory = TrajectoryFactoryPlugin::get()->create( identifier, config );
581 
582  config = confSetup.getParameter< edm::ParameterSet >( "AlignmentUpdator" );
583  identifier = config.getParameter< string >( "AlignmentUpdatorName" );
584  KalmanAlignmentUpdator* alignmentUpdator = KalmanAlignmentUpdatorPlugin::get()->create( identifier, config );
585 
586  config = confSetup.getParameter< edm::ParameterSet >( "MetricsUpdator" );
587  identifier = config.getParameter< string >( "MetricsUpdatorName" );
588  KalmanAlignmentMetricsUpdator* metricsUpdator = KalmanAlignmentMetricsUpdatorPlugin::get()->create( identifier, config );
589 
590  KalmanAlignmentSetup::SortingDirection sortingDir = getSortingDirection( strSortingDir );
591  KalmanAlignmentSetup::SortingDirection externalSortingDir = getSortingDirection( strExternalSortingDir );
592 
593  AlignmentSetup* anAlignmentSetup
594  = new AlignmentSetup( *itSel,
595  fittingSmoother, fitter->propagator(), trackingIDs, minTrackingHits, sortingDir,
596  externalFittingSmoother, externalFitter->propagator(), externalIDs, minExternalHits, externalSortingDir,
597  trajectoryFactory, alignmentUpdator, metricsUpdator );
598 
599  theAlignmentSetups.push_back( anAlignmentSetup );
600 
601  delete fittingSmoother;
602  delete fitter;
603  delete smoother;
604 
605  delete externalFittingSmoother;
606  delete externalFitter;
607  delete externalSmoother;
608  }
609  else
610  {
611  throw cms::Exception( "BadConfig" ) << "[KalmanAlignmentAlgorithm::initializeAlignmentSetups] "
612  << "Instance of class KFFittingSmoother has no KFTrajectoryFitter/KFTrajectorySmoother.";
613  }
614 
615  delete updator;
616  }
617  else
618  {
619  throw cms::Exception( "BadConfig" ) << "[KalmanAlignmentAlgorithm::initializeAlignmentSetups] "
620  << "No instance of class KFFittingSmoother registered to the TrackingComponentsRecord.";
621  }
622  }
623 
624  cout << "[KalmanAlignmentAlgorithm::initializeAlignmentSetups] I'm using " << theAlignmentSetups.size() << " AlignmentSetup(s)." << endl;
625 
626 }
627 
628 
630 KalmanAlignmentAlgorithm::getSortingDirection( const std::string& sortDir ) const
631 {
632  if ( sortDir == "SortInsideOut" ) { return KalmanAlignmentSetup::sortInsideOut; }
633  if ( sortDir == "SortOutsideIn" ) { return KalmanAlignmentSetup::sortOutsideIn; }
634  if ( sortDir == "SortUpsideDown" ) { return KalmanAlignmentSetup::sortUpsideDown; }
635  if ( sortDir == "SortDownsideUp" ) { return KalmanAlignmentSetup::sortDownsideUp; }
636 
637  throw cms::Exception( "BadConfig" ) << "[KalmanAlignmentAlgorithm::getSortingDirection] "
638  << "Unknown sorting direction: " << sortDir << std::endl;
639 }
640 
641 
642 void
644  bool applyPar, bool applyCov ) const
645 {
646  RigidBodyAlignmentParameters* rbap = dynamic_cast<RigidBodyAlignmentParameters*>( par );
647 
648  if ( !rbap )
649  throw cms::Exception( "BadConfig" ) << "applyParameters: provided alignable does not have rigid body alignment parameters";
650 
651  if ( applyPar )
652  {
654  const AlignableSurface& alignableSurface = ali->surface();
655  ali->move( alignableSurface.toGlobal( align::LocalVector( shift[0], shift[1], shift[2] ) ) );
656 
657  align::EulerAngles angles = rbap->rotation();
658  if ( angles.normsq() > 1e-10 ) ali->rotateInLocalFrame( align::toMatrix( angles ) );
659  }
660 
661  if ( applyCov )
662  {
663  const AlgebraicSymMatrix& aliCov = rbap->covariance();
664  LocalVector localError( sqrt(aliCov[0][0]), sqrt(aliCov[1][1]), sqrt(aliCov[2][2]) );
665  GlobalVector globalError = ali->surface().toGlobal( localError );
666  AlignmentPositionError ape( globalError.x(), globalError.y(), globalError.z() );
667  // FIXME (GF): The above does not seem to be a correct error transformation!
668  ali->setAlignmentPositionError( ape, true ); // true: propagate down
669  }
670 }
671 
672 
674  vector<Alignable*>& comps ) const
675 {
676  comps.push_back( ali );
677  vector<Alignable*> nextComps = ali->components();
678  vector<Alignable*>::iterator it;
679  for ( it = nextComps.begin(); it != nextComps.end(); ++it ) getComponents( *it, comps );
680 }
681 
682 
684 {
685  std::cout << "[KalmanAlignmentAlgorithm::mergeResults] START MERGING RESULTS" << std::endl;
686 
688 
689  vector<string> inFileNames = mergeConf.getParameter< vector<string> >( "InputMergeFileNames" );
690  string outFileName = mergeConf.getParameter<string>( "OutputMergeFileName" );
691 
692  bool applyPar = mergeConf.getParameter<bool>( "ApplyParameters" );
693  bool applyCov = mergeConf.getParameter<bool>( "ApplyErrors" );
694 
695  map< Alignable*, vector< AlignmentParameters* > > alignmentParametersMap;
696 
697  vector< Alignable* > allAlignables;
698  getComponents( theTracker, allAlignables );
699 
700  cout << "allAlignables.size() = " << allAlignables.size() << endl;
701 
702  AlignmentIORoot alignmentIO;
703 
704  for ( vector<string>::iterator itFile = inFileNames.begin(); itFile != inFileNames.end(); ++itFile )
705  {
706  int iter = 1;
707  int ierr = 0;
708 
709  while ( !ierr )
710  {
711  cout << "Read alignment parameters. file / iteration = " << *itFile << " / " << iter << endl;
712 
713  vector< AlignmentParameters* > alignmentParameters =
714  alignmentIO.readAlignmentParameters( allAlignables, (*itFile).c_str(), iter, ierr );
715 
716  cout << "#param / ierr = " << alignmentParameters.size() << " / " << ierr << endl;
717 
718  vector< AlignmentParameters* >::iterator itParam;
719  for ( itParam = alignmentParameters.begin(); itParam != alignmentParameters.end(); ++itParam )
720  alignmentParametersMap[(*itParam)->alignable()].push_back( *itParam );
721 
722  ++iter;
723  }
724  }
725 
726  vector< Alignable* > alignablesToWrite;
727  alignablesToWrite.reserve( alignmentParametersMap.size() );
728 
729  map< Alignable*, vector< AlignmentParameters* > >::iterator itMap;
730  for ( itMap = alignmentParametersMap.begin(); itMap != alignmentParametersMap.end(); ++itMap )
731  {
732  //cout << "merge param for alignable" << itMap->first << endl;
733 
734  AlgebraicVector mergedParam( 6, 0 );
735  AlgebraicSymMatrix mergedCov( 6, 0 );
736  int nMerge = 0;
737 
738  vector< AlignmentParameters* >& vecParam = itMap->second;
739  vector< AlignmentParameters* >::iterator itParam;
740  for ( itParam = vecParam.begin(); itParam != vecParam.end(); ++itParam, ++nMerge )
741  mergedParam += (*itParam)->parameters();
742 
743  mergedParam /= nMerge;
744 
745  // no merging of errors up to now
746  AlignmentParameters* mergedAliParam = vecParam.front()->clone( mergedParam, mergedCov );
747  itMap->first->setAlignmentParameters( mergedAliParam );
748 
749  alignablesToWrite.push_back( itMap->first );
750 
751  if ( applyPar || applyCov ) applyAlignmentParameters( itMap->first, mergedAliParam, applyPar, applyCov );
752  }
753 
754  cout << "alignablesToWrite.size() = " << alignablesToWrite.size() << endl;
755 
756  int ierr = 0;
757  // Write output to "iteration 1", ...
758  alignmentIO.writeAlignmentParameters( alignablesToWrite, outFileName.c_str(), 1, false, ierr );
759  // ... or, if "iteration 1" already exists, write it to "highest iteration + 1"
760  if ( ierr == -1 ) alignmentIO.writeAlignmentParameters( alignablesToWrite, outFileName.c_str(), -1, false, ierr );
761 
762  std::cout << "[KalmanAlignmentAlgorithm::mergeResults] DONE" << std::endl;
763 }
764 
765 
767 {
768  AlignmentPositionError zeroAPE( 0., 0., 0. );
769  theTracker->setAlignmentPositionError( zeroAPE, true );
770 }
771 
void initializeAlignmentSetups(const edm::EventSetup &setup)
virtual char const * what() const
Definition: Exception.cc:141
T getParameter(std::string const &) const
virtual void initialize(const edm::EventSetup &setup, AlignableTracker *tracker, AlignableMuon *muon, AlignableExtras *extras, AlignmentParameterStore *store)
Call at beginning of job (must be implemented in derived class)
const Propagator * propagator() const
T getUntrackedParameter(std::string const &, T const &) const
dictionary parameters
Definition: Parameters.py:2
TrackletCollection refitTracks(const edm::EventSetup &eventSetup, const AlignmentSetupCollection &algoSetups, const ConstTrajTrackPairCollection &tracks, const reco::BeamSpot *beamSpot)
void histogramParameters(std::string histoNamePrefix)
Histogram current estimate of the alignment parameters wrt. the true values.
virtual void rotateInLocalFrame(const RotationType &rotation)
Rotation intepreted in the local reference frame.
Definition: Alignable.cc:91
void getComponents(Alignable *ali, std::vector< Alignable * > &comps) const
static void fillHistogram(std::string histo_name, float data)
const TrajectoryStateUpdator * updator() const
KalmanAlignmentAlgorithm(const edm::ParameterSet &config)
T y() const
Definition: PV3DBase.h:62
virtual void move(const GlobalVector &displacement)=0
Movement with respect to the global reference frame.
PropagationDirection
const ConstTrajTrackPairCollection & trajTrackPairs_
virtual Alignables components() const =0
Return vector of all direct components.
virtual void setAlignmentPositionError(const AlignmentPositionError &ape, bool propagateDown)
void initializeAlignmentParameters(const edm::EventSetup &setup)
void update(bool enforceUpdate=false)
Call this function in case the associated Alignable was updated by the alignment algorithm.
const TrajectorySmoother * smoother() const
AlignmentParameterStore * theParameterStore
const AlgebraicVector & parameters(void) const
Get alignment parameters.
AlignmentUserVariables * userVariables(void) const
Get pointer to user variables.
void clear()
remove all selected Alignables and geometrical restrictions
int iEvent
Definition: GenABIO.cc:243
const PropagationDirection getDirection(const std::string &dir) const
void setValid(bool v)
Set validity flag.
void applyAlignmentParameters(Alignable *ali, AlignmentParameters *par, bool applyPar, bool applyCov) const
T sqrt(T t)
Definition: SSEVec.h:46
T z() const
Definition: PV3DBase.h:63
std::vector< TrackletPtr > TrackletCollection
virtual void run(const edm::EventSetup &setup, const EventInfo &eventInfo)
Run the algorithm (must be implemented in derived class)
virtual void setAlignmentPositionError(const AlignmentPositionError &ape, bool propagateDown)=0
Set the alignment position error - if (!propagateDown) do not affect daughters.
const AlignableSurface & surface() const
Return the Surface (global position and orientation) of the object.
Definition: Alignable.h:126
const align::Alignables & selectedAlignables() const
vector of alignables selected so far
CLHEP::HepVector AlgebraicVector
AlignmentParameterSelector * theSelector
AlgebraicVector EulerAngles
Definition: Definitions.h:36
void setUserVariables(AlignmentUserVariables *auv)
Set pointer to user variables.
KalmanAlignmentSetup AlignmentSetup
tuple tracks
Definition: testEve_cfg.py:39
const T & get() const
Definition: EventSetup.h:55
void writeAlignmentParameters(const align::Alignables &alivec, const char *filename, int iter, bool validCheck, int &ierr)
write AlignmentParameters
const KalmanAlignmentSetup::SortingDirection getSortingDirection(const std::string &sortDir) const
virtual AlignmentParameters * clone(const AlgebraicVector &par, const AlgebraicSymMatrix &cov) const =0
Enforce clone methods in derived classes.
const TrajectoryStateUpdator * updator() const
T const * product() const
Definition: ESHandle.h:62
AlignmentSetupCollection theAlignmentSetups
KalmanAlignmentTrackRefitter * theRefitter
AlgebraicVector translation(void) const
Get translation parameters.
unsigned int addSelection(const std::string &name, const std::vector< char > &paramSel)
virtual const MagneticField * magneticField() const =0
const Propagator * propagator() const
int numberOfUpdates(void) const
Return the number of updates.
AlignableNavigator * theNavigator
align::GlobalPoints toGlobal(const align::LocalPoints &) const
Return in global coord given a set of local points.
RotationType toMatrix(const EulerAngles &)
Convert rotation angles about x-, y-, z-axes to matrix.
Definition: Utilities.cc:40
CLHEP::HepSymMatrix AlgebraicSymMatrix
static unsigned int const shift
const TrajectoryFitter * fitter() const
static void configure(const edm::ParameterSet &config)
tuple cout
Definition: gather_cfg.py:121
#define DEFINE_EDM_PLUGIN(factory, type, name)
virtual Alignables components() const
Return vector of direct components.
virtual void terminate(void)
Call at end of job (must be implemented in derived class)
const PropagationDirection oppositeDirection(const PropagationDirection dir) const
align::Parameters readAlignmentParameters(const align::Alignables &alivec, const char *filename, int iter, int &ierr)
read AlignmentParameters
const AlgebraicSymMatrix & covariance(void) const
Get parameter covariance matrix.
AlgebraicVector rotation(void) const
Get rotation parameters.
Constructor of the full muon geometry.
Definition: AlignableMuon.h:36
T x() const
Definition: PV3DBase.h:61
TrajectoryFactoryBase::ReferenceTrajectoryCollection ReferenceTrajectoryCollection
TrajectoryFactoryBase::ExternalPredictionCollection ExternalPredictionCollection
void setup(std::vector< TH2F > &depth, std::string name, std::string units="")
T get(const Candidate &c)
Definition: component.h:56
std::vector< ConstTrajTrackPair > ConstTrajTrackPairCollection
define event information passed to algorithms