lsst.afw  15.0-21-g91b8abf62
SpanSet.h
Go to the documentation of this file.
1 // -*- lsst-c++ -*-
2 
3 /*
4  * LSST Data Management System
5  * Copyright 2008-2016 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 <https://www.lsstcorp.org/LegalNotices/>.
23  */
24 
25 #ifndef LSST_AFW_GEOM_SPANSET_H
26 #define LSST_AFW_GEOM_SPANSET_H
27 
28 #include <vector>
29 #include <algorithm>
30 #include <functional>
31 #include <memory>
32 #include <utility>
33 #include "lsst/pex/exceptions.h"
34 #include "lsst/afw/geom/Span.h"
35 #include "lsst/afw/geom/Box.h"
36 #include "lsst/afw/image/Mask.h"
42 #include "lsst/afw/image/Image.h"
44 
45 namespace lsst {
46 namespace afw {
47 namespace geom {
48 namespace details {
49 
50 /* Functor object to be used with fromMask function
51  */
52 template <typename T>
54 public:
55  bool operator()(T pixelValue) { return pixelValue != 0; }
56 };
57 
58 } // end lsst::afw::geom::details
59 
66 enum class Stencil { CIRCLE, BOX, MANHATTAN };
67 
77 class SpanSet : public afw::table::io::PersistableFacade<lsst::afw::geom::SpanSet>,
79 public:
82  typedef Span value_type;
83  typedef value_type const &const_reference;
84 
85  // Expose properties of the underlying vector containing spans such that the
86  // SpanSet can be considered a container.
87  // Return the constant versions as SpanSets should be immutable
88  const_iterator begin() const { return _spanVector.cbegin(); }
89  const_iterator end() const { return _spanVector.cend(); }
90  const_iterator cbegin() const { return _spanVector.cbegin(); }
91  const_iterator cend() const { return _spanVector.cend(); }
92  const_reference front() const { return const_cast<geom::Span &>(_spanVector.front()); }
93  const_reference back() const { return const_cast<geom::Span &>(_spanVector.back()); }
94  size_type size() const { return _spanVector.size(); }
95  bool empty() const { return _spanVector.empty(); }
96 
101  SpanSet();
102 
107  explicit SpanSet(Box2I const &box);
108 
122  template <typename iter>
123  SpanSet(iter begin, iter end, bool normalize = true) : _spanVector(begin, end) {
124  // Return a null SpanSet if spanVector is 0
125  if (_spanVector.size() == 0) {
126  _bbox = geom::Box2I();
127  _area = 0;
128  } else {
129  if (normalize) {
130  _runNormalize();
131  }
132  _initialize();
133  }
134  }
135 
147  explicit SpanSet(std::vector<Span> const &vec, bool normalize = true);
148 
160  explicit SpanSet(std::vector<Span> &&vec, bool normalize = true);
161 
162  // Explicitly delete copy and move constructors
163  SpanSet(SpanSet const &other) = delete;
164  SpanSet(SpanSet &&other) = delete;
165  ~SpanSet() = default;
166 
167  SpanSet &operator=(SpanSet const &) = default;
168  // Delegate to copy-assignment for backwards compatibility
169  SpanSet &operator=(SpanSet &&other) { return *this = other; }
170 
171  // Define class methods
174  size_type getArea() const;
175 
178  Box2I getBBox() const;
179 
187  bool isContiguous() const;
188 
194  std::shared_ptr<SpanSet> shiftedBy(int x, int y) const;
195 
200  std::shared_ptr<SpanSet> shiftedBy(Extent2I const &offset) const;
201 
206  std::shared_ptr<SpanSet> clippedTo(Box2I const &box) const;
207 
212  std::shared_ptr<SpanSet> transformedBy(LinearTransform const &t) const;
213 
218  std::shared_ptr<SpanSet> transformedBy(AffineTransform const &t) const;
219 
224  std::shared_ptr<SpanSet> transformedBy(TransformPoint2ToPoint2 const &t) const;
225 
230  bool overlaps(SpanSet const &other) const;
231 
236  bool contains(SpanSet const &other) const;
237 
242  bool contains(Point2I const &point) const;
243 
246  Point2D computeCentroid() const;
247 
250  ellipses::Quadrupole computeShape() const;
251 
260  std::shared_ptr<SpanSet> dilated(int r, Stencil s = Stencil::CIRCLE) const;
261 
268  std::shared_ptr<SpanSet> dilated(SpanSet const &other) const;
269 
278  std::shared_ptr<SpanSet> eroded(int r, Stencil s = Stencil::CIRCLE) const;
279 
286  std::shared_ptr<SpanSet> eroded(SpanSet const &other) const;
287 
302  template <typename Pixel, int inN, int inC>
303  ndarray::Array<typename std::remove_const<Pixel>::type, inN - 1, inN - 1> flatten(
304  ndarray::Array<Pixel, inN, inC> const &input, Point2I const &xy0 = Point2I()) const {
305  // Populate a lower dimensional array with the values from input taken at the points of SpanSet
306  auto outputShape = ndarray::concatenate(ndarray::makeVector(getArea()),
307  input.getShape().template last<inN - 2>());
308  ndarray::Array<typename std::remove_const<Pixel>::type, inN - 1, inN - 1> outputArray =
309  ndarray::allocate(outputShape);
310  outputArray.deep() = 0;
311  flatten(outputArray, input, xy0);
312  return outputArray;
313  }
314 
334  template <typename PixelIn, typename PixelOut, int inA, int outC, int inC>
335  void flatten(ndarray::Array<PixelOut, inA - 1, outC> const &output,
336  ndarray::Array<PixelIn, inA, inC> const &input, Point2I const &xy0 = Point2I()) const {
337  auto ndAssigner = [](Point2I const &point,
338  typename details::FlatNdGetter<PixelOut, inA - 1, outC>::Reference out,
339  typename details::ImageNdGetter<PixelIn, inA, inC>::Reference in) { out = in; };
340  // Populate array output with values from input at positions given by SpanSet
341  applyFunctor(ndAssigner, ndarray::ndFlat(output), ndarray::ndImage(input, xy0));
342  }
343 
357  template <typename Pixel, int inA, int inC>
358  ndarray::Array<typename std::remove_const<Pixel>::type, inA + 1, inA + 1> unflatten(
359  ndarray::Array<Pixel, inA, inC> const &input) const {
360  // Create a higher dimensional array the size of the bounding box and extra dimensions of input.
361  // Populate values from input, placed at locations corresponding to SpanSet, offset by the
362  // lower corner of the bounding box
363  auto existingShape = input.getShape();
364  typename decltype(existingShape)::Element height = _bbox.getHeight();
365  typename decltype(existingShape)::Element width = _bbox.getWidth();
366  auto outputShape = ndarray::concatenate(ndarray::makeVector(height, width),
367  input.getShape().template last<inA - 1>());
368  ndarray::Array<typename std::remove_const<Pixel>::type, inA + 1, inA + 1> outputArray =
369  ndarray::allocate(outputShape);
370  outputArray.deep() = 0;
371  unflatten(outputArray, input, Point2I(_bbox.getMinX(), _bbox.getMinY()));
372  return outputArray;
373  }
374 
394  template <typename PixelIn, typename PixelOut, int inA, int outC, int inC>
395  void unflatten(ndarray::Array<PixelOut, inA + 1, outC> const &output,
396  ndarray::Array<PixelIn, inA, inC> const &input, Point2I const &xy0 = Point2I()) const {
397  // Populate 2D ndarray output with values from input, at locations defined by SpanSet, optionally
398  // offset by xy0
399  auto ndAssigner = [](Point2I const &point,
401  typename details::FlatNdGetter<PixelIn, inA, inC>::Reference in) { out = in; };
402  applyFunctor(ndAssigner, ndarray::ndImage(output, xy0), ndarray::ndFlat(input));
403  }
404 
412  template <typename ImageT>
414  auto copyFunc = [](lsst::afw::geom::Point2I const &point, ImageT const &srcPix, ImageT &destPix) {
415  destPix = srcPix;
416  };
417  applyFunctor(copyFunc, src, dest);
418  }
419 
429  template <typename ImageT, typename MaskT, typename VarT>
432  auto copyFunc = [](lsst::afw::geom::Point2I const &point, ImageT const &srcPix, MaskT const &srcMask,
433  VarT const &srcVar, ImageT &destPix, MaskT &destMask, VarT &destVar) {
434  destPix = srcPix;
435  destMask = srcMask;
436  destVar = srcVar;
437  };
438  applyFunctor(copyFunc, *(src.getImage()), *(src.getMask()), *(src.getVariance()), *(dest.getImage()),
439  *(dest.getMask()), *(dest.getVariance()));
440  }
441 
455  template <typename ImageT>
456  void setImage(image::Image<ImageT> &image, ImageT val, geom::Box2I const &region = geom::Box2I(),
457  bool doClip = false) const;
458 
504  template <typename Functor, typename... Args>
505  // Normally std::forward would be used with a universal reference, however
506  // this function does not use one because without std::forward the
507  // compiler is forced to keep any r-value references alive for the
508  // duration of the function call
509  void applyFunctor(Functor &&func, Args &&... args) const {
510  /* Use a variadic template to take a functor object, and an arbitrary number
511  of parameters. For each of the arguments, construct a Getter class using
512  a function (makeGetter) which is overloaded to all the types applyFunctorImpl
513  supports: Images, MaskedImages, Exposures, ndarrays, numeric values, and
514  iterators. The functor and the getters are then passed to the implementation of
515  applyFunctor where the values of the input arguments are intelligently
516  generated at each point in SpanSet, and passed to the functor object for evaluation.
517  */
518  applyFunctorImpl(func, details::makeGetter(args)...);
519  }
520 
528  template <typename T>
529  void setMask(lsst::afw::image::Mask<T> &target, T bitmask) const;
530 
538  template <typename T>
539  void clearMask(lsst::afw::image::Mask<T> &target, T bitmask) const;
540 
541  // SpanSet functions
546  std::shared_ptr<SpanSet> intersect(SpanSet const &other) const;
547 
555  template <typename T>
556  std::shared_ptr<SpanSet> intersect(image::Mask<T> const &other, T bitmask) const;
557 
563  std::shared_ptr<SpanSet> intersectNot(SpanSet const &other) const;
564 
573  template <typename T>
574  std::shared_ptr<SpanSet> intersectNot(image::Mask<T> const &other, T bitmask) const;
575 
580  std::shared_ptr<SpanSet> union_(SpanSet const &other) const;
581 
589  template <typename T>
590  std::shared_ptr<SpanSet> union_(image::Mask<T> const &other, T bitmask) const;
591 
592  // Comparison Operators
593 
598  bool operator==(SpanSet const &other) const;
599 
600  /* Compute inequality between two SpanSets
601  *
602  * @param other The SpanSet for which inequality will be computed
603  */
604  bool operator!=(SpanSet const &other) const;
605 
615  static std::shared_ptr<geom::SpanSet> fromShape(int r, Stencil s = Stencil::CIRCLE,
616  Point2I offset = Point2I());
617 
622  static std::shared_ptr<geom::SpanSet> fromShape(geom::ellipses::Ellipse const &ellipse);
623 
640  template <typename T, typename UnaryPredicate = details::AnyBitSetFunctor<T>>
642  image::Mask<T> const &mask, UnaryPredicate comparator = details::AnyBitSetFunctor<T>()) {
643  // Create a vector which will hold all the spans created from the mask
644  std::vector<Span> tempVec;
645  // Grab some variables that will be used in the loop, so that they do not need to be fetched
646  // every iteration.
647  auto const maskArray = mask.getArray();
648  auto const minPoint = mask.getBBox().getMin();
649  auto const dimensions = maskArray.getShape();
650  auto const minY = minPoint.getY();
651  auto const minX = minPoint.getX();
652  auto const dimMinusOne = dimensions[1] - 1;
653  auto const yDim = dimensions[0];
654  auto const xDim = dimensions[1];
655  auto arrIter = maskArray.begin();
656  for (size_t y = 0; y < yDim; ++y) {
657  auto yWithOffset = y + minY;
658  bool inSpan = false; // are we currently in a span of interest?
659  std::size_t start; // starting x value of span we're currently in
660  for (size_t x = 0; x < xDim; ++x) {
661  bool compareValue = comparator((*arrIter)[x]);
662  if (inSpan) {
663  // If we were in a span but now the condition isn't satisfied, it means the Span stops
664  // at the previous pixel.
665  if (!compareValue) {
666  tempVec.push_back(Span(yWithOffset, start + minX, x - 1 + minX));
667  inSpan = false;
668  }
669  } else if (compareValue) {
670  // If we weren't in a span but now the condition is satisfied, we start a new span.
671  inSpan = true;
672  start = x;
673  }
674  }
675  // Since the x loop is over, if we're still in a span, this means the Span was not
676  // closed out and added to the vector. The last pixel should be included in the Span
677  // and the Span should be closed and added to the vector of spans.
678  if (inSpan) {
679  tempVec.push_back(
680  Span(yWithOffset, start + minX, dimMinusOne + minX));
681  }
682  ++arrIter;
683  }
684 
685  // construct a SpanSet from the spans determined above
686  return std::make_shared<SpanSet>(std::move(tempVec), false);
687  }
688 
698  template <typename T>
699  static std::shared_ptr<geom::SpanSet> fromMask(image::Mask<T> const &mask, T bitmask) {
700  return fromMask(mask, [bitmask](T const &bitPattern) { return bitPattern & bitmask; });
701  }
702 
706 
707  bool isPersistable() const override { return true; }
708 
713  std::shared_ptr<geom::SpanSet> findEdgePixels() const;
714 
715 private:
716  /* Returns the name used by the persistence layer to identify the SpanSet class
717  */
718  std::string getPersistenceName() const override;
719 
720  /* Return a string corresponding to the python module that SpanSets lives in
721  */
722  inline std::string getPythonModule() const override { return "lsst.afw.geom"; }
723 
724  /* Writes the representation of the class out to an output archive
725  */
726  void write(OutputArchiveHandle &handle) const override;
727 
728  /* A class which is used by the persistence layer to restore SpanSets from an archive
729  */
730  friend class SpansSetFactory;
731 
732  /* A function to combine overlapping Spans in a SpanSet into a single Span
733  */
734  void _runNormalize();
735 
736  /* Initializes the SpanSet class. Contains code that is common to multiple constructors
737  */
738  void _initialize();
739 
740  /* Label Spans according to contiguous group. If the SpanSet is contiguous, all Spans will be labeled 1.
741  * If there is more than one group each group will receive a label one higher than the previous.
742  */
743  void _label(geom::Span const &spn, std::vector<std::size_t> &labelVector, std::size_t currentLabel,
745  std::pair<std::vector<std::size_t>, std::size_t> _makeLabels() const;
746 
747  std::shared_ptr<SpanSet> makeShift(int x, int y) const;
748 
749  template <typename F, typename... T>
750  void applyFunctorImpl(F &&f, T... args) const {
751  /* Implementation for applying functors, loop over each of the spans, and then
752  * each point. Use the get method in the getters to fetch the value and pass
753  * the point, and the values to the functor
754  */
755  // make sure that the SpanSet is within the bounds of functor arguments
756  details::variadicBoundChecker(_bbox, _area, args...);
757  for (auto const &spn : _spanVector) {
758  // Set the current span in the getter, useful for optimizing value lookups
759  details::variadicSpanSetter(spn, args...);
760  for (int x = spn.getX0(); x <= spn.getX1(); ++x) {
761  Point2I point(x, spn.getY());
762  f(point, args.get()...);
764  }
765  }
766  }
767 
768  // Vector to hold the Spans contained in the SpanSet
769  std::vector<Span> _spanVector;
770 
771  // Box that is large enough to bound all pixels in the SpanSet
772  Box2I _bbox;
773 
774  // Number of pixels in the SpanSet
775  std::size_t _area;
776 };
777 }
778 }
779 } // Close namespace lsst::afw::geom
780 
781 #endif // LSST_AFW_GEOM_SPANSET_H
An ellipse core with quadrupole moments as parameters.
Definition: Quadrupole.h:47
VariancePtr getVariance() const
Return a (shared_ptr to) the MaskedImage&#39;s variance.
Definition: MaskedImage.h:1075
void variadicSpanSetter(Span const spn, T &x)
void unflatten(ndarray::Array< PixelOut, inA+1, outC > const &output, ndarray::Array< PixelIn, inA, inC > const &input, Point2I const &xy0=Point2I()) const
Expand an array by one spatial dimension at points given by SpanSet.
Definition: SpanSet.h:395
Stencil
An enumeration class which describes the shapes.
Definition: SpanSet.h:66
Key< Flag > const & target
size_type size() const
Definition: SpanSet.h:94
afw::table::Key< afw::table::Array< MaskPixelT > > mask
const_iterator end() const
Definition: SpanSet.h:89
geom::Box2I getBBox(ImageOrigin origin=PARENT) const
Definition: ImageBase.h:448
An object passed to Persistable::write to allow it to persist itself.
static std::shared_ptr< geom::SpanSet > fromMask(image::Mask< T > const &mask, UnaryPredicate comparator=details::AnyBitSetFunctor< T >())
Create a SpanSet from a mask.
Definition: SpanSet.h:641
A compact representation of a collection of pixels.
Definition: SpanSet.h:77
A range of pixels within one row of an Image.
Definition: Span.h:55
void applyFunctor(Functor &&func, Args &&... args) const
Apply functor on individual elements from the supplied parameters.
Definition: SpanSet.h:509
typename ndarray::Array< T, N, C >::Reference::Reference Reference
const_iterator cbegin() const
Definition: SpanSet.h:90
bool operator!=(CoordKey const &lhs, CoordKey const &rhs)
Compare CoordKeys for equality using the constituent Keys.
bool operator==(CoordKey const &lhs, CoordKey const &rhs)
Compare CoordKeys for equality using the constituent Keys.
typename ndarray::Array< T, inA, inC >::Reference Reference
const_iterator begin() const
Definition: SpanSet.h:88
ItemVariant const * other
Definition: Schema.cc:55
void copyImage(image::Image< ImageT > const &src, image::Image< ImageT > &dest)
Copy contents of source Image into destination image at the positions defined in the SpanSet...
Definition: SpanSet.h:413
static std::shared_ptr< geom::SpanSet > fromMask(image::Mask< T > const &mask, T bitmask)
Create a SpanSet from a mask.
Definition: SpanSet.h:699
An integer coordinate rectangle.
Definition: Box.h:55
ImagePtr getImage() const
Return a (shared_ptr to) the MaskedImage&#39;s image.
Definition: MaskedImage.h:1042
STL class.
A base class for objects that can be persisted via afw::table::io Archive classes.
Definition: Persistable.h:74
void copyMaskedImage(image::MaskedImage< ImageT, MaskT, VarT > const &src, image::MaskedImage< ImageT, MaskT, VarT > &dest)
Copy contents of source MaskedImage into destination image at the positions defined in the SpanSet...
Definition: SpanSet.h:430
A 2D linear coordinate transformation.
value_type const & const_reference
Definition: SpanSet.h:83
T push_back(T... args)
afw::table::PointKey< int > dimensions
Definition: GaussianPsf.cc:44
const_iterator cend() const
Definition: SpanSet.h:91
A base class for image defects.
int end
Represent a 2-dimensional array of bitmask pixels.
Definition: Mask.h:84
An affine coordinate transformation consisting of a linear transformation and an offset.
std::shared_ptr< RecordT > src
Definition: Match.cc:48
An ellipse defined by an arbitrary BaseCore and a center point.
Definition: Ellipse.h:51
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.
FlatNdGetter< T, inA, inC > makeGetter(FlatNdGetter< T, inA, inC > &getter)
void flatten(ndarray::Array< PixelOut, inA - 1, outC > const &output, ndarray::Array< PixelIn, inA, inC > const &input, Point2I const &xy0=Point2I()) const
Reduce the pixel dimensionality from 2 to 1 of an array at points given by SpanSet.
Definition: SpanSet.h:335
bool empty() const
Definition: SpanSet.h:95
double x
const_reference front() const
Definition: SpanSet.h:92
SpanSet(iter begin, iter end, bool normalize=true)
Construct a SpanSet from an iterator.
Definition: SpanSet.h:123
T move(T... args)
void variadicBoundChecker(Box2I const box, int area, T const &x)
SpanSet & operator=(SpanSet &&other)
Definition: SpanSet.h:169
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.
ndarray::Array< typename std::remove_const< Pixel >::type, inN - 1, inN - 1 > flatten(ndarray::Array< Pixel, inN, inC > const &input, Point2I const &xy0=Point2I()) const
Reduce the pixel dimensionality from 2 to 1 of an array at points given by SpanSet.
Definition: SpanSet.h:303
MaskPtr getMask() const
Return a (shared_ptr to) the MaskedImage&#39;s mask.
Definition: MaskedImage.h:1054
STL class.
std::vector< Span >::const_iterator const_iterator
Definition: SpanSet.h:80
std::vector< Span >::size_type size_type
Definition: SpanSet.h:81
bool isPersistable() const override
Return true if this particular object can be persisted using afw::table::io.
Definition: SpanSet.h:707
ndarray::Array< typename std::remove_const< Pixel >::type, inA+1, inA+1 > unflatten(ndarray::Array< Pixel, inA, inC > const &input) const
Expand an array by one spatial dimension at points given by SpanSet.
Definition: SpanSet.h:358
const_reference back() const
Definition: SpanSet.h:93
Point< int, 2 > Point2I
Definition: Point.h:301
A CRTP facade class for subclasses of Persistable.
Definition: Persistable.h:176
A class to represent a 2-dimensional array of pixels.
Definition: Image.h:69
int y
Definition: SpanSet.cc:44
Transform LSST spatial data, such as Point2D and SpherePoint, using an AST mapping.
Definition: Transform.h:67