lsst.afw  15.0-18-g5f205baaa
fits.cc
Go to the documentation of this file.
1 // -*- lsst-c++ -*-
2 
3 #include <cstdint>
4 #include <cstdio>
5 #include <complex>
6 #include <cmath>
7 #include <sstream>
8 #include <unordered_set>
9 #include <unordered_map>
10 
11 #include "fitsio.h"
12 extern "C" {
13 #include "fitsio2.h"
14 }
15 
16 #include "boost/regex.hpp"
17 #include "boost/filesystem.hpp"
18 #include "boost/preprocessor/seq/for_each.hpp"
19 #include "boost/format.hpp"
20 
21 #include "lsst/pex/exceptions.h"
22 #include "lsst/log/Log.h"
23 #include "lsst/afw/fits.h"
24 #include "lsst/afw/geom/Angle.h"
25 #include "lsst/afw/geom/wcsUtils.h"
27 
28 namespace lsst {
29 namespace afw {
30 namespace fits {
31 
32 // ----------------------------------------------------------------------------------------------------------
33 // ---- Miscellaneous utilities -----------------------------------------------------------------------------
34 // ----------------------------------------------------------------------------------------------------------
35 
36 namespace {
37 
38 /*
39  * Format a PropertySet into a FITS header string using simplifying assumptions.
40  *
41  * See @ref makeLimitedFitsHeader for details.
42  *
43  * @param[in] paramNames Names of properties to format
44  * @param[in] metadata Metadata to format
45  * @return a FITS header string (exactly 80 characters per entry, no line terminators)
46  */
47 std::string makeLimitedFitsHeaderImpl(std::vector<std::string> const &paramNames,
48  daf::base::PropertySet const &metadata) {
50  for (auto const &fullName : paramNames) {
51  std::size_t lastPeriod = fullName.rfind(char('.'));
52  auto name = (lastPeriod == std::string::npos) ? fullName : fullName.substr(lastPeriod + 1);
53  std::type_info const &type = metadata.typeOf(name);
54 
55  std::string out = "";
56  out.reserve(80);
57  if (name.size() > 8) {
58  continue; // The name is too long for a FITS keyword; skip this item
59  }
60  out = (boost::format("%-8s= ") % name).str();
61 
62  if (type == typeid(bool)) {
63  out += metadata.get<bool>(name) ? "1" : "0";
64  } else if (type == typeid(std::uint8_t)) {
65  out += (boost::format("%20d") % static_cast<int>(metadata.get<std::uint8_t>(name))).str();
66  } else if (type == typeid(int)) {
67  out += (boost::format("%20d") % metadata.get<int>(name)).str();
68  } else if (type == typeid(double)) {
69  // use G because FITS wants uppercase E for exponents
70  out += (boost::format("%20.15G") % metadata.get<double>(name)).str();
71  } else if (type == typeid(float)) {
72  out += (boost::format("%20.15G") % metadata.get<float>(name)).str();
73  } else if (type == typeid(std::string)) {
74  out += "'" + metadata.get<std::string>(name) + "'";
75  if (out.size() > 80) {
76  continue; // Formatted data is too long; skip this item
77  }
78  }
79 
80  int const len = out.size();
81  if (len < 80) {
82  out += std::string(80 - len, ' ');
83  } else if (len > 80) {
84  // non-string item has a formatted value that is too long; this should never happen
85  throw LSST_EXCEPT(pex::exceptions::LogicError,
86  "Formatted data too long: " + std::to_string(len) + " > 80: \"" + out + "\"");
87  }
88 
89  result << out;
90  }
91 
92  return result.str();
93 }
94 
103 class StringStartSet {
104  public:
106  StringStartSet(std::initializer_list<std::string> const& input) : _minSize(-1) {
107  for (auto const& word : input) {
108  std::size_t const size = word.size();
109  if (size < _minSize) {
110  _minSize = size;
111  }
112  }
113  for (auto const& word : input) {
114  std::string const start = startString(word);
115  assert(_words.count(start) == 0); // This should be the only word that starts this way
116  _words[start] = word;
117  }
118  }
119 
121  bool matches(std::string const& key) const {
122  auto const iter = _words.find(startString(key));
123  if (iter == _words.end()) {
124  return false;
125  }
126  // Check that the full word matches too
127  std::string const& word = iter->second;
128  return key.compare(0, word.size(), word) == 0;
129  }
130 
131  private:
133 
135  std::string startString(std::string const& word) const { return word.substr(0, _minSize); }
136 
137  std::size_t _minSize; // Minimum length of provided words
138  Map _words; // Start of words --> full word
139 };
140 
146 static std::unordered_set<std::string> const ignoreKeys = {
147  // FITS core keywords
148  "SIMPLE", "BITPIX", "NAXIS", "EXTEND", "GCOUNT", "PCOUNT", "XTENSION", "TFIELDS", "BSCALE", "BZERO",
149  // FITS compression keywords
150  "ZBITPIX", "ZIMAGE", "ZCMPTYPE", "ZSIMPLE", "ZEXTEND", "ZBLANK", "ZDATASUM", "ZHECKSUM",
151  // Not essential, but will prevent fitsverify warnings
152  "DATASUM", "CHECKSUM"
153  };
154 
160 StringStartSet const ignoreKeyStarts {
161  // FITS core keywords
162  "NAXIS", "TZERO", "TSCAL",
163  // FITS compression keywords
164  "ZNAXIS", "ZTILE", "ZNAME", "ZVAL"
165  };
166 
172 StringStartSet const ignoreKeyStartsWrite {
173  "TFORM", "TTYPE"
174  };
175 
176 // Strip leading and trailing single quotes and whitespace from a string.
177 std::string strip(std::string const &s) {
178  if (s.empty()) return s;
179  std::size_t i1 = s.find_first_not_of(" '");
180  std::size_t i2 = s.find_last_not_of(" '");
181  return s.substr(i1, (i1 == std::string::npos) ? 0 : 1 + i2 - i1);
182 }
183 
184 // ---- FITS binary table format codes for various C++ types. -----------------------------------------------
185 
186 char getFormatCode(bool *) { return 'X'; }
187 char getFormatCode(std::string *) { return 'A'; }
188 char getFormatCode(std::int8_t *) { return 'S'; }
189 char getFormatCode(std::uint8_t *) { return 'B'; }
190 char getFormatCode(std::int16_t *) { return 'I'; }
191 char getFormatCode(std::uint16_t *) { return 'U'; }
192 char getFormatCode(std::int32_t *) { return 'J'; }
193 char getFormatCode(std::uint32_t *) { return 'V'; }
194 char getFormatCode(std::int64_t *) { return 'K'; }
195 char getFormatCode(float *) { return 'E'; }
196 char getFormatCode(double *) { return 'D'; }
197 char getFormatCode(std::complex<float> *) { return 'C'; }
198 char getFormatCode(std::complex<double> *) { return 'M'; }
199 char getFormatCode(geom::Angle *) { return 'D'; }
200 
201 // ---- Create a TFORM value for the given type and size ----------------------------------------------------
202 
203 template <typename T>
204 std::string makeColumnFormat(int size = 1) {
205  if (size > 0) {
206  return (boost::format("%d%c") % size % getFormatCode((T *)0)).str();
207  } else if (size < 0) {
208  // variable length, max size given as -size
209  return (boost::format("1Q%c(%d)") % getFormatCode((T *)0) % (-size)).str();
210  } else {
211  // variable length, max size unknown
212  return (boost::format("1Q%c") % getFormatCode((T *)0)).str();
213  }
214 }
215 
216 // ---- Traits class to get cfitsio type constants from templates -------------------------------------------
217 
218 template <typename T>
219 struct FitsType;
220 
221 template <>
222 struct FitsType<bool> {
223  static int const CONSTANT = TLOGICAL;
224 };
225 template <>
226 struct FitsType<char> {
227  static int const CONSTANT = TSTRING;
228 };
229 template <>
230 struct FitsType<signed char> {
231  static int const CONSTANT = TSBYTE;
232 };
233 template <>
234 struct FitsType<unsigned char> {
235  static int const CONSTANT = TBYTE;
236 };
237 template <>
238 struct FitsType<short> {
239  static int const CONSTANT = TSHORT;
240 };
241 template <>
242 struct FitsType<unsigned short> {
243  static int const CONSTANT = TUSHORT;
244 };
245 template <>
246 struct FitsType<int> {
247  static int const CONSTANT = TINT;
248 };
249 template <>
250 struct FitsType<unsigned int> {
251  static int const CONSTANT = TUINT;
252 };
253 template <>
254 struct FitsType<long> {
255  static int const CONSTANT = TLONG;
256 };
257 template <>
258 struct FitsType<unsigned long> {
259  static int const CONSTANT = TULONG;
260 };
261 template <>
262 struct FitsType<long long> {
263  static int const CONSTANT = TLONGLONG;
264 };
265 template <>
266 struct FitsType<unsigned long long> {
267  static int const CONSTANT = TLONGLONG;
268 };
269 template <>
270 struct FitsType<float> {
271  static int const CONSTANT = TFLOAT;
272 };
273 template <>
274 struct FitsType<double> {
275  static int const CONSTANT = TDOUBLE;
276 };
277 template <>
278 struct FitsType<geom::Angle> {
279  static int const CONSTANT = TDOUBLE;
280 };
281 template <>
282 struct FitsType<std::complex<float> > {
283  static int const CONSTANT = TCOMPLEX;
284 };
285 template <>
286 struct FitsType<std::complex<double> > {
287  static int const CONSTANT = TDBLCOMPLEX;
288 };
289 
290 // We use TBIT when writing booleans to table cells, but TLOGICAL in headers.
291 template <typename T>
292 struct FitsTableType : public FitsType<T> {};
293 template <>
294 struct FitsTableType<bool> {
295  static int const CONSTANT = TBIT;
296 };
297 
298 template <typename T>
299 struct FitsBitPix;
300 
301 template <>
302 struct FitsBitPix<unsigned char> {
303  static int const CONSTANT = BYTE_IMG;
304 };
305 template <>
306 struct FitsBitPix<short> {
307  static int const CONSTANT = SHORT_IMG;
308 };
309 template <>
310 struct FitsBitPix<unsigned short> {
311  static int const CONSTANT = USHORT_IMG;
312 };
313 template <>
314 struct FitsBitPix<int> {
315  static int const CONSTANT = LONG_IMG;
316 }; // not a typo!
317 template <>
318 struct FitsBitPix<unsigned int> {
319  static int const CONSTANT = ULONG_IMG;
320 };
321 template <>
322 struct FitsBitPix<std::int64_t> {
323  static int const CONSTANT = LONGLONG_IMG;
324 };
325 template <>
326 struct FitsBitPix<std::uint64_t> {
327  static int const CONSTANT = LONGLONG_IMG;
328 };
329 template <>
330 struct FitsBitPix<float> {
331  static int const CONSTANT = FLOAT_IMG;
332 };
333 template <>
334 struct FitsBitPix<double> {
335  static int const CONSTANT = DOUBLE_IMG;
336 };
337 
338 static bool allowImageCompression = true;
339 
340 int fitsTypeForBitpix(int bitpix) {
341  switch (bitpix) {
342  case 8: return TBYTE;
343  case 16: return TSHORT;
344  case 32: return TINT;
345  case 64: return TLONGLONG;
346  case -32: return TFLOAT;
347  case -64: return TDOUBLE;
348  default:
350  os << "Invalid bitpix value: " << bitpix;
351  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError, os.str());
352  }
353 }
354 
355 /*
356  * Information about one item of metadata: is a comment? is valid?
357  *
358  * See isCommentIsValid for more information.
359  */
360 struct ItemInfo {
361  ItemInfo(bool isComment, bool isValid) : isComment(isComment), isValid(isValid) {}
362  bool isComment;
363  bool isValid;
364 };
365 
366 /*
367  * Is an item a commnt (or history) and is it usable in a FITS header?
368  *
369  * For an item to be valid:
370  * - If name is COMMENT or HISTORY then the item must be of type std::string
371  * - All other items are always valid
372  */
373 ItemInfo isCommentIsValid(daf::base::PropertyList const &pl, std::string const &name) {
374  if (!pl.exists(name)) {
375  return ItemInfo(false, false);
376  }
377  std::type_info const &type = pl.typeOf(name);
378  if ((name == "COMMENT") || (name == "HISTORY")) {
379  return ItemInfo(true, type == typeid(std::string));
380  }
381  return ItemInfo(false, true);
382 }
383 
384 } // anonymous
385 
386 // ----------------------------------------------------------------------------------------------------------
387 // ---- Implementations for stuff in fits.h -----------------------------------------------------------------
388 // ----------------------------------------------------------------------------------------------------------
389 
390 std::string makeErrorMessage(std::string const &fileName, int status, std::string const &msg) {
392  os << "cfitsio error";
393  if (fileName != "") {
394  os << " (" << fileName << ")";
395  }
396  if (status != 0) {
397  char fitsErrMsg[FLEN_ERRMSG];
398  fits_get_errstatus(status, fitsErrMsg);
399  os << ": " << fitsErrMsg << " (" << status << ")";
400  }
401  if (msg != "") {
402  os << " : " << msg;
403  }
404  os << "\ncfitsio error stack:\n";
405  char cfitsioMsg[FLEN_ERRMSG];
406  while (fits_read_errmsg(cfitsioMsg) != 0) {
407  os << " " << cfitsioMsg << "\n";
408  }
409  return os.str();
410 }
411 
412 std::string makeErrorMessage(void *fptr, int status, std::string const &msg) {
413  std::string fileName = "";
414  fitsfile *fd = reinterpret_cast<fitsfile *>(fptr);
415  if (fd != 0 && fd->Fptr != 0 && fd->Fptr->filename != 0) {
416  fileName = fd->Fptr->filename;
417  }
418  return makeErrorMessage(fileName, status, msg);
419 }
420 
422  std::set<std::string> const &excludeNames) {
423  daf::base::PropertyList const *pl = dynamic_cast<daf::base::PropertyList const *>(&metadata);
424  std::vector<std::string> allParamNames;
425  if (pl) {
426  allParamNames = pl->getOrderedNames();
427  } else {
428  allParamNames = metadata.paramNames(false);
429  }
430  std::vector<std::string> desiredParamNames;
431  for (auto const &name : allParamNames) {
432  if (excludeNames.count(name) == 0) {
433  desiredParamNames.push_back(name);
434  }
435  }
436  return makeLimitedFitsHeaderImpl(desiredParamNames, metadata);
437 }
438 
440  if (_managed) std::free(_ptr);
441  _ptr = 0;
442  _len = 0;
443  _managed = true;
444 }
445 
447  reset();
448  _ptr = std::malloc(len);
449  _len = len;
450  _managed = true;
451 }
452 
453 template <typename T>
454 int getBitPix() {
455  return FitsBitPix<T>::CONSTANT;
456 }
457 
458 // ----------------------------------------------------------------------------------------------------------
459 // ---- Implementations for Fits class ----------------------------------------------------------------------
460 // ----------------------------------------------------------------------------------------------------------
461 
463  std::string fileName = "<unknown>";
464  fitsfile *fd = reinterpret_cast<fitsfile *>(fptr);
465  if (fd != 0 && fd->Fptr != 0 && fd->Fptr->filename != 0) {
466  fileName = fd->Fptr->filename;
467  }
468  return fileName;
469 }
470 
472  int n = 1;
473  fits_get_hdu_num(reinterpret_cast<fitsfile *>(fptr), &n);
474  return n - 1;
475 }
476 
477 void Fits::setHdu(int hdu, bool relative) {
478  if (relative) {
479  fits_movrel_hdu(reinterpret_cast<fitsfile *>(fptr), hdu, 0, &status);
480  if (behavior & AUTO_CHECK) {
481  LSST_FITS_CHECK_STATUS(*this, boost::format("Incrementing HDU by %d") % hdu);
482  }
483  } else {
484  if (hdu != DEFAULT_HDU) {
485  fits_movabs_hdu(reinterpret_cast<fitsfile *>(fptr), hdu + 1, 0, &status);
486  }
487  if (hdu == DEFAULT_HDU && getHdu() == 0 && getImageDim() == 0) {
488  // want a silent failure here
489  int tmpStatus = status;
490  fits_movrel_hdu(reinterpret_cast<fitsfile *>(fptr), 1, 0, &tmpStatus);
491  }
492  if (behavior & AUTO_CHECK) {
493  LSST_FITS_CHECK_STATUS(*this, boost::format("Moving to HDU %d") % hdu);
494  }
495  }
496 }
497 
499  int n = 0;
500  fits_get_num_hdus(reinterpret_cast<fitsfile *>(fptr), &n, &status);
501  if (behavior & AUTO_CHECK) {
502  LSST_FITS_CHECK_STATUS(*this, "Getting number of HDUs in file.");
503  }
504  return n;
505 }
506 
507 // ---- Writing and updating header keys --------------------------------------------------------------------
508 
509 namespace {
510 
511 // Impl functions in the anonymous namespace do special handling for strings, bools, and IEEE fp values.
512 
519 std::string nonFiniteDoubleToString(double value) {
520  if (std::isfinite(value)) {
521  return "";
522  }
523  if (std::isnan(value)) {
524  return "NAN";
525  }
526  if (value < 0) {
527  return "-INFINITY";
528  }
529  return "+INFINITY";
530 }
531 
537 double stringToNonFiniteDouble(std::string const &value) {
538  if (value == "NAN") {
540  }
541  if (value == "+INFINITY") {
543  }
544  if (value == "-INFINITY") {
546  }
547  return 0;
548 }
549 
550 template <typename T>
551 void updateKeyImpl(Fits &fits, char const *key, T const &value, char const *comment) {
552  fits_update_key(reinterpret_cast<fitsfile *>(fits.fptr), FitsType<T>::CONSTANT, const_cast<char *>(key),
553  const_cast<T *>(&value), const_cast<char *>(comment), &fits.status);
554 }
555 
556 void updateKeyImpl(Fits &fits, char const *key, std::string const &value, char const *comment) {
557  fits_update_key_longstr(reinterpret_cast<fitsfile *>(fits.fptr), const_cast<char *>(key),
558  const_cast<char *>(value.c_str()), const_cast<char *>(comment), &fits.status);
559 }
560 
561 void updateKeyImpl(Fits &fits, char const *key, bool const &value, char const *comment) {
562  int v = value;
563  fits_update_key(reinterpret_cast<fitsfile *>(fits.fptr), TLOGICAL, const_cast<char *>(key), &v,
564  const_cast<char *>(comment), &fits.status);
565 }
566 
567 void updateKeyImpl(Fits &fits, char const *key, double const &value, char const *comment) {
568  std::string strValue = nonFiniteDoubleToString(value);
569  if (!strValue.empty()) {
570  updateKeyImpl(fits, key, strValue, comment);
571  } else {
572  fits_update_key(reinterpret_cast<fitsfile *>(fits.fptr), FitsType<double>::CONSTANT,
573  const_cast<char *>(key), const_cast<double *>(&value), const_cast<char *>(comment),
574  &fits.status);
575  }
576 }
577 
578 template <typename T>
579 void writeKeyImpl(Fits &fits, char const *key, T const &value, char const *comment) {
580  fits_write_key(reinterpret_cast<fitsfile *>(fits.fptr), FitsType<T>::CONSTANT, const_cast<char *>(key),
581  const_cast<T *>(&value), const_cast<char *>(comment), &fits.status);
582 }
583 
584 void writeKeyImpl(Fits &fits, char const *key, std::string const &value, char const *comment) {
585  if (strncmp(key, "COMMENT", 7) == 0) {
586  fits_write_comment(reinterpret_cast<fitsfile *>(fits.fptr), const_cast<char *>(value.c_str()),
587  &fits.status);
588  } else if (strncmp(key, "HISTORY", 7) == 0) {
589  fits_write_history(reinterpret_cast<fitsfile *>(fits.fptr), const_cast<char *>(value.c_str()),
590  &fits.status);
591  } else {
592  fits_write_key_longstr(reinterpret_cast<fitsfile *>(fits.fptr), const_cast<char *>(key),
593  const_cast<char *>(value.c_str()), const_cast<char *>(comment), &fits.status);
594  }
595 }
596 
597 void writeKeyImpl(Fits &fits, char const *key, bool const &value, char const *comment) {
598  int v = value;
599  fits_write_key(reinterpret_cast<fitsfile *>(fits.fptr), TLOGICAL, const_cast<char *>(key), &v,
600  const_cast<char *>(comment), &fits.status);
601 }
602 
603 void writeKeyImpl(Fits &fits, char const *key, double const &value, char const *comment) {
604  std::string strValue = nonFiniteDoubleToString(value);
605  if (!strValue.empty()) {
606  writeKeyImpl(fits, key, strValue, comment);
607  } else {
608  fits_write_key(reinterpret_cast<fitsfile *>(fits.fptr), FitsType<double>::CONSTANT,
609  const_cast<char *>(key), const_cast<double *>(&value), const_cast<char *>(comment),
610  &fits.status);
611  }
612 }
613 
614 } // anonymous
615 
616 template <typename T>
617 void Fits::updateKey(std::string const &key, T const &value, std::string const &comment) {
618  updateKeyImpl(*this, key.c_str(), value, comment.c_str());
619  if (behavior & AUTO_CHECK) {
620  LSST_FITS_CHECK_STATUS(*this, boost::format("Updating key '%s': '%s'") % key % value);
621  }
622 }
623 
624 template <typename T>
625 void Fits::writeKey(std::string const &key, T const &value, std::string const &comment) {
626  writeKeyImpl(*this, key.c_str(), value, comment.c_str());
627  if (behavior & AUTO_CHECK) {
628  LSST_FITS_CHECK_STATUS(*this, boost::format("Writing key '%s': '%s'") % key % value);
629  }
630 }
631 
632 template <typename T>
633 void Fits::updateKey(std::string const &key, T const &value) {
634  updateKeyImpl(*this, key.c_str(), value, 0);
635  if (behavior & AUTO_CHECK) {
636  LSST_FITS_CHECK_STATUS(*this, boost::format("Updating key '%s': '%s'") % key % value);
637  }
638 }
639 
640 template <typename T>
641 void Fits::writeKey(std::string const &key, T const &value) {
642  writeKeyImpl(*this, key.c_str(), value, 0);
643  if (behavior & AUTO_CHECK) {
644  LSST_FITS_CHECK_STATUS(*this, boost::format("Writing key '%s': '%s'") % key % value);
645  }
646 }
647 
648 template <typename T>
649 void Fits::updateColumnKey(std::string const &prefix, int n, T const &value, std::string const &comment) {
650  updateKey((boost::format("%s%d") % prefix % (n + 1)).str(), value, comment);
651  if (behavior & AUTO_CHECK) {
652  LSST_FITS_CHECK_STATUS(*this, boost::format("Updating key '%s%d': '%s'") % prefix % (n + 1) % value);
653  }
654 }
655 
656 template <typename T>
657 void Fits::writeColumnKey(std::string const &prefix, int n, T const &value, std::string const &comment) {
658  writeKey((boost::format("%s%d") % prefix % (n + 1)).str(), value, comment);
659  if (behavior & AUTO_CHECK) {
660  LSST_FITS_CHECK_STATUS(*this, boost::format("Writing key '%s%d': '%s'") % prefix % (n + 1) % value);
661  }
662 }
663 
664 template <typename T>
665 void Fits::updateColumnKey(std::string const &prefix, int n, T const &value) {
666  updateKey((boost::format("%s%d") % prefix % (n + 1)).str(), value);
667  if (behavior & AUTO_CHECK) {
668  LSST_FITS_CHECK_STATUS(*this, boost::format("Updating key '%s%d': '%s'") % prefix % (n + 1) % value);
669  }
670 }
671 
672 template <typename T>
673 void Fits::writeColumnKey(std::string const &prefix, int n, T const &value) {
674  writeKey((boost::format("%s%d") % prefix % (n + 1)).str(), value);
675  if (behavior & AUTO_CHECK) {
676  LSST_FITS_CHECK_STATUS(*this, boost::format("Writing key '%s%d': '%s'") % prefix % (n + 1) % value);
677  }
678 }
679 
680 // ---- Reading header keys ---------------------------------------------------------------------------------
681 
682 namespace {
683 
684 template <typename T>
685 void readKeyImpl(Fits &fits, char const *key, T &value) {
686  fits_read_key(reinterpret_cast<fitsfile *>(fits.fptr), FitsType<T>::CONSTANT, const_cast<char *>(key),
687  &value, 0, &fits.status);
688 }
689 
690 void readKeyImpl(Fits &fits, char const *key, std::string &value) {
691  char *buf = 0;
692  fits_read_key_longstr(reinterpret_cast<fitsfile *>(fits.fptr), const_cast<char *>(key), &buf, 0,
693  &fits.status);
694  if (buf) {
695  value = strip(buf);
696  free(buf);
697  }
698 }
699 
700 void readKeyImpl(Fits &fits, char const *key, double &value) {
701  // We need to check for the possibility that the value is a special string (for NAN, +/-Inf).
702  // If a quote mark (') is present then it's a string.
703 
704  char buf[FLEN_VALUE];
705  fits_read_keyword(reinterpret_cast<fitsfile *>(fits.fptr), const_cast<char *>(key), buf, 0, &fits.status);
706  if (fits.status != 0) {
707  return;
708  }
709  if (std::string(buf).find('\'') != std::string::npos) {
710  std::string unquoted;
711  readKeyImpl(fits, key, unquoted); // Let someone else remove quotes and whitespace
712  if (fits.status != 0) {
713  return;
714  }
715  value = stringToNonFiniteDouble(unquoted);
716  if (value == 0) {
717  throw LSST_EXCEPT(
719  (boost::format("Unrecognised string value for keyword '%s' when parsing as double: %s") %
720  key % unquoted)
721  .str());
722  }
723  } else {
724  fits_read_key(reinterpret_cast<fitsfile *>(fits.fptr), FitsType<double>::CONSTANT,
725  const_cast<char *>(key), &value, 0, &fits.status);
726  }
727 }
728 
729 } // anonymous
730 
731 template <typename T>
732 void Fits::readKey(std::string const &key, T &value) {
733  readKeyImpl(*this, key.c_str(), value);
734  if (behavior & AUTO_CHECK) {
735  LSST_FITS_CHECK_STATUS(*this, boost::format("Reading key '%s'") % key);
736  }
737 }
738 
740  char key[81]; // allow for terminating NUL
741  char value[81];
742  char comment[81];
743  int nKeys = 0;
744  fits_get_hdrspace(reinterpret_cast<fitsfile *>(fptr), &nKeys, 0, &status);
745  std::string keyStr;
746  std::string valueStr;
747  std::string commentStr;
748  int i = 1;
749  while (i <= nKeys) {
750  fits_read_keyn(reinterpret_cast<fitsfile *>(fptr), i, key, value, comment, &status);
751  keyStr = key;
752  valueStr = value;
753  commentStr = comment;
754  ++i;
755  while (valueStr.size() > 2 && valueStr[valueStr.size() - 2] == '&' && i <= nKeys) {
756  // we're using key to hold the entire record here; the actual key is safe in keyStr
757  fits_read_record(reinterpret_cast<fitsfile *>(fptr), i, key, &status);
758  if (strncmp(key, "CONTINUE", 8) != 0) {
759  // require both trailing '&' and CONTINUE to invoke long-string handling
760  break;
761  }
762  std::string card = key;
763  valueStr.erase(valueStr.size() - 2);
764  std::size_t firstQuote = card.find('\'');
765  if (firstQuote == std::string::npos) {
766  throw LSST_EXCEPT(
767  FitsError,
769  fptr, status,
770  boost::format("Invalid CONTINUE at header key %d: \"%s\".") % i % card));
771  }
772  std::size_t lastQuote = card.find('\'', firstQuote + 1);
773  if (lastQuote == std::string::npos) {
774  throw LSST_EXCEPT(
775  FitsError,
777  fptr, status,
778  boost::format("Invalid CONTINUE at header key %d: \"%s\".") % i % card));
779  }
780  valueStr += card.substr(firstQuote + 1, lastQuote - firstQuote);
781  std::size_t slash = card.find('/', lastQuote + 1);
782  if (slash != std::string::npos) {
783  commentStr += strip(card.substr(slash + 1));
784  }
785  ++i;
786  }
787  if (behavior & AUTO_CHECK) {
788  LSST_FITS_CHECK_STATUS(*this, boost::format("Reading key '%s'") % keyStr);
789  }
790  functor(keyStr, valueStr, commentStr);
791  }
792 }
793 
794 // ---- Reading and writing PropertySet/PropertyList --------------------------------------------------------
795 
796 namespace {
797 
798 bool isKeyIgnored(std::string const &key, bool write=false) {
799  return ((ignoreKeys.find(key) != ignoreKeys.end()) ||
800  ignoreKeyStarts.matches(key) ||
801  (write && ignoreKeyStartsWrite.matches(key)));
802 }
803 
804 class MetadataIterationFunctor : public HeaderIterationFunctor {
805 public:
806  virtual void operator()(std::string const &key, std::string const &value, std::string const &comment);
807 
808  template <typename T>
809  void add(std::string const &key, T value, std::string const &comment) {
810  if (list) {
811  list->add(key, value, comment);
812  } else {
813  set->add(key, value);
814  }
815  }
816 
817  bool strip;
818  daf::base::PropertySet *set;
819  daf::base::PropertyList *list;
820 };
821 
822 void MetadataIterationFunctor::operator()(std::string const &key, std::string const &value,
823  std::string const &comment) {
824  static boost::regex const boolRegex("[tTfF]");
825  static boost::regex const intRegex("[+-]?[0-9]+");
826  static boost::regex const doubleRegex("[+-]?([0-9]*\\.?[0-9]+|[0-9]+\\.?[0-9]*)([eE][+-]?[0-9]+)?");
827  static boost::regex const fitsStringRegex("'(.*?) *'");
828  boost::smatch matchStrings;
829 
830  if (strip && isKeyIgnored(key)) {
831  return;
832  }
833 
834  std::istringstream converter(value);
835  if (boost::regex_match(value, boolRegex)) {
836  // convert the string to an bool
837  add(key, bool(value == "T" || value == "t"), comment);
838  } else if (boost::regex_match(value, intRegex)) {
839  // convert the string to an int
840  std::int64_t val;
841  converter >> val;
842  if (val < (1LL << 31) && val > -(1LL << 31)) {
843  add(key, static_cast<int>(val), comment);
844  } else {
845  add(key, val, comment);
846  }
847  } else if (boost::regex_match(value, doubleRegex)) {
848  // convert the string to a double
849  double val;
850  converter >> val;
851  add(key, val, comment);
852  } else if (boost::regex_match(value, matchStrings, fitsStringRegex)) {
853  std::string const str = matchStrings[1].str(); // strip off the enclosing single quotes
854  double val = stringToNonFiniteDouble(str);
855  if (val != 0.0) {
856  add(key, val, comment);
857  } else {
858  add(key, str, comment);
859  }
860  } else if (key == "HISTORY" || key == "COMMENT") {
861  add(key, comment, "");
862  } else if (value.empty()) {
863  // do nothing for empty values
864  } else {
865  throw LSST_EXCEPT(
866  afw::fits::FitsError,
867  (boost::format("Could not parse header value for key '%s': '%s'") % key % value).str());
868  }
869 }
870 
871 void writeKeyFromProperty(Fits &fits, daf::base::PropertySet const &metadata, std::string const &key,
872  char const *comment = 0) {
873  std::type_info const &valueType = metadata.typeOf(key);
874  if (valueType == typeid(bool)) {
875  if (metadata.isArray(key)) {
876  std::vector<bool> tmp = metadata.getArray<bool>(key);
877  // work around unfortunate specialness of std::vector<bool>
878  for (std::size_t i = 0; i != tmp.size(); ++i) {
879  writeKeyImpl(fits, key.c_str(), static_cast<bool>(tmp[i]), comment);
880  }
881  } else {
882  writeKeyImpl(fits, key.c_str(), metadata.get<bool>(key), comment);
883  }
884  } else if (valueType == typeid(std::uint8_t)) {
885  if (metadata.isArray(key)) {
886  std::vector<std::uint8_t> tmp = metadata.getArray<std::uint8_t>(key);
887  for (std::size_t i = 0; i != tmp.size(); ++i) {
888  writeKeyImpl(fits, key.c_str(), tmp[i], comment);
889  }
890  } else {
891  writeKeyImpl(fits, key.c_str(), metadata.get<std::uint8_t>(key), comment);
892  }
893  } else if (valueType == typeid(int)) {
894  if (metadata.isArray(key)) {
895  std::vector<int> tmp = metadata.getArray<int>(key);
896  for (std::size_t i = 0; i != tmp.size(); ++i) {
897  writeKeyImpl(fits, key.c_str(), tmp[i], comment);
898  }
899  } else {
900  writeKeyImpl(fits, key.c_str(), metadata.get<int>(key), comment);
901  }
902  } else if (valueType == typeid(long)) {
903  if (metadata.isArray(key)) {
904  std::vector<long> tmp = metadata.getArray<long>(key);
905  for (std::size_t i = 0; i != tmp.size(); ++i) {
906  writeKeyImpl(fits, key.c_str(), tmp[i], comment);
907  }
908  } else {
909  writeKeyImpl(fits, key.c_str(), metadata.get<long>(key), comment);
910  }
911  } else if (valueType == typeid(long long)) {
912  if (metadata.isArray(key)) {
913  std::vector<long long> tmp = metadata.getArray<long long>(key);
914  for (std::size_t i = 0; i != tmp.size(); ++i) {
915  writeKeyImpl(fits, key.c_str(), tmp[i], comment);
916  }
917  } else {
918  writeKeyImpl(fits, key.c_str(), metadata.get<long long>(key), comment);
919  }
920  } else if (valueType == typeid(std::int64_t)) {
921  if (metadata.isArray(key)) {
922  std::vector<std::int64_t> tmp = metadata.getArray<std::int64_t>(key);
923  for (std::size_t i = 0; i != tmp.size(); ++i) {
924  writeKeyImpl(fits, key.c_str(), tmp[i], comment);
925  }
926  } else {
927  writeKeyImpl(fits, key.c_str(), metadata.get<std::int64_t>(key), comment);
928  }
929  } else if (valueType == typeid(double)) {
930  if (metadata.isArray(key)) {
931  std::vector<double> tmp = metadata.getArray<double>(key);
932  for (std::size_t i = 0; i != tmp.size(); ++i) {
933  writeKeyImpl(fits, key.c_str(), tmp[i], comment);
934  }
935  } else {
936  writeKeyImpl(fits, key.c_str(), metadata.get<double>(key), comment);
937  }
938  } else if (valueType == typeid(std::string)) {
939  if (metadata.isArray(key)) {
940  std::vector<std::string> tmp = metadata.getArray<std::string>(key);
941  for (std::size_t i = 0; i != tmp.size(); ++i) {
942  writeKeyImpl(fits, key.c_str(), tmp[i], comment);
943  }
944  } else {
945  writeKeyImpl(fits, key.c_str(), metadata.get<std::string>(key), comment);
946  }
947  } else {
948  // FIXME: inherited this error handling from fitsIo.cc; need a better option.
949  LOGLS_WARN("afw.writeKeyFromProperty",
950  makeErrorMessage(fits.fptr, fits.status,
951  boost::format("In %s, unknown type '%s' for key '%s'.") %
952  BOOST_CURRENT_FUNCTION % valueType.name() % key));
953  }
954  if (fits.behavior & Fits::AUTO_CHECK) {
955  LSST_FITS_CHECK_STATUS(fits, boost::format("Writing key '%s'") % key);
956  }
957 }
958 
959 } // anonymous
960 
962  MetadataIterationFunctor f;
963  f.strip = strip;
964  f.set = &metadata;
965  f.list = dynamic_cast<daf::base::PropertyList *>(&metadata);
966  forEachKey(f);
967 }
968 
970  typedef std::vector<std::string> NameList;
971  daf::base::PropertyList const *pl = dynamic_cast<daf::base::PropertyList const *>(&metadata);
972  NameList paramNames;
973  if (pl) {
974  paramNames = pl->getOrderedNames();
975  } else {
976  paramNames = metadata.paramNames(false);
977  }
978  for (NameList::const_iterator i = paramNames.begin(); i != paramNames.end(); ++i) {
979  if (!isKeyIgnored(*i, true)) {
980  if (pl) {
981  writeKeyFromProperty(*this, metadata, *i, pl->getComment(*i).c_str());
982  } else {
983  writeKeyFromProperty(*this, metadata, *i);
984  }
985  }
986  }
987 }
988 
989 // ---- Manipulating tables ---------------------------------------------------------------------------------
990 
992  char *ttype = 0;
993  char *tform = 0;
994  fits_create_tbl(reinterpret_cast<fitsfile *>(fptr), BINARY_TBL, 0, 0, &ttype, &tform, 0, 0, &status);
995  if (behavior & AUTO_CHECK) {
996  LSST_FITS_CHECK_STATUS(*this, "Creating binary table");
997  }
998 }
999 
1000 template <typename T>
1001 int Fits::addColumn(std::string const &ttype, int size) {
1002  int nCols = 0;
1003  fits_get_num_cols(reinterpret_cast<fitsfile *>(fptr), &nCols, &status);
1004  std::string tform = makeColumnFormat<T>(size);
1005  fits_insert_col(reinterpret_cast<fitsfile *>(fptr), nCols + 1, const_cast<char *>(ttype.c_str()),
1006  const_cast<char *>(tform.c_str()), &status);
1007  if (behavior & AUTO_CHECK) {
1008  LSST_FITS_CHECK_STATUS(*this, boost::format("Adding column '%s' with size %d") % ttype % size);
1009  }
1010  return nCols;
1011 }
1012 
1013 template <typename T>
1014 int Fits::addColumn(std::string const &ttype, int size, std::string const &comment) {
1015  int nCols = addColumn<T>(ttype, size);
1016  updateColumnKey("TTYPE", nCols, ttype, comment);
1017  if (behavior & AUTO_CHECK) {
1018  LSST_FITS_CHECK_STATUS(*this, boost::format("Adding column '%s' with size %d") % ttype % size);
1019  }
1020  return nCols;
1021 }
1022 
1024  long first = 0;
1025  fits_get_num_rows(reinterpret_cast<fitsfile *>(fptr), &first, &status);
1026  fits_insert_rows(reinterpret_cast<fitsfile *>(fptr), first, nRows, &status);
1027  if (behavior & AUTO_CHECK) {
1028  LSST_FITS_CHECK_STATUS(*this, boost::format("Adding %d rows to binary table") % nRows);
1029  }
1030  return first;
1031 }
1032 
1034  long r = 0;
1035  fits_get_num_rows(reinterpret_cast<fitsfile *>(fptr), &r, &status);
1036  if (behavior & AUTO_CHECK) {
1037  LSST_FITS_CHECK_STATUS(*this, "Checking how many rows are in table");
1038  }
1039  return r;
1040 }
1041 
1042 template <typename T>
1043 void Fits::writeTableArray(std::size_t row, int col, int nElements, T const *value) {
1044  fits_write_col(reinterpret_cast<fitsfile *>(fptr), FitsTableType<T>::CONSTANT, col + 1, row + 1, 1,
1045  nElements, const_cast<T *>(value), &status);
1046  if (behavior & AUTO_CHECK) {
1047  LSST_FITS_CHECK_STATUS(*this, boost::format("Writing %d-element array at table cell (%d, %d)") %
1048  nElements % row % col);
1049  }
1050 }
1051 
1052 void Fits::writeTableScalar(std::size_t row, int col, std::string const &value) {
1053  // cfitsio doesn't let us specify the size of a string, it just looks for null terminator.
1054  // Using std::string::c_str() guarantees that we have one. But we can't store arbitrary
1055  // data in a string field because cfitsio will also chop off anything after the first null
1056  // terminator.
1057  char const *tmp = value.c_str();
1058  fits_write_col(reinterpret_cast<fitsfile *>(fptr), TSTRING, col + 1, row + 1, 1, 1,
1059  const_cast<char const **>(&tmp), &status);
1060  if (behavior & AUTO_CHECK) {
1061  LSST_FITS_CHECK_STATUS(*this, boost::format("Writing value at table cell (%d, %d)") % row % col);
1062  }
1063 }
1064 
1065 template <typename T>
1066 void Fits::readTableArray(std::size_t row, int col, int nElements, T *value) {
1067  int anynul = false;
1068  fits_read_col(reinterpret_cast<fitsfile *>(fptr), FitsTableType<T>::CONSTANT, col + 1, row + 1, 1,
1069  nElements, 0, value, &anynul, &status);
1070  if (behavior & AUTO_CHECK) {
1071  LSST_FITS_CHECK_STATUS(*this, boost::format("Reading value at table cell (%d, %d)") % row % col);
1072  }
1073 }
1074 
1075 void Fits::readTableScalar(std::size_t row, int col, std::string &value, bool isVariableLength) {
1076  int anynul = false;
1077  long size = isVariableLength ? getTableArraySize(row, col) : getTableArraySize(col);
1078  // We can't directly write into a std::string until C++17.
1079  std::vector<char> buf(size + 1, 0);
1080  // cfitsio wants a char** because they imagine we might want an array of strings,
1081  // but we only want one element.
1082  char *tmp = &buf.front();
1083  fits_read_col(reinterpret_cast<fitsfile *>(fptr), TSTRING, col + 1, row + 1, 1, 1, 0, &tmp, &anynul,
1084  &status);
1085  if (behavior & AUTO_CHECK) {
1086  LSST_FITS_CHECK_STATUS(*this, boost::format("Reading value at table cell (%d, %d)") % row % col);
1087  }
1088  value = std::string(tmp);
1089 }
1090 
1092  int typecode = 0;
1093  long result = 0;
1094  long width = 0;
1095  fits_get_coltype(reinterpret_cast<fitsfile *>(fptr), col + 1, &typecode, &result, &width, &status);
1096  if (behavior & AUTO_CHECK) {
1097  LSST_FITS_CHECK_STATUS(*this, boost::format("Looking up array size for column %d") % col);
1098  }
1099  return result;
1100 }
1101 
1103  long result = 0;
1104  long offset = 0;
1105  fits_read_descript(reinterpret_cast<fitsfile *>(fptr), col + 1, row + 1, &result, &offset, &status);
1106  if (behavior & AUTO_CHECK) {
1107  LSST_FITS_CHECK_STATUS(*this, boost::format("Looking up array size for cell (%d, %d)") % row % col);
1108  }
1109  return result;
1110 }
1111 
1112 // ---- Manipulating images ---------------------------------------------------------------------------------
1113 
1115  long naxes = 0;
1116  fits_create_img(reinterpret_cast<fitsfile *>(fptr), 8, 0, &naxes, &status);
1117  if (behavior & AUTO_CHECK) {
1118  LSST_FITS_CHECK_STATUS(*this, "Creating empty image HDU");
1119  }
1120 }
1121 
1122 void Fits::createImageImpl(int bitpix, int naxis, long const *naxes) {
1123  fits_create_img(reinterpret_cast<fitsfile *>(fptr), bitpix, naxis,
1124  const_cast<long*>(naxes), &status);
1125  if (behavior & AUTO_CHECK) {
1126  LSST_FITS_CHECK_STATUS(*this, "Creating new image HDU");
1127  }
1128 }
1129 
1130 template <typename T>
1131 void Fits::writeImageImpl(T const *data, int nElements) {
1132  fits_write_img(reinterpret_cast<fitsfile *>(fptr), FitsType<T>::CONSTANT, 1, nElements,
1133  const_cast<T *>(data), &status);
1134  if (behavior & AUTO_CHECK) {
1135  LSST_FITS_CHECK_STATUS(*this, "Writing image");
1136  }
1137 }
1138 
1139 namespace {
1140 
1145 struct ImageCompressionContext {
1146  public:
1147  ImageCompressionContext(Fits & fits_, ImageCompressionOptions const& useThis)
1148  : fits(fits_), old(fits.getImageCompression()) {
1149  fits.setImageCompression(useThis);
1150  }
1151  ~ImageCompressionContext() {
1152  int status = 0;
1153  std::swap(status, fits.status);
1154  try {
1155  fits.setImageCompression(old);
1156  } catch (...) {
1157  LOGLS_WARN("afw.fits",
1158  makeErrorMessage(fits.fptr, fits.status, "Failed to restore compression settings"));
1159  }
1160  std::swap(status, fits.status);
1161  }
1162  private:
1163  Fits & fits; // FITS file we're working on
1164  ImageCompressionOptions old; // Former compression options, to be restored
1165 };
1166 
1167 } // anonymous namespace
1168 
1169 template <typename T>
1171  image::ImageBase<T> const& image,
1172  ImageWriteOptions const& options,
1175 ) {
1176  auto fits = reinterpret_cast<fitsfile *>(fptr);
1177  ImageCompressionOptions const& compression = image.getBBox().getArea() > 0 ? options.compression :
1178  ImageCompressionOptions(ImageCompressionOptions::NONE); // cfitsio can't compress empty images
1179  ImageCompressionContext comp(*this, compression); // RAII
1180  if (behavior & AUTO_CHECK) {
1181  LSST_FITS_CHECK_STATUS(*this, "Activating compression for write image");
1182  }
1183 
1184  ImageScale scale = options.scaling.determine(image, mask);
1185 
1186  // We need a place to put the image+header, and CFITSIO needs to know the dimenions.
1187  ndarray::Vector<long, 2> dims(image.getArray().getShape().reverse());
1188  createImageImpl(scale.bitpix == 0 ? detail::Bitpix<T>::value : scale.bitpix, 2, dims.elems);
1189 
1190  // Write the header
1193  if (header) {
1194  std::shared_ptr<daf::base::PropertySet> copy = header->deepCopy();
1195  copy->combine(wcsMetadata);
1196  header = copy;
1197  } else {
1198  header = wcsMetadata;
1199  }
1200  writeMetadata(*header);
1201 
1202  // Scale the image how we want it on disk
1203  ndarray::Array<T const, 2, 2> array = makeContiguousArray(image.getArray());
1204  auto pixels = scale.toFits(array, compression.quantizeLevel != 0, options.scaling.fuzz,
1205  options.compression.tiles, options.scaling.seed);
1206 
1207  // We only want cfitsio to do the scale and zero for unsigned 64-bit integer types. For those,
1208  // "double bzero" has sufficient precision to represent the appropriate value. We'll let
1209  // cfitsio handle it itself.
1210  // In all other cases, we will convert the image to use the appropriate scale and zero
1211  // (because we want to fuzz the numbers in the quantisation), so we don't want cfitsio
1212  // rescaling.
1214  fits_set_bscale(fits, 1.0, 0.0, &status);
1215  if (behavior & AUTO_CHECK) {
1216  LSST_FITS_CHECK_STATUS(*this, "Setting bscale,bzero");
1217  }
1218  }
1219 
1220  // Write the pixels
1221  int const fitsType = scale.bitpix == 0 ? FitsType<T>::CONSTANT : fitsTypeForBitpix(scale.bitpix);
1222  fits_write_img(fits, fitsType, 1, pixels->getNumElements(),
1223  const_cast<void*>(pixels->getData()), &status);
1224  if (behavior & AUTO_CHECK) {
1225  LSST_FITS_CHECK_STATUS(*this, "Writing image");
1226  }
1227 
1228  // Now write the headers we didn't want cfitsio to know about when we were writing the pixels
1229  // (because we don't want it using them to modify the pixels, and we don't want it overwriting
1230  // these values).
1232  std::isfinite(scale.bzero) && std::isfinite(scale.bscale) && (scale.bscale != 0.0)) {
1234  if (scale.bzero != 0.0) {
1235  fits_write_key_lng(fits, "BZERO", static_cast<long>(scale.bzero),
1236  "Scaling: MEMORY = BZERO + BSCALE * DISK", &status);
1237  }
1238  if (scale.bscale != 1.0) {
1239  fits_write_key_lng(fits, "BSCALE", static_cast<long>(scale.bscale),
1240  "Scaling: MEMORY = BZERO + BSCALE * DISK", &status);
1241  }
1242  } else {
1243  fits_write_key_dbl(fits, "BZERO", scale.bzero, 12,
1244  "Scaling: MEMORY = BZERO + BSCALE * DISK", &status);
1245  fits_write_key_dbl(fits, "BSCALE", scale.bscale, 12,
1246  "Scaling: MEMORY = BZERO + BSCALE * DISK", &status);
1247  }
1248  if (behavior & AUTO_CHECK) {
1249  LSST_FITS_CHECK_STATUS(*this, "Writing BSCALE,BZERO");
1250  }
1251  }
1252 
1253  if (scale.bitpix > 0) {
1254  fits_write_key_lng(fits, "BLANK", scale.blank, "Value for undefined pixels", &status);
1255  fits_write_key_lng(fits, "ZBLANK", scale.blank, "Value for undefined pixels", &status);
1257  fits_write_key_lng(fits, "ZDITHER0", options.scaling.seed, "Dithering seed", &status);
1258  fits_write_key_str(fits, "ZQUANTIZ", "SUBTRACTIVE_DITHER_1", "Dithering algorithm", &status);
1259  }
1260  if (behavior & AUTO_CHECK) {
1261  LSST_FITS_CHECK_STATUS(*this, "Writing [Z]BLANK");
1262  }
1263  }
1264 
1265  // cfitsio says this is deprecated, but Pan-STARRS found that it was sometimes necessary, writing:
1266  // "This forces a re-scan of the header to ensure everything's kosher.
1267  // Without this, compressed HDUs have been written out with PCOUNT=0 and TFORM1 not correctly set."
1268  fits_set_hdustruc(fits, &status);
1269  if (behavior & AUTO_CHECK) {
1270  LSST_FITS_CHECK_STATUS(*this, "Finalizing header");
1271  }
1272 }
1273 
1274 
1275 namespace {
1276 
1278 template <typename T, class Enable=void>
1279 struct NullValue {
1280  static T constexpr value = 0;
1281 };
1282 
1284 template <typename T>
1285 struct NullValue<T, typename std::enable_if<std::numeric_limits<T>::has_quiet_NaN>::type> {
1286  static T constexpr value = std::numeric_limits<T>::quiet_NaN();
1287 };
1288 
1289 }
1290 
1291 template <typename T>
1292 void Fits::readImageImpl(int nAxis, T *data, long *begin, long *end, long *increment) {
1293  T null = NullValue<T>::value;
1294  int anyNulls = 0;
1295  fits_read_subset(reinterpret_cast<fitsfile *>(fptr), FitsType<T>::CONSTANT, begin, end, increment,
1296  reinterpret_cast<void*>(&null), data, &anyNulls, &status);
1297  if (behavior & AUTO_CHECK) LSST_FITS_CHECK_STATUS(*this, "Reading image");
1298 }
1299 
1301  int nAxis = 0;
1302  fits_get_img_dim(reinterpret_cast<fitsfile *>(fptr), &nAxis, &status);
1303  if (behavior & AUTO_CHECK) LSST_FITS_CHECK_STATUS(*this, "Getting NAXIS");
1304  return nAxis;
1305 }
1306 
1307 void Fits::getImageShapeImpl(int maxDim, long *nAxes) {
1308  fits_get_img_size(reinterpret_cast<fitsfile *>(fptr), maxDim, nAxes, &status);
1309  if (behavior & AUTO_CHECK) LSST_FITS_CHECK_STATUS(*this, "Getting NAXES");
1310 }
1311 
1312 template <typename T>
1314  int imageType = 0;
1315  fits_get_img_equivtype(reinterpret_cast<fitsfile *>(fptr), &imageType, &status);
1316  if (behavior & AUTO_CHECK) LSST_FITS_CHECK_STATUS(*this, "Getting image type");
1318  if (imageType < 0) {
1319  return false; // can't represent floating-point with integer
1320  }
1321  return imageType <= FitsBitPix<T>::CONSTANT; // can represent a small int by a larger int
1322  }
1324  // Everything can be represented by double
1325  return true;
1326  }
1327  assert((std::is_same<T, float>::value)); // Everything else has been dealt with
1328  switch (imageType) {
1329  case TLONGLONG:
1330  case TDOUBLE:
1331  // Not enough precision in 'float'
1332  return false;
1333  default:
1334  return true;
1335  }
1336 }
1337 
1339 {
1340  auto fits = reinterpret_cast<fitsfile *>(fptr);
1341  int compType = 0; // cfitsio compression type
1342  fits_get_compression_type(fits, &compType, &status);
1343  if (behavior & AUTO_CHECK) {
1344  LSST_FITS_CHECK_STATUS(*this, "Getting compression type");
1345  }
1346 
1347  ImageCompressionOptions::Tiles tiles = ndarray::allocate(MAX_COMPRESS_DIM);
1348  fits_get_tile_dim(fits, tiles.getNumElements(), tiles.getData(), &status);
1349  if (behavior & AUTO_CHECK) {
1350  LSST_FITS_CHECK_STATUS(*this, "Getting tile dimensions");
1351  }
1352 
1353  float quantizeLevel;
1354  fits_get_quantize_level(fits, &quantizeLevel, &status);
1355  if (behavior & AUTO_CHECK) {
1356  LSST_FITS_CHECK_STATUS(*this, "Getting quantizeLevel");
1357  }
1358 
1359  return ImageCompressionOptions(compressionAlgorithmFromCfitsio(compType), tiles, quantizeLevel);
1360 }
1361 
1363 {
1364  auto fits = reinterpret_cast<fitsfile *>(fptr);
1365  fits_unset_compression_request(fits, &status); // wipe the slate and start over
1366  ImageCompressionOptions::CompressionAlgorithm const algorithm = allowImageCompression ? comp.algorithm :
1368  fits_set_compression_type(fits, compressionAlgorithmToCfitsio(algorithm), &status);
1369  if (behavior & AUTO_CHECK) {
1370  LSST_FITS_CHECK_STATUS(*this, "Setting compression type");
1371  }
1372 
1373  if (algorithm == ImageCompressionOptions::NONE) {
1374  // Nothing else worth doing
1375  return;
1376  }
1377 
1378  fits_set_tile_dim(fits, comp.tiles.getNumElements(), comp.tiles.getData(), &status);
1379  if (behavior & AUTO_CHECK) {
1380  LSST_FITS_CHECK_STATUS(*this, "Setting tile dimensions");
1381  }
1382 
1384  fits_set_quantize_level(fits, comp.quantizeLevel, &status);
1385  if (behavior & AUTO_CHECK) {
1386  LSST_FITS_CHECK_STATUS(*this, "Setting quantization level");
1387  }
1388  }
1389 }
1390 
1391 void setAllowImageCompression(bool allow) {
1392  allowImageCompression = allow;
1393 }
1394 
1396  return allowImageCompression;
1397 }
1398 
1399 // ---- Manipulating files ----------------------------------------------------------------------------------
1400 
1401 Fits::Fits(std::string const &filename, std::string const &mode, int behavior_)
1402  : fptr(0), status(0), behavior(behavior_) {
1403  if (mode == "r" || mode == "rb") {
1404  fits_open_file(reinterpret_cast<fitsfile **>(&fptr), const_cast<char *>(filename.c_str()), READONLY,
1405  &status);
1406  } else if (mode == "w" || mode == "wb") {
1407  boost::filesystem::remove(filename); // cfitsio doesn't like over-writing files
1408  fits_create_file(reinterpret_cast<fitsfile **>(&fptr), const_cast<char *>(filename.c_str()), &status);
1409  } else if (mode == "a" || mode == "ab") {
1410  fits_open_file(reinterpret_cast<fitsfile **>(&fptr), const_cast<char *>(filename.c_str()), READWRITE,
1411  &status);
1412  int nHdu = 0;
1413  fits_get_num_hdus(reinterpret_cast<fitsfile *>(fptr), &nHdu, &status);
1414  fits_movabs_hdu(reinterpret_cast<fitsfile *>(fptr), nHdu, NULL, &status);
1415  if ((behavior & AUTO_CHECK) && (behavior & AUTO_CLOSE) && (status) && (fptr)) {
1416  // We're about to throw an exception, and the destructor won't get called
1417  // because we're in the constructor, so cleanup here first.
1418  int tmpStatus = 0;
1419  fits_close_file(reinterpret_cast<fitsfile *>(fptr), &tmpStatus);
1420  }
1421  } else {
1422  throw LSST_EXCEPT(
1423  FitsError,
1424  (boost::format("Invalid mode '%s' given when opening file '%s'") % mode % filename).str());
1425  }
1426  if (behavior & AUTO_CHECK) {
1427  LSST_FITS_CHECK_STATUS(*this, boost::format("Opening file '%s' with mode '%s'") % filename % mode);
1428  }
1429 }
1430 
1431 Fits::Fits(MemFileManager &manager, std::string const &mode, int behavior_)
1432  : fptr(0), status(0), behavior(behavior_) {
1433  typedef void *(*Reallocator)(void *, std::size_t);
1434  // It's a shame this logic is essentially a duplicate of above, but the innards are different enough
1435  // we can't really reuse it.
1436  if (mode == "r" || mode == "rb") {
1437  fits_open_memfile(reinterpret_cast<fitsfile **>(&fptr), "unused", READONLY, &manager._ptr,
1438  &manager._len, 0, 0, // no reallocator or deltasize necessary for READONLY
1439  &status);
1440  } else if (mode == "w" || mode == "wb") {
1441  Reallocator reallocator = 0;
1442  if (manager._managed) reallocator = &std::realloc;
1443  fits_create_memfile(reinterpret_cast<fitsfile **>(&fptr), &manager._ptr, &manager._len, 0,
1444  reallocator, // use default deltasize
1445  &status);
1446  } else if (mode == "a" || mode == "ab") {
1447  Reallocator reallocator = 0;
1448  if (manager._managed) reallocator = &std::realloc;
1449  fits_open_memfile(reinterpret_cast<fitsfile **>(&fptr), "unused", READWRITE, &manager._ptr,
1450  &manager._len, 0, reallocator, &status);
1451  int nHdu = 0;
1452  fits_get_num_hdus(reinterpret_cast<fitsfile *>(fptr), &nHdu, &status);
1453  fits_movabs_hdu(reinterpret_cast<fitsfile *>(fptr), nHdu, NULL, &status);
1454  if ((behavior & AUTO_CHECK) && (behavior & AUTO_CLOSE) && (status) && (fptr)) {
1455  // We're about to throw an exception, and the destructor won't get called
1456  // because we're in the constructor, so cleanup here first.
1457  int tmpStatus = 0;
1458  fits_close_file(reinterpret_cast<fitsfile *>(fptr), &tmpStatus);
1459  }
1460  } else {
1461  throw LSST_EXCEPT(FitsError,
1462  (boost::format("Invalid mode '%s' given when opening memory file at '%s'") % mode %
1463  manager._ptr)
1464  .str());
1465  }
1466  if (behavior & AUTO_CHECK) {
1468  *this, boost::format("Opening memory file at '%s' with mode '%s'") % manager._ptr % mode);
1469  }
1470 }
1471 
1473  fits_close_file(reinterpret_cast<fitsfile *>(fptr), &status);
1474  fptr = nullptr;
1475 }
1476 
1480  auto combined = std::make_shared<daf::base::PropertyList>();
1481  bool const asScalar = true;
1482  for (auto const &name : first->getOrderedNames()) {
1483  auto const iscv = isCommentIsValid(*first, name);
1484  if (iscv.isComment) {
1485  if (iscv.isValid) {
1486  combined->add<std::string>(name, first->getArray<std::string>(name));
1487  }
1488  } else {
1489  combined->copy(name, first, name, asScalar);
1490  }
1491  }
1492  for (auto const &name : second->getOrderedNames()) {
1493  auto const iscv = isCommentIsValid(*second, name);
1494  if (iscv.isComment) {
1495  if (iscv.isValid) {
1496  combined->add<std::string>(name, second->getArray<std::string>(name));
1497  }
1498  } else {
1499  // `copy` will replace an item, even if has a different type, so no need to call `remove`
1500  combined->copy(name, second, name, asScalar);
1501  }
1502  }
1503  return combined;
1504 }
1505 
1508  fp.setHdu(hdu);
1509  return readMetadata(fp, strip);
1510 }
1511 
1514  fp.setHdu(hdu);
1515  return readMetadata(fp, strip);
1516 }
1517 
1519  auto metadata = std::make_shared<lsst::daf::base::PropertyList>();
1520  fitsfile.readMetadata(*metadata, strip);
1521  // if INHERIT=T, we want to also include header entries from the primary HDU
1522  if (fitsfile.getHdu() != 0 && metadata->exists("INHERIT")) {
1523  bool inherit = false;
1524  if (metadata->typeOf("INHERIT") == typeid(std::string)) {
1525  inherit = (metadata->get<std::string>("INHERIT") == "T");
1526  } else {
1527  inherit = metadata->get<bool>("INHERIT");
1528  }
1529  if (strip) metadata->remove("INHERIT");
1530  if (inherit) {
1531  fitsfile.setHdu(0);
1532  // Combine the metadata from the primary HDU with the metadata from the specified HDU,
1533  // with non-comment values from the specified HDU superseding those in the primary HDU
1534  // and comments from the specified HDU appended to comments from the primary HDU
1535  auto primaryHduMetadata = std::make_shared<daf::base::PropertyList>();
1536  fitsfile.readMetadata(*primaryHduMetadata, strip);
1537  metadata = combineMetadata(primaryHduMetadata, metadata);
1538  } else {
1539  // Purge invalid values
1540  auto const emptyMetadata = std::make_shared<lsst::daf::base::PropertyList>();
1541  metadata = combineMetadata(metadata, emptyMetadata);
1542  }
1543  }
1544  return metadata;
1545 }
1546 
1547 namespace {
1548 
1549 // RAII for moving the HDU
1550 class HduMove {
1551  public:
1552  HduMove() = delete;
1553  HduMove(HduMove const&) = delete;
1554 
1555  HduMove(Fits & fits, int hdu) : _fits(fits), _enabled(true) {
1556  _fits.setHdu(hdu);
1557  }
1558  ~HduMove() {
1559  if (!_enabled) {
1560  return;
1561  }
1562  int status = 0;
1563  std::swap(status, _fits.status);
1564  try {
1565  _fits.setHdu(0);
1566  } catch (...) {
1567  LOGLS_WARN("afw.fits",
1568  makeErrorMessage(_fits.fptr, _fits.status, "Failed to move back to PHU"));
1569  }
1570  std::swap(status, _fits.status);
1571  }
1572  void disable() { _enabled = false; }
1573 
1574  private:
1575  Fits & _fits; // FITS file we're working on
1576  bool _enabled; // Move back to PHU on destruction?
1577 };
1578 
1579 } // anonymous namespace
1580 
1582  auto fits = reinterpret_cast<fitsfile *>(fptr);
1583  if (getHdu() != 0 || countHdus() == 1) {
1584  return false; // Can't possibly be the PHU leading a compressed image
1585  }
1586  // Check NAXIS = 0
1587  int naxis;
1588  fits_get_img_dim(fits, &naxis, &status);
1589  if (behavior & AUTO_CHECK) {
1590  LSST_FITS_CHECK_STATUS(*this, "Checking NAXIS of PHU");
1591  }
1592  if (naxis != 0) {
1593  return false;
1594  }
1595  // Check first extension (and move back there when we're done if we're not compressed)
1596  HduMove move{*this, 1};
1597  bool isCompressed = fits_is_compressed_image(fits, &status);
1598  if (behavior & AUTO_CHECK) {
1599  LSST_FITS_CHECK_STATUS(*this, "Checking compression");
1600  }
1601  if (isCompressed) {
1602  move.disable();
1603  }
1604  return isCompressed;
1605 }
1606 
1607 
1609  : compression(
1610  fits::compressionAlgorithmFromString(config.get<std::string>("compression.algorithm")),
1611  std::vector<long>{config.getAsInt64("compression.columns"), config.getAsInt64("compression.rows")},
1612  config.getAsDouble("compression.quantizeLevel")
1613  ),
1614  scaling(
1615  fits::scalingAlgorithmFromString(config.get<std::string>("scaling.algorithm")),
1616  config.getAsInt("scaling.bitpix"),
1617  config.exists("scaling.maskPlanes") ? config.getArray<std::string>("scaling.maskPlanes") :
1619  config.getAsInt("scaling.seed"),
1620  config.getAsDouble("scaling.quantizeLevel"),
1621  config.getAsDouble("scaling.quantizePad"),
1622  config.get<bool>("scaling.fuzz"),
1623  config.getAsDouble("scaling.bscale"),
1624  config.getAsDouble("scaling.bzero")
1625  )
1626 {}
1627 
1628 
1629 namespace {
1630 
1631 template <typename T>
1632 void validateEntry(
1633  daf::base::PropertySet & output,
1634  daf::base::PropertySet const& input,
1635  std::string const& name,
1636  T defaultValue
1637 ) {
1638  output.add(name, input.get<T>(name, defaultValue));
1639 }
1640 
1641 
1642 template <typename T>
1643 void validateEntry(
1644  daf::base::PropertySet & output,
1645  daf::base::PropertySet const& input,
1646  std::string const& name,
1647  std::vector<T> defaultValue
1648 ) {
1649  output.add(name, input.exists(name) ? input.getArray<T>(name) : defaultValue);
1650 }
1651 
1652 } // anonymous namespace
1653 
1654 
1657  auto validated = std::make_shared<daf::base::PropertySet>();
1658 
1659  validateEntry(*validated, config, "compression.algorithm", std::string("NONE"));
1660  validateEntry(*validated, config, "compression.columns", 0);
1661  validateEntry(*validated, config, "compression.rows", 1);
1662  validateEntry(*validated, config, "compression.quantizeLevel", 0.0);
1663 
1664  validateEntry(*validated, config, "scaling.algorithm", std::string("NONE"));
1665  validateEntry(*validated, config, "scaling.bitpix", 0);
1666  validateEntry(*validated, config, "scaling.maskPlanes", std::vector<std::string>{"NO_DATA"});
1667  validateEntry(*validated, config, "scaling.seed", 1);
1668  validateEntry(*validated, config, "scaling.quantizeLevel", 5.0);
1669  validateEntry(*validated, config, "scaling.quantizePad", 10.0);
1670  validateEntry(*validated, config, "scaling.fuzz", true);
1671  validateEntry(*validated, config, "scaling.bscale", 1.0);
1672  validateEntry(*validated, config, "scaling.bzero", 0.0);
1673 
1674  // Check for additional entries that we don't support (e.g., from typos)
1675  for (auto const& name : config.names(false)) {
1676  if (!validated->exists(name)) {
1678  os << "Invalid image write option: " << name;
1680  }
1681  }
1682 
1683  return validated;
1684 }
1685 
1686 
1687 #define INSTANTIATE_KEY_OPS(r, data, T) \
1688  template void Fits::updateKey(std::string const &, T const &, std::string const &); \
1689  template void Fits::writeKey(std::string const &, T const &, std::string const &); \
1690  template void Fits::updateKey(std::string const &, T const &); \
1691  template void Fits::writeKey(std::string const &, T const &); \
1692  template void Fits::updateColumnKey(std::string const &, int, T const &, std::string const &); \
1693  template void Fits::writeColumnKey(std::string const &, int, T const &, std::string const &); \
1694  template void Fits::updateColumnKey(std::string const &, int, T const &); \
1695  template void Fits::writeColumnKey(std::string const &, int, T const &); \
1696  template void Fits::readKey(std::string const &, T &);
1697 
1698 #define INSTANTIATE_IMAGE_OPS(r, data, T) \
1699  template void Fits::writeImageImpl(T const *, int); \
1700  template void Fits::writeImage(image::ImageBase<T> const&, \
1701  ImageWriteOptions const&, \
1702  std::shared_ptr<daf::base::PropertySet const>, \
1703  std::shared_ptr<image::Mask<image::MaskPixel> const>); \
1704  template void Fits::readImageImpl(int, T *, long *, long *, long *); \
1705  template bool Fits::checkImageType<T>(); \
1706  template int getBitPix<T>();
1707 
1708 #define INSTANTIATE_TABLE_OPS(r, data, T) \
1709  template int Fits::addColumn<T>(std::string const &ttype, int size); \
1710  template int Fits::addColumn<T>(std::string const &ttype, int size, std::string const &comment);
1711 #define INSTANTIATE_TABLE_ARRAY_OPS(r, data, T) \
1712  template void Fits::writeTableArray(std::size_t row, int col, int nElements, T const *value); \
1713  template void Fits::readTableArray(std::size_t row, int col, int nElements, T *value);
1714 
1715 // ----------------------------------------------------------------------------------------------------------
1716 // ---- Explicit instantiation ------------------------------------------------------------------------------
1717 // ----------------------------------------------------------------------------------------------------------
1718 
1719 #define KEY_TYPES \
1720  (bool)(unsigned char)(short)(unsigned short)(int)(unsigned int)(long)(unsigned long)(LONGLONG)( \
1721  float)(double)(std::complex<float>)(std::complex<double>)(std::string)
1722 
1723 #define COLUMN_TYPES \
1724  (bool)(std::string)(std::uint8_t)(std::int16_t)(std::uint16_t)(std::int32_t)(std::uint32_t)( \
1725  std::int64_t)(float)(double)(geom::Angle)(std::complex<float>)(std::complex<double>)
1726 
1727 #define COLUMN_ARRAY_TYPES \
1728  (bool)(char)(std::uint8_t)(std::int16_t)(std::uint16_t)(std::int32_t)(std::uint32_t)(std::int64_t)( \
1729  float)(double)(geom::Angle)(std::complex<float>)(std::complex<double>)
1730 
1731 #define IMAGE_TYPES \
1732  (unsigned char)(short)(unsigned short)(int)(unsigned int)(std::int64_t)(std::uint64_t)(float)(double)
1733 
1738 }
1739 }
1740 } // namespace lsst::afw::fits
#define LOGLS_WARN(logger, message)
#define INSTANTIATE_TABLE_OPS(r, data, T)
Definition: fits.cc:1708
#define INSTANTIATE_KEY_OPS(r, data, T)
Definition: fits.cc:1687
int getImageDim()
Return the number of dimensions in the current HDU.
Definition: fits.cc:1300
std::size_t countRows()
Return the number of row in a table.
Definition: fits.cc:1033
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.
Definition: fits.cc:1477
std::string getFileName() const
Return the file name associated with the FITS object or "<unknown>" if there is none.
Definition: fits.cc:462
void forEachKey(HeaderIterationFunctor &functor)
Call a polymorphic functor for every key in the header.
Definition: fits.cc:739
T empty(T... args)
char * data
Definition: BaseTable.cc:204
bool isComment
Definition: fits.cc:362
lsst::afw::geom::Angle Angle
Definition: misc.h:33
ImageCompressionOptions getImageCompression()
Return the current image compression settings.
Definition: fits.cc:1338
ImageCompressionOptions compression
Options controlling compression.
Definition: fits.h:221
T find_first_not_of(T... args)
afw::table::Key< afw::table::Array< MaskPixelT > > mask
void writeMetadata(daf::base::PropertySet const &metadata)
Read a FITS header into a PropertySet or PropertyList.
Definition: fits.cc:969
#define LSST_FITS_CHECK_STATUS(fitsObj,...)
Throw a FitsError exception if the status of the given Fits object is nonzero.
Definition: fits.h:110
geom::Box2I getBBox(ImageOrigin origin=PARENT) const
Definition: ImageBase.h:448
std::vector< T > getArray(std::string const &name) const
int compressionAlgorithmToCfitsio(ImageCompressionOptions::CompressionAlgorithm algorithm)
Convert ImageCompressionOptions::CompressionAlgorithm to cfitsio.
T swap(T... args)
T front(T... args)
T get(std::string const &name) const
long blank
Value for integer images indicating non-finite values.
void readKey(std::string const &key, T &value)
Read a FITS header key into the given reference.
Definition: fits.cc:732
int bitpix
Bits per pixel; negative means floating-point: 8,16,32,64,-32,-64.
#define IMAGE_TYPES
Definition: fits.cc:1731
std::vector< std::string > paramNames(bool topLevelOnly=true) const
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.
Definition: fits.cc:649
std::shared_ptr< daf::base::PropertyList > createTrivialWcsMetadata(std::string const &wcsName, geom::Point2I const &xy0)
Definition: wcsUtils.cc:51
Options for writing an image to FITS.
Definition: fits.h:220
std::string const & getComment(std::string const &name) const
def scale(algorithm, min, max=None, frame=None)
Definition: ds9.py:115
T to_string(T... args)
int getBitPix()
Return the cfitsio integer BITPIX code for the given data type.
Definition: fits.cc:454
void readTableScalar(std::size_t row, int col, T &value)
Read an array scalar from a binary table.
Definition: fits.h:593
bool checkImageType()
Return true if the current HDU is compatible with the given pixel type.
Definition: fits.cc:1313
#define INSTANTIATE_TABLE_ARRAY_OPS(r, data, T)
Definition: fits.cc:1711
STL namespace.
bool strip
Definition: fits.cc:817
STL class.
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.
Definition: fits.cc:657
T end(T... args)
CompressionAlgorithm
Compression algorithms.
T free(T... args)
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
long getTableArraySize(int col)
Return the size of an array column.
Definition: fits.cc:1091
FITS BITPIX header value by C++ type.
void closeFile()
Close a FITS file.
Definition: fits.cc:1472
int seed
Seed for random number generator when fuzzing.
Fits * fits
Definition: FitsWriter.cc:90
void createEmpty()
Create an empty image HDU with NAXIS=0 at the end of the file.
Definition: fits.cc:1114
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.
Definition: fits.cc:617
STL class.
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
Tiles tiles
Tile size; a dimension with 0 means infinite (e.g., to specify one row: 0,1)
T push_back(T... args)
Options for tile compression of image pixels.
A base class for image defects.
int end
Represent a 2-dimensional array of bitmask pixels.
Definition: Mask.h:84
int64_t getAsInt64(std::string const &name) const
Lifetime-management for memory that goes into FITS memory files.
Definition: fits.h:120
double bzero
Zero-point to apply when reading from FITS.
std::size_t addRows(std::size_t nRows)
Append rows to a table, and return the index of the first new row.
Definition: fits.cc:1023
std::vector< std::string > names(bool topLevelOnly=true) const
std::vector< std::string > getOrderedNames(void) const
ImageCompressionOptions::CompressionAlgorithm compressionAlgorithmFromString(std::string const &name)
Interpret compression algorithm expressed in string.
Fits()
Default constructor; set all data members to 0.
Definition: fits.h:607
T erase(T... args)
#define INSTANTIATE_IMAGE_OPS(r, data, T)
Definition: fits.cc:1698
Key< U > key
Definition: Schema.cc:280
T str(T... args)
T isfinite(T... args)
bool exists(std::string const &name) const
ndarray::Array< long, 1, 1 > Tiles
void createTable()
Create a new binary table extension.
Definition: fits.cc:991
double bscale
Scale to apply when reading from FITS.
T infinity(T... args)
std::unique_ptr< SchemaItem< U > > result
Definition: Schema.cc:194
void setHdu(int hdu, bool relative=false)
Set the current HDU.
Definition: fits.cc:477
T count(T... args)
T find_last_not_of(T... args)
BOOST_PP_SEQ_FOR_EACH(INSTANTIATE_COLUMNVIEW_SCALAR, _, BOOST_PP_TUPLE_TO_SEQ(AFW_TABLE_SCALAR_FIELD_TYPE_N, AFW_TABLE_SCALAR_FIELD_TYPE_TUPLE)) BOOST_PP_SEQ_FOR_EACH(INSTANTIATE_COLUMNVIEW_ARRAY
T find(T... args)
T size(T... args)
STL class.
#define LSST_EXCEPT(type,...)
T realloc(T... args)
T name(T... args)
#define COLUMN_TYPES
Definition: fits.cc:1723
T malloc(T... args)
ImageScalingOptions scaling
Options controlling scaling.
Definition: fits.h:222
static std::shared_ptr< daf::base::PropertySet > validate(daf::base::PropertySet const &config)
Validate a PropertySet.
Definition: fits.cc:1656
bool checkCompressedImagePhu()
Go to the first image header in the FITS file.
Definition: fits.cc:1581
void setAllowImageCompression(bool allow)
Definition: fits.cc:1391
T c_str(T... args)
float quantizeLevel
quantization level: 0.0 = none requires use of GZIP or GZIP_SHUFFLE
void writeTableArray(std::size_t row, int col, int nElements, T const *value)
Write an array value to a binary table.
Definition: fits.cc:1043
void reset()
Return the manager to the same state it would be if default-constructed.
Definition: fits.cc:439
CompressionAlgorithm algorithm
Compresion algorithm to use.
void readTableArray(std::size_t row, int col, int nElements, T *value)
Read an array value from a binary table.
Definition: fits.cc:1066
std::string prefix
Definition: SchemaMapper.cc:79
T isnan(T... args)
T substr(T... args)
ImageCompressionOptions::CompressionAlgorithm compressionAlgorithmFromCfitsio(int cfitsio)
Convert compression algorithm from cfitsio to ImageCompressionOptions::CompressionAlgorithm.
ImageScale determine(image::ImageBase< T > const &image, std::shared_ptr< image::Mask< image::MaskPixel > const > mask=nullptr) const
Determine the scaling for a particular image.
void setImageCompression(ImageCompressionOptions const &options)
Set compression options for writing FITS images.
Definition: fits.cc:1362
daf::base::PropertyList * list
Definition: fits.cc:819
T quiet_NaN(T... args)
void writeKey(std::string const &key, T const &value, std::string const &comment)
Add a FITS header key to the bottom of the header.
Definition: fits.cc:625
bool fuzz
Fuzz the values when quantising floating-point values?
#define COLUMN_ARRAY_TYPES
Definition: fits.cc:1727
bool getAllowImageCompression()
Definition: fits.cc:1395
int getHdu()
Return the current HDU (0-indexed; 0 is the Primary HDU).
Definition: fits.cc:471
void add(std::string const &name, T const &value)
void writeImage(ndarray::Array< T const, N, C > const &array)
Write an ndarray::Array to a FITS image HDU.
Definition: fits.h:478
std::ostream * os
Definition: Schema.cc:736
bool isValid
Definition: fits.cc:363
int addColumn(std::string const &ttype, int size, std::string const &comment)
Add a column to a table.
Definition: fits.cc:1014
std::string makeErrorMessage(std::string const &fileName="", int status=0, std::string const &msg="")
Return an error message reflecting FITS I/O errors.
Definition: fits.cc:390
#define KEY_TYPES
Definition: fits.cc:1719
ImageScalingOptions::ScalingAlgorithm scalingAlgorithmFromString(std::string const &name)
Interpret scaling algorithm expressed in string.
std::string const wcsNameForXY0
Definition: ImageBase.h:74
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
void readMetadata(daf::base::PropertySet &metadata, bool strip=false)
Read a FITS header into a PropertySet or PropertyList.
Definition: fits.cc:961
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.
Definition: fits.cc:421
T compare(T... args)
T reserve(T... args)
const int DEFAULT_HDU
Specify that the default HDU should be read.
Definition: fitsDefaults.h:18
std::shared_ptr< detail::PixelArrayBase > toFits(ndarray::Array< T const, 2, 2 > const &image, bool forceNonfiniteRemoval, bool fuzz=true, ndarray::Array< long, 1 > const &tiles=ndarray::Array< long, 1, 1 >(), int seed=1) const
Convert to an array of pixel values to write to FITS.
ImageWriteOptions(image::Image< T > const &image)
Construct with default options for images.
Definition: fits.h:226
int countHdus()
Return the number of HDUs in the file.
Definition: fits.cc:498
Scale to apply to image.
geom::Point2I getXY0() const
Return the image&#39;s origin.
Definition: ImageBase.h:326