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