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