lsst.afw  14.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
HeavyFootprint.cc
Go to the documentation of this file.
1 /*
2  * LSST Data Management System
3  * Copyright 2008, 2009, 2010 LSST Corporation.
4  *
5  * This product includes software developed by the
6  * LSST Project (http://www.lsst.org/).
7  *
8  * This program is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the LSST License Statement and
19  * the GNU General Public License along with this program. If not,
20  * see <http://www.lsstcorp.org/LegalNotices/>.
21  */
22 
23 #include <cstdint>
24 #include <cassert>
25 #include <string>
26 #include <typeinfo>
27 #include <algorithm>
28 #include "boost/format.hpp"
29 #include "lsst/pex/exceptions.h"
39 
40 namespace lsst {
41 namespace afw {
42 namespace detection {
43 namespace {
44 
45 template <typename T>
46 struct FlattenWithSetter {
47  FlattenWithSetter(T val) : _val(val) {}
48 
49  void operator()(geom::Point2I const& point, T& out, T& in) {
50  out = in;
51  in = _val;
52  }
53 
54 private:
55  T _val;
56 };
57 
58 template <>
59 struct FlattenWithSetter<lsst::afw::image::MaskPixel> {
61  FlattenWithSetter(T val) : _mask(~val) {}
62 
63  void operator()(geom::Point2I const& point, T& out, T& in) {
64  out = in;
65  in &= _mask;
66  }
67 
68 private:
69  T _mask;
70 };
71 }
72 
73 template <typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
76  HeavyFootprintCtrl const* ctrl)
77  : Footprint(foot),
78  _image(ndarray::allocate(ndarray::makeVector(foot.getArea()))),
79  _mask(ndarray::allocate(ndarray::makeVector(foot.getArea()))),
80  _variance(ndarray::allocate(ndarray::makeVector(foot.getArea()))) {
82 
83  if (!ctrl) {
84  ctrl = &ctrl_s;
85  }
86 
87  switch (ctrl->getModifySource()) {
89  getSpans()->flatten(_image, mimage.getImage()->getArray(), mimage.getXY0());
90  getSpans()->flatten(_mask, mimage.getMask()->getArray(), mimage.getXY0());
91  getSpans()->flatten(_variance, mimage.getVariance()->getArray(), mimage.getXY0());
92  break;
94  ImagePixelT const ival = ctrl->getImageVal();
95  MaskPixelT const mval = ctrl->getMaskVal();
96  VariancePixelT const vval = ctrl->getVarianceVal();
97 
98  getSpans()->applyFunctor(FlattenWithSetter<ImagePixelT>(ival), ndarray::ndFlat(_image),
99  ndarray::ndImage(mimage.getImage()->getArray(), mimage.getXY0()));
100  getSpans()->applyFunctor(FlattenWithSetter<MaskPixelT>(mval), ndarray::ndFlat(_mask),
101  ndarray::ndImage(mimage.getMask()->getArray(), mimage.getXY0()));
102  getSpans()->applyFunctor(FlattenWithSetter<VariancePixelT>(vval), ndarray::ndFlat(_variance),
103  ndarray::ndImage(mimage.getVariance()->getArray(), mimage.getXY0()));
104  break;
105  }
106  }
107 }
108 
109 template <typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
111  HeavyFootprintCtrl const* ctrl)
112  : Footprint(foot),
113  _image(ndarray::allocate(ndarray::makeVector(foot.getArea()))),
114  _mask(ndarray::allocate(ndarray::makeVector(foot.getArea()))),
115  _variance(ndarray::allocate(ndarray::makeVector(foot.getArea()))) {}
116 
117 template <typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
120  getSpans()->unflatten(mimage.getImage()->getArray(), _image, mimage.getXY0());
121  getSpans()->unflatten(mimage.getMask()->getArray(), _mask, mimage.getXY0());
122  getSpans()->unflatten(mimage.getVariance()->getArray(), _variance, mimage.getXY0());
123 }
124 
125 template <typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
127  getSpans()->unflatten(image.getArray(), _image, image.getXY0());
128 }
129 
130 template <typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
131 std::shared_ptr<HeavyFootprint<ImagePixelT, MaskPixelT, VariancePixelT>> mergeHeavyFootprints(
134  // Merge the Footprints (by merging the Spans)
135  std::shared_ptr<Footprint> foot = mergeFootprints(h1, h2);
136 
137  // Find the union bounding-box
138  geom::Box2I bbox(h1.getBBox());
139  bbox.include(h2.getBBox());
140 
141  // Create union-bb-sized images and insert the heavies
144  h1.insert(im1);
145  h2.insert(im2);
146  // Add the pixels
147  im1 += im2;
148 
149  // Build new HeavyFootprint from the merged spans and summed pixels.
150  return std::make_shared<HeavyFootprint<ImagePixelT, MaskPixelT, VariancePixelT>>(*foot, im1);
151 }
152 
153 template <typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
156  // Coordinated cycling through the iterators while juggling the offsets into the arrays
157  typedef typename ndarray::Array<ImagePixelT const, 1, 1>::Iterator ArrayIter;
158  ArrayIter lhsArray = getImageArray().begin(), rhsArray = rhs.getImageArray().begin();
159  auto lhsIter = getSpans()->begin(), rhsIter = rhs.getSpans()->begin();
160  auto const lhsEnd = getSpans()->end(), rhsEnd = rhs.getSpans()->end();
161  double sum = 0.0;
162  while (lhsIter != lhsEnd && rhsIter != rhsEnd) {
163  geom::Span const &lhsSpan = *lhsIter, rhsSpan = *rhsIter;
164  int const yLhs = lhsSpan.getY(), yRhs = rhsSpan.getY();
165  if (yLhs == yRhs) {
166  int const x0Lhs = lhsSpan.getX0(), x1Lhs = lhsSpan.getX1();
167  int const x0Rhs = rhsSpan.getX0(), x1Rhs = rhsSpan.getX1();
168  int const xMin = std::max(x0Lhs, x0Rhs), xMax = std::min(x1Lhs, x1Rhs);
169  if (xMin <= xMax) {
170  lhsArray += xMin - x0Lhs;
171  rhsArray += xMin - x0Rhs;
172  for (int x = xMin; x <= xMax; ++x, ++lhsArray, ++rhsArray) {
173  sum += (*lhsArray) * (*rhsArray);
174  }
175  // Rewind to the start of the span, for easier sync between spans and arrays
176  lhsArray -= xMax + 1 - x0Lhs;
177  rhsArray -= xMax + 1 - x0Rhs;
178  }
179  if (x1Lhs <= x1Rhs) {
180  lhsArray += lhsSpan.getWidth();
181  ++lhsIter;
182  } else {
183  rhsArray += rhsSpan.getWidth();
184  ++rhsIter;
185  }
186  continue;
187  } else if (yLhs < yRhs) {
188  while (lhsIter != lhsEnd && lhsIter->getY() < yRhs) {
189  lhsArray += lhsIter->getWidth();
190  ++lhsIter;
191  }
192  continue;
193  } else { // yLhs > yRhs
194  while (rhsIter != rhsEnd && rhsIter->getY() < yLhs) {
195  rhsArray += rhsIter->getWidth();
196  ++rhsIter;
197  }
198  continue;
199  }
200  }
201  return sum;
202 }
203 
204 // Persistence (using afw::table::io)
205 //
206 
207 namespace {
208 
209 // Schema and Keys used to persist the pixels of a HeavyFootprint (Spans and Peaks are handled by the
210 // Footprint base class). This is a singleton, but a different one for each template instantiation.
211 template <typename ImagePixelT, typename MaskPixelT = image::MaskPixel,
212  typename VariancePixelT = image::VariancePixel>
213 struct HeavyFootprintPersistenceHelper {
214  afw::table::Schema schema;
215  afw::table::Key<afw::table::Array<ImagePixelT>> image;
216  afw::table::Key<afw::table::Array<MaskPixelT>> mask;
217  afw::table::Key<afw::table::Array<VariancePixelT>> variance;
218 
219  static HeavyFootprintPersistenceHelper const& get() {
220  static HeavyFootprintPersistenceHelper const instance;
221  return instance;
222  }
223 
224 private:
225  HeavyFootprintPersistenceHelper()
226  : schema(),
227  image(schema.addField<afw::table::Array<ImagePixelT>>(
228  "image", "image pixels for HeavyFootprint", "count")),
229  mask(schema.addField<afw::table::Array<MaskPixelT>>("mask", "mask pixels for HeavyFootprint")),
230  variance(schema.addField<afw::table::Array<VariancePixelT>>(
231  "variance", "variance pixels for HeavyFootprint", "count^2")) {
232  schema.getCitizen().markPersistent();
233  }
234 };
235 
236 // These suffix-computing structs are used to compute the string name associated with a HeavyFootprint
237 // for Persistence.
238 // We don't instantiate HeavyFootprints with anything other than defaults for Mask and Variance, so we
239 // don't bother figuring out what suffixes to use for them for now. If we change that, we just need
240 // to add more explicit specializations of this template.
241 template <typename ImagePixelT, typename MaskPixelT = image::MaskPixel,
242  typename VariancePixelT = image::VariancePixel>
243 struct ComputeSuffix;
244 template <>
245 struct ComputeSuffix<std::uint16_t> {
246  static std::string apply() { return "U"; }
247 };
248 template <>
249 struct ComputeSuffix<float> {
250  static std::string apply() { return "F"; }
251 };
252 template <>
253 struct ComputeSuffix<double> {
254  static std::string apply() { return "D"; }
255 };
256 template <>
257 struct ComputeSuffix<int> {
258  static std::string apply() { return "I"; }
259 };
260 
261 } // anonymous
262 
263 template <typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
265  return "HeavyFootprint" + ComputeSuffix<ImagePixelT, MaskPixelT, VariancePixelT>::apply();
266 }
267 
268 template <typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
270  HeavyFootprintPersistenceHelper<ImagePixelT, MaskPixelT, VariancePixelT> const& keys =
271  HeavyFootprintPersistenceHelper<ImagePixelT, MaskPixelT, VariancePixelT>::get();
272  // delegate to Footprint::write to handle spans and peaks
273  Footprint::write(handle);
274  // add one more catalog for pixel values
275  afw::table::BaseCatalog cat = handle.makeCatalog(keys.schema);
276  std::shared_ptr<afw::table::BaseRecord> record = cat.addNew();
277  // We could deep-copy the arrays instead of const-casting them, which might be marginally safer,
278  // but we always save an OutputArchive to disk immediately after we create it, so there's really
279  // no chance that we could get the HeavyFootprint in trouble by having this view modified.
280  record->set(keys.image, ndarray::const_array_cast<ImagePixelT>(getImageArray()));
281  record->set(keys.mask, ndarray::const_array_cast<MaskPixelT>(getMaskArray()));
282  record->set(keys.variance, ndarray::const_array_cast<VariancePixelT>(getVarianceArray()));
283  handle.saveCatalog(cat);
284 }
285 
286 template <typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
287 class HeavyFootprint<ImagePixelT, MaskPixelT, VariancePixelT>::Factory
289 public:
290  explicit Factory(std::string const& name) : afw::table::io::PersistableFactory(name) {}
291 
292  virtual std::shared_ptr<afw::table::io::Persistable> read(InputArchive const& archive,
293  CatalogVector const& catalogs) const {
294  HeavyFootprintPersistenceHelper<ImagePixelT, MaskPixelT, VariancePixelT> const& keys =
295  HeavyFootprintPersistenceHelper<ImagePixelT, MaskPixelT, VariancePixelT>::get();
296  HeavyFootprintPersistenceHelper<ImagePixelT, std::uint16_t, VariancePixelT> const& legacyKeys =
297  HeavyFootprintPersistenceHelper<ImagePixelT, std::uint16_t, VariancePixelT>::get();
298  LSST_ARCHIVE_ASSERT(catalogs.size() == 3u);
299 
300  // Read in the SpanSet into a new Footprint object
301  std::shared_ptr<Footprint> loadedFootprint = readSpanSet(catalogs[0], archive);
302  // Now read in the PeakCatalog records
303  readPeaks(catalogs[1], *loadedFootprint);
304  afw::table::BaseRecord const& record = catalogs[2].front();
305 
306  // Create the HeavyFootprint from the above Footprint
307  auto result =
308  std::make_shared<HeavyFootprint<ImagePixelT, MaskPixelT, VariancePixelT>>(*loadedFootprint);
309  result->_image = ndarray::const_array_cast<ImagePixelT>(record.get(keys.image));
310 
311  // Handle legacy Masks prior to change to int32
312  if (catalogs[2].getSchema() == legacyKeys.schema) {
313  auto legacyMask = ndarray::const_array_cast<std::uint16_t>(record.get(legacyKeys.mask));
314  result->_mask.deep() = legacyMask;
315  } else {
316  result->_mask = ndarray::const_array_cast<MaskPixelT>(record.get(keys.mask));
317  }
318  result->_variance = ndarray::const_array_cast<VariancePixelT>(record.get(keys.variance));
319  return result;
320  }
321 
323 };
324 
325 // initialize static instance, registering the factory with the persistence mechanism at the same time
326 template <typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
329  "HeavyFootprint" + ComputeSuffix<ImagePixelT, MaskPixelT, VariancePixelT>::apply());
330 
331 //
332 // Explicit instantiations
333 //
334 //
335 #define INSTANTIATE(TYPE) \
336  template class HeavyFootprint<TYPE>; \
337  template std::shared_ptr<HeavyFootprint<TYPE>> mergeHeavyFootprints<TYPE>(HeavyFootprint<TYPE> const&, \
338  HeavyFootprint<TYPE> const&);
339 
340 INSTANTIATE(std::uint16_t);
341 INSTANTIATE(double);
342 INSTANTIATE(float);
343 INSTANTIATE(int);
344 }
345 }
346 }
virtual std::string getPersistenceName() const
Return the name correspoinging ot the persistence type.
virtual void write(OutputArchiveHandle &handle) const
Write an instance of a Footprint to an output Archive.
int getWidth() const
Return the number of pixels.
Definition: Span.h:82
int getX0() const
Return the starting x-value.
Definition: Span.h:76
An object passed to Persistable::write to allow it to persist itself.
A control object for HeavyFootprints.
Definition: FootprintCtrl.h:94
VariancePtr getVariance() const
Return a (shared_ptr to) the MaskedImage&#39;s variance.
Definition: MaskedImage.h:993
A custom container class for records, based on std::vector.
Definition: Catalog.h:96
double dot(HeavyFootprint< ImagePixelT, MaskPixelT, VariancePixelT > const &other) const
Dot product between HeavyFootprints.
afw::table::Key< afw::table::Array< VariancePixelT > > variance
#define LSST_ARCHIVE_ASSERT(EXPR)
An assertion macro used to validate the structure of an InputArchive.
Definition: Persistable.h:47
A range of pixels within one row of an Image.
Definition: Span.h:55
void include(Point2I const &point)
Expand this to ensure that this-&gt;contains(point).
A base class for factory classes used to reconstruct objects from records.
Definition: Persistable.h:214
T _val
#define INSTANTIATE(TYPE)
ImagePtr getImage() const
Return a (shared_ptr to) the MaskedImage&#39;s image.
Definition: MaskedImage.h:960
static void readPeaks(afw::table::BaseCatalog const &, Footprint &)
Static method used to unpersist the PeakCatalog member of the Footprint class.
Definition: Footprint.cc:291
MaskPtr getMask() const
Return a (shared_ptr to) the MaskedImage&#39;s mask.
Definition: MaskedImage.h:972
An integer coordinate rectangle.
Definition: Box.h:55
A set of pixels in an Image, including those pixels&#39; actual values.
geom::Point2I getXY0() const
Return the image&#39;s origin.
Definition: Image.h:334
int getY() const
Return the y-value.
Definition: Span.h:80
virtual std::shared_ptr< afw::table::io::Persistable > read(InputArchive const &archive, CatalogVector const &catalogs) const
Construct a new object from the given InputArchive and vector of catalogs.
static std::unique_ptr< Footprint > readSpanSet(afw::table::BaseCatalog const &, afw::table::io::InputArchive const &)
Static method used to unpersist the SpanSet member of the Footprint class.
Definition: Footprint.cc:267
std::shared_ptr< geom::SpanSet > getSpans() const
Return a shared pointer to the SpanSet.
Definition: Footprint.h:116
A class to manipulate images, masks, and variance as a single object.
Definition: MaskedImage.h:81
details::FlatNdGetter< T, inA, inB > ndFlat(ndarray::Array< T, inA, inB > const &array)
Marks a ndarray to be interpreted as a 1D vector when applying a functor from a SpanSet.
int max
Definition: BoundedField.cc:99
table::Key< std::string > name
Definition: ApCorrMap.cc:71
std::shared_ptr< Footprint > mergeFootprints(Footprint const &footprint1, Footprint const &footprint2)
Merges two Footprints – appends their peaks, and unions their spans, returning a new Footprint...
Definition: Footprint.cc:321
std::int32_t MaskPixel
default type for Masks and MaskedImage Masks
Class to describe the properties of a detected object from an image.
Definition: Footprint.h:62
double x
BaseCatalog makeCatalog(Schema const &schema)
Return a new, empty catalog with the given schema.
details::ImageNdGetter< T, inA, inB > ndImage(ndarray::Array< T, inA, inB > const &array, afwGeom::Point2I xy0=afwGeom::Point2I())
Marks a ndarray to be interpreted as an image when applying a functor from a SpanSet.
std::shared_ptr< HeavyFootprint< ImagePixelT, MaskPixelT, VariancePixelT > > mergeHeavyFootprints(HeavyFootprint< ImagePixelT, MaskPixelT, VariancePixelT > const &h1, HeavyFootprint< ImagePixelT, MaskPixelT, VariancePixelT > const &h2)
Sum the two given HeavyFootprints h1 and h2, returning a HeavyFootprint with the union footprint...
afw::table::Key< afw::table::Array< MaskPixelT > > mask
A vector of catalogs used by Persistable.
Definition: CatalogVector.h:29
void write(OutputArchiveHandle &handle) const override
Write an instance of a Footprint to an output Archive.
Definition: Footprint.cc:252
Base class for all records.
Definition: BaseRecord.h:29
int min
Definition: Coord.cc:160
geom::Point2I getXY0() const
Return the image&#39;s origin.
Definition: MaskedImage.h:1024
afw::table::Key< afw::table::Array< ImagePixelT > > image
ndarray::Array< ImagePixelT, 1, 1 > getImageArray()
void insert(lsst::afw::image::MaskedImage< ImagePixelT, MaskPixelT, VariancePixelT > &mimage) const
Replace all the pixels in the image with the values in the HeavyFootprint.
Field< T >::Value get(Key< T > const &key) const
Return the value of a field for the given key.
Definition: BaseRecord.h:123
void saveCatalog(BaseCatalog const &catalog)
Save a catalog in the archive.
Point< int, 2 > Point2I
Definition: Point.h:270
int getX1() const
Return the ending x-value.
Definition: Span.h:78
A multi-catalog archive object used to load table::io::Persistable objects.
Definition: InputArchive.h:31
py::object result
Definition: schema.cc:290
float VariancePixel
default type for MaskedImage variance images
A class to represent a 2-dimensional array of pixels.
Definition: Image.h:486
HeavyFootprint()
Default constructor for HeavyFootprint.
afw::table::Schema schema
Definition: GaussianPsf.cc:43
geom::Box2I getBBox() const
Return the Footprint&#39;s bounding box.
Definition: Footprint.h:209
std::shared_ptr< RecordT > addNew()
Create a new record, add it to the end of the catalog, and return a pointer to it.
Definition: Catalog.h:463