lsst.afw  13.0-110-ge674a0930
fits.h
Go to the documentation of this file.
1 // -*- lsst-c++ -*-
2 #ifndef LSST_AFW_fits_h_INCLUDED
3 #define LSST_AFW_fits_h_INCLUDED
4 
5 /*
6  * Utilities for working with FITS files. These are mostly thin wrappers around
7  * cfitsio calls, and their main purpose is to transform functions signatures from
8  * void pointers and cfitsio's preprocessor type enums to a more type-safe and
9  * convenient interface using overloads and templates.
10  *
11  * This was written as part of implementing the afw/table library. Someday
12  * the afw/image FITS I/O should be modified to use some of these with the goal
13  * of eliminating a lot of code between the two.
14  */
15 
16 #include <climits>
17 #include <string>
18 
19 #include <boost/format.hpp>
20 
21 #include "lsst/base.h"
22 #include "lsst/pex/exceptions.h"
23 #include "lsst/daf/base.h"
24 #include "ndarray.h"
26 
27 namespace lsst {
28 namespace afw {
29 namespace fits {
30 
34 LSST_EXCEPTION_TYPE(FitsError, lsst::pex::exceptions::IoError, lsst::afw::fits::FitsError)
35 
36 
39 LSST_EXCEPTION_TYPE(FitsTypeError, lsst::afw::fits::FitsError, lsst::afw::fits::FitsTypeError)
40 
48 public:
49  virtual void operator()(std::string const& key, std::string const& value, std::string const& comment) = 0;
50 
52 };
53 
62 std::string makeErrorMessage(std::string const& fileName = "", int status = 0, std::string const& msg = "");
63 inline std::string makeErrorMessage(std::string const& fileName, int status, boost::format const& msg) {
64  return makeErrorMessage(fileName, status, msg.str());
65 }
66 
76 std::string makeErrorMessage(void* fptr, int status = 0, std::string const& msg = "");
77 inline std::string makeErrorMessage(void* fptr, int status, boost::format const& msg) {
78  return makeErrorMessage(fptr, status, msg.str());
79 }
80 
85 #define LSST_FITS_EXCEPT(type, fitsObj, ...) \
86  type(LSST_EXCEPT_HERE, lsst::afw::fits::makeErrorMessage((fitsObj).fptr, (fitsObj).status, __VA_ARGS__))
87 
91 #define LSST_FITS_CHECK_STATUS(fitsObj, ...) \
92  if ((fitsObj).status != 0) throw LSST_FITS_EXCEPT(lsst::afw::fits::FitsError, fitsObj, __VA_ARGS__)
93 
95 template <typename T>
96 int getBitPix();
97 
102 public:
109  MemFileManager() : _ptr(0), _len(0), _managed(true) {}
110 
117  explicit MemFileManager(std::size_t len) : _ptr(0), _len(0), _managed(true) { reset(len); }
118 
126  MemFileManager(void* ptr, std::size_t len) : _ptr(ptr), _len(len), _managed(false) {}
127 
133  void reset();
134 
143  void reset(std::size_t len);
144 
153  void reset(void* ptr, std::size_t len) {
154  reset();
155  _ptr = ptr;
156  _len = len;
157  _managed = false;
158  }
159 
161 
162  // No copying
163  MemFileManager(const MemFileManager&) = delete;
164  MemFileManager& operator=(const MemFileManager&) = delete;
165 
166  // No moving
167  MemFileManager(MemFileManager&&) = delete;
169 
171  void* getData() const { return _ptr; }
172 
174  std::size_t getLength() const { return _len; }
175 
176 private:
177  friend class Fits;
178 
179  void* _ptr;
180  std::size_t _len;
181  bool _managed;
182 };
183 
184 
188 template <typename T, int N, int C>
189 ndarray::Array<T const, N, N> const makeContiguousArray(ndarray::Array<T, N, C> const& array) {
190  ndarray::Array<T const, N, N> contiguous = ndarray::dynamic_dimension_cast<N>(array);
191  if (contiguous.empty()) contiguous = ndarray::copy(array);
192  return contiguous;
193 }
194 
195 
204 
206  template <typename T>
207  explicit ImageWriteOptions(image::Image<T> const& image) : compression(image) {}
208 
210  template <typename T>
211  explicit ImageWriteOptions(image::Mask<T> const& mask) : compression(mask) {}
212 
216  ImageScalingOptions const& scaling_=ImageScalingOptions())
217  : compression(compression_), scaling(scaling_) {}
218 
220  explicit ImageWriteOptions(ImageScalingOptions const& scaling_)
221  : compression(ImageCompressionOptions::NONE), scaling(scaling_) {}
222 
248 
260  static std::shared_ptr<daf::base::PropertySet> validate(daf::base::PropertySet const& config);
261 };
262 
279 class Fits {
280  void createImageImpl(int bitpix, int nAxis, long const* nAxes);
281  template <typename T>
282  void writeImageImpl(T const* data, int nElements);
283  template <typename T>
284  void readImageImpl(int nAxis, T* data, long* begin, long* end, long* increment);
285  void getImageShapeImpl(int maxDim, long* nAxes);
286 
287 public:
289  AUTO_CLOSE = 0x01, // Close files when the Fits object goes out of scope if fptr != NULL
290  AUTO_CHECK = 0x02 // Call LSST_FITS_CHECK_STATUS after every cfitsio call
291  };
292 
294  std::string getFileName() const;
295 
297  int getHdu();
298 
308  void setHdu(int hdu, bool relative = false);
309 
311  int countHdus();
312 
314  template <typename T>
316  void updateKey(std::string const& key, T const& value, std::string const& comment);
317  void updateKey(std::string const& key, char const* value, std::string const& comment) {
318  updateKey(key, std::string(value), comment);
319  }
320  template <typename T>
321  void updateKey(std::string const& key, T const& value);
322  void updateKey(std::string const& key, char const* value) { updateKey(key, std::string(value)); }
324 
326 
333  template <typename T>
334  void writeKey(std::string const& key, T const& value, std::string const& comment);
335  void writeKey(std::string const& key, char const* value, std::string const& comment) {
336  writeKey(key, std::string(value), comment);
337  }
338  template <typename T>
339  void writeKey(std::string const& key, T const& value);
340  void writeKey(std::string const& key, char const* value) { writeKey(key, std::string(value)); }
342 
344  template <typename T>
346  void updateColumnKey(std::string const& prefix, int n, T const& value, std::string const& comment);
347  void updateColumnKey(std::string const& prefix, int n, char const* value, std::string const& comment) {
348  updateColumnKey(prefix, n, std::string(value), comment);
349  }
350  template <typename T>
351  void updateColumnKey(std::string const& prefix, int n, T const& value);
352  void updateColumnKey(std::string const& prefix, int n, char const* value) {
353  updateColumnKey(prefix, n, std::string(value));
354  }
356 
358  template <typename T>
360  void writeColumnKey(std::string const& prefix, int n, T const& value, std::string const& comment);
361  void writeColumnKey(std::string const& prefix, int n, char const* value, std::string const& comment) {
362  writeColumnKey(prefix, n, std::string(value), comment);
363  }
364  template <typename T>
365  void writeColumnKey(std::string const& prefix, int n, T const& value);
366  void writeColumnKey(std::string const& prefix, int n, char const* value) {
367  writeColumnKey(prefix, n, std::string(value));
368  }
370 
380  void writeMetadata(daf::base::PropertySet const& metadata);
381 
391  void readMetadata(daf::base::PropertySet& metadata, bool strip = false);
392 
394  template <typename T>
395  void readKey(std::string const& key, T& value);
396 
405  void forEachKey(HeaderIterationFunctor& functor);
406 
413  void createEmpty();
414 
425  template <typename PixelT, int N>
426  void createImage(ndarray::Vector<ndarray::Size, N> const& shape) {
427  ndarray::Vector<long, N> nAxes(shape.reverse());
428  createImageImpl(detail::Bitpix<PixelT>::value, N, nAxes.elems);
429  }
430 
431  template <int N>
432  void createImage(int bitpix, ndarray::Vector<ndarray::Size, N> const& shape) {
433  ndarray::Vector<long, N> nAxes(shape.reverse());
434  createImageImpl(bitpix, N, nAxes.elems);
435  }
436 
443  template <typename PixelT>
444  void createImage(long x, long y) {
445  long naxes[2] = {x, y};
446  createImageImpl(detail::Bitpix<PixelT>::value, 2, naxes);
447  }
448 
458  template <typename T, int N, int C>
459  void writeImage(ndarray::Array<T const, N, C> const& array) {
460  writeImageImpl(makeContiguousArray(array).getData(), array.getNumElements());
461  }
462 
475  template <typename T>
476  void writeImage(
477  image::ImageBase<T> const& image,
478  ImageWriteOptions const& options,
479  std::shared_ptr<daf::base::PropertySet const> header=std::shared_ptr<daf::base::PropertyList>(),
480  std::shared_ptr<image::Mask<image::MaskPixel> const> mask=
481  std::shared_ptr<image::Mask<image::MaskPixel>>()
482  );
483 
485  int getImageDim();
486 
495  template <int N>
496  ndarray::Vector<ndarray::Size, N> getImageShape() {
497  ndarray::Vector<long, N> nAxes(1);
498  getImageShapeImpl(N, nAxes.elems);
499  ndarray::Vector<ndarray::Size, N> shape;
500  for (int i = 0; i < N; ++i) shape[i] = nAxes[N - i - 1];
501  return shape;
502  }
503 
510  template <typename T>
511  bool checkImageType();
512 
519  template <typename T, int N>
520  void readImage(ndarray::Array<T, N, N> const& array, ndarray::Vector<int, N> const& offset) {
521  ndarray::Vector<long, N> begin(offset.reverse());
522  ndarray::Vector<long, N> end(begin);
523  end += array.getShape().reverse();
524  ndarray::Vector<long, N> increment(1);
525  begin += increment; // first FITS pixel is 1, not 0
526  readImageImpl(N, array.getData(), begin.elems, end.elems, increment.elems);
527  }
528 
530  void createTable();
531 
538  template <typename T>
539  int addColumn(std::string const& ttype, int size, std::string const& comment);
540 
547  template <typename T>
548  int addColumn(std::string const& ttype, int size);
549 
551  std::size_t addRows(std::size_t nRows);
552 
554  std::size_t countRows();
555 
557  template <typename T>
558  void writeTableArray(std::size_t row, int col, int nElements, T const* value);
559 
561  template <typename T>
562  void writeTableScalar(std::size_t row, int col, T value) {
563  writeTableArray(row, col, 1, &value);
564  }
566  void writeTableScalar(std::size_t row, int col, std::string const& value);
567 
569  template <typename T>
570  void readTableArray(std::size_t row, int col, int nElements, T* value);
571 
573  template <typename T>
574  void readTableScalar(std::size_t row, int col, T& value) {
575  readTableArray(row, col, 1, &value);
576  }
577 
579  void readTableScalar(std::size_t row, int col, std::string& value, bool isVariableLength);
580 
582  long getTableArraySize(int col);
583 
585  long getTableArraySize(std::size_t row, int col);
586 
588  Fits() : fptr(0), status(0), behavior(0) {}
589 
591  Fits(std::string const& filename, std::string const& mode, int behavior);
592 
594  Fits(MemFileManager& manager, std::string const& mode, int behavior);
595 
597  void closeFile();
598 
602  void setImageCompression(ImageCompressionOptions const& options);
603 
605  ImageCompressionOptions getImageCompression();
606 
614  bool checkCompressedImagePhu();
615 
616  ~Fits() {
617  if ((fptr) && (behavior & AUTO_CLOSE)) closeFile();
618  }
619 
620  // No copying
621  Fits(const Fits&) = delete;
622  Fits& operator=(const Fits&) = delete;
623 
624  // No moving
625  Fits(Fits&&) = delete;
626  Fits& operator=(Fits&&) = delete;
627 
628  void* fptr; // the actual cfitsio fitsfile pointer; void to avoid including fitsio.h here.
629  int status; // the cfitsio status indicator that gets passed to every cfitsio call.
630  int behavior; // bitwise OR of BehaviorFlags
631 };
632 
643 std::shared_ptr<daf::base::PropertyList> readMetadata(std::string const& fileName, int hdu = INT_MIN,
644  bool strip = false);
655 std::shared_ptr<daf::base::PropertyList> readMetadata(fits::MemFileManager& manager, int hdu = INT_MIN,
656  bool strip = false);
666 std::shared_ptr<daf::base::PropertyList> readMetadata(fits::Fits& fitsfile, bool strip = false);
667 
668 
669 void setAllowImageCompression(bool allow);
671 
672 }
673 }
674 }
675 
676 #endif // !LSST_AFW_fits_h_INCLUDED
void createImage(int bitpix, ndarray::Vector< ndarray::Size, N > const &shape)
Definition: fits.h:432
void writeKey(std::string const &key, char const *value)
Add a FITS header key to the bottom of the header.
Definition: fits.h:340
MemFileManager(std::size_t len)
Construct a MemFileManager with (len) bytes of initial memory.
Definition: fits.h:117
void updateKey(std::string const &key, char const *value)
Set a FITS header key, editing if it already exists and appending it if not.
Definition: fits.h:322
void writeColumnKey(std::string const &prefix, int n, char const *value)
Write a key of the form XXXXXnnn, where XXXXX is the prefix and nnn is a column number.
Definition: fits.h:366
ImageCompressionOptions compression
Options controlling compression.
Definition: fits.h:202
afw::table::Key< afw::table::Array< MaskPixelT > > mask
Options for writing an image to FITS.
Definition: fits.h:201
void writeKey(std::string const &key, char const *value, std::string const &comment)
Add a FITS header key to the bottom of the header.
Definition: fits.h:335
int getBitPix()
Return the cfitsio integer BITPIX code for the given data type.
void readTableScalar(std::size_t row, int col, T &value)
Read an array scalar from a binary table.
Definition: fits.h:574
MemFileManager(void *ptr, std::size_t len)
Construct a MemFileManager that references and does not manage external memory.
Definition: fits.h:126
ImageWriteOptions(ImageCompressionOptions const &compression_=ImageCompressionOptions(ImageCompressionOptions::NONE), ImageScalingOptions const &scaling_=ImageScalingOptions())
Construct with specific compression and scaling options.
Definition: fits.h:214
ImageWriteOptions(image::Mask< T > const &mask)
Construct with default options for masks.
Definition: fits.h:211
void writeColumnKey(std::string const &prefix, int n, char const *value, std::string const &comment)
Write a key of the form XXXXXnnn, where XXXXX is the prefix and nnn is a column number.
Definition: fits.h:361
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
FITS BITPIX header value by C++ type.
std::shared_ptr< daf::base::PropertyList > readMetadata(std::string const &fileName, int hdu=INT_MIN, bool strip=false)
Read FITS header.
Definition: Utils.h:64
void updateKey(std::string const &key, char const *value, std::string const &comment)
Set a FITS header key, editing if it already exists and appending it if not.
Definition: fits.h:317
void readImage(ndarray::Array< T, N, N > const &array, ndarray::Vector< int, N > const &offset)
Read an array from a FITS image.
Definition: fits.h:520
MemFileManager()
Construct a MemFileManager with no initial memory buffer.
Definition: fits.h:109
ndarray::Array< T const, N, N > const makeContiguousArray(ndarray::Array< T, N, C > const &array)
Construct a contiguous ndarray.
Definition: fits.h:189
lsst::daf::base::PropertySet PropertySet
Definition: Wcs.cc:55
An exception thrown when problems are found when reading or writing FITS files.
Definition: fits.h:34
ndarray::Vector< ndarray::Size, N > getImageShape()
Return the shape of the current (image) HDU.
Definition: fits.h:496
Options for tile compression of image pixels.
A base class for image defects.
Definition: cameraGeom.dox:3
void createImage(long x, long y)
Create a 2-d image with pixel type provided by the given explicit PixelT template parameter...
Definition: fits.h:444
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
void * getData() const
Return the buffer.
Definition: fits.h:171
Fits()
Default constructor; set all data members to 0.
Definition: fits.h:588
void createTable(lsst::daf::persistence::LogicalLocation const &location, std::shared_ptr< lsst::pex::policy::Policy const > const &policy, std::shared_ptr< lsst::daf::base::PropertySet const > const &properties)
Creates the table identified by calling getTableName() with the given policy and properties.
void reset(void *ptr, std::size_t len)
Set the internal memory buffer to an manually-managed external block.
Definition: fits.h:153
void updateColumnKey(std::string const &prefix, int n, char const *value)
Update a key of the form XXXXXnnn, where XXXXX is the prefix and nnn is a column number.
Definition: fits.h:352
Options for scaling image pixels.
double x
ImageWriteOptions(ImageScalingOptions const &scaling_)
Construct with specific scaling options.
Definition: fits.h:220
void updateColumnKey(std::string const &prefix, int n, char const *value, std::string const &comment)
Update a key of the form XXXXXnnn, where XXXXX is the prefix and nnn is a column number.
Definition: fits.h:347
ImageScalingOptions scaling
Options controlling scaling.
Definition: fits.h:203
std::size_t getLength() const
Return the buffer length.
Definition: fits.h:174
void setAllowImageCompression(bool allow)
An exception thrown when a FITS file has the wrong type.
Definition: fits.h:39
void reset()
Return the manager to the same state it would be if default-constructed.
void createImage(ndarray::Vector< ndarray::Size, N > const &shape)
Create an image with pixel type provided by the given explicit PixelT template parameter and shape de...
Definition: fits.h:426
MemFileManager & operator=(const MemFileManager &)=delete
bool getAllowImageCompression()
void writeImage(ndarray::Array< T const, N, C > const &array)
Write an ndarray::Array to a FITS image HDU.
Definition: fits.h:459
std::string makeErrorMessage(std::string const &fileName="", int status=0, std::string const &msg="")
Return an error message reflecting FITS I/O errors.
A class to represent a 2-dimensional array of pixels.
Definition: Image.h:68
Base class for polymorphic functors used to iterator over FITS key headers.
Definition: fits.h:47
void writeTableScalar(std::size_t row, int col, T value)
Write a scalar value to a binary table.
Definition: fits.h:562
ImageWriteOptions(image::Image< T > const &image)
Construct with default options for images.
Definition: fits.h:207