lsst.afw  14.0-25-g0e8fc950e+5
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 
406 template <typename MaskPixelT>
407 Mask<MaskPixelT>::Mask(ndarray::Array<MaskPixelT, 2, 1> const& array, bool deep, geom::Point2I const& xy0)
408  : image::ImageBase<MaskPixelT>(array, deep, xy0), _maskDict(detail::MaskDict::makeMaskDict()) {}
409 
410 template <typename PixelT>
412  using std::swap; // See Meyers, Effective C++, Item 25
413 
415  swap(_maskDict, rhs._maskDict);
416 }
417 
418 template <typename PixelT>
420  a.swap(b);
421 }
422 
423 template <typename MaskPixelT>
425  Mask tmp(rhs);
426  swap(tmp); // See Meyers, Effective C++, Item 11
427 
428  return *this;
429 }
430 
431 template <typename MaskPixelT>
433  fill_pixels(_getRawView(), rhs);
434 
435  return *this;
436 }
437 
438 #ifndef DOXYGEN // doc for this section is already in header
439 
440 template <typename MaskPixelT>
442  afw::geom::Box2I const& bbox, ImageOrigin origin, bool conformMasks)
444  fits::Fits fitsfile(fileName, "r", fits::Fits::AUTO_CLOSE | fits::Fits::AUTO_CHECK);
445  fitsfile.setHdu(hdu);
446  *this = Mask(fitsfile, metadata, bbox, origin, conformMasks);
447 }
448 
449 template <typename MaskPixelT>
452  ImageOrigin origin, bool conformMasks)
454  fits::Fits fitsfile(manager, "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>
461  afw::geom::Box2I const& bbox, ImageOrigin const origin, bool const conformMasks)
463  // These are the permitted input file types
464  typedef boost::mpl::vector<unsigned char, unsigned short, short, std::int32_t> fits_mask_types;
465 
466  if (!metadata) {
468  }
469 
470  fits_read_image<fits_mask_types>(fitsfile, *this, *metadata, bbox, origin);
471 
472  // look for mask planes in the file
473  MaskPlaneDict fileMaskDict = parseMaskPlaneMetadata(metadata);
475 
476  if (*fileMD == *detail::MaskDict::makeMaskDict()) { // file is already consistent with Mask
477  return;
478  }
479 
480  if (conformMasks) { // adopt the definitions in the file
481  _maskDict = detail::MaskDict::setDefaultDict(fileMD);
482  }
483 
484  conformMaskPlanes(fileMaskDict); // convert planes defined by fileMaskDict to the order
485  // defined by Mask::_maskPlaneDict
486 }
487 
488 template <typename MaskPixelT>
489 void Mask<MaskPixelT>::writeFits(std::string const& fileName,
491  std::string const& mode) const {
492  fits::Fits fitsfile(fileName, mode, fits::Fits::AUTO_CLOSE | fits::Fits::AUTO_CHECK);
493  writeFits(fitsfile, metadata_i);
494 }
495 
496 template <typename MaskPixelT>
499  std::string const& mode) const {
500  fits::Fits fitsfile(manager, mode, fits::Fits::AUTO_CLOSE | fits::Fits::AUTO_CHECK);
501  writeFits(fitsfile, metadata_i);
502 }
503 
504 template <typename MaskPixelT>
507  writeFits(fitsfile, fits::ImageWriteOptions(*this), metadata);
508 }
509 
510 template <typename MaskPixelT>
512  std::string const& filename,
514  std::string const& mode,
516 ) const {
517  fits::Fits fitsfile(filename, mode, fits::Fits::AUTO_CLOSE | fits::Fits::AUTO_CHECK);
518  writeFits(fitsfile, options, header);
519 }
520 
521 template <typename MaskPixelT>
523  fits::MemFileManager& manager,
524  fits::ImageWriteOptions const& options,
525  std::string const& mode,
527 ) const {
528  fits::Fits fitsfile(manager, mode, fits::Fits::AUTO_CLOSE | fits::Fits::AUTO_CHECK);
529  writeFits(fitsfile, options, header);
530 }
531 
532 template <typename MaskPixelT>
534  fits::Fits& fitsfile,
535  fits::ImageWriteOptions const& options,
537 ) const {
538  std::shared_ptr<daf::base::PropertySet> useHeader = header ? header->deepCopy() :
539  std::make_shared<dafBase::PropertySet>();
540  addMaskPlanesToMetadata(useHeader);
541  fitsfile.writeImage(*this, options, useHeader);
542 }
543 
544 #endif // !DOXYGEN
545 
546 namespace {
547 struct addPlaneFunctor {
548  addPlaneFunctor(std::string const& name, int id) : _name(name), _id(id) {}
549 
550  void operator()(MapWithHash* dict) {
551  detail::MaskPlaneDict::const_iterator const it = // is id already used in this Mask?
552  std::find_if(
553  dict->begin(), dict->end(),
555  std::placeholders::_1),
556  _id));
557  if (it != dict->end()) { // mask plane is already in use
558  return;
559  }
560 
561  if (dict->find(_name) == dict->end()) { // not already set
562  dict->add(_name, _id);
563  }
564  }
565 
567  int _id;
568 };
569 }
570 
571 template <typename MaskPixelT>
573  std::string result = "";
574  MaskPlaneDict const& mpd = _maskPlaneDict()->getMaskPlaneDict();
575  for (MaskPlaneDict::const_iterator iter = mpd.begin(); iter != mpd.end(); ++iter) {
576  if (value & getBitMask(iter->second)) {
577  if (result.size() > 0) {
578  result += ",";
579  }
580  result += iter->first;
581  }
582  }
583  return result;
584 }
585 
586 template <typename MaskPixelT>
588  int id = getMaskPlaneNoThrow(name); // see if the plane is already available
589 
590  if (id < 0) { // doesn't exist
591  id = _maskPlaneDict()->getUnusedPlane();
592  }
593 
594  // build new entry, adding the plane to all Masks where this is no contradiction
595 
596  if (id >= getNumPlanesMax()) { // Max number of planes is already allocated
598  str(boost::format("Max number of planes (%1%) already used") % getNumPlanesMax()));
599  }
600 
601  _state.forEachMaskDict(addPlaneFunctor(name, id));
602 
603  return id;
604 }
605 
606 template <typename MaskPixelT>
607 int Mask<MaskPixelT>::addMaskPlane(std::string name, int planeId) {
608  if (planeId < 0 || planeId >= getNumPlanesMax()) {
609  throw LSST_EXCEPT(
611  str(boost::format("mask plane ID must be between 0 and %1%") % (getNumPlanesMax() - 1)));
612  }
613 
614  _maskPlaneDict()->add(name, planeId);
615 
616  return planeId;
617 }
618 
619 template <typename MaskPixelT>
621  return _maskDict->getMaskPlaneDict();
622 }
623 
624 template <typename MaskPixelT>
626  if (detail::MaskDict::makeMaskDict()->getMaskPlane(name) < 0) {
628  str(boost::format("Plane %s doesn't exist in the default Mask") % name));
629  }
630 
631  detail::MaskDict::incrDefaultVersion(); // leave current Masks alone
632  _maskPlaneDict()->erase(name);
633 }
634 
635 template <typename MaskPixelT>
636 void Mask<MaskPixelT>::removeAndClearMaskPlane(const std::string& name, bool const removeFromDefault
637 
638  ) {
639  clearMaskPlane(getMaskPlane(name)); // clear this bits in this Mask
640 
641  if (_maskDict == detail::MaskDict::makeMaskDict() && removeFromDefault) { // we are the default
642  ;
643  } else {
644  _maskDict = _maskDict->clone();
645  }
646 
647  _maskDict->erase(name);
648 
649  if (removeFromDefault && detail::MaskDict::makeMaskDict()->getMaskPlane(name) >= 0) {
650  removeMaskPlane(name);
651  }
652 }
653 
654 template <typename MaskPixelT>
655 MaskPixelT Mask<MaskPixelT>::getBitMaskNoThrow(int planeId) {
656  return (planeId >= 0 && planeId < getNumPlanesMax()) ? (1 << planeId) : 0;
657 }
658 
659 template <typename MaskPixelT>
660 MaskPixelT Mask<MaskPixelT>::getBitMask(int planeId) {
661  MaskPlaneDict const& mpd = _maskPlaneDict()->getMaskPlaneDict();
662 
663  for (MaskPlaneDict::const_iterator i = mpd.begin(); i != mpd.end(); ++i) {
664  if (planeId == i->second) {
665  MaskPixelT const bitmask = getBitMaskNoThrow(planeId);
666  if (bitmask == 0) { // failed
667  break;
668  }
669  return bitmask;
670  }
671  }
673  str(boost::format("Invalid mask plane ID: %d") % planeId));
674 }
675 
676 template <typename MaskPixelT>
678  int const plane = getMaskPlaneNoThrow(name);
679 
680  if (plane < 0) {
682  str(boost::format("Invalid mask plane name: %s") % name));
683  } else {
684  return plane;
685  }
686 }
687 
688 template <typename MaskPixelT>
690  return _maskPlaneDict()->getMaskPlane(name);
691 }
692 
693 template <typename MaskPixelT>
695  return getBitMask(getMaskPlane(name));
696 }
697 
698 template <typename MaskPixelT>
700  MaskPixelT mpix = 0x0;
701  for (std::vector<std::string>::const_iterator it = name.begin(); it != name.end(); ++it) {
702  mpix |= getBitMask(getMaskPlane(*it));
703  }
704  return mpix;
705 }
706 
707 template <typename MaskPixelT>
709  return _maskPlaneDict()->size();
710 }
711 
712 template <typename MaskPixelT>
714  _maskPlaneDict()->clear();
715 }
716 
717 template <typename MaskPixelT>
719  *this = 0;
720 }
721 
722 template <typename MaskPixelT>
724  *this &= ~getBitMask(planeId);
725 }
726 
727 template <typename MaskPixelT>
728 void Mask<MaskPixelT>::conformMaskPlanes(MaskPlaneDict const& currentPlaneDict) {
730 
731  if (*_maskDict == *currentMD) {
732  if (*detail::MaskDict::makeMaskDict() == *_maskDict) {
733  return; // nothing to do
734  }
735  } else {
736  //
737  // Find out which planes need to be permuted
738  //
739  MaskPixelT keepBitmask = 0; // mask of bits to keep
740  MaskPixelT canonicalMask[sizeof(MaskPixelT) * 8]; // bits in lsst::afw::image::Mask that should be
741  MaskPixelT currentMask[sizeof(MaskPixelT) * 8]; // mapped to these bits
742  int numReMap = 0;
743 
744  for (MaskPlaneDict::const_iterator i = currentPlaneDict.begin(); i != currentPlaneDict.end(); i++) {
745  std::string const name = i->first; // name of mask plane
746  int const currentPlaneNumber = i->second; // plane number currently in use
747  int canonicalPlaneNumber = getMaskPlaneNoThrow(name); // plane number in lsst::afw::image::Mask
748 
749  if (canonicalPlaneNumber < 0) { // no such plane; add it
750  canonicalPlaneNumber = addMaskPlane(name);
751  }
752 
753  if (canonicalPlaneNumber == currentPlaneNumber) {
754  keepBitmask |= getBitMask(canonicalPlaneNumber); // bit is unchanged, so preserve it
755  } else {
756  canonicalMask[numReMap] = getBitMask(canonicalPlaneNumber);
757  currentMask[numReMap] = getBitMaskNoThrow(currentPlaneNumber);
758  numReMap++;
759  }
760  }
761 
762  // Now loop over all pixels in Mask
763  if (numReMap > 0) {
764  for (int r = 0; r != this->getHeight(); ++r) { // "this->": Meyers, Effective C++, Item 43
765  for (typename Mask::x_iterator ptr = this->row_begin(r), end = this->row_end(r); ptr != end;
766  ++ptr) {
767  MaskPixelT const pixel = *ptr;
768 
769  MaskPixelT newPixel = pixel & keepBitmask; // value of invariant mask bits
770  for (int i = 0; i < numReMap; i++) {
771  if (pixel & currentMask[i]) newPixel |= canonicalMask[i];
772  }
773 
774  *ptr = newPixel;
775  }
776  }
777  }
778  }
779  // We've made the planes match the current mask dictionary
780  _maskDict = detail::MaskDict::makeMaskDict();
781 }
782 
783 template <typename MaskPixelT>
785  return this->ImageBase<MaskPixelT>::operator()(x, y);
786 }
787 
788 template <typename MaskPixelT>
790  CheckIndices const& check) {
791  return this->ImageBase<MaskPixelT>::operator()(x, y, check);
792 }
793 
794 template <typename MaskPixelT>
796  return this->ImageBase<MaskPixelT>::operator()(x, y);
797 }
798 
799 template <typename MaskPixelT>
801  int x, int y, CheckIndices const& check) const {
802  return this->ImageBase<MaskPixelT>::operator()(x, y, check);
803 }
804 
805 template <typename MaskPixelT>
806 bool Mask<MaskPixelT>::operator()(int x, int y, int planeId) const {
807  // !! converts an int to a bool
808  return !!(this->ImageBase<MaskPixelT>::operator()(x, y) & getBitMask(planeId));
809 }
810 
811 template <typename MaskPixelT>
812 bool Mask<MaskPixelT>::operator()(int x, int y, int planeId, CheckIndices const& check) const {
813  // !! converts an int to a bool
814  return !!(this->ImageBase<MaskPixelT>::operator()(x, y, check) & getBitMask(planeId));
815 }
816 
817 template <typename MaskPixelT>
819  if (*_maskDict != *other._maskDict) {
820  throw LSST_EXCEPT(pexExcept::RuntimeError, "Mask dictionaries do not match");
821  }
822 }
823 
824 template <typename MaskPixelT>
826  transform_pixels(_getRawView(), _getRawView(),
827  [&val](MaskPixelT const& l) -> MaskPixelT { return l | val; });
828  return *this;
829 }
830 
831 template <typename MaskPixelT>
833  checkMaskDictionaries(rhs);
834 
835  if (this->getDimensions() != rhs.getDimensions()) {
837  str(boost::format("Images are of different size, %dx%d v %dx%d") %
838  this->getWidth() % this->getHeight() % rhs.getWidth() % rhs.getHeight()));
839  }
840  transform_pixels(_getRawView(), rhs._getRawView(), _getRawView(),
841  [](MaskPixelT const& l, MaskPixelT const& r) -> MaskPixelT { return l | r; });
842  return *this;
843 }
844 
845 template <typename MaskPixelT>
846 Mask<MaskPixelT>& Mask<MaskPixelT>::operator&=(MaskPixelT const val) {
847  transform_pixels(_getRawView(), _getRawView(), [&val](MaskPixelT const& l) { return l & val; });
848  return *this;
849 }
850 
851 template <typename MaskPixelT>
853  checkMaskDictionaries(rhs);
854 
855  if (this->getDimensions() != rhs.getDimensions()) {
857  str(boost::format("Images are of different size, %dx%d v %dx%d") %
858  this->getWidth() % this->getHeight() % rhs.getWidth() % rhs.getHeight()));
859  }
860  transform_pixels(_getRawView(), rhs._getRawView(), _getRawView(),
861  [](MaskPixelT const& l, MaskPixelT const& r) -> MaskPixelT { return l & r; });
862  return *this;
863 }
864 
865 template <typename MaskPixelT>
867  transform_pixels(_getRawView(), _getRawView(),
868  [&val](MaskPixelT const& l) -> MaskPixelT { return l ^ val; });
869  return *this;
870 }
871 
872 template <typename MaskPixelT>
874  checkMaskDictionaries(rhs);
875 
876  if (this->getDimensions() != rhs.getDimensions()) {
878  str(boost::format("Images are of different size, %dx%d v %dx%d") %
879  this->getWidth() % this->getHeight() % rhs.getWidth() % rhs.getHeight()));
880  }
881  transform_pixels(_getRawView(), rhs._getRawView(), _getRawView(),
882  [](MaskPixelT const& l, MaskPixelT const& r) -> MaskPixelT { return l ^ r; });
883  return *this;
884 }
885 
886 template <typename MaskPixelT>
887 void Mask<MaskPixelT>::setMaskPlaneValues(int const planeId, int const x0, int const x1, int const y) {
888  MaskPixelT const bitMask = getBitMask(planeId);
889 
890  for (int x = x0; x <= x1; x++) {
891  operator()(x, y) = operator()(x, y) | bitMask;
892  }
893 }
894 
895 template <typename MaskPixelT>
897  if (!metadata) {
898  throw LSST_EXCEPT(pexExcept::InvalidParameterError, "Null std::shared_ptr<PropertySet>");
899  }
900 
901  // First, clear existing MaskPlane metadata
902  typedef std::vector<std::string> NameList;
903  NameList paramNames = metadata->paramNames(false);
904  for (NameList::const_iterator i = paramNames.begin(); i != paramNames.end(); ++i) {
905  if (i->compare(0, maskPlanePrefix.size(), maskPlanePrefix) == 0) {
906  metadata->remove(*i);
907  }
908  }
909 
910  MaskPlaneDict const& mpd = _maskPlaneDict()->getMaskPlaneDict();
911 
912  // Add new MaskPlane metadata
913  for (MaskPlaneDict::const_iterator i = mpd.begin(); i != mpd.end(); ++i) {
914  std::string const& planeName = i->first;
915  int const planeNumber = i->second;
916 
917  if (planeName != "") {
918  metadata->add(maskPlanePrefix + planeName, planeNumber);
919  }
920  }
921 }
922 
923 template <typename MaskPixelT>
926  MaskPlaneDict newDict;
927 
928  // First, clear existing MaskPlane metadata
929  typedef std::vector<std::string> NameList;
930  NameList paramNames = metadata->paramNames(false);
931  int numPlanesUsed = 0; // number of planes used
932 
933  // Iterate over childless properties with names starting with maskPlanePrefix
934  for (NameList::const_iterator i = paramNames.begin(); i != paramNames.end(); ++i) {
935  if (i->compare(0, maskPlanePrefix.size(), maskPlanePrefix) == 0) {
936  // split off maskPlanePrefix to obtain plane name
937  std::string planeName = i->substr(maskPlanePrefix.size());
938  int const planeId = metadata->getAsInt(*i);
939 
940  MaskPlaneDict::const_iterator plane = newDict.find(planeName);
941  if (plane != newDict.end() && planeId != plane->second) {
942  throw LSST_EXCEPT(pexExcept::RuntimeError, "File specifies plane " + planeName + " twice");
943  }
944  for (MaskPlaneDict::const_iterator j = newDict.begin(); j != newDict.end(); ++j) {
945  if (planeId == j->second) {
947  str(boost::format("File specifies plane %s has same value (%d) as %s") %
948  planeName % planeId % j->first));
949  }
950  }
951  // build new entry
952  if (numPlanesUsed >= getNumPlanesMax()) {
953  // Max number of planes already allocated
954  throw LSST_EXCEPT(
956  str(boost::format("Max number of planes (%1%) already used") % getNumPlanesMax()));
957  }
958  newDict[planeName] = planeId;
959  }
960  }
961  return newDict;
962 }
963 
964 template <typename MaskPixelT>
966  _maskDict->print();
967 }
968 
969 /*
970  * Static members of Mask
971  */
972 template <typename MaskPixelT>
974 
975 template <typename MaskPixelT>
978 }
979 
980 //
981 // Explicit instantiations
982 //
983 template class Mask<MaskPixel>;
984 }
985 }
986 }
static std::string interpret(MaskPixelT value)
Interpret a mask value as a comma-separated list of mask plane names.
Definition: Mask.cc:572
T empty(T... args)
static void clearMaskPlaneDict()
Reset the maskPlane dictionary.
Definition: Mask.cc:713
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:818
static int getMaskPlane(const std::string &name)
Return the mask plane number corresponding to a plane name.
Definition: Mask.cc:677
std::string const & _name
Definition: Mask.cc:566
T swap(T... args)
int getHeight() const
Return the number of rows in the image.
Definition: ImageBase.h:299
std::map< std::string, int > MaskPlaneDict
Definition: Mask.h:64
Options for writing an image to FITS.
Definition: fits.h:201
Mask & operator=(MaskPixelT const rhs)
Definition: Mask.cc:432
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:896
static int getNumPlanesUsed()
Definition: Mask.cc:708
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:279
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:636
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:924
x_iterator row_begin(int y) const
Return an x_iterator to the start of the y&#39;th row.
Definition: ImageBase.h:402
#define LOGL_DEBUG(logger, message...)
ImageBase< MaskPixelT >::PixelReference operator()(int x, int y)
get a reference to the specified pixel
Definition: Mask.cc:784
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:240
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:357
A base class for image defects.
int end
Represent a 2-dimensional array of bitmask pixels.
Definition: Mask.h:83
Lifetime-management for memory that goes into FITS memory files.
Definition: fits.h:101
int _id
Definition: Mask.cc:567
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:887
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:699
double x
void swap(ImageBase &rhs)
Definition: Image.cc:218
MaskPlaneDict const & getMaskPlaneDict() const
Return the Mask&#39;s maskPlaneDict.
Definition: Mask.cc:620
void setHdu(int hdu, bool relative=false)
Set the current HDU.
Extent< int, 2 > ExtentI
Definition: Extent.h:338
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:625
static std::shared_ptr< MaskDict > makeMaskDict()
Definition: Mask.cc:263
static int getNumPlanesMax()
Definition: Mask.h:469
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:297
std::shared_ptr< MaskDict > clone() const
Definition: Mask.cc:281
Mask & operator|=(Mask const &rhs)
OR a Mask into a Mask.
Definition: Mask.cc:832
x_iterator row_end(int y) const
Return an x_iterator to the end of the y&#39;th row.
Definition: ImageBase.h:405
T substr(T... args)
table::PointKey< int > pixel
void swap(Mask &rhs)
Definition: Mask.cc:411
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:728
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:873
void clearMaskPlane(int plane)
Clear the specified bit in all pixels.
Definition: Mask.cc:723
void writeImage(ndarray::Array< T const, N, C > const &array)
Write an ndarray::Array to a FITS image HDU.
Definition: fits.h:459
void clearAllMaskPlanes()
Clear all the pixels.
Definition: Mask.cc:718
static int addMaskPlane(const std::string &name)
Definition: Mask.cc:587
PixelReference operator()(int x, int y)
Return a reference to the pixel (x, y)
Definition: Image.cc:178
void printMaskPlanes() const
print the mask plane dictionary to std::cout
Definition: Mask.cc:965