lsst.afw  16.0-9-gdf7162dbc+1
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_InstFlux"), std::make_pair("MODEL_FLUX", "slot_ModelFlux"),
142  std::make_pair("CALIB_FLUX", "slot_CalibFlux"), std::make_pair("CENTROID", "slot_Centroid"),
143  std::make_pair("SHAPE", "slot_Shape")}};
144  for (std::size_t i = 0; i < oldSlotKeys.size(); ++i) {
145  std::string target = metadata.get(oldSlotKeys[i].first + "_SLOT", std::string(""));
146  if (!target.empty()) {
147  _impl->schema.getAliasMap()->set(oldSlotKeys[i].second, target);
148  if (stripMetadata) {
149  metadata.remove(oldSlotKeys[i].first);
150  metadata.remove(oldSlotKeys[i].first + "_ERR_SLOT");
151  metadata.remove(oldSlotKeys[i].first + "_FLAG_SLOT");
152  }
153  }
154  }
155  }
156 
157  // Read the rest of the header into the intermediate inputs container.
158  std::vector<std::string> keyList = metadata.getOrderedNames();
159  for (std::vector<std::string>::const_iterator key = keyList.begin(); key != keyList.end(); ++key) {
160  if (key->compare(0, 5, "TTYPE") == 0) {
161  int column = std::stoi(key->substr(5)) - 1;
162  auto iter = _impl->byColumn().lower_bound(column);
163  if (iter == _impl->byColumn().end() || iter->column != column) {
164  iter = _impl->byColumn().insert(iter, FitsSchemaItem(column, -1));
165  }
166  std::string v = metadata.get<std::string>(*key);
167  _impl->byColumn().modify(iter, Impl::SetTTYPE(v));
168  if (iter->doc.empty()) { // don't overwrite if already set with TDOCn
169  _impl->byColumn().modify(iter, Impl::SetDoc(metadata.getComment(*key)));
170  }
171  if (stripMetadata) {
172  metadata.remove(*key);
173  }
174  } else if (key->compare(0, 5, "TFLAG") == 0) {
175  int bit = std::stoi(key->substr(5)) - 1;
176  auto iter = _impl->byBit().lower_bound(bit);
177  if (iter == _impl->byBit().end() || iter->bit != bit) {
178  iter = _impl->byBit().insert(iter, FitsSchemaItem(-1, bit));
179  }
180  std::string v = metadata.get<std::string>(*key);
181  _impl->byBit().modify(iter, Impl::SetTTYPE(v));
182  if (iter->doc.empty()) { // don't overwrite if already set with TFDOCn
183  _impl->byBit().modify(iter, Impl::SetDoc(metadata.getComment(*key)));
184  }
185  if (stripMetadata) {
186  metadata.remove(*key);
187  }
188  } else if (key->compare(0, 4, "TDOC") == 0) {
189  int column = std::stoi(key->substr(4)) - 1;
190  auto iter = _impl->byColumn().lower_bound(column);
191  if (iter == _impl->byColumn().end() || iter->column != column) {
192  iter = _impl->byColumn().insert(iter, FitsSchemaItem(column, -1));
193  }
194  _impl->byColumn().modify(iter, Impl::SetDoc(metadata.get<std::string>(*key)));
195  if (stripMetadata) {
196  metadata.remove(*key);
197  }
198  } else if (key->compare(0, 5, "TFDOC") == 0) {
199  int bit = std::stoi(key->substr(5)) - 1;
200  auto iter = _impl->byBit().lower_bound(bit);
201  if (iter == _impl->byBit().end() || iter->bit != bit) {
202  iter = _impl->byBit().insert(iter, FitsSchemaItem(-1, bit));
203  }
204  _impl->byBit().modify(iter, Impl::SetDoc(metadata.get<std::string>(*key)));
205  if (stripMetadata) {
206  metadata.remove(*key);
207  }
208  } else if (key->compare(0, 5, "TUNIT") == 0) {
209  int column = std::stoi(key->substr(5)) - 1;
210  auto iter = _impl->byColumn().lower_bound(column);
211  if (iter == _impl->byColumn().end() || iter->column != column) {
212  iter = _impl->byColumn().insert(iter, FitsSchemaItem(column, -1));
213  }
214  _impl->byColumn().modify(iter, Impl::SetTUNIT(metadata.get<std::string>(*key)));
215  if (stripMetadata) {
216  metadata.remove(*key);
217  }
218  } else if (key->compare(0, 5, "TCCLS") == 0) {
219  int column = std::stoi(key->substr(5)) - 1;
220  auto iter = _impl->byColumn().lower_bound(column);
221  if (iter == _impl->byColumn().end() || iter->column != column) {
222  iter = _impl->byColumn().insert(iter, FitsSchemaItem(column, -1));
223  }
224  _impl->byColumn().modify(iter, Impl::SetTCCLS(metadata.get<std::string>(*key)));
225  if (stripMetadata) {
226  metadata.remove(*key);
227  }
228  } else if (key->compare(0, 5, "TFORM") == 0) {
229  int column = std::stoi(key->substr(5)) - 1;
230  auto iter = _impl->byColumn().lower_bound(column);
231  if (iter == _impl->byColumn().end() || iter->column != column) {
232  iter = _impl->byColumn().insert(iter, FitsSchemaItem(column, -1));
233  }
234  _impl->byColumn().modify(iter, Impl::SetTFORM(metadata.get<std::string>(*key)));
235  if (stripMetadata) {
236  metadata.remove(*key);
237  }
238  } else if (key->compare(0, 5, "TZERO") == 0) {
239  if (stripMetadata) {
240  metadata.remove(*key);
241  }
242  } else if (key->compare(0, 5, "TSCAL") == 0) {
243  if (stripMetadata) {
244  metadata.remove(*key);
245  }
246  } else if (key->compare(0, 5, "TNULL") == 0) {
247  if (stripMetadata) {
248  metadata.remove(*key);
249  }
250  } else if (key->compare(0, 5, "TDISP") == 0) {
251  if (stripMetadata) {
252  metadata.remove(*key);
253  }
254  }
255  }
256 
257  // Find the column used to store flags, and setup the flag-handling data members from it.
258  _impl->flagColumn = metadata.get("FLAGCOL", 0);
259  if (_impl->flagColumn > 0) {
260  if (stripMetadata) {
261  metadata.remove("FLAGCOL");
262  }
263  --_impl->flagColumn; // switch from 1-indexed to 0-indexed
264  auto iter = _impl->byColumn().find(_impl->flagColumn);
265  if (iter == _impl->byColumn().end()) {
266  throw LSST_EXCEPT(
268  (boost::format("Column for flag data not found; FLAGCOL=%d") % _impl->flagColumn).str());
269  }
270  // Regex to unpack a FITS TFORM value for a bit array column (TFORM code 'X'). The number
271  // that precedes the code is the size of the array; the number that follows it (if present)
272  // is ignored.
273  static boost::regex const regex("(\\d+)?X\\(?(\\d)*\\)?", boost::regex::perl);
274  boost::smatch m;
275  if (!boost::regex_match(iter->tform, m, regex)) {
276  throw LSST_EXCEPT(
278  (boost::format("Invalid TFORM key for flags column: '%s'") % iter->tform).str());
279  }
280  int nFlags = 1;
281  if (m[1].matched) {
282  nFlags = std::stoi(m[1].str());
283  }
284  _impl->flagKeys.resize(nFlags);
285  _impl->flagWorkspace.reset(new bool[nFlags]);
286  // Delete the flag column from the input list so we don't interpret it as a
287  // regular field.
288  _impl->byColumn().erase(iter);
289  }
290 }
291 
297 
298 void FitsSchemaInputMapper::setArchive(std::shared_ptr<InputArchive> archive) { _impl->archive = archive; }
299 
301  int oldHdu = fits.getHdu();
302  if (_impl->archiveHdu < 0) _impl->archiveHdu = oldHdu + 1;
303  try {
304  fits.setHdu(_impl->archiveHdu);
305  _impl->archive.reset(new io::InputArchive(InputArchive::readFits(fits)));
306  fits.setHdu(oldHdu);
307  return true;
308  } catch (afw::fits::FitsError &) {
309  fits.status = 0;
310  fits.setHdu(oldHdu);
311  _impl->archiveHdu = -1;
312  return false;
313  }
314 }
315 
316 bool FitsSchemaInputMapper::hasArchive() const { return static_cast<bool>(_impl->archive); }
317 
319  auto iter = _impl->byName().find(ttype);
320  if (iter == _impl->byName().end()) {
321  return 0;
322  }
323  return &(*iter);
324 }
325 
326 FitsSchemaItem const *FitsSchemaInputMapper::find(int column) const {
327  auto iter = _impl->byColumn().lower_bound(column);
328  if (iter == _impl->byColumn().end() || iter->column != column) {
329  return 0;
330  }
331  return &(*iter);
332 }
333 
335  auto iter = _impl->byColumn().lower_bound(item->column);
336  assert(iter != _impl->byColumn().end() && iter->column == item->column);
337  _impl->byColumn().erase(iter);
338 }
339 
341  auto iter = _impl->byName().find(ttype);
342  if (iter != _impl->byName().end() && iter->ttype == ttype) {
343  _impl->byName().erase(iter);
344  }
345 }
346 
348  auto iter = _impl->byColumn().lower_bound(column);
349  if (iter != _impl->byColumn().end() && iter->column == column) {
350  _impl->byColumn().erase(iter);
351  }
352 }
353 
354 void erase(int column);
355 
357  _impl->readers.push_back(std::move(reader));
358 }
359 
360 namespace {
361 
362 template <typename T>
363 class StandardReader : public FitsColumnReader {
364 public:
366  FieldBase<T> const &base = FieldBase<T>()) {
367  return std::unique_ptr<FitsColumnReader>(new StandardReader(schema, item, base));
368  }
369 
370  StandardReader(Schema &schema, FitsSchemaItem const &item, FieldBase<T> const &base)
371  : _column(item.column), _key(schema.addField<T>(item.ttype, item.doc, item.tunit, base)) {}
372 
373  virtual void readCell(BaseRecord &record, std::size_t row, afw::fits::Fits &fits,
374  std::shared_ptr<InputArchive> const &archive) const {
375  fits.readTableArray(row, _column, _key.getElementCount(), record.getElement(_key));
376  }
377 
378 private:
379  int _column;
380  Key<T> _key;
381 };
382 
383 class AngleReader : public FitsColumnReader {
384 public:
386  Schema &schema, FitsSchemaItem const &item,
388  return std::unique_ptr<FitsColumnReader>(new AngleReader(schema, item, base));
389  }
390 
391  AngleReader(Schema &schema, FitsSchemaItem const &item, FieldBase<lsst::geom::Angle> const &base)
392  : _column(item.column), _key(schema.addField<lsst::geom::Angle>(item.ttype, item.doc, "", base)) {
393  // We require an LSST-specific key in the headers before parsing a column
394  // as Angle at all, so we don't need to worry about other units or other
395  // spellings of radians. We do continue to support no units for backwards
396  // compatibility.
397  if (!item.tunit.empty() && item.tunit != "rad") {
399  "Angle fields must be persisted in radians (TUNIT='rad').");
400  }
401  }
402 
403  virtual void readCell(BaseRecord &record, std::size_t row, afw::fits::Fits &fits,
404  std::shared_ptr<InputArchive> const &archive) const {
405  double tmp = 0;
406  fits.readTableScalar(row, _column, tmp);
407  record.set(_key, tmp * lsst::geom::radians);
408  }
409 
410 private:
411  int _column;
413 };
414 
415 class StringReader : public FitsColumnReader {
416 public:
417  static std::unique_ptr<FitsColumnReader> make(Schema &schema, FitsSchemaItem const &item, int size) {
418  return std::unique_ptr<FitsColumnReader>(new StringReader(schema, item, size));
419  }
420 
421  StringReader(Schema &schema, FitsSchemaItem const &item, int size)
422  : _column(item.column),
423  _key(schema.addField<std::string>(item.ttype, item.doc, item.tunit, size)),
424  _isVariableLength(size == 0) {}
425 
426  virtual void readCell(BaseRecord &record, std::size_t row, afw::fits::Fits &fits,
427  std::shared_ptr<InputArchive> const &archive) const {
428  std::string s;
429  fits.readTableScalar(row, _column, s, _isVariableLength);
430  record.set(_key, s);
431  }
432 
433 private:
434  int _column;
435  Key<std::string> _key;
436  bool _isVariableLength;
437 };
438 
439 template <typename T>
440 class VariableLengthArrayReader : public FitsColumnReader {
441 public:
443  return std::unique_ptr<FitsColumnReader>(new VariableLengthArrayReader(schema, item));
444  }
445 
446  VariableLengthArrayReader(Schema &schema, FitsSchemaItem const &item)
447  : _column(item.column), _key(schema.addField<Array<T>>(item.ttype, item.doc, item.tunit, 0)) {}
448 
449  virtual void readCell(BaseRecord &record, std::size_t row, afw::fits::Fits &fits,
450  std::shared_ptr<InputArchive> const &archive) const {
451  int size = fits.getTableArraySize(row, _column);
452  ndarray::Array<T, 1, 1> array = ndarray::allocate(size);
453  fits.readTableArray(row, _column, size, array.getData());
454  record.set(_key, array);
455  }
456 
457 private:
458  int _column;
459  Key<Array<T>> _key;
460 };
461 
462 // Read a 2-element FITS array column as separate x and y Schema fields (hence converting
463 // from the old Point compound field to the new PointKey FunctorKey).
464 template <typename T>
465 class PointConversionReader : public FitsColumnReader {
466 public:
468  return std::unique_ptr<FitsColumnReader>(new PointConversionReader(schema, item));
469  }
470 
471  PointConversionReader(Schema &schema, FitsSchemaItem const &item)
472  : _column(item.column), _key(PointKey<T>::addFields(schema, item.ttype, item.doc, item.tunit)) {}
473 
474  virtual void readCell(BaseRecord &record, std::size_t row, afw::fits::Fits &fits,
475  std::shared_ptr<InputArchive> const &archive) const {
476  std::array<T, 2> buffer;
477  fits.readTableArray(row, _column, 2, buffer.data());
478  record.set(_key, lsst::geom::Point<T, 2>(buffer[0], buffer[1]));
479  }
480 
481 private:
482  int _column;
483  PointKey<T> _key;
484 };
485 
486 // Read a 2-element FITS array column as separate ra and dec Schema fields (hence converting
487 // from the old Coord compound field to the new CoordKey FunctorKey).
488 class CoordConversionReader : public FitsColumnReader {
489 public:
491  return std::unique_ptr<FitsColumnReader>(new CoordConversionReader(schema, item));
492  }
493 
494  CoordConversionReader(Schema &schema, FitsSchemaItem const &item)
495  : _column(item.column), _key(CoordKey::addFields(schema, item.ttype, item.doc)) {}
496 
497  virtual void readCell(BaseRecord &record, std::size_t row, afw::fits::Fits &fits,
498  std::shared_ptr<InputArchive> const &archive) const {
500  fits.readTableArray(row, _column, 2, buffer.data());
501  record.set(_key, lsst::geom::SpherePoint(buffer[0], buffer[1]));
502  }
503 
504 private:
505  int _column;
506  CoordKey _key;
507 };
508 
509 // Read a 3-element FITS array column as separate xx, yy, and xy Schema fields (hence converting
510 // from the old Moments compound field to the new QuadrupoleKey FunctorKey).
511 class MomentsConversionReader : public FitsColumnReader {
512 public:
514  return std::unique_ptr<FitsColumnReader>(new MomentsConversionReader(schema, item));
515  }
516 
517  MomentsConversionReader(Schema &schema, FitsSchemaItem const &item)
518  : _column(item.column),
519  _key(QuadrupoleKey::addFields(schema, item.ttype, item.doc, CoordinateType::PIXEL)) {}
520 
521  virtual void readCell(BaseRecord &record, std::size_t row, afw::fits::Fits &fits,
522  std::shared_ptr<InputArchive> const &archive) const {
523  std::array<double, 3> buffer;
524  fits.readTableArray(row, _column, 3, buffer.data());
525  record.set(_key, geom::ellipses::Quadrupole(buffer[0], buffer[1], buffer[2], false));
526  }
527 
528 private:
529  int _column;
530  QuadrupoleKey _key;
531 };
532 
533 // Read a FITS array column representing a packed symmetric matrix into
534 // Schema fields for each element (hence converting from the old Covariance
535 // compound field to the new CovarianceMatrixKey FunctorKey).
536 template <typename T, int N>
537 class CovarianceConversionReader : public FitsColumnReader {
538 public:
539  static std::string guessUnits(std::string const &oldUnits) {
540  static boost::regex const regex("(.*)(\\^(\\d+))?", boost::regex::perl);
541  boost::smatch m;
542  if (!boost::regex_match(oldUnits, m, regex)) {
543  int oldPower = std::stoi(m[2]);
544  int newPower = std::sqrt(oldPower);
545  return std::to_string(newPower);
546  }
547  return oldUnits;
548  }
549 
551  std::vector<std::string> const &names) {
552  return std::unique_ptr<FitsColumnReader>(new CovarianceConversionReader(schema, item, names));
553  }
554 
555  CovarianceConversionReader(Schema &schema, FitsSchemaItem const &item,
556  std::vector<std::string> const &names)
557  : _column(item.column),
558  _size(names.size()),
559  _key(CovarianceMatrixKey<T, N>::addFields(schema, item.ttype, names, guessUnits(item.tunit))),
560  _buffer(new T[detail::computeCovariancePackedSize(names.size())]) {}
561 
562  virtual void readCell(BaseRecord &record, std::size_t row, afw::fits::Fits &fits,
563  std::shared_ptr<InputArchive> const &archive) const {
564  fits.readTableArray(row, _column, detail::computeCovariancePackedSize(_size), _buffer.get());
565  for (int i = 0; i < _size; ++i) {
566  for (int j = i; j < _size; ++j) {
567  _key.setElement(record, i, j, _buffer[detail::indexCovariance(i, j)]);
568  }
569  }
570  }
571 
572 private:
573  int _column;
574  int _size;
576  std::unique_ptr<T[]> _buffer;
577 };
578 
579 std::unique_ptr<FitsColumnReader> makeColumnReader(Schema &schema, FitsSchemaItem const &item) {
580  // Regex to unpack a FITS TFORM value. The first number is the size of the array (1 if not present),
581  // followed by an alpha code indicating the type (preceded by P or Q for variable size array).
582  // The last number is ignored.
583  static boost::regex const regex("(\\d+)?([PQ])?(\\u)\\(?(\\d)*\\)?", boost::regex::perl);
584  // start by parsing the format; this tells the element type of the field and the number of elements
585  boost::smatch m;
586  if (!boost::regex_match(item.tform, m, regex)) {
588  }
589  int size = 1;
590  if (m[1].matched) {
591  size = std::stoi(m[1].str());
592  }
593  char code = m[3].str()[0];
594  if (m[2].matched) {
595  // P or Q presence indicates a variable-length array, which we can get by just setting the
596  // size to zero and letting the rest of the logic run its course.
597  size = 0;
598  }
599  // switch code over FITS codes that correspond to different element types
600  switch (code) {
601  case 'B': // 8-bit unsigned integers -- can only be scalars or Arrays
602  if (size == 1) {
603  if (item.tccls == "Array") {
604  return StandardReader<Array<std::uint8_t>>::make(schema, item, size);
605  }
606  return StandardReader<std::uint8_t>::make(schema, item);
607  }
608  if (size == 0) {
609  return VariableLengthArrayReader<std::uint8_t>::make(schema, item);
610  }
611  return StandardReader<Array<std::uint8_t>>::make(schema, item, size);
612 
613  case 'I': // 16-bit integers - can only be scalars or Arrays (we assume they're unsigned, since
614  // that's all we ever write, and CFITSIO will complain later if they aren't)
615  if (size == 1) {
616  if (item.tccls == "Array") {
617  return StandardReader<Array<std::uint16_t>>::make(schema, item, size);
618  }
619  return StandardReader<std::uint16_t>::make(schema, item);
620  }
621  if (size == 0) {
622  return VariableLengthArrayReader<std::uint16_t>::make(schema, item);
623  }
624  return StandardReader<Array<std::uint16_t>>::make(schema, item, size);
625  case 'J': // 32-bit integers - can only be scalars, Point fields, or Arrays
626  if (size == 0) {
627  return VariableLengthArrayReader<std::int32_t>::make(schema, item);
628  }
629  if (item.tccls == "Point") {
630  return PointConversionReader<std::int32_t>::make(schema, item);
631  }
632  if (size > 1 || item.tccls == "Array") {
633  return StandardReader<Array<std::int32_t>>::make(schema, item, size);
634  }
635  return StandardReader<std::int32_t>::make(schema, item);
636  case 'K': // 64-bit integers - can only be scalars.
637  if (size == 1) {
638  return StandardReader<std::int64_t>::make(schema, item);
639  }
640  case 'E': // floats
641  if (size == 0) {
642  return VariableLengthArrayReader<float>::make(schema, item);
643  }
644  if (size == 1) {
645  if (item.tccls == "Array") {
646  return StandardReader<Array<float>>::make(schema, item, 1);
647  }
648  // Just use scalars for Covariances of size 1, since that results in more
649  // natural field names (essentially never happens anyway).
650  return StandardReader<float>::make(schema, item);
651  }
652  if (size == 3 && item.tccls == "Covariance(Point)") {
653  std::vector<std::string> names = {"x", "y"};
654  return CovarianceConversionReader<float, 2>::make(schema, item, names);
655  }
656  if (size == 6 && item.tccls == "Covariance(Moments)") {
657  std::vector<std::string> names = {"xx", "yy", "xy"};
658  return CovarianceConversionReader<float, 3>::make(schema, item, names);
659  }
660  if (item.tccls == "Covariance") {
661  double v = 0.5 * (std::sqrt(1 + 8 * size) - 1);
662  int n = std::lround(v);
663  if (n * (n + 1) != size * 2) {
664  throw LSST_EXCEPT(afw::fits::FitsError, "Covariance field has invalid size.");
665  }
666  std::vector<std::string> names(n);
667  for (int i = 0; i < n; ++i) {
668  names[i] = std::to_string(i);
669  }
670  return CovarianceConversionReader<float, Eigen::Dynamic>::make(schema, item, names);
671  }
672  return StandardReader<Array<float>>::make(schema, item, size);
673  case 'D': // doubles
674  if (size == 0) {
675  return VariableLengthArrayReader<double>::make(schema, item);
676  }
677  if (size == 1) {
678  if (item.tccls == "Angle") {
679  return AngleReader::make(schema, item);
680  }
681  if (item.tccls == "Array") {
682  return StandardReader<Array<double>>::make(schema, item, 1);
683  }
684  return StandardReader<double>::make(schema, item);
685  }
686  if (size == 2) {
687  if (item.tccls == "Point") {
688  return PointConversionReader<double>::make(schema, item);
689  }
690  if (item.tccls == "Coord") {
691  return CoordConversionReader::make(schema, item);
692  }
693  }
694  if (size == 3 && item.tccls == "Moments") {
695  return MomentsConversionReader::make(schema, item);
696  }
697  return StandardReader<Array<double>>::make(schema, item, size);
698  case 'A': // strings
699  // StringReader can read both fixed-length and variable-length (size=0) strings
700  return StringReader::make(schema, item, size);
701  default:
703  }
704 }
705 
706 bool endswith(std::string const &s, std::string const &suffix) {
707  return s.size() >= suffix.size() && s.compare(s.size() - suffix.size(), suffix.size(), suffix) == 0;
708 }
709 
710 // Replace the last n characters of a string with a new suffix string, returning the result as a new string
711 std::string replaceSuffix(std::string const &s, std::size_t n, std::string const &suffix) {
712  return s.substr(0, s.size() - n) + suffix;
713 }
714 
715 } // namespace
716 
718  if (_impl->version == 0) {
719  AliasMap &aliases = *_impl->schema.getAliasMap();
720  for (auto iter = _impl->asList().begin(); iter != _impl->asList().end(); ++iter) {
721  std::size_t flagPos = iter->ttype.find("flags");
722  if (flagPos != std::string::npos) {
723  // We want to create aliases that resolve "(.*)_flag" to "$1_flags"; old schemas will have
724  // the latter, but new conventions (including slots) expect the former.
725  // But we can't do that, because adding that alias directly results in a cycle in the
726  // aliases (since aliases do partial matches, and keep trying until there are no matches,
727  // we'd have "(.*)_flag" resolve to "$1_flagssssssssssssss...").
728  // Instead, we *rename* from "flags" to "flag", then create the reverse alias.
729  std::string ttype = iter->ttype;
730  std::string prefix = iter->ttype.substr(0, flagPos);
731  ttype.replace(flagPos, 5, "flag");
732  _impl->asList().modify(iter, Impl::SetTTYPE(ttype));
733  // Note that we're not aliasing the full field, just the first part - if we have multiple
734  // flag fields, one alias should be sufficient for all of them (because of partial matching).
735  // Of course, we'll try to recreate that alias every time we handle another flag field with
736  // the same prefix, but AliasMap know hows to handle that no-op set.
737  aliases.set(prefix + "flags", prefix + "flag");
738  } else if (iter->ttype.find("flux") != std::string::npos) {
739  // Create aliases that resolve "(.*)_flux" and "(.*)_fluxSigma" to "$1" and "$1_err",
740  // if $1 contains the string "flux".
741  if (endswith(iter->ttype, "_err")) {
742  aliases.set(replaceSuffix(iter->ttype, 4, "_fluxSigma"), iter->ttype);
743  } else {
744  aliases.set(iter->ttype + "_flux", iter->ttype);
745  }
746  } else if (endswith(iter->ttype, "_err")) {
747  // Create aliases that resolve "(.*)_(.*)Sigma" and "(.*)_(.*)_(.*)_Cov" to
748  // "$1_err_$2Sigma" 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, "_xSigma"), iter->ttype + "_xSigma");
754  aliases.set(replaceSuffix(iter->ttype, 4, "_ySigma"), iter->ttype + "_ySigma");
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, "_xxSigma"), iter->ttype + "_xxSigma");
758  aliases.set(replaceSuffix(iter->ttype, 4, "_yySigma"), iter->ttype + "_yySigma");
759  aliases.set(replaceSuffix(iter->ttype, 4, "_xySigma"), iter->ttype + "_xySigma");
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  for (auto iter = _impl->asList().begin(); iter != _impl->asList().end(); ++iter) {
768  if (iter->bit < 0) { // not a Flag column
769  std::unique_ptr<FitsColumnReader> reader = makeColumnReader(_impl->schema, *iter);
770  if (reader) {
771  _impl->readers.push_back(std::move(reader));
772  } else {
773  LOGLS_WARN("afw.FitsSchemaInputMapper", "Format " << iter->tform << " for column "
774  << iter->ttype
775  << " not supported; skipping.");
776  }
777  } else { // is a Flag column
778  if (static_cast<std::size_t>(iter->bit) >= _impl->flagKeys.size()) {
780  (boost::format("Flag field '%s' is is in bit %d (0-indexed) of only %d") %
781  iter->ttype % iter->bit % _impl->flagKeys.size())
782  .str());
783  }
784  _impl->flagKeys[iter->bit] = _impl->schema.addField<Flag>(iter->ttype, iter->doc);
785  }
786  }
787  _impl->asList().clear();
788  return _impl->schema;
789 }
790 
792  if (!_impl->flagKeys.empty()) {
793  fits.readTableArray<bool>(row, _impl->flagColumn, _impl->flagKeys.size(), _impl->flagWorkspace.get());
794  for (std::size_t bit = 0; bit < _impl->flagKeys.size(); ++bit) {
795  record.set(_impl->flagKeys[bit], _impl->flagWorkspace[bit]);
796  }
797  }
798  for (auto iter = _impl->readers.begin(); iter != _impl->readers.end(); ++iter) {
799  (**iter).readCell(record, row, fits, _impl->archive);
800  }
801 }
802 } // namespace io
803 } // namespace table
804 } // namespace afw
805 } // 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:48
Field base class default implementation (used for numeric scalars and lsst::geom::Angle).
Definition: FieldBase.h:43
int m
Definition: SpanSet.cc:44
T empty(T... args)
Key< Flag > const & target
afw::table::Schema schema
Definition: GaussianPsf.cc:43
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:54
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:267
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.