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"};
159 StringStartSet
const ignoreKeyStarts{
160 "NAXIS",
"TZERO",
"TSCAL",
162 "ZNAXIS",
"ZTILE",
"ZNAME",
"ZVAL"};
169 StringStartSet
const ignoreKeyStartsWrite{
"TFORM",
"TTYPE"};
173 if (s.
empty())
return s;
176 return s.
substr(i1, (i1 == std::string::npos) ? 0 : 1 + i2 - i1);
181 char getFormatCode(
bool *) {
return 'X'; }
190 char getFormatCode(
float *) {
return 'E'; }
191 char getFormatCode(
double *) {
return 'D'; }
198 template <
typename T>
201 return (boost::format(
"%d%c") % size % getFormatCode((T *)0)).str();
202 }
else if (size < 0) {
204 return (boost::format(
"1Q%c(%d)") % getFormatCode((T *)0) % (-size)).str();
207 return (boost::format(
"1Q%c") % getFormatCode((T *)0)).str();
213 template <
typename T>
217 struct FitsType<bool> {
218 static int const CONSTANT = TLOGICAL;
221 struct FitsType<char> {
222 static int const CONSTANT = TSTRING;
225 struct FitsType<signed char> {
226 static int const CONSTANT = TSBYTE;
229 struct FitsType<unsigned char> {
230 static int const CONSTANT = TBYTE;
233 struct FitsType<short> {
234 static int const CONSTANT = TSHORT;
237 struct FitsType<unsigned short> {
238 static int const CONSTANT = TUSHORT;
241 struct FitsType<int> {
242 static int const CONSTANT = TINT;
245 struct FitsType<unsigned int> {
246 static int const CONSTANT = TUINT;
249 struct FitsType<long> {
250 static int const CONSTANT = TLONG;
253 struct FitsType<unsigned long> {
254 static int const CONSTANT = TULONG;
257 struct FitsType<long long> {
258 static int const CONSTANT = TLONGLONG;
261 struct FitsType<unsigned long long> {
262 static int const CONSTANT = TLONGLONG;
265 struct FitsType<float> {
266 static int const CONSTANT = TFLOAT;
269 struct FitsType<double> {
270 static int const CONSTANT = TDOUBLE;
274 static int const CONSTANT = TDOUBLE;
277 struct FitsType<
std::complex<float> > {
278 static int const CONSTANT = TCOMPLEX;
281 struct FitsType<
std::complex<double> > {
282 static int const CONSTANT = TDBLCOMPLEX;
286 template <
typename T>
287 struct FitsTableType :
public FitsType<T> {};
289 struct FitsTableType<bool> {
290 static int const CONSTANT = TBIT;
293 template <
typename T>
297 struct FitsBitPix<unsigned char> {
298 static int const CONSTANT = BYTE_IMG;
301 struct FitsBitPix<short> {
302 static int const CONSTANT = SHORT_IMG;
305 struct FitsBitPix<unsigned short> {
306 static int const CONSTANT = USHORT_IMG;
309 struct FitsBitPix<int> {
310 static int const CONSTANT = LONG_IMG;
313 struct FitsBitPix<unsigned int> {
314 static int const CONSTANT = ULONG_IMG;
317 struct FitsBitPix<
std::int64_t> {
318 static int const CONSTANT = LONGLONG_IMG;
321 struct FitsBitPix<
std::uint64_t> {
322 static int const CONSTANT = LONGLONG_IMG;
325 struct FitsBitPix<float> {
326 static int const CONSTANT = FLOAT_IMG;
329 struct FitsBitPix<double> {
330 static int const CONSTANT = DOUBLE_IMG;
333 static bool allowImageCompression =
true;
335 int fitsTypeForBitpix(
int bitpix) {
351 os <<
"Invalid bitpix value: " << bitpix;
352 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError, os.
str());
362 ItemInfo(
bool isComment,
bool isValid) : isComment(isComment), isValid(isValid) {}
374 ItemInfo isCommentIsValid(daf::base::PropertyList
const &pl,
std::string const &
name) {
375 if (!pl.exists(name)) {
376 return ItemInfo(
false,
false);
379 if ((name ==
"COMMENT") || (name ==
"HISTORY")) {
380 return ItemInfo(
true, type ==
typeid(
std::string));
382 return ItemInfo(
false,
true);
393 os <<
"cfitsio error";
394 if (fileName !=
"") {
395 os <<
" (" << fileName <<
")";
398 char fitsErrMsg[FLEN_ERRMSG];
399 fits_get_errstatus(status, fitsErrMsg);
400 os <<
": " << fitsErrMsg <<
" (" << status <<
")";
405 os <<
"\ncfitsio error stack:\n";
406 char cfitsioMsg[FLEN_ERRMSG];
407 while (fits_read_errmsg(cfitsioMsg) != 0) {
408 os <<
" " << cfitsioMsg <<
"\n";
415 fitsfile *fd =
reinterpret_cast<fitsfile *
>(fptr);
416 if (fd != 0 && fd->Fptr != 0 && fd->Fptr->filename != 0) {
417 fileName = fd->Fptr->filename;
432 for (
auto const &
name : allParamNames) {
437 return makeLimitedFitsHeaderImpl(desiredParamNames, metadata);
454 template <
typename T>
456 return FitsBitPix<T>::CONSTANT;
465 fitsfile *fd =
reinterpret_cast<fitsfile *
>(fptr);
466 if (fd != 0 && fd->Fptr != 0 && fd->Fptr->filename != 0) {
467 fileName = fd->Fptr->filename;
474 fits_get_hdu_num(reinterpret_cast<fitsfile *>(fptr), &n);
480 fits_movrel_hdu(reinterpret_cast<fitsfile *>(fptr), hdu, 0, &status);
481 if (behavior & AUTO_CHECK) {
486 fits_movabs_hdu(reinterpret_cast<fitsfile *>(fptr), hdu + 1, 0, &status);
488 if (hdu ==
DEFAULT_HDU && getHdu() == 0 && getImageDim() == 0) {
490 int tmpStatus = status;
491 fits_movrel_hdu(reinterpret_cast<fitsfile *>(fptr), 1, 0, &tmpStatus);
493 if (behavior & AUTO_CHECK) {
501 fits_get_num_hdus(reinterpret_cast<fitsfile *>(fptr), &n, &status);
502 if (behavior & AUTO_CHECK) {
520 std::string nonFiniteDoubleToString(
double value) {
538 double stringToNonFiniteDouble(
std::string const &value) {
539 if (value ==
"NAN") {
542 if (value ==
"+INFINITY") {
545 if (value ==
"-INFINITY") {
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);
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);
562 void updateKeyImpl(
Fits &fits,
char const *key,
bool const &value,
char const *comment) {
564 fits_update_key(reinterpret_cast<fitsfile *>(fits.
fptr), TLOGICAL, const_cast<char *>(key), &v,
565 const_cast<char *>(comment), &fits.
status);
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);
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),
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);
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()),
589 }
else if (strncmp(key,
"HISTORY", 7) == 0) {
590 fits_write_history(reinterpret_cast<fitsfile *>(fits.
fptr), const_cast<char *>(value.
c_str()),
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);
598 void writeKeyImpl(
Fits &fits,
char const *key,
bool const &value,
char const *comment) {
600 fits_write_key(reinterpret_cast<fitsfile *>(fits.
fptr), TLOGICAL, const_cast<char *>(key), &v,
601 const_cast<char *>(comment), &fits.
status);
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);
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),
617 template <
typename T>
619 updateKeyImpl(*
this, key.
c_str(), value, comment.
c_str());
620 if (behavior & AUTO_CHECK) {
625 template <
typename T>
627 writeKeyImpl(*
this, key.
c_str(), value, comment.
c_str());
628 if (behavior & AUTO_CHECK) {
633 template <
typename T>
635 updateKeyImpl(*
this, key.
c_str(), value, 0);
636 if (behavior & AUTO_CHECK) {
641 template <
typename T>
643 writeKeyImpl(*
this, key.
c_str(), value, 0);
644 if (behavior & AUTO_CHECK) {
649 template <
typename T>
651 updateKey((boost::format(
"%s%d") % prefix % (n + 1)).str(), value, comment);
652 if (behavior & AUTO_CHECK) {
657 template <
typename T>
659 writeKey((boost::format(
"%s%d") % prefix % (n + 1)).str(), value, comment);
660 if (behavior & AUTO_CHECK) {
665 template <
typename T>
667 updateKey((boost::format(
"%s%d") % prefix % (n + 1)).str(), value);
668 if (behavior & AUTO_CHECK) {
673 template <
typename T>
675 writeKey((boost::format(
"%s%d") % prefix % (n + 1)).str(), value);
676 if (behavior & AUTO_CHECK) {
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),
693 fits_read_key_longstr(reinterpret_cast<fitsfile *>(fits.
fptr), const_cast<char *>(key), &buf, 0,
701 void readKeyImpl(
Fits &fits,
char const *key,
double &value) {
705 char buf[FLEN_VALUE];
706 fits_read_keyword(reinterpret_cast<fitsfile *>(fits.
fptr), const_cast<char *>(key), buf, 0, &fits.
status);
710 if (
std::string(buf).find(
'\'') != std::string::npos) {
712 readKeyImpl(fits, key, unquoted);
716 value = stringToNonFiniteDouble(unquoted);
720 (boost::format(
"Unrecognised string value for keyword '%s' when parsing as double: %s") %
725 fits_read_key(reinterpret_cast<fitsfile *>(fits.
fptr), FitsType<double>::CONSTANT,
726 const_cast<char *>(key), &value, 0, &fits.
status);
732 template <
typename T>
734 readKeyImpl(*
this, key.
c_str(), value);
735 if (behavior & AUTO_CHECK) {
745 fits_get_hdrspace(reinterpret_cast<fitsfile *>(fptr), &nKeys, 0, &status);
751 fits_read_keyn(reinterpret_cast<fitsfile *>(fptr), i, key, value, comment, &status);
754 commentStr = comment;
756 while (valueStr.
size() > 2 && valueStr[valueStr.
size() - 2] ==
'&' && i <= nKeys) {
758 fits_read_record(reinterpret_cast<fitsfile *>(fptr), i, key, &status);
759 if (strncmp(key,
"CONTINUE", 8) != 0) {
766 if (firstQuote == std::string::npos) {
771 boost::format(
"Invalid CONTINUE at header key %d: \"%s\".") % i % card));
774 if (lastQuote == std::string::npos) {
779 boost::format(
"Invalid CONTINUE at header key %d: \"%s\".") % i % card));
781 valueStr += card.
substr(firstQuote + 1, lastQuote - firstQuote);
783 if (slash != std::string::npos) {
788 if (behavior & AUTO_CHECK) {
791 functor(keyStr, valueStr, commentStr);
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)));
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, const_cast<long *>(naxes), &status);
1124 if (behavior & AUTO_CHECK) {
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) {
1144 struct ImageCompressionContext {
1147 :
fits(fits_), old(
fits.getImageCompression()) {
1148 fits.setImageCompression(useThis);
1150 ~ImageCompressionContext() {
1154 fits.setImageCompression(old);
1169 template <
typename T>
1173 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(),
const_cast<void *
>(pixels->getData()),
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,
"Scaling: MEMORY = BZERO + BSCALE * DISK",
1245 fits_write_key_dbl(
fits,
"BSCALE", scale.
bscale, 12,
"Scaling: MEMORY = BZERO + BSCALE * DISK",
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) {
1277 template <
typename T,
class Enable =
void>
1279 static T constexpr value = 0;
1283 template <
typename T>
1284 struct NullValue<T, typename std::enable_if<std::numeric_limits<T>::has_quiet_NaN>::type> {
1290 template <
typename T>
1291 void Fits::readImageImpl(
int nAxis, T *data,
long *begin,
long *
end,
long *increment) {
1292 T null = NullValue<T>::value;
1294 fits_read_subset(reinterpret_cast<fitsfile *>(fptr), FitsType<T>::CONSTANT, begin, end, increment,
1295 reinterpret_cast<void *>(&null), data, &anyNulls, &status);
1301 fits_get_img_dim(reinterpret_cast<fitsfile *>(fptr), &nAxis, &status);
1306 void Fits::getImageShapeImpl(
int maxDim,
long *nAxes) {
1307 fits_get_img_size(reinterpret_cast<fitsfile *>(fptr), maxDim, nAxes, &status);
1311 template <
typename T>
1314 fits_get_img_equivtype(reinterpret_cast<fitsfile *>(fptr), &imageType, &status);
1317 if (imageType < 0) {
1320 return imageType <= FitsBitPix<T>::CONSTANT;
1327 switch (imageType) {
1338 auto fits =
reinterpret_cast<fitsfile *
>(fptr);
1340 fits_get_compression_type(
fits, &compType, &status);
1341 if (behavior & AUTO_CHECK) {
1346 fits_get_tile_dim(
fits, tiles.getNumElements(), tiles.getData(), &status);
1347 if (behavior & AUTO_CHECK) {
1351 float quantizeLevel;
1352 fits_get_quantize_level(
fits, &quantizeLevel, &status);
1353 if (behavior & AUTO_CHECK) {
1361 auto fits =
reinterpret_cast<fitsfile *
>(fptr);
1362 fits_unset_compression_request(
fits, &status);
1366 if (behavior & AUTO_CHECK) {
1375 fits_set_tile_dim(
fits, comp.
tiles.getNumElements(), comp.
tiles.getData(), &status);
1376 if (behavior & AUTO_CHECK) {
1382 if (behavior & AUTO_CHECK) {
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,
1399 }
else if (mode ==
"w" || mode ==
"wb") {
1400 boost::filesystem::remove(filename);
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,
1406 fits_get_num_hdus(reinterpret_cast<fitsfile *>(
fptr), &nHdu, &
status);
1407 fits_movabs_hdu(reinterpret_cast<fitsfile *>(
fptr), nHdu, NULL, &
status);
1412 fits_close_file(reinterpret_cast<fitsfile *>(
fptr), &tmpStatus);
1417 (boost::format(
"Invalid mode '%s' given when opening file '%s'") % mode % filename).str());
1426 typedef void *(*Reallocator)(
void *,
std::size_t);
1429 if (mode ==
"r" || mode ==
"rb") {
1430 fits_open_memfile(reinterpret_cast<fitsfile **>(&
fptr),
"unused", READONLY, &manager._ptr,
1431 &manager._len, 0, 0,
1433 }
else if (mode ==
"w" || mode ==
"wb") {
1434 Reallocator reallocator = 0;
1436 fits_create_memfile(reinterpret_cast<fitsfile **>(&
fptr), &manager._ptr, &manager._len, 0,
1439 }
else if (mode ==
"a" || mode ==
"ab") {
1440 Reallocator reallocator = 0;
1442 fits_open_memfile(reinterpret_cast<fitsfile **>(&
fptr),
"unused", READWRITE, &manager._ptr,
1443 &manager._len, 0, reallocator, &
status);
1445 fits_get_num_hdus(reinterpret_cast<fitsfile *>(
fptr), &nHdu, &
status);
1446 fits_movabs_hdu(reinterpret_cast<fitsfile *>(
fptr), nHdu, NULL, &
status);
1451 fits_close_file(reinterpret_cast<fitsfile *>(
fptr), &tmpStatus);
1455 (boost::format(
"Invalid mode '%s' given when opening memory file at '%s'") % mode %
1461 *
this, boost::format(
"Opening memory file at '%s' with mode '%s'") % manager._ptr % mode);
1466 fits_close_file(reinterpret_cast<fitsfile *>(
fptr), &
status);
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) {
1482 combined->copy(
name, first,
name, asScalar);
1485 for (
auto const &
name : second->getOrderedNames()) {
1486 auto const iscv = isCommentIsValid(*second,
name);
1487 if (iscv.isComment) {
1493 combined->copy(
name, second,
name, asScalar);
1512 auto metadata = std::make_shared<lsst::daf::base::PropertyList>();
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");
1520 inherit = metadata->get<
bool>(
"INHERIT");
1522 if (strip) metadata->remove(
"INHERIT");
1528 auto primaryHduMetadata = std::make_shared<daf::base::PropertyList>();
1533 auto const emptyMetadata = std::make_shared<lsst::daf::base::PropertyList>();
1546 HduMove(HduMove
const &) =
delete;
1548 HduMove(
Fits &
fits,
int hdu) : _fits(fits), _enabled(
true) { _fits.setHdu(hdu); }
1562 void disable() { _enabled =
false; }
1572 auto fits =
reinterpret_cast<fitsfile *
>(
fptr);
1586 HduMove move{*
this, 1};
1587 bool isCompressed = fits_is_compressed_image(
fits, &
status);
1594 return isCompressed;
1601 config.getAsDouble(
"compression.quantizeLevel")),
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")) {}
1612 template <
typename T>
1615 output.
add(name, input.
get<T>(name, defaultValue));
1618 template <
typename T>
1627 auto validated = std::make_shared<daf::base::PropertySet>();
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);
1634 validateEntry(*validated, config,
"scaling.algorithm",
std::string(
"NONE"));
1635 validateEntry(*validated, config,
"scaling.bitpix", 0);
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);
1645 for (
auto const &
name : config.
names(
false)) {
1646 if (!validated->exists(
name)) {
1648 os <<
"Invalid image write option: " <<
name;
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 &); 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>(); 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); 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) 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>) 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>) 1699 #define IMAGE_TYPES \ 1700 (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.
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.
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.
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.
std::vector< std::string > paramNames(bool topLevelOnly=true) const
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.
lsst::geom::Box2I getBBox(ImageOrigin origin=PARENT) const
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 > getOrderedNames(void) const
std::shared_ptr< daf::base::PropertyList > createTrivialWcsMetadata(std::string const &wcsName, lsst::geom::Point2I const &xy0)
ImageCompressionOptions::CompressionAlgorithm compressionAlgorithmFromString(std::string const &name)
Interpret compression algorithm expressed in string.
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.
std::unique_ptr< SchemaItem< U > > result
void setHdu(int hdu, bool relative=false)
Set the current HDU.
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's origin.
#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
std::vector< std::string > names(bool topLevelOnly=true) const
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.