LSST Applications  21.0.0-147-g0e635eb1+1acddb5be5,22.0.0+052faf71bd,22.0.0+1ea9a8b2b2,22.0.0+6312710a6c,22.0.0+729191ecac,22.0.0+7589c3a021,22.0.0+9f079a9461,22.0.1-1-g7d6de66+b8044ec9de,22.0.1-1-g87000a6+536b1ee016,22.0.1-1-g8e32f31+6312710a6c,22.0.1-10-gd060f87+016f7cdc03,22.0.1-12-g9c3108e+df145f6f68,22.0.1-16-g314fa6d+c825727ab8,22.0.1-19-g93a5c75+d23f2fb6d8,22.0.1-19-gb93eaa13+aab3ef7709,22.0.1-2-g8ef0a89+b8044ec9de,22.0.1-2-g92698f7+9f079a9461,22.0.1-2-ga9b0f51+052faf71bd,22.0.1-2-gac51dbf+052faf71bd,22.0.1-2-gb66926d+6312710a6c,22.0.1-2-gcb770ba+09e3807989,22.0.1-20-g32debb5+b8044ec9de,22.0.1-23-gc2439a9a+fb0756638e,22.0.1-3-g496fd5d+09117f784f,22.0.1-3-g59f966b+1e6ba2c031,22.0.1-3-g849a1b8+f8b568069f,22.0.1-3-gaaec9c0+c5c846a8b1,22.0.1-32-g5ddfab5d3+60ce4897b0,22.0.1-4-g037fbe1+64e601228d,22.0.1-4-g8623105+b8044ec9de,22.0.1-5-g096abc9+d18c45d440,22.0.1-5-g15c806e+57f5c03693,22.0.1-7-gba73697+57f5c03693,master-g6e05de7fdc+c1283a92b8,master-g72cdda8301+729191ecac,w.2021.39
LSST Data Management Base Package
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  _chi2Key(schema.addField<float>(name + "_chi2", "chi2 of the fitted PSF")),
60  _npixelsKey(schema.addField<int>(name + "_npixels",
61  "number of pixels that were included in the PSF fit", "pixel")),
62  _centroidExtractor(schema, name) {
63  _logName = logName.size() ? logName : name;
65 }
66 
68  afw::image::Exposure<float> const& exposure) const {
70  if (!psf) {
71  LOGL_ERROR(getLogName(), "PsfFlux: no psf attached to exposure");
72  throw LSST_EXCEPT(FatalAlgorithmError, "PsfFlux algorithm requires a Psf with every exposure");
73  }
74  geom::Point2D position = _centroidExtractor(measRecord, _flagHandler);
75  std::shared_ptr<afw::detection::Psf::Image> psfImage = psf->computeImage(position);
76  geom::Box2I fitBBox = psfImage->getBBox();
77  fitBBox.clip(exposure.getBBox());
78  if (fitBBox != psfImage->getBBox()) {
79  _flagHandler.setValue(measRecord, FAILURE.number,
80  true); // if we had a suspect flag, we'd set that instead
81  _flagHandler.setValue(measRecord, EDGE.number, true);
82  }
83  auto fitRegionSpans = std::make_shared<afw::geom::SpanSet>(fitBBox);
84  afw::detection::Footprint fitRegion(fitRegionSpans);
85  if (!_ctrl.badMaskPlanes.empty()) {
86  afw::image::MaskPixel badBits = 0x0;
88  i != _ctrl.badMaskPlanes.end(); ++i) {
89  badBits |= exposure.getMaskedImage().getMask()->getPlaneBitMask(*i);
90  }
91  fitRegion.setSpans(fitRegion.getSpans()
92  ->intersectNot(*exposure.getMaskedImage().getMask(), badBits)
93  ->clippedTo(exposure.getMaskedImage().getMask()->getBBox()));
94  }
95  if (fitRegion.getArea() == 0) {
97  }
98  typedef afw::detection::Psf::Pixel PsfPixel;
99  // SpanSet::flatten returns a new ndarray::Array, which must stay in scope
100  // while we use an Eigen::Map view of it
101  auto modelNdArray = fitRegion.getSpans()->flatten(psfImage->getArray(), psfImage->getXY0());
102  auto dataNdArray = fitRegion.getSpans()->flatten(exposure.getMaskedImage().getImage()->getArray(),
103  exposure.getXY0());
104  auto varianceNdArray = fitRegion.getSpans()->flatten(exposure.getMaskedImage().getVariance()->getArray(),
105  exposure.getXY0());
106  auto model = ndarray::asEigenMatrix(modelNdArray);
107  auto data = ndarray::asEigenMatrix(dataNdArray);
108  auto variance = ndarray::asEigenMatrix(varianceNdArray);
109  PsfPixel alpha = model.squaredNorm();
111  result.instFlux = model.dot(data.cast<PsfPixel>()) / alpha;
112  // If we're not using per-pixel weights to compute the instFlux, we'll still want to compute the
113  // variance as if we had, so we'll apply the weights to the model now, and update alpha.
114  result.instFluxErr = std::sqrt(model.array().square().matrix().dot(variance.cast<PsfPixel>())) / alpha;
115  measRecord.set(_areaKey, model.sum() / alpha);
116  measRecord.set(_npixelsKey, fitRegion.getSpans()->getArea());
117  if (!std::isfinite(result.instFlux) || !std::isfinite(result.instFluxErr)) {
118  throw LSST_EXCEPT(PixelValueError, "Invalid pixel value detected in image.");
119  }
120  measRecord.set(_instFluxResultKey, result);
121  auto chi2 = ((data.cast<PsfPixel>() - result.instFlux * model).array().square() /
122  variance.cast<PsfPixel>().array())
123  .sum();
124  measRecord.set(_chi2Key, chi2);
125 }
126 
128  _flagHandler.handleFailure(measRecord, error);
129 }
130 
134  for (std::size_t i = 0; i < PsfFluxAlgorithm::getFlagDefinitions().size(); i++) {
136  if (flag == PsfFluxAlgorithm::FAILURE) continue;
137  if (mapper.getInputSchema().getNames().count(mapper.getInputSchema().join(name, flag.name)) == 0)
138  continue;
140  mapper.getInputSchema().find<afw::table::Flag>(name + "_" + flag.name).key;
141  mapper.addMapping(key);
142  }
143 }
144 
145 } // namespace base
146 } // namespace meas
147 } // namespace lsst
py::object result
Definition: _schema.cc:429
table::Key< std::string > name
Definition: Amplifier.cc:116
char * data
Definition: BaseRecord.cc:61
#define LSST_EXCEPT(type,...)
Create an exception with a given type.
Definition: Exception.h:48
afw::table::Key< afw::table::Array< VariancePixelT > > variance
LSST DM logging module built on log4cxx.
#define LOGL_ERROR(logger, message...)
Log a error-level message using a varargs/printf style interface.
Definition: Log.h:563
SchemaMapper * mapper
Definition: SchemaMapper.cc:71
table::Schema schema
Definition: python.h:134
T begin(T... args)
Class to describe the properties of a detected object from an image.
Definition: Footprint.h:63
std::shared_ptr< geom::SpanSet > getSpans() const
Return a shared pointer to the SpanSet.
Definition: Footprint.h:115
std::size_t getArea() const
Return the number of pixels in this Footprint.
Definition: Footprint.h:173
void setSpans(std::shared_ptr< geom::SpanSet > otherSpanSet)
Sets the shared pointer to the SpanSet in the Footprint.
Definition: Footprint.cc:45
math::Kernel::Pixel Pixel
Pixel type of Image returned by computeImage.
Definition: Psf.h:82
MaskedImageT getMaskedImage()
Return the MaskedImage.
Definition: Exposure.h:228
lsst::geom::Point2I getXY0() const
Return the Exposure's origin.
Definition: Exposure.h:277
std::shared_ptr< lsst::afw::detection::Psf const > getPsf() const
Return the Exposure's Psf object.
Definition: Exposure.h:327
lsst::geom::Box2I getBBox(ImageOrigin const origin=PARENT) const
Definition: Exposure.h:279
VariancePtr getVariance() const
Return a (shared_ptr to) the MaskedImage's variance.
Definition: MaskedImage.h:1051
MaskPtr getMask() const
Return a (shared_ptr to) the MaskedImage's mask.
Definition: MaskedImage.h:1030
ImagePtr getImage() const
Return a (shared_ptr to) the MaskedImage's image.
Definition: MaskedImage.h:1018
void set(Key< T > const &key, U const &value)
Set value of a field for the given key.
Definition: BaseRecord.h:164
Defines the fields and offsets for a table.
Definition: Schema.h:51
A mapping between the keys of two Schemas, used to copy data between them.
Definition: SchemaMapper.h:21
Record class that contains measurements made on a single exposure.
Definition: Source.h:78
An integer coordinate rectangle.
Definition: Box.h:55
void clip(Box2I const &other) noexcept
Shrink this to ensure that other.contains(*this).
Definition: Box.cc:189
std::string getLogName() const
Definition: Algorithm.h:66
Exception to be thrown when a measurement algorithm experiences a fatal error.
Definition: exceptions.h:76
vector-type utility class to build a collection of FlagDefinitions
Definition: FlagHandler.h:60
std::size_t size() const
return the current size (number of defined elements) of the collection
Definition: FlagHandler.h:125
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
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
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
A FunctorKey for FluxResult.
Definition: FluxUtilities.h:59
Base for instFlux measurement transformations.
Exception to be thrown when a measurement algorithm experiences a known failure mode.
Definition: exceptions.h:48
Exception to be thrown when a measurement algorithm encounters a NaN or infinite pixel.
Definition: exceptions.h:83
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:67
static FlagDefinition const FAILURE
Definition: PsfFlux.h:73
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:127
static FlagDefinition const NO_GOOD_PIXELS
Definition: PsfFlux.h:74
static FlagDefinition const EDGE
Definition: PsfFlux.h:75
static FlagDefinitionList const & getFlagDefinitions()
Definition: PsfFlux.cc:49
PsfFluxAlgorithm(Control const &ctrl, std::string const &name, afw::table::Schema &schema, std::string const &logName="")
Definition: PsfFlux.cc:53
A C++ control class to handle PsfFluxAlgorithm's configuration.
Definition: PsfFlux.h:48
std::vector< std::string > badMaskPlanes
"Mask planes that indicate pixels that should be excluded from the fit" ;
Definition: PsfFlux.h:51
PsfFluxTransform(Control const &ctrl, std::string const &name, afw::table::SchemaMapper &mapper)
Definition: PsfFlux.cc:131
T empty(T... args)
T end(T... args)
T isfinite(T... args)
A base class for image defects.
T size(T... args)
T sqrt(T... args)
Simple class used to define and document flags The name and doc constitute the identity of the FlagDe...
Definition: FlagHandler.h:40
A reusable result struct for instFlux measurements.
Definition: FluxUtilities.h:41
Key< int > psf
Definition: Exposure.cc:65