LSSTApplications  18.1.0
LSSTDataManagementBasePackage
ConstrainedPhotometryModel.cc
Go to the documentation of this file.
1 // -*- LSST-C++ -*-
2 /*
3  * This file is part of jointcal.
4  *
5  * Developed for the LSST Data Management System.
6  * This product includes software developed by the LSST Project
7  * (https://www.lsst.org).
8  * See the COPYRIGHT file at the top-level directory of this distribution
9  * for details of code ownership.
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program. If not, see <https://www.gnu.org/licenses/>.
23  */
24 
25 #include <map>
26 #include <limits>
27 #include <vector>
28 #include <string>
29 
30 #include "lsst/log/Log.h"
31 
32 #include "astshim.h"
33 #include "astshim/ChebyMap.h"
37 #include "lsst/jointcal/CcdImage.h"
40 
41 namespace lsst {
42 namespace jointcal {
43 
45  std::string const &whatToFit,
46  Eigen::Index firstIndex
47 ) {
48  Eigen::Index index = firstIndex;
49  if (whatToFit.find("Model") == std::string::npos) {
50  LOGLS_WARN(_log, "assignIndices was called and Model is *not* in whatToFit");
51  return index;
52  }
53 
54  // If we got here, "Model" is definitely in whatToFit.
55  _fittingChips = (whatToFit.find("ModelChip") != std::string::npos);
56  _fittingVisits = (whatToFit.find("ModelVisit") != std::string::npos);
57  // If nothing more than "Model" is specified, it means fit everything.
58  if ((!_fittingChips) && (!_fittingVisits)) {
59  _fittingChips = _fittingVisits = true;
60  }
61 
62  if (_fittingChips) {
63  for (auto &idMapping : _chipMap) {
64  auto mapping = idMapping.second.get();
65  // Don't assign indices for fixed parameters.
66  if (mapping->isFixed()) continue;
67  mapping->setIndex(index);
68  index += mapping->getNpar();
69  }
70  }
71  if (_fittingVisits) {
72  for (auto &idMapping : _visitMap) {
73  auto mapping = idMapping.second.get();
74  mapping->setIndex(index);
75  index += mapping->getNpar();
76  }
77  }
78  for (auto &idMapping : _chipVisitMap) {
79  idMapping.second->setWhatToFit(_fittingChips, _fittingVisits);
80  }
81  return index;
82 }
83 
84 void ConstrainedPhotometryModel::offsetParams(Eigen::VectorXd const &delta) {
85  if (_fittingChips) {
86  for (auto &idMapping : _chipMap) {
87  auto mapping = idMapping.second.get();
88  // Don't offset indices for fixed parameters.
89  if (mapping->isFixed()) continue;
90  mapping->offsetParams(delta.segment(mapping->getIndex(), mapping->getNpar()));
91  }
92  }
93  if (_fittingVisits) {
94  for (auto &idMapping : _visitMap) {
95  auto mapping = idMapping.second.get();
96  mapping->offsetParams(delta.segment(mapping->getIndex(), mapping->getNpar()));
97  }
98  }
99 }
100 
102  for (auto &idMapping : _chipMap) {
103  idMapping.second.get()->freezeErrorTransform();
104  }
105  for (auto &idMapping : _visitMap) {
106  idMapping.second.get()->freezeErrorTransform();
107  }
108 }
109 
111  IndexVector &indices) const {
112  auto mapping = findMapping(ccdImage);
113  mapping->getMappingIndices(indices);
114 }
115 
117  std::size_t total = 0;
118  for (auto &idMapping : _chipMap) {
119  total += idMapping.second->getNpar();
120  }
121  for (auto &idMapping : _visitMap) {
122  total += idMapping.second->getNpar();
123  }
124  return total;
125 }
126 
128  CcdImage const &ccdImage,
129  Eigen::VectorXd &derivatives) const {
130  auto mapping = findMapping(ccdImage);
131  mapping->computeParameterDerivatives(measuredStar, measuredStar.getInstFlux(), derivatives);
132 }
133 
134 namespace {
135 // Convert photoTransform's way of storing Chebyshev coefficients into the format wanted by ChebyMap.
136 ndarray::Array<double, 2, 2> toChebyMapCoeffs(std::shared_ptr<PhotometryTransformChebyshev> transform) {
137  auto coeffs = transform->getCoefficients();
138  // 4 x nPar: ChebyMap wants rows that look like (a_ij, 1, i, j) for out += a_ij*T_i(x)*T_j(y)
139  ndarray::Array<double, 2, 2> chebyCoeffs = allocate(ndarray::makeVector(transform->getNpar(),
140  std::size_t(4)));
141  Eigen::VectorXd::Index k = 0;
142  auto order = transform->getOrder();
143  for (ndarray::Size j = 0; j <= order; ++j) {
144  ndarray::Size const iMax = order - j; // to save re-computing `i+j <= order` every inner step.
145  for (ndarray::Size i = 0; i <= iMax; ++i, ++k) {
146  chebyCoeffs[k][0] = coeffs[j][i];
147  chebyCoeffs[k][1] = 1;
148  chebyCoeffs[k][2] = i;
149  chebyCoeffs[k][3] = j;
150  }
151  }
152  return chebyCoeffs;
153 }
154 } // namespace
155 
157  for (auto &idMapping : _chipMap) {
158  idMapping.second->dump(stream);
159  stream << std::endl;
160  }
161  stream << std::endl;
162  for (auto &idMapping : _visitMap) {
163  idMapping.second->dump(stream);
164  stream << std::endl;
165  }
166 }
167 
169  auto idMapping = _chipVisitMap.find(ccdImage.getHashKey());
170  if (idMapping == _chipVisitMap.end())
172  "ConstrainedPhotometryModel cannot find CcdImage " + ccdImage.getName());
173  return idMapping->second.get();
174 }
175 
176 template <class ChipTransform, class VisitTransform, class ChipVisitMapping>
178  afw::geom::Box2D const &focalPlaneBBox, int visitOrder) {
179  // keep track of which chip we want to constrain (the one closest to the middle of the focal plane)
180  double minRadius2 = std::numeric_limits<double>::infinity();
181  CcdIdType constrainedChip = -1;
182 
183  // First initialize all visit and ccd transforms, before we make the ccdImage mappings.
184  for (auto const &ccdImage : ccdImageList) {
185  auto visit = ccdImage->getVisit();
186  auto chip = ccdImage->getCcdId();
187  auto visitPair = _visitMap.find(visit);
188  auto chipPair = _chipMap.find(chip);
189 
190  // If the chip is not in the map, add it, otherwise continue.
191  if (chipPair == _chipMap.end()) {
192  auto center = ccdImage->getDetector()->getCenter(afw::cameraGeom::FOCAL_PLANE);
193  double radius2 = std::pow(center.getX(), 2) + std::pow(center.getY(), 2);
194  if (radius2 < minRadius2) {
195  minRadius2 = radius2;
196  constrainedChip = chip;
197  }
198  auto photoCalib = ccdImage->getPhotoCalib();
199  // Use the single-frame processing calibration from the PhotoCalib as the default.
200  auto chipTransform = std::make_unique<ChipTransform>(initialChipCalibration(photoCalib));
201  _chipMap[chip] = std::make_shared<PhotometryMapping>(std::move(chipTransform));
202  }
203  // If the visit is not in the map, add it, otherwise continue.
204  if (visitPair == _visitMap.end()) {
205  auto visitTransform = std::make_unique<VisitTransform>(visitOrder, focalPlaneBBox);
206  _visitMap[visit] = std::make_shared<PhotometryMapping>(std::move(visitTransform));
207  }
208  }
209 
210  // Fix one chip mapping, to remove the degeneracy from the system.
211  _chipMap.at(constrainedChip)->setFixed(true);
212 
213  // Now create the ccdImage mappings, which are combinations of the chip/visit mappings above.
214  for (auto const &ccdImage : ccdImageList) {
215  auto visit = ccdImage->getVisit();
216  auto chip = ccdImage->getCcdId();
217  _chipVisitMap.emplace(ccdImage->getHashKey(),
218  std::make_unique<ChipVisitMapping>(_chipMap[chip], _visitMap[visit]));
219  }
220  LOGLS_INFO(_log, "Got " << _chipMap.size() << " chip mappings and " << _visitMap.size()
221  << " visit mappings; holding chip " << constrainedChip << " fixed ("
222  << getTotalParameters() << " total parameters).");
223  LOGLS_DEBUG(_log, "CcdImage map has " << _chipVisitMap.size() << " mappings, with "
224  << _chipVisitMap.bucket_count() << " buckets and a load factor of "
226 }
227 
229  CcdImage const &ccdImage) const {
230  auto detector = ccdImage.getDetector();
231  auto ccdBBox = detector->getBBox();
233 
234  // There should be no way in which we can get to this point and not have a ChipVisitMapping,
235  // so blow up if we don't.
236  assert(mapping != nullptr);
237  // We know it's a Chebyshev transform because we created it as such, so blow up if it's not.
238  auto visitPhotometryTransform = std::dynamic_pointer_cast<PhotometryTransformChebyshev>(
239  mapping->getVisitMapping()->getTransform());
240  assert(visitPhotometryTransform != nullptr);
241  auto focalBBox = visitPhotometryTransform->getBBox();
242 
243  // Unravel our chebyshev coefficients to build an astshim::ChebyMap.
244  auto coeff_f = toChebyMapCoeffs(std::dynamic_pointer_cast<PhotometryTransformChebyshev>(
245  mapping->getVisitMapping()->getTransform()));
246  // Bounds are the bbox
247  std::vector<double> lowerBound = {focalBBox.getMinX(), focalBBox.getMinY()};
248  std::vector<double> upperBound = {focalBBox.getMaxX(), focalBBox.getMaxY()};
249  afw::geom::TransformPoint2ToGeneric visitTransform(ast::ChebyMap(coeff_f, 1, lowerBound, upperBound));
250 
251  double chipConstant = mapping->getChipMapping()->getParameters()[0];
252 
253  // Compute a box that covers the area of the ccd in focal plane coordinates.
254  // This is the box over which we want to compute the mean of the visit transform.
255  auto pixToFocal = detector->getTransform(afw::cameraGeom::PIXELS, afw::cameraGeom::FOCAL_PLANE);
256  geom::Box2D ccdBBoxInFocal;
257  for (auto const &point : pixToFocal->applyForward(geom::Box2D(ccdBBox).getCorners())) {
258  ccdBBoxInFocal.include(point);
259  }
260  double visitMean = visitPhotometryTransform->mean(ccdBBoxInFocal);
261 
262  return {chipConstant, visitTransform, pixToFocal, visitMean};
263 }
264 
265 // ConstrainedFluxModel methods
266 
268  MeasuredStar const &measuredStar) const {
269  return transform(ccdImage, measuredStar) - measuredStar.getFittedStar()->getFlux();
270 }
271 
272 double ConstrainedFluxModel::transform(CcdImage const &ccdImage, MeasuredStar const &measuredStar) const {
273  auto mapping = findMapping(ccdImage);
274  return mapping->transform(measuredStar, measuredStar.getInstFlux());
275 }
276 
278  MeasuredStar const &measuredStar) const {
279  auto mapping = findMapping(ccdImage);
280  double tempErr = tweakFluxError(measuredStar);
281  return mapping->transformError(measuredStar, measuredStar.getInstFlux(), tempErr);
282 }
283 
285  auto ccdBBox = ccdImage.getDetector()->getBBox();
286  auto prep = prepPhotoCalib(ccdImage);
287 
288  // The chip part is easy: zoom map with the single value as the "zoom" factor
290  ast::ZoomMap(1, prep.chipConstant));
291 
292  // Now stitch them all together.
293  auto transform = prep.pixToFocal->then(prep.visitTransform)->then(zoomTransform);
294 
295  // NOTE: TransformBoundedField does not implement mean(), so we have to compute it here.
296  double mean = prep.chipConstant * prep.visitMean;
297 
298  auto boundedField = std::make_shared<afw::math::TransformBoundedField>(ccdBBox, *transform);
299  return std::make_shared<afw::image::PhotoCalib>(mean, ccdImage.getPhotoCalib()->getCalibrationErr(),
300  boundedField, false);
301 }
302 
303 // ConstrainedMagnitudeModel methods
304 
306  MeasuredStar const &measuredStar) const {
307  return transform(ccdImage, measuredStar) - measuredStar.getFittedStar()->getMag();
308 }
309 
311  MeasuredStar const &measuredStar) const {
312  auto mapping = findMapping(ccdImage);
313  return mapping->transform(measuredStar, measuredStar.getInstMag());
314 }
315 
317  MeasuredStar const &measuredStar) const {
318  auto mapping = findMapping(ccdImage);
319  double tempErr = tweakFluxError(measuredStar);
320  return mapping->transformError(measuredStar, measuredStar.getInstFlux(), tempErr);
321 }
322 
324  CcdImage const &ccdImage) const {
325  auto ccdBBox = ccdImage.getDetector()->getBBox();
326  auto prep = prepPhotoCalib(ccdImage);
327 
328  using namespace std::string_literals; // for operator""s to convert string literal->std::string
330  ast::MathMap(1, 1, {"y=pow(10.0,x/-2.5)"s}, {"x=-2.5*log10(y)"s}));
331 
332  // The chip part is easy: zoom map with the value (converted to a flux) as the "zoom" factor.
333  double chipCalibration = utils::ABMagnitudeToNanojansky(prep.chipConstant);
335  ast::ZoomMap(1, chipCalibration));
336 
337  // Now stitch them all together.
338  auto transform = prep.pixToFocal->then(prep.visitTransform)->then(logTransform)->then(zoomTransform);
339 
340  // NOTE: TransformBoundedField does not implement mean(), so we have to compute it here.
341  double mean = chipCalibration * std::pow(10, prep.visitMean / -2.5);
342 
343  auto boundedField = std::make_shared<afw::math::TransformBoundedField>(ccdBBox, *transform);
344  return std::make_shared<afw::image::PhotoCalib>(mean, ccdImage.getPhotoCalib()->getCalibrationErr(),
345  boundedField, false);
346 }
347 
348 // explicit instantiation of templated function, so pybind11 can
351  afw::geom::Box2D const &, int);
354  CcdImageList const &, afw::geom::Box2D const &, int);
355 
356 } // namespace jointcal
357 } // namespace lsst
#define LOGLS_WARN(logger, message)
Log a warn-level message using an iostream-based interface.
Definition: Log.h:633
std::vector< Point2D > getCorners() const
Get the corner points.
Definition: Box.cc:421
A floating-point coordinate rectangle geometry.
Definition: Box.h:305
Relates transform(s) to their position in the fitting matrix and allows interaction with the transfor...
double transformError(CcdImage const &ccdImage, MeasuredStar const &measuredStar) const override
Return the on-sky transformed flux uncertainty for measuredStar on ccdImage.
std::string getName() const
Return the _name that identifies this ccdImage.
Definition: CcdImage.h:79
Photometric offset independent of position, defined as (fluxMag0)^-1.
void include(Point2D const &point) noexcept
Expand this to ensure that this->contains(point).
Definition: Box.cc:343
CameraSysPrefix const PIXELS
Pixel coordinates: Nominal position on the entry surface of a given detector (x, y unbinned pixels)...
Definition: CameraSys.cc:34
std::shared_ptr< PhotometryMapping > getChipMapping() const
T endl(T... args)
T bucket_count(T... args)
T end(T... args)
nth-order 2d Chebyshev photometry transform, times the input flux.
T load_factor(T... args)
std::size_t getTotalParameters() const override
Return the total number of parameters in this model.
STL class.
LSST DM logging module built on log4cxx.
nth-order 2d Chebyshev photometry transform, plus the input flux.
T at(T... args)
std::shared_ptr< PhotometryMapping > getVisitMapping() const
std::shared_ptr< afw::image::PhotoCalib > toPhotoCalib(CcdImage const &ccdImage) const override
Return the mapping of ccdImage represented as a PhotoCalib.
double computeResidual(CcdImage const &ccdImage, MeasuredStar const &measuredStar) const override
Compute the residual between the model applied to a star and its associated fittedStar.
std::shared_ptr< afw::image::PhotoCalib > getPhotoCalib() const
Return the exposure&#39;s photometric calibration.
Definition: CcdImage.h:161
#define LOGLS_DEBUG(logger, message)
Log a debug-level message using an iostream-based interface.
Definition: Log.h:593
A base class for image defects.
PhotometryMappingBase * findMapping(CcdImage const &ccdImage) const override
Return a pointer to the mapping associated with this ccdImage.
objects measured on actual images.
Definition: MeasuredStar.h:46
table::Key< int > detector
T dynamic_pointer_cast(T... args)
T infinity(T... args)
void computeParameterDerivatives(MeasuredStar const &measuredStar, CcdImage const &ccdImage, Eigen::VectorXd &derivatives) const override
Compute the parametric derivatives of this model.
solver_t * s
T move(T... args)
#define LOGLS_INFO(logger, message)
Log a info-level message using an iostream-based interface.
Definition: Log.h:613
double transform(CcdImage const &ccdImage, MeasuredStar const &measuredStar) const override
Return the on-sky transformed flux for measuredStar on ccdImage.
T find(T... args)
T size(T... args)
void dump(std::ostream &stream=std::cout) const override
Dump the contents of the transforms, for debugging.
#define LSST_EXCEPT(type,...)
Create an exception with a given type.
Definition: Exception.h:48
double tweakFluxError(jointcal::MeasuredStar const &measuredStar) const
Add a fraction of the instrumental flux to the instrumental flux error, in quadrature.
STL class.
LOG_LOGGER _log
lsst.logging instance, to be created by a subclass so that messages have consistent name...
A MathMap is a Mapping which allows you to specify a set of forward and/or inverse transformation fun...
Definition: MathMap.h:61
void offsetParams(Eigen::VectorXd const &delta) override
Offset the parameters by the provided amounts (by -delta).
T pow(T... args)
A ChebyMap is a form of Mapping which performs a Chebyshev polynomial transformation.
Definition: ChebyMap.h:97
T emplace(T... args)
Reports invalid arguments.
Definition: Runtime.h:66
PrepPhotoCalib prepPhotoCalib(CcdImage const &ccdImage) const
Helper for preparing toPhotoCalib()
double computeResidual(CcdImage const &ccdImage, MeasuredStar const &measuredStar) const override
Compute the residual between the model applied to a star and its associated fittedStar.
nth-order 2d Chebyshev photometry transform.
Photometric offset independent of position, defined as -2.5 * log(flux / fluxMag0).
A Mapping which "zooms" a set of points about the origin by multiplying all coordinate values by the ...
Definition: ZoomMap.h:45
CcdImageKey getHashKey() const
Definition: CcdImage.h:152
virtual double initialChipCalibration(std::shared_ptr< afw::image::PhotoCalib const > photoCalib)=0
Return the initial calibration to use from this photoCalib.
std::shared_ptr< afw::cameraGeom::Detector > getDetector() const
Definition: CcdImage.h:150
Handler of an actual image from a single CCD.
Definition: CcdImage.h:64
std::shared_ptr< afw::image::PhotoCalib > toPhotoCalib(CcdImage const &ccdImage) const override
Return the mapping of ccdImage represented as a PhotoCalib.
double transform(CcdImage const &ccdImage, MeasuredStar const &measuredStar) const override
Return the on-sky transformed flux for measuredStar on ccdImage.
std::shared_ptr< FittedStar > getFittedStar() const
Definition: MeasuredStar.h:113
CameraSys const FOCAL_PLANE
Focal plane coordinates: Position on a 2-d planar approximation to the focal plane (x...
Definition: CameraSys.cc:30
STL class.
double ABMagnitudeToNanojansky(double magnitude)
Convert an AB magnitude to a flux in nanojansky.
Definition: Magnitude.cc:32
Implementation of the Photometric Calibration class.
void freezeErrorTransform() override
Once this routine has been called, the error transform is not modified by offsetParams().
void initialize(CcdImageList const &ccdImageList, afw::geom::Box2D const &focalPlaneBBox, int visitOrder)
Initialize the chip, visit, and chipVisit mappings by creating appropriate transforms and mappings...
virtual double transform(CcdImage const &ccdImage, MeasuredStar const &measuredStar) const =0
Return the on-sky transformed flux for measuredStar on ccdImage.
void getMappingIndices(CcdImage const &ccdImage, IndexVector &indices) const override
Get how this set of parameters (of length Npar()) map into the "grand" fit.
Transform LSST spatial data, such as lsst::geom::Point2D and lsst::geom::SpherePoint, using an AST mapping.
Definition: Transform.h:67
Eigen::Index assignIndices(std::string const &whatToFit, Eigen::Index firstIndex) override
Assign indices in the full matrix to the parameters being fit in the mappings, starting at firstIndex...
A two-level photometric transform: one for the ccd and one for the visit.
double transformError(CcdImage const &ccdImage, MeasuredStar const &measuredStar) const override
Return the on-sky transformed flux uncertainty for measuredStar on ccdImage.