lsst.afw  13.0-73-gb2a4e38
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
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"
25 
26 namespace lsst {
27 namespace afw {
28 namespace fits {
29 
33 LSST_EXCEPTION_TYPE(FitsError, lsst::pex::exceptions::IoError, lsst::afw::fits::FitsError)
34 
35 
38 LSST_EXCEPTION_TYPE(FitsTypeError, lsst::afw::fits::FitsError, lsst::afw::fits::FitsTypeError)
39 
47 public:
48  virtual void operator()(std::string const& key, std::string const& value, std::string const& comment) = 0;
49 
51 };
52 
61 std::string makeErrorMessage(std::string const& fileName = "", int status = 0, std::string const& msg = "");
62 inline std::string makeErrorMessage(std::string const& fileName, int status, boost::format const& msg) {
63  return makeErrorMessage(fileName, status, msg.str());
64 }
65 
75 std::string makeErrorMessage(void* fptr, int status = 0, std::string const& msg = "");
76 inline std::string makeErrorMessage(void* fptr, int status, boost::format const& msg) {
77  return makeErrorMessage(fptr, status, msg.str());
78 }
79 
84 #define LSST_FITS_EXCEPT(type, fitsObj, ...) \
85  type(LSST_EXCEPT_HERE, lsst::afw::fits::makeErrorMessage((fitsObj).fptr, (fitsObj).status, __VA_ARGS__))
86 
90 #define LSST_FITS_CHECK_STATUS(fitsObj, ...) \
91  if ((fitsObj).status != 0) throw LSST_FITS_EXCEPT(lsst::afw::fits::FitsError, fitsObj, __VA_ARGS__)
92 
94 template <typename T>
95 int getBitPix();
96 
101 public:
108  MemFileManager() : _ptr(0), _len(0), _managed(true) {}
109 
116  explicit MemFileManager(std::size_t len) : _ptr(0), _len(0), _managed(true) { reset(len); }
117 
125  MemFileManager(void* ptr, std::size_t len) : _ptr(ptr), _len(len), _managed(false) {}
126 
132  void reset();
133 
142  void reset(std::size_t len);
143 
152  void reset(void* ptr, std::size_t len) {
153  reset();
154  _ptr = ptr;
155  _len = len;
156  _managed = false;
157  }
158 
160 
161  // No copying
162  MemFileManager(const MemFileManager&) = delete;
163  MemFileManager& operator=(const MemFileManager&) = delete;
164 
165  // No moving
166  MemFileManager(MemFileManager&&) = delete;
168 
170  void* getData() const { return _ptr; }
171 
173  std::size_t getLength() const { return _len; }
174 
175 private:
176  friend class Fits;
177 
178  void* _ptr;
179  std::size_t _len;
180  bool _managed;
181 };
182 
199 class Fits {
200  template <typename T>
201  void createImageImpl(int nAxis, long* nAxes);
202  template <typename T>
203  void writeImageImpl(T const* data, int nElements);
204  template <typename T>
205  void readImageImpl(int nAxis, T* data, long* begin, long* end, long* increment);
206  void getImageShapeImpl(int maxDim, long* nAxes);
207 
208 public:
210  AUTO_CLOSE = 0x01, // Close files when the Fits object goes out of scope if fptr != NULL
211  AUTO_CHECK = 0x02 // Call LSST_FITS_CHECK_STATUS after every cfitsio call
212  };
213 
215  std::string getFileName() const;
216 
218  int getHdu();
219 
229  void setHdu(int hdu, bool relative = false);
230 
232  int countHdus();
233 
235  template <typename T>
237  void updateKey(std::string const& key, T const& value, std::string const& comment);
238  void updateKey(std::string const& key, char const* value, std::string const& comment) {
239  updateKey(key, std::string(value), comment);
240  }
241  template <typename T>
242  void updateKey(std::string const& key, T const& value);
243  void updateKey(std::string const& key, char const* value) { updateKey(key, std::string(value)); }
245 
247 
254  template <typename T>
255  void writeKey(std::string const& key, T const& value, std::string const& comment);
256  void writeKey(std::string const& key, char const* value, std::string const& comment) {
257  writeKey(key, std::string(value), comment);
258  }
259  template <typename T>
260  void writeKey(std::string const& key, T const& value);
261  void writeKey(std::string const& key, char const* value) { writeKey(key, std::string(value)); }
263 
265  template <typename T>
267  void updateColumnKey(std::string const& prefix, int n, T const& value, std::string const& comment);
268  void updateColumnKey(std::string const& prefix, int n, char const* value, std::string const& comment) {
269  updateColumnKey(prefix, n, std::string(value), comment);
270  }
271  template <typename T>
272  void updateColumnKey(std::string const& prefix, int n, T const& value);
273  void updateColumnKey(std::string const& prefix, int n, char const* value) {
274  updateColumnKey(prefix, n, std::string(value));
275  }
277 
279  template <typename T>
281  void writeColumnKey(std::string const& prefix, int n, T const& value, std::string const& comment);
282  void writeColumnKey(std::string const& prefix, int n, char const* value, std::string const& comment) {
283  writeColumnKey(prefix, n, std::string(value), comment);
284  }
285  template <typename T>
286  void writeColumnKey(std::string const& prefix, int n, T const& value);
287  void writeColumnKey(std::string const& prefix, int n, char const* value) {
288  writeColumnKey(prefix, n, std::string(value));
289  }
291 
301  void writeMetadata(daf::base::PropertySet const& metadata);
302 
312  void readMetadata(daf::base::PropertySet& metadata, bool strip = false);
313 
315  template <typename T>
316  void readKey(std::string const& key, T& value);
317 
326  void forEachKey(HeaderIterationFunctor& functor);
327 
334  void createEmpty();
335 
346  template <typename PixelT, int N>
347  void createImage(ndarray::Vector<ndarray::Size, N> const& shape) {
348  ndarray::Vector<long, N> nAxes(shape.reverse());
349  createImageImpl<PixelT>(N, nAxes.elems);
350  }
351 
358  template <typename PixelT>
359  void createImage(long x, long y) {
360  long naxes[2] = {x, y};
361  createImageImpl<PixelT>(2, naxes);
362  }
363 
371  template <typename T, int N, int C>
372  void writeImage(ndarray::Array<T const, N, C> const& array) {
373  ndarray::Array<T const, N, N> contiguous = ndarray::dynamic_dimension_cast<N>(array);
374  if (contiguous.empty()) contiguous = ndarray::copy(array);
375  writeImageImpl(contiguous.getData(), contiguous.getNumElements());
376  }
377 
379  int getImageDim();
380 
389  template <int N>
390  ndarray::Vector<ndarray::Size, N> getImageShape() {
391  ndarray::Vector<long, N> nAxes(1);
392  getImageShapeImpl(N, nAxes.elems);
393  ndarray::Vector<ndarray::Size, N> shape;
394  for (int i = 0; i < N; ++i) shape[i] = nAxes[N - i - 1];
395  return shape;
396  }
397 
404  template <typename T>
405  bool checkImageType();
406 
413  template <typename T, int N>
414  void readImage(ndarray::Array<T, N, N> const& array, ndarray::Vector<int, N> const& offset) {
415  ndarray::Vector<long, N> begin(offset.reverse());
416  ndarray::Vector<long, N> end(begin);
417  end += array.getShape().reverse();
418  ndarray::Vector<long, N> increment(1);
419  begin += increment; // first FITS pixel is 1, not 0
420  readImageImpl(N, array.getData(), begin.elems, end.elems, increment.elems);
421  }
422 
424  void createTable();
425 
432  template <typename T>
433  int addColumn(std::string const& ttype, int size, std::string const& comment);
434 
441  template <typename T>
442  int addColumn(std::string const& ttype, int size);
443 
445  std::size_t addRows(std::size_t nRows);
446 
448  std::size_t countRows();
449 
451  template <typename T>
452  void writeTableArray(std::size_t row, int col, int nElements, T const* value);
453 
455  template <typename T>
456  void writeTableScalar(std::size_t row, int col, T value) {
457  writeTableArray(row, col, 1, &value);
458  }
460  void writeTableScalar(std::size_t row, int col, std::string const& value);
461 
463  template <typename T>
464  void readTableArray(std::size_t row, int col, int nElements, T* value);
465 
467  template <typename T>
468  void readTableScalar(std::size_t row, int col, T& value) {
469  readTableArray(row, col, 1, &value);
470  }
471 
473  void readTableScalar(std::size_t row, int col, std::string& value, bool isVariableLength);
474 
476  long getTableArraySize(int col);
477 
479  long getTableArraySize(std::size_t row, int col);
480 
482  Fits() : fptr(0), status(0), behavior(0) {}
483 
485  Fits(std::string const& filename, std::string const& mode, int behavior);
486 
488  Fits(MemFileManager& manager, std::string const& mode, int behavior);
489 
491  void closeFile();
492 
493  ~Fits() {
494  if ((fptr) && (behavior & AUTO_CLOSE)) closeFile();
495  }
496 
497  // No copying
498  Fits(const Fits&) = delete;
499  Fits& operator=(const Fits&) = delete;
500 
501  // No moving
502  Fits(Fits&&) = delete;
503  Fits& operator=(Fits&&) = delete;
504 
505  void* fptr; // the actual cfitsio fitsfile pointer; void to avoid including fitsio.h here.
506  int status; // the cfitsio status indicator that gets passed to every cfitsio call.
507  int behavior; // bitwise OR of BehaviorFlags
508 };
509 
520 std::shared_ptr<daf::base::PropertyList> readMetadata(std::string const& fileName, int hdu = INT_MIN,
521  bool strip = false);
532 std::shared_ptr<daf::base::PropertyList> readMetadata(fits::MemFileManager& manager, int hdu = INT_MIN,
533  bool strip = false);
543 std::shared_ptr<daf::base::PropertyList> readMetadata(fits::Fits& fitsfile, bool strip = false);
544 }
545 }
546 }
547 
548 #endif // !LSST_AFW_fits_h_INCLUDED
int getImageDim()
Return the number of dimensions in the current HDU.
std::size_t countRows()
Return the number of row in a table.
void writeKey(std::string const &key, char const *value)
Add a FITS header key to the bottom of the header.
Definition: fits.h:261
MemFileManager(std::size_t len)
Construct a MemFileManager with (len) bytes of initial memory.
Definition: fits.h:116
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:243
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:287
void forEachKey(HeaderIterationFunctor &functor)
Call a polymorphic functor for every key in the header.
void writeMetadata(daf::base::PropertySet const &metadata)
Read a FITS header into a PropertySet or PropertyList.
void readKey(std::string const &key, T &value)
Read a FITS header key into the given reference.
void updateColumnKey(std::string const &prefix, int n, T const &value, std::string const &comment)
Update a key of the form XXXXXnnn, where XXXXX is the prefix and nnn is a column number.
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:256
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:468
MemFileManager(void *ptr, std::size_t len)
Construct a MemFileManager that references and does not manage external memory.
Definition: fits.h:125
bool checkImageType()
Return true if the current HDU has the given pixel type.
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:282
void writeColumnKey(std::string const &prefix, int n, T const &value, std::string const &comment)
Write a key of the form XXXXXnnn, where XXXXX is the prefix and nnn is a column number.
A simple struct that combines the two arguments that must be passed to most cfitsio routines and cont...
Definition: fits.h:199
long getTableArraySize(int col)
Return the size of an array column.
void closeFile()
Close a FITS file.
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:238
void createEmpty()
Create an empty image HDU with NAXIS=0 at the end of the file.
std::size_t getLength() const
Return the buffer length.
Definition: fits.h:173
void updateKey(std::string const &key, T const &value, std::string const &comment)
Set a FITS header key, editing if it already exists and appending it if not.
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:414
MemFileManager()
Construct a MemFileManager with no initial memory buffer.
Definition: fits.h:108
An exception thrown when problems are found when reading or writing FITS files.
Definition: fits.h:33
ndarray::Vector< ndarray::Size, N > getImageShape()
Return the shape of the current (image) HDU.
Definition: fits.h:390
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:359
Lifetime-management for memory that goes into FITS memory files.
Definition: fits.h:100
std::size_t addRows(std::size_t nRows)
Append rows to a table, and return the index of the first new row.
Fits()
Default constructor; set all data members to 0.
Definition: fits.h:482
void reset(void *ptr, std::size_t len)
Set the internal memory buffer to an manually-managed external block.
Definition: fits.h:152
void createTable()
Create a new binary table extension.
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:273
double x
void setHdu(int hdu, bool relative=false)
Set the current HDU.
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:268
std::string getFileName() const
Return the file name associated with the FITS object or &quot;&lt;unknown&gt;&quot; if there is none.
lsst::daf::base::PropertySet PropertySet
Definition: Wcs.cc:55
void writeTableArray(std::size_t row, int col, int nElements, T const *value)
Write an array value to a binary table.
An exception thrown when a FITS file has the wrong type.
Definition: fits.h:38
void reset()
Return the manager to the same state it would be if default-constructed.
void readTableArray(std::size_t row, int col, int nElements, T *value)
Read an array value from a binary table.
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:347
void writeKey(std::string const &key, T const &value, std::string const &comment)
Add a FITS header key to the bottom of the header.
MemFileManager & operator=(const MemFileManager &)=delete
Fits & operator=(const Fits &)=delete
int getHdu()
Return the current HDU (0-indexed; 0 is the Primary HDU).
void writeImage(ndarray::Array< T const, N, C > const &array)
Write an ndarray::Array to a FITS image HDU.
Definition: fits.h:372
int addColumn(std::string const &ttype, int size, std::string const &comment)
Add a column to a table.
std::string makeErrorMessage(std::string const &fileName="", int status=0, std::string const &msg="")
Return an error message reflecting FITS I/O errors.
void * getData() const
Return the buffer.
Definition: fits.h:170
Base class for polymorphic functors used to iterator over FITS key headers.
Definition: fits.h:46
void writeTableScalar(std::size_t row, int col, T value)
Write a scalar value to a binary table.
Definition: fits.h:456
void readMetadata(daf::base::PropertySet &metadata, bool strip=false)
Read a FITS header into a PropertySet or PropertyList.
int countHdus()
Return the number of HDUs in the file.