lsst.afw  16.0-51-gb4b4a8566+2
ExposureFitsReader.cc
Go to the documentation of this file.
1 /*
2  * Developed for the LSST Data Management System.
3  * This product includes software developed by the LSST Project
4  * (https://www.lsst.org).
5  * See the COPYRIGHT file at the top-level directory of this distribution
6  * for details of code ownership.
7  *
8  * This program is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program. If not, see <https://www.gnu.org/licenses/>.
20  */
21 
22 #include "lsst/log/Log.h"
23 
24 #include "lsst/afw/image/Calib.h"
26 #include "lsst/afw/geom/SkyWcs.h"
28 #include "lsst/afw/detection/Psf.h"
31 
32 namespace lsst { namespace afw { namespace image {
33 
34 namespace {
35 
36 LOG_LOGGER _log = LOG_GET("afw.image.fits.ExposureFitsReader");
37 
38 } // anonymous
39 
41 public:
42 
46  lsst::geom::Point2I const & xy0
47  ) {
48  // Try to read WCS from image metadata, and if found, strip the keywords used
49  try {
50  wcs = afw::geom::makeSkyWcs(*imageMetadata, true);
52  LOGLS_DEBUG(_log, "No WCS found in FITS metadata");
53  }
54  if (wcs && any(xy0.ne(lsst::geom::Point2I(0, 0)))) {
55  wcs = wcs->copyAtShiftedPixelOrigin(lsst::geom::Extent2D(xy0));
56  }
57 
58  // Strip LTV1, LTV2 from imageMetadata, because we don't use it internally
59  imageMetadata->remove("LTV1");
60  imageMetadata->remove("LTV2");
61 
62  if (!imageMetadata->exists("INHERIT")) {
63  // New-style exposures put everything but the Wcs in the primary HDU, use
64  // INHERIT keyword in the others. For backwards compatibility, if we don't
65  // find the INHERIT keyword, we ignore the primary HDU metadata and expect
66  // everything to be in the image HDU metadata. Note that we can't merge them,
67  // because they're probably duplicates.
68  metadata = imageMetadata;
69  } else {
70  metadata = primaryMetadata;
71  }
72 
73  filter = Filter(metadata, true);
75 
76  visitInfo = std::make_shared<VisitInfo>(*metadata);
78 
79  calib = std::make_shared<Calib>(metadata);
81 
82  // Strip MJD-OBS and DATE-OBS from metadata; those may be read by
83  // either SkyWcs or VisitInfo or both, so neither can strip them.
84  metadata->remove("MJD-OBS");
85  metadata->remove("DATE-OBS");
86  }
87 
93 };
94 
95 
97 public:
98 
99  enum Component {
100  PSF=0,
106  N_ARCHIVE_COMPONENTS
107  };
108 
110  auto popInt = [&metadata](std::string const& name) {
111  // The default of zero will cause archive.get to return a
112  // null/empty pointer, just as if a null/empty pointer was
113  // originally written to the archive.
114  int r = 0;
115  if (metadata.exists(name)) {
116  r = metadata.get<int>(name);
117  // We remove metadata entries to maintaing our practice
118  // of stripped metadata entries that have been used to
119  // construct more structured components.
120  metadata.remove(name);
121  }
122  return r;
123  };
124  _hdu = popInt("AR_HDU");
125  if (_hdu == 0) {
126  _state = ArchiveState::MISSING;
127  } else {
128  --_hdu; // Switch from FITS 1-indexed convention to LSST 0-indexed convention.
129  _state = ArchiveState::PRESENT;
130  }
131  _ids[PSF] = popInt("PSF_ID");
132  _ids[WCS] = popInt("SKYWCS_ID");
133  _ids[COADD_INPUTS] = popInt("COADD_INPUTS_ID");
134  _ids[AP_CORR_MAP] = popInt("AP_CORR_MAP_ID");
135  _ids[VALID_POLYGON] = popInt("VALID_POLYGON_ID");
136  _ids[TRANSMISSION_CURVE] = popInt("TRANSMISSION_CURVE_ID");
137  }
138 
139  template <typename T>
141  if (!_ensureLoaded(fitsFile)) {
142  return nullptr;
143  }
144  return _archive.get<T>(_ids[c]);
145  }
146 
147 private:
148 
149  bool _ensureLoaded(afw::fits::Fits * fitsFile) {
150  if (_state == ArchiveState::MISSING) {
151  return false;
152  }
153  if (_state == ArchiveState::PRESENT) {
154  afw::fits::HduMoveGuard guard(*fitsFile, _hdu);
156  _state = ArchiveState::LOADED;
157  }
158  assert(_state == ArchiveState::LOADED); // constructor body should guarantee it's not UNKNOWN
159  return true;
160  }
161 
162  enum class ArchiveState { UNKNOWN, MISSING, PRESENT, LOADED };
163 
164  int _hdu = 0;
165  ArchiveState _state = ArchiveState::UNKNOWN;
168 };
169 
170 
172  _maskedImageReader(fileName)
173 {}
174 
176  _maskedImageReader(manager)
177 {}
178 
180  _maskedImageReader(fitsFile)
181 {}
182 
183 ExposureFitsReader::~ExposureFitsReader() noexcept = default;
184 
186  return _maskedImageReader.readBBox(origin);
187 }
188 
190  return _maskedImageReader.readXY0(bbox, origin);
191 }
192 
193 std::string ExposureFitsReader::readImageDType() const { return _maskedImageReader.readImageDType(); }
194 
195 std::string ExposureFitsReader::readMaskDType() const { return _maskedImageReader.readMaskDType(); }
196 
198 
200  _ensureReaders();
201  return _metadataReader->metadata;
202 }
203 
205  _ensureReaders();
206  auto r = _archiveReader->readComponent<afw::geom::SkyWcs>(_getFitsFile(), ArchiveReader::WCS);
207  if (!r) {
208  r = _metadataReader->wcs;
209  }
210  return r;
211 }
212 
214  _ensureReaders();
215  return _metadataReader->filter;
216 }
217 
219  _ensureReaders();
220  return _metadataReader->calib;
221 }
222 
224  _ensureReaders();
225  return _archiveReader->readComponent<detection::Psf>(_getFitsFile(), ArchiveReader::PSF);
226 }
227 
229  _ensureReaders();
230  return _archiveReader->readComponent<afw::geom::polygon::Polygon>(_getFitsFile(),
232 }
233 
235  _ensureReaders();
236  return _archiveReader->readComponent<ApCorrMap>(_getFitsFile(), ArchiveReader::AP_CORR_MAP);
237 }
238 
240  _ensureReaders();
241  return _archiveReader->readComponent<CoaddInputs>(_getFitsFile(), ArchiveReader::COADD_INPUTS);
242 }
243 
245  _ensureReaders();
246  return _metadataReader->visitInfo;
247 }
248 
250  _ensureReaders();
251  return _archiveReader->readComponent<TransmissionCurve>(_getFitsFile(), ArchiveReader::TRANSMISSION_CURVE);
252 }
253 
255  auto result = std::make_shared<ExposureInfo>();
256  result->setMetadata(readMetadata());
257  result->setFilter(readFilter());
258  result->setCalib(readCalib());
259  result->setVisitInfo(readVisitInfo());
260  // When reading an ExposureInfo (as opposed to reading individual
261  // components), we warn and try to proceed when a component is present
262  // but can't be read due its serialization factory not being set up
263  // (that's what throws the NotFoundErrors caught below).
264  try {
265  result->setPsf(readPsf());
266  } catch (pex::exceptions::NotFoundError& err) {
267  LOGLS_WARN(_log, "Could not read PSF; setting to null: " << err.what());
268  }
269  try {
270  result->setCoaddInputs(readCoaddInputs());
271  } catch (pex::exceptions::NotFoundError& err) {
272  LOGLS_WARN(_log, "Could not read CoaddInputs; setting to null: " << err.what());
273  }
274  try {
275  result->setApCorrMap(readApCorrMap());
276  } catch (pex::exceptions::NotFoundError& err) {
277  LOGLS_WARN(_log, "Could not read ApCorrMap; setting to null: " << err.what());
278  }
279  try {
280  result->setValidPolygon(readValidPolygon());
281  } catch (pex::exceptions::NotFoundError& err) {
282  LOGLS_WARN(_log, "Could not read ValidPolygon; setting to null: " << err.what());
283  }
284  try {
285  result->setTransmissionCurve(readTransmissionCurve());
286  } catch (pex::exceptions::NotFoundError& err) {
287  LOGLS_WARN(_log, "Could not read TransmissionCurve; setting to null: " << err.what());
288  }
289  // In the case of WCS, we fall back to the metadata WCS if the one from
290  // the archive can't be read.
291  _ensureReaders();
292  result->setWcs(_metadataReader->wcs);
293  try {
294  auto wcs = _archiveReader->readComponent<afw::geom::SkyWcs>(_getFitsFile(), ArchiveReader::WCS);
295  if (!wcs) {
296  LOGLS_DEBUG(_log, "No WCS found in binary table");
297  } else {
298  result->setWcs(wcs);
299  }
300  } catch (pex::exceptions::NotFoundError & err) {
301  auto msg = str(boost::format("Could not read WCS extension; setting to null: %s") % err.what());
302  if (result->hasWcs()) {
303  msg += " ; using WCS from FITS header";
304  }
305  LOGLS_WARN(_log, msg);
306  }
307  return result;
308 }
309 
310 template <typename ImagePixelT>
312  bool allowUnsafe) {
313  return _maskedImageReader.readImage<ImagePixelT>(bbox, origin, allowUnsafe);
314 }
315 
316 template <typename ImagePixelT>
317 ndarray::Array<ImagePixelT, 2, 2> ExposureFitsReader::readImageArray(lsst::geom::Box2I const & bbox,
318  ImageOrigin origin,
319  bool allowUnsafe) {
320  return _maskedImageReader.readImageArray<ImagePixelT>(bbox, origin, allowUnsafe);
321 }
322 
323 template <typename MaskPixelT>
325  bool conformMasks, bool allowUnsafe) {
326  return _maskedImageReader.readMask<MaskPixelT>(bbox, origin, conformMasks, allowUnsafe);
327 }
328 
329 template <typename MaskPixelT>
330 ndarray::Array<MaskPixelT, 2, 2> ExposureFitsReader::readMaskArray(lsst::geom::Box2I const & bbox,
331  ImageOrigin origin,
332  bool allowUnsafe) {
333  return _maskedImageReader.readMaskArray<MaskPixelT>(bbox, origin, allowUnsafe);
334 }
335 
336 template <typename VariancePixelT>
338  bool allowUnsafe) {
339  return _maskedImageReader.readVariance<VariancePixelT>(bbox, origin, allowUnsafe);
340 }
341 
342 template <typename VariancePixelT>
343 ndarray::Array<VariancePixelT, 2, 2> ExposureFitsReader::readVarianceArray(lsst::geom::Box2I const & bbox,
344  ImageOrigin origin,
345  bool allowUnsafe) {
346  return _maskedImageReader.readVarianceArray<VariancePixelT>(bbox, origin, allowUnsafe);
347 }
348 
349 template <typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
351  lsst::geom::Box2I const & bbox,
352  ImageOrigin origin,
353  bool conformMasks,
354  bool allowUnsafe
355 ) {
356  return _maskedImageReader.read<ImagePixelT, MaskPixelT, VariancePixelT>(bbox, origin, conformMasks,
357  /* needAllHdus= */false,
358  allowUnsafe);
359 }
360 
361 template <typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
363  lsst::geom::Box2I const & bbox,
364  ImageOrigin origin,
365  bool conformMasks,
366  bool allowUnsafe
367 ) {
368  auto mi = readMaskedImage<ImagePixelT, MaskPixelT, VariancePixelT>(bbox, origin, conformMasks,
369  allowUnsafe);
371 }
372 
373 void ExposureFitsReader::_ensureReaders() {
374  if (!_metadataReader) {
375  auto metadataReader = std::make_unique<MetadataReader>(
376  _maskedImageReader.readPrimaryMetadata(),
377  _maskedImageReader.readImageMetadata(),
378  _maskedImageReader.readXY0()
379  );
380  _archiveReader = std::make_unique<ArchiveReader>(*metadataReader->metadata);
381  _metadataReader = std::move(metadataReader); // deferred for exception safety
382  }
383  assert(_archiveReader); // should always be initialized with _metadataReader.
384 }
385 
386 #define INSTANTIATE(ImagePixelT) \
387  template Exposure<ImagePixelT, MaskPixel, VariancePixel> ExposureFitsReader::read( \
388  lsst::geom::Box2I const &, \
389  ImageOrigin, \
390  bool, bool \
391  ); \
392  template Image<ImagePixelT> ExposureFitsReader::readImage( \
393  lsst::geom::Box2I const &, \
394  ImageOrigin, bool \
395  ); \
396  template ndarray::Array<ImagePixelT, 2, 2> ExposureFitsReader::readImageArray(\
397  lsst::geom::Box2I const &, \
398  ImageOrigin, \
399  bool \
400  ); \
401  template MaskedImage<ImagePixelT, MaskPixel, VariancePixel> ExposureFitsReader::readMaskedImage( \
402  lsst::geom::Box2I const &, \
403  ImageOrigin, \
404  bool, bool \
405  )
406 
408 INSTANTIATE(int);
409 INSTANTIATE(float);
410 INSTANTIATE(double);
412 
413 template Mask<MaskPixel> ExposureFitsReader::readMask(
414  lsst::geom::Box2I const &,
415  ImageOrigin,
416  bool,
417  bool
418 );
419 template ndarray::Array<MaskPixel, 2, 2> ExposureFitsReader::readMaskArray(
420  lsst::geom::Box2I const &,
421  ImageOrigin,
422  bool
423 );
424 
425 template Image<VariancePixel> ExposureFitsReader::readVariance(
426  lsst::geom::Box2I const &,
427  ImageOrigin,
428  bool
429 );
430 template ndarray::Array<VariancePixel, 2, 2> ExposureFitsReader::readVarianceArray(
431  lsst::geom::Box2I const &,
432  ImageOrigin,
433  bool
434 );
435 
436 
437 
438 }}} // lsst::afw::image
#define LOGLS_WARN(logger, message)
std::shared_ptr< T > readComponent(afw::fits::Fits *fitsFile, Component c)
lsst::geom::Box2I readBBox(ImageOrigin origin=PARENT)
Read the bounding box of the on-disk image.
A 2-dimensional celestial WCS that transform pixels to ICRS RA/Dec, using the LSST standard for pixel...
Definition: SkyWcs.h:115
A spatially-varying transmission curve as a function of wavelength.
std::shared_ptr< daf::base::PropertyList > metadata
std::shared_ptr< ExposureInfo > readExposureInfo()
Read the ExposureInfo containing all non-image components.
CoordinateExpr< N > ne(Point< int, N > const &other) const noexcept
lsst::geom::Box2I readBBox(ImageOrigin origin=PARENT)
Read the bounding box of the on-disk image.
Image< VariancePixelT > readVariance(lsst::geom::Box2I const &bbox=lsst::geom::Box2I(), ImageOrigin origin=PARENT, bool allowUnsafe=false)
Read the variance plane.
virtual char const * what(void) const noexcept
std::shared_ptr< Calib > readCalib()
Read the Exposure&#39;s photometric calibration.
A thin wrapper around std::map to allow aperture corrections to be attached to Exposures.
Definition: ApCorrMap.h:44
A class to contain the data, WCS, and other information needed to describe an image of the sky...
Definition: Exposure.h:72
std::string readVarianceDType() const
Read a string describing the pixel type of the on-disk image plane.
std::shared_ptr< CoaddInputs > readCoaddInputs()
Read the Exposure&#39;s coadd input catalogs.
ndarray::Array< MaskPixelT, 2, 2 > readMaskArray(lsst::geom::Box2I const &bbox=lsst::geom::Box2I(), ImageOrigin origin=PARENT, bool allowUnsafe=false)
Read the mask plane.
Image< VariancePixelT > readVariance(lsst::geom::Box2I const &bbox=lsst::geom::Box2I(), ImageOrigin origin=PARENT, bool allowUnsafe=false)
Read the variance plane.
int stripFilterKeywords(std::shared_ptr< lsst::daf::base::PropertySet > metadata)
Remove Filter-related keywords from the metadata.
Definition: Filter.cc:138
ndarray::Array< VariancePixelT, 2, 2 > readVarianceArray(lsst::geom::Box2I const &bbox=lsst::geom::Box2I(), ImageOrigin origin=PARENT, bool allowUnsafe=false)
Read the variance plane.
std::shared_ptr< VisitInfo > readVisitInfo()
Read the Exposure&#39;s visit metadata.
Image< ImagePixelT > readImage(lsst::geom::Box2I const &bbox=lsst::geom::Box2I(), ImageOrigin origin=PARENT, bool allowUnsafe=false)
Read the image plane.
ExposureFitsReader(std::string const &fileName)
Construct a FITS reader object.
A simple struct that combines the two arguments that must be passed to most cfitsio routines and cont...
Definition: fits.h:296
Rotation angle is unknown.
std::shared_ptr< io::OutputArchive > _archive
Definition: Exposure.cc:202
Image< ImagePixelT > readImage(lsst::geom::Box2I const &bbox=lsst::geom::Box2I(), ImageOrigin origin=PARENT, bool allowUnsafe=false)
Read the image plane.
bool any(CoordinateExpr< N > const &expr) noexcept
std::string readImageDType() const
Read a string describing the pixel type of the on-disk image plane.
A simple Persistable struct containing ExposureCatalogs that record the inputs to a coadd...
Definition: CoaddInputs.h:48
STL class.
Filter readFilter()
Read the Exposure&#39;s filter.
virtual void remove(std::string const &name)
std::shared_ptr< afw::geom::polygon::Polygon > readValidPolygon()
Read the polygon describing the region of validity for the Exposure.
table::Key< table::Array< std::uint8_t > > wcs
Definition: SkyWcs.cc:71
#define LOGLS_DEBUG(logger, message)
A base class for image defects.
Represent a 2-dimensional array of bitmask pixels.
Definition: Mask.h:78
Lifetime-management for memory that goes into FITS memory files.
Definition: fits.h:120
std::string readImageDType() const
Read a string describing the pixel type of the on-disk image plane.
A class to manipulate images, masks, and variance as a single object.
Definition: MaskedImage.h:74
std::shared_ptr< daf::base::PropertyList > readPrimaryMetadata()
Read the FITS header of one of the HDUs.
bool exists(std::string const &name) const
int stripCalibKeywords(std::shared_ptr< lsst::daf::base::PropertySet > metadata)
Remove Calib-related keywords from the metadata.
Definition: Calib.cc:160
T move(T... args)
std::string readMaskDType() const
Read a string describing the pixel type of the on-disk image plane.
Holds an integer identifier for an LSST filter.
Definition: Filter.h:153
std::unique_ptr< SchemaItem< U > > result
Definition: Schema.cc:194
std::shared_ptr< afw::geom::SkyWcs > readWcs()
Read the Exposure&#39;s world coordinate system.
Mask< MaskPixelT > readMask(lsst::geom::Box2I const &bbox=lsst::geom::Box2I(), ImageOrigin origin=PARENT, bool conformMasks=false, bool allowUnsafe=false)
Read the mask plane.
ndarray::Array< VariancePixelT, 2, 2 > readVarianceArray(lsst::geom::Box2I const &bbox=lsst::geom::Box2I(), ImageOrigin origin=PARENT, bool allowUnsafe=false)
Read the variance plane.
MaskedImage< ImagePixelT, MaskPixelT, VariancePixelT > read(lsst::geom::Box2I const &bbox=lsst::geom::Box2I(), ImageOrigin origin=PARENT, bool conformMasks=false, bool needAllHdus=false, bool allowUnsafe=false)
Read the full MaskedImage.
std::shared_ptr< ApCorrMap > readApCorrMap()
Read the Exposure&#39;s aperture correction map.
std::string readMaskDType() const
Read a string describing the pixel type of the on-disk image plane.
T get(std::string const &name) const
MaskedImage< ImagePixelT, MaskPixelT, VariancePixelT > readMaskedImage(lsst::geom::Box2I const &bbox=lsst::geom::Box2I(), ImageOrigin origin=PARENT, bool conformMasks=false, bool allowUnsafe=false)
Read the MaskedImage.
static InputArchive readFits(fits::Fits &fitsfile)
Read an object from an already open FITS object.
std::shared_ptr< SkyWcs > makeSkyWcs(daf::base::PropertySet &metadata, bool strip=false)
Construct a SkyWcs from FITS keywords.
Definition: SkyWcs.cc:476
std::string readVarianceDType() const
Read a string describing the pixel type of the on-disk image plane.
ndarray::Array< ImagePixelT, 2, 2 > readImageArray(lsst::geom::Box2I const &bbox=lsst::geom::Box2I(), ImageOrigin origin=PARENT, bool allowUnsafe=false)
Read the image plane.
#define INSTANTIATE(ImagePixelT)
int stripVisitInfoKeywords(daf::base::PropertySet &metadata)
Remove VisitInfo-related keywords from the metadata.
Definition: VisitInfo.cc:266
table::Box2IKey bbox
lsst::geom::Point2I readXY0(lsst::geom::Box2I const &bbox=lsst::geom::Box2I(), ImageOrigin origin=PARENT)
Read the image origin from the on-disk image or a subimage thereof.
Cartesian polygons.
Definition: Polygon.h:58
ndarray::Array< MaskPixelT, 2, 2 > readMaskArray(lsst::geom::Box2I const &bbox=lsst::geom::Box2I(), ImageOrigin origin=PARENT, bool allowUnsafe=false)
Read the mask plane.
Exposure< ImagePixelT, MaskPixelT, VariancePixelT > read(lsst::geom::Box2I const &bbox=lsst::geom::Box2I(), ImageOrigin origin=PARENT, bool conformMasks=false, bool allowUnsafe=false)
Read the full Exposure.
std::shared_ptr< daf::base::PropertyList > readMetadata()
Read the flexible metadata associated with the Exposure.
std::shared_ptr< daf::base::PropertyList > readImageMetadata()
Read the FITS header of one of the HDUs.
std::shared_ptr< detection::Psf > readPsf()
Read the Exposure&#39;s point-spread function.
Mask< MaskPixelT > readMask(lsst::geom::Box2I const &bbox=lsst::geom::Box2I(), ImageOrigin origin=PARENT, bool conformMasks=false, bool allowUnsafe=false)
Read the mask plane.
A multi-catalog archive object used to load table::io::Persistable objects.
Definition: InputArchive.h:31
#define LOG_GET(logger)
A polymorphic base class for representing an image&#39;s Point Spread Function.
Definition: Psf.h:75
MetadataReader(std::shared_ptr< daf::base::PropertyList > primaryMetadata, std::shared_ptr< daf::base::PropertyList > imageMetadata, lsst::geom::Point2I const &xy0)
std::shared_ptr< TransmissionCurve > readTransmissionCurve()
Read the Exposure&#39;s transmission curve.
A class to represent a 2-dimensional array of pixels.
Definition: Image.h:59
ndarray::Array< ImagePixelT, 2, 2 > readImageArray(lsst::geom::Box2I const &bbox=lsst::geom::Box2I(), ImageOrigin origin=PARENT, bool allowUnsafe=false)
Read the image plane.
RAII scoped guard for moving the HDU in a Fits object.
Definition: fits.h:723
lsst::geom::Point2I readXY0(lsst::geom::Box2I const &bbox=lsst::geom::Box2I(), ImageOrigin origin=PARENT)
Read the image origin from the on-disk image or a subimage thereof.