34#include <Math/ProbFunc.h>
36#include <TDecompChol.h>
37#include <TMatrixDSymEigen.h>
44 double& chi2,
double& ndf,
45 int startId,
int endId,
int& nFailedHits)
52 Exception exc(
"KalmanFitter::fitTrack ==> cannot use (un)weightedClosestToReference(Wire) as multiple measurement handling.",__LINE__,__FILE__);
74 for (
int i = startId; ; i+=direction) {
76 assert(direction == +1 || direction == -1);
79 debugOut <<
" process TrackPoint nr. " << i <<
" (" << tp <<
")\n";
96 debugOut <<
"There was an exception, try to continue with next TrackPoint " << i+direction <<
" \n";
116 Exception exc(
"KalmanFitter::processTrack: Cannot process pruned track!", __LINE__,__FILE__);
128 debugOut <<
"take backward update of previous iteration as seed \n";
135 debugOut <<
"take smoothed state of cardinal rep fit as seed \n";
149 debugOut <<
"take seed state of track as seed \n";
156 double oldChi2FW(1.e6);
157 double oldChi2BW(1.e6);
158 double oldPvalFW(0.);
160 double oldPvalBW = 0.;
161 double chi2FW(0), ndfFW(0);
162 double chi2BW(0), ndfBW(0);
164 int nFailedHitsForward(0), nFailedHitsBackward(0);
170 unsigned int nIt = 0;
174 debugOut <<
"\033[1;21mstate pre" << std::endl;
176 debugOut <<
"\033[0mfitting" << std::endl;
179 if (!
fitTrack(tr, rep, chi2FW, ndfFW, 0, -1, nFailedHitsForward)) {
188 debugOut <<
"\033[1;21mstate post forward" << std::endl;
196 if (!
fitTrack(tr, rep, chi2BW, ndfBW, -1, 0, nFailedHitsBackward)) {
205 debugOut <<
"\033[1;21mstate post backward" << std::endl;
209 debugOut <<
"old chi2s: " << oldChi2BW <<
", " << oldChi2FW
210 <<
" new chi2s: " << chi2BW <<
", " << chi2FW
211 <<
" oldPvals " << oldPvalFW <<
", " << oldPvalBW << std::endl;
215 double PvalBW = std::max(0.,ROOT::Math::chisquared_cdf_c(chi2BW, ndfBW));
216 double PvalFW = (
debugLvl_ > 0) ? std::max(0.,ROOT::Math::chisquared_cdf_c(chi2FW, ndfFW)) : 0;
222 bool converged(
false);
223 bool finished(
false);
249 if (nFailedHitsForward == 0 && nFailedHitsBackward == 0)
256 status->
setNFailedPoints(std::max(nFailedHitsForward, nFailedHitsBackward));
272 debugOut <<
"KalmanFitter::number of max iterations reached!\n";
281 status->
setNFailedPoints(std::max(nFailedHitsForward, nFailedHitsBackward));
293 status->
setNFailedPoints(std::max(nFailedHitsForward, nFailedHitsBackward));
307 Exception exc(
"KalmanFitter::processTrack: Cannot process pruned track!", __LINE__,__FILE__);
325 if (direction == 1 && startId > 0)
331 if (prevTrackPoint !=
nullptr &&
337 debugOut <<
"take update of previous fitter info as seed \n";
344 debugOut <<
"take smoothed state of cardinal rep fit as seed \n";
358 debugOut <<
"take seed of track as seed \n";
369 debugOut <<
"\033[1;21mstate pre" << std::endl;
371 debugOut <<
"\033[0mfitting" << std::endl;
376 fitTrack(tr, rep, chi2, ndf, startId, endId, nFailedHits);
383 const AbsTrackRep* rep,
double& chi2,
double& ndf,
int direction)
385 assert(direction == -1 || direction == +1);
401 bool oldWeightsFixed(
false);
402 std::vector<double> oldWeights;
416 const std::vector< genfit::AbsMeasurement* >& rawMeasurements = tp->
getRawMeasurements();
424 debugOut <<
"extrapolated by " << extLen << std::endl;
431 const std::vector< genfit::AbsMeasurement* >& rawMeasurements = tp->
getRawMeasurements();
432 for (std::vector< genfit::AbsMeasurement* >::const_iterator it = rawMeasurements.begin(); it != rawMeasurements.end(); ++it) {
447 debugOut <<
"its plane is at R = " << plane->getO().Perp()
448 <<
" with normal pointing along (" << plane->getNormal().X() <<
", " << plane->getNormal().Y() <<
", " << plane->getNormal().Z() <<
")" << std::endl;
451 TVectorD stateVector(state->
getState());
452 TMatrixDSym cov(state->
getCov());
458 const std::vector<MeasurementOnPlane *>& measurements =
getMeasurements(fi, tp, direction);
459 for (std::vector<MeasurementOnPlane *>::const_iterator it = measurements.begin(); it != measurements.end(); ++it) {
461 const double weight = mOnPlane.
getWeight();
464 debugOut <<
"Weight of measurement: " << weight <<
"\n";
469 debugOut <<
"Weight of measurement is almost 0, continue ... \n";
474 const TVectorD& measurement(mOnPlane.
getState());
478 1./weight * mOnPlane.
getCov() :
482 debugOut <<
"State prediction: "; stateVector.Print();
486 debugOut <<
"measurement: "; measurement.Print();
487 debugOut <<
"measurement covariance V: "; V.Print();
492 TVectorD res(measurement - H->
Hv(stateVector));
494 debugOut <<
"Residual = (" << res(0);
495 if (res.GetNrows() > 1)
505 TMatrixDSym covSumInv(cov);
510 TMatrixD CHt(H->
MHt(cov));
511 TVectorD update(TMatrixD(CHt, TMatrixD::kMult, covSumInv) * res);
518 debugOut <<
"Update: "; update.Print();
523 stateVector += update;
524 covSumInv.Similarity(CHt);
530 debugOut <<
"updated state: "; stateVector.Print();
531 debugOut <<
"updated cov: "; cov.Print();
534 TVectorD resNew(measurement - H->
Hv(stateVector));
536 debugOut <<
"Residual New = (" << resNew(0);
538 if (resNew.GetNrows() > 1)
545 TMatrixDSym HCHt(cov);
552 chi2inc += HCHt.Similarity(resNew);
555 ndfInc += weight * measurement.GetNrows();
558 ndfInc += measurement.GetNrows();
561 debugOut <<
"chi² increment = " << chi2inc << std::endl;
573 TDecompChol decompCov(cov);
574 decompCov.Decompose();
575 TMatrixD S(decompCov.GetU());
577 const std::vector<MeasurementOnPlane *>& measurements =
getMeasurements(fi, tp, direction);
578 for (std::vector<MeasurementOnPlane *>::const_iterator it = measurements.begin(); it != measurements.end(); ++it) {
580 const double weight = mOnPlane.
getWeight();
583 debugOut <<
"Weight of measurement: " << weight <<
"\n";
588 debugOut <<
"Weight of measurement is almost 0, continue ... \n";
593 const TVectorD& measurement(mOnPlane.
getState());
597 1./weight * mOnPlane.
getCov() :
601 debugOut <<
"State prediction: "; stateVector.Print();
605 debugOut <<
"measurement: "; measurement.Print();
606 debugOut <<
"measurement covariance V: "; V.Print();
611 TVectorD res(measurement - H->
Hv(stateVector));
613 debugOut <<
"Residual = (" << res(0);
614 if (res.GetNrows() > 1)
620 TDecompChol decompR(V);
622 const TMatrixD& R(decompR.GetU());
624 TVectorD update(stateVector.GetNrows());
627 stateVector += update;
634 debugOut <<
"updated state: "; stateVector.Print();
635 debugOut <<
"updated cov: "; TMatrixDSym(TMatrixDSym::kAtA, S).Print() ;
638 res -= H->
Hv(update);
640 debugOut <<
"Residual New = (" << res(0);
642 if (res.GetNrows() > 1)
653 TMatrixDSym HCHt(TMatrixDSym::kAtA, H->
MHt(S));
659 chi2inc += HCHt.Similarity(res);
662 ndfInc += weight * measurement.GetNrows();
665 ndfInc += measurement.GetNrows();
668 debugOut <<
"chi² increment = " << chi2inc << std::endl;
672 cov = TMatrixDSym(TMatrixDSym::kAtA, S);
688void KalmanFitter::Streamer(TBuffer &R__b)
695 if (R__b.IsReading()) {
696 Version_t R__v = R__b.ReadVersion(&R__s, &R__c);
if (R__v) { }
699 baseClass0::Streamer(R__b);
703 R__b.CheckByteCount(R__s, R__c, thisClass::IsA());
705 R__c = R__b.WriteVersion(thisClass::IsA(), kTRUE);
707 typedef genfit::AbsKalmanFitter baseClass0;
708 baseClass0::Streamer(R__b);
710 R__b.SetByteCount(R__c, kTRUE);
const SharedPlanePtr & getPlane() const
HMatrix for projecting from AbsTrackRep parameters to measured parameters in a DetPlane.
virtual TVectorD Hv(const TVectorD &v) const
H*v.
virtual void HMHt(TMatrixDSym &M) const
similarity: H*M*H^t
virtual TMatrixD MHt(const TMatrixDSym &M) const
M*H^t.
Abstract base class for Kalman fitter and derived fitting algorithms.
double blowUpFactor_
Blow up the covariance of the forward (backward) fit by this factor before seeding the backward (forw...
unsigned int maxIterations_
Maximum number of iterations to attempt. Forward and backward are counted as one iteration.
bool canIgnoreWeights() const
returns if the fitter can ignore the weights and handle the MeasurementOnPlanes as if they had weight...
const std::vector< MeasurementOnPlane * > getMeasurements(const KalmanFitterInfo *fi, const TrackPoint *tp, int direction) const
get the measurementsOnPlane taking the multipleMeasurementHandling_ into account
double blowUpMaxVal_
Limit the cov entries to this maxuimum value when blowing up the cov.
double deltaPval_
Convergence criterion.
bool resetOffDiagonals_
Reset the off-diagonals to 0 when blowing up the cov.
unsigned int minIterations_
Minimum number of iterations to attempt. Forward and backward are counted as one iteration.
eMultipleMeasurementHandling multipleMeasurementHandling_
How to handle if there are multiple MeasurementsOnPlane.
Abstract base class for a track representation.
virtual double extrapolateToPlane(StateOnPlane &state, const genfit::SharedPlanePtr &plane, bool stopAtBoundary=false, bool calcJacobianNoise=false) const =0
Extrapolates the state to plane, and returns the extrapolation length and, via reference,...
virtual double getQop(const StateOnPlane &state) const =0
Get charge over momentum.
virtual void setTime(StateOnPlane &state, double time) const =0
Set time at which the state was defined.
virtual void setPosMomCov(MeasuredStateOnPlane &state, const TVector3 &pos, const TVector3 &mom, const TMatrixDSym &cov6x6) const =0
Set position, momentum and covariance of state.
virtual void setQop(StateOnPlane &state, double qop) const =0
Set charge/momentum.
virtual unsigned int getDim() const =0
Get the dimension of the state vector used by the track representation.
virtual void getPosMomCov(const MeasuredStateOnPlane &state, TVector3 &pos, TVector3 &mom, TMatrixDSym &cov) const =0
Translates MeasuredStateOnPlane into 3D position, momentum and 6x6 covariance.
Exception class for error handling in GENFIT (provides storage for diagnostic information)
void setFatal(bool b=true)
Set fatal flag.
virtual const char * what() const noexcept
Standard error message handling for exceptions. use like "std::cerr << e.what();".
void setIsFitConvergedPartially(bool fitConverged=true)
void setIsFitted(bool fitted=true)
void setNFailedPoints(int nFailedPoints)
bool isTrackPruned() const
Has the track been pruned after the fit?
void setIsFitConvergedFully(bool fitConverged=true)
void setCharge(double charge)
FitStatus for use with AbsKalmanFitter implementations.
void setForwardNdf(double fNdf)
void setBackwardNdf(double bNdf)
void setForwardChi2(double fChi2)
void setBackwardChi2(double bChi2)
void setNumIterations(unsigned int numIterations)
MeasuredStateOnPlane with additional info produced by a Kalman filter or DAF.
Simple Kalman filter implementation.
void processTrackPartially(Track *tr, const AbsTrackRep *rep, int startId=0, int endId=-1)
bool squareRootFormalism_
void processTrackWithRep(Track *tr, const AbsTrackRep *rep, bool resortHits=false) override
Hit resorting currently NOT supported.
std::unique_ptr< MeasuredStateOnPlane > currentState_
bool fitTrack(Track *tr, const AbsTrackRep *rep, double &chi2, double &ndf, int startId, int endId, int &nFailedHits)
void processTrackPoint(TrackPoint *tp, const AbsTrackRep *rep, double &chi2, double &ndf, int direction)
Collects information needed and produced by a AbsKalmanFitter implementations and is specific to one ...
bool hasBackwardUpdate() const override
bool hasPredictionsAndUpdates() const
virtual bool checkConsistency(const genfit::PruneFlags *=nullptr) const override
KalmanFittedStateOnPlane * getUpdate(int direction) const
void setWeights(const std::vector< double > &)
Set weights of measurements.
const MeasuredStateOnPlane & getFittedState(bool biased=true) const override
Get unbiased or biased (default) smoothed state.
void addMeasurementsOnPlane(const std::vector< genfit::MeasurementOnPlane * > &measurementsOnPlane)
std::vector< double > getWeights() const
Get weights of measurements.
void setPrediction(MeasuredStateOnPlane *prediction, int direction)
void deleteBackwardInfo() override
void deleteMeasurementInfo() override
unsigned int getNumMeasurements() const
KalmanFittedStateOnPlane * getBackwardUpdate() const
bool hasUpdate(int direction) const override
MeasuredStateOnPlane * getPrediction(int direction) const
void fixWeights(bool arg=true)
bool areWeightsFixed() const
Are the weights fixed?
void deleteForwardInfo() override
void setUpdate(KalmanFittedStateOnPlane *update, int direction)
StateOnPlane with additional covariance matrix.
const TMatrixDSym & getCov() const
Measured coordinates on a plane.
const AbsHMatrix * getHMatrix() const
const TVectorD & getState() const
const TVectorD & getAuxInfo() const
Collection of TrackPoint objects, AbsTrackRep objects and FitStatus objects.
TrackPoint * getPoint(int id) const
FitStatus * getFitStatus(const AbsTrackRep *rep=nullptr) const
Get FitStatus for a AbsTrackRep. Per default, return FitStatus for cardinalRep.
bool hasFitStatus(const AbsTrackRep *rep=nullptr) const
Check if track has a FitStatus for given AbsTrackRep. Per default, check for cardinal rep.
const TVectorD & getStateSeed() const
double getTimeSeed() const
TrackPoint * getPointWithMeasurement(int id) const
unsigned int getNumPointsWithMeasurement() const
TrackPoint * getPointWithMeasurementAndFitterInfo(int id, const AbsTrackRep *rep=nullptr) const
const TMatrixDSym & getCovSeed() const
AbsTrackRep * getCardinalRep() const
Get cardinal track representation.
void setFitStatus(FitStatus *fitStatus, const AbsTrackRep *rep)
Object containing AbsMeasurement and AbsFitterInfo objects.
bool hasFitterInfo(const AbsTrackRep *rep) const
void deleteFitterInfo(const AbsTrackRep *rep)
bool hasRawMeasurements() const
const std::vector< genfit::AbsMeasurement * > & getRawMeasurements() const
void setFitterInfo(genfit::AbsFitterInfo *fitterInfo)
Takes Ownership.
AbsFitterInfo * getFitterInfo(const AbsTrackRep *rep=nullptr) const
Get fitterInfo for rep. Per default, use cardinal rep.
Defines for I/O streams used for error and debug printing.
@ weightedClosestToReference
@ weightedClosestToReferenceWire
@ unweightedClosestToReference
@ unweightedClosestToReferenceWire
std::shared_ptr< genfit::DetPlane > SharedPlanePtr
Shared Pointer to a DetPlane.