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