lsst.afw  16.0-56-g615901931+1
Calib.cc
Go to the documentation of this file.
1 // -*- lsst-c++ -*-
2 
3 /*
4  * LSST Data Management System
5  * Copyright 2008-2016 LSST Corporation.
6  *
7  * This product includes software developed by the
8  * LSST Project (http://www.lsst.org/).
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the LSST License Statement and
21  * the GNU General Public License along with this program. If not,
22  * see <http://www.lsstcorp.org/LegalNotices/>.
23  */
24 
25 /*
26  * Classes to support calibration (e.g. photometric zero points, exposure times)
27  */
28 #include <cmath>
29 #include <cstdint>
30 #include <string>
31 
32 #include "boost/format.hpp"
33 #include "boost/algorithm/string/trim.hpp"
34 
35 #include "ndarray.h"
36 #include "lsst/pex/exceptions.h"
38 #include "lsst/afw/image/Calib.h"
44 
45 namespace lsst {
46 namespace afw {
47 
50 
51 namespace image {
52 
54 template <typename T>
55 ndarray::Array<T, 1> abMagFromFlux(ndarray::Array<T const, 1> const& flux) {
56  ndarray::Array<T, 1> out = ndarray::allocate(flux.getShape());
57  for (std::size_t ii = 0; ii < flux.getNumElements(); ++ii) {
58  out[ii] = abMagFromFlux(flux[ii]);
59  }
60  return out;
61 }
62 
64 template <typename T>
65 ndarray::Array<T, 1> abMagErrFromFluxErr(ndarray::Array<T const, 1> const& fluxErr,
66  ndarray::Array<T const, 1> const& flux) {
67  if (flux.getNumElements() != fluxErr.getNumElements()) {
68  throw LSST_EXCEPT(pex::exceptions::LengthError, (boost::format("Length mismatch: %d vs %d") %
69  flux.getNumElements() % fluxErr.getNumElements())
70  .str());
71  }
72  ndarray::Array<T, 1> out = ndarray::allocate(flux.getShape());
73  for (std::size_t ii = 0; ii < flux.getNumElements(); ++ii) {
74  out[ii] = abMagErrFromFluxErr(fluxErr[ii], flux[ii]);
75  }
76  return out;
77 }
78 
80 template <typename T>
81 ndarray::Array<T, 1> fluxFromABMag(ndarray::Array<T const, 1> const& mag) {
82  ndarray::Array<T, 1> out = ndarray::allocate(mag.getShape());
83  for (std::size_t ii = 0; ii < mag.getNumElements(); ++ii) {
84  out[ii] = fluxFromABMag(mag[ii]);
85  }
86  return out;
87 }
88 
90 template <typename T>
91 ndarray::Array<T, 1> fluxErrFromABMagErr(ndarray::Array<T const, 1> const& magErr,
92  ndarray::Array<T const, 1> const& mag) {
93  if (mag.getNumElements() != magErr.getNumElements()) {
94  throw LSST_EXCEPT(pex::exceptions::LengthError, (boost::format("Length mismatch: %d vs %d") %
95  mag.getNumElements() % magErr.getNumElements())
96  .str());
97  }
98  ndarray::Array<T, 1> out = ndarray::allocate(mag.getShape());
99  for (std::size_t ii = 0; ii < mag.getNumElements(); ++ii) {
100  out[ii] = fluxErrFromABMagErr(magErr[ii], mag[ii]);
101  }
102  return out;
103 }
104 
105 Calib::Calib() noexcept : _fluxMag0(0.0), _fluxMag0Err(0.0) {}
106 Calib::Calib(double fluxMag0) : _fluxMag0(fluxMag0), _fluxMag0Err(0.0) {}
107 Calib::Calib(std::vector<std::shared_ptr<Calib const>> const& calibs) : _fluxMag0(0.0), _fluxMag0Err(0.0) {
108  if (calibs.empty()) {
110  "You must provide at least one input Calib");
111  }
112 
113  double const fluxMag00 = calibs[0]->_fluxMag0;
114  double const fluxMag0Err0 = calibs[0]->_fluxMag0Err;
115 
116  for (std::vector<std::shared_ptr<Calib const>>::const_iterator ptr = calibs.begin(); ptr != calibs.end();
117  ++ptr) {
118  Calib const& calib = **ptr;
119 
120  if (::fabs(fluxMag00 - calib._fluxMag0) > std::numeric_limits<double>::epsilon() ||
121  ::fabs(fluxMag0Err0 - calib._fluxMag0Err) > std::numeric_limits<double>::epsilon()) {
123  (boost::format("You may only combine calibs with the same fluxMag0: "
124  "%g +- %g v %g +- %g") %
125  calib.getFluxMag0().first % calib.getFluxMag0().second %
126  calibs[0]->getFluxMag0().first % calibs[0]->getFluxMag0().second)
127  .str());
128  }
129  }
130 }
131 
133  double fluxMag0 = 0.0, fluxMag0Err = 0.0;
134 
135  auto key = "FLUXMAG0";
136  if (metadata->exists(key)) {
137  fluxMag0 = metadata->getAsDouble(key);
138 
139  key = "FLUXMAG0ERR";
140  if (metadata->exists(key)) {
141  fluxMag0Err = metadata->getAsDouble(key);
142  }
143  }
144 
145  _fluxMag0 = fluxMag0;
146  _fluxMag0Err = fluxMag0Err;
147 }
148 bool Calib::_throwOnNegativeFlux = true;
149 void Calib::setThrowOnNegativeFlux(bool raiseException) noexcept { _throwOnNegativeFlux = raiseException; }
150 
151 bool Calib::getThrowOnNegativeFlux() noexcept { return _throwOnNegativeFlux; }
152 
153 Calib::Calib(Calib const&) noexcept = default;
154 Calib::Calib(Calib&&) noexcept = default;
155 Calib& Calib::operator=(Calib const&) noexcept = default;
156 Calib& Calib::operator=(Calib&&) noexcept = default;
157 Calib::~Calib() noexcept = default;
158 
159 namespace detail {
161  int nstripped = 0;
162 
163  auto key = "FLUXMAG0";
164  if (metadata->exists(key)) {
165  metadata->remove(key);
166  nstripped++;
167  }
168 
169  key = "FLUXMAG0ERR";
170  if (metadata->exists(key)) {
171  metadata->remove(key);
172  nstripped++;
173  }
174 
175  return nstripped;
176 }
177 } // namespace detail
178 
179 bool Calib::operator==(Calib const& rhs) const noexcept {
180  return _fluxMag0 == rhs._fluxMag0 && _fluxMag0Err == rhs._fluxMag0Err;
181 }
182 
184  _fluxMag0 = fluxMag0;
185  _fluxMag0Err = fluxMag0Err;
186 }
188  _fluxMag0 = fluxMag0AndErr.first;
189  _fluxMag0Err = fluxMag0AndErr.second;
190 }
191 
192 std::pair<double, double> Calib::getFluxMag0() const { return std::make_pair(_fluxMag0, _fluxMag0Err); }
193 
194 namespace {
195 
196 inline void checkNegativeFlux0(double fluxMag0) {
197  if (fluxMag0 <= 0) {
199  (boost::format("Flux of 0-mag object must be >= 0: saw %g") % fluxMag0).str());
200  }
201 }
202 inline bool isNegativeFlux(double flux, bool doThrow) {
203  if (flux <= 0) {
204  if (doThrow) {
206  (boost::format("Flux must be >= 0: saw %g") % flux).str());
207  }
208  return true;
209  }
210  return false;
211 }
212 inline double convertToFlux(double fluxMag0, double mag) { return fluxMag0 * ::pow(10.0, -0.4 * mag); }
213 inline double convertToFluxErr(double fluxMag0InvSNR, double flux, double magErr) {
214  // Want to:
215  // return flux * hypot(_fluxMag0Err/_fluxMag0, 0.4*std::log(10)*magSigma/mag);
216  // But hypot is not standard C++ so use <http://en.wikipedia.org/wiki/Hypot#Implementation>
217  double a = fluxMag0InvSNR;
218  double b = 0.4 * std::log(10.0) * magErr;
219  if (std::abs(a) < std::abs(b)) {
220  std::swap(a, b);
221  }
222  return flux * std::abs(a) * std::sqrt(1 + std::pow(b / a, 2));
223 }
224 inline double convertToMag(double fluxMag0, double flux) { return -2.5 * ::log10(flux / fluxMag0); }
225 
226 inline void convertToMagWithErr(double* mag, double* magErr, double fluxMag0, double fluxMag0Err, double flux,
227  double fluxErr) {
228  *mag = -2.5 * std::log10(flux / fluxMag0);
229  double const x = fluxErr / flux;
230  double const y = fluxMag0Err / fluxMag0;
231  *magErr = (2.5 / std::log(10.0)) * std::sqrt(x * x + y * y);
232 }
233 
234 } // anonymous namespace
235 
236 double Calib::getFlux(double const mag) const {
237  checkNegativeFlux0(_fluxMag0);
238  return convertToFlux(_fluxMag0, mag);
239 }
240 ndarray::Array<double, 1> Calib::getFlux(ndarray::Array<double const, 1> const& mag) const {
241  checkNegativeFlux0(_fluxMag0);
242  ndarray::Array<double, 1> flux = ndarray::allocate(mag.size());
243  ndarray::Array<double const, 1>::Iterator inIter = mag.begin();
244  ndarray::Array<double, 1>::Iterator outIter = flux.begin();
245  for (; inIter != mag.end(); ++inIter, ++outIter) {
246  *outIter = convertToFlux(_fluxMag0, *inIter);
247  }
248  return flux;
249 }
250 
251 std::pair<double, double> Calib::getFlux(double const mag, double const magSigma) const {
252  checkNegativeFlux0(_fluxMag0);
253  double const flux = convertToFlux(_fluxMag0, mag);
254  double const fluxErr = convertToFluxErr(_fluxMag0Err / _fluxMag0, flux, magSigma);
255  return std::make_pair(flux, fluxErr);
256 }
257 
259  ndarray::Array<double const, 1> const& mag, ndarray::Array<double const, 1> const& magErr) const {
260  checkNegativeFlux0(_fluxMag0);
261  if (mag.size() != magErr.size()) {
262  throw LSST_EXCEPT(
264  (boost::format("Size of mag (%d) and magErr (%d) don't match") % mag.size() % magErr.size())
265  .str());
266  }
267 
268  ndarray::Array<double, 1> flux = ndarray::allocate(mag.size());
269  ndarray::Array<double, 1> fluxErr = ndarray::allocate(mag.size());
270  ndarray::Array<double const, 1>::Iterator magIter = mag.begin();
271  ndarray::Array<double const, 1>::Iterator magErrIter = magErr.begin();
272  ndarray::Array<double, 1>::Iterator fluxIter = flux.begin();
273  ndarray::Array<double, 1>::Iterator fluxErrIter = fluxErr.begin();
274 
275  double fluxMag0InvSNR = _fluxMag0Err / _fluxMag0;
276  for (; magIter != mag.end(); ++magIter, ++magErrIter, ++fluxIter, ++fluxErrIter) {
277  *fluxIter = convertToFlux(_fluxMag0, *magIter);
278  *fluxErrIter = convertToFluxErr(fluxMag0InvSNR, *fluxIter, *magErrIter);
279  }
280 
281  return std::make_pair(flux, fluxErr);
282 }
283 
284 double Calib::getMagnitude(double const flux) const {
285  checkNegativeFlux0(_fluxMag0);
286  if (isNegativeFlux(flux, Calib::getThrowOnNegativeFlux())) {
288  }
289  return convertToMag(_fluxMag0, flux);
290 }
291 
292 std::pair<double, double> Calib::getMagnitude(double const flux, double const fluxErr) const {
293  checkNegativeFlux0(_fluxMag0);
294  if (isNegativeFlux(flux, Calib::getThrowOnNegativeFlux())) {
295  double const NaN = std::numeric_limits<double>::quiet_NaN();
296  return std::make_pair(NaN, NaN);
297  }
298 
299  double mag, magErr;
300  convertToMagWithErr(&mag, &magErr, _fluxMag0, _fluxMag0Err, flux, fluxErr);
301  return std::make_pair(mag, magErr);
302 }
303 
304 ndarray::Array<double, 1> Calib::getMagnitude(ndarray::Array<double const, 1> const& flux) const {
305  checkNegativeFlux0(_fluxMag0);
306  ndarray::Array<double, 1> mag = ndarray::allocate(flux.size());
307  ndarray::Array<double const, 1>::Iterator fluxIter = flux.begin();
308  ndarray::Array<double, 1>::Iterator magIter = mag.begin();
309  int nonPositive = 0;
310  for (; fluxIter != flux.end(); ++fluxIter, ++magIter) {
311  if (isNegativeFlux(*fluxIter, false)) {
312  ++nonPositive;
314  continue;
315  }
316  *magIter = convertToMag(_fluxMag0, *fluxIter);
317  }
318  if (nonPositive && Calib::getThrowOnNegativeFlux()) {
320  (boost::format("Flux must be >= 0: %d non-positive seen") % nonPositive).str());
321  }
322  return mag;
323 }
324 
326  ndarray::Array<double const, 1> const& flux, ndarray::Array<double const, 1> const& fluxErr) const {
327  checkNegativeFlux0(_fluxMag0);
328  if (flux.size() != fluxErr.size()) {
330  (boost::format("Size of flux (%d) and fluxErr (%d) don't match") % flux.size() %
331  fluxErr.size())
332  .str());
333  }
334 
335  ndarray::Array<double, 1> mag = ndarray::allocate(flux.size());
336  ndarray::Array<double, 1> magErr = ndarray::allocate(flux.size());
337  ndarray::Array<double const, 1>::Iterator fluxIter = flux.begin();
338  ndarray::Array<double const, 1>::Iterator fluxErrIter = fluxErr.begin();
339  ndarray::Array<double, 1>::Iterator magIter = mag.begin();
340  ndarray::Array<double, 1>::Iterator magErrIter = magErr.begin();
341  int nonPositive = 0;
342  for (; fluxIter != flux.end(); ++fluxIter, ++fluxErrIter, ++magIter, ++magErrIter) {
343  if (isNegativeFlux(*fluxIter, false)) {
344  ++nonPositive;
345  double const NaN = std::numeric_limits<double>::quiet_NaN();
346  *magIter = NaN;
347  *magErrIter = NaN;
348  continue;
349  }
350  double f, df;
351  convertToMagWithErr(&f, &df, _fluxMag0, _fluxMag0Err, *fluxIter, *fluxErrIter);
352  *magIter = f;
353  *magErrIter = df;
354  }
355  if (nonPositive && Calib::getThrowOnNegativeFlux()) {
357  (boost::format("Flux must be >= 0: %d non-positive seen") % nonPositive).str());
358  }
359  return std::make_pair(mag, magErr);
360 }
361 
362 namespace {
363 
364 int const CALIB_TABLE_CURRENT_VERSION = 2; // current version of ExposureTable
365 std::string const EXPTIME_FIELD_NAME = "exptime"; // name of exposure time field
366 
367 class CalibKeys {
368 public:
369  table::Schema schema;
370  table::Key<std::int64_t> midTime;
371  table::Key<double> expTime;
372  table::Key<double> fluxMag0;
373  table::Key<double> fluxMag0Err;
374 
375  // No copying
376  CalibKeys(const CalibKeys&) = delete;
377  CalibKeys& operator=(const CalibKeys&) = delete;
378 
379  // No moving
380  CalibKeys(CalibKeys&&) = delete;
381  CalibKeys& operator=(CalibKeys&&) = delete;
382 
383  CalibKeys(int tableVersion = CALIB_TABLE_CURRENT_VERSION)
384  : schema(), midTime(), expTime(), fluxMag0(), fluxMag0Err() {
385  if (tableVersion == 1) {
386  // obsolete fields
387  midTime = schema.addField<std::int64_t>(
388  "midtime", "middle of the time of the exposure relative to Unix epoch", "ns");
389  expTime = schema.addField<double>(EXPTIME_FIELD_NAME, "exposure time", "s");
390  }
391  fluxMag0 = schema.addField<double>("fluxmag0", "flux of a zero-magnitude object", "count");
392  fluxMag0Err = schema.addField<double>("fluxmag0.err", "1-sigma error on fluxmag0", "count");
393  }
394 };
395 
396 class CalibFactory : public table::io::PersistableFactory {
397 public:
398  std::shared_ptr<table::io::Persistable> read(InputArchive const& archive,
399  CatalogVector const& catalogs) const override {
400  // table version is not persisted, so we don't have a clean way to determine the version;
401  // the hack is version = 1 if exptime found, else current
402  int tableVersion = 1;
403  try {
404  catalogs.front().getSchema().find<double>(EXPTIME_FIELD_NAME);
405  } catch (pex::exceptions::NotFoundError) {
406  tableVersion = CALIB_TABLE_CURRENT_VERSION;
407  }
408 
409  CalibKeys const keys{tableVersion};
410  LSST_ARCHIVE_ASSERT(catalogs.size() == 1u);
411  LSST_ARCHIVE_ASSERT(catalogs.front().size() == 1u);
412  LSST_ARCHIVE_ASSERT(catalogs.front().getSchema() == keys.schema);
413  table::BaseRecord const& record = catalogs.front().front();
415  result->setFluxMag0(record.get(keys.fluxMag0), record.get(keys.fluxMag0Err));
416  return result;
417  }
418 
419  explicit CalibFactory(std::string const& name) : table::io::PersistableFactory(name) {}
420 };
421 
422 std::string getCalibPersistenceName() { return "Calib"; }
423 
424 CalibFactory registration(getCalibPersistenceName());
425 
426 } // namespace
427 
428 std::string Calib::getPersistenceName() const { return getCalibPersistenceName(); }
429 
430 void Calib::write(OutputArchiveHandle& handle) const {
431  CalibKeys const keys{};
432  table::BaseCatalog cat = handle.makeCatalog(keys.schema);
435  record->set(keys.fluxMag0, fluxMag0.first);
436  record->set(keys.fluxMag0Err, fluxMag0.second);
437  handle.saveCatalog(cat);
438 }
439 
440 Calib& Calib::operator*=(double const scale) {
441  _fluxMag0 *= scale;
442  _fluxMag0Err *= scale;
443  return *this;
444 }
445 
446 // Explicit instantiation
447 #define INSTANTIATE(TYPE) \
448  template ndarray::Array<TYPE, 1> abMagFromFlux(ndarray::Array<TYPE const, 1> const& flux); \
449  template ndarray::Array<TYPE, 1> abMagErrFromFluxErr(ndarray::Array<TYPE const, 1> const& fluxErr, \
450  ndarray::Array<TYPE const, 1> const& flux); \
451  template ndarray::Array<TYPE, 1> fluxFromABMag(ndarray::Array<TYPE const, 1> const& mag); \
452  template ndarray::Array<TYPE, 1> fluxErrFromABMagErr(ndarray::Array<TYPE const, 1> const& magErr, \
453  ndarray::Array<TYPE const, 1> const& mag);
454 
455 INSTANTIATE(float);
456 INSTANTIATE(double);
457 
458 } // namespace image
459 } // namespace afw
460 } // namespace lsst
def keys(self)
template ndarray::Array< double, 1 > abMagErrFromFluxErr(ndarray::Array< double const, 1 > const &fluxErr, ndarray::Array< double const, 1 > const &flux)
Calib() noexcept
ctor
Definition: Calib.cc:105
An object passed to Persistable::write to allow it to persist itself.
#define INSTANTIATE(TYPE)
Definition: Calib.cc:447
T swap(T... args)
T epsilon(T... args)
#define LSST_ARCHIVE_ASSERT(EXPR)
An assertion macro used to validate the structure of an InputArchive.
Definition: Persistable.h:48
T log(T... args)
static void setThrowOnNegativeFlux(bool raiseException) noexcept
Set whether Calib should throw an exception when asked to convert a flux to a magnitude.
Definition: Calib.cc:149
def scale(algorithm, min, max=None, frame=None)
Definition: ds9.py:114
double getFlux(double const mag) const
Return a flux (in ADUs) given a magnitude.
Definition: Calib.cc:236
template ndarray::Array< double, 1 > fluxFromABMag(ndarray::Array< double const, 1 > const &mag)
static std::shared_ptr< T > dynamicCast(std::shared_ptr< Persistable > const &ptr)
Dynamically cast a shared_ptr.
Definition: Persistable.cc:18
Calib & operator=(Calib const &) noexcept
table::Key< double > expTime
Definition: Calib.cc:371
static bool getThrowOnNegativeFlux() noexcept
Tell me whether Calib will throw an exception if asked to convert a flux to a magnitude.
Definition: Calib.cc:151
T log10(T... args)
Describe an exposure&#39;s calibration.
Definition: Calib.h:95
Calib & operator*=(double const scale)
Definition: Calib.cc:440
template ndarray::Array< double, 1 > abMagFromFlux(ndarray::Array< double const, 1 > const &flux)
STL class.
table::Key< std::int64_t > midTime
Definition: Calib.cc:370
table::Schema schema
Definition: Calib.cc:369
A base class for image defects.
std::string getPersistenceName() const override
Return the unique name used to persist this object and look up its factory.
Definition: Calib.cc:428
table::Key< int > b
Key< U > key
Definition: Schema.cc:280
T make_pair(T... args)
void setFluxMag0(double fluxMag0, double fluxMag0Err=0.0)
Set the flux of a zero-magnitude object.
Definition: Calib.cc:183
double x
int stripCalibKeywords(std::shared_ptr< lsst::daf::base::PropertySet > metadata)
Remove Calib-related keywords from the metadata.
Definition: Calib.cc:160
template ndarray::Array< double, 1 > fluxErrFromABMagErr(ndarray::Array< double const, 1 > const &magErr, ndarray::Array< double const, 1 > const &mag)
std::unique_ptr< SchemaItem< U > > result
Definition: Schema.cc:194
double getMagnitude(double const flux) const
Return a magnitude given a flux.
Definition: Calib.cc:284
BaseCatalog makeCatalog(Schema const &schema)
Return a new, empty catalog with the given schema.
#define LSST_EXCEPT(type,...)
STL class.
~Calib() noexcept override
table::Key< double > fluxMag0Err
Definition: Calib.cc:373
T pow(T... args)
table::Key< int > a
table::Key< double > fluxMag0
Definition: Calib.cc:372
std::pair< double, double > getFluxMag0() const
Return the flux, and error in flux, of a zero-magnitude object.
Definition: Calib.cc:192
T quiet_NaN(T... args)
T sqrt(T... args)
void saveCatalog(BaseCatalog const &catalog)
Save a catalog in the archive.
bool operator==(Calib const &rhs) const noexcept
Are two Calibs identical?
Definition: Calib.cc:179
void write(OutputArchiveHandle &handle) const override
Write the object to one or more catalogs.
Definition: Calib.cc:430
int y
Definition: SpanSet.cc:49
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