lsst.afw  16.0-43-gaa65a4573+2
FitsSchemaInputMapper.cc
Go to the documentation of this file.
1 // -*- lsst-c++ -*-
2 
3 #include <array>
4 #include <cmath>
5 #include <cstdint>
6 #include <cstdio>
7 #include <string>
8 
9 #include "boost/regex.hpp"
10 #include "boost/multi_index_container.hpp"
11 #include "boost/multi_index/sequenced_index.hpp"
12 #include "boost/multi_index/ordered_index.hpp"
13 #include "boost/multi_index/hashed_index.hpp"
14 #include "boost/multi_index/member.hpp"
15 
16 #include "lsst/log/Log.h"
17 #include "lsst/geom.h"
20 
21 namespace lsst {
22 namespace afw {
23 namespace table {
24 namespace io {
25 
26 namespace {
27 
28 // A quirk of Boost.MultiIndex (which we use for our container of FitsSchemaItems)
29 // that you have to use a special functor (like this one) to set data members
30 // in a container with set indices (because setting those values might require
31 // the element to be moved to a different place in the set). Check out
32 // the Boost.MultiIndex docs for more information.
33 template <std::string FitsSchemaItem::*Member>
34 struct SetFitsSchemaString {
35  void operator()(FitsSchemaItem &item) { item.*Member = _v; }
36  explicit SetFitsSchemaString(std::string const &v) : _v(v) {}
37 
38 private:
39  std::string const &_v;
40 };
41 
42 } // namespace
43 
45 public:
46  // A container class (based on Boost.MultiIndex) that provides three sort orders,
47  // on column number, flag bit, and name (ttype). This allows us to insert fields into the
48  // schema in the correct order, regardless of which order they appear in the
49  // FITS header.
50  typedef boost::multi_index_container<
52  boost::multi_index::indexed_by<
53  boost::multi_index::ordered_non_unique<
54  boost::multi_index::member<FitsSchemaItem, int, &FitsSchemaItem::column>>,
55  boost::multi_index::ordered_non_unique<
56  boost::multi_index::member<FitsSchemaItem, int, &FitsSchemaItem::bit>>,
57  boost::multi_index::hashed_unique<
58  boost::multi_index::member<FitsSchemaItem, std::string, &FitsSchemaItem::ttype>>,
59  boost::multi_index::sequenced<>>>
61 
62  // Typedefs for the special functors used to set data members.
63  typedef SetFitsSchemaString<&FitsSchemaItem::ttype> SetTTYPE;
64  typedef SetFitsSchemaString<&FitsSchemaItem::tform> SetTFORM;
65  typedef SetFitsSchemaString<&FitsSchemaItem::tccls> SetTCCLS;
66  typedef SetFitsSchemaString<&FitsSchemaItem::tunit> SetTUNIT;
67  typedef SetFitsSchemaString<&FitsSchemaItem::doc> SetDoc;
68 
69  // Typedefs for the different indices.
70  typedef InputContainer::nth_index<0>::type ByColumn;
71  typedef InputContainer::nth_index<1>::type ByBit;
72  typedef InputContainer::nth_index<2>::type ByName;
73  typedef InputContainer::nth_index<3>::type AsList;
74 
75  // Getters for the different indices.
76  ByColumn &byColumn() { return inputs.get<0>(); }
77  ByBit &byBit() { return inputs.get<1>(); }
78  ByName &byName() { return inputs.get<2>(); }
79  AsList &asList() { return inputs.get<3>(); }
80 
81  Impl() : version(0), flagColumn(0), archiveHdu(-1) {}
82 
83  int version;
92 };
93 
95  : _impl(std::make_shared<Impl>()) {
96  // Set the table version. If AFW_TABLE_VERSION tag exists, use that
97  // If not, set to 0 if it has an AFW_TYPE, Schema default otherwise (DM-590)
98  if (!metadata.exists("AFW_TYPE")) {
99  _impl->version = lsst::afw::table::Schema::VERSION;
100  }
101  _impl->version = metadata.get("AFW_TABLE_VERSION", _impl->version);
102  if (stripMetadata) {
103  metadata.remove("AFW_TABLE_VERSION");
104  }
105  if (stripMetadata) {
106  metadata.remove("AFW_TYPE");
107  }
108 
109  // Find a key that indicates an Archive stored on other HDUs
110  _impl->archiveHdu = metadata.get("AR_HDU", -1);
111  if (_impl->archiveHdu > 0) {
112  --_impl->archiveHdu; // AR_HDU is 1-indexed for historical reasons (RFC-304; see Source.cc)
113  if (stripMetadata) {
114  metadata.remove("AR_HDU");
115  }
116  }
117 
118  // Read aliases, stored as header entries with key 'ALIAS'
119  try {
120  std::vector<std::string> rawAliases = metadata.getArray<std::string>("ALIAS");
121  for (std::vector<std::string>::const_iterator i = rawAliases.begin(); i != rawAliases.end(); ++i) {
122  std::size_t pos = i->find_first_of(':');
123  if (pos == std::string::npos) {
125  (boost::format("Malformed alias definition: '%s'") % (*i)).str());
126  }
127  _impl->schema.getAliasMap()->set(i->substr(0, pos), i->substr(pos + 1, std::string::npos));
128  }
129  if (stripMetadata) {
130  metadata.remove("ALIAS");
131  }
132  } catch (pex::exceptions::NotFoundError &) {
133  // if there are no aliases, just move on
134  }
135 
136  if (_impl->version == 0) {
137  // Read slots saved using an old mechanism in as aliases, since the new slot mechanism delegates
138  // slot definition to the AliasMap.
139  static std::array<std::pair<std::string, std::string>, 7> oldSlotKeys = {
140  {std::make_pair("PSF_FLUX", "slot_PsfFlux"), std::make_pair("AP_FLUX", "slot_ApFlux"),
141  std::make_pair("INST_FLUX", "slot_GaussianFlux"),
142  std::make_pair("MODEL_FLUX", "slot_ModelFlux"),
143  std::make_pair("CALIB_FLUX", "slot_CalibFlux"), std::make_pair("CENTROID", "slot_Centroid"),
144  std::make_pair("SHAPE", "slot_Shape")}};
145  for (std::size_t i = 0; i < oldSlotKeys.size(); ++i) {
146  std::string target = metadata.get(oldSlotKeys[i].first + "_SLOT", std::string(""));
147  if (!target.empty()) {
148  _impl->schema.getAliasMap()->set(oldSlotKeys[i].second, target);
149  if (stripMetadata) {
150  metadata.remove(oldSlotKeys[i].first);
151  metadata.remove(oldSlotKeys[i].first + "_ERR_SLOT");
152  metadata.remove(oldSlotKeys[i].first + "_FLAG_SLOT");
153  }
154  }
155  }
156  }
157 
158  // Read the rest of the header into the intermediate inputs container.
159  std::vector<std::string> keyList = metadata.getOrderedNames();
160  for (std::vector<std::string>::const_iterator key = keyList.begin(); key != keyList.end(); ++key) {
161  if (key->compare(0, 5, "TTYPE") == 0) {
162  int column = std::stoi(key->substr(5)) - 1;
163  auto iter = _impl->byColumn().lower_bound(column);
164  if (iter == _impl->byColumn().end() || iter->column != column) {
165  iter = _impl->byColumn().insert(iter, FitsSchemaItem(column, -1));
166  }
167  std::string v = metadata.get<std::string>(*key);
168  _impl->byColumn().modify(iter, Impl::SetTTYPE(v));
169  if (iter->doc.empty()) { // don't overwrite if already set with TDOCn
170  _impl->byColumn().modify(iter, Impl::SetDoc(metadata.getComment(*key)));
171  }
172  if (stripMetadata) {
173  metadata.remove(*key);
174  }
175  } else if (key->compare(0, 5, "TFLAG") == 0) {
176  int bit = std::stoi(key->substr(5)) - 1;
177  auto iter = _impl->byBit().lower_bound(bit);
178  if (iter == _impl->byBit().end() || iter->bit != bit) {
179  iter = _impl->byBit().insert(iter, FitsSchemaItem(-1, bit));
180  }
181  std::string v = metadata.get<std::string>(*key);
182  _impl->byBit().modify(iter, Impl::SetTTYPE(v));
183  if (iter->doc.empty()) { // don't overwrite if already set with TFDOCn
184  _impl->byBit().modify(iter, Impl::SetDoc(metadata.getComment(*key)));
185  }
186  if (stripMetadata) {
187  metadata.remove(*key);
188  }
189  } else if (key->compare(0, 4, "TDOC") == 0) {
190  int column = std::stoi(key->substr(4)) - 1;
191  auto iter = _impl->byColumn().lower_bound(column);
192  if (iter == _impl->byColumn().end() || iter->column != column) {
193  iter = _impl->byColumn().insert(iter, FitsSchemaItem(column, -1));
194  }
195  _impl->byColumn().modify(iter, Impl::SetDoc(metadata.get<std::string>(*key)));
196  if (stripMetadata) {
197  metadata.remove(*key);
198  }
199  } else if (key->compare(0, 5, "TFDOC") == 0) {
200  int bit = std::stoi(key->substr(5)) - 1;
201  auto iter = _impl->byBit().lower_bound(bit);
202  if (iter == _impl->byBit().end() || iter->bit != bit) {
203  iter = _impl->byBit().insert(iter, FitsSchemaItem(-1, bit));
204  }
205  _impl->byBit().modify(iter, Impl::SetDoc(metadata.get<std::string>(*key)));
206  if (stripMetadata) {
207  metadata.remove(*key);
208  }
209  } else if (key->compare(0, 5, "TUNIT") == 0) {
210  int column = std::stoi(key->substr(5)) - 1;
211  auto iter = _impl->byColumn().lower_bound(column);
212  if (iter == _impl->byColumn().end() || iter->column != column) {
213  iter = _impl->byColumn().insert(iter, FitsSchemaItem(column, -1));
214  }
215  _impl->byColumn().modify(iter, Impl::SetTUNIT(metadata.get<std::string>(*key)));
216  if (stripMetadata) {
217  metadata.remove(*key);
218  }
219  } else if (key->compare(0, 5, "TCCLS") == 0) {
220  int column = std::stoi(key->substr(5)) - 1;
221  auto iter = _impl->byColumn().lower_bound(column);
222  if (iter == _impl->byColumn().end() || iter->column != column) {
223  iter = _impl->byColumn().insert(iter, FitsSchemaItem(column, -1));
224  }
225  _impl->byColumn().modify(iter, Impl::SetTCCLS(metadata.get<std::string>(*key)));
226  if (stripMetadata) {
227  metadata.remove(*key);
228  }
229  } else if (key->compare(0, 5, "TFORM") == 0) {
230  int column = std::stoi(key->substr(5)) - 1;
231  auto iter = _impl->byColumn().lower_bound(column);
232  if (iter == _impl->byColumn().end() || iter->column != column) {
233  iter = _impl->byColumn().insert(iter, FitsSchemaItem(column, -1));
234  }
235  _impl->byColumn().modify(iter, Impl::SetTFORM(metadata.get<std::string>(*key)));
236  if (stripMetadata) {
237  metadata.remove(*key);
238  }
239  } else if (key->compare(0, 5, "TZERO") == 0) {
240  if (stripMetadata) {
241  metadata.remove(*key);
242  }
243  } else if (key->compare(0, 5, "TSCAL") == 0) {
244  if (stripMetadata) {
245  metadata.remove(*key);
246  }
247  } else if (key->compare(0, 5, "TNULL") == 0) {
248  if (stripMetadata) {
249  metadata.remove(*key);
250  }
251  } else if (key->compare(0, 5, "TDISP") == 0) {
252  if (stripMetadata) {
253  metadata.remove(*key);
254  }
255  }
256  }
257 
258  // Find the column used to store flags, and setup the flag-handling data members from it.
259  _impl->flagColumn = metadata.get("FLAGCOL", 0);
260  if (_impl->flagColumn > 0) {
261  if (stripMetadata) {
262  metadata.remove("FLAGCOL");
263  }
264  --_impl->flagColumn; // switch from 1-indexed to 0-indexed
265  auto iter = _impl->byColumn().find(_impl->flagColumn);
266  if (iter == _impl->byColumn().end()) {
267  throw LSST_EXCEPT(
269  (boost::format("Column for flag data not found; FLAGCOL=%d") % _impl->flagColumn).str());
270  }
271  // Regex to unpack a FITS TFORM value for a bit array column (TFORM code 'X'). The number
272  // that precedes the code is the size of the array; the number that follows it (if present)
273  // is ignored.
274  static boost::regex const regex("(\\d+)?X\\(?(\\d)*\\)?", boost::regex::perl);
275  boost::smatch m;
276  if (!boost::regex_match(iter->tform, m, regex)) {
277  throw LSST_EXCEPT(
279  (boost::format("Invalid TFORM key for flags column: '%s'") % iter->tform).str());
280  }
281  int nFlags = 1;
282  if (m[1].matched) {
283  nFlags = std::stoi(m[1].str());
284  }
285  _impl->flagKeys.resize(nFlags);
286  _impl->flagWorkspace.reset(new bool[nFlags]);
287  // Delete the flag column from the input list so we don't interpret it as a
288  // regular field.
289  _impl->byColumn().erase(iter);
290  }
291 }
292 
298 
299 void FitsSchemaInputMapper::setArchive(std::shared_ptr<InputArchive> archive) { _impl->archive = archive; }
300 
302  int oldHdu = fits.getHdu();
303  if (_impl->archiveHdu < 0) _impl->archiveHdu = oldHdu + 1;
304  try {
305  fits.setHdu(_impl->archiveHdu);
306  _impl->archive.reset(new io::InputArchive(InputArchive::readFits(fits)));
307  fits.setHdu(oldHdu);
308  return true;
309  } catch (afw::fits::FitsError &) {
310  fits.status = 0;
311  fits.setHdu(oldHdu);
312  _impl->archiveHdu = -1;
313  return false;
314  }
315 }
316 
317 bool FitsSchemaInputMapper::hasArchive() const { return static_cast<bool>(_impl->archive); }
318 
320  auto iter = _impl->byName().find(ttype);
321  if (iter == _impl->byName().end()) {
322  return 0;
323  }
324  return &(*iter);
325 }
326 
327 FitsSchemaItem const *FitsSchemaInputMapper::find(int column) const {
328  auto iter = _impl->byColumn().lower_bound(column);
329  if (iter == _impl->byColumn().end() || iter->column != column) {
330  return 0;
331  }
332  return &(*iter);
333 }
334 
336  auto iter = _impl->byColumn().lower_bound(item->column);
337  assert(iter != _impl->byColumn().end() && iter->column == item->column);
338  _impl->byColumn().erase(iter);
339 }
340 
342  auto iter = _impl->byName().find(ttype);
343  if (iter != _impl->byName().end() && iter->ttype == ttype) {
344  _impl->byName().erase(iter);
345  }
346 }
347 
349  auto iter = _impl->byColumn().lower_bound(column);
350  if (iter != _impl->byColumn().end() && iter->column == column) {
351  _impl->byColumn().erase(iter);
352  }
353 }
354 
355 void erase(int column);
356 
358  _impl->readers.push_back(std::move(reader));
359 }
360 
361 namespace {
362 
363 template <typename T>
364 class StandardReader : public FitsColumnReader {
365 public:
367  FieldBase<T> const &base = FieldBase<T>()) {
368  return std::unique_ptr<FitsColumnReader>(new StandardReader(schema, item, base));
369  }
370 
371  StandardReader(Schema &schema, FitsSchemaItem const &item, FieldBase<T> const &base)
372  : _column(item.column), _key(schema.addField<T>(item.ttype, item.doc, item.tunit, base)) {}
373 
374  void readCell(BaseRecord &record, std::size_t row, afw::fits::Fits &fits,
375  std::shared_ptr<InputArchive> const &archive) const override {
376  fits.readTableArray(row, _column, _key.getElementCount(), record.getElement(_key));
377  }
378 
379 private:
380  int _column;
381  Key<T> _key;
382 };
383 
384 class AngleReader : public FitsColumnReader {
385 public:
387  Schema &schema, FitsSchemaItem const &item,
389  return std::unique_ptr<FitsColumnReader>(new AngleReader(schema, item, base));
390  }
391 
392  AngleReader(Schema &schema, FitsSchemaItem const &item, FieldBase<lsst::geom::Angle> const &base)
393  : _column(item.column), _key(schema.addField<lsst::geom::Angle>(item.ttype, item.doc, "", base)) {
394  // We require an LSST-specific key in the headers before parsing a column
395  // as Angle at all, so we don't need to worry about other units or other
396  // spellings of radians. We do continue to support no units for backwards
397  // compatibility.
398  if (!item.tunit.empty() && item.tunit != "rad") {
400  "Angle fields must be persisted in radians (TUNIT='rad').");
401  }
402  }
403 
404  void readCell(BaseRecord &record, std::size_t row, afw::fits::Fits &fits,
405  std::shared_ptr<InputArchive> const &archive) const override {
406  double tmp = 0;
407  fits.readTableScalar(row, _column, tmp);
408  record.set(_key, tmp * lsst::geom::radians);
409  }
410 
411 private:
412  int _column;
414 };
415 
416 class StringReader : public FitsColumnReader {
417 public:
418  static std::unique_ptr<FitsColumnReader> make(Schema &schema, FitsSchemaItem const &item, int size) {
419  return std::unique_ptr<FitsColumnReader>(new StringReader(schema, item, size));
420  }
421 
422  StringReader(Schema &schema, FitsSchemaItem const &item, int size)
423  : _column(item.column),
424  _key(schema.addField<std::string>(item.ttype, item.doc, item.tunit, size)),
425  _isVariableLength(size == 0) {}
426 
427  void readCell(BaseRecord &record, std::size_t row, afw::fits::Fits &fits,
428  std::shared_ptr<InputArchive> const &archive) const override {
429  std::string s;
430  fits.readTableScalar(row, _column, s, _isVariableLength);
431  record.set(_key, s);
432  }
433 
434 private:
435  int _column;
436  Key<std::string> _key;
437  bool _isVariableLength;
438 };
439 
440 template <typename T>
441 class VariableLengthArrayReader : public FitsColumnReader {
442 public:
444  return std::unique_ptr<FitsColumnReader>(new VariableLengthArrayReader(schema, item));
445  }
446 
447  VariableLengthArrayReader(Schema &schema, FitsSchemaItem const &item)
448  : _column(item.column), _key(schema.addField<Array<T>>(item.ttype, item.doc, item.tunit, 0)) {}
449 
450  void readCell(BaseRecord &record, std::size_t row, afw::fits::Fits &fits,
451  std::shared_ptr<InputArchive> const &archive) const override {
452  int size = fits.getTableArraySize(row, _column);
453  ndarray::Array<T, 1, 1> array = ndarray::allocate(size);
454  fits.readTableArray(row, _column, size, array.getData());
455  record.set(_key, array);
456  }
457 
458 private:
459  int _column;
460  Key<Array<T>> _key;
461 };
462 
463 // Read a 2-element FITS array column as separate x and y Schema fields (hence converting
464 // from the old Point compound field to the new PointKey FunctorKey).
465 template <typename T>
466 class PointConversionReader : public FitsColumnReader {
467 public:
469  return std::unique_ptr<FitsColumnReader>(new PointConversionReader(schema, item));
470  }
471 
472  PointConversionReader(Schema &schema, FitsSchemaItem const &item)
473  : _column(item.column), _key(PointKey<T>::addFields(schema, item.ttype, item.doc, item.tunit)) {}
474 
475  void readCell(BaseRecord &record, std::size_t row, afw::fits::Fits &fits,
476  std::shared_ptr<InputArchive> const &archive) const override {
477  std::array<T, 2> buffer;
478  fits.readTableArray(row, _column, 2, buffer.data());
479  record.set(_key, lsst::geom::Point<T, 2>(buffer[0], buffer[1]));
480  }
481 
482 private:
483  int _column;
484  PointKey<T> _key;
485 };
486 
487 // Read a 2-element FITS array column as separate ra and dec Schema fields (hence converting
488 // from the old Coord compound field to the new CoordKey FunctorKey).
489 class CoordConversionReader : public FitsColumnReader {
490 public:
492  return std::unique_ptr<FitsColumnReader>(new CoordConversionReader(schema, item));
493  }
494 
495  CoordConversionReader(Schema &schema, FitsSchemaItem const &item)
496  : _column(item.column), _key(CoordKey::addFields(schema, item.ttype, item.doc)) {}
497 
498  void readCell(BaseRecord &record, std::size_t row, afw::fits::Fits &fits,
499  std::shared_ptr<InputArchive> const &archive) const override {
501  fits.readTableArray(row, _column, 2, buffer.data());
502  record.set(_key, lsst::geom::SpherePoint(buffer[0], buffer[1]));
503  }
504 
505 private:
506  int _column;
507  CoordKey _key;
508 };
509 
510 // Read a 3-element FITS array column as separate xx, yy, and xy Schema fields (hence converting
511 // from the old Moments compound field to the new QuadrupoleKey FunctorKey).
512 class MomentsConversionReader : public FitsColumnReader {
513 public:
515  return std::unique_ptr<FitsColumnReader>(new MomentsConversionReader(schema, item));
516  }
517 
518  MomentsConversionReader(Schema &schema, FitsSchemaItem const &item)
519  : _column(item.column),
520  _key(QuadrupoleKey::addFields(schema, item.ttype, item.doc, CoordinateType::PIXEL)) {}
521 
522  void readCell(BaseRecord &record, std::size_t row, afw::fits::Fits &fits,
523  std::shared_ptr<InputArchive> const &archive) const override {
524  std::array<double, 3> buffer;
525  fits.readTableArray(row, _column, 3, buffer.data());
526  record.set(_key, geom::ellipses::Quadrupole(buffer[0], buffer[1], buffer[2], false));
527  }
528 
529 private:
530  int _column;
531  QuadrupoleKey _key;
532 };
533 
534 // Read a FITS array column representing a packed symmetric matrix into
535 // Schema fields for each element (hence converting from the old Covariance
536 // compound field to the new CovarianceMatrixKey FunctorKey).
537 template <typename T, int N>
538 class CovarianceConversionReader : public FitsColumnReader {
539 public:
540  static std::string guessUnits(std::string const &oldUnits) {
541  static boost::regex const regex("(.*)(\\^(\\d+))?", boost::regex::perl);
542  boost::smatch m;
543  if (!boost::regex_match(oldUnits, m, regex)) {
544  int oldPower = std::stoi(m[2]);
545  int newPower = std::sqrt(oldPower);
546  return std::to_string(newPower);
547  }
548  return oldUnits;
549  }
550 
552  std::vector<std::string> const &names) {
553  return std::unique_ptr<FitsColumnReader>(new CovarianceConversionReader(schema, item, names));
554  }
555 
556  CovarianceConversionReader(Schema &schema, FitsSchemaItem const &item,
557  std::vector<std::string> const &names)
558  : _column(item.column),
559  _size(names.size()),
560  _key(CovarianceMatrixKey<T, N>::addFields(schema, item.ttype, names, guessUnits(item.tunit))),
561  _buffer(new T[detail::computeCovariancePackedSize(names.size())]) {}
562 
563  void readCell(BaseRecord &record, std::size_t row, afw::fits::Fits &fits,
564  std::shared_ptr<InputArchive> const &archive) const override {
565  fits.readTableArray(row, _column, detail::computeCovariancePackedSize(_size), _buffer.get());
566  for (int i = 0; i < _size; ++i) {
567  for (int j = i; j < _size; ++j) {
568  _key.setElement(record, i, j, _buffer[detail::indexCovariance(i, j)]);
569  }
570  }
571  }
572 
573 private:
574  int _column;
575  int _size;
577  std::unique_ptr<T[]> _buffer;
578 };
579 
580 std::unique_ptr<FitsColumnReader> makeColumnReader(Schema &schema, FitsSchemaItem const &item) {
581  // Regex to unpack a FITS TFORM value. The first number is the size of the array (1 if not present),
582  // followed by an alpha code indicating the type (preceded by P or Q for variable size array).
583  // The last number is ignored.
584  static boost::regex const regex("(\\d+)?([PQ])?(\\u)\\(?(\\d)*\\)?", boost::regex::perl);
585  // start by parsing the format; this tells the element type of the field and the number of elements
586  boost::smatch m;
587  if (!boost::regex_match(item.tform, m, regex)) {
589  }
590  int size = 1;
591  if (m[1].matched) {
592  size = std::stoi(m[1].str());
593  }
594  char code = m[3].str()[0];
595  if (m[2].matched) {
596  // P or Q presence indicates a variable-length array, which we can get by just setting the
597  // size to zero and letting the rest of the logic run its course.
598  size = 0;
599  }
600  // switch code over FITS codes that correspond to different element types
601  switch (code) {
602  case 'B': // 8-bit unsigned integers -- can only be scalars or Arrays
603  if (size == 1) {
604  if (item.tccls == "Array") {
605  return StandardReader<Array<std::uint8_t>>::make(schema, item, size);
606  }
607  return StandardReader<std::uint8_t>::make(schema, item);
608  }
609  if (size == 0) {
610  return VariableLengthArrayReader<std::uint8_t>::make(schema, item);
611  }
612  return StandardReader<Array<std::uint8_t>>::make(schema, item, size);
613 
614  case 'I': // 16-bit integers - can only be scalars or Arrays (we assume they're unsigned, since
615  // that's all we ever write, and CFITSIO will complain later if they aren't)
616  if (size == 1) {
617  if (item.tccls == "Array") {
618  return StandardReader<Array<std::uint16_t>>::make(schema, item, size);
619  }
620  return StandardReader<std::uint16_t>::make(schema, item);
621  }
622  if (size == 0) {
623  return VariableLengthArrayReader<std::uint16_t>::make(schema, item);
624  }
625  return StandardReader<Array<std::uint16_t>>::make(schema, item, size);
626  case 'J': // 32-bit integers - can only be scalars, Point fields, or Arrays
627  if (size == 0) {
628  return VariableLengthArrayReader<std::int32_t>::make(schema, item);
629  }
630  if (item.tccls == "Point") {
631  return PointConversionReader<std::int32_t>::make(schema, item);
632  }
633  if (size > 1 || item.tccls == "Array") {
634  return StandardReader<Array<std::int32_t>>::make(schema, item, size);
635  }
636  return StandardReader<std::int32_t>::make(schema, item);
637  case 'K': // 64-bit integers - can only be scalars.
638  if (size == 1) {
639  return StandardReader<std::int64_t>::make(schema, item);
640  }
641  case 'E': // floats
642  if (size == 0) {
643  return VariableLengthArrayReader<float>::make(schema, item);
644  }
645  if (size == 1) {
646  if (item.tccls == "Array") {
647  return StandardReader<Array<float>>::make(schema, item, 1);
648  }
649  // Just use scalars for Covariances of size 1, since that results in more
650  // natural field names (essentially never happens anyway).
651  return StandardReader<float>::make(schema, item);
652  }
653  if (size == 3 && item.tccls == "Covariance(Point)") {
654  std::vector<std::string> names = {"x", "y"};
655  return CovarianceConversionReader<float, 2>::make(schema, item, names);
656  }
657  if (size == 6 && item.tccls == "Covariance(Moments)") {
658  std::vector<std::string> names = {"xx", "yy", "xy"};
659  return CovarianceConversionReader<float, 3>::make(schema, item, names);
660  }
661  if (item.tccls == "Covariance") {
662  double v = 0.5 * (std::sqrt(1 + 8 * size) - 1);
663  int n = std::lround(v);
664  if (n * (n + 1) != size * 2) {
665  throw LSST_EXCEPT(afw::fits::FitsError, "Covariance field has invalid size.");
666  }
667  std::vector<std::string> names(n);
668  for (int i = 0; i < n; ++i) {
669  names[i] = std::to_string(i);
670  }
671  return CovarianceConversionReader<float, Eigen::Dynamic>::make(schema, item, names);
672  }
673  return StandardReader<Array<float>>::make(schema, item, size);
674  case 'D': // doubles
675  if (size == 0) {
676  return VariableLengthArrayReader<double>::make(schema, item);
677  }
678  if (size == 1) {
679  if (item.tccls == "Angle") {
680  return AngleReader::make(schema, item);
681  }
682  if (item.tccls == "Array") {
683  return StandardReader<Array<double>>::make(schema, item, 1);
684  }
685  return StandardReader<double>::make(schema, item);
686  }
687  if (size == 2) {
688  if (item.tccls == "Point") {
689  return PointConversionReader<double>::make(schema, item);
690  }
691  if (item.tccls == "Coord") {
692  return CoordConversionReader::make(schema, item);
693  }
694  }
695  if (size == 3 && item.tccls == "Moments") {
696  return MomentsConversionReader::make(schema, item);
697  }
698  return StandardReader<Array<double>>::make(schema, item, size);
699  case 'A': // strings
700  // StringReader can read both fixed-length and variable-length (size=0) strings
701  return StringReader::make(schema, item, size);
702  default:
704  }
705 }
706 
707 bool endswith(std::string const &s, std::string const &suffix) {
708  return s.size() >= suffix.size() && s.compare(s.size() - suffix.size(), suffix.size(), suffix) == 0;
709 }
710 
711 // Replace the last n characters of a string with a new suffix string, returning the result as a new string
712 std::string replaceSuffix(std::string const &s, std::size_t n, std::string const &suffix) {
713  return s.substr(0, s.size() - n) + suffix;
714 }
715 
716 } // namespace
717 
719  if (_impl->version == 0) {
720  AliasMap &aliases = *_impl->schema.getAliasMap();
721  for (auto iter = _impl->asList().begin(); iter != _impl->asList().end(); ++iter) {
722  std::size_t flagPos = iter->ttype.find("flags");
723  if (flagPos != std::string::npos) {
724  // We want to create aliases that resolve "(.*)_flag" to "$1_flags"; old schemas will have
725  // the latter, but new conventions (including slots) expect the former.
726  // But we can't do that, because adding that alias directly results in a cycle in the
727  // aliases (since aliases do partial matches, and keep trying until there are no matches,
728  // we'd have "(.*)_flag" resolve to "$1_flagssssssssssssss...").
729  // Instead, we *rename* from "flags" to "flag", then create the reverse alias.
730  std::string ttype = iter->ttype;
731  std::string prefix = iter->ttype.substr(0, flagPos);
732  ttype.replace(flagPos, 5, "flag");
733  _impl->asList().modify(iter, Impl::SetTTYPE(ttype));
734  // Note that we're not aliasing the full field, just the first part - if we have multiple
735  // flag fields, one alias should be sufficient for all of them (because of partial matching).
736  // Of course, we'll try to recreate that alias every time we handle another flag field with
737  // the same prefix, but AliasMap know hows to handle that no-op set.
738  aliases.set(prefix + "flags", prefix + "flag");
739  } else if (iter->ttype.find("flux") != std::string::npos) {
740  // Create an alias that resolves "X_instFlux" to "X" or "X_instFluxErr" to "X_err".
741  if (endswith(iter->ttype, "_err")) {
742  aliases.set(replaceSuffix(iter->ttype, 4, "_instFluxErr"), iter->ttype);
743  } else {
744  aliases.set(iter->ttype + "_instFlux", iter->ttype);
745  }
746  } else if (endswith(iter->ttype, "_err")) {
747  // Create aliases that resolve "(.*)_(.*)Err" and "(.*)_(.*)_(.*)_Cov" to
748  // "$1_err_$2Err" and "$1_err_$2_$3_Cov", to make centroid and shape uncertainties
749  // available under the new conventions. We don't have to create aliases for the
750  // centroid and shape values themselves, as those will automatically be correct
751  // after the PointConversionReader and MomentsConversionReader do their work.
752  if (iter->tccls == "Covariance(Point)") {
753  aliases.set(replaceSuffix(iter->ttype, 4, "_xErr"), iter->ttype + "_xErr");
754  aliases.set(replaceSuffix(iter->ttype, 4, "_yErr"), iter->ttype + "_yErr");
755  aliases.set(replaceSuffix(iter->ttype, 4, "_x_y_Cov"), iter->ttype + "_x_y_Cov");
756  } else if (iter->tccls == "Covariance(Moments)") {
757  aliases.set(replaceSuffix(iter->ttype, 4, "_xxErr"), iter->ttype + "_xxErr");
758  aliases.set(replaceSuffix(iter->ttype, 4, "_yyErr"), iter->ttype + "_yyErr");
759  aliases.set(replaceSuffix(iter->ttype, 4, "_xyErr"), iter->ttype + "_xyErr");
760  aliases.set(replaceSuffix(iter->ttype, 4, "_xx_yy_Cov"), iter->ttype + "_xx_yy_Cov");
761  aliases.set(replaceSuffix(iter->ttype, 4, "_xx_xy_Cov"), iter->ttype + "_xx_xy_Cov");
762  aliases.set(replaceSuffix(iter->ttype, 4, "_yy_xy_Cov"), iter->ttype + "_yy_xy_Cov");
763  }
764  }
765  }
766  }
767  if (_impl->version == 1) {
768  // Version 1 tables use Sigma when we should use Err (see RFC-333) and had no fields
769  // that should have been named Sigma. So provide aliases xErr -> xSigma
770  AliasMap &aliases = *_impl->schema.getAliasMap();
771  for (auto iter = _impl->asList().begin(); iter != _impl->asList().end(); ++iter) {
772  if (iter->ttype.find("flux") != std::string::npos) {
773  // Create an alias that resolves "X_instFlux" to "X_flux" or "X_instFluxErr" to "X_fluxSigma".
774  if (endswith(iter->ttype, "fluxSigma")) {
775  // replace "fluxSigma"->"instFluxErr"
776  aliases.set(replaceSuffix(iter->ttype, 9, "instFluxErr"), iter->ttype);
777  } else {
778  // replace "flux"->"instFlux"
779  aliases.set(replaceSuffix(iter->ttype, 4, "instFlux"), iter->ttype);
780  }
781  } else if (endswith(iter->ttype, "Sigma")) {
782  aliases.set(replaceSuffix(iter->ttype, 5, "Err"), iter->ttype);
783  }
784  }
785  }
786  if (_impl->version == 2) {
787  // Version 2 tables used _flux when we should use _instFlux (see RFC-322).
788  AliasMap &aliases = *_impl->schema.getAliasMap();
789  for (auto iter = _impl->asList().begin(); iter != _impl->asList().end(); ++iter) {
790  if (iter->ttype.find("flux") != std::string::npos) {
791  // Create an alias that resolves "X_instFlux" to "X_flux" or "X_instFluxErr" to "X_fluxErr".
792  if (endswith(iter->ttype, "fluxErr")) {
793  // replace "fluxErr"->"instFluxErr"
794  aliases.set(replaceSuffix(iter->ttype, 9, "instFluxErr"), iter->ttype);
795  } else {
796  // replace "flux"->"instFlux"
797  aliases.set(replaceSuffix(iter->ttype, 4, "instFlux"), iter->ttype);
798  }
799  }
800  }
801  }
802  for (auto iter = _impl->asList().begin(); iter != _impl->asList().end(); ++iter) {
803  if (iter->bit < 0) { // not a Flag column
804  std::unique_ptr<FitsColumnReader> reader = makeColumnReader(_impl->schema, *iter);
805  if (reader) {
806  _impl->readers.push_back(std::move(reader));
807  } else {
808  LOGLS_WARN("afw.FitsSchemaInputMapper", "Format " << iter->tform << " for column "
809  << iter->ttype
810  << " not supported; skipping.");
811  }
812  } else { // is a Flag column
813  if (static_cast<std::size_t>(iter->bit) >= _impl->flagKeys.size()) {
815  (boost::format("Flag field '%s' is is in bit %d (0-indexed) of only %d") %
816  iter->ttype % iter->bit % _impl->flagKeys.size())
817  .str());
818  }
819  _impl->flagKeys[iter->bit] = _impl->schema.addField<Flag>(iter->ttype, iter->doc);
820  }
821  }
822  _impl->asList().clear();
823  return _impl->schema;
824 }
825 
827  if (!_impl->flagKeys.empty()) {
828  fits.readTableArray<bool>(row, _impl->flagColumn, _impl->flagKeys.size(), _impl->flagWorkspace.get());
829  for (std::size_t bit = 0; bit < _impl->flagKeys.size(); ++bit) {
830  record.set(_impl->flagKeys[bit], _impl->flagWorkspace[bit]);
831  }
832  }
833  for (auto iter = _impl->readers.begin(); iter != _impl->readers.end(); ++iter) {
834  (**iter).readCell(record, row, fits, _impl->archive);
835  }
836 }
837 } // namespace io
838 } // namespace table
839 } // namespace afw
840 } // namespace lsst
#define LOGLS_WARN(logger, message)
An ellipse core with quadrupole moments as parameters.
Definition: Quadrupole.h:47
Defines the fields and offsets for a table.
Definition: Schema.h:50
Field base class default implementation (used for numeric scalars and lsst::geom::Angle).
Definition: FieldBase.h:43
int m
Definition: SpanSet.cc:49
T empty(T... args)
Key< Flag > const & target
afw::table::Schema schema
Definition: GaussianPsf.cc:48
std::string const & getComment(std::string const &name) const
std::vector< T > getArray(std::string const &name) const
SetFitsSchemaString<&FitsSchemaItem::tccls > SetTCCLS
T to_string(T... args)
void set(std::string const &alias, std::string const &target)
Add an alias to the schema or replace an existing one.
Definition: AliasMap.cc:77
void readTableScalar(std::size_t row, int col, T &value)
Read an array scalar from a binary table.
Definition: fits.h:589
Mapping class that holds aliases for a Schema.
Definition: AliasMap.h:36
SetFitsSchemaString<&FitsSchemaItem::doc > SetDoc
STL namespace.
T end(T... args)
A class that describes a mapping from a FITS binary table to an afw::table Schema.
A simple struct that combines the two arguments that must be passed to most cfitsio routines and cont...
Definition: fits.h:296
int computeCovariancePackedSize(int size)
Defines the packed size of a covariance matrices.
Definition: FieldBase.h:35
long getTableArraySize(int col)
Return the size of an array column.
Definition: fits.cc:1091
AngleUnit constexpr radians
A structure that describes a field as a collection of related strings read from the FITS header...
SetFitsSchemaString<&FitsSchemaItem::tform > SetTFORM
Fits * fits
Definition: FitsWriter.cc:90
STL class.
virtual void remove(std::string const &name)
An exception thrown when problems are found when reading or writing FITS files.
Definition: fits.h:35
T data(T... args)
A base class for image defects.
A FunctorKey used to get or set a lsst::geom::Point from an (x,y) pair of int or double Keys...
Definition: aggregates.h:47
FitsSchemaInputMapper(daf::base::PropertyList &metadata, bool stripMetadata)
Construct a mapper from a PropertyList of FITS header values, stripping recognized keys if desired...
T replace(T... args)
static QuadrupoleKey addFields(Schema &schema, std::string const &name, std::string const &doc, CoordinateType coordType=CoordinateType::PIXEL)
Add a set of quadrupole subfields to a schema and return a QuadrupoleKey that points to them...
Definition: aggregates.cc:100
std::vector< std::string > getOrderedNames(void) const
std::vector< std::unique_ptr< FitsColumnReader > > readers
Key< U > key
Definition: Schema.cc:280
boost::multi_index_container< FitsSchemaItem, boost::multi_index::indexed_by< boost::multi_index::ordered_non_unique< boost::multi_index::member< FitsSchemaItem, int, &FitsSchemaItem::column > >, boost::multi_index::ordered_non_unique< boost::multi_index::member< FitsSchemaItem, int, &FitsSchemaItem::bit > >, boost::multi_index::hashed_unique< boost::multi_index::member< FitsSchemaItem, std::string, &FitsSchemaItem::ttype > >, boost::multi_index::sequenced<> > > InputContainer
int indexCovariance(int i, int j)
Defines the ordering of packed covariance matrices.
Definition: FieldBase.h:32
T make_pair(T... args)
bool exists(std::string const &name) const
Tag types used to declare specialized field types.
Definition: misc.h:32
T move(T... args)
void setHdu(int hdu, bool relative=false)
Set the current HDU.
Definition: fits.cc:478
Field< T >::Element * getElement(Key< T > const &key)
Return a pointer to the underlying elements of a field (non-const).
Definition: BaseRecord.h:67
T size(T... args)
#define LSST_EXCEPT(type,...)
STL class.
T get(std::string const &name) const
FitsSchemaInputMapper & operator=(FitsSchemaInputMapper const &)
Base class for all records.
Definition: BaseRecord.h:31
static int const VERSION
Definition: Schema.h:56
A class used as a handle to a particular field in a table.
Definition: fwd.h:45
Schema finalize()
Map any remaining items into regular Schema items, and return the final Schema.
T begin(T... args)
SetFitsSchemaString<&FitsSchemaItem::tunit > SetTUNIT
static InputArchive readFits(fits::Fits &fitsfile)
Read an object from an already open FITS object.
static CoordKey addFields(afw::table::Schema &schema, std::string const &name, std::string const &doc)
Add a pair of _ra, _dec fields to a Schema, and return a CoordKey that points to them.
Definition: aggregates.cc:83
STL class.
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
bool readArchive(afw::fits::Fits &fits)
Set the Archive by reading from the HDU specified by the AR_HDU header entry.
T substr(T... args)
void set(Key< T > const &key, U const &value)
Set value of a field for the given key.
Definition: BaseRecord.h:138
void erase(Item const *item)
Remove the given item (which should have been retrieved via find()) from the mapping, preventing it from being included in the regular fields added by finalize().
int nFlags
Definition: FitsWriter.cc:91
SetFitsSchemaString<&FitsSchemaItem::ttype > SetTTYPE
void setArchive(std::shared_ptr< InputArchive > archive)
Set the Archive to an externally-provided one, overriding any that may have been read.
T sqrt(T... args)
void customize(std::unique_ptr< FitsColumnReader > reader)
Customize a mapping by providing a FitsColumnReader instance that will be invoked by readRecords()...
A multi-catalog archive object used to load table::io::Persistable objects.
Definition: InputArchive.h:31
bool hasArchive() const
Return true if the mapper has an InputArchive.
int getHdu()
Return the current HDU (0-indexed; 0 is the Primary HDU).
Definition: fits.cc:472
Item const * find(std::string const &ttype) const
Find an item with the given column name (ttype), returning nullptr if no such column exists...
A FunctorKey used to get or set a geom::ellipses::Quadrupole from a tuple of constituent Keys...
Definition: aggregates.h:268
T stoi(T... args)
Key< T > addField(Field< T > const &field, bool doReplace=false)
Add a new field to the Schema, and return the associated Key.
Definition: Schema.cc:667
T lround(T... args)
T compare(T... args)
A FunctorKey used to get or set celestial coordinates from a pair of lsst::geom::Angle keys...
Definition: aggregates.h:196
void readRecord(BaseRecord &record, afw::fits::Fits &fits, std::size_t row)
Fill a record from a FITS binary table row.