lsst.meas.base  14.0-21-gb9e430a+6
PsfFlux.cc
Go to the documentation of this file.
1 
2 // -*- lsst-c++ -*-
3 /*
4  * LSST Data Management System
5  * Copyright 2008-2015 AURA/LSST.
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 #include <array>
26 #include <cmath>
27 
28 #include "ndarray/eigen.h"
29 
30 #include "lsst/afw/table/Source.h"
31 #include "lsst/afw/detection/Psf.h"
32 #include "lsst/log/Log.h"
33 #include "lsst/afw/geom/SpanSet.h"
34 #include "lsst/meas/base/PsfFlux.h"
35 
36 namespace lsst { namespace meas { namespace base {
37 namespace {
38 FlagDefinitionList flagDefinitions;
39 } // end anonymous
40 
41 FlagDefinition const PsfFluxAlgorithm::FAILURE = flagDefinitions.addFailureFlag();
42 FlagDefinition const PsfFluxAlgorithm::NO_GOOD_PIXELS = flagDefinitions.add("flag_noGoodPixels", "not enough non-rejected pixels in data to attempt the fit");
43 FlagDefinition const PsfFluxAlgorithm::EDGE = flagDefinitions.add("flag_edge", "object was too close to the edge of the image to use the full PSF model");
44 
46  return flagDefinitions;
47 }
48 
49 
50 namespace {
51 
52 
53 } // anonymous
54 
56  Control const & ctrl,
57  std::string const & name,
58  afw::table::Schema & schema,
59  std::string const & logName
60 ) : _ctrl(ctrl),
61  _fluxResultKey(
62  FluxResultKey::addFields(schema, name, "flux derived from linear least-squares fit of PSF model")
63  ),
64  _areaKey(schema.addField<float>(name + "_area", "effective area of PSF", "pixel")),
65  _centroidExtractor(schema, name)
66 {
67  _logName = logName.size() ? logName : name;
68  _flagHandler = FlagHandler::addFields(schema, name,
70 }
71 
73  afw::table::SourceRecord & measRecord,
74  afw::image::Exposure<float> const & exposure
75 ) const {
76  PTR(afw::detection::Psf const) psf = exposure.getPsf();
77  if (!psf) {
78  LOGL_ERROR(getLogName(), "PsfFlux: no psf attached to exposure");
79  throw LSST_EXCEPT(
81  "PsfFlux algorithm requires a Psf with every exposure"
82  );
83  }
84  afw::geom::Point2D position = _centroidExtractor(measRecord, _flagHandler);
85  PTR(afw::detection::Psf::Image) psfImage = psf->computeImage(position);
86  afw::geom::Box2I fitBBox = psfImage->getBBox();
87  fitBBox.clip(exposure.getBBox());
88  if (fitBBox != psfImage->getBBox()) {
89  _flagHandler.setValue(measRecord, FAILURE.number, true); // if we had a suspect flag, we'd set that instead
90  _flagHandler.setValue(measRecord, EDGE.number, true);
91  }
92  auto fitRegionSpans = std::make_shared<afw::geom::SpanSet>(fitBBox);
93  afw::detection::Footprint fitRegion(fitRegionSpans);
94  if (!_ctrl.badMaskPlanes.empty()) {
95  afw::image::MaskPixel badBits = 0x0;
96  for (
98  i != _ctrl.badMaskPlanes.end();
99  ++i
100  ) {
101  badBits |= exposure.getMaskedImage().getMask()->getPlaneBitMask(*i);
102  }
103  fitRegion.setSpans(fitRegion.getSpans()->intersectNot(*exposure.getMaskedImage().getMask(),
104  badBits)->clippedTo(exposure.getMaskedImage().getMask()->getBBox()));
105  }
106  if (fitRegion.getArea() == 0) {
107  throw LSST_EXCEPT(
111  );
112  }
113  typedef afw::detection::Psf::Pixel PsfPixel;
115  ndarray::EigenView<PsfPixel,1,1,Eigen::ArrayXpr> model(
116  fitRegion.getSpans()->flatten(psfImage->getArray(), psfImage->getXY0())
117  );
118  ndarray::EigenView<float,1,1,Eigen::ArrayXpr> data(
119  fitRegion.getSpans()->flatten(exposure.getMaskedImage().getImage()->getArray(), exposure.getXY0())
120  );
121  ndarray::EigenView<VarPixel,1,1,Eigen::ArrayXpr> variance(
122  fitRegion.getSpans()->flatten(exposure.getMaskedImage().getVariance()->getArray(),
123  exposure.getXY0())
124  );
125  PsfPixel alpha = model.matrix().squaredNorm();
126  FluxResult result;
127  result.flux = model.matrix().dot(data.matrix().cast<PsfPixel>()) / alpha;
128  // If we're not using per-pixel weights to compute the flux, we'll still want to compute the
129  // variance as if we had, so we'll apply the weights to the model vector now, and update alpha.
130  result.fluxSigma = std::sqrt(model.square().matrix().dot(variance.matrix().cast<PsfPixel>()))
131  / alpha;
132  measRecord.set(_areaKey, model.matrix().sum() / alpha);
133  if (!std::isfinite(result.flux) || !std::isfinite(result.fluxSigma)) {
134  throw LSST_EXCEPT(PixelValueError, "Invalid pixel value detected in image.");
135  }
136  measRecord.set(_fluxResultKey, result);
137 }
138 
140  _flagHandler.handleFailure(measRecord, error);
141 }
142 
144  Control const & ctrl,
145  std::string const & name,
146  afw::table::SchemaMapper & mapper
147 ) :
148  FluxTransform{name, mapper}
149 {
150  for (std::size_t i = 0; i < PsfFluxAlgorithm::getFlagDefinitions().size(); i++) {
152  if (flag == PsfFluxAlgorithm::FAILURE) continue;
153  if (mapper.getInputSchema().getNames().count(
154  mapper.getInputSchema().join(name, flag.name)) == 0) continue;
155  afw::table::Key<afw::table::Flag> key = mapper.getInputSchema().find<afw::table::Flag>(
156  name + "_" + flag.name).key;
157  mapper.addMapping(key);
158  }
159 }
160 
161 }}} // namespace lsst::meas::base
std::size_t size() const
return the current size (number of defined elements) of the collection
Definition: FlagHandler.h:133
std::vector< std::string > badMaskPlanes
"Mask planes that indicate pixels that should be excluded from the fit" ;
Definition: PsfFlux.h:50
static FlagDefinition const NO_GOOD_PIXELS
Definition: PsfFlux.h:74
static FlagDefinitionList const & getFlagDefinitions()
Definition: PsfFlux.cc:45
T empty(T... args)
afw::table::Key< afw::table::Array< VariancePixelT > > variance
geom::Box2I getBBox(ImageOrigin const origin=PARENT) const
Exception to be thrown when a measurement algorithm encounters a NaN or infinite pixel.
Definition: exceptions.h:91
PsfFluxAlgorithm(Control const &ctrl, std::string const &name, afw::table::Schema &schema, std::string const &logName="")
Definition: PsfFlux.cc:55
static FlagDefinition const EDGE
Definition: PsfFlux.h:75
Simple class used to define and document flags The name and doc constitute the identity of the FlagDe...
Definition: FlagHandler.h:38
#define PTR(...)
T end(T... args)
#define LOGL_ERROR(logger, message...)
void setValue(afw::table::BaseRecord &record, std::size_t i, bool value) const
Set the flag field corresponding to the given flag index.
Definition: FlagHandler.h:276
Exception to be thrown when a measurement algorithm experiences a known failure mode.
Definition: exceptions.h:48
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: PsfFlux.cc:139
Base for flux measurement transformations.
string name
Exception to be thrown when a measurement algorithm experiences a fatal error.
Definition: exceptions.h:83
STL class.
PsfFluxTransform(Control const &ctrl, std::string const &name, afw::table::SchemaMapper &mapper)
Definition: PsfFlux.cc:143
MaskedImageT getMaskedImage()
math::Kernel::Pixel Pixel
static FlagDefinition const FAILURE
Definition: PsfFlux.h:73
std::string getLogName() const
Definition: Algorithm.h:68
T isfinite(T... args)
Flux flux
Measured flux in DN.
Definition: FluxUtilities.h:40
A FunctorKey for FluxResult.
Definition: FluxUtilities.h:58
geom::Point2I getXY0() 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
T size(T... args)
#define LSST_EXCEPT(type,...)
STL class.
T begin(T... args)
std::shared_ptr< lsst::afw::detection::Psf > getPsf()
void handleFailure(afw::table::BaseRecord &record, MeasurementError const *error=nullptr) const
Handle an expected or unexpected Exception thrown by a measurement algorithm.
Definition: FlagHandler.cc:93
void set(Key< T > const &key, U const &value)
void clip(Box2I const &other)
virtual void measure(afw::table::SourceRecord &measRecord, afw::image::Exposure< float > const &exposure) const
Called to measure a single child source in an image.
Definition: PsfFlux.cc:72
T sqrt(T... args)
vector-type utility class to build a collection of FlagDefinitions
Definition: FlagHandler.h:63
FluxErrElement fluxSigma
1-Sigma error (sqrt of variance) on flux in DN.
Definition: FluxUtilities.h:41
A C++ control class to handle PsfFluxAlgorithm&#39;s configuration.
Definition: PsfFlux.h:46
A reusable result struct for flux measurements.
Definition: FluxUtilities.h:39