lsst.afw  15.0-17-g0b88e3da8+6
Mask.cc
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 <http://www.lsstcorp.org/LegalNotices/>.
23  */
24 
25 // Implementations of Mask class methods
26 
27 /*
28  * There are a number of classes defined here and in Mask.h
29  *
30  * The fundamental type visible to the user is Mask; a 2-d array of pixels. Each of these pixels should
31  * be thought of as a set of bits, and the names of these bits are given by MaskPlaneDict (which is
32  * implemented as a std::map)
33  *
34  * Internally to this file, we have a MapWithHash which is like a std::map, but maintains a hash of its
35  * contents; this is used to check equality efficiently.
36  *
37  * We also have a MaskDict which isa MapWithHash, but also maintains a list of MaskDicts (or equivalently
38  * MapWithHash) allowing us to iterate over these maps, updating them as needed.
39  *
40  * The list of MaskDicts is actually kept as a singleton of a helper class, DictState
41  */
42 
43 #include <functional>
44 #include <list>
45 #include <string>
46 
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"
52 
53 #include "boost/functional/hash.hpp"
54 
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"
59 #include "lsst/afw/image/Mask.h"
60 
62 
63 //
64 // for FITS code
65 //
66 #include "boost/mpl/vector.hpp"
67 #include "boost/gil/gil_all.hpp"
70 
71 namespace afwGeom = lsst::afw::geom;
72 namespace dafBase = lsst::daf::base;
74 
75 namespace lsst {
76 namespace afw {
77 namespace image {
78 namespace detail {
79 class MaskDict;
80 }
81 
82 namespace {
83 void setInitMaskBits(std::shared_ptr<detail::MaskDict> dict);
84 /*
85  * A std::map that maintains a hash value of its contents
86  *
87  * We don't simply inherit from the std::map as we need to force the user to use add and remove;
88  * we could inherit, make operator[] private, and never use MapWithHash via a base-class pointer
89  * but it seemed simpler to only forward the functions we wish to support
90  */
91 struct MapWithHash {
92  typedef detail::MaskPlaneDict::value_type value_type;
93  typedef detail::MaskPlaneDict::const_iterator const_iterator;
94 
95  MapWithHash(detail::MaskPlaneDict const& dict = detail::MaskPlaneDict())
96  : _dict(dict), _hash(_calcHash()) {}
97  ~MapWithHash() {}
98 
99  bool operator==(MapWithHash const& rhs) const { return _hash == rhs._hash; }
100 
101  const_iterator begin() const { return _dict.begin(); }
102  const_iterator end() const { return _dict.end(); }
103  const_iterator find(detail::MaskPlaneDict::key_type const& name) const { return _dict.find(name); }
104 
105  void add(std::string const& str, int val) {
106  _dict[str] = val;
107  _calcHash();
108  }
109 
110  bool empty() const { return _dict.empty(); }
111 
112  void clear() { _dict.clear(); }
113 
114  std::size_t size() const { return _dict.size(); }
115 
116  void erase(std::string const& str) {
117  if (_dict.find(str) != _dict.end()) {
118  _dict.erase(str);
119  _calcHash();
120  }
121  }
122 
123  detail::MaskPlaneDict const& getMaskPlaneDict() const { return _dict; }
124 
125  std::size_t getHash() const { return _hash; }
126 
127 private:
128  detail::MaskPlaneDict _dict;
129  std::size_t _hash;
130 
131  // calculate the hash
132  std::size_t _calcHash() {
133  _hash = 0x0;
134  for (const_iterator ptr = begin(); ptr != end(); ++ptr) {
135  _hash = (_hash << 1) ^
136  boost::hash<std::string>()((*ptr).first + str(boost::format("%d") % ptr->second));
137  }
138 
139  return _hash;
140  }
141 };
142 
143 bool operator!=(MapWithHash const& lhs, MapWithHash const& rhs) { return !(lhs == rhs); }
144 
145 class DictState; // forward declaration
146 }
147 
148 namespace detail {
149 /*
150  * A MaskDict is a MapWithHash, but additionally maintains a list of all live MaskDicts (the list is
151  * actually kept in a singleton instance of DictState)
152  */
153 class MaskDict : public MapWithHash {
154  friend class ::lsst::afw::image::DictState; // actually anonymous within lsst::afw::image; g++ is
155  // confused
156 
157  MaskDict() : MapWithHash() {}
158  MaskDict(MapWithHash const* dict) : MapWithHash(*dict) {}
159 
160 public:
164 
166 
167  ~MaskDict();
168 
169  int getUnusedPlane() const;
170  int getMaskPlane(const std::string& name) const;
171 
172  void print() const {
173  for (MapWithHash::const_iterator ptr = begin(); ptr != end(); ++ptr) {
174  std::cout << "Plane " << ptr->second << " -> " << ptr->first << std::endl;
175  }
176  }
177 
179  static void listMaskDicts();
180 };
181 }
182 
183 namespace {
184 /*
185  * A struct to hold our global state, and for whose components
186  * we can control the order of creation/destruction
187  */
188 class DictState {
189  friend class detail::MaskDict;
190 
191  typedef std::map<MapWithHash*, int> HandleList;
192 
193 public:
194  DictState() {
195  _dictCounter = 0;
196  _defaultMaskDict = std::shared_ptr<detail::MaskDict>(new detail::MaskDict);
197  _dicts[_defaultMaskDict.get()] = _dictCounter++;
198  }
199 
200  ~DictState() {
201  _defaultMaskDict.reset();
202 
203  for (HandleList::iterator ptr = _dicts.begin(); ptr != _dicts.end(); ++ptr) {
204  delete ptr->first;
205  }
206  _dicts.clear();
207  }
208 
209  template <typename FunctorT>
210  void forEachMaskDict(FunctorT func) {
211  for (HandleList::const_iterator ptr = _dicts.begin(); ptr != _dicts.end(); ++ptr) {
212  func(ptr->first);
213  }
214  }
215 
216 private:
217  std::shared_ptr<detail::MaskDict> getDefaultDict() {
218  static bool first = true;
219 
220  if (first) {
221  setInitMaskBits(_defaultMaskDict);
222 
223  first = false;
224  }
225 
226  return _defaultMaskDict;
227  }
228 
230  _defaultMaskDict = newDefaultMaskDict;
231 
232  return _defaultMaskDict;
233  }
234 
235  void addDict(MapWithHash* dict) { _dicts[dict] = _dictCounter++; }
236 
237  void eraseDict(MapWithHash* dict) { _dicts.erase(dict); }
238 
240  _defaultMaskDict = std::shared_ptr<detail::MaskDict>(new detail::MaskDict(*_defaultMaskDict.get()));
241  addDict(_defaultMaskDict.get());
242 
243  return _defaultMaskDict;
244  }
245 
246  std::shared_ptr<detail::MaskDict> _defaultMaskDict; // default MaskDict to use
247  HandleList _dicts; // all the live MaskDicts
248  int _dictCounter;
249 };
250 
251 static DictState _state;
252 }
253 
254 namespace detail {
255 /*
256  * Implementation of MaskDict
257  */
258 /*
259  * Return the default dictionary, unless you provide mpd in which case you get one of
260  * your very very own
261  */
262 std::shared_ptr<MaskDict> MaskDict::makeMaskDict() { return _state.getDefaultDict(); }
263 
265  std::shared_ptr<MaskDict> dict = _state.getDefaultDict();
266 
267  if (!mpd.empty()) {
268  MapWithHash mwh(mpd);
269  dict = std::shared_ptr<MaskDict>(new MaskDict(&mwh));
270  _state.addDict(dict.get());
271  }
272 
273  return dict;
274 }
275 
277  return _state.setDefaultDict(dict);
278 }
279 
281  std::shared_ptr<MaskDict> dict(new MaskDict(*this));
282 
283  _state.addDict(dict.get());
284 
285  return dict;
286 }
287 
288 MaskDict::~MaskDict() { _state.eraseDict(this); }
289 
290 std::shared_ptr<MaskDict> MaskDict::incrDefaultVersion() { return _state.incrDefaultVersion(); }
291 
293  if (empty()) {
294  return 0;
295  }
296 
297  MapWithHash::const_iterator const it = std::max_element(
298  begin(), end(),
300  std::bind(&MapWithHash::value_type::second, std::placeholders::_2)));
301  assert(it != end());
302  int id = it->second + 1; // The maskPlane to use if there are no gaps
303 
304  for (int i = 0; i < id; ++i) {
305  MapWithHash::const_iterator const it = // is i already used in this Mask?
306  std::find_if(
307  begin(), end(),
309  std::bind(&MapWithHash::value_type::second, std::placeholders::_1), i));
310  if (it == end()) { // Not used; so we'll use it
311  return i;
312  }
313  }
314 
315  return id;
316 }
317 
319  MapWithHash::const_iterator i = find(name);
320 
321  return (i == end()) ? -1 : i->second;
322 }
323 }
324 
325 namespace {
326 /*
327  * Definition of the default mask bits
328  *
329  * N.b. this function is in an anonymous namespace, and is invisible to doxygen. ALL mask
330  * planes defined here should be documented with the Mask class in Mask.h
331  */
332 void setInitMaskBits(std::shared_ptr<detail::MaskDict> dict) {
333  int i = -1;
334  dict->add("BAD", ++i);
335  dict->add("SAT", ++i); // should be SATURATED
336  dict->add("INTRP", ++i); // should be INTERPOLATED
337  dict->add("CR", ++i); //
338  dict->add("EDGE", ++i); //
339  dict->add("DETECTED", ++i); //
340  dict->add("DETECTED_NEGATIVE", ++i);
341  dict->add("SUSPECT", ++i);
342  dict->add("NO_DATA", ++i);
343 }
344 }
345 
346 template <typename MaskPixelT>
347 void Mask<MaskPixelT>::_initializePlanes(MaskPlaneDict const& planeDefs) {
348  LOGL_DEBUG("afw.image.Mask", "Number of mask planes: %d", getNumPlanesMax());
349 
350  _maskDict = detail::MaskDict::makeMaskDict(planeDefs);
351 }
352 
353 template <typename MaskPixelT>
354 Mask<MaskPixelT>::Mask(unsigned int width, unsigned int height, MaskPlaneDict const& planeDefs)
355  : ImageBase<MaskPixelT>(afwGeom::ExtentI(width, height)) {
356  _initializePlanes(planeDefs);
357  *this = 0x0;
358 }
359 
360 template <typename MaskPixelT>
361 Mask<MaskPixelT>::Mask(unsigned int width, unsigned int height, MaskPixelT initialValue,
362  MaskPlaneDict const& planeDefs)
363  : ImageBase<MaskPixelT>(afwGeom::ExtentI(width, height)) {
364  _initializePlanes(planeDefs);
365  *this = initialValue;
366 }
367 
368 template <typename MaskPixelT>
370  : ImageBase<MaskPixelT>(dimensions) {
371  _initializePlanes(planeDefs);
372  *this = 0x0;
373 }
374 
375 template <typename MaskPixelT>
376 Mask<MaskPixelT>::Mask(afwGeom::Extent2I const& dimensions, MaskPixelT initialValue,
377  MaskPlaneDict const& planeDefs)
378  : ImageBase<MaskPixelT>(dimensions) {
379  _initializePlanes(planeDefs);
380  *this = initialValue;
381 }
382 
383 template <typename MaskPixelT>
385  : ImageBase<MaskPixelT>(bbox) {
386  _initializePlanes(planeDefs);
387  *this = 0x0;
388 }
389 
390 template <typename MaskPixelT>
391 Mask<MaskPixelT>::Mask(afwGeom::Box2I const& bbox, MaskPixelT initialValue, MaskPlaneDict const& planeDefs)
392  : ImageBase<MaskPixelT>(bbox) {
393  _initializePlanes(planeDefs);
394  *this = initialValue;
395 }
396 
397 template <typename MaskPixelT>
398 Mask<MaskPixelT>::Mask(Mask const& rhs, afwGeom::Box2I const& bbox, ImageOrigin const origin, bool const deep)
399  : ImageBase<MaskPixelT>(rhs, bbox, origin, deep), _maskDict(rhs._maskDict) {}
400 
401 template <typename MaskPixelT>
402 Mask<MaskPixelT>::Mask(Mask const& rhs, bool deep)
403  : ImageBase<MaskPixelT>(rhs, deep), _maskDict(rhs._maskDict) {}
404 // Delegate to copy-constructor for backwards compatibility
405 template <typename MaskPixelT>
406 Mask<MaskPixelT>::Mask(Mask&& rhs) : Mask(rhs, false) {}
407 
408 template <typename MaskPixelT>
409 Mask<MaskPixelT>::~Mask() = default;
410 
411 template <typename MaskPixelT>
412 Mask<MaskPixelT>::Mask(ndarray::Array<MaskPixelT, 2, 1> const& array, bool deep, geom::Point2I const& xy0)
413  : image::ImageBase<MaskPixelT>(array, deep, xy0), _maskDict(detail::MaskDict::makeMaskDict()) {}
414 
415 template <typename PixelT>
417  using std::swap; // See Meyers, Effective C++, Item 25
418 
420  swap(_maskDict, rhs._maskDict);
421 }
422 
423 template <typename PixelT>
425  a.swap(b);
426 }
427 
428 template <typename MaskPixelT>
430  Mask tmp(rhs);
431  swap(tmp); // See Meyers, Effective C++, Item 11
432 
433  return *this;
434 }
435 // Delegate to copy-assignment for backwards compatibility
436 template <typename MaskPixelT>
438  return *this = rhs;
439 }
440 
441 template <typename MaskPixelT>
443  fill_pixels(_getRawView(), rhs);
444 
445  return *this;
446 }
447 
448 #ifndef DOXYGEN // doc for this section is already in header
449 
450 template <typename MaskPixelT>
452  afw::geom::Box2I const& bbox, ImageOrigin origin, bool conformMasks)
454  fits::Fits fitsfile(fileName, "r", fits::Fits::AUTO_CLOSE | fits::Fits::AUTO_CHECK);
455  fitsfile.setHdu(hdu);
456  *this = Mask(fitsfile, metadata, bbox, origin, conformMasks);
457 }
458 
459 template <typename MaskPixelT>
462  ImageOrigin origin, bool conformMasks)
464  fits::Fits fitsfile(manager, "r", fits::Fits::AUTO_CLOSE | fits::Fits::AUTO_CHECK);
465  fitsfile.setHdu(hdu);
466  *this = Mask(fitsfile, metadata, bbox, origin, conformMasks);
467 }
468 
469 template <typename MaskPixelT>
471  afw::geom::Box2I const& bbox, ImageOrigin const origin, bool const conformMasks)
473  // These are the permitted input file types
474  typedef boost::mpl::vector<unsigned char, unsigned short, short, std::int32_t> fits_mask_types;
475 
476  if (!metadata) {
478  }
479 
480  fits_read_image<fits_mask_types>(fitsfile, *this, *metadata, bbox, origin);
481 
482  // look for mask planes in the file
483  MaskPlaneDict fileMaskDict = parseMaskPlaneMetadata(metadata);
485 
486  if (*fileMD == *detail::MaskDict::makeMaskDict()) { // file is already consistent with Mask
487  return;
488  }
489 
490  if (conformMasks) { // adopt the definitions in the file
491  _maskDict = detail::MaskDict::setDefaultDict(fileMD);
492  }
493 
494  conformMaskPlanes(fileMaskDict); // convert planes defined by fileMaskDict to the order
495  // defined by Mask::_maskPlaneDict
496 }
497 
498 template <typename MaskPixelT>
499 void Mask<MaskPixelT>::writeFits(std::string const& fileName,
501  std::string const& mode) const {
502  fits::Fits fitsfile(fileName, mode, fits::Fits::AUTO_CLOSE | fits::Fits::AUTO_CHECK);
503  writeFits(fitsfile, metadata_i);
504 }
505 
506 template <typename MaskPixelT>
509  std::string const& mode) const {
510  fits::Fits fitsfile(manager, mode, fits::Fits::AUTO_CLOSE | fits::Fits::AUTO_CHECK);
511  writeFits(fitsfile, metadata_i);
512 }
513 
514 template <typename MaskPixelT>
517  writeFits(fitsfile, fits::ImageWriteOptions(*this), metadata);
518 }
519 
520 template <typename MaskPixelT>
522  std::string const& filename,
524  std::string const& mode,
526 ) const {
527  fits::Fits fitsfile(filename, mode, fits::Fits::AUTO_CLOSE | fits::Fits::AUTO_CHECK);
528  writeFits(fitsfile, options, header);
529 }
530 
531 template <typename MaskPixelT>
533  fits::MemFileManager& manager,
534  fits::ImageWriteOptions const& options,
535  std::string const& mode,
537 ) const {
538  fits::Fits fitsfile(manager, mode, fits::Fits::AUTO_CLOSE | fits::Fits::AUTO_CHECK);
539  writeFits(fitsfile, options, header);
540 }
541 
542 template <typename MaskPixelT>
544  fits::Fits& fitsfile,
545  fits::ImageWriteOptions const& options,
547 ) const {
548  std::shared_ptr<daf::base::PropertySet> useHeader = header ? header->deepCopy() :
549  std::make_shared<dafBase::PropertySet>();
550  addMaskPlanesToMetadata(useHeader);
551  fitsfile.writeImage(*this, options, useHeader);
552 }
553 
554 #endif // !DOXYGEN
555 
556 namespace {
557 struct addPlaneFunctor {
558  addPlaneFunctor(std::string const& name, int id) : _name(name), _id(id) {}
559 
560  void operator()(MapWithHash* dict) {
561  detail::MaskPlaneDict::const_iterator const it = // is id already used in this Mask?
562  std::find_if(
563  dict->begin(), dict->end(),
565  std::placeholders::_1),
566  _id));
567  if (it != dict->end()) { // mask plane is already in use
568  return;
569  }
570 
571  if (dict->find(_name) == dict->end()) { // not already set
572  dict->add(_name, _id);
573  }
574  }
575 
577  int _id;
578 };
579 }
580 
581 template <typename MaskPixelT>
583  std::string result = "";
584  MaskPlaneDict const& mpd = _maskPlaneDict()->getMaskPlaneDict();
585  for (MaskPlaneDict::const_iterator iter = mpd.begin(); iter != mpd.end(); ++iter) {
586  if (value & getBitMask(iter->second)) {
587  if (result.size() > 0) {
588  result += ",";
589  }
590  result += iter->first;
591  }
592  }
593  return result;
594 }
595 
596 template <typename MaskPixelT>
598  int id = getMaskPlaneNoThrow(name); // see if the plane is already available
599 
600  if (id < 0) { // doesn't exist
601  id = _maskPlaneDict()->getUnusedPlane();
602  }
603 
604  // build new entry, adding the plane to all Masks where this is no contradiction
605 
606  if (id >= getNumPlanesMax()) { // Max number of planes is already allocated
608  str(boost::format("Max number of planes (%1%) already used") % getNumPlanesMax()));
609  }
610 
611  _state.forEachMaskDict(addPlaneFunctor(name, id));
612 
613  return id;
614 }
615 
616 template <typename MaskPixelT>
617 int Mask<MaskPixelT>::addMaskPlane(std::string name, int planeId) {
618  if (planeId < 0 || planeId >= getNumPlanesMax()) {
619  throw LSST_EXCEPT(
621  str(boost::format("mask plane ID must be between 0 and %1%") % (getNumPlanesMax() - 1)));
622  }
623 
624  _maskPlaneDict()->add(name, planeId);
625 
626  return planeId;
627 }
628 
629 template <typename MaskPixelT>
631  return _maskDict->getMaskPlaneDict();
632 }
633 
634 template <typename MaskPixelT>
636  if (detail::MaskDict::makeMaskDict()->getMaskPlane(name) < 0) {
638  str(boost::format("Plane %s doesn't exist in the default Mask") % name));
639  }
640 
641  detail::MaskDict::incrDefaultVersion(); // leave current Masks alone
642  _maskPlaneDict()->erase(name);
643 }
644 
645 template <typename MaskPixelT>
646 void Mask<MaskPixelT>::removeAndClearMaskPlane(const std::string& name, bool const removeFromDefault
647 
648  ) {
649  clearMaskPlane(getMaskPlane(name)); // clear this bits in this Mask
650 
651  if (_maskDict == detail::MaskDict::makeMaskDict() && removeFromDefault) { // we are the default
652  ;
653  } else {
654  _maskDict = _maskDict->clone();
655  }
656 
657  _maskDict->erase(name);
658 
659  if (removeFromDefault && detail::MaskDict::makeMaskDict()->getMaskPlane(name) >= 0) {
660  removeMaskPlane(name);
661  }
662 }
663 
664 template <typename MaskPixelT>
665 MaskPixelT Mask<MaskPixelT>::getBitMaskNoThrow(int planeId) {
666  return (planeId >= 0 && planeId < getNumPlanesMax()) ? (1 << planeId) : 0;
667 }
668 
669 template <typename MaskPixelT>
670 MaskPixelT Mask<MaskPixelT>::getBitMask(int planeId) {
671  MaskPlaneDict const& mpd = _maskPlaneDict()->getMaskPlaneDict();
672 
673  for (MaskPlaneDict::const_iterator i = mpd.begin(); i != mpd.end(); ++i) {
674  if (planeId == i->second) {
675  MaskPixelT const bitmask = getBitMaskNoThrow(planeId);
676  if (bitmask == 0) { // failed
677  break;
678  }
679  return bitmask;
680  }
681  }
683  str(boost::format("Invalid mask plane ID: %d") % planeId));
684 }
685 
686 template <typename MaskPixelT>
688  int const plane = getMaskPlaneNoThrow(name);
689 
690  if (plane < 0) {
692  str(boost::format("Invalid mask plane name: %s") % name));
693  } else {
694  return plane;
695  }
696 }
697 
698 template <typename MaskPixelT>
700  return _maskPlaneDict()->getMaskPlane(name);
701 }
702 
703 template <typename MaskPixelT>
705  return getBitMask(getMaskPlane(name));
706 }
707 
708 template <typename MaskPixelT>
710  MaskPixelT mpix = 0x0;
711  for (std::vector<std::string>::const_iterator it = name.begin(); it != name.end(); ++it) {
712  mpix |= getBitMask(getMaskPlane(*it));
713  }
714  return mpix;
715 }
716 
717 template <typename MaskPixelT>
719  return _maskPlaneDict()->size();
720 }
721 
722 template <typename MaskPixelT>
724  _maskPlaneDict()->clear();
725 }
726 
727 template <typename MaskPixelT>
729  *this = 0;
730 }
731 
732 template <typename MaskPixelT>
734  *this &= ~getBitMask(planeId);
735 }
736 
737 template <typename MaskPixelT>
738 void Mask<MaskPixelT>::conformMaskPlanes(MaskPlaneDict const& currentPlaneDict) {
740 
741  if (*_maskDict == *currentMD) {
742  if (*detail::MaskDict::makeMaskDict() == *_maskDict) {
743  return; // nothing to do
744  }
745  } else {
746  //
747  // Find out which planes need to be permuted
748  //
749  MaskPixelT keepBitmask = 0; // mask of bits to keep
750  MaskPixelT canonicalMask[sizeof(MaskPixelT) * 8]; // bits in lsst::afw::image::Mask that should be
751  MaskPixelT currentMask[sizeof(MaskPixelT) * 8]; // mapped to these bits
752  int numReMap = 0;
753 
754  for (MaskPlaneDict::const_iterator i = currentPlaneDict.begin(); i != currentPlaneDict.end(); i++) {
755  std::string const name = i->first; // name of mask plane
756  int const currentPlaneNumber = i->second; // plane number currently in use
757  int canonicalPlaneNumber = getMaskPlaneNoThrow(name); // plane number in lsst::afw::image::Mask
758 
759  if (canonicalPlaneNumber < 0) { // no such plane; add it
760  canonicalPlaneNumber = addMaskPlane(name);
761  }
762 
763  if (canonicalPlaneNumber == currentPlaneNumber) {
764  keepBitmask |= getBitMask(canonicalPlaneNumber); // bit is unchanged, so preserve it
765  } else {
766  canonicalMask[numReMap] = getBitMask(canonicalPlaneNumber);
767  currentMask[numReMap] = getBitMaskNoThrow(currentPlaneNumber);
768  numReMap++;
769  }
770  }
771 
772  // Now loop over all pixels in Mask
773  if (numReMap > 0) {
774  for (int r = 0; r != this->getHeight(); ++r) { // "this->": Meyers, Effective C++, Item 43
775  for (typename Mask::x_iterator ptr = this->row_begin(r), end = this->row_end(r); ptr != end;
776  ++ptr) {
777  MaskPixelT const pixel = *ptr;
778 
779  MaskPixelT newPixel = pixel & keepBitmask; // value of invariant mask bits
780  for (int i = 0; i < numReMap; i++) {
781  if (pixel & currentMask[i]) newPixel |= canonicalMask[i];
782  }
783 
784  *ptr = newPixel;
785  }
786  }
787  }
788  }
789  // We've made the planes match the current mask dictionary
790  _maskDict = detail::MaskDict::makeMaskDict();
791 }
792 
793 template <typename MaskPixelT>
795  return this->ImageBase<MaskPixelT>::operator()(x, y);
796 }
797 
798 template <typename MaskPixelT>
800  CheckIndices const& check) {
801  return this->ImageBase<MaskPixelT>::operator()(x, y, check);
802 }
803 
804 template <typename MaskPixelT>
806  return this->ImageBase<MaskPixelT>::operator()(x, y);
807 }
808 
809 template <typename MaskPixelT>
811  int x, int y, CheckIndices const& check) const {
812  return this->ImageBase<MaskPixelT>::operator()(x, y, check);
813 }
814 
815 template <typename MaskPixelT>
816 bool Mask<MaskPixelT>::operator()(int x, int y, int planeId) const {
817  // !! converts an int to a bool
818  return !!(this->ImageBase<MaskPixelT>::operator()(x, y) & getBitMask(planeId));
819 }
820 
821 template <typename MaskPixelT>
822 bool Mask<MaskPixelT>::operator()(int x, int y, int planeId, CheckIndices const& check) const {
823  // !! converts an int to a bool
824  return !!(this->ImageBase<MaskPixelT>::operator()(x, y, check) & getBitMask(planeId));
825 }
826 
827 template <typename MaskPixelT>
829  if (*_maskDict != *other._maskDict) {
830  throw LSST_EXCEPT(pexExcept::RuntimeError, "Mask dictionaries do not match");
831  }
832 }
833 
834 template <typename MaskPixelT>
836  transform_pixels(_getRawView(), _getRawView(),
837  [&val](MaskPixelT const& l) -> MaskPixelT { return l | val; });
838  return *this;
839 }
840 
841 template <typename MaskPixelT>
843  checkMaskDictionaries(rhs);
844 
845  if (this->getDimensions() != rhs.getDimensions()) {
847  str(boost::format("Images are of different size, %dx%d v %dx%d") %
848  this->getWidth() % this->getHeight() % rhs.getWidth() % rhs.getHeight()));
849  }
850  transform_pixels(_getRawView(), rhs._getRawView(), _getRawView(),
851  [](MaskPixelT const& l, MaskPixelT const& r) -> MaskPixelT { return l | r; });
852  return *this;
853 }
854 
855 template <typename MaskPixelT>
856 Mask<MaskPixelT>& Mask<MaskPixelT>::operator&=(MaskPixelT const val) {
857  transform_pixels(_getRawView(), _getRawView(), [&val](MaskPixelT const& l) { return l & val; });
858  return *this;
859 }
860 
861 template <typename MaskPixelT>
863  checkMaskDictionaries(rhs);
864 
865  if (this->getDimensions() != rhs.getDimensions()) {
867  str(boost::format("Images are of different size, %dx%d v %dx%d") %
868  this->getWidth() % this->getHeight() % rhs.getWidth() % rhs.getHeight()));
869  }
870  transform_pixels(_getRawView(), rhs._getRawView(), _getRawView(),
871  [](MaskPixelT const& l, MaskPixelT const& r) -> MaskPixelT { return l & r; });
872  return *this;
873 }
874 
875 template <typename MaskPixelT>
877  transform_pixels(_getRawView(), _getRawView(),
878  [&val](MaskPixelT const& l) -> MaskPixelT { return l ^ val; });
879  return *this;
880 }
881 
882 template <typename MaskPixelT>
884  checkMaskDictionaries(rhs);
885 
886  if (this->getDimensions() != rhs.getDimensions()) {
888  str(boost::format("Images are of different size, %dx%d v %dx%d") %
889  this->getWidth() % this->getHeight() % rhs.getWidth() % rhs.getHeight()));
890  }
891  transform_pixels(_getRawView(), rhs._getRawView(), _getRawView(),
892  [](MaskPixelT const& l, MaskPixelT const& r) -> MaskPixelT { return l ^ r; });
893  return *this;
894 }
895 
896 template <typename MaskPixelT>
897 void Mask<MaskPixelT>::setMaskPlaneValues(int const planeId, int const x0, int const x1, int const y) {
898  MaskPixelT const bitMask = getBitMask(planeId);
899 
900  for (int x = x0; x <= x1; x++) {
901  operator()(x, y) = operator()(x, y) | bitMask;
902  }
903 }
904 
905 template <typename MaskPixelT>
907  if (!metadata) {
908  throw LSST_EXCEPT(pexExcept::InvalidParameterError, "Null std::shared_ptr<PropertySet>");
909  }
910 
911  // First, clear existing MaskPlane metadata
912  typedef std::vector<std::string> NameList;
913  NameList paramNames = metadata->paramNames(false);
914  for (NameList::const_iterator i = paramNames.begin(); i != paramNames.end(); ++i) {
915  if (i->compare(0, maskPlanePrefix.size(), maskPlanePrefix) == 0) {
916  metadata->remove(*i);
917  }
918  }
919 
920  MaskPlaneDict const& mpd = _maskPlaneDict()->getMaskPlaneDict();
921 
922  // Add new MaskPlane metadata
923  for (MaskPlaneDict::const_iterator i = mpd.begin(); i != mpd.end(); ++i) {
924  std::string const& planeName = i->first;
925  int const planeNumber = i->second;
926 
927  if (planeName != "") {
928  metadata->add(maskPlanePrefix + planeName, planeNumber);
929  }
930  }
931 }
932 
933 template <typename MaskPixelT>
936  MaskPlaneDict newDict;
937 
938  // First, clear existing MaskPlane metadata
939  typedef std::vector<std::string> NameList;
940  NameList paramNames = metadata->paramNames(false);
941  int numPlanesUsed = 0; // number of planes used
942 
943  // Iterate over childless properties with names starting with maskPlanePrefix
944  for (NameList::const_iterator i = paramNames.begin(); i != paramNames.end(); ++i) {
945  if (i->compare(0, maskPlanePrefix.size(), maskPlanePrefix) == 0) {
946  // split off maskPlanePrefix to obtain plane name
947  std::string planeName = i->substr(maskPlanePrefix.size());
948  int const planeId = metadata->getAsInt(*i);
949 
950  MaskPlaneDict::const_iterator plane = newDict.find(planeName);
951  if (plane != newDict.end() && planeId != plane->second) {
952  throw LSST_EXCEPT(pexExcept::RuntimeError, "File specifies plane " + planeName + " twice");
953  }
954  for (MaskPlaneDict::const_iterator j = newDict.begin(); j != newDict.end(); ++j) {
955  if (planeId == j->second) {
957  str(boost::format("File specifies plane %s has same value (%d) as %s") %
958  planeName % planeId % j->first));
959  }
960  }
961  // build new entry
962  if (numPlanesUsed >= getNumPlanesMax()) {
963  // Max number of planes already allocated
964  throw LSST_EXCEPT(
966  str(boost::format("Max number of planes (%1%) already used") % getNumPlanesMax()));
967  }
968  newDict[planeName] = planeId;
969  }
970  }
971  return newDict;
972 }
973 
974 template <typename MaskPixelT>
976  _maskDict->print();
977 }
978 
979 /*
980  * Static members of Mask
981  */
982 template <typename MaskPixelT>
984 
985 template <typename MaskPixelT>
988 }
989 
990 //
991 // Explicit instantiations
992 //
993 template class Mask<MaskPixel>;
994 }
995 }
996 }
static std::string interpret(MaskPixelT value)
Interpret a mask value as a comma-separated list of mask plane names.
Definition: Mask.cc:582
T empty(T... args)
static void clearMaskPlaneDict()
Reset the maskPlane dictionary.
Definition: Mask.cc:723
def erase(frame=None)
Definition: ds9.py:103
static int getMaskPlane(const std::string &name)
Return the mask plane number corresponding to a plane name.
Definition: Mask.cc:687
std::string const & _name
Definition: Mask.cc:576
T swap(T... args)
int getHeight() const
Return the number of rows in the image.
Definition: ImageBase.h:301
std::map< std::string, int > MaskPlaneDict
Definition: Mask.h:65
Options for writing an image to FITS.
Definition: fits.h:220
Mask & operator=(MaskPixelT const rhs)
Definition: Mask.cc:442
T endl(T... args)
T max_element(T... args)
_view_t::x_iterator x_iterator
An iterator for traversing the pixels in a row.
Definition: ImageBase.h:137
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.
T end(T... args)
tuple options
ItemVariant const * other
Definition: Schema.cc:55
static void addMaskPlanesToMetadata(std::shared_ptr< lsst::daf::base::PropertySet >)
Given a PropertySet, replace any existing MaskPlane assignments with the current ones.
Definition: Mask.cc:906
static int getNumPlanesUsed()
Definition: Mask.cc:718
A simple struct that combines the two arguments that must be passed to most cfitsio routines and cont...
Definition: fits.h:298
The base class for all image classed (Image, Mask, MaskedImage, ...)
Definition: ImageBase.h:106
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...
Definition: Mask.cc:646
static MaskPlaneDict parseMaskPlaneMetadata(std::shared_ptr< lsst::daf::base::PropertySet const > metadata)
Given a PropertySet that contains the MaskPlane assignments, setup the MaskPlanes.
Definition: Mask.cc:934
x_iterator row_begin(int y) const
Return an x_iterator to the start of the y&#39;th row.
Definition: ImageBase.h:404
#define LOGL_DEBUG(logger, message...)
ImageBase< MaskPixelT >::PixelReference operator()(int x, int y)
get a reference to the specified pixel
Definition: Mask.cc:794
An integer coordinate rectangle.
Definition: Box.h:55
iterator end() const
Return an STL compliant iterator to the end of the image.
Definition: Image.cc:248
STL class.
Mask(unsigned int width, unsigned int height, MaskPlaneDict const &planeDefs=MaskPlaneDict())
Construct a Mask initialized to 0x0.
Definition: Mask.cc:354
int getMaskPlane(const std::string &name) const
Definition: Mask.cc:318
afw::table::PointKey< int > dimensions
Definition: GaussianPsf.cc:44
geom::Extent2I getDimensions() const
Return the image&#39;s size; useful for passing to constructors.
Definition: ImageBase.h:359
A base class for image defects.
int end
Represent a 2-dimensional array of bitmask pixels.
Definition: Mask.h:84
Lifetime-management for memory that goes into FITS memory files.
Definition: fits.h:120
int _id
Definition: Mask.cc:577
table::Key< int > b
void setMaskPlaneValues(const int plane, const int x0, const int x1, const int y)
Set the bit specified by "planeId" for pixels (x0, y) ...
Definition: Mask.cc:897
T bind(T... args)
A class used to request that array accesses be checked.
Definition: ImageBase.h:78
static MaskPixelT getPlaneBitMask(const std::vector< std::string > &names)
Return the bitmask corresponding to a vector of plane names OR&#39;d together.
Definition: Mask.cc:709
double x
void swap(ImageBase &rhs)
Definition: Image.cc:226
std::unique_ptr< SchemaItem< U > > result
Definition: Schema.cc:194
MaskPlaneDict const & getMaskPlaneDict() const
Return the Mask&#39;s maskPlaneDict.
Definition: Mask.cc:630
void setHdu(int hdu, bool relative=false)
Set the current HDU.
Definition: fits.cc:477
Extent< int, 2 > ExtentI
Definition: Extent.h:377
T get(T... args)
static std::shared_ptr< MaskDict > incrDefaultVersion()
Definition: Mask.cc:290
T find(T... args)
T size(T... args)
#define LSST_EXCEPT(type,...)
static void removeMaskPlane(const std::string &name)
Definition: Mask.cc:635
static std::shared_ptr< MaskDict > makeMaskDict()
Definition: Mask.cc:262
static int getNumPlanesMax()
Definition: Mask.h:475
T begin(T... args)
Mask & operator &=(Mask const &rhs)
AND a Mask into a Mask.
int getWidth() const
Return the number of columns in the image.
Definition: ImageBase.h:299
std::shared_ptr< MaskDict > clone() const
Definition: Mask.cc:280
Mask & operator|=(Mask const &rhs)
OR a Mask into a Mask.
Definition: Mask.cc:842
x_iterator row_end(int y) const
Return an x_iterator to the end of the y&#39;th row.
Definition: ImageBase.h:407
T substr(T... args)
table::Box2IKey bbox
table::Key< int > a
table::PointKey< int > pixel
void swap(Mask &rhs)
Definition: Mask.cc:416
static std::shared_ptr< MaskDict > setDefaultDict(std::shared_ptr< MaskDict > dict)
Definition: Mask.cc:276
void conformMaskPlanes(const MaskPlaneDict &masterPlaneDict)
Adjust this mask to conform to the standard Mask class&#39;s mask plane dictionary, adding any new mask p...
Definition: Mask.cc:738
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)
XOR a Mask into a Mask.
Definition: Mask.cc:883
void clearMaskPlane(int plane)
Clear the specified bit in all pixels.
Definition: Mask.cc:733
void writeImage(ndarray::Array< T const, N, C > const &array)
Write an ndarray::Array to a FITS image HDU.
Definition: fits.h:478
void clearAllMaskPlanes()
Clear all the pixels.
Definition: Mask.cc:728
int y
Definition: SpanSet.cc:44
static int addMaskPlane(const std::string &name)
Definition: Mask.cc:597
PixelReference operator()(int x, int y)
Return a reference to the pixel (x, y)
Definition: Image.cc:186
void printMaskPlanes() const
print the mask plane dictionary to std::cout
Definition: Mask.cc:975