8 #include <unordered_set> 9 #include <unordered_map> 16 #include "boost/regex.hpp" 17 #include "boost/filesystem.hpp" 18 #include "boost/preprocessor/seq/for_each.hpp" 19 #include "boost/format.hpp" 48 daf::base::PropertySet
const &metadata) {
50 for (
auto const &fullName : paramNames) {
52 auto name = (lastPeriod == std::string::npos) ? fullName : fullName.substr(lastPeriod + 1);
57 if (
name.size() > 8) {
60 out = (boost::format(
"%-8s= ") %
name).str();
62 if (type ==
typeid(
bool)) {
63 out += metadata.get<
bool>(
name) ?
"1" :
"0";
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)) {
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();
75 if (out.
size() > 80) {
80 int const len = out.
size();
83 }
else if (len > 80) {
86 "Formatted data too long: " +
std::to_string(len) +
" > 80: \"" + out +
"\"");
103 class StringStartSet {
107 for (
auto const& word : input) {
109 if (size < _minSize) {
113 for (
auto const& word : input) {
115 assert(_words.
count(start) == 0);
116 _words[start] = word;
122 auto const iter = _words.
find(startString(key));
123 if (iter == _words.
end()) {
148 "SIMPLE",
"BITPIX",
"NAXIS",
"EXTEND",
"GCOUNT",
"PCOUNT",
"XTENSION",
"TFIELDS",
"BSCALE",
"BZERO",
150 "ZBITPIX",
"ZIMAGE",
"ZCMPTYPE",
"ZSIMPLE",
"ZEXTEND",
"ZBLANK",
"ZDATASUM",
"ZHECKSUM",
152 "DATASUM",
"CHECKSUM" 160 StringStartSet
const ignoreKeyStarts {
162 "NAXIS",
"TZERO",
"TSCAL",
164 "ZNAXIS",
"ZTILE",
"ZNAME",
"ZVAL" 172 StringStartSet
const ignoreKeyStartsWrite {
178 if (s.
empty())
return s;
181 return s.
substr(i1, (i1 == std::string::npos) ? 0 : 1 + i2 - i1);
186 char getFormatCode(
bool *) {
return 'X'; }
195 char getFormatCode(
float *) {
return 'E'; }
196 char getFormatCode(
double *) {
return 'D'; }
203 template <
typename T>
206 return (boost::format(
"%d%c") % size % getFormatCode((T *)0)).str();
207 }
else if (size < 0) {
209 return (boost::format(
"1Q%c(%d)") % getFormatCode((T *)0) % (-size)).str();
212 return (boost::format(
"1Q%c") % getFormatCode((T *)0)).str();
218 template <
typename T>
222 struct FitsType<bool> {
223 static int const CONSTANT = TLOGICAL;
226 struct FitsType<char> {
227 static int const CONSTANT = TSTRING;
230 struct FitsType<signed char> {
231 static int const CONSTANT = TSBYTE;
234 struct FitsType<unsigned char> {
235 static int const CONSTANT = TBYTE;
238 struct FitsType<short> {
239 static int const CONSTANT = TSHORT;
242 struct FitsType<unsigned short> {
243 static int const CONSTANT = TUSHORT;
246 struct FitsType<int> {
247 static int const CONSTANT = TINT;
250 struct FitsType<unsigned int> {
251 static int const CONSTANT = TUINT;
254 struct FitsType<long> {
255 static int const CONSTANT = TLONG;
258 struct FitsType<unsigned long> {
259 static int const CONSTANT = TULONG;
262 struct FitsType<long long> {
263 static int const CONSTANT = TLONGLONG;
266 struct FitsType<unsigned long long> {
267 static int const CONSTANT = TLONGLONG;
270 struct FitsType<float> {
271 static int const CONSTANT = TFLOAT;
274 struct FitsType<double> {
275 static int const CONSTANT = TDOUBLE;
278 struct FitsType<geom::
Angle> {
279 static int const CONSTANT = TDOUBLE;
282 struct FitsType<
std::complex<float> > {
283 static int const CONSTANT = TCOMPLEX;
286 struct FitsType<
std::complex<double> > {
287 static int const CONSTANT = TDBLCOMPLEX;
291 template <
typename T>
292 struct FitsTableType :
public FitsType<T> {};
294 struct FitsTableType<bool> {
295 static int const CONSTANT = TBIT;
298 template <
typename T>
302 struct FitsBitPix<unsigned char> {
303 static int const CONSTANT = BYTE_IMG;
306 struct FitsBitPix<short> {
307 static int const CONSTANT = SHORT_IMG;
310 struct FitsBitPix<unsigned short> {
311 static int const CONSTANT = USHORT_IMG;
314 struct FitsBitPix<int> {
315 static int const CONSTANT = LONG_IMG;
318 struct FitsBitPix<unsigned int> {
319 static int const CONSTANT = ULONG_IMG;
322 struct FitsBitPix<
std::int64_t> {
323 static int const CONSTANT = LONGLONG_IMG;
326 struct FitsBitPix<
std::uint64_t> {
327 static int const CONSTANT = LONGLONG_IMG;
330 struct FitsBitPix<float> {
331 static int const CONSTANT = FLOAT_IMG;
334 struct FitsBitPix<double> {
335 static int const CONSTANT = DOUBLE_IMG;
338 static bool allowImageCompression =
true;
340 int fitsTypeForBitpix(
int 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;
350 os <<
"Invalid bitpix value: " << bitpix;
351 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError, os.
str());
361 ItemInfo(
bool isComment,
bool isValid) : isComment(isComment), isValid(isValid) {}
373 ItemInfo isCommentIsValid(daf::base::PropertyList
const &pl,
std::string const &
name) {
374 if (!pl.exists(name)) {
375 return ItemInfo(
false,
false);
378 if ((name ==
"COMMENT") || (name ==
"HISTORY")) {
379 return ItemInfo(
true, type ==
typeid(
std::string));
381 return ItemInfo(
false,
true);
392 os <<
"cfitsio error";
393 if (fileName !=
"") {
394 os <<
" (" << fileName <<
")";
397 char fitsErrMsg[FLEN_ERRMSG];
398 fits_get_errstatus(status, fitsErrMsg);
399 os <<
": " << fitsErrMsg <<
" (" << status <<
")";
404 os <<
"\ncfitsio error stack:\n";
405 char cfitsioMsg[FLEN_ERRMSG];
406 while (fits_read_errmsg(cfitsioMsg) != 0) {
407 os <<
" " << cfitsioMsg <<
"\n";
414 fitsfile *fd =
reinterpret_cast<fitsfile *
>(fptr);
415 if (fd != 0 && fd->Fptr != 0 && fd->Fptr->filename != 0) {
416 fileName = fd->Fptr->filename;
431 for (
auto const &
name : allParamNames) {
436 return makeLimitedFitsHeaderImpl(desiredParamNames, metadata);
453 template <
typename T>
455 return FitsBitPix<T>::CONSTANT;
464 fitsfile *fd =
reinterpret_cast<fitsfile *
>(fptr);
465 if (fd != 0 && fd->Fptr != 0 && fd->Fptr->filename != 0) {
466 fileName = fd->Fptr->filename;
473 fits_get_hdu_num(reinterpret_cast<fitsfile *>(fptr), &n);
479 fits_movrel_hdu(reinterpret_cast<fitsfile *>(fptr), hdu, 0, &status);
480 if (behavior & AUTO_CHECK) {
485 fits_movabs_hdu(reinterpret_cast<fitsfile *>(fptr), hdu + 1, 0, &status);
487 if (hdu ==
DEFAULT_HDU && getHdu() == 0 && getImageDim() == 0) {
489 int tmpStatus = status;
490 fits_movrel_hdu(reinterpret_cast<fitsfile *>(fptr), 1, 0, &tmpStatus);
492 if (behavior & AUTO_CHECK) {
500 fits_get_num_hdus(reinterpret_cast<fitsfile *>(fptr), &n, &status);
501 if (behavior & AUTO_CHECK) {
519 std::string nonFiniteDoubleToString(
double value) {
537 double stringToNonFiniteDouble(
std::string const &value) {
538 if (value ==
"NAN") {
541 if (value ==
"+INFINITY") {
544 if (value ==
"-INFINITY") {
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);
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);
561 void updateKeyImpl(
Fits &fits,
char const *key,
bool const &value,
char const *comment) {
563 fits_update_key(reinterpret_cast<fitsfile *>(fits.
fptr), TLOGICAL, const_cast<char *>(key), &v,
564 const_cast<char *>(comment), &fits.
status);
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);
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),
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);
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()),
588 }
else if (strncmp(key,
"HISTORY", 7) == 0) {
589 fits_write_history(reinterpret_cast<fitsfile *>(fits.
fptr), const_cast<char *>(value.
c_str()),
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);
597 void writeKeyImpl(
Fits &fits,
char const *key,
bool const &value,
char const *comment) {
599 fits_write_key(reinterpret_cast<fitsfile *>(fits.
fptr), TLOGICAL, const_cast<char *>(key), &v,
600 const_cast<char *>(comment), &fits.
status);
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);
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),
616 template <
typename T>
618 updateKeyImpl(*
this, key.
c_str(), value, comment.
c_str());
619 if (behavior & AUTO_CHECK) {
624 template <
typename T>
626 writeKeyImpl(*
this, key.
c_str(), value, comment.
c_str());
627 if (behavior & AUTO_CHECK) {
632 template <
typename T>
634 updateKeyImpl(*
this, key.
c_str(), value, 0);
635 if (behavior & AUTO_CHECK) {
640 template <
typename T>
642 writeKeyImpl(*
this, key.
c_str(), value, 0);
643 if (behavior & AUTO_CHECK) {
648 template <
typename T>
650 updateKey((boost::format(
"%s%d") % prefix % (n + 1)).str(), value, comment);
651 if (behavior & AUTO_CHECK) {
656 template <
typename T>
658 writeKey((boost::format(
"%s%d") % prefix % (n + 1)).str(), value, comment);
659 if (behavior & AUTO_CHECK) {
664 template <
typename T>
666 updateKey((boost::format(
"%s%d") % prefix % (n + 1)).str(), value);
667 if (behavior & AUTO_CHECK) {
672 template <
typename T>
674 writeKey((boost::format(
"%s%d") % prefix % (n + 1)).str(), value);
675 if (behavior & AUTO_CHECK) {
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),
692 fits_read_key_longstr(reinterpret_cast<fitsfile *>(fits.
fptr), const_cast<char *>(key), &buf, 0,
700 void readKeyImpl(
Fits &fits,
char const *key,
double &value) {
704 char buf[FLEN_VALUE];
705 fits_read_keyword(reinterpret_cast<fitsfile *>(fits.
fptr), const_cast<char *>(key), buf, 0, &fits.
status);
709 if (
std::string(buf).find(
'\'') != std::string::npos) {
711 readKeyImpl(fits, key, unquoted);
715 value = stringToNonFiniteDouble(unquoted);
719 (boost::format(
"Unrecognised string value for keyword '%s' when parsing as double: %s") %
724 fits_read_key(reinterpret_cast<fitsfile *>(fits.
fptr), FitsType<double>::CONSTANT,
725 const_cast<char *>(key), &value, 0, &fits.
status);
731 template <
typename T>
733 readKeyImpl(*
this, key.
c_str(), value);
734 if (behavior & AUTO_CHECK) {
744 fits_get_hdrspace(reinterpret_cast<fitsfile *>(fptr), &nKeys, 0, &status);
750 fits_read_keyn(reinterpret_cast<fitsfile *>(fptr), i, key, value, comment, &status);
753 commentStr = comment;
755 while (valueStr.
size() > 2 && valueStr[valueStr.
size() - 2] ==
'&' && i <= nKeys) {
757 fits_read_record(reinterpret_cast<fitsfile *>(fptr), i, key, &status);
758 if (strncmp(key,
"CONTINUE", 8) != 0) {
765 if (firstQuote == std::string::npos) {
770 boost::format(
"Invalid CONTINUE at header key %d: \"%s\".") % i % card));
773 if (lastQuote == std::string::npos) {
778 boost::format(
"Invalid CONTINUE at header key %d: \"%s\".") % i % card));
780 valueStr += card.
substr(firstQuote + 1, lastQuote - firstQuote);
782 if (slash != std::string::npos) {
787 if (behavior & AUTO_CHECK) {
790 functor(keyStr, valueStr, commentStr);
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)));
808 template <
typename T>
811 list->add(key, value, comment);
813 set->add(key, value);
818 daf::base::PropertySet *
set;
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;
830 if (
strip && isKeyIgnored(key)) {
835 if (boost::regex_match(value, boolRegex)) {
837 add(key,
bool(value ==
"T" || value ==
"t"), comment);
838 }
else if (boost::regex_match(value, intRegex)) {
842 if (val < (1
LL << 31) && val > -(1
LL << 31)) {
843 add(key, static_cast<int>(val), comment);
845 add(key, val, comment);
847 }
else if (boost::regex_match(value, doubleRegex)) {
851 add(key, val, comment);
852 }
else if (boost::regex_match(value, matchStrings, fitsStringRegex)) {
854 double val = stringToNonFiniteDouble(str);
856 add(key, val, comment);
858 add(key, str, comment);
860 }
else if (key ==
"HISTORY" || key ==
"COMMENT") {
861 add(key, comment,
"");
862 }
else if (value.
empty()) {
866 afw::fits::FitsError,
867 (boost::format(
"Could not parse header value for key '%s': '%s'") % key % value).str());
871 void writeKeyFromProperty(Fits &fits, daf::base::PropertySet
const &metadata,
std::string const &key,
872 char const *comment = 0) {
874 if (valueType ==
typeid(
bool)) {
875 if (metadata.isArray(key)) {
879 writeKeyImpl(fits, key.
c_str(),
static_cast<bool>(tmp[i]), comment);
882 writeKeyImpl(fits, key.
c_str(), metadata.get<
bool>(key), comment);
885 if (metadata.isArray(key)) {
888 writeKeyImpl(fits, key.
c_str(), tmp[i], comment);
893 }
else if (valueType ==
typeid(
int)) {
894 if (metadata.isArray(key)) {
897 writeKeyImpl(fits, key.
c_str(), tmp[i], comment);
900 writeKeyImpl(fits, key.
c_str(), metadata.get<
int>(key), comment);
902 }
else if (valueType ==
typeid(
long)) {
903 if (metadata.isArray(key)) {
906 writeKeyImpl(fits, key.
c_str(), tmp[i], comment);
909 writeKeyImpl(fits, key.
c_str(), metadata.get<
long>(key), comment);
911 }
else if (valueType ==
typeid(
long long)) {
912 if (metadata.isArray(key)) {
915 writeKeyImpl(fits, key.
c_str(), tmp[i], comment);
918 writeKeyImpl(fits, key.
c_str(), metadata.get<
long long>(key), comment);
921 if (metadata.isArray(key)) {
924 writeKeyImpl(fits, key.
c_str(), tmp[i], comment);
929 }
else if (valueType ==
typeid(
double)) {
930 if (metadata.isArray(key)) {
933 writeKeyImpl(fits, key.
c_str(), tmp[i], comment);
936 writeKeyImpl(fits, key.
c_str(), metadata.get<
double>(key), comment);
939 if (metadata.isArray(key)) {
942 writeKeyImpl(fits, key.
c_str(), tmp[i], comment);
951 boost::format(
"In %s, unknown type '%s' for key '%s'.") %
952 BOOST_CURRENT_FUNCTION % valueType.
name() % key));
962 MetadataIterationFunctor f;
978 for (NameList::const_iterator i = paramNames.begin(); i != paramNames.end(); ++i) {
979 if (!isKeyIgnored(*i,
true)) {
983 writeKeyFromProperty(*
this, metadata, *i);
994 fits_create_tbl(reinterpret_cast<fitsfile *>(fptr), BINARY_TBL, 0, 0, &ttype, &tform, 0, 0, &status);
995 if (behavior & AUTO_CHECK) {
1000 template <
typename T>
1003 fits_get_num_cols(reinterpret_cast<fitsfile *>(fptr), &nCols, &status);
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) {
1013 template <
typename T>
1015 int nCols = addColumn<T>(ttype, size);
1016 updateColumnKey(
"TTYPE", nCols, ttype, comment);
1017 if (behavior & AUTO_CHECK) {
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) {
1035 fits_get_num_rows(reinterpret_cast<fitsfile *>(fptr), &r, &status);
1036 if (behavior & AUTO_CHECK) {
1042 template <
typename T>
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) {
1048 nElements % row % col);
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) {
1065 template <
typename T>
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) {
1077 long size = isVariableLength ? getTableArraySize(row, col) : getTableArraySize(col);
1082 char *tmp = &buf.
front();
1083 fits_read_col(reinterpret_cast<fitsfile *>(fptr), TSTRING, col + 1, row + 1, 1, 1, 0, &tmp, &anynul,
1085 if (behavior & AUTO_CHECK) {
1095 fits_get_coltype(reinterpret_cast<fitsfile *>(fptr), col + 1, &typecode, &result, &width, &status);
1096 if (behavior & AUTO_CHECK) {
1105 fits_read_descript(reinterpret_cast<fitsfile *>(fptr), col + 1, row + 1, &result, &offset, &status);
1106 if (behavior & AUTO_CHECK) {
1116 fits_create_img(reinterpret_cast<fitsfile *>(fptr), 8, 0, &naxes, &status);
1117 if (behavior & AUTO_CHECK) {
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) {
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) {
1145 struct ImageCompressionContext {
1148 : fits(fits_), old(fits.getImageCompression()) {
1149 fits.setImageCompression(useThis);
1151 ~ImageCompressionContext() {
1155 fits.setImageCompression(old);
1158 makeErrorMessage(fits.fptr, fits.status,
"Failed to restore compression settings"));
1169 template <
typename T>
1176 auto fits =
reinterpret_cast<fitsfile *
>(fptr);
1179 ImageCompressionContext comp(*
this, compression);
1180 if (behavior & AUTO_CHECK) {
1187 ndarray::Vector<long, 2> dims(image.
getArray().getShape().reverse());
1195 copy->combine(wcsMetadata);
1198 header = wcsMetadata;
1200 writeMetadata(*header);
1214 fits_set_bscale(fits, 1.0, 0.0, &status);
1215 if (behavior & AUTO_CHECK) {
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) {
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);
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);
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);
1248 if (behavior & AUTO_CHECK) {
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);
1260 if (behavior & AUTO_CHECK) {
1268 fits_set_hdustruc(fits, &status);
1269 if (behavior & AUTO_CHECK) {
1278 template <
typename T,
class Enable=
void>
1280 static T constexpr value = 0;
1284 template <
typename T>
1285 struct NullValue<T, typename std::enable_if<std::numeric_limits<T>::has_quiet_NaN>::type> {
1291 template <
typename T>
1292 void Fits::readImageImpl(
int nAxis, T *data,
long *begin,
long *end,
long *increment) {
1293 T null = NullValue<T>::value;
1295 fits_read_subset(reinterpret_cast<fitsfile *>(fptr), FitsType<T>::CONSTANT, begin, end, increment,
1296 reinterpret_cast<void*>(&null), data, &anyNulls, &status);
1302 fits_get_img_dim(reinterpret_cast<fitsfile *>(fptr), &nAxis, &status);
1307 void Fits::getImageShapeImpl(
int maxDim,
long *nAxes) {
1308 fits_get_img_size(reinterpret_cast<fitsfile *>(fptr), maxDim, nAxes, &status);
1312 template <
typename T>
1315 fits_get_img_equivtype(reinterpret_cast<fitsfile *>(fptr), &imageType, &status);
1318 if (imageType < 0) {
1321 return imageType <= FitsBitPix<T>::CONSTANT;
1328 switch (imageType) {
1340 auto fits =
reinterpret_cast<fitsfile *
>(fptr);
1342 fits_get_compression_type(fits, &compType, &status);
1343 if (behavior & AUTO_CHECK) {
1348 fits_get_tile_dim(fits, tiles.getNumElements(), tiles.getData(), &status);
1349 if (behavior & AUTO_CHECK) {
1353 float quantizeLevel;
1354 fits_get_quantize_level(fits, &quantizeLevel, &status);
1355 if (behavior & AUTO_CHECK) {
1364 auto fits =
reinterpret_cast<fitsfile *
>(fptr);
1365 fits_unset_compression_request(fits, &status);
1369 if (behavior & AUTO_CHECK) {
1378 fits_set_tile_dim(fits, comp.
tiles.getNumElements(), comp.
tiles.getData(), &status);
1379 if (behavior & AUTO_CHECK) {
1385 if (behavior & AUTO_CHECK) {
1392 allowImageCompression = allow;
1396 return allowImageCompression;
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,
1406 }
else if (mode ==
"w" || mode ==
"wb") {
1407 boost::filesystem::remove(filename);
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,
1413 fits_get_num_hdus(reinterpret_cast<fitsfile *>(
fptr), &nHdu, &
status);
1414 fits_movabs_hdu(reinterpret_cast<fitsfile *>(
fptr), nHdu, NULL, &
status);
1419 fits_close_file(reinterpret_cast<fitsfile *>(
fptr), &tmpStatus);
1424 (boost::format(
"Invalid mode '%s' given when opening file '%s'") % mode % filename).str());
1433 typedef void *(*Reallocator)(
void *,
std::size_t);
1436 if (mode ==
"r" || mode ==
"rb") {
1437 fits_open_memfile(reinterpret_cast<fitsfile **>(&
fptr),
"unused", READONLY, &manager._ptr,
1438 &manager._len, 0, 0,
1440 }
else if (mode ==
"w" || mode ==
"wb") {
1441 Reallocator reallocator = 0;
1443 fits_create_memfile(reinterpret_cast<fitsfile **>(&
fptr), &manager._ptr, &manager._len, 0,
1446 }
else if (mode ==
"a" || mode ==
"ab") {
1447 Reallocator reallocator = 0;
1449 fits_open_memfile(reinterpret_cast<fitsfile **>(&
fptr),
"unused", READWRITE, &manager._ptr,
1450 &manager._len, 0, reallocator, &
status);
1452 fits_get_num_hdus(reinterpret_cast<fitsfile *>(
fptr), &nHdu, &
status);
1453 fits_movabs_hdu(reinterpret_cast<fitsfile *>(
fptr), nHdu, NULL, &
status);
1458 fits_close_file(reinterpret_cast<fitsfile *>(
fptr), &tmpStatus);
1462 (boost::format(
"Invalid mode '%s' given when opening memory file at '%s'") % mode %
1468 *
this, boost::format(
"Opening memory file at '%s' with mode '%s'") % manager._ptr % mode);
1473 fits_close_file(reinterpret_cast<fitsfile *>(
fptr), &
status);
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) {
1489 combined->copy(
name, first,
name, asScalar);
1492 for (
auto const &
name : second->getOrderedNames()) {
1493 auto const iscv = isCommentIsValid(*second,
name);
1494 if (iscv.isComment) {
1500 combined->copy(
name, second,
name, asScalar);
1519 auto metadata = std::make_shared<lsst::daf::base::PropertyList>();
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");
1527 inherit = metadata->get<
bool>(
"INHERIT");
1529 if (strip) metadata->remove(
"INHERIT");
1535 auto primaryHduMetadata = std::make_shared<daf::base::PropertyList>();
1540 auto const emptyMetadata = std::make_shared<lsst::daf::base::PropertyList>();
1553 HduMove(HduMove
const&) =
delete;
1555 HduMove(
Fits & fits,
int hdu) :
_fits(fits), _enabled(
true) {
1572 void disable() { _enabled =
false; }
1582 auto fits =
reinterpret_cast<fitsfile *
>(
fptr);
1588 fits_get_img_dim(fits, &naxis, &
status);
1596 HduMove move{*
this, 1};
1597 bool isCompressed = fits_is_compressed_image(fits, &
status);
1604 return isCompressed;
1612 config.getAsDouble(
"compression.quantizeLevel")
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")
1631 template <
typename T>
1638 output.
add(name, input.
get<T>(name, defaultValue));
1642 template <
typename T>
1657 auto validated = std::make_shared<daf::base::PropertySet>();
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);
1664 validateEntry(*validated, config,
"scaling.algorithm",
std::string(
"NONE"));
1665 validateEntry(*validated, config,
"scaling.bitpix", 0);
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);
1675 for (
auto const&
name : config.
names(
false)) {
1676 if (!validated->exists(
name)) {
1678 os <<
"Invalid image write option: " <<
name;
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 &); 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>(); 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); 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) 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>) 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>) 1731 #define IMAGE_TYPES \ 1732 (unsigned char)(short)(unsigned short)(int)(unsigned int)(std::int64_t)(std::uint64_t)(float)(double) #define LOGLS_WARN(logger, message)
#define INSTANTIATE_TABLE_OPS(r, data, T)
#define INSTANTIATE_KEY_OPS(r, data, T)
int getImageDim()
Return the number of dimensions in the current HDU.
std::size_t countRows()
Return the number of row in a table.
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.
std::string getFileName() const
Return the file name associated with the FITS object or "<unknown>" if there is none.
void forEachKey(HeaderIterationFunctor &functor)
Call a polymorphic functor for every key in the header.
lsst::afw::geom::Angle Angle
ImageCompressionOptions getImageCompression()
Return the current image compression settings.
ImageCompressionOptions compression
Options controlling compression.
T find_first_not_of(T... args)
void writeMetadata(daf::base::PropertySet const &metadata)
Read a FITS header into a PropertySet or PropertyList.
#define LSST_FITS_CHECK_STATUS(fitsObj,...)
Throw a FitsError exception if the status of the given Fits object is nonzero.
geom::Box2I getBBox(ImageOrigin origin=PARENT) const
std::vector< T > getArray(std::string const &name) const
int compressionAlgorithmToCfitsio(ImageCompressionOptions::CompressionAlgorithm algorithm)
Convert ImageCompressionOptions::CompressionAlgorithm to cfitsio.
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.
int bitpix
Bits per pixel; negative means floating-point: 8,16,32,64,-32,-64.
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.
Options for writing an image to FITS.
std::string const & getComment(std::string const &name) const
def scale(algorithm, min, max=None, frame=None)
int getBitPix()
Return the cfitsio integer BITPIX code for the given data type.
void readTableScalar(std::size_t row, int col, T &value)
Read an array scalar from a binary table.
bool checkImageType()
Return true if the current HDU is compatible with the given pixel type.
#define INSTANTIATE_TABLE_ARRAY_OPS(r, data, T)
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.
CompressionAlgorithm
Compression algorithms.
A simple struct that combines the two arguments that must be passed to most cfitsio routines and cont...
The base class for all image classed (Image, Mask, MaskedImage, ...)
long getTableArraySize(int col)
Return the size of an array column.
FITS BITPIX header value by C++ type.
void closeFile()
Close a FITS file.
int seed
Seed for random number generator when fuzzing.
void createEmpty()
Create an empty image HDU with NAXIS=0 at the end of the file.
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.
ndarray::Array< T const, N, N > const makeContiguousArray(ndarray::Array< T, N, C > const &array)
Construct a contiguous ndarray.
An exception thrown when problems are found when reading or writing FITS files.
Tiles tiles
Tile size; a dimension with 0 means infinite (e.g., to specify one row: 0,1)
Options for tile compression of image pixels.
A base class for image defects.
Represent a 2-dimensional array of bitmask pixels.
int64_t getAsInt64(std::string const &name) const
Lifetime-management for memory that goes into FITS memory files.
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.
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.
std::shared_ptr< daf::base::PropertyList > createTrivialWcsMetadata(std::string const &wcsName, geom::Point2I const &xy0)
Fits()
Default constructor; set all data members to 0.
#define INSTANTIATE_IMAGE_OPS(r, data, T)
bool exists(std::string const &name) const
ndarray::Array< long, 1, 1 > Tiles
void createTable()
Create a new binary table extension.
double bscale
Scale to apply when reading from FITS.
void setHdu(int hdu, bool relative=false)
Set the current HDU.
T find_last_not_of(T... args)
#define LSST_EXCEPT(type,...)
ImageScalingOptions scaling
Options controlling scaling.
static std::shared_ptr< daf::base::PropertySet > validate(daf::base::PropertySet const &config)
Validate a PropertySet.
bool checkCompressedImagePhu()
Go to the first image header in the FITS file.
void setAllowImageCompression(bool allow)
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.
void reset()
Return the manager to the same state it would be if default-constructed.
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.
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.
daf::base::PropertyList * list
void writeKey(std::string const &key, T const &value, std::string const &comment)
Add a FITS header key to the bottom of the header.
bool fuzz
Fuzz the values when quantising floating-point values?
#define COLUMN_ARRAY_TYPES
bool getAllowImageCompression()
int getHdu()
Return the current HDU (0-indexed; 0 is the Primary HDU).
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.
int addColumn(std::string const &ttype, int size, std::string const &comment)
Add a column to a table.
std::string makeErrorMessage(std::string const &fileName="", int status=0, std::string const &msg="")
Return an error message reflecting FITS I/O errors.
ImageScalingOptions::ScalingAlgorithm scalingAlgorithmFromString(std::string const &name)
Interpret scaling algorithm expressed in string.
std::string const wcsNameForXY0
void writeTableScalar(std::size_t row, int col, T value)
Write a scalar value to a binary table.
void readMetadata(daf::base::PropertySet &metadata, bool strip=false)
Read a FITS header into a PropertySet or PropertyList.
std::string makeLimitedFitsHeader(lsst::daf::base::PropertySet const &metadata, std::set< std::string > const &excludeNames={})
Format a PropertySet into an FITS header string in a simplistic fashion.
const int DEFAULT_HDU
Specify that the default HDU should be read.
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.
int countHdus()
Return the number of HDUs in the file.
geom::Point2I getXY0() const
Return the image's origin.