lsst.meas.base  13.0-33-gb1a1d47
PeakLikelihoodFlux.cc
Go to the documentation of this file.
1 // -*- lsst-c++ -*-
2 /*
3  * LSST Data Management System
4  * Copyright 2008-2013 LSST Corporation.
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 "ndarray/eigen.h"
25 
26 #include "lsst/afw/detection/Psf.h"
27 #include "lsst/afw/geom/Box.h"
28 #include "lsst/pex/exceptions.h"
29 #include "lsst/afw/geom.h"
30 #include "lsst/afw/image.h"
31 #include "lsst/afw/math.h"
32 
34 #include "lsst/afw/table/Source.h"
35 
36 namespace lsst { namespace meas { namespace base {
37 namespace {
38 FlagDefinitionList flagDefinitions;
39 } // end anonymous
40 
41 FlagDefinition const PeakLikelihoodFluxAlgorithm::FAILURE = flagDefinitions.addFailureFlag();
42 
44  return flagDefinitions;
45 }
46 
47 
48 namespace {
49 
50 /************************************************************************************************************/
67 class PsfAttributes {
68 public:
69  enum Method { ADAPTIVE_MOMENT,
70  FIRST_MOMENT,
71  SECOND_MOMENT,
72  NOISE_EQUIVALENT,
73  BICKERTON
74  };
75 
76  PsfAttributes(CONST_PTR(lsst::afw::detection::Psf) psf, int const iX, int const iY);
77  PsfAttributes(CONST_PTR(lsst::afw::detection::Psf) psf, lsst::afw::geom::Point2I const& cen);
78 
79  double computeGaussianWidth(Method how=ADAPTIVE_MOMENT) const;
80  double computeEffectiveArea() const;
81 
82 private:
83  PTR(lsst::afw::image::Image<double>) _psfImage;
84 };
85 
89 PsfAttributes::PsfAttributes(
90  CONST_PTR(lsst::afw::detection::Psf) psf,
91  int const iX,
92  int const iY
93  )
94 {
95  // N.b. (iX, iY) are ints so that we know this image is centered in the central pixel of _psfImage
96  _psfImage = psf->computeImage(afw::geom::PointD(iX, iY));
97 }
98 
102 PsfAttributes::PsfAttributes(
103  CONST_PTR(lsst::afw::detection::Psf) psf,
104  lsst::afw::geom::Point2I const& cen
105  ) :
106  // N.b. cen is a PointI so that we know this image is centered in the central pixel of _psfImage
107  _psfImage(psf->computeImage(afw::geom::PointD(cen)))
108 {
109 }
110 
115 double PsfAttributes::computeEffectiveArea() const {
116 
117  double sum = 0.0;
118  double sumsqr = 0.0;
119  for (int iY = 0; iY != _psfImage->getHeight(); ++iY) {
120  afw::image::Image<double>::x_iterator end = _psfImage->row_end(iY);
121  for (afw::image::Image<double>::x_iterator ptr = _psfImage->row_begin(iY); ptr != end; ++ptr) {
122  sum += *ptr;
123  sumsqr += (*ptr)*(*ptr);
124  }
125  }
126  return sum*sum/sumsqr;
127 }
128 
129 } // end anonymous namespace
130 
138 template<typename T>
139 typename afw::image::MaskedImage<T>::SinglePixel computeShiftedValue(
140  afw::image::MaskedImage<T> const &maskedImage,
141  std::string const &warpingKernelName,
142  afw::geom::Point2D const &fracShift,
143  afw::geom::Point2I const &parentInd
144 ) {
145  typedef typename afw::image::Exposure<T>::MaskedImageT MaskedImageT;
146  typedef typename afw::image::Image<double> KernelImageT;
147 
148  PTR(afw::math::SeparableKernel) warpingKernelPtr = afw::math::makeWarpingKernel(warpingKernelName);
149 
150  if ((std::abs(fracShift[0]) >= 1) || (std::abs(fracShift[1]) >= 1)) {
151  std::ostringstream os;
152  os << "fracShift = " << fracShift << " too large; abs value must be < 1 in both axes";
153  throw LSST_EXCEPT(pex::exceptions::RangeError, os.str());
154  }
155 
156  // warping kernels have even dimension and want the peak to the right of center
157  if (fracShift[0] < 0) {
158  warpingKernelPtr->setCtrX(warpingKernelPtr->getCtrX() + 1);
159  }
160  if (fracShift[1] < 0) {
161  warpingKernelPtr->setCtrY(warpingKernelPtr->getCtrY() + 1);
162  }
163  afw::geom::Box2I warpingOverlapBBox(
164  parentInd - afw::geom::Extent2I(warpingKernelPtr->getCtr()),
165  warpingKernelPtr->getDimensions());
166  if (!maskedImage.getBBox().contains(warpingOverlapBBox)) {
167  std::ostringstream os;
168  os << "Warping kernel extends off the edge"
169  << "; kernel bbox = " << warpingOverlapBBox
170  << "; exposure bbox = " << maskedImage.getBBox();
171  throw LSST_EXCEPT(pex::exceptions::RangeError, os.str());
172  }
173  warpingKernelPtr->setKernelParameters(std::make_pair(fracShift[0], fracShift[1]));
174  KernelImageT warpingKernelImage(warpingKernelPtr->getDimensions());
175  warpingKernelPtr->computeImage(warpingKernelImage, true);
176  typename KernelImageT::const_xy_locator const warpingKernelLoc = warpingKernelImage.xy_at(0,0);
177 
178  // Compute imLoc: an image locator that matches kernel locator (0,0) such that
179  // image ctrPix overlaps center of warping kernel
180  afw::geom::Point2I subimMin = warpingOverlapBBox.getMin();
181  typename MaskedImageT::const_xy_locator const mimageLoc = maskedImage.xy_at(subimMin.getX(), subimMin.getY());
182  return afw::math::convolveAtAPoint<MaskedImageT, MaskedImageT>(
183  mimageLoc, warpingKernelLoc, warpingKernelPtr->getWidth(), warpingKernelPtr->getHeight());
184 }
186  Control const & ctrl,
187  std::string const & name,
188  afw::table::Schema & schema
189 ) : _ctrl(ctrl),
190  _fluxResultKey(
191  FluxResultKey::addFields(schema, name, "flux from PeakLikelihood Flux algorithm")
192  ),
193  _centroidExtractor(schema, name)
194 {
195  _flagHandler = FlagHandler::addFields(schema, name, getFlagDefinitions());
196 }
197 
199  afw::table::SourceRecord & measRecord,
200  afw::image::Exposure<float> const & exposure
201 ) const {
202  // get the value from the centroid slot only
203  afw::geom::Point2D center = _centroidExtractor(measRecord, _flagHandler);
204  FluxResult result;
205  typedef afw::image::Exposure<float>::MaskedImageT MaskedImageT;
206  MaskedImageT const& mimage = exposure.getMaskedImage();
207 
218  if (!exposure.hasPsf()) {
219  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError, "exposure has no PSF");
220  }
221  PTR(afw::detection::Psf const) psfPtr = exposure.getPsf();
222  if (!afw::geom::Box2D(mimage.getBBox()).contains(center)) {
223  std::ostringstream os;
224  os << "Center = " << center << " not in exposure bbox" << mimage.getBBox();
225  throw LSST_EXCEPT(pex::exceptions::RangeError, os.str());
226  }
227 
228  // compute parent index and fractional offset of ctrPix: the pixel closest to "center",
229  // the centroid of the source
230  std::pair<int, double> const xCtrPixParentIndFrac = afw::image::positionToIndex(center.getX(), true);
231  std::pair<int, double> const yCtrPixParentIndFrac = afw::image::positionToIndex(center.getY(), true);
232 
233  afw::geom::Point2I ctrPixParentInd(xCtrPixParentIndFrac.first, yCtrPixParentIndFrac.first);
234  afw::geom::Point2D ctrPixPos(
235  afw::image::indexToPosition(ctrPixParentInd[0]),
236  afw::image::indexToPosition(ctrPixParentInd[1])
237  );
238 
239  // compute weight = 1/sum(PSF^2) for PSF at ctrPix, where PSF is normalized to a sum of 1
240  PsfAttributes psfAttr(psfPtr, ctrPixParentInd);
241  double weight = psfAttr.computeEffectiveArea();
242 
243  /*
244  * Compute value of image at center of source, as shifted by a fractional pixel to center the source
245  * on ctrPix.
246  */
247  MaskedImageT::SinglePixel mimageCtrPix = computeShiftedValue(
248  mimage,
249  _ctrl.warpingKernelName,
250  afw::geom::Point2D(xCtrPixParentIndFrac.second, yCtrPixParentIndFrac.second),
251  ctrPixParentInd
252  );
253  double flux = mimageCtrPix.image()*weight;
254  double var = mimageCtrPix.variance()*weight*weight;
255  result.flux = flux;
256  result.fluxSigma = std::sqrt(var);
257  measRecord.set(_fluxResultKey, result);
258  _flagHandler.setValue(measRecord, FAILURE.number, false);
259 
260 }
261 
262 void PeakLikelihoodFluxAlgorithm::fail(afw::table::SourceRecord & measRecord, MeasurementError * error) const {
263  _flagHandler.handleFailure(measRecord, error);
264 }
265 
266 }}} // namespace lsst::meas::base
PeakLikelihoodFluxAlgorithm(Control const &ctrl, std::string const &name, afw::table::Schema &schema)
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
C++ control object for peak likelihood flux.
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: mainpage.dox:3
virtual void measure(afw::table::SourceRecord &measRecord, afw::image::Exposure< float > const &exposure) const
Called to measure a single child source in an image.
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
std::string warpingKernelName
"Name of warping kernel (e.g. \"lanczos4") used to compute the peak" ;
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
afw::image::MaskedImage< T >::SinglePixel computeShiftedValue(afw::image::MaskedImage< T > const &maskedImage, std::string const &warpingKernelName, afw::geom::Point2D const &fracShift, afw::geom::Point2I const &parentInd)
Compute the value of one pixel of an image after a fractional pixel shift Since we only want the valu...
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 reusable result struct for flux measurements.
Definition: FluxUtilities.h:37
static FlagDefinitionList const & getFlagDefinitions()