lsst.afw  16.0-69-ga986782ad
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,
233  bool includeScaleUncertainty) const {
234  // Deep copy construct, as we're mutiplying in-place.
235  auto result = MaskedImage<float>(maskedImage, true);
236 
237  if (_isConstant) {
238  *(result.getImage()) *= _calibrationMean;
239  } else {
240  _calibration->multiplyImage(*(result.getImage()), true); // only in the overlap region
241  }
242  if (includeScaleUncertainty) {
243  toMaggiesVariance(maskedImage.getImage()->getArray(), maskedImage.getVariance()->getArray(),
244  _calibrationErr, result.getImage()->getArray(), result.getVariance()->getArray());
245  } else {
246  toMaggiesVariance(maskedImage.getImage()->getArray(), maskedImage.getVariance()->getArray(), 0,
247  result.getImage()->getArray(), result.getVariance()->getArray());
248  }
249 
250  return result;
251 }
252 
253 // ------------------- persistence -------------------
254 
255 namespace {
256 
257 class PhotoCalibSchema {
258 public:
259  table::Schema schema;
260  table::Key<double> calibrationMean;
261  table::Key<double> calibrationErr;
262  table::Key<table::Flag> isConstant;
263  table::Key<int> field;
264  table::Key<int> version;
265 
266  // No copying
267  PhotoCalibSchema(PhotoCalibSchema const &) = delete;
268  PhotoCalibSchema &operator=(PhotoCalibSchema const &) = delete;
269  // No moving
270  PhotoCalibSchema(PhotoCalibSchema &&) = delete;
271  PhotoCalibSchema &operator=(PhotoCalibSchema &&) = delete;
272 
273  static PhotoCalibSchema const &get() {
274  static PhotoCalibSchema const instance;
275  return instance;
276  }
277 
278 private:
279  PhotoCalibSchema()
280  : schema(),
281  calibrationMean(schema.addField<double>(
282  "calibrationMean", "mean calibration on this PhotoCalib's domain", "count")),
284  schema.addField<double>("calibrationErr", "1-sigma error on calibrationMean", "count")),
285  isConstant(schema.addField<table::Flag>("isConstant", "Is this spatially-constant?")),
286  field(schema.addField<int>("field", "archive ID of the BoundedField object")),
287  version(schema.addField<int>("version", "version of this PhotoCalib")) {
288  schema.getCitizen().markPersistent();
289  }
290 };
291 
292 class PhotoCalibFactory : public table::io::PersistableFactory {
293 public:
294  PTR(table::io::Persistable)
295  read(InputArchive const &archive, CatalogVector const &catalogs) const override {
296  table::BaseRecord const &record = catalogs.front().front();
297  PhotoCalibSchema const &keys = PhotoCalibSchema::get();
298  int version = getVersion(record);
299  if (version != 0) {
300  throw(pex::exceptions::TypeError("Unsupported version: " + std::to_string(version)));
301  }
302  return std::make_shared<PhotoCalib>(record.get(keys.calibrationMean), record.get(keys.calibrationErr),
303  archive.get<afw::math::BoundedField>(record.get(keys.field)),
304  record.get(keys.isConstant));
305  }
306 
307  PhotoCalibFactory(std::string const &name) : afw::table::io::PersistableFactory(name) {}
308 
309 protected:
310  int getVersion(table::BaseRecord const &record) const {
311  int version = -1;
312  try {
313  std::string versionName = "version";
314  auto versionKey = record.getSchema().find<int>(versionName);
315  version = record.get(versionKey.key);
316  } catch (const pex::exceptions::NotFoundError &) {
317  // un-versioned files are version 0
318  version = 0;
319  }
320  return version;
321  }
322 };
323 
324 std::string getPhotoCalibPersistenceName() { return "PhotoCalib"; }
325 
326 PhotoCalibFactory registration(getPhotoCalibPersistenceName());
327 
328 } // anonymous namespace
329 
330 std::string PhotoCalib::getPersistenceName() const { return getPhotoCalibPersistenceName(); }
331 
332 void PhotoCalib::write(OutputArchiveHandle &handle) const {
333  PhotoCalibSchema const &keys = PhotoCalibSchema::get();
334  table::BaseCatalog catalog = handle.makeCatalog(keys.schema);
335  auto record = catalog.addNew();
336  record->set(keys.calibrationMean, _calibrationMean);
337  record->set(keys.calibrationErr, _calibrationErr);
338  record->set(keys.isConstant, _isConstant);
339  record->set(keys.field, handle.put(_calibration));
340  record->set(keys.version, SERIALIZATION_VERSION);
341  handle.saveCatalog(catalog);
342 }
343 
344 // ------------------- private/protected helpers -------------------
345 
346 double PhotoCalib::evaluate(lsst::geom::Point<double, 2> const &point) const {
347  if (_isConstant)
348  return _calibrationMean;
349  else
350  return _calibration->evaluate(point);
351 }
352 
353 void PhotoCalib::instFluxToMaggiesArray(afw::table::SourceCatalog const &sourceCatalog,
354  std::string const &instFluxField,
355  ndarray::Array<double, 2, 2> result) const {
356  double instFlux, instFluxErr, maggies, calibration;
357  auto instFluxKey = sourceCatalog.getSchema().find<double>(instFluxField + "_instFlux").key;
358  auto instFluxErrKey = sourceCatalog.getSchema().find<double>(instFluxField + "_instFluxErr").key;
359  auto iter = result.begin();
360  for (auto const &rec : sourceCatalog) {
361  instFlux = rec.get(instFluxKey);
362  instFluxErr = rec.get(instFluxErrKey);
363  calibration = evaluate(rec.getCentroid());
364  maggies = toMaggies(instFlux, calibration);
365  (*iter)[0] = maggies;
366  (*iter)[1] = toMaggiesErr(instFlux, instFluxErr, calibration, _calibrationErr, maggies);
367  iter++;
368  }
369 }
370 
371 void PhotoCalib::instFluxToMagnitudeArray(afw::table::SourceCatalog const &sourceCatalog,
372  std::string const &instFluxField,
373  ndarray::Array<double, 2, 2> result) const {
374  double instFlux, instFluxErr, calibration;
375  auto instFluxKey = sourceCatalog.getSchema().find<double>(instFluxField + "_instFlux").key;
376  auto instFluxErrKey = sourceCatalog.getSchema().find<double>(instFluxField + "_instFluxErr").key;
377  auto iter = result.begin();
378  for (auto const &rec : sourceCatalog) {
379  instFlux = rec.get(instFluxKey);
380  instFluxErr = rec.get(instFluxErrKey);
381  calibration = evaluate(rec.getCentroid());
382  (*iter)[0] = toMagnitude(instFlux, calibration);
383  (*iter)[1] = toMagnitudeErr(instFlux, instFluxErr, calibration, _calibrationErr);
384  iter++;
385  }
386 }
387 
388 } // namespace image
389 } // namespace afw
390 } // 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:261
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:262
def scale(algorithm, min, max=None, frame=None)
Definition: ds9.py:109
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:260
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:259
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:264
table::Key< int > field
Definition: PhotoCalib.cc:263