LSSTApplications  18.1.0
LSSTDataManagementBasePackage
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 {
37 namespace meas {
38 namespace base {
39 namespace {
40 FlagDefinitionList flagDefinitions;
41 } // namespace
42 
43 FlagDefinition const PsfFluxAlgorithm::FAILURE = flagDefinitions.addFailureFlag();
44 FlagDefinition const PsfFluxAlgorithm::NO_GOOD_PIXELS =
45  flagDefinitions.add("flag_noGoodPixels", "not enough non-rejected pixels in data to attempt the fit");
46 FlagDefinition const PsfFluxAlgorithm::EDGE = flagDefinitions.add(
47  "flag_edge", "object was too close to the edge of the image to use the full PSF model");
48 
49 FlagDefinitionList const& PsfFluxAlgorithm::getFlagDefinitions() { return flagDefinitions; }
50 
51 namespace {} // namespace
52 
54  std::string const& logName)
55  : _ctrl(ctrl),
56  _instFluxResultKey(FluxResultKey::addFields(
57  schema, name, "instFlux derived from linear least-squares fit of PSF model")),
58  _areaKey(schema.addField<float>(name + "_area", "effective area of PSF", "pixel")),
59  _centroidExtractor(schema, name) {
60  _logName = logName.size() ? logName : name;
61  _flagHandler = FlagHandler::addFields(schema, name, getFlagDefinitions());
62 }
63 
65  afw::image::Exposure<float> const& exposure) const {
66  PTR(afw::detection::Psf const) psf = exposure.getPsf();
67  if (!psf) {
68  LOGL_ERROR(getLogName(), "PsfFlux: no psf attached to exposure");
69  throw LSST_EXCEPT(FatalAlgorithmError, "PsfFlux algorithm requires a Psf with every exposure");
70  }
71  geom::Point2D position = _centroidExtractor(measRecord, _flagHandler);
72  PTR(afw::detection::Psf::Image) psfImage = psf->computeImage(position);
73  geom::Box2I fitBBox = psfImage->getBBox();
74  fitBBox.clip(exposure.getBBox());
75  if (fitBBox != psfImage->getBBox()) {
76  _flagHandler.setValue(measRecord, FAILURE.number,
77  true); // if we had a suspect flag, we'd set that instead
78  _flagHandler.setValue(measRecord, EDGE.number, true);
79  }
80  auto fitRegionSpans = std::make_shared<afw::geom::SpanSet>(fitBBox);
81  afw::detection::Footprint fitRegion(fitRegionSpans);
82  if (!_ctrl.badMaskPlanes.empty()) {
83  afw::image::MaskPixel badBits = 0x0;
85  i != _ctrl.badMaskPlanes.end(); ++i) {
86  badBits |= exposure.getMaskedImage().getMask()->getPlaneBitMask(*i);
87  }
88  fitRegion.setSpans(fitRegion.getSpans()
89  ->intersectNot(*exposure.getMaskedImage().getMask(), badBits)
90  ->clippedTo(exposure.getMaskedImage().getMask()->getBBox()));
91  }
92  if (fitRegion.getArea() == 0) {
94  }
95  typedef afw::detection::Psf::Pixel PsfPixel;
96  // SpanSet::flatten returns a new ndarray::Array, which must stay in scope
97  // while we use an Eigen::Map view of it
98  auto modelNdArray = fitRegion.getSpans()->flatten(psfImage->getArray(), psfImage->getXY0());
99  auto dataNdArray = fitRegion.getSpans()->flatten(exposure.getMaskedImage().getImage()->getArray(),
100  exposure.getXY0());
101  auto varianceNdArray = fitRegion.getSpans()->flatten(exposure.getMaskedImage().getVariance()->getArray(),
102  exposure.getXY0());
103  auto model = ndarray::asEigenMatrix(modelNdArray);
104  auto data = ndarray::asEigenMatrix(dataNdArray);
105  auto variance = ndarray::asEigenMatrix(varianceNdArray);
106  PsfPixel alpha = model.squaredNorm();
108  result.instFlux = model.dot(data.cast<PsfPixel>()) / alpha;
109  // If we're not using per-pixel weights to compute the instFlux, we'll still want to compute the
110  // variance as if we had, so we'll apply the weights to the model now, and update alpha.
111  result.instFluxErr = std::sqrt(model.array().square().matrix().dot(variance.cast<PsfPixel>())) / alpha;
112  measRecord.set(_areaKey, model.sum() / alpha);
113  if (!std::isfinite(result.instFlux) || !std::isfinite(result.instFluxErr)) {
114  throw LSST_EXCEPT(PixelValueError, "Invalid pixel value detected in image.");
115  }
116  measRecord.set(_instFluxResultKey, result);
117 }
118 
120  _flagHandler.handleFailure(measRecord, error);
121 }
122 
125  : FluxTransform{name, mapper} {
126  for (std::size_t i = 0; i < PsfFluxAlgorithm::getFlagDefinitions().size(); i++) {
128  if (flag == PsfFluxAlgorithm::FAILURE) continue;
129  if (mapper.getInputSchema().getNames().count(mapper.getInputSchema().join(name, flag.name)) == 0)
130  continue;
132  mapper.getInputSchema().find<afw::table::Flag>(name + "_" + flag.name).key;
133  mapper.addMapping(key);
134  }
135 }
136 
137 } // namespace base
138 } // namespace meas
139 } // 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
std::vector< std::string > badMaskPlanes
"Mask planes that indicate pixels that should be excluded from the fit" ;
Definition: PsfFlux.h:51
static FlagDefinition const NO_GOOD_PIXELS
Definition: PsfFlux.h:74
static FlagDefinitionList const & getFlagDefinitions()
Definition: PsfFlux.cc:49
T empty(T... args)
Exception to be thrown when a measurement algorithm encounters a NaN or infinite pixel.
Definition: exceptions.h:83
#define PTR(...)
Definition: base.h:41
PsfFluxAlgorithm(Control const &ctrl, std::string const &name, afw::table::Schema &schema, std::string const &logName="")
Definition: PsfFlux.cc:53
afw::table::Key< afw::table::Array< VariancePixelT > > variance
A mapping between the keys of two Schemas, used to copy data between them.
Definition: SchemaMapper.h:21
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:40
py::object result
Definition: schema.cc:418
lsst::geom::Point2I getXY0() const
Return the Exposure&#39;s origin.
Definition: Exposure.h:273
T end(T... args)
#define LOGL_ERROR(logger, message...)
Log a error-level message using a varargs/printf style interface.
Definition: Log.h:537
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:262
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
lsst::geom::Box2I getBBox(ImageOrigin const origin=PARENT) const
Definition: Exposure.h:275
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:119
Base for instFlux measurement transformations.
Exception to be thrown when a measurement algorithm experiences a fatal error.
Definition: exceptions.h:76
ImagePtr getImage() const
Return a (shared_ptr to) the MaskedImage&#39;s image.
Definition: MaskedImage.h:1058
STL class.
LSST DM logging module built on log4cxx.
PsfFluxTransform(Control const &ctrl, std::string const &name, afw::table::SchemaMapper &mapper)
Definition: PsfFlux.cc:123
A base class for image defects.
MaskedImageT getMaskedImage()
Return the MaskedImage.
Definition: Exposure.h:230
char * data
Definition: BaseRecord.cc:62
math::Kernel::Pixel Pixel
Pixel type of Image returned by computeImage.
Definition: Psf.h:84
static FlagDefinition const FAILURE
Definition: PsfFlux.h:73
std::string getLogName() const
Definition: Algorithm.h:66
T isfinite(T... args)
table::Schema schema
Definition: Camera.cc:161
A FunctorKey for FluxResult.
Definition: FluxUtilities.h:59
Class to describe the properties of a detected object from an image.
Definition: Footprint.h:62
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
MaskPtr getMask() const
Return a (shared_ptr to) the MaskedImage&#39;s mask.
Definition: MaskedImage.h:1070
T size(T... args)
#define LSST_EXCEPT(type,...)
Create an exception with a given type.
Definition: Exception.h:48
STL class.
T begin(T... args)
Key< U > key
Definition: Schema.cc:281
std::shared_ptr< lsst::afw::detection::Psf > getPsf()
Return the Exposure&#39;s Psf object.
Definition: Exposure.h:320
void clip(Box2I const &other) noexcept
Shrink this to ensure that other.contains(*this).
Definition: Box.cc:194
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:76
void set(Key< T > const &key, U const &value)
Set value of a field for the given key.
Definition: BaseRecord.h:164
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
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:64
T sqrt(T... args)
vector-type utility class to build a collection of FlagDefinitions
Definition: FlagHandler.h:60
A polymorphic base class for representing an image&#39;s Point Spread Function.
Definition: Psf.h:76
A C++ control class to handle PsfFluxAlgorithm&#39;s configuration.
Definition: PsfFlux.h:48
An integer coordinate rectangle.
Definition: Box.h:54
A reusable result struct for instFlux measurements.
Definition: FluxUtilities.h:41
SchemaMapper * mapper
Definition: SchemaMapper.cc:78