47 #pragma clang diagnostic push
48 #pragma clang diagnostic ignored "-Wunused-variable"
49 #pragma clang diagnostic pop
50 #include "boost/format.hpp"
51 #include "boost/filesystem/path.hpp"
53 #include "boost/functional/hash.hpp"
55 #include "lsst/daf/base.h"
56 #include "lsst/daf/base/Citizen.h"
57 #include "lsst/pex/exceptions.h"
58 #include "lsst/log/Log.h"
67 #include "boost/mpl/vector.hpp"
68 #include "boost/gil/gil_all.hpp"
72 namespace afwGeom = lsst::afw::geom;
73 namespace dafBase = lsst::daf::base;
74 namespace pexExcept = lsst::pex::exceptions;
84 void setInitMaskBits(std::shared_ptr<detail::MaskDict> dict);
93 typedef detail::MaskPlaneDict::value_type value_type;
94 typedef detail::MaskPlaneDict::const_iterator const_iterator;
100 bool operator==(MapWithHash
const& rhs)
const {
return _hash == rhs._hash; }
102 const_iterator begin()
const {
return _dict.begin(); }
103 const_iterator end()
const {
return _dict.end(); }
104 const_iterator find(detail::MaskPlaneDict::key_type
const&
name)
const {
return _dict.find(name); }
106 void add(std::string
const& str,
int val) {
111 bool empty()
const {
return _dict.empty(); }
113 void clear() {
_dict.clear(); }
115 std::size_t size()
const {
return _dict.size(); }
117 void erase(std::string
const& str) {
126 std::size_t getHash()
const {
return _hash; }
133 std::size_t _calcHash() {
135 for (const_iterator ptr = begin(); ptr != end(); ++ptr) {
137 boost::hash<std::string>()((*ptr).first + str(boost::format(
"%d") % ptr->second));
144 bool operator!=(MapWithHash
const& lhs, MapWithHash
const& rhs) {
return !(lhs == rhs); }
155 friend class ::lsst::afw::image::DictState;
159 MaskDict(MapWithHash
const* dict) : MapWithHash(*dict) {}
164 static std::shared_ptr<MaskDict>
setDefaultDict(std::shared_ptr<MaskDict> dict);
166 std::shared_ptr<MaskDict>
clone()
const;
174 for (MapWithHash::const_iterator ptr = begin(); ptr != end(); ++ptr) {
175 std::cout <<
"Plane " << ptr->second <<
" -> " << ptr->first << std::endl;
190 friend class detail::MaskDict;
192 typedef std::map<MapWithHash*, int> HandleList;
204 for (HandleList::iterator ptr =
_dicts.begin(); ptr !=
_dicts.end(); ++ptr) {
210 template <
typename FunctorT>
211 void forEachMaskDict(FunctorT func) {
212 for (HandleList::const_iterator ptr =
_dicts.begin(); ptr !=
_dicts.end(); ++ptr) {
218 std::shared_ptr<detail::MaskDict> getDefaultDict() {
219 static bool first =
true;
230 std::shared_ptr<detail::MaskDict> setDefaultDict(std::shared_ptr<detail::MaskDict> newDefaultMaskDict) {
238 void eraseDict(MapWithHash* dict) {
_dicts.erase(dict); }
240 std::shared_ptr<detail::MaskDict> incrDefaultVersion() {
252 static DictState _state;
266 std::shared_ptr<MaskDict> dict = _state.getDefaultDict();
269 MapWithHash mwh(mpd);
270 dict = std::shared_ptr<MaskDict>(
new MaskDict(&mwh));
271 _state.addDict(dict.get());
278 return _state.setDefaultDict(dict);
282 std::shared_ptr<MaskDict> dict(
new MaskDict(*
this));
284 _state.addDict(dict.get());
298 MapWithHash::const_iterator
const it = std::max_element(
303 int id = it->second + 1;
305 for (
int i = 0; i < id; ++i) {
306 MapWithHash::const_iterator
const it =
309 std::bind(std::equal_to<int>(),
320 MapWithHash::const_iterator i = find(name);
322 return (i == end()) ? -1 : i->second;
333 void setInitMaskBits(std::shared_ptr<detail::MaskDict> dict) {
335 dict->add(
"BAD", ++i);
336 dict->add(
"SAT", ++i);
337 dict->add(
"INTRP", ++i);
338 dict->add(
"CR", ++i);
339 dict->add(
"EDGE", ++i);
340 dict->add(
"DETECTED", ++i);
341 dict->add(
"DETECTED_NEGATIVE", ++i);
342 dict->add(
"SUSPECT", ++i);
343 dict->add(
"NO_DATA", ++i);
347 template <
typename MaskPixelT>
348 void Mask<MaskPixelT>::_initializePlanes(
MaskPlaneDict const& planeDefs) {
349 LOGL_DEBUG(
"afw.image.Mask",
"Number of mask planes: %d", getNumPlanesMax());
354 template <
typename MaskPixelT>
357 _initializePlanes(planeDefs);
361 template <
typename MaskPixelT>
365 _initializePlanes(planeDefs);
366 *
this = initialValue;
369 template <
typename MaskPixelT>
372 _initializePlanes(planeDefs);
376 template <
typename MaskPixelT>
380 _initializePlanes(planeDefs);
381 *
this = initialValue;
384 template <
typename MaskPixelT>
387 _initializePlanes(planeDefs);
391 template <
typename MaskPixelT>
394 _initializePlanes(planeDefs);
395 *
this = initialValue;
398 template <
typename MaskPixelT>
400 :
ImageBase<MaskPixelT>(rhs, bbox, origin, deep), _maskDict(rhs._maskDict) {}
402 template <
typename MaskPixelT>
404 :
ImageBase<MaskPixelT>(rhs, deep), _maskDict(rhs._maskDict) {}
406 template <
typename MaskPixelT>
408 :
image::
ImageBase<MaskPixelT>(array, deep, xy0), _maskDict(detail::MaskDict::makeMaskDict()) {}
410 template <
typename PixelT>
415 swap(_maskDict, rhs._maskDict);
418 template <
typename PixelT>
423 template <
typename MaskPixelT>
431 template <
typename MaskPixelT>
433 fill_pixels(_getRawView(), rhs);
438 #ifndef DOXYGEN // doc for this section is already in header
440 template <
typename MaskPixelT>
441 Mask<MaskPixelT>::Mask(std::string
const& fileName,
int hdu, std::shared_ptr<daf::base::PropertySet> metadata,
443 :
ImageBase<MaskPixelT>(), _maskDict(detail::MaskDict::makeMaskDict()) {
445 fitsfile.setHdu(hdu);
446 *
this =
Mask(fitsfile, metadata, bbox, origin, conformMasks);
449 template <
typename MaskPixelT>
451 std::shared_ptr<daf::base::PropertySet> metadata,
afw::geom::Box2I const& bbox,
453 : ImageBase<MaskPixelT>(), _maskDict(detail::MaskDict::makeMaskDict()) {
455 fitsfile.setHdu(hdu);
456 *
this =
Mask(fitsfile, metadata, bbox, origin, conformMasks);
459 template <
typename MaskPixelT>
462 : ImageBase<MaskPixelT>(), _maskDict(detail::MaskDict::makeMaskDict()) {
464 typedef boost::mpl::vector<unsigned char, unsigned short, short> fits_mask_types;
470 fits_read_image<fits_mask_types>(fitsfile, *
this, *metadata, bbox, origin);
488 template <
typename MaskPixelT>
490 std::shared_ptr<lsst::daf::base::PropertySet const> metadata_i,
491 std::string
const& mode)
const {
493 writeFits(fitsfile, metadata_i);
496 template <
typename MaskPixelT>
498 std::shared_ptr<lsst::daf::base::PropertySet const> metadata_i,
499 std::string
const& mode)
const {
501 writeFits(fitsfile, metadata_i);
504 template <
typename MaskPixelT>
506 std::shared_ptr<lsst::daf::base::PropertySet const> metadata_i)
const {
507 std::shared_ptr<dafBase::PropertySet> metadata;
509 metadata = metadata_i->deepCopy();
513 addMaskPlanesToMetadata(metadata);
517 std::shared_ptr<dafBase::PropertySet> wcsAMetadata =
519 metadata->combine(wcsAMetadata);
527 struct addPlaneFunctor {
528 addPlaneFunctor(std::string
const& name,
int id) :
_name(name),
_id(id) {}
530 void operator()(MapWithHash* dict) {
531 detail::MaskPlaneDict::const_iterator
const it =
533 dict->begin(), dict->end(),
535 std::placeholders::_1),
537 if (it != dict->end()) {
541 if (dict->find(
_name) == dict->end()) {
551 template <
typename MaskPixelT>
554 MaskPlaneDict const& mpd = _maskPlaneDict()->getMaskPlaneDict();
555 for (MaskPlaneDict::const_iterator iter = mpd.begin(); iter != mpd.end(); ++iter) {
556 if (value & getBitMask(iter->second)) {
557 if (result.size() > 0) {
560 result += iter->first;
566 template <
typename MaskPixelT>
568 int id = getMaskPlaneNoThrow(name);
571 id = _maskPlaneDict()->getUnusedPlane();
576 if (
id >= getNumPlanesMax()) {
577 throw LSST_EXCEPT(pexExcept::RuntimeError,
578 str(boost::format(
"Max number of planes (%1%) already used") % getNumPlanesMax()));
581 _state.forEachMaskDict(addPlaneFunctor(name,
id));
586 template <
typename MaskPixelT>
588 if (planeId < 0 || planeId >= getNumPlanesMax()) {
590 pexExcept::RangeError,
591 str(boost::format(
"mask plane ID must be between 0 and %1%") % (getNumPlanesMax() - 1)));
594 _maskPlaneDict()->add(name, planeId);
599 template <
typename MaskPixelT>
601 return _maskDict->getMaskPlaneDict();
604 template <
typename MaskPixelT>
607 throw LSST_EXCEPT(pexExcept::InvalidParameterError,
608 str(boost::format(
"Plane %s doesn't exist in the default Mask") % name));
612 _maskPlaneDict()->erase(name);
615 template <
typename MaskPixelT>
619 clearMaskPlane(getMaskPlane(name));
624 _maskDict = _maskDict->clone();
627 _maskDict->erase(name);
630 removeMaskPlane(name);
634 template <
typename MaskPixelT>
636 return (planeId >= 0 && planeId < getNumPlanesMax()) ? (1 << planeId) : 0;
639 template <
typename MaskPixelT>
640 MaskPixelT Mask<MaskPixelT>::getBitMask(
int planeId) {
641 MaskPlaneDict const& mpd = _maskPlaneDict()->getMaskPlaneDict();
643 for (MaskPlaneDict::const_iterator i = mpd.begin(); i != mpd.end(); ++i) {
644 if (planeId == i->second) {
645 MaskPixelT
const bitmask = getBitMaskNoThrow(planeId);
652 throw LSST_EXCEPT(pexExcept::InvalidParameterError,
653 str(boost::format(
"Invalid mask plane ID: %d") % planeId));
656 template <
typename MaskPixelT>
658 int const plane = getMaskPlaneNoThrow(name);
661 throw LSST_EXCEPT(pexExcept::InvalidParameterError,
662 str(boost::format(
"Invalid mask plane name: %s") % name));
668 template <
typename MaskPixelT>
673 template <
typename MaskPixelT>
675 return getBitMask(getMaskPlane(name));
678 template <
typename MaskPixelT>
680 MaskPixelT mpix = 0x0;
681 for (std::vector<std::string>::const_iterator it = name.begin(); it != name.end(); ++it) {
682 mpix |= getBitMask(getMaskPlane(*it));
687 template <
typename MaskPixelT>
689 return _maskPlaneDict()->size();
692 template <
typename MaskPixelT>
694 _maskPlaneDict()->clear();
697 template <
typename MaskPixelT>
702 template <
typename MaskPixelT>
704 *
this &= ~getBitMask(planeId);
707 template <
typename MaskPixelT>
711 if (*_maskDict == *currentMD) {
719 MaskPixelT keepBitmask = 0;
720 MaskPixelT canonicalMask[
sizeof(MaskPixelT) * 8];
721 MaskPixelT currentMask[
sizeof(MaskPixelT) * 8];
724 for (MaskPlaneDict::const_iterator i = currentPlaneDict.begin(); i != currentPlaneDict.end(); i++) {
725 std::string
const name = i->first;
726 int const currentPlaneNumber = i->second;
727 int canonicalPlaneNumber = getMaskPlaneNoThrow(name);
729 if (canonicalPlaneNumber < 0) {
730 canonicalPlaneNumber = addMaskPlane(name);
733 if (canonicalPlaneNumber == currentPlaneNumber) {
734 keepBitmask |= getBitMask(canonicalPlaneNumber);
736 canonicalMask[numReMap] = getBitMask(canonicalPlaneNumber);
737 currentMask[numReMap] = getBitMaskNoThrow(currentPlaneNumber);
744 for (
int r = 0; r != this->getHeight(); ++r) {
745 for (
typename Mask::x_iterator ptr = this->row_begin(r), end = this->row_end(r); ptr != end;
747 MaskPixelT
const pixel = *ptr;
749 MaskPixelT newPixel = pixel & keepBitmask;
750 for (
int i = 0; i < numReMap; i++) {
751 if (pixel & currentMask[i]) newPixel |= canonicalMask[i];
763 template <
typename MaskPixelT>
768 template <
typename MaskPixelT>
774 template <
typename MaskPixelT>
779 template <
typename MaskPixelT>
785 template <
typename MaskPixelT>
791 template <
typename MaskPixelT>
797 template <
typename MaskPixelT>
799 if (*_maskDict != *other._maskDict) {
800 throw LSST_EXCEPT(pexExcept::RuntimeError,
"Mask dictionaries do not match");
804 template <
typename MaskPixelT>
806 transform_pixels(_getRawView(), _getRawView(),
807 [&val](MaskPixelT
const& l) -> MaskPixelT {
return l | val; });
811 template <
typename MaskPixelT>
813 checkMaskDictionaries(rhs);
816 throw LSST_EXCEPT(pexExcept::LengthError,
817 str(boost::format(
"Images are of different size, %dx%d v %dx%d") %
820 transform_pixels(_getRawView(), rhs.
_getRawView(), _getRawView(),
821 [](MaskPixelT
const& l, MaskPixelT
const& r) -> MaskPixelT {
return l | r; });
825 template <
typename MaskPixelT>
827 transform_pixels(_getRawView(), _getRawView(), [&val](MaskPixelT
const& l) {
return l & val; });
831 template <
typename MaskPixelT>
833 checkMaskDictionaries(rhs);
836 throw LSST_EXCEPT(pexExcept::LengthError,
837 str(boost::format(
"Images are of different size, %dx%d v %dx%d") %
840 transform_pixels(_getRawView(), rhs.
_getRawView(), _getRawView(),
841 [](MaskPixelT
const& l, MaskPixelT
const& r) -> MaskPixelT {
return l & r; });
845 template <
typename MaskPixelT>
847 transform_pixels(_getRawView(), _getRawView(),
848 [&val](MaskPixelT
const& l) -> MaskPixelT {
return l ^ val; });
852 template <
typename MaskPixelT>
854 checkMaskDictionaries(rhs);
857 throw LSST_EXCEPT(pexExcept::LengthError,
858 str(boost::format(
"Images are of different size, %dx%d v %dx%d") %
861 transform_pixels(_getRawView(), rhs.
_getRawView(), _getRawView(),
862 [](MaskPixelT
const& l, MaskPixelT
const& r) -> MaskPixelT {
return l ^ r; });
866 template <
typename MaskPixelT>
868 MaskPixelT
const bitMask = getBitMask(planeId);
870 for (
int x = x0;
x <= x1;
x++) {
871 operator()(
x, y) = operator()(
x, y) | bitMask;
875 template <
typename MaskPixelT>
878 throw LSST_EXCEPT(pexExcept::InvalidParameterError,
"Null std::shared_ptr<PropertySet>");
882 typedef std::vector<std::string> NameList;
883 NameList paramNames = metadata->paramNames(
false);
884 for (NameList::const_iterator i = paramNames.begin(); i != paramNames.end(); ++i) {
885 if (i->compare(0, maskPlanePrefix.size(), maskPlanePrefix) == 0) {
886 metadata->remove(*i);
890 MaskPlaneDict const& mpd = _maskPlaneDict()->getMaskPlaneDict();
893 for (MaskPlaneDict::const_iterator i = mpd.begin(); i != mpd.end(); ++i) {
894 std::string
const& planeName = i->first;
895 int const planeNumber = i->second;
897 if (planeName !=
"") {
898 metadata->add(maskPlanePrefix + planeName, planeNumber);
903 template <
typename MaskPixelT>
905 std::shared_ptr<dafBase::PropertySet const> metadata) {
909 typedef std::vector<std::string> NameList;
910 NameList paramNames = metadata->paramNames(
false);
911 int numPlanesUsed = 0;
914 for (NameList::const_iterator i = paramNames.begin(); i != paramNames.end(); ++i) {
915 if (i->compare(0, maskPlanePrefix.size(), maskPlanePrefix) == 0) {
917 std::string planeName = i->substr(maskPlanePrefix.size());
918 int const planeId = metadata->getAsInt(*i);
920 MaskPlaneDict::const_iterator plane = newDict.find(planeName);
921 if (plane != newDict.end() && planeId != plane->second) {
922 throw LSST_EXCEPT(pexExcept::RuntimeError,
"File specifies plane " + planeName +
" twice");
924 for (MaskPlaneDict::const_iterator j = newDict.begin(); j != newDict.end(); ++j) {
925 if (planeId == j->second) {
926 throw LSST_EXCEPT(pexExcept::RuntimeError,
927 str(boost::format(
"File specifies plane %s has same value (%d) as %s") %
928 planeName % planeId % j->first));
932 if (numPlanesUsed >= getNumPlanesMax()) {
935 pexExcept::RuntimeError,
936 str(boost::format(
"Max number of planes (%1%) already used") % getNumPlanesMax()));
938 newDict[planeName] = planeId;
944 template <
typename MaskPixelT>
952 template <
typename MaskPixelT>
955 template <
typename MaskPixelT>
963 template class Mask<MaskPixel>;
static std::string interpret(MaskPixelT value)
Interpret a mask value as a comma-separated list of mask plane names.
afw::table::PointKey< int > dimensions
static void clearMaskPlaneDict()
Reset the maskPlane dictionary.
std::string const & _name
bool operator!=(Coord const &lhs, Coord const &rhs)
Inequality; the complement of equality.
void fits_write_image(fits::Fits &fitsfile, const ImageT &image, std::shared_ptr< daf::base::PropertySet const > metadata=std::shared_ptr< daf::base::PropertySet const >())
void swap(ImageBase< PixelT > &a, ImageBase< PixelT > &b)
static int getMaskPlane(const std::string &name)
Return the mask plane number corresponding to a plane name.
std::map< std::string, int > MaskPlaneDict
Mask & operator=(MaskPixelT const rhs)
_view_t::x_iterator x_iterator
An iterator for traversing the pixels in a row.
detail::MaskPlaneDict MaskPlaneDict
bool operator==(CoordKey const &lhs, CoordKey const &rhs)
Compare CoordKeys for equality using the constituent Keys.
int getUnusedPlane() const
static void addMaskPlanesToMetadata(std::shared_ptr< lsst::daf::base::PropertySet >)
Given a PropertySet, replace any existing MaskPlane assignments with the current ones.
static int getNumPlanesUsed()
static MaskPlaneDict parseMaskPlaneMetadata(std::shared_ptr< lsst::daf::base::PropertySet const > metadata)
Given a PropertySet that contains the MaskPlane assignments, setup the MaskPlanes.
A simple struct that combines the two arguments that must be passed to most cfitsio routines and cont...
The base class for all image classed (Image, Mask, MaskedImage, ...)
void removeAndClearMaskPlane(const std::string &name, bool const removeFromDefault=false)
Clear all pixels of the specified mask and remove the plane from the mask plane dictionary; optionall...
ImageBase< MaskPixelT >::PixelReference operator()(int x, int y)
get a reference to the specified pixel
An integer coordinate rectangle.
Mask & operator&=(Mask const &rhs)
AND a Mask into a Mask.
Mask(unsigned int width, unsigned int height, MaskPlaneDict const &planeDefs=MaskPlaneDict())
Construct a Mask initialized to 0x0.
detail::MaskPlaneDict _dict
geom::Extent2I getDimensions() const
Return the image's size; useful for passing to constructors.
Represent a 2-dimensional array of bitmask pixels.
Lifetime-management for memory that goes into FITS memory files.
_view_t _getRawView() const
void setMaskPlaneValues(const int plane, const int x0, const int x1, const int y)
Set the bit specified by "planeId" for pixels (x0, y) ...
table::Key< std::string > name
A class used to request that array accesses be checked.
int getHeight() const
Return the number of rows in the image.
static MaskPixelT getPlaneBitMask(const std::vector< std::string > &names)
Return the bitmask corresponding to a vector of plane names OR'd together.
void swap(ImageBase &rhs)
std::shared_ptr< MaskDict > clone() const
static void listMaskDicts()
static std::shared_ptr< MaskDict > incrDefaultVersion()
static void removeMaskPlane(const std::string &name)
static std::shared_ptr< MaskDict > makeMaskDict()
MaskPlaneDict const & getMaskPlaneDict() const
Return the Mask's maskPlaneDict.
void writeFits(std::string const &fileName, std::shared_ptr< lsst::daf::base::PropertySet const > metadata=std::shared_ptr< lsst::daf::base::PropertySet >(), std::string const &mode="w") const
Write a mask to a regular FITS file.
Mask & operator|=(Mask const &rhs)
OR a Mask into a Mask.
table::PointKey< int > pixel
static std::shared_ptr< MaskDict > setDefaultDict(std::shared_ptr< MaskDict > dict)
std::shared_ptr< lsst::daf::base::PropertyList > createTrivialWcsAsPropertySet(std::string const &wcsName, int const x0=0, int const y0=0)
void conformMaskPlanes(const MaskPlaneDict &masterPlaneDict)
Adjust this mask to conform to the standard Mask class's mask plane dictionary, adding any new mask p...
std::shared_ptr< detail::MaskDict > _defaultMaskDict
Mask & operator^=(Mask const &rhs)
XOR a Mask into a Mask.
void clearMaskPlane(int plane)
Clear the specified bit in all pixels.
void printMaskPlanes() const
print the mask plane dictionary to std::cout
int getWidth() const
Return the number of columns in the image.
void clearAllMaskPlanes()
Clear all the pixels.
static int addMaskPlane(const std::string &name)
PixelReference operator()(int x, int y)
Return a reference to the pixel (x, y)
std::string const wcsNameForXY0
int getMaskPlane(const std::string &name) const
lsst::daf::base::PropertyList PropertyList