LSSTApplications  17.0+124,17.0+14,17.0+73,18.0.0+37,18.0.0+80,18.0.0-4-g68ffd23+4,18.1.0-1-g0001055+12,18.1.0-1-g03d53ef+5,18.1.0-1-g1349e88+55,18.1.0-1-g2505f39+44,18.1.0-1-g5315e5e+4,18.1.0-1-g5e4b7ea+14,18.1.0-1-g7e8fceb+4,18.1.0-1-g85f8cd4+48,18.1.0-1-g8ff0b9f+4,18.1.0-1-ga2c679d+1,18.1.0-1-gd55f500+35,18.1.0-10-gb58edde+2,18.1.0-11-g0997b02+4,18.1.0-13-gfe4edf0b+12,18.1.0-14-g259bd21+21,18.1.0-19-gdb69f3f+2,18.1.0-2-g5f9922c+24,18.1.0-2-gd3b74e5+11,18.1.0-2-gfbf3545+32,18.1.0-26-g728bddb4+5,18.1.0-27-g6ff7ca9+2,18.1.0-3-g52aa583+25,18.1.0-3-g8ea57af+9,18.1.0-3-gb69f684+42,18.1.0-3-gfcaddf3+6,18.1.0-32-gd8786685a,18.1.0-4-gf3f9b77+6,18.1.0-5-g1dd662b+2,18.1.0-5-g6dbcb01+41,18.1.0-6-gae77429+3,18.1.0-7-g9d75d83+9,18.1.0-7-gae09a6d+30,18.1.0-9-gc381ef5+4,w.2019.45
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"
34 #include "lsst/geom.h"
38 #include "lsst/jointcal/CcdImage.h"
41 
42 namespace lsst {
43 namespace jointcal {
44 
46  std::string const &whatToFit,
47  Eigen::Index firstIndex
48 ) {
49  Eigen::Index index = firstIndex;
50  if (whatToFit.find("Model") == std::string::npos) {
51  LOGLS_WARN(_log, "assignIndices was called and Model is *not* in whatToFit");
52  return index;
53  }
54 
55  // If we got here, "Model" is definitely in whatToFit.
56  _fittingChips = (whatToFit.find("ModelChip") != std::string::npos);
57  _fittingVisits = (whatToFit.find("ModelVisit") != std::string::npos);
58  // If nothing more than "Model" is specified, it means fit everything.
59  if ((!_fittingChips) && (!_fittingVisits)) {
60  _fittingChips = _fittingVisits = true;
61  }
62 
63  if (_fittingChips) {
64  for (auto &idMapping : _chipMap) {
65  auto mapping = idMapping.second.get();
66  // Don't assign indices for fixed parameters.
67  if (mapping->isFixed()) continue;
68  mapping->setIndex(index);
69  index += mapping->getNpar();
70  }
71  }
72  if (_fittingVisits) {
73  for (auto &idMapping : _visitMap) {
74  auto mapping = idMapping.second.get();
75  mapping->setIndex(index);
76  index += mapping->getNpar();
77  }
78  }
79  for (auto &idMapping : _chipVisitMap) {
80  idMapping.second->setWhatToFit(_fittingChips, _fittingVisits);
81  }
82  return index;
83 }
84 
85 void ConstrainedPhotometryModel::offsetParams(Eigen::VectorXd const &delta) {
86  if (_fittingChips) {
87  for (auto &idMapping : _chipMap) {
88  auto mapping = idMapping.second.get();
89  // Don't offset indices for fixed parameters.
90  if (mapping->isFixed()) continue;
91  mapping->offsetParams(delta.segment(mapping->getIndex(), mapping->getNpar()));
92  }
93  }
94  if (_fittingVisits) {
95  for (auto &idMapping : _visitMap) {
96  auto mapping = idMapping.second.get();
97  mapping->offsetParams(delta.segment(mapping->getIndex(), mapping->getNpar()));
98  }
99  }
100 }
101 
103  for (auto &idMapping : _chipMap) {
104  idMapping.second.get()->freezeErrorTransform();
105  }
106  for (auto &idMapping : _visitMap) {
107  idMapping.second.get()->freezeErrorTransform();
108  }
109 }
110 
112  IndexVector &indices) const {
113  auto mapping = findMapping(ccdImage);
114  mapping->getMappingIndices(indices);
115 }
116 
118  std::size_t total = 0;
119  for (auto &idMapping : _chipMap) {
120  total += idMapping.second->getNpar();
121  }
122  for (auto &idMapping : _visitMap) {
123  total += idMapping.second->getNpar();
124  }
125  return total;
126 }
127 
129  CcdImage const &ccdImage,
130  Eigen::VectorXd &derivatives) const {
131  auto mapping = findMapping(ccdImage);
132  mapping->computeParameterDerivatives(measuredStar, measuredStar.getInstFlux(), derivatives);
133 }
134 
135 namespace {
136 // Convert photoTransform's way of storing Chebyshev coefficients into the format wanted by ChebyMap.
137 ndarray::Array<double, 2, 2> toChebyMapCoeffs(std::shared_ptr<PhotometryTransformChebyshev> transform) {
138  auto coeffs = transform->getCoefficients();
139  // 4 x nPar: ChebyMap wants rows that look like (a_ij, 1, i, j) for out += a_ij*T_i(x)*T_j(y)
140  ndarray::Array<double, 2, 2> chebyCoeffs = allocate(ndarray::makeVector(transform->getNpar(),
141  std::size_t(4)));
142  Eigen::VectorXd::Index k = 0;
143  auto order = transform->getOrder();
144  for (ndarray::Size j = 0; j <= order; ++j) {
145  ndarray::Size const iMax = order - j; // to save re-computing `i+j <= order` every inner step.
146  for (ndarray::Size i = 0; i <= iMax; ++i, ++k) {
147  chebyCoeffs[k][0] = coeffs[j][i];
148  chebyCoeffs[k][1] = 1;
149  chebyCoeffs[k][2] = i;
150  chebyCoeffs[k][3] = j;
151  }
152  }
153  return chebyCoeffs;
154 }
155 } // namespace
156 
158  for (auto &idMapping : _chipMap) {
159  idMapping.second->dump(stream);
160  stream << std::endl;
161  }
162  stream << std::endl;
163  for (auto &idMapping : _visitMap) {
164  idMapping.second->dump(stream);
165  stream << std::endl;
166  }
167 }
168 
170  auto idMapping = _chipVisitMap.find(ccdImage.getHashKey());
171  if (idMapping == _chipVisitMap.end())
173  "ConstrainedPhotometryModel cannot find CcdImage " + ccdImage.getName());
174  return idMapping->second.get();
175 }
176 
177 template <class ChipTransform, class VisitTransform, class ChipVisitMapping>
179  geom::Box2D const &focalPlaneBBox, int visitOrder) {
180  // keep track of which chip we want to constrain (the one closest to the middle of the focal plane)
181  double minRadius2 = std::numeric_limits<double>::infinity();
182  CcdIdType constrainedChip = -1;
183 
184  // First initialize all visit and ccd transforms, before we make the ccdImage mappings.
185  for (auto const &ccdImage : ccdImageList) {
186  auto visit = ccdImage->getVisit();
187  auto chip = ccdImage->getCcdId();
188  auto visitPair = _visitMap.find(visit);
189  auto chipPair = _chipMap.find(chip);
190 
191  // If the chip is not in the map, add it, otherwise continue.
192  if (chipPair == _chipMap.end()) {
193  auto center = ccdImage->getDetector()->getCenter(afw::cameraGeom::FOCAL_PLANE);
194  double radius2 = std::pow(center.getX(), 2) + std::pow(center.getY(), 2);
195  if (radius2 < minRadius2) {
196  minRadius2 = radius2;
197  constrainedChip = chip;
198  }
199  auto photoCalib = ccdImage->getPhotoCalib();
200  // Use the single-frame processing calibration from the PhotoCalib as the default.
201  auto chipTransform = std::make_unique<ChipTransform>(initialChipCalibration(photoCalib));
202  _chipMap[chip] = std::make_shared<PhotometryMapping>(std::move(chipTransform));
203  }
204  // If the visit is not in the map, add it, otherwise continue.
205  if (visitPair == _visitMap.end()) {
206  auto visitTransform = std::make_unique<VisitTransform>(visitOrder, focalPlaneBBox);
207  _visitMap[visit] = std::make_shared<PhotometryMapping>(std::move(visitTransform));
208  }
209  }
210 
211  // Fix one chip mapping, to remove the degeneracy from the system.
212  _chipMap.at(constrainedChip)->setFixed(true);
213 
214  // Now create the ccdImage mappings, which are combinations of the chip/visit mappings above.
215  for (auto const &ccdImage : ccdImageList) {
216  auto visit = ccdImage->getVisit();
217  auto chip = ccdImage->getCcdId();
218  _chipVisitMap.emplace(ccdImage->getHashKey(),
219  std::make_unique<ChipVisitMapping>(_chipMap[chip], _visitMap[visit]));
220  }
221  LOGLS_INFO(_log, "Got " << _chipMap.size() << " chip mappings and " << _visitMap.size()
222  << " visit mappings; holding chip " << constrainedChip << " fixed ("
223  << getTotalParameters() << " total parameters).");
224  LOGLS_DEBUG(_log, "CcdImage map has " << _chipVisitMap.size() << " mappings, with "
225  << _chipVisitMap.bucket_count() << " buckets and a load factor of "
227 }
228 
230  CcdImage const &ccdImage) const {
231  auto detector = ccdImage.getDetector();
232  auto ccdBBox = detector->getBBox();
234 
235  // There should be no way in which we can get to this point and not have a ChipVisitMapping,
236  // so blow up if we don't.
237  assert(mapping != nullptr);
238  // We know it's a Chebyshev transform because we created it as such, so blow up if it's not.
239  auto visitPhotometryTransform = std::dynamic_pointer_cast<PhotometryTransformChebyshev>(
240  mapping->getVisitMapping()->getTransform());
241  assert(visitPhotometryTransform != nullptr);
242  auto focalBBox = visitPhotometryTransform->getBBox();
243 
244  // Unravel our chebyshev coefficients to build an astshim::ChebyMap.
245  auto coeff_f = toChebyMapCoeffs(std::dynamic_pointer_cast<PhotometryTransformChebyshev>(
246  mapping->getVisitMapping()->getTransform()));
247  // Bounds are the bbox
248  std::vector<double> lowerBound = {focalBBox.getMinX(), focalBBox.getMinY()};
249  std::vector<double> upperBound = {focalBBox.getMaxX(), focalBBox.getMaxY()};
250  afw::geom::TransformPoint2ToGeneric visitTransform(ast::ChebyMap(coeff_f, 1, lowerBound, upperBound));
251 
252  double chipConstant = mapping->getChipMapping()->getParameters()[0];
253 
254  // Compute a box that covers the area of the ccd in focal plane coordinates.
255  // This is the box over which we want to compute the mean of the visit transform.
256  auto pixToFocal = detector->getTransform(afw::cameraGeom::PIXELS, afw::cameraGeom::FOCAL_PLANE);
257  geom::Box2D ccdBBoxInFocal;
258  for (auto const &point : pixToFocal->applyForward(geom::Box2D(ccdBBox).getCorners())) {
259  ccdBBoxInFocal.include(point);
260  }
261  double visitMean = visitPhotometryTransform->mean(ccdBBoxInFocal);
262 
263  return {chipConstant, visitTransform, pixToFocal, visitMean};
264 }
265 
266 // ConstrainedFluxModel methods
267 
269  MeasuredStar const &measuredStar) const {
270  return transform(ccdImage, measuredStar) - measuredStar.getFittedStar()->getFlux();
271 }
272 
273 double ConstrainedFluxModel::transform(CcdImage const &ccdImage, MeasuredStar const &measuredStar) const {
274  auto mapping = findMapping(ccdImage);
275  return mapping->transform(measuredStar, measuredStar.getInstFlux());
276 }
277 
279  MeasuredStar const &measuredStar) const {
280  auto mapping = findMapping(ccdImage);
281  double tempErr = tweakFluxError(measuredStar);
282  return mapping->transformError(measuredStar, measuredStar.getInstFlux(), tempErr);
283 }
284 
286  auto ccdBBox = ccdImage.getDetector()->getBBox();
287  auto prep = prepPhotoCalib(ccdImage);
288 
289  // The chip part is easy: zoom map with the single value as the "zoom" factor
291  ast::ZoomMap(1, prep.chipConstant));
292 
293  // Now stitch them all together.
294  auto transform = prep.pixToFocal->then(prep.visitTransform)->then(zoomTransform);
295 
296  // NOTE: TransformBoundedField does not implement mean(), so we have to compute it here.
297  double mean = prep.chipConstant * prep.visitMean;
298 
299  auto boundedField = std::make_shared<afw::math::TransformBoundedField>(ccdBBox, *transform);
300  return std::make_shared<afw::image::PhotoCalib>(mean, ccdImage.getPhotoCalib()->getCalibrationErr(),
301  boundedField, false);
302 }
303 
304 // ConstrainedMagnitudeModel methods
305 
307  MeasuredStar const &measuredStar) const {
308  return transform(ccdImage, measuredStar) - measuredStar.getFittedStar()->getMag();
309 }
310 
312  MeasuredStar const &measuredStar) const {
313  auto mapping = findMapping(ccdImage);
314  return mapping->transform(measuredStar, measuredStar.getInstMag());
315 }
316 
318  MeasuredStar const &measuredStar) const {
319  auto mapping = findMapping(ccdImage);
320  double tempErr = tweakFluxError(measuredStar);
321  return mapping->transformError(measuredStar, measuredStar.getInstFlux(), tempErr);
322 }
323 
325  CcdImage const &ccdImage) const {
326  auto ccdBBox = ccdImage.getDetector()->getBBox();
327  auto prep = prepPhotoCalib(ccdImage);
328 
329  using namespace std::string_literals; // for operator""s to convert string literal->std::string
331  ast::MathMap(1, 1, {"y=pow(10.0,x/-2.5)"s}, {"x=-2.5*log10(y)"s}));
332 
333  // The chip part is easy: zoom map with the value (converted to a flux) as the "zoom" factor.
334  double chipCalibration = utils::ABMagnitudeToNanojansky(prep.chipConstant);
336  ast::ZoomMap(1, chipCalibration));
337 
338  // Now stitch them all together.
339  auto transform = prep.pixToFocal->then(prep.visitTransform)->then(logTransform)->then(zoomTransform);
340 
341  // NOTE: TransformBoundedField does not implement mean(), so we have to compute it here.
342  double mean = chipCalibration * std::pow(10, prep.visitMean / -2.5);
343 
344  auto boundedField = std::make_shared<afw::math::TransformBoundedField>(ccdBBox, *transform);
345  return std::make_shared<afw::image::PhotoCalib>(mean, ccdImage.getPhotoCalib()->getCalibrationErr(),
346  boundedField, false);
347 }
348 
349 // explicit instantiation of templated function, so pybind11 can
352  geom::Box2D const &, int);
355  CcdImageList const &, geom::Box2D const &, int);
356 
357 } // namespace jointcal
358 } // namespace lsst
#define LOGLS_WARN(logger, message)
Log a warn-level message using an iostream-based interface.
Definition: Log.h:648
std::vector< Point2D > getCorners() const
Get the corner points.
Definition: Box.cc:496
A floating-point coordinate rectangle geometry.
Definition: Box.h:413
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:380
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:608
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)
void initialize(CcdImageList const &ccdImageList, geom::Box2D const &focalPlaneBBox, int visitOrder)
Initialize the chip, visit, and chipVisit mappings by creating appropriate transforms and mappings...
T infinity(T... args)
void computeParameterDerivatives(MeasuredStar const &measuredStar, CcdImage const &ccdImage, Eigen::VectorXd &derivatives) const override
Compute the parametric derivatives of this model.
T move(T... args)
#define LOGLS_INFO(logger, message)
Log a info-level message using an iostream-based interface.
Definition: Log.h:628
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().
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.