lsst.afw  14.0-34-g2d9284d60+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"
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 namespace detail {
151  int nstripped = 0;
152 
153  auto key = "FLUXMAG0";
154  if (metadata->exists(key)) {
155  metadata->remove(key);
156  nstripped++;
157  }
158 
159  key = "FLUXMAG0ERR";
160  if (metadata->exists(key)) {
161  metadata->remove(key);
162  nstripped++;
163  }
164 
165  return nstripped;
166 }
167 }
168 
169 bool Calib::operator==(Calib const& rhs) const {
170  return _fluxMag0 == rhs._fluxMag0 && _fluxMag0Sigma == rhs._fluxMag0Sigma;
171 }
172 
174  _fluxMag0 = fluxMag0;
175  _fluxMag0Sigma = fluxMag0Sigma;
176 }
178  _fluxMag0 = fluxMag0AndSigma.first;
179  _fluxMag0Sigma = fluxMag0AndSigma.second;
180 }
181 
182 std::pair<double, double> Calib::getFluxMag0() const { return std::make_pair(_fluxMag0, _fluxMag0Sigma); }
183 
184 namespace {
185 
186 inline void checkNegativeFlux0(double fluxMag0) {
187  if (fluxMag0 <= 0) {
189  (boost::format("Flux of 0-mag object must be >= 0: saw %g") % fluxMag0).str());
190  }
191 }
192 inline bool isNegativeFlux(double flux, bool doThrow) {
193  if (flux <= 0) {
194  if (doThrow) {
196  (boost::format("Flux must be >= 0: saw %g") % flux).str());
197  }
198  return true;
199  }
200  return false;
201 }
202 inline double convertToFlux(double fluxMag0, double mag) { return fluxMag0 * ::pow(10.0, -0.4 * mag); }
203 inline double convertToFluxErr(double fluxMag0InvSNR, double flux, double magErr) {
204  // Want to:
205  // return flux * hypot(_fluxMag0Sigma/_fluxMag0, 0.4*std::log(10)*magSigma/mag);
206  // But hypot is not standard C++ so use <http://en.wikipedia.org/wiki/Hypot#Implementation>
207  double a = fluxMag0InvSNR;
208  double b = 0.4 * std::log(10.0) * magErr;
209  if (std::abs(a) < std::abs(b)) {
210  std::swap(a, b);
211  }
212  return flux * std::abs(a) * std::sqrt(1 + std::pow(b / a, 2));
213 }
214 inline double convertToMag(double fluxMag0, double flux) { return -2.5 * ::log10(flux / fluxMag0); }
215 
216 inline void convertToMagWithErr(double* mag, double* magErr, double fluxMag0, double fluxMag0Err,
217  double flux, double fluxErr) {
218  *mag = -2.5*std::log10(flux/fluxMag0);
219  double const x = fluxErr/flux;
220  double const y = fluxMag0Err/fluxMag0;
221  *magErr = (2.5/std::log(10.0))*std::sqrt(x*x + y*y);
222 }
223 
224 } // anonymous namespace
225 
226 double Calib::getFlux(double const mag) const {
227  checkNegativeFlux0(_fluxMag0);
228  return convertToFlux(_fluxMag0, mag);
229 }
230 ndarray::Array<double, 1> Calib::getFlux(ndarray::Array<double const, 1> const& mag) const {
231  checkNegativeFlux0(_fluxMag0);
232  ndarray::Array<double, 1> flux = ndarray::allocate(mag.size());
233  ndarray::Array<double const, 1>::Iterator inIter = mag.begin();
234  ndarray::Array<double, 1>::Iterator outIter = flux.begin();
235  for (; inIter != mag.end(); ++inIter, ++outIter) {
236  *outIter = convertToFlux(_fluxMag0, *inIter);
237  }
238  return flux;
239 }
240 
241 std::pair<double, double> Calib::getFlux(double const mag, double const magSigma) const {
242  checkNegativeFlux0(_fluxMag0);
243  double const flux = convertToFlux(_fluxMag0, mag);
244  double const fluxErr = convertToFluxErr(_fluxMag0Sigma / _fluxMag0, flux, magSigma);
245  return std::make_pair(flux, fluxErr);
246 }
247 
249  ndarray::Array<double const, 1> const& mag, ndarray::Array<double const, 1> const& magErr) const {
250  checkNegativeFlux0(_fluxMag0);
251  if (mag.size() != magErr.size()) {
252  throw LSST_EXCEPT(
254  (boost::format("Size of mag (%d) and magErr (%d) don't match") % mag.size() % magErr.size())
255  .str());
256  }
257 
258  ndarray::Array<double, 1> flux = ndarray::allocate(mag.size());
259  ndarray::Array<double, 1> fluxErr = ndarray::allocate(mag.size());
260  ndarray::Array<double const, 1>::Iterator magIter = mag.begin();
261  ndarray::Array<double const, 1>::Iterator magErrIter = magErr.begin();
262  ndarray::Array<double, 1>::Iterator fluxIter = flux.begin();
263  ndarray::Array<double, 1>::Iterator fluxErrIter = fluxErr.begin();
264 
265  double fluxMag0InvSNR = _fluxMag0Sigma / _fluxMag0;
266  for (; magIter != mag.end(); ++magIter, ++magErrIter, ++fluxIter, ++fluxErrIter) {
267  *fluxIter = convertToFlux(_fluxMag0, *magIter);
268  *fluxErrIter = convertToFluxErr(fluxMag0InvSNR, *fluxIter, *magErrIter);
269  }
270 
271  return std::make_pair(flux, fluxErr);
272 }
273 
274 double Calib::getMagnitude(double const flux) const {
275  checkNegativeFlux0(_fluxMag0);
276  if (isNegativeFlux(flux, Calib::getThrowOnNegativeFlux())) {
278  }
279  return convertToMag(_fluxMag0, flux);
280 }
281 
282 std::pair<double, double> Calib::getMagnitude(double const flux, double const fluxErr) const {
283  checkNegativeFlux0(_fluxMag0);
284  if (isNegativeFlux(flux, Calib::getThrowOnNegativeFlux())) {
285  double const NaN = std::numeric_limits<double>::quiet_NaN();
286  return std::make_pair(NaN, NaN);
287  }
288 
289  double mag, magErr;
290  convertToMagWithErr(&mag, &magErr, _fluxMag0, _fluxMag0Sigma, flux, fluxErr);
291  return std::make_pair(mag, magErr);
292 }
293 
294 ndarray::Array<double, 1> Calib::getMagnitude(ndarray::Array<double const, 1> const& flux) const {
295  checkNegativeFlux0(_fluxMag0);
296  ndarray::Array<double, 1> mag = ndarray::allocate(flux.size());
297  ndarray::Array<double const, 1>::Iterator fluxIter = flux.begin();
298  ndarray::Array<double, 1>::Iterator magIter = mag.begin();
299  int nonPositive = 0;
300  for (; fluxIter != flux.end(); ++fluxIter, ++magIter) {
301  if (isNegativeFlux(*fluxIter, false)) {
302  ++nonPositive;
304  continue;
305  }
306  *magIter = convertToMag(_fluxMag0, *fluxIter);
307  }
308  if (nonPositive && Calib::getThrowOnNegativeFlux()) {
310  (boost::format("Flux must be >= 0: %d non-positive seen") % nonPositive).str());
311  }
312  return mag;
313 }
314 
316  ndarray::Array<double const, 1> const& flux, ndarray::Array<double const, 1> const& fluxErr) const {
317  checkNegativeFlux0(_fluxMag0);
318  if (flux.size() != fluxErr.size()) {
320  (boost::format("Size of flux (%d) and fluxErr (%d) don't match") % flux.size() %
321  fluxErr.size())
322  .str());
323  }
324 
325  ndarray::Array<double, 1> mag = ndarray::allocate(flux.size());
326  ndarray::Array<double, 1> magErr = ndarray::allocate(flux.size());
327  ndarray::Array<double const, 1>::Iterator fluxIter = flux.begin();
328  ndarray::Array<double const, 1>::Iterator fluxErrIter = fluxErr.begin();
329  ndarray::Array<double, 1>::Iterator magIter = mag.begin();
330  ndarray::Array<double, 1>::Iterator magErrIter = magErr.begin();
331  int nonPositive = 0;
332  for (; fluxIter != flux.end(); ++fluxIter, ++fluxErrIter, ++magIter, ++magErrIter) {
333  if (isNegativeFlux(*fluxIter, false)) {
334  ++nonPositive;
335  double const NaN = std::numeric_limits<double>::quiet_NaN();
336  *magIter = NaN;
337  *magErrIter = NaN;
338  continue;
339  }
340  double f, df;
341  convertToMagWithErr(&f, &df, _fluxMag0, _fluxMag0Sigma, *fluxIter, *fluxErrIter);
342  *magIter = f;
343  *magErrIter = df;
344  }
345  if (nonPositive && Calib::getThrowOnNegativeFlux()) {
347  (boost::format("Flux must be >= 0: %d non-positive seen") % nonPositive).str());
348  }
349  return std::make_pair(mag, magErr);
350 }
351 
352 namespace {
353 
354 int const CALIB_TABLE_CURRENT_VERSION = 2; // current version of ExposureTable
355 std::string const EXPTIME_FIELD_NAME = "exptime"; // name of exposure time field
356 
357 class CalibKeys {
358 public:
359  table::Schema schema;
360  table::Key<std::int64_t> midTime;
361  table::Key<double> expTime;
362  table::Key<double> fluxMag0;
363  table::Key<double> fluxMag0Sigma;
364 
365  // No copying
366  CalibKeys(const CalibKeys&) = delete;
367  CalibKeys& operator=(const CalibKeys&) = delete;
368 
369  // No moving
370  CalibKeys(CalibKeys&&) = delete;
371  CalibKeys& operator=(CalibKeys&&) = delete;
372 
373  CalibKeys(int tableVersion = CALIB_TABLE_CURRENT_VERSION)
374  : schema(), midTime(), expTime(), fluxMag0(), fluxMag0Sigma() {
375  if (tableVersion == 1) {
376  // obsolete fields
377  midTime = schema.addField<std::int64_t>(
378  "midtime", "middle of the time of the exposure relative to Unix epoch", "ns");
379  expTime = schema.addField<double>(EXPTIME_FIELD_NAME, "exposure time", "s");
380  }
381  fluxMag0 = schema.addField<double>("fluxmag0", "flux of a zero-magnitude object", "count");
382  fluxMag0Sigma = schema.addField<double>("fluxmag0.err", "1-sigma error on fluxmag0", "count");
383  }
384 };
385 
386 class CalibFactory : public table::io::PersistableFactory {
387 public:
388  virtual std::shared_ptr<table::io::Persistable> read(InputArchive const& archive,
389  CatalogVector const& catalogs) const {
390  // table version is not persisted, so we don't have a clean way to determine the version;
391  // the hack is version = 1 if exptime found, else current
392  int tableVersion = 1;
393  try {
394  catalogs.front().getSchema().find<double>(EXPTIME_FIELD_NAME);
395  } catch (pex::exceptions::NotFoundError) {
396  tableVersion = CALIB_TABLE_CURRENT_VERSION;
397  }
398 
399  CalibKeys const keys{tableVersion};
400  LSST_ARCHIVE_ASSERT(catalogs.size() == 1u);
401  LSST_ARCHIVE_ASSERT(catalogs.front().size() == 1u);
402  LSST_ARCHIVE_ASSERT(catalogs.front().getSchema() == keys.schema);
403  table::BaseRecord const& record = catalogs.front().front();
404  std::shared_ptr<Calib> result(new Calib());
405  result->setFluxMag0(record.get(keys.fluxMag0), record.get(keys.fluxMag0Sigma));
406  return result;
407  }
408 
409  explicit CalibFactory(std::string const& name) : table::io::PersistableFactory(name) {}
410 };
411 
412 std::string getCalibPersistenceName() { return "Calib"; }
413 
414 CalibFactory registration(getCalibPersistenceName());
415 
416 } // anonymous
417 
418 std::string Calib::getPersistenceName() const { return getCalibPersistenceName(); }
419 
420 void Calib::write(OutputArchiveHandle& handle) const {
421  CalibKeys const keys{};
422  table::BaseCatalog cat = handle.makeCatalog(keys.schema);
425  record->set(keys.fluxMag0, fluxMag0.first);
426  record->set(keys.fluxMag0Sigma, fluxMag0.second);
427  handle.saveCatalog(cat);
428 }
429 
430 Calib& Calib::operator*=(double const scale) {
431  _fluxMag0 *= scale;
432  _fluxMag0Sigma *= scale;
433  return *this;
434 }
435 
436 
437 // Explicit instantiation
438 #define INSTANTIATE(TYPE) \
439 template ndarray::Array<TYPE, 1> abMagFromFlux(ndarray::Array<TYPE const, 1> const& flux); \
440 template ndarray::Array<TYPE, 1> abMagErrFromFluxErr(ndarray::Array<TYPE const, 1> const& fluxErr, \
441  ndarray::Array<TYPE const, 1> const& flux); \
442 template ndarray::Array<TYPE, 1> fluxFromABMag(ndarray::Array<TYPE const, 1> const& mag); \
443 template ndarray::Array<TYPE, 1> fluxErrFromABMagErr(ndarray::Array<TYPE const, 1> const& magErr, \
444  ndarray::Array<TYPE const, 1> const& mag);
445 
446 INSTANTIATE(float);
447 INSTANTIATE(double);
448 
449 }
450 }
451 } // lsst::afw::image
table::Key< std::string > name
Definition: ApCorrMap.cc:71
table::Key< double > fluxMag0Sigma
Definition: Calib.cc:363
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:438
T swap(T... args)
A custom container class for records, based on std::vector.
Definition: Catalog.h:97
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:117
double getFlux(double const mag) const
Return a flux (in ADUs) given a magnitude.
Definition: Calib.cc:226
table::Key< double > expTime
Definition: Calib.cc:361
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:430
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:420
table::Key< std::int64_t > midTime
Definition: Calib.cc:360
table::Schema schema
Definition: Calib.cc:359
A base class for image defects.
void operator=(Persistable const &other)
Definition: Persistable.h:140
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
table::Key< int > b
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:150
bool operator==(Calib const &rhs) const
Are two Calibs identical?
Definition: Calib.cc:169
virtual std::string getPersistenceName() const
Return the unique name used to persist this object and look up its factory.
Definition: Calib.cc:418
double getMagnitude(double const flux) const
Return a magnitude given a flux.
Definition: Calib.cc:274
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:173
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:362
std::pair< double, double > getFluxMag0() const
Return the flux, and error in flux, of a zero-magnitude object.
Definition: Calib.cc:182
T quiet_NaN(T... args)
T sqrt(T... args)
void saveCatalog(BaseCatalog const &catalog)
Save a catalog in the archive.
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:466