lsst.meas.base  13.0-33-gb1a1d47+5
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  _centroidExtractor(schema, name)
65 {
66  _logName = logName.size() ? logName : name;
67  _flagHandler = FlagHandler::addFields(schema, name,
69 }
70 
72  afw::table::SourceRecord & measRecord,
73  afw::image::Exposure<float> const & exposure
74 ) const {
75  PTR(afw::detection::Psf const) psf = exposure.getPsf();
76  if (!psf) {
77  LOGL_ERROR(getLogName(), "PsfFlux: no psf attached to exposure");
78  throw LSST_EXCEPT(
80  "PsfFlux algorithm requires a Psf with every exposure"
81  );
82  }
83  afw::geom::Point2D position = _centroidExtractor(measRecord, _flagHandler);
84  PTR(afw::detection::Psf::Image) psfImage = psf->computeImage(position);
85  afw::geom::Box2I fitBBox = psfImage->getBBox();
86  fitBBox.clip(exposure.getBBox());
87  if (fitBBox != psfImage->getBBox()) {
88  _flagHandler.setValue(measRecord, FAILURE.number, true); // if we had a suspect flag, we'd set that instead
89  _flagHandler.setValue(measRecord, EDGE.number, true);
90  }
91  auto fitRegionSpans = std::make_shared<afw::geom::SpanSet>(fitBBox);
92  afw::detection::Footprint fitRegion(fitRegionSpans);
93  if (!_ctrl.badMaskPlanes.empty()) {
94  afw::image::MaskPixel badBits = 0x0;
95  for (
96  std::vector<std::string>::const_iterator i = _ctrl.badMaskPlanes.begin();
97  i != _ctrl.badMaskPlanes.end();
98  ++i
99  ) {
100  badBits |= exposure.getMaskedImage().getMask()->getPlaneBitMask(*i);
101  }
102  fitRegion.setSpans(fitRegion.getSpans()->intersectNot(*exposure.getMaskedImage().getMask(),
103  badBits)->clippedTo(exposure.getMaskedImage().getMask()->getBBox()));
104  }
105  if (fitRegion.getArea() == 0) {
106  throw LSST_EXCEPT(
110  );
111  }
112  typedef afw::detection::Psf::Pixel PsfPixel;
113  typedef afw::image::MaskedImage<float>::Variance::Pixel VarPixel;
114  ndarray::EigenView<PsfPixel,1,1,Eigen::ArrayXpr> model(
115  fitRegion.getSpans()->flatten(psfImage->getArray(), psfImage->getXY0())
116  );
117  ndarray::EigenView<float,1,1,Eigen::ArrayXpr> data(
118  fitRegion.getSpans()->flatten(exposure.getMaskedImage().getImage()->getArray(), exposure.getXY0())
119  );
120  ndarray::EigenView<VarPixel,1,1,Eigen::ArrayXpr> variance(
121  fitRegion.getSpans()->flatten(exposure.getMaskedImage().getVariance()->getArray(),
122  exposure.getXY0())
123  );
124  PsfPixel alpha = model.matrix().squaredNorm();
125  FluxResult result;
126  result.flux = model.matrix().dot(data.matrix().cast<PsfPixel>()) / alpha;
127  // If we're not using per-pixel weights to compute the flux, we'll still want to compute the
128  // variance as if we had, so we'll apply the weights to the model vector now, and update alpha.
129  result.fluxSigma = std::sqrt(model.square().matrix().dot(variance.matrix().cast<PsfPixel>()))
130  / alpha;
131  if (!std::isfinite(result.flux) || !std::isfinite(result.fluxSigma)) {
132  throw LSST_EXCEPT(PixelValueError, "Invalid pixel value detected in image.");
133  }
134  measRecord.set(_fluxResultKey, result);
135 }
136 
137 void PsfFluxAlgorithm::fail(afw::table::SourceRecord & measRecord, MeasurementError * error) const {
138  _flagHandler.handleFailure(measRecord, error);
139 }
140 
142  Control const & ctrl,
143  std::string const & name,
144  afw::table::SchemaMapper & mapper
145 ) :
146  FluxTransform{name, mapper}
147 {
148  for (std::size_t i = 0; i < PsfFluxAlgorithm::getFlagDefinitions().size(); i++) {
150  if (flag == PsfFluxAlgorithm::FAILURE) continue;
151  if (mapper.getInputSchema().getNames().count(
152  mapper.getInputSchema().join(name, flag.name)) == 0) continue;
153  afw::table::Key<afw::table::Flag> key = mapper.getInputSchema().find<afw::table::Flag>(
154  name + "_" + flag.name).key;
155  mapper.addMapping(key);
156  }
157 }
158 
159 }}} // 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
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
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:137
Base for flux measurement transformations.
Exception to be thrown when a measurement algorithm experiences a fatal error.
Definition: exceptions.h:83
Matrix alpha
PsfFluxTransform(Control const &ctrl, std::string const &name, afw::table::SchemaMapper &mapper)
Definition: PsfFlux.cc:141
Definition: mainpage.dox:3
static FlagDefinition const FAILURE
Definition: PsfFlux.h:73
std::string getLogName() const
Definition: Algorithm.h:67
Flux flux
Measured flux in DN.
Definition: FluxUtilities.h:38
A FunctorKey for FluxResult.
Definition: FluxUtilities.h:56
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 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
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:71
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:39
A C++ control class to handle PsfFluxAlgorithm&#39;s configuration.
Definition: PsfFlux.h:46
A reusable result struct for flux measurements.
Definition: FluxUtilities.h:37