lsst.afw  14.0-58-g91bfccb15
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 #include "lsst/afw/fitsDefaults.h"
27 
28 namespace lsst {
29 namespace afw {
30 namespace fits {
31 
36 
37 
40 LSST_EXCEPTION_TYPE(FitsTypeError, lsst::afw::fits::FitsError, lsst::afw::fits::FitsTypeError)
41 
49 public:
50  virtual void operator()(std::string const& key, std::string const& value, std::string const& comment) = 0;
51 
53 };
54 
63 std::string makeErrorMessage(std::string const& fileName = "", int status = 0, std::string const& msg = "");
64 inline std::string makeErrorMessage(std::string const& fileName, int status, boost::format const& msg) {
65  return makeErrorMessage(fileName, status, msg.str());
66 }
67 
77 std::string makeErrorMessage(void* fptr, int status = 0, std::string const& msg = "");
78 inline std::string makeErrorMessage(void* fptr, int status, boost::format const& msg) {
79  return makeErrorMessage(fptr, status, msg.str());
80 }
81 
98  std::set<std::string> const& excludeNames = {});
99 
104 #define LSST_FITS_EXCEPT(type, fitsObj, ...) \
105  type(LSST_EXCEPT_HERE, lsst::afw::fits::makeErrorMessage((fitsObj).fptr, (fitsObj).status, __VA_ARGS__))
106 
110 #define LSST_FITS_CHECK_STATUS(fitsObj, ...) \
111  if ((fitsObj).status != 0) throw LSST_FITS_EXCEPT(lsst::afw::fits::FitsError, fitsObj, __VA_ARGS__)
112 
114 template <typename T>
115 int getBitPix();
116 
121 public:
128  MemFileManager() : _ptr(0), _len(0), _managed(true) {}
129 
136  explicit MemFileManager(std::size_t len) : _ptr(0), _len(0), _managed(true) { reset(len); }
137 
145  MemFileManager(void* ptr, std::size_t len) : _ptr(ptr), _len(len), _managed(false) {}
146 
152  void reset();
153 
162  void reset(std::size_t len);
163 
172  void reset(void* ptr, std::size_t len) {
173  reset();
174  _ptr = ptr;
175  _len = len;
176  _managed = false;
177  }
178 
180 
181  // No copying
182  MemFileManager(const MemFileManager&) = delete;
183  MemFileManager& operator=(const MemFileManager&) = delete;
184 
185  // No moving
186  MemFileManager(MemFileManager&&) = delete;
188 
190  void* getData() const { return _ptr; }
191 
193  std::size_t getLength() const { return _len; }
194 
195 private:
196  friend class Fits;
197 
198  void* _ptr;
199  std::size_t _len;
200  bool _managed;
201 };
202 
203 
207 template <typename T, int N, int C>
208 ndarray::Array<T const, N, N> const makeContiguousArray(ndarray::Array<T, N, C> const& array) {
209  ndarray::Array<T const, N, N> contiguous = ndarray::dynamic_dimension_cast<N>(array);
210  if (contiguous.empty()) contiguous = ndarray::copy(array);
211  return contiguous;
212 }
213 
214 
223 
225  template <typename T>
226  explicit ImageWriteOptions(image::Image<T> const& image) : compression(image) {}
227 
229  template <typename T>
230  explicit ImageWriteOptions(image::Mask<T> const& mask) : compression(mask) {}
231 
235  ImageScalingOptions const& scaling_=ImageScalingOptions())
236  : compression(compression_), scaling(scaling_) {}
237 
239  explicit ImageWriteOptions(ImageScalingOptions const& scaling_)
240  : compression(ImageCompressionOptions::NONE), scaling(scaling_) {}
241 
267 
280 };
281 
298 class Fits {
299  void createImageImpl(int bitpix, int nAxis, long const* nAxes);
300  template <typename T>
301  void writeImageImpl(T const* data, int nElements);
302  template <typename T>
303  void readImageImpl(int nAxis, T* data, long* begin, long* end, long* increment);
304  void getImageShapeImpl(int maxDim, long* nAxes);
305 
306 public:
308  AUTO_CLOSE = 0x01, // Close files when the Fits object goes out of scope if fptr != NULL
309  AUTO_CHECK = 0x02 // Call LSST_FITS_CHECK_STATUS after every cfitsio call
310  };
311 
313  std::string getFileName() const;
314 
316  int getHdu();
317 
327  void setHdu(int hdu, bool relative = false);
328 
330  int countHdus();
331 
333  template <typename T>
335  void updateKey(std::string const& key, T const& value, std::string const& comment);
336  void updateKey(std::string const& key, char const* value, std::string const& comment) {
337  updateKey(key, std::string(value), comment);
338  }
339  template <typename T>
340  void updateKey(std::string const& key, T const& value);
341  void updateKey(std::string const& key, char const* value) { updateKey(key, std::string(value)); }
343 
345 
352  template <typename T>
353  void writeKey(std::string const& key, T const& value, std::string const& comment);
354  void writeKey(std::string const& key, char const* value, std::string const& comment) {
355  writeKey(key, std::string(value), comment);
356  }
357  template <typename T>
358  void writeKey(std::string const& key, T const& value);
359  void writeKey(std::string const& key, char const* value) { writeKey(key, std::string(value)); }
361 
363  template <typename T>
365  void updateColumnKey(std::string const& prefix, int n, T const& value, std::string const& comment);
366  void updateColumnKey(std::string const& prefix, int n, char const* value, std::string const& comment) {
367  updateColumnKey(prefix, n, std::string(value), comment);
368  }
369  template <typename T>
370  void updateColumnKey(std::string const& prefix, int n, T const& value);
371  void updateColumnKey(std::string const& prefix, int n, char const* value) {
372  updateColumnKey(prefix, n, std::string(value));
373  }
375 
377  template <typename T>
379  void writeColumnKey(std::string const& prefix, int n, T const& value, std::string const& comment);
380  void writeColumnKey(std::string const& prefix, int n, char const* value, std::string const& comment) {
381  writeColumnKey(prefix, n, std::string(value), comment);
382  }
383  template <typename T>
384  void writeColumnKey(std::string const& prefix, int n, T const& value);
385  void writeColumnKey(std::string const& prefix, int n, char const* value) {
386  writeColumnKey(prefix, n, std::string(value));
387  }
389 
399  void writeMetadata(daf::base::PropertySet const& metadata);
400 
410  void readMetadata(daf::base::PropertySet& metadata, bool strip = false);
411 
413  template <typename T>
414  void readKey(std::string const& key, T& value);
415 
424  void forEachKey(HeaderIterationFunctor& functor);
425 
432  void createEmpty();
433 
444  template <typename PixelT, int N>
445  void createImage(ndarray::Vector<ndarray::Size, N> const& shape) {
446  ndarray::Vector<long, N> nAxes(shape.reverse());
447  createImageImpl(detail::Bitpix<PixelT>::value, N, nAxes.elems);
448  }
449 
450  template <int N>
451  void createImage(int bitpix, ndarray::Vector<ndarray::Size, N> const& shape) {
452  ndarray::Vector<long, N> nAxes(shape.reverse());
453  createImageImpl(bitpix, N, nAxes.elems);
454  }
455 
462  template <typename PixelT>
463  void createImage(long x, long y) {
464  long naxes[2] = {x, y};
465  createImageImpl(detail::Bitpix<PixelT>::value, 2, naxes);
466  }
467 
477  template <typename T, int N, int C>
478  void writeImage(ndarray::Array<T const, N, C> const& array) {
479  writeImageImpl(makeContiguousArray(array).getData(), array.getNumElements());
480  }
481 
494  template <typename T>
495  void writeImage(
496  image::ImageBase<T> const& image,
497  ImageWriteOptions const& options,
501  );
502 
504  int getImageDim();
505 
514  template <int N>
515  ndarray::Vector<ndarray::Size, N> getImageShape() {
516  ndarray::Vector<long, N> nAxes(1);
517  getImageShapeImpl(N, nAxes.elems);
518  ndarray::Vector<ndarray::Size, N> shape;
519  for (int i = 0; i < N; ++i) shape[i] = nAxes[N - i - 1];
520  return shape;
521  }
522 
529  template <typename T>
530  bool checkImageType();
531 
538  template <typename T, int N>
539  void readImage(ndarray::Array<T, N, N> const& array, ndarray::Vector<int, N> const& offset) {
540  ndarray::Vector<long, N> begin(offset.reverse());
541  ndarray::Vector<long, N> end(begin);
542  end += array.getShape().reverse();
543  ndarray::Vector<long, N> increment(1);
544  begin += increment; // first FITS pixel is 1, not 0
545  readImageImpl(N, array.getData(), begin.elems, end.elems, increment.elems);
546  }
547 
549  void createTable();
550 
557  template <typename T>
558  int addColumn(std::string const& ttype, int size, std::string const& comment);
559 
566  template <typename T>
567  int addColumn(std::string const& ttype, int size);
568 
570  std::size_t addRows(std::size_t nRows);
571 
573  std::size_t countRows();
574 
576  template <typename T>
577  void writeTableArray(std::size_t row, int col, int nElements, T const* value);
578 
580  template <typename T>
581  void writeTableScalar(std::size_t row, int col, T value) {
582  writeTableArray(row, col, 1, &value);
583  }
585  void writeTableScalar(std::size_t row, int col, std::string const& value);
586 
588  template <typename T>
589  void readTableArray(std::size_t row, int col, int nElements, T* value);
590 
592  template <typename T>
593  void readTableScalar(std::size_t row, int col, T& value) {
594  readTableArray(row, col, 1, &value);
595  }
596 
598  void readTableScalar(std::size_t row, int col, std::string& value, bool isVariableLength);
599 
601  long getTableArraySize(int col);
602 
604  long getTableArraySize(std::size_t row, int col);
605 
607  Fits() : fptr(0), status(0), behavior(0) {}
608 
610  Fits(std::string const& filename, std::string const& mode, int behavior);
611 
613  Fits(MemFileManager& manager, std::string const& mode, int behavior);
614 
616  void closeFile();
617 
621  void setImageCompression(ImageCompressionOptions const& options);
622 
624  ImageCompressionOptions getImageCompression();
625 
633  bool checkCompressedImagePhu();
634 
635  ~Fits() {
636  if ((fptr) && (behavior & AUTO_CLOSE)) closeFile();
637  }
638 
639  // No copying
640  Fits(const Fits&) = delete;
641  Fits& operator=(const Fits&) = delete;
642 
643  // No moving
644  Fits(Fits&&) = delete;
645  Fits& operator=(Fits&&) = delete;
646 
647  void* fptr; // the actual cfitsio fitsfile pointer; void to avoid including fitsio.h here.
648  int status; // the cfitsio status indicator that gets passed to every cfitsio call.
649  int behavior; // bitwise OR of BehaviorFlags
650 };
651 
672 
684  bool strip = false);
696  bool strip = false);
707 
708 
709 void setAllowImageCompression(bool allow);
711 
712 }
713 }
714 }
715 
716 #endif // !LSST_AFW_fits_h_INCLUDED
void createImage(int bitpix, ndarray::Vector< ndarray::Size, N > const &shape)
Definition: fits.h:451
void writeKey(std::string const &key, char const *value)
Add a FITS header key to the bottom of the header.
Definition: fits.h:359
MemFileManager(std::size_t len)
Construct a MemFileManager with (len) bytes of initial memory.
Definition: fits.h:136
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:341
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:385
ImageCompressionOptions compression
Options controlling compression.
Definition: fits.h:221
afw::table::Key< afw::table::Array< MaskPixelT > > mask
Options for writing an image to FITS.
Definition: fits.h:220
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:354
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:593
MemFileManager(void *ptr, std::size_t len)
Construct a MemFileManager that references and does not manage external memory.
Definition: fits.h:145
ImageWriteOptions(ImageCompressionOptions const &compression_=ImageCompressionOptions(ImageCompressionOptions::NONE), ImageScalingOptions const &scaling_=ImageScalingOptions())
Construct with specific compression and scaling options.
Definition: fits.h:233
ImageWriteOptions(image::Mask< T > const &mask)
Construct with default options for masks.
Definition: fits.h:230
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:380
tuple options
A simple struct that combines the two arguments that must be passed to most cfitsio routines and cont...
Definition: fits.h:298
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 > combineMetadata(std::shared_ptr< const daf::base::PropertyList > first, std::shared_ptr< const daf::base::PropertyList > second)
Combine two sets of metadata in a FITS-appropriate fashion.
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:336
STL class.
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:539
MemFileManager()
Construct a MemFileManager with no initial memory buffer.
Definition: fits.h:128
ndarray::Array< T const, N, N > const makeContiguousArray(ndarray::Array< T, N, C > const &array)
Construct a contiguous ndarray.
Definition: fits.h:208
An exception thrown when problems are found when reading or writing FITS files.
Definition: fits.h:35
std::shared_ptr< daf::base::PropertyList > readMetadata(std::string const &fileName, int hdu=DEFAULT_HDU, bool strip=false)
Read FITS header.
Definition: Utils.h:64
ndarray::Vector< ndarray::Size, N > getImageShape()
Return the shape of the current (image) HDU.
Definition: fits.h:515
Options for tile compression of image pixels.
A base class for image defects.
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:463
int end
Represent a 2-dimensional array of bitmask pixels.
Definition: Mask.h:84
Lifetime-management for memory that goes into FITS memory files.
Definition: fits.h:120
validate
void * getData() const
Return the buffer.
Definition: fits.h:190
Fits()
Default constructor; set all data members to 0.
Definition: fits.h:607
void reset(void *ptr, std::size_t len)
Set the internal memory buffer to an manually-managed external block.
Definition: fits.h:172
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:371
Options for scaling image pixels.
double x
ImageWriteOptions(ImageScalingOptions const &scaling_)
Construct with specific scaling options.
Definition: fits.h:239
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:366
STL class.
ImageScalingOptions scaling
Options controlling scaling.
Definition: fits.h:222
std::size_t getLength() const
Return the buffer length.
Definition: fits.h:193
void setAllowImageCompression(bool allow)
An exception thrown when a FITS file has the wrong type.
Definition: fits.h:40
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:445
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:478
#define LSST_EXCEPTION_TYPE(t, b, c)
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:69
Base class for polymorphic functors used to iterator over FITS key headers.
Definition: fits.h:48
void writeTableScalar(std::size_t row, int col, T value)
Write a scalar value to a binary table.
Definition: fits.h:581
std::string makeLimitedFitsHeader(lsst::daf::base::PropertySet const &metadata, std::set< std::string > const &excludeNames={})
Format a PropertySet into an FITS header string in a simplistic fashion.
const int DEFAULT_HDU
Specify that the default HDU should be read.
Definition: fitsDefaults.h:18
ImageWriteOptions(image::Image< T > const &image)
Construct with default options for images.
Definition: fits.h:226