LSSTApplications  16.0-10-g0ee56ad+5,16.0-11-ga33d1f2+5,16.0-12-g3ef5c14+3,16.0-12-g71e5ef5+18,16.0-12-gbdf3636+3,16.0-13-g118c103+3,16.0-13-g8f68b0a+3,16.0-15-gbf5c1cb+4,16.0-16-gfd17674+3,16.0-17-g7c01f5c+3,16.0-18-g0a50484+1,16.0-20-ga20f992+8,16.0-21-g0e05fd4+6,16.0-21-g15e2d33+4,16.0-22-g62d8060+4,16.0-22-g847a80f+4,16.0-25-gf00d9b8+1,16.0-28-g3990c221+4,16.0-3-gf928089+3,16.0-32-g88a4f23+5,16.0-34-gd7987ad+3,16.0-37-gc7333cb+2,16.0-4-g10fc685+2,16.0-4-g18f3627+26,16.0-4-g5f3a788+26,16.0-5-gaf5c3d7+4,16.0-5-gcc1f4bb+1,16.0-6-g3b92700+4,16.0-6-g4412fcd+3,16.0-6-g7235603+4,16.0-69-g2562ce1b+2,16.0-8-g14ebd58+4,16.0-8-g2df868b+1,16.0-8-g4cec79c+6,16.0-8-gadf6c7a+1,16.0-8-gfc7ad86,16.0-82-g59ec2a54a+1,16.0-9-g5400cdc+2,16.0-9-ge6233d7+5,master-g2880f2d8cf+3,v17.0.rc1
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 
44 unsigned ConstrainedPhotometryModel::assignIndices(std::string const &whatToFit, unsigned firstIndex) {
45  unsigned index = firstIndex;
46  if (whatToFit.find("Model") == std::string::npos) {
47  LOGLS_WARN(_log, "assignIndices was called and Model is *not* in whatToFit");
48  return index;
49  }
50 
51  // If we got here, "Model" is definitely in whatToFit.
52  _fittingChips = (whatToFit.find("ModelChip") != std::string::npos);
53  _fittingVisits = (whatToFit.find("ModelVisit") != std::string::npos);
54  // If nothing more than "Model" is specified, it means fit everything.
55  if ((!_fittingChips) && (!_fittingVisits)) {
56  _fittingChips = _fittingVisits = true;
57  }
58 
59  if (_fittingChips) {
60  for (auto &idMapping : _chipMap) {
61  auto mapping = idMapping.second.get();
62  // Don't assign indices for fixed parameters.
63  if (mapping->isFixed()) continue;
64  mapping->setIndex(index);
65  index += mapping->getNpar();
66  }
67  }
68  if (_fittingVisits) {
69  for (auto &idMapping : _visitMap) {
70  auto mapping = idMapping.second.get();
71  mapping->setIndex(index);
72  index += mapping->getNpar();
73  }
74  }
75  for (auto &idMapping : _chipVisitMap) {
76  idMapping.second->setWhatToFit(_fittingChips, _fittingVisits);
77  }
78  return index;
79 }
80 
81 void ConstrainedPhotometryModel::offsetParams(Eigen::VectorXd const &delta) {
82  if (_fittingChips) {
83  for (auto &idMapping : _chipMap) {
84  auto mapping = idMapping.second.get();
85  // Don't offset indices for fixed parameters.
86  if (mapping->isFixed()) continue;
87  mapping->offsetParams(delta.segment(mapping->getIndex(), mapping->getNpar()));
88  }
89  }
90  if (_fittingVisits) {
91  for (auto &idMapping : _visitMap) {
92  auto mapping = idMapping.second.get();
93  mapping->offsetParams(delta.segment(mapping->getIndex(), mapping->getNpar()));
94  }
95  }
96 }
97 
99  for (auto &idMapping : _chipMap) {
100  idMapping.second.get()->freezeErrorTransform();
101  }
102  for (auto &idMapping : _visitMap) {
103  idMapping.second.get()->freezeErrorTransform();
104  }
105 }
106 
108  std::vector<unsigned> &indices) const {
109  auto mapping = findMapping(ccdImage);
110  mapping->getMappingIndices(indices);
111 }
112 
114  int total = 0;
115  for (auto &idMapping : _chipMap) {
116  total += idMapping.second->getNpar();
117  }
118  for (auto &idMapping : _visitMap) {
119  total += idMapping.second->getNpar();
120  }
121  return total;
122 }
123 
125  CcdImage const &ccdImage,
126  Eigen::VectorXd &derivatives) const {
127  auto mapping = findMapping(ccdImage);
128  mapping->computeParameterDerivatives(measuredStar, measuredStar.getInstFlux(), derivatives);
129 }
130 
131 namespace {
132 // Convert photoTransform's way of storing Chebyshev coefficients into the format wanted by ChebyMap.
133 ndarray::Array<double, 2, 2> toChebyMapCoeffs(std::shared_ptr<PhotometryTransformChebyshev> transform) {
134  auto coeffs = transform->getCoefficients();
135  // 4 x nPar: ChebyMap wants rows that look like (a_ij, 1, i, j) for out += a_ij*T_i(x)*T_j(y)
136  ndarray::Array<double, 2, 2> chebyCoeffs = allocate(ndarray::makeVector(transform->getNpar(), 4));
137  Eigen::VectorXd::Index k = 0;
138  auto order = transform->getOrder();
139  for (ndarray::Size j = 0; j <= order; ++j) {
140  ndarray::Size const iMax = order - j; // to save re-computing `i+j <= order` every inner step.
141  for (ndarray::Size i = 0; i <= iMax; ++i, ++k) {
142  chebyCoeffs[k][0] = coeffs[j][i];
143  chebyCoeffs[k][1] = 1;
144  chebyCoeffs[k][2] = i;
145  chebyCoeffs[k][3] = j;
146  }
147  }
148  return chebyCoeffs;
149 }
150 } // namespace
151 
153  for (auto &idMapping : _chipMap) {
154  idMapping.second->dump(stream);
155  stream << std::endl;
156  }
157  stream << std::endl;
158  for (auto &idMapping : _visitMap) {
159  idMapping.second->dump(stream);
160  stream << std::endl;
161  }
162 }
163 
165  auto idMapping = _chipVisitMap.find(ccdImage.getHashKey());
166  if (idMapping == _chipVisitMap.end())
168  "ConstrainedPhotometryModel cannot find CcdImage " + ccdImage.getName());
169  return idMapping->second.get();
170 }
171 
172 template <class ChipTransform, class VisitTransform, class ChipVisitMapping>
174  afw::geom::Box2D const &focalPlaneBBox, int visitOrder) {
175  // keep track of which chip we want to constrain (the one closest to the middle of the focal plane)
176  double minRadius2 = std::numeric_limits<double>::infinity();
177  CcdIdType constrainedChip = -1;
178 
179  // First initialize all visit and ccd transforms, before we make the ccdImage mappings.
180  for (auto const &ccdImage : ccdImageList) {
181  auto visit = ccdImage->getVisit();
182  auto chip = ccdImage->getCcdId();
183  auto visitPair = _visitMap.find(visit);
184  auto chipPair = _chipMap.find(chip);
185 
186  // If the chip is not in the map, add it, otherwise continue.
187  if (chipPair == _chipMap.end()) {
188  auto center = ccdImage->getDetector()->getCenter(afw::cameraGeom::FOCAL_PLANE);
189  double radius2 = std::pow(center.getX(), 2) + std::pow(center.getY(), 2);
190  if (radius2 < minRadius2) {
191  minRadius2 = radius2;
192  constrainedChip = chip;
193  }
194  auto photoCalib = ccdImage->getPhotoCalib();
195  // Use the single-frame processing calibration from the PhotoCalib as the default.
196  auto chipTransform = std::make_unique<ChipTransform>(initialChipCalibration(photoCalib));
197  _chipMap[chip] = std::make_shared<PhotometryMapping>(std::move(chipTransform));
198  }
199  // If the visit is not in the map, add it, otherwise continue.
200  if (visitPair == _visitMap.end()) {
201  auto visitTransform = std::make_unique<VisitTransform>(visitOrder, focalPlaneBBox);
202  _visitMap[visit] = std::make_shared<PhotometryMapping>(std::move(visitTransform));
203  }
204  }
205 
206  // Fix one chip mapping, to remove the degeneracy from the system.
207  _chipMap.at(constrainedChip)->setFixed(true);
208 
209  // Now create the ccdImage mappings, which are combinations of the chip/visit mappings above.
210  for (auto const &ccdImage : ccdImageList) {
211  auto visit = ccdImage->getVisit();
212  auto chip = ccdImage->getCcdId();
213  _chipVisitMap.emplace(ccdImage->getHashKey(),
214  std::make_unique<ChipVisitMapping>(_chipMap[chip], _visitMap[visit]));
215  }
216  LOGLS_INFO(_log, "Got " << _chipMap.size() << " chip mappings and " << _visitMap.size()
217  << " visit mappings; holding chip " << constrainedChip << " fixed ("
218  << getTotalParameters() << " total parameters).");
219  LOGLS_DEBUG(_log, "CcdImage map has " << _chipVisitMap.size() << " mappings, with "
220  << _chipVisitMap.bucket_count() << " buckets and a load factor of "
222 }
223 
225  CcdImage const &ccdImage) const {
226  auto detector = ccdImage.getDetector();
227  auto ccdBBox = detector->getBBox();
229 
230  // There should be no way in which we can get to this point and not have a ChipVisitMapping,
231  // so blow up if we don't.
232  assert(mapping != nullptr);
233  // We know it's a Chebyshev transform because we created it as such, so blow up if it's not.
234  auto visitPhotometryTransform = std::dynamic_pointer_cast<PhotometryTransformChebyshev>(
235  mapping->getVisitMapping()->getTransform());
236  assert(visitPhotometryTransform != nullptr);
237  auto focalBBox = visitPhotometryTransform->getBBox();
238 
239  // Unravel our chebyshev coefficients to build an astshim::ChebyMap.
240  auto coeff_f = toChebyMapCoeffs(std::dynamic_pointer_cast<PhotometryTransformChebyshev>(
241  mapping->getVisitMapping()->getTransform()));
242  // Bounds are the bbox
243  std::vector<double> lowerBound = {focalBBox.getMinX(), focalBBox.getMinY()};
244  std::vector<double> upperBound = {focalBBox.getMaxX(), focalBBox.getMaxY()};
245  afw::geom::TransformPoint2ToGeneric visitTransform(ast::ChebyMap(coeff_f, 1, lowerBound, upperBound));
246 
247  double chipConstant = mapping->getChipMapping()->getParameters()[0];
248 
249  // Compute a box that covers the area of the ccd in focal plane coordinates.
250  // This is the box over which we want to compute the mean of the visit transform.
251  auto pixToFocal = detector->getTransform(afw::cameraGeom::PIXELS, afw::cameraGeom::FOCAL_PLANE);
252  geom::Box2D ccdBBoxInFocal;
253  for (auto const &point : pixToFocal->applyForward(geom::Box2D(ccdBBox).getCorners())) {
254  ccdBBoxInFocal.include(point);
255  }
256  double visitMean = visitPhotometryTransform->mean(ccdBBoxInFocal);
257 
258  return {chipConstant, visitTransform, pixToFocal, visitMean};
259 }
260 
261 // ConstrainedFluxModel methods
262 
264  MeasuredStar const &measuredStar) const {
265  return transform(ccdImage, measuredStar) - measuredStar.getFittedStar()->getFlux();
266 }
267 
268 double ConstrainedFluxModel::transform(CcdImage const &ccdImage, MeasuredStar const &measuredStar) const {
269  auto mapping = findMapping(ccdImage);
270  return mapping->transform(measuredStar, measuredStar.getInstFlux());
271 }
272 
274  MeasuredStar const &measuredStar) const {
275  auto mapping = findMapping(ccdImage);
276  double tempErr = tweakFluxError(measuredStar);
277  return mapping->transformError(measuredStar, measuredStar.getInstFlux(), tempErr);
278 }
279 
281  auto ccdBBox = ccdImage.getDetector()->getBBox();
282  auto prep = prepPhotoCalib(ccdImage);
283 
284  // The chip part is easy: zoom map with the single value as the "zoom" factor
286  ast::ZoomMap(1, prep.chipConstant));
287 
288  // Now stitch them all together.
289  auto transform = prep.pixToFocal->then(prep.visitTransform)->then(zoomTransform);
290 
291  // NOTE: TransformBoundedField does not implement mean(), so we have to compute it here.
292  double mean = prep.chipConstant * prep.visitMean;
293 
294  auto boundedField = std::make_shared<afw::math::TransformBoundedField>(ccdBBox, *transform);
295  return std::make_shared<afw::image::PhotoCalib>(mean, ccdImage.getPhotoCalib()->getCalibrationErr(),
296  boundedField, false);
297 }
298 
299 // ConstrainedMagnitudeModel methods
300 
302  MeasuredStar const &measuredStar) const {
303  return transform(ccdImage, measuredStar) - measuredStar.getFittedStar()->getMag();
304 }
305 
307  MeasuredStar const &measuredStar) const {
308  auto mapping = findMapping(ccdImage);
309  return mapping->transform(measuredStar, measuredStar.getInstMag());
310 }
311 
313  MeasuredStar const &measuredStar) const {
314  auto mapping = findMapping(ccdImage);
315  double tempErr = tweakFluxError(measuredStar);
316  return mapping->transformError(measuredStar, measuredStar.getInstFlux(), tempErr);
317 }
318 
320  CcdImage const &ccdImage) const {
321  auto ccdBBox = ccdImage.getDetector()->getBBox();
322  auto prep = prepPhotoCalib(ccdImage);
323 
324  using namespace std::string_literals; // for operator""s to convert string literal->std::string
326  ast::MathMap(1, 1, {"y=pow(10.0,x/-2.5)"s}, {"x=-2.5*log10(y)"s}));
327 
328  // The chip part is easy: zoom map with the value (converted to a flux) as the "zoom" factor.
329  double chipCalibration = utils::ABMagnitudeToNanojansky(prep.chipConstant);
331  ast::ZoomMap(1, chipCalibration));
332 
333  // Now stitch them all together.
334  auto transform = prep.pixToFocal->then(prep.visitTransform)->then(logTransform)->then(zoomTransform);
335 
336  // NOTE: TransformBoundedField does not implement mean(), so we have to compute it here.
337  double mean = chipCalibration * std::pow(10, prep.visitMean / -2.5);
338 
339  auto boundedField = std::make_shared<afw::math::TransformBoundedField>(ccdBBox, *transform);
340  return std::make_shared<afw::image::PhotoCalib>(mean, ccdImage.getPhotoCalib()->getCalibrationErr(),
341  boundedField, false);
342 }
343 
344 // explicit instantiation of templated function, so pybind11 can
347  afw::geom::Box2D const &, int);
350  CcdImageList const &, afw::geom::Box2D const &, int);
351 
352 } // namespace jointcal
353 } // 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:417
A floating-point coordinate rectangle geometry.
Definition: Box.h:294
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:339
CameraSysPrefix const PIXELS
Nominal pixels on the detector (unbinned) This ignores manufacturing imperfections, "tree ring" distortions and all other such effects.
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)
STL class.
LSST DM logging module built on log4cxx.
unsigned assignIndices(std::string const &whatToFit, unsigned firstIndex) override
Assign indices in the full matrix to the parameters being fit in the mappings, starting at firstIndex...
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.
int getTotalParameters() const override
Return the total number of parameters in this model.
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.
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: Rectilinear x, y (and z when talking about the location of a detector) on th...
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.
Transform LSST spatial data, such as lsst::geom::Point2D and lsst::geom::SpherePoint, using an AST mapping.
Definition: Transform.h:67
void getMappingIndices(CcdImage const &ccdImage, std::vector< unsigned > &indices) const override
Get how this set of parameters (of length Npar()) map into the "grand" fit.
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.