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