LSST Applications g0b6bd0c080+a72a5dd7e6,g1182afd7b4+2a019aa3bb,g17e5ecfddb+2b8207f7de,g1d67935e3f+06cf436103,g38293774b4+ac198e9f13,g396055baef+6a2097e274,g3b44f30a73+6611e0205b,g480783c3b1+98f8679e14,g48ccf36440+89c08d0516,g4b93dc025c+98f8679e14,g5c4744a4d9+a302e8c7f0,g613e996a0d+e1c447f2e0,g6c8d09e9e7+25247a063c,g7271f0639c+98f8679e14,g7a9cd813b8+124095ede6,g9d27549199+a302e8c7f0,ga1cf026fa3+ac198e9f13,ga32aa97882+7403ac30ac,ga786bb30fb+7a139211af,gaa63f70f4e+9994eb9896,gabf319e997+ade567573c,gba47b54d5d+94dc90c3ea,gbec6a3398f+06cf436103,gc6308e37c7+07dd123edb,gc655b1545f+ade567573c,gcc9029db3c+ab229f5caf,gd01420fc67+06cf436103,gd877ba84e5+06cf436103,gdb4cecd868+6f279b5b48,ge2d134c3d5+cc4dbb2e3f,ge448b5faa6+86d1ceac1d,gecc7e12556+98f8679e14,gf3ee170dca+25247a063c,gf4ac96e456+ade567573c,gf9f5ea5b4d+ac198e9f13,gff490e6085+8c2580be5c,w.2022.27
LSST Data Management Base Package
Public Member Functions | Protected Member Functions | Protected Attributes | List of all members
lsst::jointcal::AstrometryFit Class Reference

Class that handles the astrometric least squares problem. More...

#include <AstrometryFit.h>

Inheritance diagram for lsst::jointcal::AstrometryFit:
lsst::jointcal::FitterBase

Public Member Functions

 AstrometryFit (std::shared_ptr< Associations > associations, std::shared_ptr< AstrometryModel > astrometryModel, double posError)
 this is the only constructor More...
 
 AstrometryFit (AstrometryFit const &)=delete
 No copy or move: there is only ever one fitter of a given type. More...
 
 AstrometryFit (AstrometryFit &&)=delete
 
AstrometryFitoperator= (AstrometryFit const &)=delete
 
AstrometryFitoperator= (AstrometryFit &&)=delete
 
void assignIndices (std::string const &whatToFit) override
 Set parameters to fit and assign indices in the big matrix. More...
 
void freezeErrorTransform ()
 The transformations used to propagate errors are freezed to the current state. More...
 
void offsetParams (Eigen::VectorXd const &delta) override
 Offset the parameters by the requested quantities. More...
 
std::shared_ptr< AstrometryModelgetModel () const
 Return the model being fit. More...
 
void checkStuff ()
 DEBUGGING routine. More...
 
MinimizeResult minimize (std::string const &whatToFit, double nSigmaCut=0, double sigmaRelativeTolerance=0, bool doRankUpdate=true, bool doLineSearch=false, std::string const &dumpMatrixFile="")
 Does a 1 step minimization, assuming a linear model. More...
 
Chi2Statistic computeChi2 () const
 Returns the chi2 for the current state. More...
 
void leastSquareDerivatives (TripletList &tripletList, Eigen::VectorXd &grad) const
 Evaluates the chI^2 derivatives (Jacobian and gradient) for the current whatToFit setting. More...
 
virtual void saveChi2Contributions (std::string const &baseName) const
 Save the full chi2 term per star that was used in the minimization, for debugging. More...
 

Protected Member Functions

void saveChi2MeasContributions (std::string const &filename) const override
 Save a CSV file containing residuals of measurement terms. More...
 
void saveChi2RefContributions (std::string const &filename) const override
 Save a CSV file containing residuals of reference terms. More...
 
std::size_t findOutliers (double nSigmaCut, MeasuredStarList &msOutliers, FittedStarList &fsOutliers, double &cut) const
 Find Measurements and references contributing more than a cut, computed as. More...
 
void outliersContributions (MeasuredStarList &msOutliers, FittedStarList &fsOutliers, TripletList &tripletList, Eigen::VectorXd &grad)
 Contributions to derivatives from (presumably) outlier terms. More...
 
void removeMeasOutliers (MeasuredStarList &outliers)
 Remove measuredStar outliers from the fit. No Refit done. More...
 
void removeRefOutliers (FittedStarList &outliers)
 Remove refStar outliers from the fit. No Refit done. More...
 

Protected Attributes

std::shared_ptr< Associations_associations
 
std::string _whatToFit
 
Eigen::Index _lastNTrip
 
Eigen::Index _nTotal
 
Eigen::Index _nModelParams
 
Eigen::Index _nStarParams
 
LOG_LOGGER _log
 

Detailed Description

Class that handles the astrometric least squares problem.

This is the class that actually computes the quantities required to carry out a LS astrometric fit wrt distortion mappings and coordinates of common objects. Namely it computes the Jacobian and gradient of the chi2 (w.r.t. parameters), and the Chi2 itself. It interfaces with the actual modelling of distortions via a mimimum virtual interface AstrometryModel, and the actual mappings via an other virtual interface : Mapping.

In short AstrometryFit aims at computing derivatives of least quares. The terms of the chi2 are of two kinds:

kind 1 -> (T(X_M) - p(F))^T W (T(X_M) - p(F))

with X_M is a measured (2d) position in CCD coordinates, F refers to the position of the object in some space, defined in practise by p. There is one such term per measurement. The default setup would be that p is the projection from sky to some tangent plane and hence T maps the CCD coordinates onto this TP. p is obtained via the DistorsionModel and can be different for all CcdImage's. Depending on what is beeing fitted, one could imagine cases where the projector p is the same for all CcdImages.

Kind 2 -> (p'(F)-p'(R))^T W_R (p'(F)-p'(R)) R refers to some externally-provided reference object position, and p' to some projector from sky to some plane. The reference objects define the overall coordinate frame, which is required when all T and all F are fitted simultaneously. There is one such term per external reference object. There can be more F (fitted) objects than R (reference) objects.

In the same framework, one can fit relative transforms between images by setting p = Identity for all input CcdImages and not fitting T for one of the CcdImage's. One does not need reference object and would then naturally not have any Kind 2 terms.

Definition at line 78 of file AstrometryFit.h.

Constructor & Destructor Documentation

◆ AstrometryFit() [1/3]

lsst::jointcal::AstrometryFit::AstrometryFit ( std::shared_ptr< Associations associations,
std::shared_ptr< AstrometryModel astrometryModel,
double  posError 
)

this is the only constructor

Definition at line 66 of file AstrometryFit.cc.

68 : FitterBase(std::move(associations)),
69 _astrometryModel(std::move(astrometryModel)),
70 _epoch(_associations->getEpoch()),
71 _posError(posError) {
72 _log = LOG_GET("lsst.jointcal.AstrometryFit");
73}
#define LOG_GET(logger)
Returns a Log object associated with logger.
Definition: Log.h:75
std::shared_ptr< Associations > _associations
Definition: FitterBase.h:165
FitterBase(std::shared_ptr< Associations > associations)
Definition: FitterBase.h:57
T move(T... args)

◆ AstrometryFit() [2/3]

lsst::jointcal::AstrometryFit::AstrometryFit ( AstrometryFit const &  )
delete

No copy or move: there is only ever one fitter of a given type.

◆ AstrometryFit() [3/3]

lsst::jointcal::AstrometryFit::AstrometryFit ( AstrometryFit &&  )
delete

Member Function Documentation

◆ assignIndices()

void lsst::jointcal::AstrometryFit::assignIndices ( std::string const &  whatToFit)
overridevirtual

Set parameters to fit and assign indices in the big matrix.

Parameters
[in]whatToFitValid strings: zero or more of "Distortions", "Positions", "PM" which define which parameter set is going to be variable when computing derivatives (leastSquareDerivatives) and minimizing (minimize()). whatToFit="Positions Distortions" will minimize w.r.t mappings and objects positions, and not w.r.t proper motions and refraction modeling. However if proper motions and/or refraction parameters have already been set, then they are accounted for when computing residuals. The string is forwarded to the AstrometryModel, and it can then be used to turn subsets of distortion parameter on or off, if the AstrometryModel implements such a thing.

Implements lsst::jointcal::FitterBase.

Definition at line 423 of file AstrometryFit.cc.

423 {
424 _whatToFit = whatToFit;
425 LOGLS_INFO(_log, "assignIndices: Now fitting " << whatToFit);
426 _fittingDistortions = (_whatToFit.find("Distortions") != std::string::npos);
427 _fittingPos = (_whatToFit.find("Positions") != std::string::npos);
428 _fittingPM = (_whatToFit.find("PM") != std::string::npos);
429 // When entering here, we assume that whatToFit has already been interpreted.
430
431 _nModelParams = 0;
432 if (_fittingDistortions) _nModelParams = _astrometryModel->assignIndices(_whatToFit, 0);
434
435 if (_fittingPos) {
436 FittedStarList &fittedStarList = _associations->fittedStarList;
437 for (auto &fittedStar : fittedStarList) {
438 // the parameter layout here is used also
439 // - when filling the derivatives
440 // - when updating (offsetParams())
441 // - in GetMeasuredStarIndices
442 fittedStar->setIndexInMatrix(ipar);
443 ipar += 2;
444 // TODO: left as reference for when we implement PM fitting
445 // if ((_fittingPM)&fittedStar->mightMove) ipar += 2;
446 }
447 }
449 _nTotal = ipar;
450 LOGLS_DEBUG(_log, "nParameters total: " << _nTotal << " model: " << _nModelParams
451 << " values: " << _nStarParams);
452}
#define LOGLS_INFO(logger, message)
Log a info-level message using an iostream-based interface.
Definition: Log.h:639
#define LOGLS_DEBUG(logger, message)
Log a debug-level message using an iostream-based interface.
Definition: Log.h:619
Eigen::Index _nModelParams
Definition: FitterBase.h:170
T find(T... args)

◆ checkStuff()

void lsst::jointcal::AstrometryFit::checkStuff ( )

DEBUGGING routine.

Definition at line 480 of file AstrometryFit.cc.

480 {
481 const char *what2fit[] = {"Positions", "Distortions", "Positions Distortions"};
482 // DEBUG
483 for (unsigned k = 0; k < sizeof(what2fit) / sizeof(what2fit[0]); ++k) {
484 assignIndices(what2fit[k]);
485 TripletList tripletList(10000);
486 Eigen::VectorXd grad(_nTotal);
487 grad.setZero();
488 leastSquareDerivatives(tripletList, grad);
489 SparseMatrixD jacobian(_nTotal, tripletList.getNextFreeIndex());
490 jacobian.setFromTriplets(tripletList.begin(), tripletList.end());
491 SparseMatrixD hessian = jacobian * jacobian.transpose();
492 LOGLS_DEBUG(_log, "npar : " << _nTotal << ' ' << _nModelParams);
493 }
494}
Eigen::SparseMatrix< double, 0, Eigen::Index > SparseMatrixD
Definition: Eigenstuff.h:35
void assignIndices(std::string const &whatToFit) override
Set parameters to fit and assign indices in the big matrix.
void leastSquareDerivatives(TripletList &tripletList, Eigen::VectorXd &grad) const
Evaluates the chI^2 derivatives (Jacobian and gradient) for the current whatToFit setting.
Definition: FitterBase.cc:346

◆ computeChi2()

Chi2Statistic lsst::jointcal::FitterBase::computeChi2 ( ) const
inherited

Returns the chi2 for the current state.

Definition at line 42 of file FitterBase.cc.

42 {
43 Chi2Statistic chi2;
44 accumulateStatImageList(_associations->getCcdImageList(), chi2);
46 // chi2.ndof contains the number of squares.
47 // So subtract the number of parameters.
48 chi2.ndof -= _nTotal;
49 return chi2;
50}
virtual void accumulateStatRefStars(Chi2Accumulator &accum) const =0
Compute the chi2 (per star or total, depending on which Chi2Accumulator is used) for RefStars.
virtual void accumulateStatImageList(CcdImageList const &ccdImageList, Chi2Accumulator &accum) const =0
Compute the chi2 (per star or total, depending on which Chi2Accumulator is used) for measurements.

◆ findOutliers()

std::size_t lsst::jointcal::FitterBase::findOutliers ( double  nSigmaCut,
MeasuredStarList msOutliers,
FittedStarList fsOutliers,
double &  cut 
) const
protectedinherited

Find Measurements and references contributing more than a cut, computed as.

\[ <chi2> + nSigmaCut + rms(chi2). \]

The outliers are NOT removed, and no refit is done.

After returning from here, there are still measurements that contribute above the cut, but their contribution should be evaluated after a refit before discarding them.

Parameters
[in]nSigmaCutNumber of sigma to select on.
[out]msOutlierslist of MeasuredStar outliers to populate
[out]fsOutlierslist of FittedStar outliers to populate
[out]cutvalue of chi2 that defines which objects are outliers
Returns
Total number of outliers that were removed.

Definition at line 52 of file FitterBase.cc.

53 {
54 // collect chi2 contributions
55 Chi2List chi2List;
56 chi2List.reserve(_associations->getMaxMeasuredStars() + _associations->refStarList.size());
57 // contributions from measurement terms:
58 accumulateStatImageList(_associations->ccdImageList, chi2List);
59 // and from reference terms
60 accumulateStatRefStars(chi2List);
61
62 // compute some statistics
63 size_t nval = chi2List.size();
64 if (nval == 0) return 0;
65 sort(chi2List.begin(), chi2List.end());
66 double median = (nval & 1) ? chi2List[nval / 2].chi2
67 : 0.5 * (chi2List[nval / 2 - 1].chi2 + chi2List[nval / 2].chi2);
68 auto averageAndSigma = chi2List.computeAverageAndSigma();
69 LOGLS_DEBUG(_log, "findOutliers chi2 stat: mean/median/sigma " << averageAndSigma.first << '/' << median
70 << '/' << averageAndSigma.second);
71 cut = averageAndSigma.first + nSigmaCut * averageAndSigma.second;
72 /* For each of the parameters, we will not remove more than 1
73 measurement that contributes to constraining it. Keep track using
74 of what we are touching using an integer vector. This is the
75 trick that Marc Betoule came up to for outlier removals in "star
76 flats" fits. */
77 Eigen::VectorXi affectedParams(_nTotal);
78 affectedParams.setZero();
79
80 std::size_t nOutliers = 0; // returned to the caller
81 // start from the strongest outliers.
82 for (auto chi2 = chi2List.rbegin(); chi2 != chi2List.rend(); ++chi2) {
83 if (chi2->chi2 < cut) break; // because the array is sorted.
84 IndexVector indices;
85 /* now, we want to get the indices of the parameters this chi2
86 term depends on. We have to figure out which kind of term it
87 is; we use for that the type of the star attached to the Chi2Star. */
88 auto measuredStar = std::dynamic_pointer_cast<MeasuredStar>(chi2->star);
89 std::shared_ptr<FittedStar> fittedStar; // To add to fsOutliers if it is a reference outlier.
90 if (measuredStar == nullptr) {
91 // it is a reference outlier
92 fittedStar = std::dynamic_pointer_cast<FittedStar>(chi2->star);
93 if (fittedStar->getMeasurementCount() == 0) {
94 LOGLS_WARN(_log, "FittedStar with no measuredStars found as an outlier: "
95 << *fittedStar << " chi2: " << chi2->chi2);
96 continue;
97 }
98 if (_nStarParams == 0) {
100 "RefStar is outlier but not removed when not fitting FittedStar-RefStar values: "
101 << *(fittedStar->getRefStar()) << " chi2: " << chi2->chi2);
102 continue;
103 }
104 // NOTE: Stars contribute twice to astrometry (x,y), but once to photometry (flux),
105 // NOTE: but we only need to mark one index here because both will be removed with that star.
106 indices.push_back(fittedStar->getIndexInMatrix());
107 LOGLS_TRACE(_log, "Removing refStar " << *(fittedStar->getRefStar()) << " chi2: " << chi2->chi2);
108 /* One might think it would be useful to account for PM
109 parameters here, but it is just useless */
110 } else {
111 // it is a measurement outlier
112 auto tempFittedStar = measuredStar->getFittedStar();
113 if (tempFittedStar->getMeasurementCount() == 1 && tempFittedStar->getRefStar() == nullptr) {
114 LOGLS_WARN(_log, "FittedStar with 1 measuredStar and no refStar found as an outlier: "
115 << *tempFittedStar);
116 continue;
117 }
118 getIndicesOfMeasuredStar(*measuredStar, indices);
119 LOGLS_TRACE(_log, "Removing measStar " << *measuredStar << " chi2: " << chi2->chi2);
120 }
121
122 /* Find out if we already discarded a stronger outlier
123 constraining some parameter this one constrains as well. If
124 yes, we keep this one, because this stronger outlier could be
125 causing the large chi2 we have in hand. */
126 bool drop_it = true;
127 for (auto const &i : indices) {
128 if (affectedParams(i) != 0) {
129 drop_it = false;
130 }
131 }
132
133 if (drop_it) // store the outlier in one of the lists:
134 {
135 if (measuredStar == nullptr) {
136 // reference term
137 fsOutliers.push_back(fittedStar);
138 } else {
139 // measurement term
140 msOutliers.push_back(measuredStar);
141 }
142 // mark the parameters as directly changed when we discard this chi2 term.
143 for (auto const &i : indices) {
144 affectedParams(i)++;
145 }
146 nOutliers++;
147 }
148 } // end loop on measurements/references
149 LOGLS_DEBUG(_log, "findOutliers: found " << msOutliers.size() << " meas outliers and "
150 << fsOutliers.size() << " ref outliers ");
151
152 return nOutliers;
153}
#define LOGLS_WARN(logger, message)
Log a warn-level message using an iostream-based interface.
Definition: Log.h:659
#define LOGLS_TRACE(logger, message)
Log a trace-level message using an iostream-based interface.
Definition: Log.h:599
virtual void getIndicesOfMeasuredStar(MeasuredStar const &measuredStar, IndexVector &indices) const =0
Set the indices of a measured star from the full matrix, for outlier removal.
T push_back(T... args)
T sort(T... args)

◆ freezeErrorTransform()

void lsst::jointcal::AstrometryFit::freezeErrorTransform ( )
inline

The transformations used to propagate errors are freezed to the current state.

The routine can be called when the mappings are roughly in place. After the call, the transformations used to propage errors are no longer affected when updating the mappings. This allows to have an exactly linear fit, which can be useful.

Definition at line 117 of file AstrometryFit.h.

117{ _astrometryModel->freezeErrorTransform(); }

◆ getModel()

std::shared_ptr< AstrometryModel > lsst::jointcal::AstrometryFit::getModel ( ) const
inline

Return the model being fit.

Definition at line 122 of file AstrometryFit.h.

122{ return _astrometryModel; }

◆ leastSquareDerivatives()

void lsst::jointcal::FitterBase::leastSquareDerivatives ( TripletList tripletList,
Eigen::VectorXd &  grad 
) const
inherited

Evaluates the chI^2 derivatives (Jacobian and gradient) for the current whatToFit setting.

The Jacobian is given as triplets in a sparse matrix, the gradient as a dense vector. The parameters which vary, and their indices, are to be set using assignIndices.

Parameters
tripletListtripletList of (row,col,value) representing the Jacobian of the chi2.
gradThe gradient of the chi2.

Definition at line 346 of file FitterBase.cc.

346 {
347 auto ccdImageList = _associations->getCcdImageList();
348 for (auto const &ccdImage : ccdImageList) {
349 leastSquareDerivativesMeasurement(*ccdImage, tripletList, grad);
350 }
351 leastSquareDerivativesReference(_associations->fittedStarList, tripletList, grad);
352}
virtual void leastSquareDerivativesReference(FittedStarList const &fittedStarList, TripletList &tripletList, Eigen::VectorXd &grad) const =0
Compute the derivatives of the reference terms.
virtual void leastSquareDerivativesMeasurement(CcdImage const &ccdImage, TripletList &tripletList, Eigen::VectorXd &grad, MeasuredStarList const *measuredStarList=nullptr) const =0
Compute the derivatives of the measured stars and model for one CcdImage.

◆ minimize()

MinimizeResult lsst::jointcal::FitterBase::minimize ( std::string const &  whatToFit,
double  nSigmaCut = 0,
double  sigmaRelativeTolerance = 0,
bool  doRankUpdate = true,
bool  doLineSearch = false,
std::string const &  dumpMatrixFile = "" 
)
inherited

Does a 1 step minimization, assuming a linear model.

This is a complete Newton Raphson step. Compute first and second derivatives, solve for the step and apply it, with an optional line search.

It calls assignIndices, leastSquareDerivatives, solves the linear system and calls offsetParams, then removes outliers in a loop if requested. Relies on sparse linear algebra via Eigen's CholmodSupport package.

Parameters
[in]whatToFitSee child method assignIndices for valid string values.
[in]nSigmaCutHow many sigma to reject outliers at. Outlier rejection ignored for nSigmaCut=0.
[in]sigmaRelativeTolerancePercentage change in the chi2 cut for outliers tolerated for termination. If value is zero, minimization iterations will continue until there are no outliers.
[in]doRankUpdateUse CholmodSimplicialLDLT2.update() to do a fast rank update after outlier removal; otherwise do a slower full recomputation of the matrix. Only matters if nSigmaCut != 0.
[in]doLineSearchUse boost's brent_find_minima to perform a line search after the gradient solution is found, and apply the scale factor to the computed offsets. The line search is done in the domain [-1, 2], but if the scale factor is far from 1.0, then the problem is likely in a significantly non-linear regime.
[in]dumpMatrixFileWrite the pre-fit Hessian matrix and gradient to the files with "-mat.txt" and "-grad.txt". Be aware, this requires a large increase in memory usage to create a dense matrix before writing it; the output file may be large. Writing the matrix can be helpful for debugging bad fits. Read it and compute the real eigenvalues (recall that the Hessian is symmetric by construction) with numpy:
hessian = np.matrix(np.loadtxt("dumpMatrixFile-mat.txt"))
values, vectors = np.linalg.eigh(hessian)
Returns
Return code describing success/failure of fit.
Note
When fitting one parameter set by itself (e.g. "Model"), the system is purely linear (assuming there are no cross-terms in the derivatives, e.g. the SimpleAstrometryModel), which should result in the optimal chi2 after a single step. This can be used to debug the fitter by fitting that parameter set twice in a row: the second run with the same "whatToFit" will produce no change in the fitted parameters, if the calculations and indices are defined correctly.

Definition at line 178 of file FitterBase.cc.

180 {
181 assignIndices(whatToFit);
182
184
185 // For the initial vector size, use all measured stars + all fitted stars, which should give the
186 // maximum possible number of triplets.
187 std::size_t nTrip = (_lastNTrip)
188 ? _lastNTrip
189 : _associations->getMaxMeasuredStars() + _associations->fittedStarList.size();
190 TripletList tripletList(nTrip);
191 Eigen::VectorXd grad(_nTotal);
192 grad.setZero();
193 double scale = 1.0;
194
195 // Fill the triplets
196 leastSquareDerivatives(tripletList, grad);
197 _lastNTrip = tripletList.size();
198
199 LOGLS_DEBUG(_log, "End of triplet filling, ntrip = " << tripletList.size());
200
201 SparseMatrixD hessian = createHessian(_nTotal, tripletList);
202 tripletList.clear(); // we don't need it any more after we have the hessian.
203
204 LOGLS_DEBUG(_log, "Starting factorization, hessian: dim="
205 << hessian.rows() << " non-zeros=" << hessian.nonZeros()
206 << " filling-frac = " << hessian.nonZeros() / std::pow(hessian.rows(), 2));
207
208 if (dumpMatrixFile != "") {
209 if (hessian.rows() * hessian.cols() > 2e8) {
210 LOGLS_WARN(_log, "Hessian matrix is too big to dump to file, with rows, columns: "
211 << hessian.rows() << ", " << hessian.cols());
212 } else {
213 dumpMatrixAndGradient(hessian, grad, dumpMatrixFile, _log);
214 }
215 }
216
218 if (chol.info() != Eigen::Success) {
219 LOGLS_ERROR(_log, "minimize: factorization failed ");
221 }
222
223 std::size_t totalMeasOutliers = 0;
224 std::size_t totalRefOutliers = 0;
225 double oldChi2 = computeChi2().chi2;
226 double oldSigmaCut = 0.;
227 double sigmaCut = 0.;
228
229 while (true) {
230 Eigen::VectorXd delta = chol.solve(grad);
231 if (doLineSearch) {
232 scale = _lineSearch(delta);
233 }
234 offsetParams(scale * delta);
235 Chi2Statistic currentChi2(computeChi2());
236 LOGLS_DEBUG(_log, currentChi2);
237 if (!isfinite(currentChi2.chi2)) {
238 LOGL_ERROR(_log, "chi2 is not finite. Aborting outlier rejection.");
239 returnCode = MinimizeResult::NonFinite;
240 break;
241 }
242 if (currentChi2.chi2 > oldChi2 && totalMeasOutliers + totalRefOutliers != 0) {
243 LOGL_WARN(_log, "chi2 went up, skipping outlier rejection loop");
245 break;
246 }
247 oldChi2 = currentChi2.chi2;
248
249 if (nSigmaCut == 0) break; // no rejection step to perform
250 MeasuredStarList msOutliers;
251 FittedStarList fsOutliers;
252 // keep nOutliers so we don't have to sum msOutliers.size()+fsOutliers.size() twice below.
253 std::size_t nOutliers = findOutliers(nSigmaCut, msOutliers, fsOutliers, sigmaCut);
254 double relChange = 0.;
255 if(oldSigmaCut!=0.) relChange = (1 - sigmaCut / oldSigmaCut);
256
257 LOGLS_DEBUG(_log, "findOutliers chi2 cut level: " << sigmaCut << ", relative change: " << relChange);
258 // If sigmaRelativeTolerance is set and at least one iteration has been done, break loop when the
259 // fractional change in sigmaCut levels is less than the sigmaRelativeTolerance parameter.
260 if ((sigmaRelativeTolerance > 0) && (oldSigmaCut > 0 && relChange < sigmaRelativeTolerance)) {
261 LOGLS_INFO(_log, "Iterations stopped with chi2 cut at " << sigmaCut << " and relative change of "
262 << relChange);
263 break;
264 }
265 totalMeasOutliers += msOutliers.size();
266 totalRefOutliers += fsOutliers.size();
267 oldSigmaCut = sigmaCut;
268 if (nOutliers == 0) break;
269 TripletList outlierTriplets(nOutliers);
270 grad.setZero(); // recycle the gradient
271 // compute the contributions of outliers to derivatives
272 outliersContributions(msOutliers, fsOutliers, outlierTriplets, grad);
273 // Remove significant outliers
274 removeMeasOutliers(msOutliers);
275 removeRefOutliers(fsOutliers);
276 if (doRankUpdate) {
277 // convert triplet list to eigen internal format
278 SparseMatrixD H(_nTotal, outlierTriplets.getNextFreeIndex());
279 H.setFromTriplets(outlierTriplets.begin(), outlierTriplets.end());
280 chol.update(H, false /* means downdate */);
281 // The contribution of outliers to the gradient is the opposite
282 // of the contribution of all other terms, because they add up to 0
283 grad *= -1;
284 } else {
285 // don't reuse tripletList because we want a new nextFreeIndex.
286 TripletList nextTripletList(_lastNTrip);
287 grad.setZero();
288 // Rebuild the matrix and gradient
289 leastSquareDerivatives(nextTripletList, grad);
290 _lastNTrip = nextTripletList.size();
291 LOGLS_DEBUG(_log, "Triplets recomputed, ntrip = " << nextTripletList.size());
292
293 hessian = createHessian(_nTotal, nextTripletList);
294 nextTripletList.clear(); // we don't need it any more after we have the hessian.
295
297 "Restarting factorization, hessian: dim="
298 << hessian.rows() << " non-zeros=" << hessian.nonZeros()
299 << " filling-frac = " << hessian.nonZeros() / std::pow(hessian.rows(), 2));
300 chol.compute(hessian);
301 if (chol.info() != Eigen::Success) {
302 LOGLS_ERROR(_log, "minimize: factorization failed ");
304 }
305 }
306 }
307
308 if (totalMeasOutliers + totalRefOutliers > 0) {
309 _associations->cleanFittedStars();
310 }
311
312 // only print the outlier summary if outlier rejection was turned on.
313 if (nSigmaCut != 0) {
314 LOGLS_INFO(_log, "Number of outliers (Measured + Reference = Total): "
315 << totalMeasOutliers << " + " << totalRefOutliers << " = "
316 << totalMeasOutliers + totalRefOutliers);
317 }
318 return returnCode;
319}
#define LOGL_WARN(logger, message...)
Log a warn-level message using a varargs/printf style interface.
Definition: Log.h:547
#define LOGLS_ERROR(logger, message)
Log a error-level message using an iostream-based interface.
Definition: Log.h:679
#define LOGL_ERROR(logger, message...)
Log a error-level message using a varargs/printf style interface.
Definition: Log.h:563
void removeRefOutliers(FittedStarList &outliers)
Remove refStar outliers from the fit. No Refit done.
Definition: FitterBase.cc:340
Chi2Statistic computeChi2() const
Returns the chi2 for the current state.
Definition: FitterBase.cc:42
virtual void assignIndices(std::string const &whatToFit)=0
Set parameters to fit and assign indices in the big matrix.
virtual void offsetParams(Eigen::VectorXd const &delta)=0
Offset the parameters by the requested quantities.
void outliersContributions(MeasuredStarList &msOutliers, FittedStarList &fsOutliers, TripletList &tripletList, Eigen::VectorXd &grad)
Contributions to derivatives from (presumably) outlier terms.
Definition: FitterBase.cc:321
std::size_t findOutliers(double nSigmaCut, MeasuredStarList &msOutliers, FittedStarList &fsOutliers, double &cut) const
Find Measurements and references contributing more than a cut, computed as.
Definition: FitterBase.cc:52
void removeMeasOutliers(MeasuredStarList &outliers)
Remove measuredStar outliers from the fit. No Refit done.
Definition: FitterBase.cc:332
T isfinite(T... args)
def scale(algorithm, min, max=None, frame=None)
Definition: ds9.py:108
MinimizeResult
Return value of minimize()
Definition: FitterBase.h:42
T pow(T... args)

◆ offsetParams()

void lsst::jointcal::AstrometryFit::offsetParams ( Eigen::VectorXd const &  delta)
overridevirtual

Offset the parameters by the requested quantities.

The used parameter layout is the one from the last call to assignIndices or minimize(). There is no easy way to check that the current setting of whatToFit and the provided Delta vector are compatible: we can only test the size.

Parameters
[in]deltavector of offsets to apply

Implements lsst::jointcal::FitterBase.

Definition at line 454 of file AstrometryFit.cc.

454 {
455 if (delta.size() != _nTotal)
456 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
457 "AstrometryFit::offsetParams : the provided vector length is not compatible with "
458 "the current whatToFit setting");
459 if (_fittingDistortions) _astrometryModel->offsetParams(delta);
460
461 if (_fittingPos) {
462 FittedStarList &fittedStarList = _associations->fittedStarList;
463 for (auto const &i : fittedStarList) {
464 FittedStar &fs = *i;
465 // the parameter layout here is used also
466 // - when filling the derivatives
467 // - when assigning indices (assignIndices())
468 Eigen::Index index = fs.getIndexInMatrix();
469 fs.x += delta(index);
470 fs.y += delta(index + 1);
471 // TODO: left as reference for when we implement PM fitting
472 // if ((_fittingPM)&fs.mightMove) {
473 // fs.pmx += delta(index + 2);
474 // fs.pmy += delta(index + 3);
475 // }
476 }
477 }
478}
#define LSST_EXCEPT(type,...)
Create an exception with a given type.
Definition: Exception.h:48

◆ operator=() [1/2]

AstrometryFit & lsst::jointcal::AstrometryFit::operator= ( AstrometryFit &&  )
delete

◆ operator=() [2/2]

AstrometryFit & lsst::jointcal::AstrometryFit::operator= ( AstrometryFit const &  )
delete

◆ outliersContributions()

void lsst::jointcal::FitterBase::outliersContributions ( MeasuredStarList msOutliers,
FittedStarList fsOutliers,
TripletList tripletList,
Eigen::VectorXd &  grad 
)
protectedinherited

Contributions to derivatives from (presumably) outlier terms.

No discarding done.

Definition at line 321 of file FitterBase.cc.

322 {
323 for (auto &outlier : msOutliers) {
324 MeasuredStarList tmp;
325 tmp.push_back(outlier);
326 const CcdImage &ccdImage = outlier->getCcdImage();
327 leastSquareDerivativesMeasurement(ccdImage, tripletList, grad, &tmp);
328 }
329 leastSquareDerivativesReference(fsOutliers, tripletList, grad);
330}

◆ removeMeasOutliers()

void lsst::jointcal::FitterBase::removeMeasOutliers ( MeasuredStarList outliers)
protectedinherited

Remove measuredStar outliers from the fit. No Refit done.

Definition at line 332 of file FitterBase.cc.

332 {
333 for (auto &measuredStar : outliers) {
334 auto fittedStar = measuredStar->getFittedStar();
335 measuredStar->setValid(false);
336 fittedStar->getMeasurementCount()--; // could be put in setValid
337 }
338}

◆ removeRefOutliers()

void lsst::jointcal::FitterBase::removeRefOutliers ( FittedStarList outliers)
protectedinherited

Remove refStar outliers from the fit. No Refit done.

Definition at line 340 of file FitterBase.cc.

340 {
341 for (auto &fittedStar : outliers) {
342 fittedStar->setRefStar(nullptr);
343 }
344}

◆ saveChi2Contributions()

void lsst::jointcal::FitterBase::saveChi2Contributions ( std::string const &  baseName) const
virtualinherited

Save the full chi2 term per star that was used in the minimization, for debugging.

Saves results to text files "baseName-meas.csv" and "baseName-ref.csv" for the MeasuredStar and RefStar contributions, respectively. This method is mostly useful for debugging: we will probably want to create a better persistence system for jointcal's internal representations in the future (see DM-12446).

Definition at line 354 of file FitterBase.cc.

354 {
355 std::string replaceStr = "{type}";
356 auto pos = baseName.find(replaceStr);
357 std::string measFilename(baseName);
358 measFilename.replace(pos, replaceStr.size(), "-meas.csv");
359 std::string refFilename(baseName);
360 refFilename.replace(pos, replaceStr.size(), "-ref.csv");
361 saveChi2MeasContributions(measFilename);
362 saveChi2RefContributions(refFilename);
363}
virtual void saveChi2MeasContributions(std::string const &filename) const =0
Save a CSV file containing residuals of measurement terms.
virtual void saveChi2RefContributions(std::string const &filename) const =0
Save a CSV file containing residuals of reference terms.
T size(T... args)

◆ saveChi2MeasContributions()

void lsst::jointcal::AstrometryFit::saveChi2MeasContributions ( std::string const &  filename) const
overrideprotectedvirtual

Save a CSV file containing residuals of measurement terms.

Implements lsst::jointcal::FitterBase.

Definition at line 496 of file AstrometryFit.cc.

496 {
497 std::ofstream ofile(filename.c_str());
498 std::string separator = "\t";
499
500 ofile << "id" << separator << "xccd" << separator << "yccd " << separator;
501 ofile << "rx" << separator << "ry" << separator;
502 ofile << "xtp" << separator << "ytp" << separator;
503 ofile << "mag" << separator << "deltaYears" << separator;
504 ofile << "xErr" << separator << "yErr" << separator << "xyCov" << separator;
505 ofile << "xtpi" << separator << "ytpi" << separator;
506 ofile << "rxi" << separator << "ryi" << separator;
507 ofile << "fsindex" << separator;
508 ofile << "ra" << separator << "dec" << separator;
509 ofile << "chi2" << separator << "nm" << separator;
510 ofile << "detector" << separator << "visit" << std::endl;
511
512 ofile << "id in source catalog" << separator << "coordinates in CCD (pixels)" << separator << separator;
513 ofile << "residual on TP (degrees)" << separator << separator;
514 ofile << "transformed coordinate in TP (degrees)" << separator << separator;
515 ofile << "rough magnitude" << separator << "Julian epoch year delta from fit epoch" << separator;
516 ofile << "transformed measurement uncertainty (degrees)" << separator << separator << separator;
517 ofile << "as-read position on TP (degrees)" << separator << separator;
518 ofile << "as-read residual on TP (degrees)" << separator << separator;
519 ofile << "unique index of the fittedStar" << separator;
520 ofile << "on sky position of fittedStar" << separator << separator;
521 ofile << "contribution to chi2 (2D dofs)" << separator << "number of measurements of this fittedStar"
522 << separator;
523 ofile << "detector id" << separator << "visit id" << std::endl;
524
525 const CcdImageList &ccdImageList = _associations->getCcdImageList();
526 for (auto const &ccdImage : ccdImageList) {
527 const MeasuredStarList &cat = ccdImage->getCatalogForFit();
528 const AstrometryMapping *mapping = _astrometryModel->getMapping(*ccdImage);
529 const auto readTransform = ccdImage->getReadWcs();
530 // FittedStar is "observed" epoch, MeasuredStar is "baseline"
531 double deltaYears = _epoch - ccdImage->getEpoch();
532 for (auto const &ms : cat) {
533 if (!ms->isValid()) continue;
534 FatPoint tpPos;
535 FatPoint inPos = *ms;
536 tweakAstromMeasurementErrors(inPos, *ms, _posError);
537 mapping->transformPosAndErrors(inPos, tpPos);
538 auto sky2TP = _astrometryModel->getSkyToTangentPlane(*ccdImage);
539 const std::unique_ptr<AstrometryTransform> readPixToTangentPlane =
540 compose(*sky2TP, *readTransform);
541 FatPoint inputTpPos = readPixToTangentPlane->apply(inPos);
542 std::shared_ptr<FittedStar const> const fs = ms->getFittedStar();
543
544 Point fittedStarInTP = transformFittedStar(*fs, *sky2TP, deltaYears);
545 Point res = tpPos - fittedStarInTP;
546 Point inputRes = inputTpPos - fittedStarInTP;
547 double det = tpPos.vx * tpPos.vy - std::pow(tpPos.vxy, 2);
548 double wxx = tpPos.vy / det;
549 double wyy = tpPos.vx / det;
550 double wxy = -tpPos.vxy / det;
551 double chi2 = wxx * res.x * res.x + wyy * res.y * res.y + 2 * wxy * res.x * res.y;
552
553 ofile << std::setprecision(9);
554 ofile << ms->getId() << separator << ms->x << separator << ms->y << separator;
555 ofile << res.x << separator << res.y << separator;
556 ofile << tpPos.x << separator << tpPos.y << separator;
557 ofile << fs->getMag() << separator << deltaYears << separator;
558 ofile << tpPos.vx << separator << tpPos.vy << separator << tpPos.vxy << separator;
559 ofile << inputTpPos.x << separator << inputTpPos.y << separator;
560 ofile << inputRes.x << separator << inputRes.y << separator;
561 ofile << fs->getIndexInMatrix() << separator;
562 ofile << fs->x << separator << fs->y << separator;
563 ofile << chi2 << separator << fs->getMeasurementCount() << separator;
564 ofile << ccdImage->getCcdId() << separator << ccdImage->getVisit() << std::endl;
565 } // loop on measurements in image
566 } // loop on images
567}
T endl(T... args)
std::unique_ptr< AstrometryTransform > compose(AstrometryTransform const &left, AstrometryTransform const &right)
Returns a pointer to a composition of transforms, representing left(right()).
std::list< std::shared_ptr< CcdImage > > CcdImageList
Definition: CcdImage.h:46
T setprecision(T... args)

◆ saveChi2RefContributions()

void lsst::jointcal::AstrometryFit::saveChi2RefContributions ( std::string const &  filename) const
overrideprotectedvirtual

Save a CSV file containing residuals of reference terms.

Implements lsst::jointcal::FitterBase.

Definition at line 569 of file AstrometryFit.cc.

569 {
570 std::ofstream ofile(filename.c_str());
571 std::string separator = "\t";
572
573 ofile << "ra" << separator << "dec " << separator;
574 ofile << "rx" << separator << "ry" << separator;
575 ofile << "mag" << separator;
576 ofile << "xErr" << separator << "yErr" << separator << "xyCov" << separator;
577 ofile << "fsindex" << separator;
578 ofile << "chi2" << separator << "nm" << std::endl;
579
580 ofile << "coordinates of fittedStar (degrees)" << separator << separator;
581 ofile << "residual on TP (degrees)" << separator << separator;
582 ofile << "magnitude" << separator;
583 ofile << "refStar transformed measurement uncertainty (degrees)" << separator << separator << separator;
584 ofile << "unique index of the fittedStar" << separator;
585 ofile << "refStar contribution to chi2 (2D dofs)" << separator
586 << "number of measurements of this FittedStar" << std::endl;
587
588 // The following loop is heavily inspired from AstrometryFit::computeChi2()
589 const FittedStarList &fittedStarList = _associations->fittedStarList;
590 TanRaDecToPixel proj(AstrometryTransformLinear(), Point(0., 0.));
591 for (auto const &i : fittedStarList) {
592 const FittedStar &fs = *i;
593 auto rs = fs.getRefStar();
594 if (rs == nullptr) continue;
595 proj.setTangentPoint(fs);
596 // fs projects to (0,0), no need to compute its transform.
597 FatPoint rsProj;
598 proj.transformPosAndErrors(*rs, rsProj);
599 double chi2 = computeProjectedRefStarChi2(rsProj);
600
601 ofile << std::setprecision(9);
602 ofile << fs.x << separator << fs.y << separator;
603 ofile << rsProj.x << separator << rsProj.y << separator;
604 ofile << fs.getMag() << separator;
605 ofile << rsProj.vx << separator << rsProj.vy << separator << rsProj.vxy << separator;
606 ofile << fs.getIndexInMatrix() << separator;
607 ofile << chi2 << separator << fs.getMeasurementCount() << std::endl;
608 } // loop on FittedStars
609}

Member Data Documentation

◆ _associations

std::shared_ptr<Associations> lsst::jointcal::FitterBase::_associations
protectedinherited

Definition at line 165 of file FitterBase.h.

◆ _lastNTrip

Eigen::Index lsst::jointcal::FitterBase::_lastNTrip
protectedinherited

Definition at line 168 of file FitterBase.h.

◆ _log

LOG_LOGGER lsst::jointcal::FitterBase::_log
protectedinherited

Definition at line 174 of file FitterBase.h.

◆ _nModelParams

Eigen::Index lsst::jointcal::FitterBase::_nModelParams
protectedinherited

Definition at line 170 of file FitterBase.h.

◆ _nStarParams

Eigen::Index lsst::jointcal::FitterBase::_nStarParams
protectedinherited

Definition at line 171 of file FitterBase.h.

◆ _nTotal

Eigen::Index lsst::jointcal::FitterBase::_nTotal
protectedinherited

Definition at line 169 of file FitterBase.h.

◆ _whatToFit

std::string lsst::jointcal::FitterBase::_whatToFit
protectedinherited

Definition at line 166 of file FitterBase.h.


The documentation for this class was generated from the following files: