LSSTApplications  11.0-13-gbb96280,12.1.rc1,12.1.rc1+1,12.1.rc1+2,12.1.rc1+5,12.1.rc1+8,12.1.rc1-1-g06d7636+1,12.1.rc1-1-g253890b+5,12.1.rc1-1-g3d31b68+7,12.1.rc1-1-g3db6b75+1,12.1.rc1-1-g5c1385a+3,12.1.rc1-1-g83b2247,12.1.rc1-1-g90cb4cf+6,12.1.rc1-1-g91da24b+3,12.1.rc1-2-g3521f8a,12.1.rc1-2-g39433dd+4,12.1.rc1-2-g486411b+2,12.1.rc1-2-g4c2be76,12.1.rc1-2-gc9c0491,12.1.rc1-2-gda2cd4f+6,12.1.rc1-3-g3391c73+2,12.1.rc1-3-g8c1bd6c+1,12.1.rc1-3-gcf4b6cb+2,12.1.rc1-4-g057223e+1,12.1.rc1-4-g19ed13b+2,12.1.rc1-4-g30492a7
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 { namespace meas { namespace base {
37 
38 ApertureFluxControl::ApertureFluxControl() : radii(10), maxSincRadius(10.0), shiftKernel("lanczos5") {
39  // defaults here stolen from HSC pipeline defaults
40  static std::array<double,10> defaultRadii = {{
41  3.0, 4.5, 6.0, 9.0, 12.0, 17.0, 25.0, 35.0, 50.0, 70.0
42  }};
43  std::copy(defaultRadii.begin(), defaultRadii.end(), radii.begin());
44 }
45 
46 std::array<FlagDefinition,ApertureFluxAlgorithm::N_FLAGS> const & ApertureFluxAlgorithm::getFlagDefinitions() {
47  static std::array<FlagDefinition,ApertureFluxAlgorithm::N_FLAGS> flagDefs = {{
48  {"flag", "general failure flag"},
49  {"flag_apertureTruncated", "aperture did not fit within measurement image"},
50  {"flag_sincCoeffsTruncated", "full sinc coefficient image did not fit within measurement image"}
51  }};
52  return flagDefs;
53 }
54 
55 std::string ApertureFluxAlgorithm::makeFieldPrefix(std::string const & name, double radius) {
56  std::string prefix = (boost::format("%s_%.1f") % name % radius).str();
57  return boost::replace_all_copy(prefix, ".", "_");
58 }
59 
61  afw::table::Schema & schema, std::string const & prefix, std::string const & doc, bool isSinc
62 ) :
63  fluxKey(FluxResultKey::addFields(schema, prefix, doc)),
64  flags(
65  FlagHandler::addFields(
66  schema, prefix,
68  ApertureFluxAlgorithm::getFlagDefinitions().begin() + (isSinc ? 3 : 2)
69  )
70  )
71 {}
72 
74  Control const & ctrl,
75  std::string const & name,
77  daf::base::PropertySet & metadata
78 
79 ) : _ctrl(ctrl),
80  _centroidExtractor(schema, name)
81 {
82  _keys.reserve(ctrl.radii.size());
83  for (std::size_t i = 0; i < ctrl.radii.size(); ++i) {
84  metadata.add(name + "_radii", ctrl.radii[i]);
85  std::string prefix = ApertureFluxAlgorithm::makeFieldPrefix(name, ctrl.radii[i]);
86  std::string doc = (boost::format("flux within %f-pixel aperture") % ctrl.radii[i]).str();
87  _keys.push_back(Keys(schema, prefix, doc, ctrl.radii[i] <= ctrl.maxSincRadius));
88  }
89 }
90 
92  // This should only get called in the case of completely unexpected failures, so it's not terrible
93  // that we just set the general failure flags for all radii here instead of trying to figure out
94  // which ones we've already done. Any known failure modes are handled inside measure().
95  for (std::size_t i = 0; i < _ctrl.radii.size(); ++i) {
96  _keys[i].flags.handleFailure(measRecord, error);
97  }
98 }
99 
101  Result const & result,
102  afw::table::SourceRecord & record,
103  int index
104 ) const {
105  record.set(_keys[index].fluxKey, result);
106  if (result.getFlag(FAILURE)) {
107  _keys[index].flags.setValue(record, FAILURE, true);
108  }
109  if (result.getFlag(APERTURE_TRUNCATED)) {
110  _keys[index].flags.setValue(record, APERTURE_TRUNCATED, true);
111  }
112  if (result.getFlag(SINC_COEFFS_TRUNCATED)) {
113  _keys[index].flags.setValue(record, SINC_COEFFS_TRUNCATED, true);
114  }
115 }
116 
117 namespace {
118 
119 // Helper function for computeSincFlux get Sinc flux coefficients, and handle cases where the coeff
120 // image needs to be clipped to fit in the measurement image
121 template <typename T>
122 CONST_PTR(afw::image::Image<T>) getSincCoeffs(
123  afw::geom::Box2I const & bbox, // measurement image bbox we need to fit inside
124  afw::geom::ellipses::Ellipse const & ellipse, // ellipse that defines the aperture
125  ApertureFluxAlgorithm::Result & result, // result object where we set flags if we do clip
126  ApertureFluxAlgorithm::Control const & ctrl // configuration
127 ) {
128  CONST_PTR(afw::image::Image<T>) cImage = SincCoeffs<T>::get(ellipse.getCore(), 0.0);
129  cImage = afw::math::offsetImage(
130  *cImage,
131  ellipse.getCenter().getX(),
132  ellipse.getCenter().getY(),
133  ctrl.shiftKernel
134  );
135  if (!bbox.contains(cImage->getBBox())) {
136  // We had to clip out at least part part of the coeff image,
137  // but since that's much larger than the aperture (and close
138  // to zero outside the aperture), it may not be a serious
139  // problem.
141  afw::geom::Box2I overlap = cImage->getBBox();
142  overlap.clip(bbox);
143  if (!overlap.contains(afw::geom::Box2I(ellipse.computeBBox()))) {
144  // The clipping was indeed serious, as we we did have to clip within
145  // the aperture; can't expect any decent answer at this point.
147  result.setFlag(ApertureFluxAlgorithm::FAILURE);
148  }
149  cImage = std::make_shared< afw::image::Image<T> >(*cImage, overlap);
150  }
151  return cImage;
152 }
153 
154 } // anonymous
155 
156 template <typename T>
158  afw::image::Image<T> const & image,
159  afw::geom::ellipses::Ellipse const & ellipse,
160  Control const & ctrl
161 ) {
162  Result result;
163  CONST_PTR(afw::image::Image<T>) cImage = getSincCoeffs<T>(image.getBBox(), ellipse, result, ctrl);
164  if (result.getFlag(APERTURE_TRUNCATED)) return result;
165  afw::image::Image<T> subImage(image, cImage->getBBox());
166  result.flux = (subImage.getArray().template asEigen<Eigen::ArrayXpr>()
167  * cImage->getArray().template asEigen<Eigen::ArrayXpr>()).sum();
168  return result;
169 }
170 
171 template <typename T>
174  afw::geom::ellipses::Ellipse const & ellipse,
175  Control const & ctrl
176 ) {
177  Result result;
178  CONST_PTR(afw::image::Image<T>) cImage = getSincCoeffs<T>(image.getBBox(), ellipse, result, ctrl);
179  if (result.getFlag(APERTURE_TRUNCATED)) return result;
181  result.flux = (subImage.getImage()->getArray().template asEigen<Eigen::ArrayXpr>()
182  * cImage->getArray().template asEigen<Eigen::ArrayXpr>()).sum();
183  result.fluxSigma = std::sqrt(
184  (subImage.getVariance()->getArray().template asEigen<Eigen::ArrayXpr>().template cast<T>()
185  * cImage->getArray().template asEigen<Eigen::ArrayXpr>().square()).sum()
186  );
187  return result;
188 }
189 
190 template <typename T>
192  afw::image::Image<T> const & image,
193  afw::geom::ellipses::Ellipse const & ellipse,
194  Control const & ctrl
195 ) {
196  Result result;
197  afw::geom::ellipses::PixelRegion region(ellipse); // behaves mostly like a Footprint
198  if (!image.getBBox().contains(region.getBBox())) {
199  result.setFlag(APERTURE_TRUNCATED);
200  result.setFlag(FAILURE);
201  return result;
202  }
203  result.flux = 0;
204  for (
205  afw::geom::ellipses::PixelRegion::Iterator spanIter = region.begin(), spanEnd = region.end();
206  spanIter != spanEnd;
207  ++spanIter
208  ) {
209  typename afw::image::Image<T>::x_iterator pixIter = image.x_at(
210  spanIter->getBeginX() - image.getX0(),
211  spanIter->getY() - image.getY0()
212  );
213  result.flux += std::accumulate(pixIter, pixIter + spanIter->getWidth(), 0.0);
214  }
215  return result;
216 }
217 
218 template <typename T>
221  afw::geom::ellipses::Ellipse const & ellipse,
222  Control const & ctrl
223 ) {
224  Result result;
225  afw::geom::ellipses::PixelRegion region(ellipse); // behaves mostly like a Footprint
226  if (!image.getBBox().contains(region.getBBox())) {
227  result.setFlag(APERTURE_TRUNCATED);
228  result.setFlag(FAILURE);
229  return result;
230  }
231  result.flux = 0.0;
232  result.fluxSigma = 0.0;
233  for (
234  afw::geom::ellipses::PixelRegion::Iterator spanIter = region.begin(), spanEnd = region.end();
235  spanIter != spanEnd;
236  ++spanIter
237  ) {
238  typename afw::image::MaskedImage<T>::Image::x_iterator pixIter = image.getImage()->x_at(
239  spanIter->getBeginX() - image.getX0(),
240  spanIter->getY() - image.getY0()
241  );
242  typename afw::image::MaskedImage<T>::Variance::x_iterator varIter = image.getVariance()->x_at(
243  spanIter->getBeginX() - image.getX0(),
244  spanIter->getY() - image.getY0()
245  );
246  result.flux += std::accumulate(pixIter, pixIter + spanIter->getWidth(), 0.0);
247  // we use this to hold variance as we accumulate...
248  result.fluxSigma += std::accumulate(varIter, varIter + spanIter->getWidth(), 0.0);
249  }
250  result.fluxSigma = std::sqrt(result.fluxSigma); // ...and switch back to sigma here.
251  return result;
252 }
253 
254 template <typename T>
256  afw::image::Image<T> const & image,
257  afw::geom::ellipses::Ellipse const & ellipse,
258  Control const & ctrl
259 ) {
260  return (afw::geom::ellipses::Axes(ellipse.getCore()).getB() <= ctrl.maxSincRadius)
261  ? computeSincFlux(image, ellipse, ctrl)
262  : computeNaiveFlux(image, ellipse, ctrl);
263 }
264 
265 template <typename T>
268  afw::geom::ellipses::Ellipse const & ellipse,
269  Control const & ctrl
270 ) {
271  return (afw::geom::ellipses::Axes(ellipse.getCore()).getB() <= ctrl.maxSincRadius)
272  ? computeSincFlux(image, ellipse, ctrl)
273  : computeNaiveFlux(image, ellipse, ctrl);
274 }
275 #define INSTANTIATE(T) \
276  template \
277  ApertureFluxAlgorithm::Result ApertureFluxAlgorithm::computeFlux( \
278  afw::image::Image<T> const &, \
279  afw::geom::ellipses::Ellipse const &, \
280  Control const & \
281  ); \
282  template \
283  ApertureFluxAlgorithm::Result ApertureFluxAlgorithm::computeFlux( \
284  afw::image::MaskedImage<T> const &, \
285  afw::geom::ellipses::Ellipse const &, \
286  Control const & \
287  ); \
288  template \
289  ApertureFluxAlgorithm::Result ApertureFluxAlgorithm::computeSincFlux( \
290  afw::image::Image<T> const &, \
291  afw::geom::ellipses::Ellipse const &, \
292  Control const & \
293  ); \
294  template \
295  ApertureFluxAlgorithm::Result ApertureFluxAlgorithm::computeSincFlux( \
296  afw::image::MaskedImage<T> const &, \
297  afw::geom::ellipses::Ellipse const &, \
298  Control const & \
299  ); \
300  template \
301  ApertureFluxAlgorithm::Result ApertureFluxAlgorithm::computeNaiveFlux( \
302  afw::image::Image<T> const &, \
303  afw::geom::ellipses::Ellipse const &, \
304  Control const & \
305  ); \
306  template \
307  ApertureFluxAlgorithm::Result ApertureFluxAlgorithm::computeNaiveFlux( \
308  afw::image::MaskedImage<T> const &, \
309  afw::geom::ellipses::Ellipse const &, \
310  Control const & \
311  )
312 
313 INSTANTIATE(float);
314 INSTANTIATE(double);
315 
317  Control const & ctrl,
318  std::string const & name,
319  afw::table::SchemaMapper & mapper
320 ) :
321  BaseTransform(name),
322  _ctrl(ctrl)
323 {
324  for (std::size_t i = 0; i < _ctrl.radii.size(); ++i) {
325  for (auto flag = ApertureFluxAlgorithm::getFlagDefinitions().begin();
327  (_ctrl.radii[i] <= _ctrl.maxSincRadius ? 3 : 2); flag++) {
328  mapper.addMapping(mapper.getInputSchema().find<afw::table::Flag>((boost::format("%s_%s") %
330  flag->name).str()).key);
331  }
334  }
335 }
336 
338  afw::table::SourceCatalog const & inputCatalog,
339  afw::table::BaseCatalog & outputCatalog,
340  afw::image::Wcs const & wcs,
341  afw::image::Calib const & calib
342 ) const {
343  checkCatalogSize(inputCatalog, outputCatalog);
344  std::vector<FluxResultKey> fluxKeys;
345  for (std::size_t i = 0; i < _ctrl.radii.size(); ++i) {
346  fluxKeys.push_back(FluxResultKey(inputCatalog.getSchema()[
348  }
349  afw::table::SourceCatalog::const_iterator inSrc = inputCatalog.begin();
350  afw::table::BaseCatalog::iterator outSrc = outputCatalog.begin();
351  {
352  // While noThrow is in scope, converting a negative flux to a magnitude
353  // returns NaN rather than throwing.
355  for (; inSrc != inputCatalog.end() && outSrc != outputCatalog.end(); ++inSrc, ++outSrc) {
356  for (std::size_t i = 0; i < _ctrl.radii.size(); ++i) {
357  FluxResult fluxResult = fluxKeys[i].get(*inSrc);
358  _magKeys[i].set(*outSrc, calib.getMagnitude(fluxResult.flux, fluxResult.fluxSigma));
359  }
360  }
361  }
362 }
363 
364 }}} // namespace lsst::meas::base
365 
Defines the fields and offsets for a table.
Definition: Schema.h:44
static std::array< FlagDefinition, ApertureFluxAlgorithm::N_FLAGS > const & getFlagDefinitions()
Definition: ApertureFlux.cc:46
virtual void fail(afw::table::SourceRecord &measRecord, MeasurementError *error=NULL) const
Definition: ApertureFlux.cc:91
ImageT::Ptr offsetImage(ImageT const &inImage, float dx, float dy, std::string const &algorithmName, unsigned int buffer)
Return an image offset by (dx, dy) using the specified algorithm.
Definition: offsetImage.cc:55
table::Key< std::string > name
Definition: ApCorrMap.cc:71
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.
x_iterator x_at(int x, int y) const
Return an x_iterator to the point (x, y) in the image.
Definition: Image.h:331
bool contains(Point2I const &point) const
Return true if the box contains the point.
Schema const getInputSchema() const
Return the input schema (copy-on-write).
Definition: SchemaMapper.h:23
A custom container class for records, based on std::vector.
Definition: Catalog.h:95
afw::table::Schema schema
Definition: GaussianPsf.cc:41
SafeCentroidExtractor _centroidExtractor
Definition: ApertureFlux.h:234
A mapping between the keys of two Schemas, used to copy data between them.
Definition: SchemaMapper.h:19
static Result computeSincFlux(afw::image::Image< T > const &image, afw::geom::ellipses::Ellipse const &ellipse, Control const &ctrl=Control())
std::vector< double > radii
&quot;Radius (in pixels) of apertures.&quot; ;
Definition: ApertureFlux.h:51
virtual void operator()(afw::table::SourceCatalog const &inputCatalog, afw::table::BaseCatalog &outputCatalog, afw::image::Wcs const &wcs, afw::image::Calib const &calib) const
_view_t::x_iterator x_iterator
An iterator for traversing the pixels in a row.
Definition: Image.h:151
geom::Box2I getBBox(ImageOrigin const origin=PARENT) const
Definition: MaskedImage.h:911
tbl::Key< int > wcs
Flux flux
Measured flux in DN.
Definition: FluxUtilities.h:38
geom::Box2I getBBox(ImageOrigin origin=PARENT) const
Definition: Image.h:379
ImagePtr getImage(bool const noThrow=false) const
Return a (Ptr to) the MaskedImage&#39;s image.
Definition: MaskedImage.h:875
Implementation of the WCS standard for a any projection.
Definition: Wcs.h:107
std::array< FlagDefinition, BlendednessAlgorithm::N_FLAGS > const & getFlagDefinitions()
Definition: Blendedness.cc:215
#define CONST_PTR(...)
Definition: base.h:47
Exception to be thrown when a measurement algorithm experiences a known failure mode.
Definition: exceptions.h:48
double maxSincRadius
&quot;Maximum radius (in pixels) for which the sinc algorithm should be used instead of the &quot; &quot;faster naiv...
Definition: ApertureFlux.h:57
int getX0() const
Definition: Image.h:249
An integer coordinate rectangle.
Definition: Box.h:53
FluxErrElement fluxSigma
1-Sigma error (sqrt of variance) on flux in DN.
Definition: FluxUtilities.h:39
VariancePtr getVariance(bool const noThrow=false) const
Return a (Ptr to) the MaskedImage&#39;s variance.
Definition: MaskedImage.h:896
table::Key< table::Array< Kernel::Pixel > > image
Definition: FixedKernel.cc:117
def error
Definition: log.py:103
ApertureFluxTransform(Control const &ctrl, std::string const &name, afw::table::SchemaMapper &mapper)
Custom catalog class for record/table subclasses that are guaranteed to have an ID, and should generally be sorted by that ID.
Definition: fwd.h:55
An ellipse defined by an arbitrary BaseCore and a center point.
Definition: Ellipse.h:50
bool getFlag(ApertureFluxAlgorithm::FlagBits bit) const
Return the flag value associated with the given bit.
Definition: ApertureFlux.h:257
Iterator class for CatalogT.
Definition: Catalog.h:35
A class to manipulate images, masks, and variance as a single object.
Definition: MaskedImage.h:78
if(width!=gim.getWidth()||height!=gim.getHeight()||x0!=gim.getX0()||y0!=gim.getY0())
Definition: saturated.cc:47
Schema & editOutputSchema()
Return a reference to the output schema that allows it to be modified in place.
Definition: SchemaMapper.h:29
Box2I const & getBBox() const
Definition: PixelRegion.h:45
void copyResultToRecord(Result const &result, afw::table::SourceRecord &record, int index) const
A FunctorKey for FluxResult.
Definition: FluxUtilities.h:56
static MagResultKey addFields(afw::table::Schema &schema, std::string const &name)
BaseCore const & getCore() const
Return the ellipse core.
Definition: Ellipse.h:75
ApertureFluxAlgorithm(Control const &ctrl, std::string const &name, afw::table::Schema &schema, daf::base::PropertySet &metadata)
Definition: ApertureFlux.cc:73
static std::string makeFieldPrefix(std::string const &name, double radius)
Definition: ApertureFlux.cc:55
#define INSTANTIATE(T)
An ellipse core for the semimajor/semiminor axis and position angle parametrization (a...
Definition: Axes.h:45
void setFlag(ApertureFluxAlgorithm::FlagBits bit, bool value=true)
Set the flag value associated with the given bit.
Definition: ApertureFlux.h:260
Class for storing generic metadata.
Definition: PropertySet.h:82
Keys(afw::table::Schema &schema, std::string const &prefix, std::string const &doc, bool isSinc)
Definition: ApertureFlux.cc:60
int getWidth() const
Return the number of columns in the image.
Definition: MaskedImage.h:907
void set(Key< T > const &key, U const &value)
Set value of a field for the given key.
Definition: BaseRecord.h:145
std::vector< MagResultKey > _magKeys
Definition: ApertureFlux.h:294
Record class that contains measurements made on a single exposure.
Definition: Source.h:80
void clip(Box2I const &other)
Shrink this to ensure that other.contains(*this).
SchemaItem< T > find(std::string const &name) const
Find a SchemaItem in the Schema by name.
void checkCatalogSize(afw::table::BaseCatalog const &cat1, afw::table::BaseCatalog const &cat2) const
Ensure that catalogs have the same size.
Definition: Transform.h:101
static Result computeNaiveFlux(afw::image::Image< T > const &image, afw::geom::ellipses::Ellipse const &ellipse, Control const &ctrl=Control())
void add(std::string const &name, T const &value)
Definition: PropertySet.cc:619
int getWidth() const
Return the number of columns in the image.
Definition: Image.h:239
A class to represent a 2-dimensional array of pixels.
Definition: PSF.h:43
Schema getSchema() const
Return the schema associated with the catalog&#39;s table.
Definition: Catalog.h:115
A reusable result struct for flux measurements.
Definition: FluxUtilities.h:37
static Result computeFlux(afw::image::Image< T > const &image, afw::geom::ellipses::Ellipse const &ellipse, Control const &ctrl=Control())
int getY0() const
Definition: Image.h:257
double getMagnitude(double const flux) const
Definition: Calib.cc:397