lsst.afw  13.0-92-g8ecf155+1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
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;
74 namespace pexExcept = lsst::pex::exceptions;
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:
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:
162  static std::shared_ptr<MaskDict> makeMaskDict();
163  static std::shared_ptr<MaskDict> makeMaskDict(detail::MaskPlaneDict const& dict);
164  static std::shared_ptr<MaskDict> setDefaultDict(std::shared_ptr<MaskDict> dict);
165 
166  std::shared_ptr<MaskDict> clone() const;
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 
179  static std::shared_ptr<MaskDict> incrDefaultVersion();
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);
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 
230  std::shared_ptr<detail::MaskDict> setDefaultDict(std::shared_ptr<detail::MaskDict> newDefaultMaskDict) {
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 
240  std::shared_ptr<detail::MaskDict> incrDefaultVersion() {
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
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 
265 std::shared_ptr<MaskDict> MaskDict::makeMaskDict(detail::MaskPlaneDict const& mpd) {
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 
277 std::shared_ptr<MaskDict> MaskDict::setDefaultDict(std::shared_ptr<MaskDict> dict) {
278  return _state.setDefaultDict(dict);
279 }
280 
281 std::shared_ptr<MaskDict> MaskDict::clone() const {
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(),
300  std::bind(std::less<int>(), std::bind(&MapWithHash::value_type::second, std::placeholders::_1),
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(),
309  std::bind(std::equal_to<int>(),
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 
319 int detail::MaskDict::getMaskPlane(const std::string& name) const {
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>
441 Mask<MaskPixelT>::Mask(std::string const& fileName, int hdu, std::shared_ptr<daf::base::PropertySet> metadata,
442  afw::geom::Box2I const& bbox, ImageOrigin origin, bool conformMasks)
443  : ImageBase<MaskPixelT>(), _maskDict(detail::MaskDict::makeMaskDict()) {
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>
451  std::shared_ptr<daf::base::PropertySet> metadata, afw::geom::Box2I const& bbox,
452  ImageOrigin origin, bool conformMasks)
453  : ImageBase<MaskPixelT>(), _maskDict(detail::MaskDict::makeMaskDict()) {
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>
460 Mask<MaskPixelT>::Mask(fits::Fits& fitsfile, std::shared_ptr<daf::base::PropertySet> metadata,
461  afw::geom::Box2I const& bbox, ImageOrigin const origin, bool const conformMasks)
462  : ImageBase<MaskPixelT>(), _maskDict(detail::MaskDict::makeMaskDict()) {
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) {
467  metadata = std::shared_ptr<daf::base::PropertySet>(new daf::base::PropertyList);
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);
474  std::shared_ptr<detail::MaskDict> fileMD = detail::MaskDict::makeMaskDict(fileMaskDict);
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,
490  std::shared_ptr<lsst::daf::base::PropertySet const> metadata_i,
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>
497 void Mask<MaskPixelT>::writeFits(fits::MemFileManager& manager,
498  std::shared_ptr<lsst::daf::base::PropertySet const> metadata_i,
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>
505 void Mask<MaskPixelT>::writeFits(fits::Fits& fitsfile,
506  std::shared_ptr<lsst::daf::base::PropertySet const> metadata_i) const {
507  std::shared_ptr<dafBase::PropertySet> metadata;
508  if (metadata_i) {
509  metadata = metadata_i->deepCopy();
510  } else {
511  metadata = std::shared_ptr<dafBase::PropertySet>(new dafBase::PropertyList());
512  }
513  addMaskPlanesToMetadata(metadata);
514  //
515  // Add WCS with (X0, Y0) information
516  //
517  std::shared_ptr<dafBase::PropertySet> wcsAMetadata =
518  detail::createTrivialWcsAsPropertySet(detail::wcsNameForXY0, this->getX0(), this->getY0());
519  metadata->combine(wcsAMetadata);
520 
521  fits_write_image(fitsfile, *this, metadata);
522 }
523 
524 #endif // !DOXYGEN
525 
526 namespace {
527 struct addPlaneFunctor {
528  addPlaneFunctor(std::string const& name, int id) : _name(name), _id(id) {}
529 
530  void operator()(MapWithHash* dict) {
531  detail::MaskPlaneDict::const_iterator const it = // is id already used in this Mask?
532  std::find_if(
533  dict->begin(), dict->end(),
534  std::bind(std::equal_to<int>(), std::bind(&detail::MaskPlaneDict::value_type::second,
535  std::placeholders::_1),
536  _id));
537  if (it != dict->end()) { // mask plane is already in use
538  return;
539  }
540 
541  if (dict->find(_name) == dict->end()) { // not already set
542  dict->add(_name, _id);
543  }
544  }
545 
546  std::string const& _name;
547  int _id;
548 };
549 }
550 
551 template <typename MaskPixelT>
552 std::string Mask<MaskPixelT>::interpret(MaskPixelT value) {
553  std::string result = "";
554  MaskPlaneDict const& mpd = _maskPlaneDict()->getMaskPlaneDict();
555  for (MaskPlaneDict::const_iterator iter = mpd.begin(); iter != mpd.end(); ++iter) {
556  if (value & getBitMask(iter->second)) {
557  if (result.size() > 0) {
558  result += ",";
559  }
560  result += iter->first;
561  }
562  }
563  return result;
564 }
565 
566 template <typename MaskPixelT>
567 int Mask<MaskPixelT>::addMaskPlane(const std::string& name) {
568  int id = getMaskPlaneNoThrow(name); // see if the plane is already available
569 
570  if (id < 0) { // doesn't exist
571  id = _maskPlaneDict()->getUnusedPlane();
572  }
573 
574  // build new entry, adding the plane to all Masks where this is no contradiction
575 
576  if (id >= getNumPlanesMax()) { // Max number of planes is already allocated
577  throw LSST_EXCEPT(pexExcept::RuntimeError,
578  str(boost::format("Max number of planes (%1%) already used") % getNumPlanesMax()));
579  }
580 
581  _state.forEachMaskDict(addPlaneFunctor(name, id));
582 
583  return id;
584 }
585 
586 template <typename MaskPixelT>
587 int Mask<MaskPixelT>::addMaskPlane(std::string name, int planeId) {
588  if (planeId < 0 || planeId >= getNumPlanesMax()) {
589  throw LSST_EXCEPT(
590  pexExcept::RangeError,
591  str(boost::format("mask plane ID must be between 0 and %1%") % (getNumPlanesMax() - 1)));
592  }
593 
594  _maskPlaneDict()->add(name, planeId);
595 
596  return planeId;
597 }
598 
599 template <typename MaskPixelT>
601  return _maskDict->getMaskPlaneDict();
602 }
603 
604 template <typename MaskPixelT>
605 void Mask<MaskPixelT>::removeMaskPlane(const std::string& name) {
606  if (detail::MaskDict::makeMaskDict()->getMaskPlane(name) < 0) {
607  throw LSST_EXCEPT(pexExcept::InvalidParameterError,
608  str(boost::format("Plane %s doesn't exist in the default Mask") % name));
609  }
610 
611  detail::MaskDict::incrDefaultVersion(); // leave current Masks alone
612  _maskPlaneDict()->erase(name);
613 }
614 
615 template <typename MaskPixelT>
616 void Mask<MaskPixelT>::removeAndClearMaskPlane(const std::string& name, bool const removeFromDefault
617 
618  ) {
619  clearMaskPlane(getMaskPlane(name)); // clear this bits in this Mask
620 
621  if (_maskDict == detail::MaskDict::makeMaskDict() && removeFromDefault) { // we are the default
622  ;
623  } else {
624  _maskDict = _maskDict->clone();
625  }
626 
627  _maskDict->erase(name);
628 
629  if (removeFromDefault && detail::MaskDict::makeMaskDict()->getMaskPlane(name) >= 0) {
630  removeMaskPlane(name);
631  }
632 }
633 
634 template <typename MaskPixelT>
635 MaskPixelT Mask<MaskPixelT>::getBitMaskNoThrow(int planeId) {
636  return (planeId >= 0 && planeId < getNumPlanesMax()) ? (1 << planeId) : 0;
637 }
638 
639 template <typename MaskPixelT>
640 MaskPixelT Mask<MaskPixelT>::getBitMask(int planeId) {
641  MaskPlaneDict const& mpd = _maskPlaneDict()->getMaskPlaneDict();
642 
643  for (MaskPlaneDict::const_iterator i = mpd.begin(); i != mpd.end(); ++i) {
644  if (planeId == i->second) {
645  MaskPixelT const bitmask = getBitMaskNoThrow(planeId);
646  if (bitmask == 0) { // failed
647  break;
648  }
649  return bitmask;
650  }
651  }
652  throw LSST_EXCEPT(pexExcept::InvalidParameterError,
653  str(boost::format("Invalid mask plane ID: %d") % planeId));
654 }
655 
656 template <typename MaskPixelT>
657 int Mask<MaskPixelT>::getMaskPlane(const std::string& name) {
658  int const plane = getMaskPlaneNoThrow(name);
659 
660  if (plane < 0) {
661  throw LSST_EXCEPT(pexExcept::InvalidParameterError,
662  str(boost::format("Invalid mask plane name: %s") % name));
663  } else {
664  return plane;
665  }
666 }
667 
668 template <typename MaskPixelT>
669 int Mask<MaskPixelT>::getMaskPlaneNoThrow(const std::string& name) {
670  return _maskPlaneDict()->getMaskPlane(name);
671 }
672 
673 template <typename MaskPixelT>
674 MaskPixelT Mask<MaskPixelT>::getPlaneBitMask(const std::string& name) {
675  return getBitMask(getMaskPlane(name));
676 }
677 
678 template <typename MaskPixelT>
679 MaskPixelT Mask<MaskPixelT>::getPlaneBitMask(const std::vector<std::string>& name) {
680  MaskPixelT mpix = 0x0;
681  for (std::vector<std::string>::const_iterator it = name.begin(); it != name.end(); ++it) {
682  mpix |= getBitMask(getMaskPlane(*it));
683  }
684  return mpix;
685 }
686 
687 template <typename MaskPixelT>
689  return _maskPlaneDict()->size();
690 }
691 
692 template <typename MaskPixelT>
694  _maskPlaneDict()->clear();
695 }
696 
697 template <typename MaskPixelT>
699  *this = 0;
700 }
701 
702 template <typename MaskPixelT>
704  *this &= ~getBitMask(planeId);
705 }
706 
707 template <typename MaskPixelT>
708 void Mask<MaskPixelT>::conformMaskPlanes(MaskPlaneDict const& currentPlaneDict) {
709  std::shared_ptr<detail::MaskDict> currentMD = detail::MaskDict::makeMaskDict(currentPlaneDict);
710 
711  if (*_maskDict == *currentMD) {
712  if (*detail::MaskDict::makeMaskDict() == *_maskDict) {
713  return; // nothing to do
714  }
715  } else {
716  //
717  // Find out which planes need to be permuted
718  //
719  MaskPixelT keepBitmask = 0; // mask of bits to keep
720  MaskPixelT canonicalMask[sizeof(MaskPixelT) * 8]; // bits in lsst::afw::image::Mask that should be
721  MaskPixelT currentMask[sizeof(MaskPixelT) * 8]; // mapped to these bits
722  int numReMap = 0;
723 
724  for (MaskPlaneDict::const_iterator i = currentPlaneDict.begin(); i != currentPlaneDict.end(); i++) {
725  std::string const name = i->first; // name of mask plane
726  int const currentPlaneNumber = i->second; // plane number currently in use
727  int canonicalPlaneNumber = getMaskPlaneNoThrow(name); // plane number in lsst::afw::image::Mask
728 
729  if (canonicalPlaneNumber < 0) { // no such plane; add it
730  canonicalPlaneNumber = addMaskPlane(name);
731  }
732 
733  if (canonicalPlaneNumber == currentPlaneNumber) {
734  keepBitmask |= getBitMask(canonicalPlaneNumber); // bit is unchanged, so preserve it
735  } else {
736  canonicalMask[numReMap] = getBitMask(canonicalPlaneNumber);
737  currentMask[numReMap] = getBitMaskNoThrow(currentPlaneNumber);
738  numReMap++;
739  }
740  }
741 
742  // Now loop over all pixels in Mask
743  if (numReMap > 0) {
744  for (int r = 0; r != this->getHeight(); ++r) { // "this->": Meyers, Effective C++, Item 43
745  for (typename Mask::x_iterator ptr = this->row_begin(r), end = this->row_end(r); ptr != end;
746  ++ptr) {
747  MaskPixelT const pixel = *ptr;
748 
749  MaskPixelT newPixel = pixel & keepBitmask; // value of invariant mask bits
750  for (int i = 0; i < numReMap; i++) {
751  if (pixel & currentMask[i]) newPixel |= canonicalMask[i];
752  }
753 
754  *ptr = newPixel;
755  }
756  }
757  }
758  }
759  // We've made the planes match the current mask dictionary
760  _maskDict = detail::MaskDict::makeMaskDict();
761 }
762 
763 template <typename MaskPixelT>
765  return this->ImageBase<MaskPixelT>::operator()(x, y);
766 }
767 
768 template <typename MaskPixelT>
770  CheckIndices const& check) {
771  return this->ImageBase<MaskPixelT>::operator()(x, y, check);
772 }
773 
774 template <typename MaskPixelT>
776  return this->ImageBase<MaskPixelT>::operator()(x, y);
777 }
778 
779 template <typename MaskPixelT>
781  int x, int y, CheckIndices const& check) const {
782  return this->ImageBase<MaskPixelT>::operator()(x, y, check);
783 }
784 
785 template <typename MaskPixelT>
786 bool Mask<MaskPixelT>::operator()(int x, int y, int planeId) const {
787  // !! converts an int to a bool
788  return !!(this->ImageBase<MaskPixelT>::operator()(x, y) & getBitMask(planeId));
789 }
790 
791 template <typename MaskPixelT>
792 bool Mask<MaskPixelT>::operator()(int x, int y, int planeId, CheckIndices const& check) const {
793  // !! converts an int to a bool
794  return !!(this->ImageBase<MaskPixelT>::operator()(x, y, check) & getBitMask(planeId));
795 }
796 
797 template <typename MaskPixelT>
799  if (*_maskDict != *other._maskDict) {
800  throw LSST_EXCEPT(pexExcept::RuntimeError, "Mask dictionaries do not match");
801  }
802 }
803 
804 template <typename MaskPixelT>
806  transform_pixels(_getRawView(), _getRawView(),
807  [&val](MaskPixelT const& l) -> MaskPixelT { return l | val; });
808  return *this;
809 }
810 
811 template <typename MaskPixelT>
813  checkMaskDictionaries(rhs);
814 
815  if (this->getDimensions() != rhs.getDimensions()) {
816  throw LSST_EXCEPT(pexExcept::LengthError,
817  str(boost::format("Images are of different size, %dx%d v %dx%d") %
818  this->getWidth() % this->getHeight() % rhs.getWidth() % rhs.getHeight()));
819  }
820  transform_pixels(_getRawView(), rhs._getRawView(), _getRawView(),
821  [](MaskPixelT const& l, MaskPixelT const& r) -> MaskPixelT { return l | r; });
822  return *this;
823 }
824 
825 template <typename MaskPixelT>
827  transform_pixels(_getRawView(), _getRawView(), [&val](MaskPixelT const& l) { return l & val; });
828  return *this;
829 }
830 
831 template <typename MaskPixelT>
833  checkMaskDictionaries(rhs);
834 
835  if (this->getDimensions() != rhs.getDimensions()) {
836  throw LSST_EXCEPT(pexExcept::LengthError,
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>
847  transform_pixels(_getRawView(), _getRawView(),
848  [&val](MaskPixelT const& l) -> MaskPixelT { return l ^ val; });
849  return *this;
850 }
851 
852 template <typename MaskPixelT>
854  checkMaskDictionaries(rhs);
855 
856  if (this->getDimensions() != rhs.getDimensions()) {
857  throw LSST_EXCEPT(pexExcept::LengthError,
858  str(boost::format("Images are of different size, %dx%d v %dx%d") %
859  this->getWidth() % this->getHeight() % rhs.getWidth() % rhs.getHeight()));
860  }
861  transform_pixels(_getRawView(), rhs._getRawView(), _getRawView(),
862  [](MaskPixelT const& l, MaskPixelT const& r) -> MaskPixelT { return l ^ r; });
863  return *this;
864 }
865 
866 template <typename MaskPixelT>
867 void Mask<MaskPixelT>::setMaskPlaneValues(int const planeId, int const x0, int const x1, int const y) {
868  MaskPixelT const bitMask = getBitMask(planeId);
869 
870  for (int x = x0; x <= x1; x++) {
871  operator()(x, y) = operator()(x, y) | bitMask;
872  }
873 }
874 
875 template <typename MaskPixelT>
876 void Mask<MaskPixelT>::addMaskPlanesToMetadata(std::shared_ptr<dafBase::PropertySet> metadata) {
877  if (!metadata) {
878  throw LSST_EXCEPT(pexExcept::InvalidParameterError, "Null std::shared_ptr<PropertySet>");
879  }
880 
881  // First, clear existing MaskPlane metadata
882  typedef std::vector<std::string> NameList;
883  NameList paramNames = metadata->paramNames(false);
884  for (NameList::const_iterator i = paramNames.begin(); i != paramNames.end(); ++i) {
885  if (i->compare(0, maskPlanePrefix.size(), maskPlanePrefix) == 0) {
886  metadata->remove(*i);
887  }
888  }
889 
890  MaskPlaneDict const& mpd = _maskPlaneDict()->getMaskPlaneDict();
891 
892  // Add new MaskPlane metadata
893  for (MaskPlaneDict::const_iterator i = mpd.begin(); i != mpd.end(); ++i) {
894  std::string const& planeName = i->first;
895  int const planeNumber = i->second;
896 
897  if (planeName != "") {
898  metadata->add(maskPlanePrefix + planeName, planeNumber);
899  }
900  }
901 }
902 
903 template <typename MaskPixelT>
905  std::shared_ptr<dafBase::PropertySet const> metadata) {
906  MaskPlaneDict newDict;
907 
908  // First, clear existing MaskPlane metadata
909  typedef std::vector<std::string> NameList;
910  NameList paramNames = metadata->paramNames(false);
911  int numPlanesUsed = 0; // number of planes used
912 
913  // Iterate over childless properties with names starting with maskPlanePrefix
914  for (NameList::const_iterator i = paramNames.begin(); i != paramNames.end(); ++i) {
915  if (i->compare(0, maskPlanePrefix.size(), maskPlanePrefix) == 0) {
916  // split off maskPlanePrefix to obtain plane name
917  std::string planeName = i->substr(maskPlanePrefix.size());
918  int const planeId = metadata->getAsInt(*i);
919 
920  MaskPlaneDict::const_iterator plane = newDict.find(planeName);
921  if (plane != newDict.end() && planeId != plane->second) {
922  throw LSST_EXCEPT(pexExcept::RuntimeError, "File specifies plane " + planeName + " twice");
923  }
924  for (MaskPlaneDict::const_iterator j = newDict.begin(); j != newDict.end(); ++j) {
925  if (planeId == j->second) {
926  throw LSST_EXCEPT(pexExcept::RuntimeError,
927  str(boost::format("File specifies plane %s has same value (%d) as %s") %
928  planeName % planeId % j->first));
929  }
930  }
931  // build new entry
932  if (numPlanesUsed >= getNumPlanesMax()) {
933  // Max number of planes already allocated
934  throw LSST_EXCEPT(
935  pexExcept::RuntimeError,
936  str(boost::format("Max number of planes (%1%) already used") % getNumPlanesMax()));
937  }
938  newDict[planeName] = planeId;
939  }
940  }
941  return newDict;
942 }
943 
944 template <typename MaskPixelT>
946  _maskDict->print();
947 }
948 
949 /*
950  * Static members of Mask
951  */
952 template <typename MaskPixelT>
953 std::string const Mask<MaskPixelT>::maskPlanePrefix("MP_");
954 
955 template <typename MaskPixelT>
956 std::shared_ptr<detail::MaskDict> Mask<MaskPixelT>::_maskPlaneDict() {
958 }
959 
960 //
961 // Explicit instantiations
962 //
963 template class Mask<MaskPixel>;
964 }
965 }
966 }
static std::string interpret(MaskPixelT value)
Interpret a mask value as a comma-separated list of mask plane names.
Definition: Mask.cc:552
afw::table::PointKey< int > dimensions
Definition: GaussianPsf.cc:44
static void clearMaskPlaneDict()
Reset the maskPlane dictionary.
Definition: Mask.cc:693
std::size_t _hash
Definition: Mask.cc:130
std::string const & _name
Definition: Mask.cc:546
bool operator!=(Coord const &lhs, Coord const &rhs)
Inequality; the complement of equality.
Definition: Coord.h:818
void fits_write_image(fits::Fits &fitsfile, const ImageT &image, std::shared_ptr< daf::base::PropertySet const > metadata=std::shared_ptr< daf::base::PropertySet const >())
Definition: fits_io.h:99
void swap(ImageBase< PixelT > &a, ImageBase< PixelT > &b)
Definition: Image.cc:227
static int getMaskPlane(const std::string &name)
Return the mask plane number corresponding to a plane name.
Definition: Mask.cc:657
std::map< std::string, int > MaskPlaneDict
Definition: Mask.h:64
Mask & operator=(MaskPixelT const rhs)
Definition: Mask.cc:432
_view_t::x_iterator x_iterator
An iterator for traversing the pixels in a row.
Definition: Image.h:147
detail::MaskPlaneDict MaskPlaneDict
Definition: Mask.h:85
bool operator==(CoordKey const &lhs, CoordKey const &rhs)
Compare CoordKeys for equality using the constituent Keys.
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:876
static int getNumPlanesUsed()
Definition: Mask.cc:688
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:904
A simple struct that combines the two arguments that must be passed to most cfitsio routines and cont...
Definition: fits.h:199
The base class for all image classed (Image, Mask, MaskedImage, ...)
Definition: Image.h:116
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:616
ImageBase< MaskPixelT >::PixelReference operator()(int x, int y)
get a reference to the specified pixel
Definition: Mask.cc:764
An integer coordinate rectangle.
Definition: Box.h:55
Mask & operator&=(Mask const &rhs)
AND a Mask into a Mask.
Definition: Mask.cc:832
Mask(unsigned int width, unsigned int height, MaskPlaneDict const &planeDefs=MaskPlaneDict())
Construct a Mask initialized to 0x0.
Definition: Mask.cc:355
detail::MaskPlaneDict _dict
Definition: Mask.cc:129
geom::Extent2I getDimensions() const
Return the image&#39;s size; useful for passing to constructors.
Definition: Image.h:367
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:100
_view_t _getRawView() const
Definition: Image.h:476
void setMaskPlaneValues(const int plane, const int x0, const int x1, const int y)
Set the bit specified by &quot;planeId&quot; for pixels (x0, y) ...
Definition: Mask.cc:867
table::Key< std::string > name
Definition: ApCorrMap.cc:71
A class used to request that array accesses be checked.
Definition: Image.h:88
int getHeight() const
Return the number of rows in the image.
Definition: Image.h:309
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:679
void swap(ImageBase &rhs)
Definition: Image.cc:218
int _dictCounter
Definition: Mask.cc:249
double x
std::shared_ptr< MaskDict > clone() const
Definition: Mask.cc:281
Extent< int, 2 > ExtentI
Definition: Extent.h:338
int _id
Definition: Mask.cc:547
static std::shared_ptr< MaskDict > incrDefaultVersion()
Definition: Mask.cc:291
HandleList _dicts
Definition: Mask.cc:248
static void removeMaskPlane(const std::string &name)
Definition: Mask.cc:605
static std::shared_ptr< MaskDict > makeMaskDict()
Definition: Mask.cc:263
MaskPlaneDict const & getMaskPlaneDict() const
Return the Mask&#39;s maskPlaneDict.
Definition: Mask.cc:600
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.
afw::table::Key< afw::table::Array< ImagePixelT > > image
Mask & operator|=(Mask const &rhs)
OR a Mask into a Mask.
Definition: Mask.cc:812
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
std::shared_ptr< lsst::daf::base::PropertyList > createTrivialWcsAsPropertySet(std::string const &wcsName, int const x0=0, int const y0=0)
Definition: Wcs.cc:1069
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:708
std::shared_ptr< detail::MaskDict > _defaultMaskDict
Definition: Mask.cc:247
Mask & operator^=(Mask const &rhs)
XOR a Mask into a Mask.
Definition: Mask.cc:853
py::object result
Definition: schema.cc:290
void clearMaskPlane(int plane)
Clear the specified bit in all pixels.
Definition: Mask.cc:703
void printMaskPlanes() const
print the mask plane dictionary to std::cout
Definition: Mask.cc:945
int getWidth() const
Return the number of columns in the image.
Definition: Image.h:307
void clearAllMaskPlanes()
Clear all the pixels.
Definition: Mask.cc:698
static int addMaskPlane(const std::string &name)
Definition: Mask.cc:567
PixelReference operator()(int x, int y)
Return a reference to the pixel (x, y)
Definition: Image.cc:178
std::string const wcsNameForXY0
Definition: Image.h:84
int end
int getMaskPlane(const std::string &name) const
Definition: Mask.cc:319
lsst::daf::base::PropertyList PropertyList
Definition: Wcs.cc:56