CMS 3D CMS Logo

/afs/cern.ch/work/a/aaltunda/public/www/CMSSW_6_2_5/src/Alignment/ReferenceTrajectories/src/ReferenceTrajectory.cc

Go to the documentation of this file.
00001 //  Author     : Gero Flucke (based on code by Edmund Widl replacing ORCA's TkReferenceTrack)
00002 //  date       : 2006/09/17
00003 //  last update: $Date: 2013/04/12 13:22:30 $
00004 //  by         : $Author: innocent $
00005 
00006 #include <memory>
00007 
00008 #include "Alignment/ReferenceTrajectories/interface/ReferenceTrajectory.h"
00009 
00010 #include "DataFormats/GeometrySurface/interface/Surface.h" 
00011 #include "DataFormats/GeometrySurface/interface/Plane.h"
00012 
00013 #include "FWCore/MessageLogger/interface/MessageLogger.h"
00014 
00015 #include "DataFormats/CLHEP/interface/AlgebraicObjects.h" 
00016 #include "DataFormats/GeometrySurface/interface/LocalError.h"
00017 #include "DataFormats/GeometryVector/interface/LocalPoint.h"
00018 #include "Geometry/CommonDetUnit/interface/GeomDet.h"
00019 
00020 #include "DataFormats/TrajectoryState/interface/LocalTrajectoryParameters.h"
00021 #include "DataFormats/TrackingRecHit/interface/KfComponentsHolder.h"
00022 
00023 #include "TrackingTools/AnalyticalJacobians/interface/AnalyticalCurvilinearJacobian.h"
00024 #include "TrackingTools/AnalyticalJacobians/interface/JacobianLocalToCurvilinear.h"
00025 #include "TrackingTools/AnalyticalJacobians/interface/JacobianCurvilinearToLocal.h"
00026 
00027 #include "TrackingTools/GeomPropagators/interface/AnalyticalPropagator.h"
00028 #include "TrackPropagation/RungeKutta/interface/defaultRKPropagator.h"
00029 
00030 #include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h"
00031 #include "TrackingTools/TrajectoryParametrization/interface/GlobalTrajectoryParameters.h"
00032 
00033 #include "TrackingTools/MaterialEffects/interface/MultipleScatteringUpdator.h"
00034 #include "TrackingTools/MaterialEffects/interface/EnergyLossUpdator.h"
00035 #include "TrackingTools/MaterialEffects/interface/CombinedMaterialEffectsUpdator.h"
00036 #include <TrackingTools/PatternTools/interface/TSCPBuilderNoMaterial.h>
00037 #include <TrackingTools/PatternTools/interface/TSCBLBuilderNoMaterial.h>
00038 #include "TrackingTools/TrajectoryState/interface/TrajectoryStateClosestToPoint.h"
00039 #include "TrackingTools/TrajectoryState/interface/TrajectoryStateClosestToBeamLine.h"
00040 
00041 #include "MagneticField/Engine/interface/MagneticField.h"
00042 
00043 #include "Alignment/ReferenceTrajectories/interface/BeamSpotTransientTrackingRecHit.h"
00044 #include "Alignment/ReferenceTrajectories/interface/BeamSpotGeomDet.h"
00045 
00046 //__________________________________________________________________________________
00047 
00048 ReferenceTrajectory::ReferenceTrajectory(const TrajectoryStateOnSurface &refTsos,
00049                                          const TransientTrackingRecHit::ConstRecHitContainer
00050                                          &recHits, bool hitsAreReverse,
00051                                          const MagneticField *magField, 
00052                                          MaterialEffects materialEffects,
00053                                          PropagationDirection propDir,
00054                                          double mass,
00055                                          bool useBeamSpot, const reco::BeamSpot &beamSpot) 
00056  : ReferenceTrajectoryBase( 
00057    (materialEffects >= brokenLinesCoarse) ? 1 : refTsos.localParameters().mixedFormatVector().kSize, 
00058    (useBeamSpot == true) ? recHits.size()+1 : recHits.size(),
00059    (materialEffects >= brokenLinesCoarse) ? 
00060        2*((useBeamSpot == true) ? recHits.size()+1 : recHits.size())   :
00061    ( (materialEffects == breakPoints) ? 2*((useBeamSpot == true) ? recHits.size()+1 : recHits.size())-2 : 0) , 
00062    (materialEffects >= brokenLinesCoarse) ? 
00063        2*((useBeamSpot == true) ? recHits.size()+1 : recHits.size())-4 : 
00064    ( (materialEffects == breakPoints) ? 2*((useBeamSpot == true) ? recHits.size()+1 : recHits.size())-2 : 0) )
00065 {
00066   // no check against magField == 0  
00067   theParameters = asHepVector<5>( refTsos.localParameters().mixedFormatVector() );
00068   
00069   if (hitsAreReverse) {
00070     TransientTrackingRecHit::ConstRecHitContainer fwdRecHits;
00071     fwdRecHits.reserve(recHits.size());
00072     for (TransientTrackingRecHit::ConstRecHitContainer::const_reverse_iterator it=recHits.rbegin();
00073          it != recHits.rend(); ++it) {
00074       fwdRecHits.push_back(*it);
00075     }
00076     theValidityFlag = this->construct(refTsos, fwdRecHits, mass, materialEffects,
00077                                       propDir, magField,
00078                                       useBeamSpot, beamSpot);
00079   } else {
00080     theValidityFlag = this->construct(refTsos, recHits, mass, materialEffects,
00081                                       propDir, magField,
00082                                       useBeamSpot, beamSpot);
00083   }
00084 }
00085 
00086 
00087 //__________________________________________________________________________________
00088 
00089 ReferenceTrajectory::ReferenceTrajectory( unsigned int nPar, unsigned int nHits,
00090                                           MaterialEffects materialEffects)
00091  : ReferenceTrajectoryBase( 
00092    (materialEffects >= brokenLinesCoarse) ? 1 : nPar, 
00093    nHits, 
00094    (materialEffects >= brokenLinesCoarse) ? 2*nHits   : ( (materialEffects == breakPoints) ? 2*nHits-2 : 0 ), 
00095    (materialEffects >= brokenLinesCoarse) ? 2*nHits-4 : ( (materialEffects == breakPoints) ? 2*nHits-2 : 0 ) )
00096 {}
00097 
00098 
00099 //__________________________________________________________________________________
00100 
00101 bool ReferenceTrajectory::construct(const TrajectoryStateOnSurface &refTsos, 
00102                                     const TransientTrackingRecHit::ConstRecHitContainer &recHits,
00103                                     double mass, MaterialEffects materialEffects,
00104                                     const PropagationDirection propDir,
00105                                     const MagneticField *magField,
00106                                     bool useBeamSpot,
00107                                     const reco::BeamSpot &beamSpot)
00108 {   
00109   TrajectoryStateOnSurface theRefTsos = refTsos;
00110 
00111   const SurfaceSide surfaceSide = this->surfaceSide(propDir);
00112   // auto_ptr to avoid memory leaks in case of not reaching delete at end of method:
00113   std::auto_ptr<MaterialEffectsUpdator> aMaterialEffectsUpdator
00114     (this->createUpdator(materialEffects, mass));
00115   if (!aMaterialEffectsUpdator.get()) return false; // empty auto_ptr
00116 
00117   AlgebraicMatrix                 fullJacobian(theParameters.num_row(), theParameters.num_row());
00118   std::vector<AlgebraicMatrix>    allJacobians; 
00119   allJacobians.reserve(theNumberOfHits);
00120 
00121   TransientTrackingRecHit::ConstRecHitPointer  previousHitPtr;
00122   TrajectoryStateOnSurface                     previousTsos;
00123   AlgebraicSymMatrix              previousChangeInCurvature(theParameters.num_row(), 1);
00124   std::vector<AlgebraicSymMatrix> allCurvatureChanges; 
00125   allCurvatureChanges.reserve(theNumberOfHits);
00126   
00127   const LocalTrajectoryError zeroErrors(0., 0., 0., 0., 0.);
00128 
00129   std::vector<AlgebraicMatrix> allProjections;
00130   allProjections.reserve(theNumberOfHits);
00131   std::vector<AlgebraicSymMatrix> allDeltaParameterCovs;
00132   allDeltaParameterCovs.reserve(theNumberOfHits);
00133 
00134   // CHK
00135   std::vector<AlgebraicMatrix> allLocalToCurv;
00136   allLocalToCurv.reserve(theNumberOfHits); 
00137   std::vector<double> allSteps;
00138   allSteps.reserve(theNumberOfHits); 
00139   std::vector<AlgebraicMatrix>    allCurvlinJacobians; 
00140   allCurvlinJacobians.reserve(theNumberOfHits);
00141   
00142   AlgebraicMatrix firstCurvlinJacobian(5, 5, 1);
00143   
00144   unsigned int iRow = 0;
00145 
00146   // local storage vector of all rechits (including rechit for beam spot in case it is used)
00147   TransientTrackingRecHit::ConstRecHitContainer allRecHits;
00148 
00149   if (useBeamSpot && propDir==alongMomentum) {
00150     
00151     GlobalPoint bs(beamSpot.x0(), beamSpot.y0(), beamSpot.z0());
00152     
00153     TrajectoryStateClosestToBeamLine tsctbl(TSCBLBuilderNoMaterial()(*(refTsos.freeState()), beamSpot));
00154     if (!tsctbl.isValid()) {
00155       edm::LogError("Alignment") << "@SUB=ReferenceTrajectory::construct" 
00156                                  << "TrajectoryStateClostestToBeamLine invalid. Skip track.";
00157       return false;
00158     }
00159 
00160     FreeTrajectoryState pcaFts = tsctbl.trackStateAtPCA();
00161     GlobalVector bd(beamSpot.dxdz(), beamSpot.dydz(), 1.0);
00162     
00163     //propagation FIXME: Should use same propagator everywhere...
00164     AnalyticalPropagator propagator(magField);
00165     std::pair< TrajectoryStateOnSurface, double > tsosWithPath =
00166       propagator.propagateWithPath(pcaFts, refTsos.surface());
00167     
00168     if (!tsosWithPath.first.isValid()) return false;
00169     
00170     GlobalVector momDir(pcaFts.momentum());
00171     GlobalVector perpDir(bd.cross(momDir));
00172     Plane::RotationType rotation(perpDir, bd);
00173     
00174     BeamSpotGeomDet * bsGeom = new BeamSpotGeomDet(Plane::build(bs, rotation));
00175 
00176     // There is also a constructor taking the magentic field. Use this one instead?
00177     theRefTsos = TrajectoryStateOnSurface(pcaFts, bsGeom->surface());
00178     
00179     TransientTrackingRecHit::ConstRecHitPointer bsRecHit = 
00180       new BeamSpotTransientTrackingRecHit(beamSpot,
00181                                           bsGeom,
00182                                           theRefTsos.freeState()->momentum().phi());
00183     allRecHits.push_back(bsRecHit);
00184 
00185   }
00186   
00187   // copy all rechits to the local storage vector
00188   TransientTrackingRecHit::ConstRecHitContainer::const_iterator itRecHit;
00189   for ( itRecHit = recHits.begin(); itRecHit != recHits.end(); ++itRecHit ) { 
00190     const TransientTrackingRecHit::ConstRecHitPointer &hitPtr = *itRecHit;
00191     allRecHits.push_back(hitPtr);
00192   }
00193 
00194   for ( itRecHit = allRecHits.begin(); itRecHit != allRecHits.end(); ++itRecHit ) { 
00195     
00196     const TransientTrackingRecHit::ConstRecHitPointer &hitPtr = *itRecHit;
00197     theRecHits.push_back(hitPtr);
00198 
00199     if (0 == iRow) {
00200 
00201       // compute the derivatives of the reference-track's parameters w.r.t. the initial ones
00202       // derivative of the initial reference-track parameters w.r.t. themselves is of course the identity 
00203       fullJacobian = AlgebraicMatrix(theParameters.num_row(), theParameters.num_row(), 1);
00204       allJacobians.push_back(fullJacobian);
00205       theTsosVec.push_back(theRefTsos);
00206       const JacobianLocalToCurvilinear startTrafo(hitPtr->det()->surface(), theRefTsos.localParameters(), *magField);
00207       const AlgebraicMatrix localToCurvilinear =  asHepMatrix<5>(startTrafo.jacobian());
00208       if (materialEffects <= breakPoints) {
00209          theInnerTrajectoryToCurvilinear = asHepMatrix<5>(startTrafo.jacobian());
00210          theInnerLocalToTrajectory = AlgebraicMatrix(5, 5, 1);
00211       }  
00212       allLocalToCurv.push_back(localToCurvilinear);
00213       allSteps.push_back(0.);
00214       allCurvlinJacobians.push_back(firstCurvlinJacobian);
00215 
00216     } else {
00217 
00218       AlgebraicMatrix nextJacobian;
00219       AlgebraicMatrix nextCurvlinJacobian;
00220       double nextStep = 0.;
00221       TrajectoryStateOnSurface nextTsos;
00222 
00223       if (!this->propagate(previousHitPtr->det()->surface(), previousTsos,
00224                            hitPtr->det()->surface(), nextTsos,
00225                            nextJacobian, nextCurvlinJacobian, nextStep, propDir, magField)) {
00226         return false; // stop if problem...// no delete aMaterialEffectsUpdator needed
00227       }
00228       
00229       allJacobians.push_back(nextJacobian);
00230       fullJacobian = nextJacobian * previousChangeInCurvature * fullJacobian;
00231       theTsosVec.push_back(nextTsos);
00232       
00233       const JacobianLocalToCurvilinear startTrafo(hitPtr->det()->surface(), nextTsos.localParameters(), *magField);
00234       const AlgebraicMatrix localToCurvilinear =  asHepMatrix<5>(startTrafo.jacobian());
00235       allLocalToCurv.push_back(localToCurvilinear);
00236       if (nextStep == 0.) { 
00237         edm::LogError("Alignment") << "@SUB=ReferenceTrajectory::construct"
00238                                    << "step 0. from id " << previousHitPtr->geographicalId()
00239                                    << " to " << hitPtr->det()->geographicalId() << ".";
00240         // brokenLinesFine will not work, brokenLinesCoarse combines close by layers
00241         if (materialEffects == brokenLinesFine) {
00242           edm::LogError("Alignment") << "@SUB=ReferenceTrajectory::construct" << "Skip track.";
00243           return false;
00244         }
00245       }
00246       allSteps.push_back(nextStep);
00247       allCurvlinJacobians.push_back(nextCurvlinJacobian);
00248 
00249     }
00250 
00251     // take material effects into account. since trajectory-state is constructed with errors equal zero,
00252     // the updated state contains only the uncertainties due to interactions in the current layer.
00253     const TrajectoryStateOnSurface tmpTsos(theTsosVec.back().localParameters(), zeroErrors,
00254                                            theTsosVec.back().surface(), magField, surfaceSide);
00255     const TrajectoryStateOnSurface updatedTsos = aMaterialEffectsUpdator->updateState(tmpTsos, propDir);
00256 
00257     if ( !updatedTsos.isValid() ) return false;// no delete aMaterialEffectsUpdator needed
00258     
00259     if ( theTsosVec.back().localParameters().charge() )
00260     {
00261       previousChangeInCurvature[0][0] = updatedTsos.localParameters().signedInverseMomentum() 
00262         / theTsosVec.back().localParameters().signedInverseMomentum();
00263     }
00264     
00265     // get multiple-scattering covariance-matrix
00266     allDeltaParameterCovs.push_back( asHepMatrix<5>(updatedTsos.localError().matrix()) );
00267     allCurvatureChanges.push_back(previousChangeInCurvature);
00268     
00269     // projection-matrix tsos-parameters -> measurement-coordinates
00270     allProjections.push_back(this->getHitProjectionMatrix(hitPtr));
00271     // set start-parameters for next propagation. trajectory-state without error
00272     //  - no error propagation needed here.
00273     previousHitPtr = hitPtr;
00274     previousTsos   = TrajectoryStateOnSurface(updatedTsos.globalParameters(),
00275                                               updatedTsos.surface(), surfaceSide);
00276     
00277     if (materialEffects < brokenLinesCoarse) {
00278       this->fillDerivatives(allProjections.back(), fullJacobian, iRow);
00279     }
00280 
00281     AlgebraicVector mixedLocalParams = asHepVector<5>(theTsosVec.back().localParameters().mixedFormatVector());
00282     this->fillTrajectoryPositions(allProjections.back(), mixedLocalParams, iRow);
00283     if ( useRecHit( hitPtr ) ) this->fillMeasurementAndError(hitPtr, iRow, updatedTsos);
00284 
00285     iRow += nMeasPerHit;
00286   } // end of loop on hits
00287 
00288   bool msOK = true;
00289   switch (materialEffects) {
00290   case none:
00291     break;
00292   case multipleScattering:
00293   case energyLoss:
00294   case combined:
00295     msOK = this->addMaterialEffectsCov(allJacobians, allProjections, allCurvatureChanges,
00296                                        allDeltaParameterCovs);
00297     break;
00298   case breakPoints:
00299     msOK = this->addMaterialEffectsBp(allJacobians, allProjections, allCurvatureChanges,
00300                                       allDeltaParameterCovs, allLocalToCurv);
00301     break;
00302   case brokenLinesCoarse:
00303     msOK = this->addMaterialEffectsBrl(allProjections, allDeltaParameterCovs, allLocalToCurv,
00304                                        allSteps, refTsos.globalParameters());
00305     break;
00306   case brokenLinesFine:
00307     msOK = this->addMaterialEffectsBrl(allCurvlinJacobians, allProjections, allCurvatureChanges,
00308                                        allDeltaParameterCovs, allLocalToCurv, refTsos.globalParameters());
00309   }
00310   if (!msOK) return false;
00311  
00312   if (refTsos.hasError()) {
00313     AlgebraicSymMatrix parameterCov = asHepMatrix<5>(refTsos.localError().matrix());
00314     AlgebraicMatrix  parDeriv;
00315     if (theNumberOfVirtualPars>0) { 
00316       parDeriv = theDerivatives.sub( 1, nMeasPerHit*allJacobians.size(), 1, theParameters.num_row() ); 
00317     } else {
00318       parDeriv = theDerivatives; 
00319     }
00320     theTrajectoryPositionCov = parameterCov.similarity(parDeriv);
00321   } else {
00322     theTrajectoryPositionCov = AlgebraicSymMatrix(theDerivatives.num_row(), 1);
00323   }
00324 
00325   return true;
00326 }
00327 
00328 //__________________________________________________________________________________
00329 
00330 MaterialEffectsUpdator*
00331 ReferenceTrajectory::createUpdator(MaterialEffects materialEffects, double mass) const
00332 {
00333   switch (materialEffects) {
00334     // MultipleScatteringUpdator doesn't change the trajectory-state
00335     // during update and can therefore be used if material effects should be ignored:
00336   case none:
00337   case multipleScattering: 
00338     return new MultipleScatteringUpdator(mass);
00339   case energyLoss:
00340     return new EnergyLossUpdator(mass);
00341   case combined:
00342     return new CombinedMaterialEffectsUpdator(mass);
00343   case breakPoints:
00344     return new CombinedMaterialEffectsUpdator(mass);
00345   case brokenLinesCoarse:
00346   case brokenLinesFine:
00347     return new CombinedMaterialEffectsUpdator(mass);
00348 }
00349 
00350   return 0;
00351 }
00352 
00353 //__________________________________________________________________________________
00354 
00355 bool ReferenceTrajectory::propagate(const Plane &previousSurface, const TrajectoryStateOnSurface &previousTsos,
00356                                     const Plane &newSurface, TrajectoryStateOnSurface &newTsos, AlgebraicMatrix &newJacobian, 
00357                                     AlgebraicMatrix &newCurvlinJacobian, double &nextStep,
00358                                     const PropagationDirection propDir, const MagneticField *magField) const
00359 {
00360   // propagate to next layer
00364   //AnalyticalPropagator aPropagator(magField, propDir);
00365   // Hard coded RungeKutta instead Analytical (avoid bias in TEC), but
00366   // work around TrackPropagation/RungeKutta/interface/RKTestPropagator.h and
00367   // http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.9
00368   defaultRKPropagator::Product  rkprod(magField, propDir); //double tolerance = 5.e-5)
00369   Propagator &aPropagator = rkprod.propagator;
00370   const std::pair<TrajectoryStateOnSurface, double> tsosWithPath =
00371     aPropagator.propagateWithPath(previousTsos, newSurface);
00372 
00373   // stop if propagation wasn't successful
00374   if (!tsosWithPath.first.isValid()) return false;
00375   
00376   nextStep = tsosWithPath.second;
00377   // calculate derivative of reference-track parameters on the actual layer w.r.t. the ones
00378   // on the previous layer (both in global coordinates)
00379   const AnalyticalCurvilinearJacobian aJacobian(previousTsos.globalParameters(), 
00380                                                 tsosWithPath.first.globalPosition(),
00381                                                 tsosWithPath.first.globalMomentum(),
00382                                                 tsosWithPath.second);
00383   const AlgebraicMatrix curvilinearJacobian = asHepMatrix<5,5>(aJacobian.jacobian());
00384 
00385   // jacobian of the track parameters on the previous layer for local->global transformation
00386   const JacobianLocalToCurvilinear startTrafo(previousSurface, previousTsos.localParameters(), *magField);
00387   const AlgebraicMatrix localToCurvilinear = asHepMatrix<5>(startTrafo.jacobian());
00388     
00389   // jacobian of the track parameters on the actual layer for global->local transformation
00390   const JacobianCurvilinearToLocal endTrafo(newSurface, tsosWithPath.first.localParameters(), *magField);
00391   const AlgebraicMatrix curvilinearToLocal = asHepMatrix<5>(endTrafo.jacobian());
00392   
00393   // compute derivative of reference-track parameters on the actual layer w.r.t. the ones on
00394   // the previous layer (both in their local representation)
00395   newCurvlinJacobian = curvilinearJacobian;
00396   newJacobian = curvilinearToLocal * curvilinearJacobian * localToCurvilinear;
00397   newTsos     = tsosWithPath.first;
00398 
00399   return true;
00400 }
00401 
00402 //__________________________________________________________________________________
00403 
00404 void ReferenceTrajectory::fillMeasurementAndError(const TransientTrackingRecHit::ConstRecHitPointer &hitPtr,
00405                                                   unsigned int iRow,
00406                                                   const TrajectoryStateOnSurface &updatedTsos)
00407 {
00408   // get the measurements and their errors, use information updated with tsos if improving
00409   // (GF: Also for measurements or only for errors or do the former not change?)
00410   // GF 10/2008: I doubt that it makes sense to update the hit with the tsos here:
00411   //             That is an analytical extrapolation and not the best guess of the real 
00412   //             track state on the module, but the latter should be better to get the best
00413   //             hit uncertainty estimate!
00414   TransientTrackingRecHit::ConstRecHitPointer newHitPtr(hitPtr->canImproveWithTrack() ?
00415                                                         hitPtr->clone(updatedTsos) : hitPtr);
00416 
00417   const LocalPoint localMeasurement    = newHitPtr->localPosition();
00418   const LocalError localMeasurementCov = newHitPtr->localPositionError();
00419   
00420   theMeasurements[iRow]   = localMeasurement.x();
00421   theMeasurements[iRow+1] = localMeasurement.y();
00422   theMeasurementsCov[iRow][iRow]     = localMeasurementCov.xx();
00423   theMeasurementsCov[iRow][iRow+1]   = localMeasurementCov.xy();
00424   theMeasurementsCov[iRow+1][iRow+1] = localMeasurementCov.yy();
00425   // GF: Should be a loop once the hit dimension is not hardcoded as nMeasPerHit (to be checked):
00426   // for (int i = 0; i < hitPtr->dimension(); ++i) {
00427   //   theMeasurements[iRow+i]   = hitPtr->parameters()[i]; // fixme: parameters() is by value!
00428   //   for (int j = i; j < hitPtr->dimension(); ++j) {
00429   //     theMeasurementsCov[iRow+i][iRow+j] = hitPtr->parametersError()[i][j];
00430   //   }
00431   // }
00432 }
00433 
00434 //__________________________________________________________________________________
00435 
00436 void ReferenceTrajectory::fillDerivatives(const AlgebraicMatrix &projection,
00437                                           const AlgebraicMatrix &fullJacobian,
00438                                           unsigned int iRow)
00439 {
00440   // derivatives of the local coordinates of the reference track w.r.t. to the inital track-parameters
00441   const AlgebraicMatrix projectedJacobian(projection * fullJacobian);
00442   for (int i = 0; i < parameters().num_row(); ++i) {
00443     theDerivatives[iRow  ][i] = projectedJacobian[0][i];
00444     theDerivatives[iRow+1][i] = projectedJacobian[1][i];
00445     // GF: Should be a loop once the hit dimension is not hardcoded as nMeasPerHit (to be checked):
00446     // for (int j = 0; j < projection.num_col(); ++j) {
00447     //   theDerivatives[iRow+j][i] = projectedJacobian[j][i];
00448     // }
00449   }
00450 }
00451 
00452 //__________________________________________________________________________________
00453 
00454 void ReferenceTrajectory::fillTrajectoryPositions(const AlgebraicMatrix &projection, 
00455                                                   const AlgebraicVector &mixedLocalParams, 
00456                                                   unsigned int iRow)
00457 {
00458   // get the local coordinates of the reference trajectory
00459   const AlgebraicVector localPosition(projection * mixedLocalParams);
00460   theTrajectoryPositions[iRow] = localPosition[0];
00461   theTrajectoryPositions[iRow+1] = localPosition[1];
00462   // GF: Should be a loop once the hit dimension is not hardcoded as nMeasPerHit (to be checked):
00463   // for (int j = 0; j < projection.num_col(); ++j) {
00464   //   theTrajectoryPositions[iRow+j] = localPosition[j];
00465   // }
00466 }
00467 
00468 //__________________________________________________________________________________
00469 
00470 bool ReferenceTrajectory::addMaterialEffectsCov(const std::vector<AlgebraicMatrix> &allJacobians, 
00471                                                 const std::vector<AlgebraicMatrix> &allProjections,
00472                                                 const std::vector<AlgebraicSymMatrix> &allCurvatureChanges,
00473                                                 const std::vector<AlgebraicSymMatrix> &allDeltaParameterCovs)
00474 {
00475   // the uncertainty due to multiple scattering is 'transferred' to the error matrix of the hits
00476 
00477   // GF: Needs update once hit dimension is not hardcoded as nMeasPerHit!
00478 
00479   AlgebraicSymMatrix materialEffectsCov(nMeasPerHit * allJacobians.size(), 0);
00480 
00481   // additional covariance-matrix of the measurements due to material-effects (single measurement)
00482   AlgebraicSymMatrix deltaMaterialEffectsCov;
00483 
00484   // additional covariance-matrix of the parameters due to material-effects
00485   AlgebraicSymMatrix paramMaterialEffectsCov(allDeltaParameterCovs[0]); //initialization
00486   // error-propagation to state after energy loss
00487   //GFback  paramMaterialEffectsCov = paramMaterialEffectsCov.similarity(allCurvatureChanges[0]);
00488 
00489   AlgebraicMatrix tempParameterCov;
00490   AlgebraicMatrix tempMeasurementCov;
00491 
00492   for (unsigned int k = 1; k < allJacobians.size(); ++k) {
00493     // error-propagation to next layer
00494     paramMaterialEffectsCov = paramMaterialEffectsCov.similarity(allJacobians[k]);
00495 
00496     // get dependences for the measurements
00497     deltaMaterialEffectsCov = paramMaterialEffectsCov.similarity(allProjections[k]);
00498     materialEffectsCov[nMeasPerHit*k  ][nMeasPerHit*k  ] = deltaMaterialEffectsCov[0][0];
00499     materialEffectsCov[nMeasPerHit*k  ][nMeasPerHit*k+1] = deltaMaterialEffectsCov[0][1];
00500     materialEffectsCov[nMeasPerHit*k+1][nMeasPerHit*k  ] = deltaMaterialEffectsCov[1][0];
00501     materialEffectsCov[nMeasPerHit*k+1][nMeasPerHit*k+1] = deltaMaterialEffectsCov[1][1];
00502 
00503     // GFback add uncertainties for the following layers due to scattering at this layer
00504     paramMaterialEffectsCov += allDeltaParameterCovs[k];
00505     // end GFback
00506     tempParameterCov = paramMaterialEffectsCov;
00507 
00508     // compute "inter-layer-dependencies"
00509     for (unsigned int l = k+1; l < allJacobians.size(); ++l) {
00510       tempParameterCov   = allJacobians[l]   * allCurvatureChanges[l] * tempParameterCov;
00511       tempMeasurementCov = allProjections[l] * tempParameterCov       * allProjections[k].T();
00512 
00513       materialEffectsCov[nMeasPerHit*l][nMeasPerHit*k] = tempMeasurementCov[0][0];
00514       materialEffectsCov[nMeasPerHit*k][nMeasPerHit*l] = tempMeasurementCov[0][0];
00515 
00516       materialEffectsCov[nMeasPerHit*l][nMeasPerHit*k+1] = tempMeasurementCov[0][1];
00517       materialEffectsCov[nMeasPerHit*k+1][nMeasPerHit*l] = tempMeasurementCov[0][1];
00518 
00519       materialEffectsCov[nMeasPerHit*l+1][nMeasPerHit*k] = tempMeasurementCov[1][0];
00520       materialEffectsCov[nMeasPerHit*k][nMeasPerHit*l+1] = tempMeasurementCov[1][0];
00521 
00522       materialEffectsCov[nMeasPerHit*l+1][nMeasPerHit*k+1] = tempMeasurementCov[1][1];
00523       materialEffectsCov[nMeasPerHit*k+1][nMeasPerHit*l+1] = tempMeasurementCov[1][1];
00524     } 
00525     // add uncertainties for the following layers due to scattering at this layer
00526     // GFback paramMaterialEffectsCov += allDeltaParameterCovs[k];    
00527     // error-propagation to state after energy loss
00528     paramMaterialEffectsCov = paramMaterialEffectsCov.similarity(allCurvatureChanges[k]);
00529      
00530   }
00531   theMeasurementsCov += materialEffectsCov;
00532 
00533   return true; // cannot fail
00534 }
00535 
00536 //__________________________________________________________________________________
00537 
00538 bool ReferenceTrajectory::addMaterialEffectsBp(const std::vector<AlgebraicMatrix> &allJacobians, 
00539                                                const std::vector<AlgebraicMatrix> &allProjections,
00540                                                const std::vector<AlgebraicSymMatrix> &allCurvatureChanges,
00541                                                const std::vector<AlgebraicSymMatrix> &allDeltaParameterCovs,
00542                                                const std::vector<AlgebraicMatrix> &allLocalToCurv)
00543 {
00544 //CHK: add material effects using break points
00545   int offsetPar = theNumberOfPars; 
00546   int offsetMeas = nMeasPerHit * allJacobians.size();
00547   int ierr = 0; 
00548 
00549   AlgebraicMatrix tempJacobian;
00550   AlgebraicMatrix MSprojection(2,5);
00551   MSprojection[0][1] = 1;
00552   MSprojection[1][2] = 1;
00553   AlgebraicSymMatrix tempMSCov; 
00554   AlgebraicSymMatrix tempMSCovProj;
00555   AlgebraicMatrix tempMSJacProj;   
00556 
00557   for (unsigned int k = 1; k < allJacobians.size(); ++k) {
00558 // CHK 
00559     int kbp = k-1;
00560     tempJacobian = allJacobians[k] * allCurvatureChanges[k];
00561     tempMSCov = allDeltaParameterCovs[k-1].similarity(allLocalToCurv[k-1]);
00562     tempMSCovProj = tempMSCov.similarity(MSprojection);
00563     theMeasurementsCov[offsetMeas+nMeasPerHit*kbp  ][offsetMeas+nMeasPerHit*kbp  ] = tempMSCovProj[0][0];
00564     theMeasurementsCov[offsetMeas+nMeasPerHit*kbp+1][offsetMeas+nMeasPerHit*kbp+1]=  tempMSCovProj[1][1];
00565     theDerivatives[offsetMeas+nMeasPerHit*kbp  ][offsetPar+2*kbp  ] = 1.0;
00566     theDerivatives[offsetMeas+nMeasPerHit*kbp+1][offsetPar+2*kbp+1] = 1.0 ; 
00567 
00568     tempMSJacProj = (allProjections[k] * ( tempJacobian * allLocalToCurv[k-1].inverse(ierr) )) * MSprojection.T();
00569     if (ierr) {
00570       edm::LogError("Alignment") << "@SUB=ReferenceTrajectory::addMaterialEffectsBp"
00571                                  << "Inversion 1 for break points failed: " << ierr;
00572       return false;
00573     }
00574     theDerivatives[nMeasPerHit*k  ][offsetPar+2*kbp  ] =  tempMSJacProj[0][0];  
00575     theDerivatives[nMeasPerHit*k  ][offsetPar+2*kbp+1] =  tempMSJacProj[0][1]; 
00576     theDerivatives[nMeasPerHit*k+1][offsetPar+2*kbp  ] =  tempMSJacProj[1][0];  
00577     theDerivatives[nMeasPerHit*k+1][offsetPar+2*kbp+1] =  tempMSJacProj[1][1];
00578               
00579     for (unsigned int l = k+1; l < allJacobians.size(); ++l) {
00580 // CHK    
00581       int kbp = k-1;
00582       tempJacobian = allJacobians[l] * allCurvatureChanges[l] * tempJacobian; 
00583       tempMSJacProj = (allProjections[l] * ( tempJacobian * allLocalToCurv[k-1].inverse(ierr) )) * MSprojection.T();
00584       if (ierr) {
00585         edm::LogError("Alignment") << "@SUB=ReferenceTrajectory::addMaterialEffectsBp"
00586                                    << "Inversion 2 for break points failed: " << ierr;
00587         return false;
00588       }
00589       theDerivatives[nMeasPerHit*l  ][offsetPar+2*kbp  ] =  tempMSJacProj[0][0];  
00590       theDerivatives[nMeasPerHit*l  ][offsetPar+2*kbp+1] =  tempMSJacProj[0][1]; 
00591       theDerivatives[nMeasPerHit*l+1][offsetPar+2*kbp  ] =  tempMSJacProj[1][0];  
00592       theDerivatives[nMeasPerHit*l+1][offsetPar+2*kbp+1] =  tempMSJacProj[1][1]; 
00593 
00594     }
00595 
00596   }
00597 
00598   return true;
00599 }
00600 
00601 //__________________________________________________________________________________
00602 
00603 bool ReferenceTrajectory::addMaterialEffectsBrl(const std::vector<AlgebraicMatrix> &allCurvlinJacobians, 
00604                                                 const std::vector<AlgebraicMatrix> &allProjections,
00605                                                 const std::vector<AlgebraicSymMatrix> &allCurvatureChanges,
00606                                                 const std::vector<AlgebraicSymMatrix> &allDeltaParameterCovs,
00607                                                 const std::vector<AlgebraicMatrix> &allLocalToCurv,
00608                                                 const GlobalTrajectoryParameters &gtp)
00609 {
00610 //CHK: add material effects using broken lines
00611 //fine: use exact Jacobians, all detectors  
00612 //broken lines: pair of offsets (u1,u2) = (xt,yt) (in curvilinear frame (q/p,lambda,phi,xt,yt)) at each layer
00613 //              scattering angles (alpha1,alpha2) = (cosLambda*dPhi, dLambda) (cosLambda cancels in Chi2)
00614 //              DU' = (dU'/dU)*DU + (dU'/dAlpha)*DAlpha + (dU'/dQbyp)*DQbyp (propagation of U)
00615 //                  = J*DU + S*DAlpha + d*DQbyp
00616 //           => DAlpha = S^-1 (DU' - J*DU - d*DQbyp)
00617 
00618   int offsetPar = theNumberOfPars;
00619   int offsetMeas = nMeasPerHit*allCurvlinJacobians.size();
00620   int ierr = 0;
00621 
00622   GlobalVector p = gtp.momentum();
00623   double cosLambda = sqrt((p.x()*p.x()+p.y()*p.y())/(p.x()*p.x()+p.y()*p.y()+p.z()*p.z()));
00624 
00625 // transformations Curvilinear <-> BrokenLines
00626   AlgebraicMatrix QbypToCurv(5,1);   // dCurv/dQbyp
00627   QbypToCurv[0][0] = 1.;             // dQbyp/dQbyp
00628   AlgebraicMatrix AngleToCurv(5,2);  // dCurv/dAlpha
00629   AngleToCurv[1][1] = 1.;            // dlambda/dalpha2
00630   AngleToCurv[2][0] = 1./cosLambda;  // dphi/dalpha1
00631   AlgebraicMatrix CurvToAngle(2,5);  // dAlpha/dCurv
00632   CurvToAngle[1][1] = 1.;            // dalpha2/dlambda
00633   CurvToAngle[0][2] = cosLambda;     // dalpha1/dphi
00634   AlgebraicMatrix OffsetToCurv(5,2); // dCurv/dU
00635   OffsetToCurv[3][0] = 1.;           // dxt/du1
00636   OffsetToCurv[4][1] = 1.;           // dyt/du2
00637   AlgebraicMatrix CurvToOffset(2,5); // dU/dCurv
00638   CurvToOffset[0][3] = 1.;           // du1/dxt
00639   CurvToOffset[1][4] = 1.;           // du2/dyt
00640 
00641 // transformations  trajectory to components (Qbyp, U1, U2)
00642   AlgebraicMatrix TrajToQbyp(1,5);
00643   TrajToQbyp[0][0] = 1.;
00644   AlgebraicMatrix TrajToOff1(2,5);
00645   TrajToOff1[0][1] = 1.;
00646   TrajToOff1[1][2] = 1.;
00647   AlgebraicMatrix TrajToOff2(2,5);
00648   TrajToOff2[0][3] = 1.;
00649   TrajToOff2[1][4] = 1.;
00650 
00651   AlgebraicMatrix JacOffsetToAngleC, JacQbypToAngleC;
00652   AlgebraicMatrix JacCurvToOffsetL, JacOffsetToOffsetL, JacAngleToOffsetL, JacQbypToOffsetL, JacOffsetToAngleL;
00653   AlgebraicMatrix JacCurvToOffsetN, JacOffsetToOffsetN, JacAngleToOffsetN, JacQbypToOffsetN, JacOffsetToAngleN;
00654 
00655 // transformation from trajectory to curvilinear parameters
00656 
00657   JacCurvToOffsetN = CurvToOffset * allCurvlinJacobians[1]; // (dU'/dCurv') * (dCurv'/dCurv) @ 2nd point
00658   JacOffsetToOffsetN = JacCurvToOffsetN * OffsetToCurv; // J: (dU'/dU)     = (dU'/dCurv') * (dCurv'/dCurv) * (dCurv/dU)
00659   JacAngleToOffsetN  = JacCurvToOffsetN * AngleToCurv;  // S: (dU'/dAlpha) = (dU'/dCurv') * (dCurv'/dCurv) * (dCurv/dAlpha)
00660   JacQbypToOffsetN   = JacCurvToOffsetN * QbypToCurv;   // d: (dU'/dQbyp)  = (dU'/dCurv') * (dCurv'/dCurv) * (dCurv/dQbyp)
00661   JacOffsetToAngleN  = JacAngleToOffsetN.inverse(ierr); // W
00662   if (ierr) {
00663      edm::LogError("Alignment") << "@SUB=ReferenceTrajectory::addMaterialEffectsBrl"
00664                                 << "Inversion 1 for fine broken lines failed: " << ierr;
00665      return false;
00666   }
00667   JacOffsetToAngleC = -(JacOffsetToAngleN * JacOffsetToOffsetN); // (dAlpha/dU)
00668   JacQbypToAngleC   = -(JacOffsetToAngleN * JacQbypToOffsetN);   // (dAlpha/dQbyp)
00669   // (dAlpha/dTraj) = (dAlpha/dQbyp) * (dQbyp/dTraj) + (dAlpha/dU1) * (dU1/dTraj) + (dAlpha/dU2) * (dU2/dTraj)
00670   AlgebraicMatrix JacTrajToAngle = JacQbypToAngleC * TrajToQbyp + JacOffsetToAngleC * TrajToOff1 + JacOffsetToAngleN * TrajToOff2;
00671   // (dCurv/dTraj) = (dCurv/dQbyp) * (dQbyp/dTraj) + (dCurv/dAlpha) * (dAlpha/dTraj) + (dCurv/dU) * (dU/dTraj)
00672   theInnerTrajectoryToCurvilinear = QbypToCurv * TrajToQbyp + AngleToCurv * JacTrajToAngle + OffsetToCurv * TrajToOff1;
00673   theInnerLocalToTrajectory = theInnerTrajectoryToCurvilinear.inverse(ierr) * allLocalToCurv[0];
00674   if (ierr) {
00675     edm::LogError("Alignment") << "@SUB=ReferenceTrajectory::addMaterialEffectsBrl"
00676                                << "Inversion 2 for fine broken lines failed: " << ierr;
00677     return false;
00678   }
00679 
00680   AlgebraicMatrix tempJacobian(allCurvatureChanges[0]);
00681   AlgebraicSymMatrix tempMSCov;
00682   AlgebraicSymMatrix tempMSCovProj;
00683   AlgebraicMatrix tempJacL, tempJacN;
00684   AlgebraicMatrix JacOffsetToMeas;
00685 
00686 // measurements from hits  
00687   for (unsigned int k = 0; k < allCurvlinJacobians.size(); ++k) {
00688 //  (dMeas/dU) = (dMeas/dLoc) * (dLoc/dCurv) * (dCurv/dU)
00689     JacOffsetToMeas = (allProjections[k] * allLocalToCurv[k].inverse(ierr) ) * OffsetToCurv;
00690     if (ierr) {
00691        edm::LogError("Alignment") << "@SUB=ReferenceTrajectory::addMaterialEffectsBrl"
00692                                    << "Inversion 3 for fine broken lines failed: " << ierr;
00693        return false;
00694     }
00695     theDerivatives[nMeasPerHit*k  ][offsetPar+2*k  ] =  JacOffsetToMeas[0][0];
00696     theDerivatives[nMeasPerHit*k  ][offsetPar+2*k+1] =  JacOffsetToMeas[0][1];
00697     theDerivatives[nMeasPerHit*k+1][offsetPar+2*k  ] =  JacOffsetToMeas[1][0];
00698     theDerivatives[nMeasPerHit*k+1][offsetPar+2*k+1] =  JacOffsetToMeas[1][1];
00699   }
00700 
00701 // measurement of MS kink  
00702   for (unsigned int k = 1; k < allCurvlinJacobians.size()-1; ++k) {
00703 // CHK 
00704     int iMsMeas = k-1; 
00705     int l    = k-1; // last hit
00706     int n    = k+1; // next hit
00707 
00708 // amount of multiple scattering in layer k  (angular error perp to direction)  
00709     tempMSCov = allDeltaParameterCovs[k].similarity(allLocalToCurv[k]);
00710     tempMSCovProj = tempMSCov.similarity(CurvToAngle);
00711     theMeasurementsCov[offsetMeas+nMeasPerHit*iMsMeas  ][offsetMeas+nMeasPerHit*iMsMeas  ] = tempMSCovProj[1][1];
00712     theMeasurementsCov[offsetMeas+nMeasPerHit*iMsMeas+1][offsetMeas+nMeasPerHit*iMsMeas+1] = tempMSCovProj[0][0];
00713 
00714 // transformation matices for offsets ( l <- k -> n )
00715     tempJacL = allCurvlinJacobians[k] * tempJacobian;
00716     JacCurvToOffsetL = CurvToOffset * tempJacL.inverse(ierr); // (dU'/dCurv') * (dCurv'/dCurv) @ last point
00717 
00718     if (ierr) {
00719        edm::LogError("Alignment") << "@SUB=ReferenceTrajectory::addMaterialEffectsBrl"
00720                                    << "Inversion 4 for fine broken lines failed: " << ierr;
00721        return false;
00722     }
00723     JacOffsetToOffsetL = JacCurvToOffsetL * OffsetToCurv; // J-: (dU'/dU)     = (dU'/dCurv') * (dCurv'/dCurv) * (dCurv/dU)
00724     JacAngleToOffsetL  = JacCurvToOffsetL * AngleToCurv;  // S-: (dU'/dAlpha) = (dU'/dCurv') * (dCurv'/dCurv) * (dCurv/dAlpha)
00725     JacQbypToOffsetL   = JacCurvToOffsetL * QbypToCurv;   // d-: (dU'/dQbyp)  = (dU'/dCurv') * (dCurv'/dCurv) * (dCurv/dQbyp)
00726     JacOffsetToAngleL  =-JacAngleToOffsetL.inverse(ierr); // W-
00727     if (ierr) {
00728        edm::LogError("Alignment") << "@SUB=ReferenceTrajectory::addMaterialEffectsBrl"
00729                                    << "Inversion 5 for fine broken lines failed: " << ierr;
00730        return false;
00731     }
00732     tempJacobian = tempJacobian * allCurvatureChanges[k];
00733     tempJacN = allCurvlinJacobians[n] * tempJacobian;
00734     JacCurvToOffsetN = CurvToOffset * tempJacN; // (dU'/dCurv') * (dCurv'/dCurv) @ next point
00735     JacOffsetToOffsetN = JacCurvToOffsetN * OffsetToCurv; // J+: (dU'/dU)     = (dU'/dCurv') * (dCurv'/dCurv) * (dCurv/dU)
00736     JacAngleToOffsetN  = JacCurvToOffsetN * AngleToCurv;  // S+: (dU'/dAlpha) = (dU'/dCurv') * (dCurv'/dCurv) * (dCurv/dAlpha)
00737     JacQbypToOffsetN   = JacCurvToOffsetN * QbypToCurv;   // d+: (dU'/dQbyp)  = (dU'/dCurv') * (dCurv'/dCurv) * (dCurv/dQbyp)
00738     JacOffsetToAngleN  = JacAngleToOffsetN.inverse(ierr); // W+
00739     if (ierr) {
00740        edm::LogError("Alignment") << "@SUB=ReferenceTrajectory::addMaterialEffectsBrl"
00741                                    << "Inversion 6 for fine broken lines failed: " << ierr;
00742        return false;
00743     }
00744     JacOffsetToAngleC = -(JacOffsetToAngleL * JacOffsetToOffsetL + JacOffsetToAngleN * JacOffsetToOffsetN);
00745     JacQbypToAngleC   = -(JacOffsetToAngleL * JacQbypToOffsetL   + JacOffsetToAngleN * JacQbypToOffsetN);
00746 
00747     // bending    
00748     theDerivatives[offsetMeas+nMeasPerHit*iMsMeas  ][              0] = JacQbypToAngleC[0][0];
00749     theDerivatives[offsetMeas+nMeasPerHit*iMsMeas+1][              0] = JacQbypToAngleC[1][0];
00750     // last layer
00751     theDerivatives[offsetMeas+nMeasPerHit*iMsMeas  ][offsetPar+2*l  ] = JacOffsetToAngleL[0][0];
00752     theDerivatives[offsetMeas+nMeasPerHit*iMsMeas  ][offsetPar+2*l+1] = JacOffsetToAngleL[0][1];
00753     theDerivatives[offsetMeas+nMeasPerHit*iMsMeas+1][offsetPar+2*l  ] = JacOffsetToAngleL[1][0];
00754     theDerivatives[offsetMeas+nMeasPerHit*iMsMeas+1][offsetPar+2*l+1] = JacOffsetToAngleL[1][1];
00755     // current layer
00756     theDerivatives[offsetMeas+nMeasPerHit*iMsMeas  ][offsetPar+2*k  ] = JacOffsetToAngleC[0][0];
00757     theDerivatives[offsetMeas+nMeasPerHit*iMsMeas  ][offsetPar+2*k+1] = JacOffsetToAngleC[0][1];
00758     theDerivatives[offsetMeas+nMeasPerHit*iMsMeas+1][offsetPar+2*k  ] = JacOffsetToAngleC[1][0];
00759     theDerivatives[offsetMeas+nMeasPerHit*iMsMeas+1][offsetPar+2*k+1] = JacOffsetToAngleC[1][1];
00760 
00761     // next layer
00762     theDerivatives[offsetMeas+nMeasPerHit*iMsMeas  ][offsetPar+2*n  ] = JacOffsetToAngleN[0][0];
00763     theDerivatives[offsetMeas+nMeasPerHit*iMsMeas  ][offsetPar+2*n+1] = JacOffsetToAngleN[0][1];
00764     theDerivatives[offsetMeas+nMeasPerHit*iMsMeas+1][offsetPar+2*n  ] = JacOffsetToAngleN[1][0];
00765     theDerivatives[offsetMeas+nMeasPerHit*iMsMeas+1][offsetPar+2*n+1] = JacOffsetToAngleN[1][1];
00766 
00767   }
00768 
00769   return true;
00770 }
00771 
00772 //__________________________________________________________________________________
00773 
00774 bool ReferenceTrajectory::addMaterialEffectsBrl(const std::vector<AlgebraicMatrix> &allProjections,
00775                                                 const std::vector<AlgebraicSymMatrix> &allDeltaParameterCovs,
00776                                                 const std::vector<AlgebraicMatrix> &allLocalToCurv,
00777                                                 const std::vector<double> &allSteps,
00778                                                 const GlobalTrajectoryParameters &gtp,
00779                                                 const double minStep)
00780 {
00781 //CHK: add material effects using broken lines
00782 //BrokenLinesCoarse: combine close by detectors, 
00783 //                   use approximate Jacobians from Steps (limit Qbyp -> 0),
00784 //                   bending only in RPhi (B=(0,0,Bz)), no energy loss correction
00785 
00786   int offsetPar = theNumberOfPars; 
00787   int offsetMeas = nMeasPerHit*allSteps.size();
00788   int ierr = 0;
00789 
00790   GlobalVector p = gtp.momentum();
00791   double cosLambda = sqrt((p.x()*p.x()+p.y()*p.y())/(p.x()*p.x()+p.y()*p.y()+p.z()*p.z()));
00792   double bFac = -gtp.magneticFieldInInverseGeV(gtp.position()).mag();
00793 
00794   // transformation from trajectory to curvilinear parameters at refTsos
00795   double delta (1.0/allSteps[1]);    
00796   theInnerTrajectoryToCurvilinear[0][0] = 1;
00797   theInnerTrajectoryToCurvilinear[1][2] = -delta;  
00798   theInnerTrajectoryToCurvilinear[1][4] =  delta;    
00799   theInnerTrajectoryToCurvilinear[2][0] = -0.5*bFac/delta;
00800   theInnerTrajectoryToCurvilinear[2][1] = -delta/cosLambda;
00801   theInnerTrajectoryToCurvilinear[2][3] =  delta/cosLambda;
00802   theInnerTrajectoryToCurvilinear[3][1] = 1;
00803   theInnerTrajectoryToCurvilinear[4][2] = 1;
00804   theInnerLocalToTrajectory = theInnerTrajectoryToCurvilinear.inverse(ierr) * allLocalToCurv[0];
00805   if (ierr) {
00806     edm::LogError("Alignment") << "@SUB=ReferenceTrajectory::addMaterialEffectsBrl"
00807                                << "Inversion 1 for coarse broken lines failed: " << ierr;
00808     return false;
00809   }
00810 
00811   AlgebraicMatrix CurvToAngle(2,5);  // dAlpha/dCurv
00812   CurvToAngle[1][1] = 1.;            // dalpha2/dlambda
00813   CurvToAngle[0][2] = cosLambda;     // dalpha1/dphi
00814   AlgebraicMatrix OffsetToCurv(5,2); // dCurv/dU
00815   OffsetToCurv[3][0] = 1.;           // dxt/du1
00816   OffsetToCurv[4][1] = 1.;           // dyt/du2
00817 
00818   AlgebraicSymMatrix tempMSCov;
00819   AlgebraicSymMatrix tempMSCovProj;
00820   AlgebraicMatrix JacOffsetToMeas;
00821 
00822   // combine closeby detectors into single plane
00823   std::vector<unsigned int> first(allSteps.size());
00824   std::vector<unsigned int> last (allSteps.size());
00825   std::vector<unsigned int> plane(allSteps.size());
00826   std::vector<double> sPlane(allSteps.size());
00827   unsigned int nPlane = 0;
00828   double sTot = 0;
00829 
00830   for (unsigned int k = 1; k < allSteps.size(); ++k) {
00831     sTot += allSteps[k];
00832     if (fabs(allSteps[k])>minStep) { nPlane += 1; first[nPlane] = k; }
00833     last[nPlane] = k;
00834     plane[k] = nPlane;
00835     sPlane[nPlane] += sTot;
00836   }
00837   if (nPlane < 2) return false; // pathological cases: need at least 2 planes
00838 
00839   theNumberOfVirtualPars = 2*(nPlane+1);
00840   theNumberOfVirtualMeas = 2*(nPlane-1);// unsigned underflow for nPlane == 0...
00841   for (unsigned int k = 0; k <= nPlane; ++k) { sPlane[k] /= (double) (last[k]-first[k]+1); }
00842 
00843   // measurements from hits
00844   sTot = 0; 
00845   for (unsigned int k = 0; k < allSteps.size(); ++k) {
00846     sTot += allSteps[k];
00847 //  (dMeas/dU) = (dMeas/dLoc) * (dLoc/dCurv) * (dCurv/dU)
00848     JacOffsetToMeas = (allProjections[k] * allLocalToCurv[k].inverse(ierr) ) * OffsetToCurv;
00849     if (ierr) {
00850       edm::LogError("Alignment") << "@SUB=ReferenceTrajectory::addMaterialEffectsBrl"
00851                                  << "Inversion 2 for coarse broken lines failed: " << ierr;
00852       return false;
00853     }
00854 
00855     unsigned int iPlane = plane[k];
00856     if (last[iPlane] == first[iPlane])
00857     { // single plane
00858       theDerivatives[nMeasPerHit*k  ][offsetPar+2*iPlane  ] =  JacOffsetToMeas[0][0];
00859       theDerivatives[nMeasPerHit*k  ][offsetPar+2*iPlane+1] =  JacOffsetToMeas[0][1];
00860       theDerivatives[nMeasPerHit*k+1][offsetPar+2*iPlane  ] =  JacOffsetToMeas[1][0];
00861       theDerivatives[nMeasPerHit*k+1][offsetPar+2*iPlane+1] =  JacOffsetToMeas[1][1];
00862     } else
00863     { // combined plane: (linear) interpolation
00864       unsigned int jPlane; // neighbor plane for interpolation
00865       if (fabs(sTot) < fabs(sPlane[iPlane])) { jPlane = (iPlane>0) ? iPlane - 1 : 1; }
00866       else  { jPlane = (iPlane<nPlane) ? iPlane + 1 : nPlane -1 ;}
00867       // interpolation weights
00868       double sDiff = sPlane[iPlane] - sPlane[jPlane];
00869       double iFrac = (sTot - sPlane[jPlane]) / sDiff;
00870       double jFrac = 1.0 - iFrac;
00871       theDerivatives[nMeasPerHit*k  ][offsetPar+2*iPlane  ] =  JacOffsetToMeas[0][0]*iFrac;
00872       theDerivatives[nMeasPerHit*k  ][offsetPar+2*iPlane+1] =  JacOffsetToMeas[0][1]*iFrac;
00873       theDerivatives[nMeasPerHit*k+1][offsetPar+2*iPlane  ] =  JacOffsetToMeas[1][0]*iFrac;
00874       theDerivatives[nMeasPerHit*k+1][offsetPar+2*iPlane+1] =  JacOffsetToMeas[1][1]*iFrac;
00875       theDerivatives[nMeasPerHit*k  ][offsetPar+2*jPlane  ] =  JacOffsetToMeas[0][0]*jFrac;
00876       theDerivatives[nMeasPerHit*k  ][offsetPar+2*jPlane+1] =  JacOffsetToMeas[0][1]*jFrac;
00877       theDerivatives[nMeasPerHit*k+1][offsetPar+2*jPlane  ] =  JacOffsetToMeas[1][0]*jFrac;
00878       theDerivatives[nMeasPerHit*k+1][offsetPar+2*jPlane+1] =  JacOffsetToMeas[1][1]*jFrac;
00879       // 2nd order neglected
00880       // theDerivatives[nMeasPerHit*k  ][                   0] = -0.5*bFac*sDiff*iFrac*sDiff*jFrac*cosLambda;
00881     }
00882   }
00883 
00884 // measurement of MS kink
00885   for (unsigned int i = 1; i < nPlane; ++i) {
00886 // CHK 
00887     int iMsMeas = i-1;
00888     int l    = i-1; // last hit
00889     int n    = i+1; // next hit
00890 
00891 // amount of multiple scattering in plane k
00892     for (unsigned int k = first[i]; k <= last[i]; ++k) {
00893       tempMSCov = allDeltaParameterCovs[k].similarity(allLocalToCurv[k]);
00894       tempMSCovProj = tempMSCov.similarity(CurvToAngle);
00895       theMeasurementsCov[offsetMeas+nMeasPerHit*iMsMeas  ][offsetMeas+nMeasPerHit*iMsMeas  ] += tempMSCovProj[0][0];
00896       theMeasurementsCov[offsetMeas+nMeasPerHit*iMsMeas+1][offsetMeas+nMeasPerHit*iMsMeas+1] += tempMSCovProj[1][1];
00897     }
00898 // broken line measurements for layer k, correlations between both planes neglected
00899     double stepK = sPlane[i] - sPlane[l];
00900     double stepN = sPlane[n] - sPlane[i];
00901     double deltaK (1.0/stepK);
00902     double deltaN (1.0/stepN);
00903     // bending (only in RPhi)
00904     theDerivatives[offsetMeas+nMeasPerHit*iMsMeas  ][              0] = -0.5*bFac*(stepK+stepN)*cosLambda;
00905     // last layer
00906     theDerivatives[offsetMeas+nMeasPerHit*iMsMeas  ][offsetPar+2*l  ] = deltaK;
00907     theDerivatives[offsetMeas+nMeasPerHit*iMsMeas+1][offsetPar+2*l+1] = deltaK;
00908     // current layer
00909     theDerivatives[offsetMeas+nMeasPerHit*iMsMeas  ][offsetPar+2*i  ] = -(deltaK + deltaN);
00910     theDerivatives[offsetMeas+nMeasPerHit*iMsMeas+1][offsetPar+2*i+1] = -(deltaK + deltaN);
00911     // next layer
00912     theDerivatives[offsetMeas+nMeasPerHit*iMsMeas  ][offsetPar+2*n  ] = deltaN;
00913     theDerivatives[offsetMeas+nMeasPerHit*iMsMeas+1][offsetPar+2*n+1] = deltaN;
00914   }
00915 
00916   return true;
00917 }
00918 
00919 //__________________________________________________________________________________
00920 
00921 AlgebraicMatrix
00922 ReferenceTrajectory::getHitProjectionMatrix
00923 (const TransientTrackingRecHit::ConstRecHitPointer &hitPtr) const
00924 {
00925   if (this->useRecHit(hitPtr)) {
00926     // check which templated non-member function to call:
00927     switch (hitPtr->dimension()) {
00928     case 1:
00929       return getHitProjectionMatrixT<1>(hitPtr);
00930     case 2:
00931       return getHitProjectionMatrixT<2>(hitPtr);
00932     case 3:
00933       return getHitProjectionMatrixT<3>(hitPtr);
00934     case 4:
00935       return getHitProjectionMatrixT<4>(hitPtr);
00936     case 5:
00937       return getHitProjectionMatrixT<5>(hitPtr);
00938     default:
00939       throw cms::Exception("ReferenceTrajectory::getHitProjectionMatrix")
00940         << "Unexpected hit dimension: " << hitPtr->dimension() << "\n";
00941     }
00942   }
00943   // invalid or (to please compiler) unknown dimension
00944   return AlgebraicMatrix(2, 5, 0); // get size from ???
00945 }
00946 
00947 //__________________________________________________________________________________
00948 
00949 template<unsigned int N>
00950 AlgebraicMatrix 
00951 ReferenceTrajectory::getHitProjectionMatrixT
00952 (const TransientTrackingRecHit::ConstRecHitPointer &hitPtr) const
00953 {
00954   // define variables that will be used to setup the KfComponentsHolder
00955   // (their allocated memory is needed by 'hitPtr->getKfComponents(..)'
00956   // ProjectMatrix<double,5,N>  pf; // not needed
00957   typename AlgebraicROOTObject<N,5>::Matrix H; 
00958   typename AlgebraicROOTObject<N>::Vector r, rMeas; 
00959   typename AlgebraicROOTObject<N,N>::SymMatrix V, VMeas;
00960   // input for the holder - but dummy is OK here to just get the projection matrix:
00961   const AlgebraicVector5 dummyPars;
00962   const AlgebraicSymMatrix55 dummyErr;
00963 
00964   // setup the holder with the correct dimensions and get the values
00965   KfComponentsHolder holder;
00966   holder.setup<N>(&r, &V, &H, /*&pf,*/ &rMeas, &VMeas, dummyPars, dummyErr);
00967   hitPtr->getKfComponents(holder);
00968 
00969   return asHepMatrix<N,5>(holder.projection<N>());
00970 }
00971