lsst.afw  16.0-66-g44ffc98c2
PhotoCalib.cc
Go to the documentation of this file.
1 /*
2  * LSST Data Management System
3  * Copyright 2017 LSST Corporation.
4  *
5  * This product includes software developed by the
6  * LSST Project (http://www.lsst.org/).
7  *
8  * This program is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the LSST License Statement and
19  * the GNU General Public License along with this program. If not,
20  * see <http://www.lsstcorp.org/LegalNotices/>.
21  */
22 
23 #include <cmath>
24 
25 #include "lsst/geom/Point.h"
28 #include "lsst/afw/table/Source.h"
32 #include "lsst/pex/exceptions.h"
33 #include "ndarray.h"
35 
36 namespace lsst {
37 namespace afw {
38 
41 
42 namespace image {
43 
44 // ------------------- helpers -------------------
45 
46 namespace {
47 
48 int const SERIALIZATION_VERSION = 0;
49 
50 double toMaggies(double instFlux, double scale) { return instFlux * scale; }
51 
52 double toMagnitude(double instFlux, double scale) { return -2.5 * log10(instFlux * scale); }
53 
54 double fromMagnitude(double magnitude, double scale) { return pow(10, magnitude / -2.5) / scale; }
55 
56 double toMaggiesErr(double instFlux, double instFluxErr, double scale, double scaleErr, double maggies) {
57  return maggies * hypot(instFluxErr / instFlux, scaleErr / scale);
58 }
59 
73 void toMaggiesVariance(ndarray::Array<float const, 2, 1> const &instFlux,
74  ndarray::Array<float const, 2, 1> const &instFluxVar, float scaleErr,
75  ndarray::Array<float const, 2, 1> const &maggies, ndarray::Array<float, 2, 1> out) {
76  auto eigenMaggies = ndarray::asEigen<Eigen::ArrayXpr>(maggies);
77  auto eigenInstFluxVar = ndarray::asEigen<Eigen::ArrayXpr>(instFluxVar);
78  auto eigenInstFlux = ndarray::asEigen<Eigen::ArrayXpr>(instFlux);
79  auto eigenOut = ndarray::asEigen<Eigen::ArrayXpr>(out);
80  eigenOut = eigenMaggies.square() * (eigenInstFluxVar / eigenInstFlux.square() +
81  (scaleErr / eigenMaggies * eigenInstFlux).square());
82 }
83 
84 double toMagnitudeErr(double instFlux, double instFluxErr, double scale, double scaleErr) {
85  return 2.5 / log(10.0) * hypot(instFluxErr / instFlux, scaleErr / scale);
86 }
87 
88 } // anonymous namespace
89 
90 // ------------------- Conversions to Maggies -------------------
91 
92 double PhotoCalib::instFluxToMaggies(double instFlux, lsst::geom::Point<double, 2> const &point) const {
93  return toMaggies(instFlux, evaluate(point));
94 }
95 
96 double PhotoCalib::instFluxToMaggies(double instFlux) const { return toMaggies(instFlux, _calibrationMean); }
97 
98 Measurement PhotoCalib::instFluxToMaggies(double instFlux, double instFluxErr,
99  lsst::geom::Point<double, 2> const &point) const {
100  double calibration, err, maggies;
101  calibration = evaluate(point);
102  maggies = toMaggies(instFlux, calibration);
103  err = toMaggiesErr(instFlux, instFluxErr, calibration, _calibrationErr, maggies);
104  return Measurement(maggies, err);
105 }
106 
107 Measurement PhotoCalib::instFluxToMaggies(double instFlux, double instFluxErr) const {
108  double maggies = toMaggies(instFlux, _calibrationMean);
109  double err = toMaggiesErr(instFlux, instFluxErr, _calibrationMean, _calibrationErr, maggies);
110  return Measurement(maggies, err);
111 }
112 
113 Measurement PhotoCalib::instFluxToMaggies(afw::table::SourceRecord const &sourceRecord,
114  std::string const &instFluxField) const {
115  auto position = sourceRecord.getCentroid();
116  auto instFluxKey = sourceRecord.getSchema().find<double>(instFluxField + "_instFlux").key;
117  auto instFluxErrKey = sourceRecord.getSchema().find<double>(instFluxField + "_instFluxErr").key;
118  return instFluxToMaggies(sourceRecord.get(instFluxKey), sourceRecord.get(instFluxErrKey), position);
119 }
120 ndarray::Array<double, 2, 2> PhotoCalib::instFluxToMaggies(afw::table::SourceCatalog const &sourceCatalog,
121  std::string const &instFluxField) const {
122  ndarray::Array<double, 2, 2> result =
123  ndarray::allocate(ndarray::makeVector(int(sourceCatalog.size()), 2));
124  instFluxToMaggiesArray(sourceCatalog, instFluxField, result);
125  return result;
126 }
127 
128 void PhotoCalib::instFluxToMaggies(afw::table::SourceCatalog &sourceCatalog, std::string const &instFluxField,
129  std::string const &outField) const {
130  auto instFluxKey = sourceCatalog.getSchema().find<double>(instFluxField + "_instFlux").key;
131  auto instFluxErrKey = sourceCatalog.getSchema().find<double>(instFluxField + "_instFluxErr").key;
132  auto maggiesKey = sourceCatalog.getSchema().find<double>(outField + "_instFlux").key;
133  auto maggiesErrKey = sourceCatalog.getSchema().find<double>(outField + "_instFluxErr").key;
134  for (auto &record : sourceCatalog) {
135  auto result =
136  instFluxToMaggies(record.get(instFluxKey), record.get(instFluxErrKey), record.getCentroid());
137  record.set(maggiesKey, result.value);
138  record.set(maggiesErrKey, result.err);
139  }
140 }
141 
142 // ------------------- Conversions to Magnitudes -------------------
143 
144 double PhotoCalib::instFluxToMagnitude(double instFlux, lsst::geom::Point<double, 2> const &point) const {
145  return toMagnitude(instFlux, evaluate(point));
146 }
147 
148 double PhotoCalib::instFluxToMagnitude(double instFlux) const {
149  return toMagnitude(instFlux, _calibrationMean);
150 }
151 
152 Measurement PhotoCalib::instFluxToMagnitude(double instFlux, double instFluxErr,
153  lsst::geom::Point<double, 2> const &point) const {
154  double calibration, err, magnitude;
155  calibration = evaluate(point);
156  magnitude = toMagnitude(instFlux, calibration);
157  err = toMagnitudeErr(instFlux, instFluxErr, calibration, _calibrationErr);
158  return Measurement(magnitude, err);
159 }
160 
161 Measurement PhotoCalib::instFluxToMagnitude(double instFlux, double instFluxErr) const {
162  double magnitude = toMagnitude(instFlux, _calibrationMean);
163  double err = toMagnitudeErr(instFlux, instFluxErr, _calibrationMean, _calibrationErr);
164  return Measurement(magnitude, err);
165 }
166 
167 Measurement PhotoCalib::instFluxToMagnitude(afw::table::SourceRecord const &sourceRecord,
168  std::string const &instFluxField) const {
169  auto position = sourceRecord.getCentroid();
170  auto instFluxKey = sourceRecord.getSchema().find<double>(instFluxField + "_instFlux").key;
171  auto instFluxErrKey = sourceRecord.getSchema().find<double>(instFluxField + "_instFluxErr").key;
172  return instFluxToMagnitude(sourceRecord.get(instFluxKey), sourceRecord.get(instFluxErrKey), position);
173 }
174 
175 ndarray::Array<double, 2, 2> PhotoCalib::instFluxToMagnitude(afw::table::SourceCatalog const &sourceCatalog,
176  std::string const &instFluxField) const {
177  ndarray::Array<double, 2, 2> result =
178  ndarray::allocate(ndarray::makeVector(int(sourceCatalog.size()), 2));
179  instFluxToMagnitudeArray(sourceCatalog, instFluxField, result);
180  return result;
181 }
182 
183 void PhotoCalib::instFluxToMagnitude(afw::table::SourceCatalog &sourceCatalog,
184  std::string const &instFluxField, std::string const &outField) const {
185  auto instFluxKey = sourceCatalog.getSchema().find<double>(instFluxField + "_instFlux").key;
186  auto instFluxErrKey = sourceCatalog.getSchema().find<double>(instFluxField + "_instFluxErr").key;
187  auto magKey = sourceCatalog.getSchema().find<double>(outField + "_mag").key;
188  auto magErrKey = sourceCatalog.getSchema().find<double>(outField + "_magErr").key;
189  for (auto &record : sourceCatalog) {
190  auto result = instFluxToMagnitude(record.get(instFluxKey), record.get(instFluxErrKey),
191  record.getCentroid());
192  record.set(magKey, result.value);
193  record.set(magErrKey, result.err);
194  }
195 }
196 
197 // ------------------- other utility methods -------------------
198 
199 double PhotoCalib::magnitudeToInstFlux(double magnitude) const {
200  return fromMagnitude(magnitude, _calibrationMean);
201 }
202 
203 double PhotoCalib::magnitudeToInstFlux(double magnitude, lsst::geom::Point<double, 2> const &point) const {
204  return fromMagnitude(magnitude, evaluate(point));
205 }
206 
207 std::shared_ptr<math::BoundedField> PhotoCalib::computeScaledCalibration() const {
208  return *(_calibration) / _calibrationMean;
209 }
210 
212  throw LSST_EXCEPT(pex::exceptions::LogicError, "Not Implemented: See DM-10154.");
213 }
214 
215 bool PhotoCalib::operator==(PhotoCalib const &rhs) const {
216  return (_calibrationMean == rhs._calibrationMean && _calibrationErr == rhs._calibrationErr &&
217  (*_calibration) == *(rhs._calibration));
218 }
219 
220 double PhotoCalib::computeCalibrationMean(std::shared_ptr<afw::math::BoundedField> calibration) const {
221  return calibration->mean();
222 }
223 
225  if (photoCalib._isConstant)
226  os << "spatially constant with ";
227  else
228  os << *(photoCalib._calibration) << " with ";
229  return os << "mean: " << photoCalib._calibrationMean << " err: " << photoCalib._calibrationErr;
230 }
231 
232 MaskedImage<float> PhotoCalib::calibrateImage(MaskedImage<float> const &maskedImage) const {
233  // Deep copy construct, as we're mutiplying in-place.
234  auto result = MaskedImage<float>(maskedImage, true);
235 
236  if (_isConstant) {
237  *(result.getImage()) *= _calibrationMean;
238  } else {
239  _calibration->multiplyImage(*(result.getImage()), true); // only in the overlap region
240  }
241  toMaggiesVariance(maskedImage.getImage()->getArray(), maskedImage.getVariance()->getArray(),
242  _calibrationErr, result.getImage()->getArray(), result.getVariance()->getArray());
243 
244  return result;
245 }
246 
247 // ------------------- persistence -------------------
248 
249 namespace {
250 
251 class PhotoCalibSchema {
252 public:
253  table::Schema schema;
254  table::Key<double> calibrationMean;
255  table::Key<double> calibrationErr;
256  table::Key<table::Flag> isConstant;
257  table::Key<int> field;
258  table::Key<int> version;
259 
260  // No copying
261  PhotoCalibSchema(PhotoCalibSchema const &) = delete;
262  PhotoCalibSchema &operator=(PhotoCalibSchema const &) = delete;
263  // No moving
264  PhotoCalibSchema(PhotoCalibSchema &&) = delete;
265  PhotoCalibSchema &operator=(PhotoCalibSchema &&) = delete;
266 
267  static PhotoCalibSchema const &get() {
268  static PhotoCalibSchema const instance;
269  return instance;
270  }
271 
272 private:
273  PhotoCalibSchema()
274  : schema(),
275  calibrationMean(schema.addField<double>(
276  "calibrationMean", "mean calibration on this PhotoCalib's domain", "count")),
278  schema.addField<double>("calibrationErr", "1-sigma error on calibrationMean", "count")),
279  isConstant(schema.addField<table::Flag>("isConstant", "Is this spatially-constant?")),
280  field(schema.addField<int>("field", "archive ID of the BoundedField object")),
281  version(schema.addField<int>("version", "version of this PhotoCalib")) {
282  schema.getCitizen().markPersistent();
283  }
284 };
285 
286 class PhotoCalibFactory : public table::io::PersistableFactory {
287 public:
288  PTR(table::io::Persistable)
289  read(InputArchive const &archive, CatalogVector const &catalogs) const override {
290  table::BaseRecord const &record = catalogs.front().front();
291  PhotoCalibSchema const &keys = PhotoCalibSchema::get();
292  int version = getVersion(record);
293  if (version != 0) {
294  throw(pex::exceptions::TypeError("Unsupported version: " + std::to_string(version)));
295  }
296  return std::make_shared<PhotoCalib>(record.get(keys.calibrationMean), record.get(keys.calibrationErr),
297  archive.get<afw::math::BoundedField>(record.get(keys.field)),
298  record.get(keys.isConstant));
299  }
300 
301  PhotoCalibFactory(std::string const &name) : afw::table::io::PersistableFactory(name) {}
302 
303 protected:
304  int getVersion(table::BaseRecord const &record) const {
305  int version = -1;
306  try {
307  std::string versionName = "version";
308  auto versionKey = record.getSchema().find<int>(versionName);
309  version = record.get(versionKey.key);
310  } catch (const pex::exceptions::NotFoundError &) {
311  // un-versioned files are version 0
312  version = 0;
313  }
314  return version;
315  }
316 };
317 
318 std::string getPhotoCalibPersistenceName() { return "PhotoCalib"; }
319 
320 PhotoCalibFactory registration(getPhotoCalibPersistenceName());
321 
322 } // anonymous namespace
323 
324 std::string PhotoCalib::getPersistenceName() const { return getPhotoCalibPersistenceName(); }
325 
326 void PhotoCalib::write(OutputArchiveHandle &handle) const {
327  PhotoCalibSchema const &keys = PhotoCalibSchema::get();
328  table::BaseCatalog catalog = handle.makeCatalog(keys.schema);
329  auto record = catalog.addNew();
330  record->set(keys.calibrationMean, _calibrationMean);
331  record->set(keys.calibrationErr, _calibrationErr);
332  record->set(keys.isConstant, _isConstant);
333  record->set(keys.field, handle.put(_calibration));
334  record->set(keys.version, SERIALIZATION_VERSION);
335  handle.saveCatalog(catalog);
336 }
337 
338 // ------------------- private/protected helpers -------------------
339 
340 double PhotoCalib::evaluate(lsst::geom::Point<double, 2> const &point) const {
341  if (_isConstant)
342  return _calibrationMean;
343  else
344  return _calibration->evaluate(point);
345 }
346 
347 void PhotoCalib::instFluxToMaggiesArray(afw::table::SourceCatalog const &sourceCatalog,
348  std::string const &instFluxField,
349  ndarray::Array<double, 2, 2> result) const {
350  double instFlux, instFluxErr, maggies, calibration;
351  auto instFluxKey = sourceCatalog.getSchema().find<double>(instFluxField + "_instFlux").key;
352  auto instFluxErrKey = sourceCatalog.getSchema().find<double>(instFluxField + "_instFluxErr").key;
353  auto iter = result.begin();
354  for (auto const &rec : sourceCatalog) {
355  instFlux = rec.get(instFluxKey);
356  instFluxErr = rec.get(instFluxErrKey);
357  calibration = evaluate(rec.getCentroid());
358  maggies = toMaggies(instFlux, calibration);
359  (*iter)[0] = maggies;
360  (*iter)[1] = toMaggiesErr(instFlux, instFluxErr, calibration, _calibrationErr, maggies);
361  iter++;
362  }
363 }
364 
365 void PhotoCalib::instFluxToMagnitudeArray(afw::table::SourceCatalog const &sourceCatalog,
366  std::string const &instFluxField,
367  ndarray::Array<double, 2, 2> result) const {
368  double instFlux, instFluxErr, calibration;
369  auto instFluxKey = sourceCatalog.getSchema().find<double>(instFluxField + "_instFlux").key;
370  auto instFluxErrKey = sourceCatalog.getSchema().find<double>(instFluxField + "_instFluxErr").key;
371  auto iter = result.begin();
372  for (auto const &rec : sourceCatalog) {
373  instFlux = rec.get(instFluxKey);
374  instFluxErr = rec.get(instFluxErrKey);
375  calibration = evaluate(rec.getCentroid());
376  (*iter)[0] = toMagnitude(instFlux, calibration);
377  (*iter)[1] = toMagnitudeErr(instFlux, instFluxErr, calibration, _calibrationErr);
378  iter++;
379  }
380 }
381 
382 } // namespace image
383 } // namespace afw
384 } // namespace lsst
VariancePtr getVariance() const
Return a (shared_ptr to) the MaskedImage&#39;s variance.
Definition: MaskedImage.h:1091
table::Key< double > calibrationErr
Definition: PhotoCalib.cc:255
def keys(self)
int put(Persistable const *obj, bool permissive=false)
Save an object to the archive and return a unique ID that can be used to retrieve it from an InputArc...
An object passed to Persistable::write to allow it to persist itself.
The photometric calibration of an exposure.
Definition: PhotoCalib.h:102
table::Key< table::Flag > isConstant
Definition: PhotoCalib.cc:256
def scale(algorithm, min, max=None, frame=None)
Definition: ds9.py:114
T to_string(T... args)
static std::shared_ptr< T > dynamicCast(std::shared_ptr< Persistable > const &ptr)
Dynamically cast a shared_ptr.
Definition: Persistable.cc:18
A value and its error.
Definition: PhotoCalib.h:48
#define PTR(...)
ItemVariant const * other
Definition: Schema.cc:56
Field< T >::Value get(Key< T > const &key) const
Return the value of a field for the given key.
Definition: BaseRecord.h:125
T log10(T... args)
table::Key< double > calibrationMean
Definition: PhotoCalib.cc:254
ImagePtr getImage() const
Return a (shared_ptr to) the MaskedImage&#39;s image.
Definition: MaskedImage.h:1058
STL class.
SchemaItem< T > find(std::string const &name) const
Find a SchemaItem in the Schema by name.
Definition: Schema.cc:656
A base class for image defects.
A class to manipulate images, masks, and variance as a single object.
Definition: MaskedImage.h:74
log
Key< U > key
Definition: Schema.cc:281
Schema getSchema() const
Return the Schema that holds this record&#39;s fields and keys.
Definition: BaseRecord.h:54
std::unique_ptr< SchemaItem< U > > result
Definition: Schema.cc:195
BaseCatalog makeCatalog(Schema const &schema)
Return a new, empty catalog with the given schema.
table::Schema schema
Definition: PhotoCalib.cc:253
std::ostream & operator<<(std::ostream &os, PhotoCalib const &photoCalib)
Definition: PhotoCalib.cc:224
T hypot(T... args)
T find(T... args)
#define LSST_EXCEPT(type,...)
T pow(T... args)
Record class that contains measurements made on a single exposure.
Definition: Source.h:82
void saveCatalog(BaseCatalog const &catalog)
Save a catalog in the archive.
std::ostream * os
Definition: Schema.cc:746
STL class.
Implementation of the Photometric Calibration class.
CentroidSlotDefinition::MeasValue getCentroid() const
Get the value of the Centroid slot measurement.
Definition: Source.h:644
std::shared_ptr< RecordT > addNew()
Create a new record, add it to the end of the catalog, and return a pointer to it.
Definition: Catalog.h:472
table::Key< int > version
Definition: PhotoCalib.cc:258
table::Key< int > field
Definition: PhotoCalib.cc:257