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