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