lsst.afw  14.0-34-g2d9284d60+1
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 
86 #define LSST_FITS_EXCEPT(type, fitsObj, ...) \
87  type(LSST_EXCEPT_HERE, lsst::afw::fits::makeErrorMessage((fitsObj).fptr, (fitsObj).status, __VA_ARGS__))
88 
92 #define LSST_FITS_CHECK_STATUS(fitsObj, ...) \
93  if ((fitsObj).status != 0) throw LSST_FITS_EXCEPT(lsst::afw::fits::FitsError, fitsObj, __VA_ARGS__)
94 
96 template <typename T>
97 int getBitPix();
98 
103 public:
110  MemFileManager() : _ptr(0), _len(0), _managed(true) {}
111 
118  explicit MemFileManager(std::size_t len) : _ptr(0), _len(0), _managed(true) { reset(len); }
119 
127  MemFileManager(void* ptr, std::size_t len) : _ptr(ptr), _len(len), _managed(false) {}
128 
134  void reset();
135 
144  void reset(std::size_t len);
145 
154  void reset(void* ptr, std::size_t len) {
155  reset();
156  _ptr = ptr;
157  _len = len;
158  _managed = false;
159  }
160 
162 
163  // No copying
164  MemFileManager(const MemFileManager&) = delete;
165  MemFileManager& operator=(const MemFileManager&) = delete;
166 
167  // No moving
168  MemFileManager(MemFileManager&&) = delete;
170 
172  void* getData() const { return _ptr; }
173 
175  std::size_t getLength() const { return _len; }
176 
177 private:
178  friend class Fits;
179 
180  void* _ptr;
181  std::size_t _len;
182  bool _managed;
183 };
184 
185 
189 template <typename T, int N, int C>
190 ndarray::Array<T const, N, N> const makeContiguousArray(ndarray::Array<T, N, C> const& array) {
191  ndarray::Array<T const, N, N> contiguous = ndarray::dynamic_dimension_cast<N>(array);
192  if (contiguous.empty()) contiguous = ndarray::copy(array);
193  return contiguous;
194 }
195 
196 
205 
207  template <typename T>
208  explicit ImageWriteOptions(image::Image<T> const& image) : compression(image) {}
209 
211  template <typename T>
212  explicit ImageWriteOptions(image::Mask<T> const& mask) : compression(mask) {}
213 
217  ImageScalingOptions const& scaling_=ImageScalingOptions())
218  : compression(compression_), scaling(scaling_) {}
219 
221  explicit ImageWriteOptions(ImageScalingOptions const& scaling_)
222  : compression(ImageCompressionOptions::NONE), scaling(scaling_) {}
223 
249 
262 };
263 
280 class Fits {
281  void createImageImpl(int bitpix, int nAxis, long const* nAxes);
282  template <typename T>
283  void writeImageImpl(T const* data, int nElements);
284  template <typename T>
285  void readImageImpl(int nAxis, T* data, long* begin, long* end, long* increment);
286  void getImageShapeImpl(int maxDim, long* nAxes);
287 
288 public:
290  AUTO_CLOSE = 0x01, // Close files when the Fits object goes out of scope if fptr != NULL
291  AUTO_CHECK = 0x02 // Call LSST_FITS_CHECK_STATUS after every cfitsio call
292  };
293 
295  std::string getFileName() const;
296 
298  int getHdu();
299 
309  void setHdu(int hdu, bool relative = false);
310 
312  int countHdus();
313 
315  template <typename T>
317  void updateKey(std::string const& key, T const& value, std::string const& comment);
318  void updateKey(std::string const& key, char const* value, std::string const& comment) {
319  updateKey(key, std::string(value), comment);
320  }
321  template <typename T>
322  void updateKey(std::string const& key, T const& value);
323  void updateKey(std::string const& key, char const* value) { updateKey(key, std::string(value)); }
325 
327 
334  template <typename T>
335  void writeKey(std::string const& key, T const& value, std::string const& comment);
336  void writeKey(std::string const& key, char const* value, std::string const& comment) {
337  writeKey(key, std::string(value), comment);
338  }
339  template <typename T>
340  void writeKey(std::string const& key, T const& value);
341  void writeKey(std::string const& key, char const* value) { writeKey(key, std::string(value)); }
343 
345  template <typename T>
347  void updateColumnKey(std::string const& prefix, int n, T const& value, std::string const& comment);
348  void updateColumnKey(std::string const& prefix, int n, char const* value, std::string const& comment) {
349  updateColumnKey(prefix, n, std::string(value), comment);
350  }
351  template <typename T>
352  void updateColumnKey(std::string const& prefix, int n, T const& value);
353  void updateColumnKey(std::string const& prefix, int n, char const* value) {
354  updateColumnKey(prefix, n, std::string(value));
355  }
357 
359  template <typename T>
361  void writeColumnKey(std::string const& prefix, int n, T const& value, std::string const& comment);
362  void writeColumnKey(std::string const& prefix, int n, char const* value, std::string const& comment) {
363  writeColumnKey(prefix, n, std::string(value), comment);
364  }
365  template <typename T>
366  void writeColumnKey(std::string const& prefix, int n, T const& value);
367  void writeColumnKey(std::string const& prefix, int n, char const* value) {
368  writeColumnKey(prefix, n, std::string(value));
369  }
371 
381  void writeMetadata(daf::base::PropertySet const& metadata);
382 
392  void readMetadata(daf::base::PropertySet& metadata, bool strip = false);
393 
395  template <typename T>
396  void readKey(std::string const& key, T& value);
397 
406  void forEachKey(HeaderIterationFunctor& functor);
407 
414  void createEmpty();
415 
426  template <typename PixelT, int N>
427  void createImage(ndarray::Vector<ndarray::Size, N> const& shape) {
428  ndarray::Vector<long, N> nAxes(shape.reverse());
429  createImageImpl(detail::Bitpix<PixelT>::value, N, nAxes.elems);
430  }
431 
432  template <int N>
433  void createImage(int bitpix, ndarray::Vector<ndarray::Size, N> const& shape) {
434  ndarray::Vector<long, N> nAxes(shape.reverse());
435  createImageImpl(bitpix, N, nAxes.elems);
436  }
437 
444  template <typename PixelT>
445  void createImage(long x, long y) {
446  long naxes[2] = {x, y};
447  createImageImpl(detail::Bitpix<PixelT>::value, 2, naxes);
448  }
449 
459  template <typename T, int N, int C>
460  void writeImage(ndarray::Array<T const, N, C> const& array) {
461  writeImageImpl(makeContiguousArray(array).getData(), array.getNumElements());
462  }
463 
476  template <typename T>
477  void writeImage(
478  image::ImageBase<T> const& image,
479  ImageWriteOptions const& options,
483  );
484 
486  int getImageDim();
487 
496  template <int N>
497  ndarray::Vector<ndarray::Size, N> getImageShape() {
498  ndarray::Vector<long, N> nAxes(1);
499  getImageShapeImpl(N, nAxes.elems);
500  ndarray::Vector<ndarray::Size, N> shape;
501  for (int i = 0; i < N; ++i) shape[i] = nAxes[N - i - 1];
502  return shape;
503  }
504 
511  template <typename T>
512  bool checkImageType();
513 
520  template <typename T, int N>
521  void readImage(ndarray::Array<T, N, N> const& array, ndarray::Vector<int, N> const& offset) {
522  ndarray::Vector<long, N> begin(offset.reverse());
523  ndarray::Vector<long, N> end(begin);
524  end += array.getShape().reverse();
525  ndarray::Vector<long, N> increment(1);
526  begin += increment; // first FITS pixel is 1, not 0
527  readImageImpl(N, array.getData(), begin.elems, end.elems, increment.elems);
528  }
529 
531  void createTable();
532 
539  template <typename T>
540  int addColumn(std::string const& ttype, int size, std::string const& comment);
541 
548  template <typename T>
549  int addColumn(std::string const& ttype, int size);
550 
552  std::size_t addRows(std::size_t nRows);
553 
555  std::size_t countRows();
556 
558  template <typename T>
559  void writeTableArray(std::size_t row, int col, int nElements, T const* value);
560 
562  template <typename T>
563  void writeTableScalar(std::size_t row, int col, T value) {
564  writeTableArray(row, col, 1, &value);
565  }
567  void writeTableScalar(std::size_t row, int col, std::string const& value);
568 
570  template <typename T>
571  void readTableArray(std::size_t row, int col, int nElements, T* value);
572 
574  template <typename T>
575  void readTableScalar(std::size_t row, int col, T& value) {
576  readTableArray(row, col, 1, &value);
577  }
578 
580  void readTableScalar(std::size_t row, int col, std::string& value, bool isVariableLength);
581 
583  long getTableArraySize(int col);
584 
586  long getTableArraySize(std::size_t row, int col);
587 
589  Fits() : fptr(0), status(0), behavior(0) {}
590 
592  Fits(std::string const& filename, std::string const& mode, int behavior);
593 
595  Fits(MemFileManager& manager, std::string const& mode, int behavior);
596 
598  void closeFile();
599 
603  void setImageCompression(ImageCompressionOptions const& options);
604 
606  ImageCompressionOptions getImageCompression();
607 
615  bool checkCompressedImagePhu();
616 
617  ~Fits() {
618  if ((fptr) && (behavior & AUTO_CLOSE)) closeFile();
619  }
620 
621  // No copying
622  Fits(const Fits&) = delete;
623  Fits& operator=(const Fits&) = delete;
624 
625  // No moving
626  Fits(Fits&&) = delete;
627  Fits& operator=(Fits&&) = delete;
628 
629  void* fptr; // the actual cfitsio fitsfile pointer; void to avoid including fitsio.h here.
630  int status; // the cfitsio status indicator that gets passed to every cfitsio call.
631  int behavior; // bitwise OR of BehaviorFlags
632 };
633 
645  bool strip = false);
657  bool strip = false);
668 
669 
670 void setAllowImageCompression(bool allow);
672 
673 }
674 }
675 }
676 
677 #endif // !LSST_AFW_fits_h_INCLUDED
void createImage(int bitpix, ndarray::Vector< ndarray::Size, N > const &shape)
Definition: fits.h:433
void writeKey(std::string const &key, char const *value)
Add a FITS header key to the bottom of the header.
Definition: fits.h:341
MemFileManager(std::size_t len)
Construct a MemFileManager with (len) bytes of initial memory.
Definition: fits.h:118
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:323
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:367
ImageCompressionOptions compression
Options controlling compression.
Definition: fits.h:203
afw::table::Key< afw::table::Array< MaskPixelT > > mask
Options for writing an image to FITS.
Definition: fits.h:202
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:336
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:575
MemFileManager(void *ptr, std::size_t len)
Construct a MemFileManager that references and does not manage external memory.
Definition: fits.h:127
ImageWriteOptions(ImageCompressionOptions const &compression_=ImageCompressionOptions(ImageCompressionOptions::NONE), ImageScalingOptions const &scaling_=ImageScalingOptions())
Construct with specific compression and scaling options.
Definition: fits.h:215
ImageWriteOptions(image::Mask< T > const &mask)
Construct with default options for masks.
Definition: fits.h:212
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:362
tuple options
A simple struct that combines the two arguments that must be passed to most cfitsio routines and cont...
Definition: fits.h:280
The base class for all image classed (Image, Mask, MaskedImage, ...)
Definition: ImageBase.h:106
FITS BITPIX header value by C++ type.
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:318
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:521
MemFileManager()
Construct a MemFileManager with no initial memory buffer.
Definition: fits.h:110
ndarray::Array< T const, N, N > const makeContiguousArray(ndarray::Array< T, N, C > const &array)
Construct a contiguous ndarray.
Definition: fits.h:190
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:497
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:445
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:102
validate
void * getData() const
Return the buffer.
Definition: fits.h:172
Fits()
Default constructor; set all data members to 0.
Definition: fits.h:589
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.
Definition: Utils.cc:243
void reset(void *ptr, std::size_t len)
Set the internal memory buffer to an manually-managed external block.
Definition: fits.h:154
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:353
Options for scaling image pixels.
double x
ImageWriteOptions(ImageScalingOptions const &scaling_)
Construct with specific scaling options.
Definition: fits.h:221
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:348
ImageScalingOptions scaling
Options controlling scaling.
Definition: fits.h:204
std::size_t getLength() const
Return the buffer length.
Definition: fits.h:175
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:427
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:460
#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:563
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:208