LSSTApplications  18.1.0
LSSTDataManagementBasePackage
ApertureFlux.cc
Go to the documentation of this file.
1 // -*- lsst-c++ -*-
2 /*
3  * LSST Data Management System
4  * Copyright 2008-2016 AURA/LSST.
5  *
6  * This product includes software developed by the
7  * LSST Project (http://www.lsst.org/).
8  *
9  * This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the LSST License Statement and
20  * the GNU General Public License along with this program. If not,
21  * see <http://www.lsstcorp.org/LegalNotices/>.
22  */
23 
24 #include <numeric>
25 
26 #include "boost/algorithm/string/replace.hpp"
27 
28 #include "ndarray/eigen.h"
29 
32 #include "lsst/afw/table/Source.h"
35 
36 namespace lsst {
37 namespace meas {
38 namespace base {
39 namespace {
40 FlagDefinitionList flagDefinitions;
41 } // namespace
42 
43 FlagDefinition const ApertureFluxAlgorithm::FAILURE = flagDefinitions.addFailureFlag();
44 FlagDefinition const ApertureFluxAlgorithm::APERTURE_TRUNCATED =
45  flagDefinitions.add("flag_apertureTruncated", "aperture did not fit within measurement image");
46 FlagDefinition const ApertureFluxAlgorithm::SINC_COEFFS_TRUNCATED = flagDefinitions.add(
47  "flag_sincCoeffsTruncated", "full sinc coefficient image did not fit within measurement image");
48 
50 
51 ApertureFluxControl::ApertureFluxControl() : radii(10), maxSincRadius(10.0), shiftKernel("lanczos5") {
52  // defaults here stolen from HSC pipeline defaults
53  static std::array<double, 10> defaultRadii = {{3.0, 4.5, 6.0, 9.0, 12.0, 17.0, 25.0, 35.0, 50.0, 70.0}};
54  std::copy(defaultRadii.begin(), defaultRadii.end(), radii.begin());
55 }
56 
58  std::string prefix = (boost::format("%s_%.1f") % name % radius).str();
59  return boost::replace_all_copy(prefix, ".", "_");
60 }
61 
62 ApertureFluxAlgorithm::Keys::Keys(afw::table::Schema &schema, std::string const &prefix,
63  std::string const &doc, bool isSinc)
64  : instFluxKey(FluxResultKey::addFields(schema, prefix, doc)),
65  flags(
66  // The exclusion List can either be empty, or constain the sinc coeffs flag
69  isSinc ? FlagDefinitionList() : FlagDefinitionList({{SINC_COEFFS_TRUNCATED}}))) {}
70 
73 
74  )
75  : _ctrl(ctrl), _centroidExtractor(schema, name) {
76  _keys.reserve(ctrl.radii.size());
77  for (std::size_t i = 0; i < ctrl.radii.size(); ++i) {
78  metadata.add(name + "_radii", ctrl.radii[i]);
80  std::string doc = (boost::format("instFlux within %f-pixel aperture") % ctrl.radii[i]).str();
81  _keys.push_back(Keys(schema, prefix, doc, ctrl.radii[i] <= ctrl.maxSincRadius));
82  }
83 }
84 
86  // This should only get called in the case of completely unexpected failures, so it's not terrible
87  // that we just set the general failure flags for all radii here instead of trying to figure out
88  // which ones we've already done. Any known failure modes are handled inside measure().
89  for (std::size_t i = 0; i < _ctrl.radii.size(); ++i) {
90  _keys[i].flags.handleFailure(measRecord, error);
91  }
92 }
93 
95  int index) const {
96  record.set(_keys[index].instFluxKey, result);
97  if (result.getFlag(FAILURE.number)) {
98  _keys[index].flags.setValue(record, FAILURE.number, true);
99  }
100  if (result.getFlag(APERTURE_TRUNCATED.number)) {
101  _keys[index].flags.setValue(record, APERTURE_TRUNCATED.number, true);
102  }
103  if (result.getFlag(SINC_COEFFS_TRUNCATED.number)) {
104  _keys[index].flags.setValue(record, SINC_COEFFS_TRUNCATED.number, true);
105  }
106 }
107 
108 namespace {
109 
110 // Helper function for computeSincFlux get Sinc instFlux coefficients, and handle cases where the coeff
111 // image needs to be clipped to fit in the measurement image
112 template <typename T>
114 getSincCoeffs(geom::Box2I const &bbox, // measurement image bbox we need to fit inside
115  afw::geom::ellipses::Ellipse const &ellipse, // ellipse that defines the aperture
116  ApertureFluxAlgorithm::Result &result, // result object where we set flags if we do clip
117  ApertureFluxAlgorithm::Control const &ctrl // configuration
118 ) {
119  CONST_PTR(afw::image::Image<T>) cImage = SincCoeffs<T>::get(ellipse.getCore(), 0.0);
120  cImage = afw::math::offsetImage(*cImage, ellipse.getCenter().getX(), ellipse.getCenter().getY(),
121  ctrl.shiftKernel);
122  if (!bbox.contains(cImage->getBBox())) {
123  // We had to clip out at least part part of the coeff image,
124  // but since that's much larger than the aperture (and close
125  // to zero outside the aperture), it may not be a serious
126  // problem.
127  result.setFlag(ApertureFluxAlgorithm::SINC_COEFFS_TRUNCATED.number);
128  geom::Box2I overlap = cImage->getBBox();
129  overlap.clip(bbox);
130  if (!overlap.contains(geom::Box2I(ellipse.computeBBox()))) {
131  // The clipping was indeed serious, as we we did have to clip within
132  // the aperture; can't expect any decent answer at this point.
133  result.setFlag(ApertureFluxAlgorithm::APERTURE_TRUNCATED.number);
134  result.setFlag(ApertureFluxAlgorithm::FAILURE.number);
135  }
136  cImage = std::make_shared<afw::image::Image<T> >(*cImage, overlap);
137  }
138  return cImage;
139 }
140 
141 } // namespace
142 
143 template <typename T>
146  Result result;
147  CONST_PTR(afw::image::Image<T>) cImage = getSincCoeffs<T>(image.getBBox(), ellipse, result, ctrl);
148  if (result.getFlag(APERTURE_TRUNCATED.number)) return result;
149  afw::image::Image<T> subImage(image, cImage->getBBox());
150  result.instFlux =
151  (ndarray::asEigenArray(subImage.getArray()) * ndarray::asEigenArray(cImage->getArray())).sum();
152  return result;
153 }
154 
155 template <typename T>
158  Control const &ctrl) {
159  Result result;
160  CONST_PTR(afw::image::Image<T>) cImage = getSincCoeffs<T>(image.getBBox(), ellipse, result, ctrl);
161  if (result.getFlag(APERTURE_TRUNCATED.number)) return result;
163  result.instFlux = (ndarray::asEigenArray(subImage.getImage()->getArray()) *
164  ndarray::asEigenArray(cImage->getArray()))
165  .sum();
166  result.instFluxErr =
167  std::sqrt((ndarray::asEigenArray(subImage.getVariance()->getArray()).template cast<T>() *
168  ndarray::asEigenArray(cImage->getArray()).square())
169  .sum());
170  return result;
171 }
172 
173 template <typename T>
176  Result result;
177  afw::geom::ellipses::PixelRegion region(ellipse); // behaves mostly like a Footprint
178  if (!image.getBBox().contains(region.getBBox())) {
180  result.setFlag(FAILURE.number);
181  return result;
182  }
183  result.instFlux = 0;
184  for (afw::geom::ellipses::PixelRegion::Iterator spanIter = region.begin(), spanEnd = region.end();
185  spanIter != spanEnd; ++spanIter) {
186  typename afw::image::Image<T>::x_iterator pixIter =
187  image.x_at(spanIter->getBeginX() - image.getX0(), spanIter->getY() - image.getY0());
188  result.instFlux += std::accumulate(pixIter, pixIter + spanIter->getWidth(), 0.0);
189  }
190  return result;
191 }
192 
193 template <typename T>
196  Control const &ctrl) {
197  Result result;
198  afw::geom::ellipses::PixelRegion region(ellipse); // behaves mostly like a Footprint
199  if (!image.getBBox().contains(region.getBBox())) {
201  result.setFlag(FAILURE.number);
202  return result;
203  }
204  result.instFlux = 0.0;
205  result.instFluxErr = 0.0;
206  for (afw::geom::ellipses::PixelRegion::Iterator spanIter = region.begin(), spanEnd = region.end();
207  spanIter != spanEnd; ++spanIter) {
208  typename afw::image::MaskedImage<T>::Image::x_iterator pixIter = image.getImage()->x_at(
209  spanIter->getBeginX() - image.getX0(), spanIter->getY() - image.getY0());
210  typename afw::image::MaskedImage<T>::Variance::x_iterator varIter = image.getVariance()->x_at(
211  spanIter->getBeginX() - image.getX0(), spanIter->getY() - image.getY0());
212  result.instFlux += std::accumulate(pixIter, pixIter + spanIter->getWidth(), 0.0);
213  // we use this to hold variance as we accumulate...
214  result.instFluxErr += std::accumulate(varIter, varIter + spanIter->getWidth(), 0.0);
215  }
216  result.instFluxErr = std::sqrt(result.instFluxErr); // ...and switch back to sigma here.
217  return result;
218 }
219 
220 template <typename T>
223  Control const &ctrl) {
224  return (afw::geom::ellipses::Axes(ellipse.getCore()).getB() <= ctrl.maxSincRadius)
225  ? computeSincFlux(image, ellipse, ctrl)
226  : computeNaiveFlux(image, ellipse, ctrl);
227 }
228 
229 template <typename T>
232  Control const &ctrl) {
233  return (afw::geom::ellipses::Axes(ellipse.getCore()).getB() <= ctrl.maxSincRadius)
234  ? computeSincFlux(image, ellipse, ctrl)
235  : computeNaiveFlux(image, ellipse, ctrl);
236 }
237 #define INSTANTIATE(T) \
238  template ApertureFluxAlgorithm::Result ApertureFluxAlgorithm::computeFlux( \
239  afw::image::Image<T> const &, afw::geom::ellipses::Ellipse const &, Control const &); \
240  template ApertureFluxAlgorithm::Result ApertureFluxAlgorithm::computeFlux( \
241  afw::image::MaskedImage<T> const &, afw::geom::ellipses::Ellipse const &, Control const &); \
242  template ApertureFluxAlgorithm::Result ApertureFluxAlgorithm::computeSincFlux( \
243  afw::image::Image<T> const &, afw::geom::ellipses::Ellipse const &, Control const &); \
244  template ApertureFluxAlgorithm::Result ApertureFluxAlgorithm::computeSincFlux( \
245  afw::image::MaskedImage<T> const &, afw::geom::ellipses::Ellipse const &, Control const &); \
246  template ApertureFluxAlgorithm::Result ApertureFluxAlgorithm::computeNaiveFlux( \
247  afw::image::Image<T> const &, afw::geom::ellipses::Ellipse const &, Control const &); \
248  template ApertureFluxAlgorithm::Result ApertureFluxAlgorithm::computeNaiveFlux( \
249  afw::image::MaskedImage<T> const &, afw::geom::ellipses::Ellipse const &, Control const &)
250 
251 INSTANTIATE(float);
252 INSTANTIATE(double);
253 
256  : BaseTransform(name), _ctrl(ctrl) {
257  for (std::size_t i = 0; i < _ctrl.radii.size(); ++i) {
260  if (_ctrl.radii[i] > _ctrl.maxSincRadius &&
261  flag == ApertureFluxAlgorithm::SINC_COEFFS_TRUNCATED) {
262  continue;
263  }
264  mapper.addMapping(
265  mapper.getInputSchema()
266  .find<afw::table::Flag>(
267  (boost::format("%s_%s") %
268  ApertureFluxAlgorithm::makeFieldPrefix(name, _ctrl.radii[i]) % flag.name)
269  .str())
270  .key);
271  }
272  _magKeys.push_back(MagResultKey::addFields(
274  }
275 }
276 
278  afw::table::BaseCatalog &outputCatalog, afw::geom::SkyWcs const &wcs,
279  afw::image::PhotoCalib const &photoCalib) const {
280  checkCatalogSize(inputCatalog, outputCatalog);
281  std::vector<FluxResultKey> instFluxKeys;
282  for (std::size_t i = 0; i < _ctrl.radii.size(); ++i) {
283  instFluxKeys.push_back(FluxResultKey(
284  inputCatalog.getSchema()[ApertureFluxAlgorithm::makeFieldPrefix(_name, _ctrl.radii[i])]));
285  }
286  afw::table::SourceCatalog::const_iterator inSrc = inputCatalog.begin();
287  afw::table::BaseCatalog::iterator outSrc = outputCatalog.begin();
288  {
289  for (; inSrc != inputCatalog.end() && outSrc != outputCatalog.end(); ++inSrc, ++outSrc) {
290  for (std::size_t i = 0; i < _ctrl.radii.size(); ++i) {
291  FluxResult instFluxResult = instFluxKeys[i].get(*inSrc);
292  _magKeys[i].set(*outSrc, photoCalib.instFluxToMagnitude(instFluxResult.instFlux,
293  instFluxResult.instFluxErr));
294  }
295  }
296  }
297 }
298 
299 } // namespace base
300 } // namespace meas
301 } // namespace lsst
std::size_t size() const
return the current size (number of defined elements) of the collection
Definition: FlagHandler.h:125
Defines the fields and offsets for a table.
Definition: Schema.h:50
VariancePtr getVariance() const
Return a (shared_ptr to) the MaskedImage&#39;s variance.
Definition: MaskedImage.h:1091
lsst::geom::Point2D const & getCenter() const
Return the center point.
Definition: Ellipse.h:62
lsst::geom::Box2I const & getBBox() const
Definition: PixelRegion.h:45
static boost::shared_ptr< CoeffT const > get(afw::geom::ellipses::Axes const &outerEllipse, float const innerRadiusFactor=0.0)
Get the coefficients for an aperture.
Definition: SincCoeffs.cc:506
T copy(T... args)
A 2-dimensional celestial WCS that transform pixels to ICRS RA/Dec, using the LSST standard for pixel...
Definition: SkyWcs.h:117
virtual void fail(afw::table::SourceRecord &measRecord, MeasurementError *error=nullptr) const
Handle an exception thrown by the current algorithm by setting flags in the given record...
Definition: ApertureFlux.cc:85
bool getFlag(unsigned int index) const
Return the flag value associated with the given bit.
Definition: ApertureFlux.h:219
void setFlag(unsigned int index, bool value=true)
Set the flag value associated with the given bit.
Definition: ApertureFlux.h:227
#define INSTANTIATE(T)
The photometric calibration of an exposure.
Definition: PhotoCalib.h:116
Schema const getInputSchema() const
Return the input schema (copy-on-write).
Definition: SchemaMapper.h:24
static FlagDefinitionList const & getFlagDefinitions()
Definition: ApertureFlux.cc:49
A mapping between the keys of two Schemas, used to copy data between them.
Definition: SchemaMapper.h:21
Simple class used to define and document flags The name and doc constitute the identity of the FlagDe...
Definition: FlagHandler.h:40
py::object result
Definition: schema.cc:418
_view_t::x_iterator x_iterator
An iterator for traversing the pixels in a row.
Definition: ImageBase.h:134
double instFluxToMagnitude(double instFlux, lsst::geom::Point< double, 2 > const &point) const
Convert instFlux in ADU to AB magnitude.
Definition: PhotoCalib.cc:187
BaseCore const & getCore() const
Return the ellipse core.
Definition: Ellipse.h:71
ApertureFluxAlgorithm(Control const &ctrl, std::string const &name, afw::table::Schema &schema, daf::base::PropertySet &metadata)
Construct the algorithm and add its fields to the given Schema.
Definition: ApertureFlux.cc:71
#define CONST_PTR(...)
A shared pointer to a const object.
Definition: base.h:47
T end(T... args)
std::string prefix
Definition: SchemaMapper.cc:79
void copyResultToRecord(Result const &result, afw::table::SourceRecord &record, int index) const
Definition: ApertureFlux.cc:94
int getX0() const
Return the image&#39;s column-origin.
Definition: ImageBase.h:324
meas::base::FluxErrElement instFluxErr
Standard deviation of instFlux in DN.
Definition: FluxUtilities.h:43
Exception to be thrown when a measurement algorithm experiences a known failure mode.
Definition: exceptions.h:48
static FluxResultKey addFields(afw::table::Schema &schema, std::string const &name, std::string const &doc)
Add a pair of _instFlux, _instFluxErr fields to a Schema, and return a FluxResultKey that points to t...
table::Key< table::Array< std::uint8_t > > wcs
Definition: SkyWcs.cc:71
ImagePtr getImage() const
Return a (shared_ptr to) the MaskedImage&#39;s image.
Definition: MaskedImage.h:1058
Configuration object for multiple-aperture flux algorithms.
Definition: ApertureFlux.h:49
STL class.
T push_back(T... args)
SchemaItem< T > find(std::string const &name) const
Find a SchemaItem in the Schema by name.
Definition: Schema.cc:656
static FlagDefinition const FAILURE
Definition: ApertureFlux.h:85
A base class for image defects.
static FlagDefinition const APERTURE_TRUNCATED
Definition: ApertureFlux.h:86
lsst::geom::Box2I getBBox(ImageOrigin origin=PARENT) const
Definition: ImageBase.h:463
int getX0() const
Return the image&#39;s column-origin.
Definition: MaskedImage.h:1106
static Result computeFlux(afw::image::Image< T > const &image, afw::geom::ellipses::Ellipse const &ellipse, Control const &ctrl=Control())
Compute the instFlux (and optionally, uncertanties) within an aperture using the algorithm determined...
iterator end()
Iterator access.
Definition: Catalog.h:397
An ellipse defined by an arbitrary BaseCore and a center point.
Definition: Ellipse.h:51
double maxSincRadius
"Maximum radius (in pixels) for which the sinc algorithm should be used instead of the " "faster naiv...
Definition: ApertureFlux.h:58
static std::string makeFieldPrefix(std::string const &name, double radius)
Construct an appropriate prefix for table fields.
Definition: ApertureFlux.cc:57
static FlagDefinition const SINC_COEFFS_TRUNCATED
Definition: ApertureFlux.h:87
Iterator class for CatalogT.
Definition: Catalog.h:38
def format(config, name=None, writeSourceLine=True, prefix="", verbose=False)
Definition: history.py:168
A class to manipulate images, masks, and variance as a single object.
Definition: MaskedImage.h:74
lsst::geom::Box2D computeBBox() const
Return the bounding box of the ellipse.
Definition: Ellipse.cc:55
static Result computeNaiveFlux(afw::image::Image< T > const &image, afw::geom::ellipses::Ellipse const &ellipse, Control const &ctrl=Control())
Compute the instFlux (and optionally, uncertanties) within an aperture using naive photometry...
table::Schema schema
Definition: Camera.cc:161
Schema & editOutputSchema()
Return a reference to the output schema that allows it to be modified in place.
Definition: SchemaMapper.h:30
table::Box2IKey bbox
Definition: Detector.cc:169
A FunctorKey for FluxResult.
Definition: FluxUtilities.h:59
virtual void operator()(afw::table::SourceCatalog const &inputCatalog, afw::table::BaseCatalog &outputCatalog, afw::geom::SkyWcs const &wcs, afw::image::PhotoCalib const &photoCalib) const
static FlagHandler addFields(afw::table::Schema &schema, std::string const &prefix, FlagDefinitionList const &flagDefs, FlagDefinitionList const &exclDefs=FlagDefinitionList::getEmptyList())
Add Flag fields to a schema, creating a FlagHandler object to manage them.
Definition: FlagHandler.cc:37
int getY0() const
Return the image&#39;s row-origin.
Definition: MaskedImage.h:1114
static MagResultKey addFields(afw::table::Schema &schema, std::string const &name)
Add a pair of _mag, _magErr fields to a Schema, and return a MagResultKey that points to them...
T size(T... args)
STL class.
An ellipse core for the semimajor/semiminor axis and position angle parametrization (a...
Definition: Axes.h:47
int getY0() const
Return the image&#39;s row-origin.
Definition: ImageBase.h:332
std::shared_ptr< ImageT > offsetImage(ImageT const &image, float dx, float dy, std::string const &algorithmName="lanczos5", unsigned int buffer=0)
Return an image offset by (dx, dy) using the specified algorithm.
Definition: offsetImage.cc:41
T begin(T... args)
Key< U > key
Definition: Schema.cc:281
bool contains(Point2I const &point) const noexcept
Return true if the box contains the point.
Definition: Box.cc:117
Class for storing generic metadata.
Definition: PropertySet.h:68
int getWidth() const
Return the number of columns in the image.
Definition: ImageBase.h:314
Abstract base class for all C++ measurement transformations.
Definition: Transform.h:86
void clip(Box2I const &other) noexcept
Shrink this to ensure that other.contains(*this).
Definition: Box.cc:194
static Result computeSincFlux(afw::image::Image< T > const &image, afw::geom::ellipses::Ellipse const &ellipse, Control const &ctrl=Control())
Compute the instFlux (and optionally, uncertanties) within an aperture using Sinc photometry...
STL class.
x_iterator x_at(int x, int y) const
Return an x_iterator to the point (x, y) in the image.
Definition: ImageBase.h:425
void set(Key< T > const &key, U const &value)
Set value of a field for the given key.
Definition: BaseRecord.h:164
int getWidth() const
Return the number of columns in the image.
Definition: MaskedImage.h:1094
void checkCatalogSize(afw::table::BaseCatalog const &cat1, afw::table::BaseCatalog const &cat2) const
Ensure that catalogs have the same size.
Definition: Transform.h:102
Record class that contains measurements made on a single exposure.
Definition: Source.h:82
meas::base::Flux instFlux
Measured instFlux in DN.
Definition: FluxUtilities.h:42
T sqrt(T... args)
Key< T > addMapping(Key< T > const &inputKey, bool doReplace=false)
Add a new field to the output Schema that is a copy of a field in the input Schema.
std::string shiftKernel
"Warping kernel used to shift Sinc photometry coefficients to different center positions" ; ...
Definition: ApertureFlux.h:62
T accumulate(T... args)
Backwards-compatibility support for depersisting the old Calib (FluxMag0/FluxMag0Err) objects...
std::vector< double > radii
"Radius (in pixels) of apertures." ;
Definition: ApertureFlux.h:53
iterator begin()
Iterator access.
Definition: Catalog.h:396
vector-type utility class to build a collection of FlagDefinitions
Definition: FlagHandler.h:60
void add(std::string const &name, T const &value)
Append a single value to the vector of values for a property name (possibly hierarchical).
lsst::geom::Box2I getBBox(ImageOrigin const origin=PARENT) const
Definition: MaskedImage.h:1098
An integer coordinate rectangle.
Definition: Box.h:54
A class to represent a 2-dimensional array of pixels.
Definition: Image.h:59
ApertureFluxTransform(Control const &ctrl, std::string const &name, afw::table::SchemaMapper &mapper)
A reusable result struct for instFlux measurements.
Definition: FluxUtilities.h:41
SchemaMapper * mapper
Definition: SchemaMapper.cc:78
T reserve(T... args)
A Result struct for running an aperture flux algorithm with a single radius.
Definition: ApertureFlux.h:217