lsst.afw  16.0-10-gd1b3a1c94
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/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 
159 StringStartSet const ignoreKeyStarts{// FITS core keywords
160  "NAXIS", "TZERO", "TSCAL",
161  // FITS compression keywords
162  "ZNAXIS", "ZTILE", "ZNAME", "ZVAL"};
163 
169 StringStartSet const ignoreKeyStartsWrite{"TFORM", "TTYPE"};
170 
171 // Strip leading and trailing single quotes and whitespace from a string.
172 std::string strip(std::string const &s) {
173  if (s.empty()) return s;
174  std::size_t i1 = s.find_first_not_of(" '");
175  std::size_t i2 = s.find_last_not_of(" '");
176  return s.substr(i1, (i1 == std::string::npos) ? 0 : 1 + i2 - i1);
177 }
178 
179 // ---- FITS binary table format codes for various C++ types. -----------------------------------------------
180 
181 char getFormatCode(bool *) { return 'X'; }
182 char getFormatCode(std::string *) { return 'A'; }
183 char getFormatCode(std::int8_t *) { return 'S'; }
184 char getFormatCode(std::uint8_t *) { return 'B'; }
185 char getFormatCode(std::int16_t *) { return 'I'; }
186 char getFormatCode(std::uint16_t *) { return 'U'; }
187 char getFormatCode(std::int32_t *) { return 'J'; }
188 char getFormatCode(std::uint32_t *) { return 'V'; }
189 char getFormatCode(std::int64_t *) { return 'K'; }
190 char getFormatCode(float *) { return 'E'; }
191 char getFormatCode(double *) { return 'D'; }
192 char getFormatCode(std::complex<float> *) { return 'C'; }
193 char getFormatCode(std::complex<double> *) { return 'M'; }
194 char getFormatCode(lsst::geom::Angle *) { return 'D'; }
195 
196 // ---- Create a TFORM value for the given type and size ----------------------------------------------------
197 
198 template <typename T>
199 std::string makeColumnFormat(int size = 1) {
200  if (size > 0) {
201  return (boost::format("%d%c") % size % getFormatCode((T *)0)).str();
202  } else if (size < 0) {
203  // variable length, max size given as -size
204  return (boost::format("1Q%c(%d)") % getFormatCode((T *)0) % (-size)).str();
205  } else {
206  // variable length, max size unknown
207  return (boost::format("1Q%c") % getFormatCode((T *)0)).str();
208  }
209 }
210 
211 // ---- Traits class to get cfitsio type constants from templates -------------------------------------------
212 
213 template <typename T>
214 struct FitsType;
215 
216 template <>
217 struct FitsType<bool> {
218  static int const CONSTANT = TLOGICAL;
219 };
220 template <>
221 struct FitsType<char> {
222  static int const CONSTANT = TSTRING;
223 };
224 template <>
225 struct FitsType<signed char> {
226  static int const CONSTANT = TSBYTE;
227 };
228 template <>
229 struct FitsType<unsigned char> {
230  static int const CONSTANT = TBYTE;
231 };
232 template <>
233 struct FitsType<short> {
234  static int const CONSTANT = TSHORT;
235 };
236 template <>
237 struct FitsType<unsigned short> {
238  static int const CONSTANT = TUSHORT;
239 };
240 template <>
241 struct FitsType<int> {
242  static int const CONSTANT = TINT;
243 };
244 template <>
245 struct FitsType<unsigned int> {
246  static int const CONSTANT = TUINT;
247 };
248 template <>
249 struct FitsType<long> {
250  static int const CONSTANT = TLONG;
251 };
252 template <>
253 struct FitsType<unsigned long> {
254  static int const CONSTANT = TULONG;
255 };
256 template <>
257 struct FitsType<long long> {
258  static int const CONSTANT = TLONGLONG;
259 };
260 template <>
261 struct FitsType<unsigned long long> {
262  static int const CONSTANT = TLONGLONG;
263 };
264 template <>
265 struct FitsType<float> {
266  static int const CONSTANT = TFLOAT;
267 };
268 template <>
269 struct FitsType<double> {
270  static int const CONSTANT = TDOUBLE;
271 };
272 template <>
273 struct FitsType<lsst::geom::Angle> {
274  static int const CONSTANT = TDOUBLE;
275 };
276 template <>
277 struct FitsType<std::complex<float> > {
278  static int const CONSTANT = TCOMPLEX;
279 };
280 template <>
281 struct FitsType<std::complex<double> > {
282  static int const CONSTANT = TDBLCOMPLEX;
283 };
284 
285 // We use TBIT when writing booleans to table cells, but TLOGICAL in headers.
286 template <typename T>
287 struct FitsTableType : public FitsType<T> {};
288 template <>
289 struct FitsTableType<bool> {
290  static int const CONSTANT = TBIT;
291 };
292 
293 template <typename T>
294 struct FitsBitPix;
295 
296 template <>
297 struct FitsBitPix<unsigned char> {
298  static int const CONSTANT = BYTE_IMG;
299 };
300 template <>
301 struct FitsBitPix<short> {
302  static int const CONSTANT = SHORT_IMG;
303 };
304 template <>
305 struct FitsBitPix<unsigned short> {
306  static int const CONSTANT = USHORT_IMG;
307 };
308 template <>
309 struct FitsBitPix<int> {
310  static int const CONSTANT = LONG_IMG;
311 }; // not a typo!
312 template <>
313 struct FitsBitPix<unsigned int> {
314  static int const CONSTANT = ULONG_IMG;
315 };
316 template <>
317 struct FitsBitPix<std::int64_t> {
318  static int const CONSTANT = LONGLONG_IMG;
319 };
320 template <>
321 struct FitsBitPix<std::uint64_t> {
322  static int const CONSTANT = LONGLONG_IMG;
323 };
324 template <>
325 struct FitsBitPix<float> {
326  static int const CONSTANT = FLOAT_IMG;
327 };
328 template <>
329 struct FitsBitPix<double> {
330  static int const CONSTANT = DOUBLE_IMG;
331 };
332 
333 static bool allowImageCompression = true;
334 
335 int fitsTypeForBitpix(int bitpix) {
336  switch (bitpix) {
337  case 8:
338  return TBYTE;
339  case 16:
340  return TSHORT;
341  case 32:
342  return TINT;
343  case 64:
344  return TLONGLONG;
345  case -32:
346  return TFLOAT;
347  case -64:
348  return TDOUBLE;
349  default:
351  os << "Invalid bitpix value: " << bitpix;
352  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError, os.str());
353  }
354 }
355 
356 /*
357  * Information about one item of metadata: is a comment? is valid?
358  *
359  * See isCommentIsValid for more information.
360  */
361 struct ItemInfo {
362  ItemInfo(bool isComment, bool isValid) : isComment(isComment), isValid(isValid) {}
363  bool isComment;
364  bool isValid;
365 };
366 
367 /*
368  * Is an item a commnt (or history) and is it usable in a FITS header?
369  *
370  * For an item to be valid:
371  * - If name is COMMENT or HISTORY then the item must be of type std::string
372  * - All other items are always valid
373  */
374 ItemInfo isCommentIsValid(daf::base::PropertyList const &pl, std::string const &name) {
375  if (!pl.exists(name)) {
376  return ItemInfo(false, false);
377  }
378  std::type_info const &type = pl.typeOf(name);
379  if ((name == "COMMENT") || (name == "HISTORY")) {
380  return ItemInfo(true, type == typeid(std::string));
381  }
382  return ItemInfo(false, true);
383 }
384 
385 } // namespace
386 
387 // ----------------------------------------------------------------------------------------------------------
388 // ---- Implementations for stuff in fits.h -----------------------------------------------------------------
389 // ----------------------------------------------------------------------------------------------------------
390 
391 std::string makeErrorMessage(std::string const &fileName, int status, std::string const &msg) {
393  os << "cfitsio error";
394  if (fileName != "") {
395  os << " (" << fileName << ")";
396  }
397  if (status != 0) {
398  char fitsErrMsg[FLEN_ERRMSG];
399  fits_get_errstatus(status, fitsErrMsg);
400  os << ": " << fitsErrMsg << " (" << status << ")";
401  }
402  if (msg != "") {
403  os << " : " << msg;
404  }
405  os << "\ncfitsio error stack:\n";
406  char cfitsioMsg[FLEN_ERRMSG];
407  while (fits_read_errmsg(cfitsioMsg) != 0) {
408  os << " " << cfitsioMsg << "\n";
409  }
410  return os.str();
411 }
412 
413 std::string makeErrorMessage(void *fptr, int status, std::string const &msg) {
414  std::string fileName = "";
415  fitsfile *fd = reinterpret_cast<fitsfile *>(fptr);
416  if (fd != 0 && fd->Fptr != 0 && fd->Fptr->filename != 0) {
417  fileName = fd->Fptr->filename;
418  }
419  return makeErrorMessage(fileName, status, msg);
420 }
421 
423  std::set<std::string> const &excludeNames) {
424  daf::base::PropertyList const *pl = dynamic_cast<daf::base::PropertyList const *>(&metadata);
425  std::vector<std::string> allParamNames;
426  if (pl) {
427  allParamNames = pl->getOrderedNames();
428  } else {
429  allParamNames = metadata.paramNames(false);
430  }
431  std::vector<std::string> desiredParamNames;
432  for (auto const &name : allParamNames) {
433  if (excludeNames.count(name) == 0) {
434  desiredParamNames.push_back(name);
435  }
436  }
437  return makeLimitedFitsHeaderImpl(desiredParamNames, metadata);
438 }
439 
441  if (_managed) std::free(_ptr);
442  _ptr = 0;
443  _len = 0;
444  _managed = true;
445 }
446 
448  reset();
449  _ptr = std::malloc(len);
450  _len = len;
451  _managed = true;
452 }
453 
454 template <typename T>
455 int getBitPix() {
456  return FitsBitPix<T>::CONSTANT;
457 }
458 
459 // ----------------------------------------------------------------------------------------------------------
460 // ---- Implementations for Fits class ----------------------------------------------------------------------
461 // ----------------------------------------------------------------------------------------------------------
462 
464  std::string fileName = "<unknown>";
465  fitsfile *fd = reinterpret_cast<fitsfile *>(fptr);
466  if (fd != 0 && fd->Fptr != 0 && fd->Fptr->filename != 0) {
467  fileName = fd->Fptr->filename;
468  }
469  return fileName;
470 }
471 
473  int n = 1;
474  fits_get_hdu_num(reinterpret_cast<fitsfile *>(fptr), &n);
475  return n - 1;
476 }
477 
478 void Fits::setHdu(int hdu, bool relative) {
479  if (relative) {
480  fits_movrel_hdu(reinterpret_cast<fitsfile *>(fptr), hdu, 0, &status);
481  if (behavior & AUTO_CHECK) {
482  LSST_FITS_CHECK_STATUS(*this, boost::format("Incrementing HDU by %d") % hdu);
483  }
484  } else {
485  if (hdu != DEFAULT_HDU) {
486  fits_movabs_hdu(reinterpret_cast<fitsfile *>(fptr), hdu + 1, 0, &status);
487  }
488  if (hdu == DEFAULT_HDU && getHdu() == 0 && getImageDim() == 0) {
489  // want a silent failure here
490  int tmpStatus = status;
491  fits_movrel_hdu(reinterpret_cast<fitsfile *>(fptr), 1, 0, &tmpStatus);
492  }
493  if (behavior & AUTO_CHECK) {
494  LSST_FITS_CHECK_STATUS(*this, boost::format("Moving to HDU %d") % hdu);
495  }
496  }
497 }
498 
500  int n = 0;
501  fits_get_num_hdus(reinterpret_cast<fitsfile *>(fptr), &n, &status);
502  if (behavior & AUTO_CHECK) {
503  LSST_FITS_CHECK_STATUS(*this, "Getting number of HDUs in file.");
504  }
505  return n;
506 }
507 
508 // ---- Writing and updating header keys --------------------------------------------------------------------
509 
510 namespace {
511 
512 // Impl functions in the anonymous namespace do special handling for strings, bools, and IEEE fp values.
513 
520 std::string nonFiniteDoubleToString(double value) {
521  if (std::isfinite(value)) {
522  return "";
523  }
524  if (std::isnan(value)) {
525  return "NAN";
526  }
527  if (value < 0) {
528  return "-INFINITY";
529  }
530  return "+INFINITY";
531 }
532 
538 double stringToNonFiniteDouble(std::string const &value) {
539  if (value == "NAN") {
541  }
542  if (value == "+INFINITY") {
544  }
545  if (value == "-INFINITY") {
547  }
548  return 0;
549 }
550 
551 template <typename T>
552 void updateKeyImpl(Fits &fits, char const *key, T const &value, char const *comment) {
553  fits_update_key(reinterpret_cast<fitsfile *>(fits.fptr), FitsType<T>::CONSTANT, const_cast<char *>(key),
554  const_cast<T *>(&value), const_cast<char *>(comment), &fits.status);
555 }
556 
557 void updateKeyImpl(Fits &fits, char const *key, std::string const &value, char const *comment) {
558  fits_update_key_longstr(reinterpret_cast<fitsfile *>(fits.fptr), const_cast<char *>(key),
559  const_cast<char *>(value.c_str()), const_cast<char *>(comment), &fits.status);
560 }
561 
562 void updateKeyImpl(Fits &fits, char const *key, bool const &value, char const *comment) {
563  int v = value;
564  fits_update_key(reinterpret_cast<fitsfile *>(fits.fptr), TLOGICAL, const_cast<char *>(key), &v,
565  const_cast<char *>(comment), &fits.status);
566 }
567 
568 void updateKeyImpl(Fits &fits, char const *key, double const &value, char const *comment) {
569  std::string strValue = nonFiniteDoubleToString(value);
570  if (!strValue.empty()) {
571  updateKeyImpl(fits, key, strValue, comment);
572  } else {
573  fits_update_key(reinterpret_cast<fitsfile *>(fits.fptr), FitsType<double>::CONSTANT,
574  const_cast<char *>(key), const_cast<double *>(&value), const_cast<char *>(comment),
575  &fits.status);
576  }
577 }
578 
579 template <typename T>
580 void writeKeyImpl(Fits &fits, char const *key, T const &value, char const *comment) {
581  fits_write_key(reinterpret_cast<fitsfile *>(fits.fptr), FitsType<T>::CONSTANT, const_cast<char *>(key),
582  const_cast<T *>(&value), const_cast<char *>(comment), &fits.status);
583 }
584 
585 void writeKeyImpl(Fits &fits, char const *key, std::string const &value, char const *comment) {
586  if (strncmp(key, "COMMENT", 7) == 0) {
587  fits_write_comment(reinterpret_cast<fitsfile *>(fits.fptr), const_cast<char *>(value.c_str()),
588  &fits.status);
589  } else if (strncmp(key, "HISTORY", 7) == 0) {
590  fits_write_history(reinterpret_cast<fitsfile *>(fits.fptr), const_cast<char *>(value.c_str()),
591  &fits.status);
592  } else {
593  fits_write_key_longstr(reinterpret_cast<fitsfile *>(fits.fptr), const_cast<char *>(key),
594  const_cast<char *>(value.c_str()), const_cast<char *>(comment), &fits.status);
595  }
596 }
597 
598 void writeKeyImpl(Fits &fits, char const *key, bool const &value, char const *comment) {
599  int v = value;
600  fits_write_key(reinterpret_cast<fitsfile *>(fits.fptr), TLOGICAL, const_cast<char *>(key), &v,
601  const_cast<char *>(comment), &fits.status);
602 }
603 
604 void writeKeyImpl(Fits &fits, char const *key, double const &value, char const *comment) {
605  std::string strValue = nonFiniteDoubleToString(value);
606  if (!strValue.empty()) {
607  writeKeyImpl(fits, key, strValue, comment);
608  } else {
609  fits_write_key(reinterpret_cast<fitsfile *>(fits.fptr), FitsType<double>::CONSTANT,
610  const_cast<char *>(key), const_cast<double *>(&value), const_cast<char *>(comment),
611  &fits.status);
612  }
613 }
614 
615 } // namespace
616 
617 template <typename T>
618 void Fits::updateKey(std::string const &key, T const &value, std::string const &comment) {
619  updateKeyImpl(*this, key.c_str(), value, comment.c_str());
620  if (behavior & AUTO_CHECK) {
621  LSST_FITS_CHECK_STATUS(*this, boost::format("Updating key '%s': '%s'") % key % value);
622  }
623 }
624 
625 template <typename T>
626 void Fits::writeKey(std::string const &key, T const &value, std::string const &comment) {
627  writeKeyImpl(*this, key.c_str(), value, comment.c_str());
628  if (behavior & AUTO_CHECK) {
629  LSST_FITS_CHECK_STATUS(*this, boost::format("Writing key '%s': '%s'") % key % value);
630  }
631 }
632 
633 template <typename T>
634 void Fits::updateKey(std::string const &key, T const &value) {
635  updateKeyImpl(*this, key.c_str(), value, 0);
636  if (behavior & AUTO_CHECK) {
637  LSST_FITS_CHECK_STATUS(*this, boost::format("Updating key '%s': '%s'") % key % value);
638  }
639 }
640 
641 template <typename T>
642 void Fits::writeKey(std::string const &key, T const &value) {
643  writeKeyImpl(*this, key.c_str(), value, 0);
644  if (behavior & AUTO_CHECK) {
645  LSST_FITS_CHECK_STATUS(*this, boost::format("Writing key '%s': '%s'") % key % value);
646  }
647 }
648 
649 template <typename T>
650 void Fits::updateColumnKey(std::string const &prefix, int n, T const &value, std::string const &comment) {
651  updateKey((boost::format("%s%d") % prefix % (n + 1)).str(), value, comment);
652  if (behavior & AUTO_CHECK) {
653  LSST_FITS_CHECK_STATUS(*this, boost::format("Updating key '%s%d': '%s'") % prefix % (n + 1) % value);
654  }
655 }
656 
657 template <typename T>
658 void Fits::writeColumnKey(std::string const &prefix, int n, T const &value, std::string const &comment) {
659  writeKey((boost::format("%s%d") % prefix % (n + 1)).str(), value, comment);
660  if (behavior & AUTO_CHECK) {
661  LSST_FITS_CHECK_STATUS(*this, boost::format("Writing key '%s%d': '%s'") % prefix % (n + 1) % value);
662  }
663 }
664 
665 template <typename T>
666 void Fits::updateColumnKey(std::string const &prefix, int n, T const &value) {
667  updateKey((boost::format("%s%d") % prefix % (n + 1)).str(), value);
668  if (behavior & AUTO_CHECK) {
669  LSST_FITS_CHECK_STATUS(*this, boost::format("Updating key '%s%d': '%s'") % prefix % (n + 1) % value);
670  }
671 }
672 
673 template <typename T>
674 void Fits::writeColumnKey(std::string const &prefix, int n, T const &value) {
675  writeKey((boost::format("%s%d") % prefix % (n + 1)).str(), value);
676  if (behavior & AUTO_CHECK) {
677  LSST_FITS_CHECK_STATUS(*this, boost::format("Writing key '%s%d': '%s'") % prefix % (n + 1) % value);
678  }
679 }
680 
681 // ---- Reading header keys ---------------------------------------------------------------------------------
682 
683 namespace {
684 
685 template <typename T>
686 void readKeyImpl(Fits &fits, char const *key, T &value) {
687  fits_read_key(reinterpret_cast<fitsfile *>(fits.fptr), FitsType<T>::CONSTANT, const_cast<char *>(key),
688  &value, 0, &fits.status);
689 }
690 
691 void readKeyImpl(Fits &fits, char const *key, std::string &value) {
692  char *buf = 0;
693  fits_read_key_longstr(reinterpret_cast<fitsfile *>(fits.fptr), const_cast<char *>(key), &buf, 0,
694  &fits.status);
695  if (buf) {
696  value = strip(buf);
697  free(buf);
698  }
699 }
700 
701 void readKeyImpl(Fits &fits, char const *key, double &value) {
702  // We need to check for the possibility that the value is a special string (for NAN, +/-Inf).
703  // If a quote mark (') is present then it's a string.
704 
705  char buf[FLEN_VALUE];
706  fits_read_keyword(reinterpret_cast<fitsfile *>(fits.fptr), const_cast<char *>(key), buf, 0, &fits.status);
707  if (fits.status != 0) {
708  return;
709  }
710  if (std::string(buf).find('\'') != std::string::npos) {
711  std::string unquoted;
712  readKeyImpl(fits, key, unquoted); // Let someone else remove quotes and whitespace
713  if (fits.status != 0) {
714  return;
715  }
716  value = stringToNonFiniteDouble(unquoted);
717  if (value == 0) {
718  throw LSST_EXCEPT(
720  (boost::format("Unrecognised string value for keyword '%s' when parsing as double: %s") %
721  key % unquoted)
722  .str());
723  }
724  } else {
725  fits_read_key(reinterpret_cast<fitsfile *>(fits.fptr), FitsType<double>::CONSTANT,
726  const_cast<char *>(key), &value, 0, &fits.status);
727  }
728 }
729 
730 } // namespace
731 
732 template <typename T>
733 void Fits::readKey(std::string const &key, T &value) {
734  readKeyImpl(*this, key.c_str(), value);
735  if (behavior & AUTO_CHECK) {
736  LSST_FITS_CHECK_STATUS(*this, boost::format("Reading key '%s'") % key);
737  }
738 }
739 
741  char key[81]; // allow for terminating NUL
742  char value[81];
743  char comment[81];
744  int nKeys = 0;
745  fits_get_hdrspace(reinterpret_cast<fitsfile *>(fptr), &nKeys, 0, &status);
746  std::string keyStr;
747  std::string valueStr;
748  std::string commentStr;
749  int i = 1;
750  while (i <= nKeys) {
751  fits_read_keyn(reinterpret_cast<fitsfile *>(fptr), i, key, value, comment, &status);
752  keyStr = key;
753  valueStr = value;
754  commentStr = comment;
755  ++i;
756  while (valueStr.size() > 2 && valueStr[valueStr.size() - 2] == '&' && i <= nKeys) {
757  // we're using key to hold the entire record here; the actual key is safe in keyStr
758  fits_read_record(reinterpret_cast<fitsfile *>(fptr), i, key, &status);
759  if (strncmp(key, "CONTINUE", 8) != 0) {
760  // require both trailing '&' and CONTINUE to invoke long-string handling
761  break;
762  }
763  std::string card = key;
764  valueStr.erase(valueStr.size() - 2);
765  std::size_t firstQuote = card.find('\'');
766  if (firstQuote == std::string::npos) {
767  throw LSST_EXCEPT(
768  FitsError,
770  fptr, status,
771  boost::format("Invalid CONTINUE at header key %d: \"%s\".") % i % card));
772  }
773  std::size_t lastQuote = card.find('\'', firstQuote + 1);
774  if (lastQuote == std::string::npos) {
775  throw LSST_EXCEPT(
776  FitsError,
778  fptr, status,
779  boost::format("Invalid CONTINUE at header key %d: \"%s\".") % i % card));
780  }
781  valueStr += card.substr(firstQuote + 1, lastQuote - firstQuote);
782  std::size_t slash = card.find('/', lastQuote + 1);
783  if (slash != std::string::npos) {
784  commentStr += strip(card.substr(slash + 1));
785  }
786  ++i;
787  }
788  if (behavior & AUTO_CHECK) {
789  LSST_FITS_CHECK_STATUS(*this, boost::format("Reading key '%s'") % keyStr);
790  }
791  functor(keyStr, valueStr, commentStr);
792  }
793 }
794 
795 // ---- Reading and writing PropertySet/PropertyList --------------------------------------------------------
796 
797 namespace {
798 
799 bool isKeyIgnored(std::string const &key, bool write = false) {
800  return ((ignoreKeys.find(key) != ignoreKeys.end()) || 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 } // namespace
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, const_cast<long *>(naxes), &status);
1124  if (behavior & AUTO_CHECK) {
1125  LSST_FITS_CHECK_STATUS(*this, "Creating new image HDU");
1126  }
1127 }
1128 
1129 template <typename T>
1130 void Fits::writeImageImpl(T const *data, int nElements) {
1131  fits_write_img(reinterpret_cast<fitsfile *>(fptr), FitsType<T>::CONSTANT, 1, nElements,
1132  const_cast<T *>(data), &status);
1133  if (behavior & AUTO_CHECK) {
1134  LSST_FITS_CHECK_STATUS(*this, "Writing image");
1135  }
1136 }
1137 
1138 namespace {
1139 
1144 struct ImageCompressionContext {
1145 public:
1146  ImageCompressionContext(Fits &fits_, ImageCompressionOptions const &useThis)
1147  : fits(fits_), old(fits.getImageCompression()) {
1148  fits.setImageCompression(useThis);
1149  }
1150  ~ImageCompressionContext() {
1151  int status = 0;
1152  std::swap(status, fits.status);
1153  try {
1154  fits.setImageCompression(old);
1155  } catch (...) {
1156  LOGLS_WARN("afw.fits",
1157  makeErrorMessage(fits.fptr, fits.status, "Failed to restore compression settings"));
1158  }
1159  std::swap(status, fits.status);
1160  }
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>
1173  auto fits = reinterpret_cast<fitsfile *>(fptr);
1174  ImageCompressionOptions const &compression =
1175  image.getBBox().getArea() > 0
1176  ? options.compression
1178  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(), const_cast<void *>(pixels->getData()),
1223  &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, "Scaling: MEMORY = BZERO + BSCALE * DISK",
1244  &status);
1245  fits_write_key_dbl(fits, "BSCALE", scale.bscale, 12, "Scaling: MEMORY = BZERO + BSCALE * DISK",
1246  &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 namespace {
1275 
1277 template <typename T, class Enable = void>
1278 struct NullValue {
1279  static T constexpr value = 0;
1280 };
1281 
1283 template <typename T>
1284 struct NullValue<T, typename std::enable_if<std::numeric_limits<T>::has_quiet_NaN>::type> {
1285  static T constexpr value = std::numeric_limits<T>::quiet_NaN();
1286 };
1287 
1288 } // namespace
1289 
1290 template <typename T>
1291 void Fits::readImageImpl(int nAxis, T *data, long *begin, long *end, long *increment) {
1292  T null = NullValue<T>::value;
1293  int anyNulls = 0;
1294  fits_read_subset(reinterpret_cast<fitsfile *>(fptr), FitsType<T>::CONSTANT, begin, end, increment,
1295  reinterpret_cast<void *>(&null), data, &anyNulls, &status);
1296  if (behavior & AUTO_CHECK) LSST_FITS_CHECK_STATUS(*this, "Reading image");
1297 }
1298 
1300  int nAxis = 0;
1301  fits_get_img_dim(reinterpret_cast<fitsfile *>(fptr), &nAxis, &status);
1302  if (behavior & AUTO_CHECK) LSST_FITS_CHECK_STATUS(*this, "Getting NAXIS");
1303  return nAxis;
1304 }
1305 
1306 void Fits::getImageShapeImpl(int maxDim, long *nAxes) {
1307  fits_get_img_size(reinterpret_cast<fitsfile *>(fptr), maxDim, nAxes, &status);
1308  if (behavior & AUTO_CHECK) LSST_FITS_CHECK_STATUS(*this, "Getting NAXES");
1309 }
1310 
1311 template <typename T>
1313  int imageType = 0;
1314  fits_get_img_equivtype(reinterpret_cast<fitsfile *>(fptr), &imageType, &status);
1315  if (behavior & AUTO_CHECK) LSST_FITS_CHECK_STATUS(*this, "Getting image type");
1317  if (imageType < 0) {
1318  return false; // can't represent floating-point with integer
1319  }
1320  return imageType <= FitsBitPix<T>::CONSTANT; // can represent a small int by a larger int
1321  }
1323  // Everything can be represented by double
1324  return true;
1325  }
1326  assert((std::is_same<T, float>::value)); // Everything else has been dealt with
1327  switch (imageType) {
1328  case TLONGLONG:
1329  case TDOUBLE:
1330  // Not enough precision in 'float'
1331  return false;
1332  default:
1333  return true;
1334  }
1335 }
1336 
1338  auto fits = reinterpret_cast<fitsfile *>(fptr);
1339  int compType = 0; // cfitsio compression type
1340  fits_get_compression_type(fits, &compType, &status);
1341  if (behavior & AUTO_CHECK) {
1342  LSST_FITS_CHECK_STATUS(*this, "Getting compression type");
1343  }
1344 
1345  ImageCompressionOptions::Tiles tiles = ndarray::allocate(MAX_COMPRESS_DIM);
1346  fits_get_tile_dim(fits, tiles.getNumElements(), tiles.getData(), &status);
1347  if (behavior & AUTO_CHECK) {
1348  LSST_FITS_CHECK_STATUS(*this, "Getting tile dimensions");
1349  }
1350 
1351  float quantizeLevel;
1352  fits_get_quantize_level(fits, &quantizeLevel, &status);
1353  if (behavior & AUTO_CHECK) {
1354  LSST_FITS_CHECK_STATUS(*this, "Getting quantizeLevel");
1355  }
1356 
1357  return ImageCompressionOptions(compressionAlgorithmFromCfitsio(compType), tiles, quantizeLevel);
1358 }
1359 
1361  auto fits = reinterpret_cast<fitsfile *>(fptr);
1362  fits_unset_compression_request(fits, &status); // wipe the slate and start over
1364  allowImageCompression ? comp.algorithm : ImageCompressionOptions::NONE;
1365  fits_set_compression_type(fits, compressionAlgorithmToCfitsio(algorithm), &status);
1366  if (behavior & AUTO_CHECK) {
1367  LSST_FITS_CHECK_STATUS(*this, "Setting compression type");
1368  }
1369 
1370  if (algorithm == ImageCompressionOptions::NONE) {
1371  // Nothing else worth doing
1372  return;
1373  }
1374 
1375  fits_set_tile_dim(fits, comp.tiles.getNumElements(), comp.tiles.getData(), &status);
1376  if (behavior & AUTO_CHECK) {
1377  LSST_FITS_CHECK_STATUS(*this, "Setting tile dimensions");
1378  }
1379 
1381  fits_set_quantize_level(fits, comp.quantizeLevel, &status);
1382  if (behavior & AUTO_CHECK) {
1383  LSST_FITS_CHECK_STATUS(*this, "Setting quantization level");
1384  }
1385  }
1386 }
1387 
1388 void setAllowImageCompression(bool allow) { allowImageCompression = allow; }
1389 
1390 bool getAllowImageCompression() { return allowImageCompression; }
1391 
1392 // ---- Manipulating files ----------------------------------------------------------------------------------
1393 
1394 Fits::Fits(std::string const &filename, std::string const &mode, int behavior_)
1395  : fptr(0), status(0), behavior(behavior_) {
1396  if (mode == "r" || mode == "rb") {
1397  fits_open_file(reinterpret_cast<fitsfile **>(&fptr), const_cast<char *>(filename.c_str()), READONLY,
1398  &status);
1399  } else if (mode == "w" || mode == "wb") {
1400  boost::filesystem::remove(filename); // cfitsio doesn't like over-writing files
1401  fits_create_file(reinterpret_cast<fitsfile **>(&fptr), const_cast<char *>(filename.c_str()), &status);
1402  } else if (mode == "a" || mode == "ab") {
1403  fits_open_file(reinterpret_cast<fitsfile **>(&fptr), const_cast<char *>(filename.c_str()), READWRITE,
1404  &status);
1405  int nHdu = 0;
1406  fits_get_num_hdus(reinterpret_cast<fitsfile *>(fptr), &nHdu, &status);
1407  fits_movabs_hdu(reinterpret_cast<fitsfile *>(fptr), nHdu, NULL, &status);
1408  if ((behavior & AUTO_CHECK) && (behavior & AUTO_CLOSE) && (status) && (fptr)) {
1409  // We're about to throw an exception, and the destructor won't get called
1410  // because we're in the constructor, so cleanup here first.
1411  int tmpStatus = 0;
1412  fits_close_file(reinterpret_cast<fitsfile *>(fptr), &tmpStatus);
1413  }
1414  } else {
1415  throw LSST_EXCEPT(
1416  FitsError,
1417  (boost::format("Invalid mode '%s' given when opening file '%s'") % mode % filename).str());
1418  }
1419  if (behavior & AUTO_CHECK) {
1420  LSST_FITS_CHECK_STATUS(*this, boost::format("Opening file '%s' with mode '%s'") % filename % mode);
1421  }
1422 }
1423 
1424 Fits::Fits(MemFileManager &manager, std::string const &mode, int behavior_)
1425  : fptr(0), status(0), behavior(behavior_) {
1426  typedef void *(*Reallocator)(void *, std::size_t);
1427  // It's a shame this logic is essentially a duplicate of above, but the innards are different enough
1428  // we can't really reuse it.
1429  if (mode == "r" || mode == "rb") {
1430  fits_open_memfile(reinterpret_cast<fitsfile **>(&fptr), "unused", READONLY, &manager._ptr,
1431  &manager._len, 0, 0, // no reallocator or deltasize necessary for READONLY
1432  &status);
1433  } else if (mode == "w" || mode == "wb") {
1434  Reallocator reallocator = 0;
1435  if (manager._managed) reallocator = &std::realloc;
1436  fits_create_memfile(reinterpret_cast<fitsfile **>(&fptr), &manager._ptr, &manager._len, 0,
1437  reallocator, // use default deltasize
1438  &status);
1439  } else if (mode == "a" || mode == "ab") {
1440  Reallocator reallocator = 0;
1441  if (manager._managed) reallocator = &std::realloc;
1442  fits_open_memfile(reinterpret_cast<fitsfile **>(&fptr), "unused", READWRITE, &manager._ptr,
1443  &manager._len, 0, reallocator, &status);
1444  int nHdu = 0;
1445  fits_get_num_hdus(reinterpret_cast<fitsfile *>(fptr), &nHdu, &status);
1446  fits_movabs_hdu(reinterpret_cast<fitsfile *>(fptr), nHdu, NULL, &status);
1447  if ((behavior & AUTO_CHECK) && (behavior & AUTO_CLOSE) && (status) && (fptr)) {
1448  // We're about to throw an exception, and the destructor won't get called
1449  // because we're in the constructor, so cleanup here first.
1450  int tmpStatus = 0;
1451  fits_close_file(reinterpret_cast<fitsfile *>(fptr), &tmpStatus);
1452  }
1453  } else {
1454  throw LSST_EXCEPT(FitsError,
1455  (boost::format("Invalid mode '%s' given when opening memory file at '%s'") % mode %
1456  manager._ptr)
1457  .str());
1458  }
1459  if (behavior & AUTO_CHECK) {
1461  *this, boost::format("Opening memory file at '%s' with mode '%s'") % manager._ptr % mode);
1462  }
1463 }
1464 
1466  fits_close_file(reinterpret_cast<fitsfile *>(fptr), &status);
1467  fptr = nullptr;
1468 }
1469 
1473  auto combined = std::make_shared<daf::base::PropertyList>();
1474  bool const asScalar = true;
1475  for (auto const &name : first->getOrderedNames()) {
1476  auto const iscv = isCommentIsValid(*first, name);
1477  if (iscv.isComment) {
1478  if (iscv.isValid) {
1479  combined->add<std::string>(name, first->getArray<std::string>(name));
1480  }
1481  } else {
1482  combined->copy(name, first, name, asScalar);
1483  }
1484  }
1485  for (auto const &name : second->getOrderedNames()) {
1486  auto const iscv = isCommentIsValid(*second, name);
1487  if (iscv.isComment) {
1488  if (iscv.isValid) {
1489  combined->add<std::string>(name, second->getArray<std::string>(name));
1490  }
1491  } else {
1492  // `copy` will replace an item, even if has a different type, so no need to call `remove`
1493  combined->copy(name, second, name, asScalar);
1494  }
1495  }
1496  return combined;
1497 }
1498 
1501  fp.setHdu(hdu);
1502  return readMetadata(fp, strip);
1503 }
1504 
1507  fp.setHdu(hdu);
1508  return readMetadata(fp, strip);
1509 }
1510 
1512  auto metadata = std::make_shared<lsst::daf::base::PropertyList>();
1513  fitsfile.readMetadata(*metadata, strip);
1514  // if INHERIT=T, we want to also include header entries from the primary HDU
1515  if (fitsfile.getHdu() != 0 && metadata->exists("INHERIT")) {
1516  bool inherit = false;
1517  if (metadata->typeOf("INHERIT") == typeid(std::string)) {
1518  inherit = (metadata->get<std::string>("INHERIT") == "T");
1519  } else {
1520  inherit = metadata->get<bool>("INHERIT");
1521  }
1522  if (strip) metadata->remove("INHERIT");
1523  if (inherit) {
1524  fitsfile.setHdu(0);
1525  // Combine the metadata from the primary HDU with the metadata from the specified HDU,
1526  // with non-comment values from the specified HDU superseding those in the primary HDU
1527  // and comments from the specified HDU appended to comments from the primary HDU
1528  auto primaryHduMetadata = std::make_shared<daf::base::PropertyList>();
1529  fitsfile.readMetadata(*primaryHduMetadata, strip);
1530  metadata = combineMetadata(primaryHduMetadata, metadata);
1531  } else {
1532  // Purge invalid values
1533  auto const emptyMetadata = std::make_shared<lsst::daf::base::PropertyList>();
1534  metadata = combineMetadata(metadata, emptyMetadata);
1535  }
1536  }
1537  return metadata;
1538 }
1539 
1540 namespace {
1541 
1542 // RAII for moving the HDU
1543 class HduMove {
1544 public:
1545  HduMove() = delete;
1546  HduMove(HduMove const &) = delete;
1547 
1548  HduMove(Fits &fits, int hdu) : _fits(fits), _enabled(true) { _fits.setHdu(hdu); }
1549  ~HduMove() {
1550  if (!_enabled) {
1551  return;
1552  }
1553  int status = 0;
1554  std::swap(status, _fits.status);
1555  try {
1556  _fits.setHdu(0);
1557  } catch (...) {
1558  LOGLS_WARN("afw.fits", makeErrorMessage(_fits.fptr, _fits.status, "Failed to move back to PHU"));
1559  }
1560  std::swap(status, _fits.status);
1561  }
1562  void disable() { _enabled = false; }
1563 
1564 private:
1565  Fits &_fits; // FITS file we're working on
1566  bool _enabled; // Move back to PHU on destruction?
1567 };
1568 
1569 } // anonymous namespace
1570 
1572  auto fits = reinterpret_cast<fitsfile *>(fptr);
1573  if (getHdu() != 0 || countHdus() == 1) {
1574  return false; // Can't possibly be the PHU leading a compressed image
1575  }
1576  // Check NAXIS = 0
1577  int naxis;
1578  fits_get_img_dim(fits, &naxis, &status);
1579  if (behavior & AUTO_CHECK) {
1580  LSST_FITS_CHECK_STATUS(*this, "Checking NAXIS of PHU");
1581  }
1582  if (naxis != 0) {
1583  return false;
1584  }
1585  // Check first extension (and move back there when we're done if we're not compressed)
1586  HduMove move{*this, 1};
1587  bool isCompressed = fits_is_compressed_image(fits, &status);
1588  if (behavior & AUTO_CHECK) {
1589  LSST_FITS_CHECK_STATUS(*this, "Checking compression");
1590  }
1591  if (isCompressed) {
1592  move.disable();
1593  }
1594  return isCompressed;
1595 }
1596 
1598  : compression(fits::compressionAlgorithmFromString(config.get<std::string>("compression.algorithm")),
1599  std::vector<long>{config.getAsInt64("compression.columns"),
1600  config.getAsInt64("compression.rows")},
1601  config.getAsDouble("compression.quantizeLevel")),
1602  scaling(fits::scalingAlgorithmFromString(config.get<std::string>("scaling.algorithm")),
1603  config.getAsInt("scaling.bitpix"),
1604  config.exists("scaling.maskPlanes") ? config.getArray<std::string>("scaling.maskPlanes")
1606  config.getAsInt("scaling.seed"), config.getAsDouble("scaling.quantizeLevel"),
1607  config.getAsDouble("scaling.quantizePad"), config.get<bool>("scaling.fuzz"),
1608  config.getAsDouble("scaling.bscale"), config.getAsDouble("scaling.bzero")) {}
1609 
1610 namespace {
1611 
1612 template <typename T>
1613 void validateEntry(daf::base::PropertySet &output, daf::base::PropertySet const &input,
1614  std::string const &name, T defaultValue) {
1615  output.add(name, input.get<T>(name, defaultValue));
1616 }
1617 
1618 template <typename T>
1619 void validateEntry(daf::base::PropertySet &output, daf::base::PropertySet const &input,
1620  std::string const &name, std::vector<T> defaultValue) {
1621  output.add(name, input.exists(name) ? input.getArray<T>(name) : defaultValue);
1622 }
1623 
1624 } // anonymous namespace
1625 
1627  auto validated = std::make_shared<daf::base::PropertySet>();
1628 
1629  validateEntry(*validated, config, "compression.algorithm", std::string("NONE"));
1630  validateEntry(*validated, config, "compression.columns", 0);
1631  validateEntry(*validated, config, "compression.rows", 1);
1632  validateEntry(*validated, config, "compression.quantizeLevel", 0.0);
1633 
1634  validateEntry(*validated, config, "scaling.algorithm", std::string("NONE"));
1635  validateEntry(*validated, config, "scaling.bitpix", 0);
1636  validateEntry(*validated, config, "scaling.maskPlanes", std::vector<std::string>{"NO_DATA"});
1637  validateEntry(*validated, config, "scaling.seed", 1);
1638  validateEntry(*validated, config, "scaling.quantizeLevel", 5.0);
1639  validateEntry(*validated, config, "scaling.quantizePad", 10.0);
1640  validateEntry(*validated, config, "scaling.fuzz", true);
1641  validateEntry(*validated, config, "scaling.bscale", 1.0);
1642  validateEntry(*validated, config, "scaling.bzero", 0.0);
1643 
1644  // Check for additional entries that we don't support (e.g., from typos)
1645  for (auto const &name : config.names(false)) {
1646  if (!validated->exists(name)) {
1648  os << "Invalid image write option: " << name;
1650  }
1651  }
1652 
1653  return validated;
1654 }
1655 
1656 #define INSTANTIATE_KEY_OPS(r, data, T) \
1657  template void Fits::updateKey(std::string const &, T const &, std::string const &); \
1658  template void Fits::writeKey(std::string const &, T const &, std::string const &); \
1659  template void Fits::updateKey(std::string const &, T const &); \
1660  template void Fits::writeKey(std::string const &, T const &); \
1661  template void Fits::updateColumnKey(std::string const &, int, T const &, std::string const &); \
1662  template void Fits::writeColumnKey(std::string const &, int, T const &, std::string const &); \
1663  template void Fits::updateColumnKey(std::string const &, int, T const &); \
1664  template void Fits::writeColumnKey(std::string const &, int, T const &); \
1665  template void Fits::readKey(std::string const &, T &);
1666 
1667 #define INSTANTIATE_IMAGE_OPS(r, data, T) \
1668  template void Fits::writeImageImpl(T const *, int); \
1669  template void Fits::writeImage(image::ImageBase<T> const &, ImageWriteOptions const &, \
1670  std::shared_ptr<daf::base::PropertySet const>, \
1671  std::shared_ptr<image::Mask<image::MaskPixel> const>); \
1672  template void Fits::readImageImpl(int, T *, long *, long *, long *); \
1673  template bool Fits::checkImageType<T>(); \
1674  template int getBitPix<T>();
1675 
1676 #define INSTANTIATE_TABLE_OPS(r, data, T) \
1677  template int Fits::addColumn<T>(std::string const &ttype, int size); \
1678  template int Fits::addColumn<T>(std::string const &ttype, int size, std::string const &comment);
1679 #define INSTANTIATE_TABLE_ARRAY_OPS(r, data, T) \
1680  template void Fits::writeTableArray(std::size_t row, int col, int nElements, T const *value); \
1681  template void Fits::readTableArray(std::size_t row, int col, int nElements, T *value);
1682 
1683 // ----------------------------------------------------------------------------------------------------------
1684 // ---- Explicit instantiation ------------------------------------------------------------------------------
1685 // ----------------------------------------------------------------------------------------------------------
1686 
1687 #define KEY_TYPES \
1688  (bool)(unsigned char)(short)(unsigned short)(int)(unsigned int)(long)(unsigned long)(LONGLONG)( \
1689  float)(double)(std::complex<float>)(std::complex<double>)(std::string)
1690 
1691 #define COLUMN_TYPES \
1692  (bool)(std::string)(std::uint8_t)(std::int16_t)(std::uint16_t)(std::int32_t)(std::uint32_t)( \
1693  std::int64_t)(float)(double)(lsst::geom::Angle)(std::complex<float>)(std::complex<double>)
1694 
1695 #define COLUMN_ARRAY_TYPES \
1696  (bool)(char)(std::uint8_t)(std::int16_t)(std::uint16_t)(std::int32_t)(std::uint32_t)(std::int64_t)( \
1697  float)(double)(lsst::geom::Angle)(std::complex<float>)(std::complex<double>)
1698 
1699 #define IMAGE_TYPES \
1700  (unsigned char)(short)(unsigned short)(int)(unsigned int)(std::int64_t)(std::uint64_t)(float)(double)
1701 
1706 } // namespace fits
1707 } // namespace afw
1708 } // namespace lsst
#define LOGLS_WARN(logger, message)
#define INSTANTIATE_TABLE_OPS(r, data, T)
Definition: fits.cc:1676
#define INSTANTIATE_KEY_OPS(r, data, T)
Definition: fits.cc:1656
int getImageDim()
Return the number of dimensions in the current HDU.
Definition: fits.cc:1299
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:1470
std::string getFileName() const
Return the file name associated with the FITS object or "<unknown>" if there is none.
Definition: fits.cc:463
void forEachKey(HeaderIterationFunctor &functor)
Call a polymorphic functor for every key in the header.
Definition: fits.cc:740
T empty(T... args)
char * data
Definition: BaseTable.cc:205
bool isComment
Definition: fits.cc:363
ImageCompressionOptions getImageCompression()
Return the current image compression settings.
Definition: fits.cc:1337
ImageCompressionOptions compression
Options controlling compression.
Definition: fits.h:219
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
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:733
int bitpix
Bits per pixel; negative means floating-point: 8,16,32,64,-32,-64.
#define IMAGE_TYPES
Definition: fits.cc:1699
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:650
Options for writing an image to FITS.
Definition: fits.h:218
std::string const & getComment(std::string const &name) const
def scale(algorithm, min, max=None, frame=None)
Definition: ds9.py:113
T to_string(T... args)
int getBitPix()
Return the cfitsio integer BITPIX code for the given data type.
Definition: fits.cc:455
void readTableScalar(std::size_t row, int col, T &value)
Read an array scalar from a binary table.
Definition: fits.h:589
bool checkImageType()
Return true if the current HDU is compatible with the given pixel type.
Definition: fits.cc:1312
#define INSTANTIATE_TABLE_ARRAY_OPS(r, data, T)
Definition: fits.cc:1679
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:658
T end(T... args)
std::vector< std::string > paramNames(bool topLevelOnly=true) const
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:296
The base class for all image classed (Image, Mask, MaskedImage, ...)
Definition: ImageBase.h:104
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:1465
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:618
STL class.
ndarray::Array< T const, N, N > const makeContiguousArray(ndarray::Array< T, N, C > const &array)
Construct a contiguous ndarray.
Definition: fits.h:207
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
Definition: BoundedField.cc:99
lsst::geom::Box2I getBBox(ImageOrigin origin=PARENT) const
Definition: ImageBase.h:448
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 > getOrderedNames(void) const
std::shared_ptr< daf::base::PropertyList > createTrivialWcsMetadata(std::string const &wcsName, lsst::geom::Point2I const &xy0)
Definition: wcsUtils.cc:51
ImageCompressionOptions::CompressionAlgorithm compressionAlgorithmFromString(std::string const &name)
Interpret compression algorithm expressed in string.
int getArea() const
Fits()
Default constructor; set all data members to 0.
Definition: fits.h:603
T erase(T... args)
#define INSTANTIATE_IMAGE_OPS(r, data, T)
Definition: fits.cc:1667
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:478
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
lsst::geom::Point2I getXY0() const
Return the image&#39;s origin.
Definition: ImageBase.h:326
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:1691
T malloc(T... args)
ImageScalingOptions scaling
Options controlling scaling.
Definition: fits.h:220
static std::shared_ptr< daf::base::PropertySet > validate(daf::base::PropertySet const &config)
Validate a PropertySet.
Definition: fits.cc:1626
bool checkCompressedImagePhu()
Go to the first image header in the FITS file.
Definition: fits.cc:1571
void setAllowImageCompression(bool allow)
Definition: fits.cc:1388
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:440
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:1360
lsst::geom::Angle Angle
Definition: misc.h:33
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:626
bool fuzz
Fuzz the values when quantising floating-point values?
#define COLUMN_ARRAY_TYPES
Definition: fits.cc:1695
std::vector< std::string > names(bool topLevelOnly=true) const
bool getAllowImageCompression()
Definition: fits.cc:1390
int getHdu()
Return the current HDU (0-indexed; 0 is the Primary HDU).
Definition: fits.cc:472
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:476
std::ostream * os
Definition: Schema.cc:737
bool isValid
Definition: fits.cc:364
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:391
#define KEY_TYPES
Definition: fits.cc:1687
ImageScalingOptions::ScalingAlgorithm scalingAlgorithmFromString(std::string const &name)
Interpret scaling algorithm expressed in string.
std::string const wcsNameForXY0
Definition: ImageBase.h:72
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:577
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:422
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:224
int countHdus()
Return the number of HDUs in the file.
Definition: fits.cc:499
Scale to apply to image.