lsst.afw  15.0-29-ga12a2b06e
Schema.cc
Go to the documentation of this file.
1 #include <list>
2 #include <memory>
3 #include <stdexcept>
4 #include <type_traits>
5 
6 #include "boost/mpl/and.hpp"
7 #include "boost/mpl/bool.hpp"
8 #include "boost/iterator/transform_iterator.hpp"
9 #include "boost/iterator/filter_iterator.hpp"
10 #include "boost/preprocessor/seq/for_each.hpp"
11 #include "boost/preprocessor/tuple/to_seq.hpp"
12 
13 #include "lsst/afw/table/Schema.h"
17 #include "lsst/afw/fits.h"
18 
19 namespace lsst {
20 namespace afw {
21 namespace table {
22 
23 //-----------------------------------------------------------------------------------------------------------
24 //----- Miscellaneous Utilities -----------------------------------------------------------------------------
25 //-----------------------------------------------------------------------------------------------------------
26 
27 namespace {
28 
29 inline char getDelimiter() { return '_'; }
30 
31 // Concatenate two strings with a single-character delimiter between them
32 std::string join(std::string const &a, std::string const &b, char delimiter) {
33  std::string full;
34  full.reserve(a.size() + b.size() + 1);
35  full += a;
36  full.push_back(delimiter);
37  full += b;
38  return full;
39 }
40 
41 // Functor to compare two ItemVariants for Key equality.
42 class ItemFunctors {
43  typedef detail::SchemaImpl::ItemVariant ItemVariant;
44 
45  // Compares keys - must be initialized with one ItemVariant and passed the other.
46  struct KeyHelper : public boost::static_visitor<bool> {
47  explicit KeyHelper(ItemVariant const *other_) : other(other_) {}
48 
49  template <typename T>
50  bool operator()(SchemaItem<T> const &a) const {
51  SchemaItem<T> const *b = boost::get<SchemaItem<T> >(other);
52  return (b) && a.key == b->key;
53  }
54 
55  ItemVariant const *other;
56  };
57 
58  // Extracts field name from an ItemVariant
59  struct NameHelper : public boost::static_visitor<std::string const &> {
60  template <typename T>
61  std::string const &operator()(SchemaItem<T> const &a) const {
62  return a.field.getName();
63  }
64  };
65 
66  // Extracts field doc from an ItemVariant
67  struct DocHelper : public boost::static_visitor<std::string const &> {
68  template <typename T>
69  std::string const &operator()(SchemaItem<T> const &a) const {
70  return a.field.getDoc();
71  }
72  };
73 
74  // Extracts field units from an ItemVariant
75  struct UnitsHelper : public boost::static_visitor<std::string const &> {
76  template <typename T>
77  std::string const &operator()(SchemaItem<T> const &a) const {
78  return a.field.getUnits();
79  }
80  };
81 
82 public:
83  static bool compareKeys(ItemVariant const &a, ItemVariant const &b) {
84  return boost::apply_visitor(KeyHelper(&b), a);
85  }
86 
87  static bool compareNames(ItemVariant const &a, ItemVariant const &b) {
88  return boost::apply_visitor(NameHelper(), a) == boost::apply_visitor(NameHelper(), b);
89  }
90 
91  static bool compareDocs(ItemVariant const &a, ItemVariant const &b) {
92  return boost::apply_visitor(DocHelper(), a) == boost::apply_visitor(DocHelper(), b);
93  }
94 
95  static bool compareUnits(ItemVariant const &a, ItemVariant const &b) {
96  return boost::apply_visitor(UnitsHelper(), a) == boost::apply_visitor(UnitsHelper(), b);
97  }
98 };
99 
100 } // anonymous
101 
102 //-----------------------------------------------------------------------------------------------------------
103 //----- SchemaImpl implementation ---------------------------------------------------------------------------
104 //-----------------------------------------------------------------------------------------------------------
105 
106 namespace detail {
107 
108 //----- Finding a SchemaItem by field name ------------------------------------------------------------------
109 
110 // This is easier to understand if you start reading from the bottom of this section, with
111 // SchemaImpl::find(std::string const &), then work your way up.
112 
113 namespace {
114 
115 // Given a SchemaItem for a regular field, look for a subfield with the given name.
116 // Return the index of the subfield (>= 0) on success, -1 on failure.
117 template <typename T>
118 inline int findNamedSubfield(
119  SchemaItem<T> const &item, std::string const &name, char delimiter,
120  boost::mpl::true_ * // whether a match is possible based on the type of T; computed by caller
121  ) {
122  if (name.size() <= item.field.getName().size()) return -1;
123 
124  if ( // compare invocation is equivalent to "name.startswith(item.field.getName())" in Python
125  name.compare(0, item.field.getName().size(), item.field.getName()) == 0 &&
126  name[item.field.getName().size()] == delimiter) {
127  int const position = item.field.getName().size() + 1;
128  int const size = name.size() - position;
129  int const nElements = item.field.getElementCount();
130  for (int i = 0; i < nElements; ++i) {
131  if (name.compare(position, size, Key<T>::subfields[i]) == 0) {
132  return i;
133  }
134  }
135  }
136  return -1;
137 }
138 
139 // This is an overload of findNamedSubfield that always fails; it's called when we
140 // know from the type of the field and subfield that they're incompatible.
141 template <typename T>
142 inline int findNamedSubfield(
143  SchemaItem<T> const &item, std::string const &name, char delimiter,
144  boost::mpl::false_ * // whether a match is possible based on the type of T; computed by caller
145  ) {
146  return -1;
147 }
148 
149 // Given a SchemaItem and a subfield index, make a new SchemaItem that corresponds to that
150 // subfield and put it in the result smart pointer.
151 template <typename T, typename U>
152 inline void makeSubfieldItem(
153  SchemaItem<T> const &item, int index, char delimiter, std::unique_ptr<SchemaItem<U> > &result,
154  boost::mpl::true_ * // whether a match is possible based on the types of T and U; computed by caller
155  ) {
156  result.reset(new SchemaItem<U>(detail::Access::extractElement(item.key, index),
157  Field<U>(join(item.field.getName(), Key<T>::subfields[index], delimiter),
158  item.field.getDoc(), item.field.getUnits())));
159 }
160 
161 // An overload of makeSubfieldItem that always fails because we know T and U aren't compatible.
162 template <typename T, typename U>
163 inline void makeSubfieldItem(
164  SchemaItem<T> const &item, int index, char delimiter, std::unique_ptr<SchemaItem<U> > &result,
165  boost::mpl::false_ * // whether a match is possible based on the types of T and U; computed by caller
166  ) {}
167 
168 // This is a Variant visitation functor used to extract subfield items by name.
169 // For example, if we have a Point field "a", if we search the Schema for "a.x",
170 // we want to return a SchemaItem that makes it look like "a.x" is a full-fledged
171 // field in its own right.
172 template <typename U>
173 struct ExtractItemByName : public boost::static_visitor<> {
174  explicit ExtractItemByName(std::string const &name_, char delimiter_)
175  : delimiter(delimiter_), name(name_) {}
176 
177  template <typename T>
178  void operator()(SchemaItem<T> const &item) const {
179  // We want to find out if 'item' has a subfield whose fully-qualified name matches our
180  // name data member. But we also know that the subfield needs to have type U, and that
181  // the field needs to have named subfields.
182  // This typedef is boost::mpl::true_ if all the above is true, and boost::mpl::false_ otherwise.
183  typedef typename boost::mpl::and_<std::is_same<U, typename Field<T>::Element>,
184  boost::mpl::bool_<KeyBase<T>::HAS_NAMED_SUBFIELDS> >::type
185  IsMatchPossible;
186  // We use that type to dispatch one of the two overloads of findNamedSubfield.
187  int n = findNamedSubfield(item, name, delimiter, (IsMatchPossible *)0);
188  // If we have a match, we call another overloaded template to make the subfield.
189  if (n >= 0) makeSubfieldItem(item, n, delimiter, result, (IsMatchPossible *)0);
190  }
191 
192  char delimiter;
193  std::string name; // name we're looking for
194  mutable std::unique_ptr<SchemaItem<U> > result; // where we put the result to signal that we're done
195 };
196 
197 } // anonymous
198 
199 // Here's the driver for the find-by-name algorithm.
200 template <typename T>
201 SchemaItem<T> SchemaImpl::find(std::string const &name) const {
202  NameMap::const_iterator i = _names.lower_bound(name);
203  if (i != _names.end()) {
204  if (i->first == name) {
205  // got an exact match; we're done if it has the right type, and dead if it doesn't.
206  try {
207  return boost::get<SchemaItem<T> const>(_items[i->second]);
208  } catch (boost::bad_get &err) {
210  (boost::format("Field '%s' does not have the given type.") % name).str());
211  }
212  }
213  }
214  // We didn't get an exact match, but we might be searching for "a.x/a_x" and "a" might be a point field.
215  // Because the names are sorted, we know we overshot it, so we work backwards.
216  ExtractItemByName<T> extractor(name, getDelimiter());
217  while (i != _names.begin()) {
218  --i;
219  boost::apply_visitor(extractor, _items[i->second]); // see if the current item is a match
220  if (extractor.result) return *extractor.result;
221  }
223  (boost::format("Field or subfield withname '%s' not found with type '%s'.") % name %
225  .str());
226 }
227 
228 //----- Finding a SchemaItem by key -------------------------------------------------------------------------
229 
230 // This is easier to understand if you start reading from the bottom of this section, with
231 // SchemaImpl::find(Key<T> const &), then work your way up.
232 
233 namespace {
234 
235 // Given a SchemaItem for a regular field, look for a subfield with the given Key
236 // Return the index of the subfield (>= 0) on success, -1 on failure.
237 template <typename T, typename U>
238 inline int findKeySubfield(
239  SchemaItem<T> const &item, Key<U> const &key,
240  boost::mpl::true_ * // whether a match is possible based on the types of T and U; computed by caller
241  ) {
242  int n = (key.getOffset() - item.key.getOffset()) / sizeof(U);
243  if (n >= 0 && n < item.key.getElementCount()) {
244  return n;
245  }
246  return -1;
247 }
248 
249 // This is an overload of findKeySubfield that always fails; it's called when we
250 // know from the type of the field and subfield that they're incompatible.
251 template <typename T, typename U>
252 inline int findKeySubfield(
253  SchemaItem<T> const &item, Key<U> const &key,
254  boost::mpl::false_ * // whether a match is possible based on the types of T and U; computed by caller
255  ) {
256  return -1;
257 }
258 
259 // This is a Variant visitation functor used to extract subfield items by key.
260 template <typename U>
261 struct ExtractItemByKey : public boost::static_visitor<> {
262  explicit ExtractItemByKey(Key<U> const &key_, char delimiter_) : delimiter(delimiter_), key(key_) {}
263 
264  template <typename T>
265  void operator()(SchemaItem<T> const &item) const {
266  // We want to find out if 'item' has a subfield whose matches our key data member.
267  // But we also know that the subfield needs to have type U.
268  // This typedef is boost::mpl::true_ if the above is true, and boost::mpl::false_ otherwise.
269  typedef typename boost::mpl::and_<std::is_same<U, typename Field<T>::Element>,
270  boost::mpl::bool_<KeyBase<T>::HAS_NAMED_SUBFIELDS> >::type
271  IsMatchPossible;
272  // We use that type to dispatch one of the two overloads of findKeySubfield.
273  int n = findKeySubfield(item, key, (IsMatchPossible *)0);
274  // If we have a match, we call another overloaded template to make the subfield.
275  // (this is the same makeSubfieldItem used in ExtractItemByName, so it's defined up there)
276  if (n >= 0) makeSubfieldItem(item, n, delimiter, result, (IsMatchPossible *)0);
277  }
278 
279  char delimiter;
280  Key<U> key;
282 };
283 
284 } // anonymous.
285 
286 // Here's the driver for the find-by-key algorithm. It's pretty similar to the find-by-name algorithm.
287 template <typename T>
288 SchemaItem<T> SchemaImpl::find(Key<T> const &key) const {
289  OffsetMap::const_iterator i = _offsets.lower_bound(key.getOffset());
290  if (i != _offsets.end()) {
291  if (i->first == key.getOffset()) {
292  try {
293  return boost::get<SchemaItem<T> const>(_items[i->second]);
294  } catch (boost::bad_get &err) {
295  // just swallow the exception; this might be a subfield key that points to the beginning.
296  }
297  }
298  // We didn't get an exact match, but we might be searching for a subfield.
299  // Because the offsets are sorted, we know we overshot it, so we work backwards.
300  ExtractItemByKey<T> extractor(key, getDelimiter());
301  while (i != _offsets.begin()) {
302  --i;
303  boost::apply_visitor(extractor, _items[i->second]);
304  if (extractor.result) return *extractor.result;
305  }
306  }
308  (boost::format("Field or subfield with offset %d not found with type '%s'.") %
310  .str());
311 }
312 
313 // We handle Flag fields separately when searching for keys, because their keys aren't like the others.
314 SchemaItem<Flag> SchemaImpl::find(Key<Flag> const &key) const {
315  FlagMap::const_iterator i = _flags.lower_bound(std::make_pair(key.getOffset(), key.getBit()));
316  if (i != _flags.end()) {
317  if (i->first.first == key.getOffset() && i->first.second == key.getBit()) {
318  try {
319  return boost::get<SchemaItem<Flag> const>(_items[i->second]);
320  } catch (boost::bad_get &err) {
322  (boost::format("Flag field with offset %d and bit %d not found.") %
323  key.getOffset() % key.getBit())
324  .str());
325  }
326  }
327  }
328  // Flag keys are never subfields, so we require an exact match.
330  (boost::format("Flag field with offset %d and bit %d not found.") % key.getOffset() %
331  key.getBit())
332  .str());
333 }
334 
335 //----- Replacing an existing SchemaItem --------------------------------------------------------------------
336 
337 // This is easier to understand if you start reading from the bottom of this section, with
338 // SchemaImpl::replaceField, then work your way up.
339 
340 namespace {
341 
342 // Find an exact SchemaItem by key ('exact' means no subfields, unlike the find member function above)
343 // Return the index into the item container.
344 template <typename T>
345 inline int findKey(SchemaImpl::OffsetMap const &offsets, SchemaImpl::FlagMap const &flags, Key<T> const &key,
346  bool throwIfMissing = true) {
347  SchemaImpl::OffsetMap::const_iterator i = offsets.find(key.getOffset());
348  if (i == offsets.end()) {
349  if (throwIfMissing) {
351  (boost::format("Key of type %s with offset %d not found in Schema") %
353  .str());
354  } else {
355  return -1;
356  }
357  }
358  return i->second;
359 }
360 
361 // Like the above, but special-cased for Flag
362 inline int findKey(SchemaImpl::OffsetMap const &offsets, SchemaImpl::FlagMap const &flags,
363  Key<Flag> const &key, bool throwIfMissing = true) {
364  SchemaImpl::FlagMap::const_iterator i = flags.find(std::make_pair(key.getOffset(), key.getBit()));
365  if (i == flags.end()) {
366  if (throwIfMissing) {
367  throw LSST_EXCEPT(
369  (boost::format("Key of type Flag with offset %d and bit %d not found in Schema") %
370  key.getOffset() % key.getBit())
371  .str());
372  } else {
373  return -1;
374  }
375  }
376  return i->second;
377 }
378 
379 } // anonymous
380 
381 template <typename T>
382 void SchemaImpl::replaceField(Key<T> const &key, Field<T> const &field) {
383  NameMap::iterator j = _names.find(field.getName());
384  SchemaItem<T> *item = 0;
385  if (j != _names.end()) {
386  // The field name is already present in the Schema; see if it's the one we're replacing.
387  // If we can get the old item with this, we don't need to update the name map at all.
388  item = boost::get<SchemaItem<T> >(&_items[j->second]);
389  if (!item || key != item->key) {
390  throw LSST_EXCEPT(
392  (boost::format("Field with name '%s' already present in schema with a different key.") %
393  field.getName())
394  .str());
395  }
396  }
397  if (!item) { // Need to find the original item by key, since it's a new name.
398  int index = findKey(_offsets, _flags, key);
399  item = boost::get<SchemaItem<T> >(&_items[index]);
400  if (!item) {
402  (boost::format("Incorrect key type '%s'.") % key).str());
403  }
404  j = _names.find(item->field.getName());
405  _names.insert(j, std::pair<std::string, int>(field.getName(), j->second));
406  _names.erase(j);
407  }
408  item->field = field;
409 }
410 
411 //----- Other SchemaImpl things -----------------------------------------------------------------------------
412 
413 template <typename T>
414 int SchemaImpl::contains(SchemaItem<T> const &item, int flags) const {
415  if (!(flags & Schema::EQUAL_KEYS)) {
417  "Can only check whether item is in schema if flags & EQUAL_KEYS");
418  }
419  SchemaItem<T> const *cmpItem = 0;
420  int index = findKey(_offsets, _flags, item.key, false);
421  if (index >= 0) {
422  cmpItem = boost::get<SchemaItem<T> >(&_items[index]);
423  if (!cmpItem) {
424  if ((flags & Schema::EQUAL_NAMES) && cmpItem->field.getName() != item.field.getName()) {
425  flags &= ~Schema::EQUAL_NAMES;
426  }
427  if ((flags & Schema::EQUAL_DOCS) && cmpItem->field.getDoc() != item.field.getDoc()) {
428  flags &= ~Schema::EQUAL_DOCS;
429  }
430  if ((flags & Schema::EQUAL_UNITS) && cmpItem->field.getUnits() != item.field.getUnits()) {
431  flags &= ~Schema::EQUAL_UNITS;
432  }
433  }
434  } else {
435  flags = 0;
436  }
437  return flags;
438 }
439 
440 std::set<std::string> SchemaImpl::getNames(bool topOnly) const {
442  if (topOnly) {
443  for (NameMap::const_iterator i = _names.begin(); i != _names.end(); ++i) {
444  std::size_t sep = i->first.find(getDelimiter());
445  if (sep == std::string::npos) {
446  result.insert(result.end(), i->first);
447  } else {
448  result.insert(result.end(), i->first.substr(0, sep));
449  }
450  }
451  } else {
452  for (NameMap::const_iterator i = _names.begin(); i != _names.end(); ++i) {
453  result.insert(result.end(), i->first);
454  }
455  }
456  return result;
457 }
458 
459 std::set<std::string> SchemaImpl::getNames(bool topOnly, std::string const &prefix) const {
461  if (topOnly) {
462  for (NameMap::const_iterator i = _names.lower_bound(prefix); i != _names.end(); ++i) {
463  if (i->first.compare(0, prefix.size(), prefix) != 0) break;
464  std::size_t sep = i->first.find(getDelimiter(), prefix.size() + 1);
465  if (sep == std::string::npos) {
466  result.insert(result.end(),
467  i->first.substr(prefix.size() + 1, i->first.size() - prefix.size()));
468  } else {
469  result.insert(result.end(), i->first.substr(prefix.size() + 1, sep - prefix.size() - 1));
470  }
471  }
472  } else {
473  for (NameMap::const_iterator i = _names.lower_bound(prefix); i != _names.end(); ++i) {
474  if (i->first.compare(0, prefix.size(), prefix) != 0) break;
475  result.insert(result.end(),
476  i->first.substr(prefix.size() + 1, i->first.size() - prefix.size() - 1));
477  }
478  }
479  return result;
480 }
481 
482 template <typename T>
483 Key<Array<T> > SchemaImpl::addField(Field<Array<T> > const &field, bool doReplace) {
484  if (field.isVariableLength()) {
485  // Variable-length array: allocate space for one ndarray
486  return addFieldImpl(sizeof(ndarray::Array<T, 1, 1>), 1, field, doReplace);
487  }
488  // Fixed-length array: allocate space for getElementCount() elements of type T
489  return addFieldImpl(sizeof(typename Field<T>::Element), field.getElementCount(), field, doReplace);
490 }
491 
492 Key<std::string> SchemaImpl::addField(Field<std::string> const &field, bool doReplace) {
493  if (field.isVariableLength()) {
494  // Variable-length string: allocate space for one std::string
495  return addFieldImpl(sizeof(std::string), 1, field, doReplace);
496  }
497  // Fixed-length string: allocate space for getElementCount() chars
498  return addFieldImpl(sizeof(typename Field<std::string>::Element), field.getElementCount(), field, doReplace);
499 }
500 
501 template <typename T>
502 Key<T> SchemaImpl::addField(Field<T> const &field, bool doReplace) {
503  return addFieldImpl(sizeof(typename Field<T>::Element), field.getElementCount(), field, doReplace);
504 }
505 
506 Key<Flag> SchemaImpl::addField(Field<Flag> const &field, bool doReplace) {
507  static int const ELEMENT_SIZE = sizeof(Field<Flag>::Element);
509  _names.insert(std::pair<std::string, int>(field.getName(), _items.size()));
510  if (!result.second) {
511  if (doReplace) {
512  SchemaItem<Flag> *item = boost::get<SchemaItem<Flag> >(&_items[result.first->second]);
513  if (!item) {
514  throw LSST_EXCEPT(
516  (boost::format("Cannot replace field with name '%s' because types differ.") %
517  field.getName())
518  .str());
519  }
520  if (item->field.getElementCount() != field.getElementCount()) {
521  throw LSST_EXCEPT(
523  (boost::format("Cannot replace field with name '%s' because sizes differ.") %
524  field.getName())
525  .str());
526  }
527  item->field = field;
528  return item->key;
529  } else {
530  throw LSST_EXCEPT(
532  (boost::format("Field with name '%s' already present in schema.") % field.getName())
533  .str());
534  }
535  } else {
536  if (_lastFlagField < 0 || _lastFlagBit >= ELEMENT_SIZE * 8) {
537  int padding = ELEMENT_SIZE - _recordSize % ELEMENT_SIZE;
538  if (padding != ELEMENT_SIZE) {
539  _recordSize += padding;
540  }
541  _lastFlagField = _recordSize;
542  _lastFlagBit = 0;
543  _recordSize += field.getElementCount() * ELEMENT_SIZE;
544  }
545  SchemaItem<Flag> item(detail::Access::makeKey(_lastFlagField, _lastFlagBit), field);
546  ++_lastFlagBit;
547  _flags.insert(std::pair<std::pair<int, int>, int>(
548  std::make_pair(item.key.getOffset(), item.key.getBit()), _items.size()));
549  _items.push_back(item);
550  return item.key;
551  }
552 }
553 
554 template <typename T>
555 Key<T> SchemaImpl::addFieldImpl(int elementSize, int elementCount, Field<T> const &field, bool doReplace) {
557  _names.insert(std::pair<std::string, int>(field.getName(), _items.size()));
558  if (!result.second) {
559  if (doReplace) {
560  SchemaItem<T> *item = boost::get<SchemaItem<T> >(&_items[result.first->second]);
561  if (!item) {
562  throw LSST_EXCEPT(
564  (boost::format("Cannot replace field with name '%s' because types differ.") %
565  field.getName())
566  .str());
567  }
568  // n.b. we don't use elementCount here because we *do* want variable length arrays (for
569  // which we set elementCount == 1, but field->getElementCount() == -1) to compare as different
570  // from fixed-length arrays with a single element.
571  if (item->field.getElementCount() != field.getElementCount()) {
572  throw LSST_EXCEPT(
574  (boost::format("Cannot replace field with name '%s' because sizes differ.") %
575  field.getName())
576  .str());
577  }
578  item->field = field;
579  return item->key;
580  } else {
581  throw LSST_EXCEPT(
583  (boost::format("Field with name '%s' already present in schema.") % field.getName())
584  .str());
585  }
586  } else {
587  int padding = elementSize - _recordSize % elementSize;
588  if (padding != elementSize) {
589  _recordSize += padding;
590  }
591  SchemaItem<T> item(detail::Access::makeKey(field, _recordSize), field);
592  _recordSize += elementCount * elementSize;
593  _offsets.insert(std::pair<int, int>(item.key.getOffset(), _items.size()));
594  _items.push_back(item);
595  return item.key;
596  }
597 }
598 
599 } // namespace detail
600 
601 //-----------------------------------------------------------------------------------------------------------
602 //----- Schema implementation -------------------------------------------------------------------------------
603 //-----------------------------------------------------------------------------------------------------------
604 
605 int const Schema::VERSION;
606 
607 Schema::Schema() : _impl(std::make_shared<Impl>()), _aliases(std::make_shared<AliasMap>()) {}
608 
609 Schema::Schema(Schema const &other) : _impl(other._impl), _aliases(other._aliases) {}
610 // Delegate to copy constructor for backwards compatibility
612 
613 Schema &Schema::operator=(Schema const&) = default;
614 Schema &Schema::operator=(Schema&&) = default;
615 Schema::~Schema() = default;
616 
617 Schema Schema::readFits(std::string const &filename, int hdu) {
619  fp.setHdu(hdu);
620  return readFits(fp);
621 }
622 
625  fp.setHdu(hdu);
626  return readFits(fp);
627 }
628 
631  fitsfile.readMetadata(header, false);
632  return fromFitsMetadata(header);
633 }
634 
636  return io::FitsSchemaInputMapper(header, stripMetadata).finalize();
637 }
638 
639 std::string Schema::join(std::string const &a, std::string const &b) const {
640  // delegate to utility funcs at top of this file
641  return afw::table::join(a, b, getDelimiter());
642 }
643 
644 void Schema::_edit() {
645  if (!_impl.unique()) {
646  std::shared_ptr<Impl> data(std::make_shared<Impl>(*_impl));
647  _impl.swap(data);
648  }
649 }
650 
651 std::set<std::string> Schema::getNames(bool topOnly) const { return _impl->getNames(topOnly); }
652 
653 template <typename T>
655  std::string tmp(name);
656  _aliases->_apply(tmp);
657  return _impl->find<T>(tmp);
658 }
659 
660 template <typename T>
662  return _impl->find(key);
663 }
664 
665 template <typename T>
666 Key<T> Schema::addField(Field<T> const &field, bool doReplace) {
667  _edit();
668  return _impl->addField(field, doReplace);
669 }
670 
671 template <typename T>
673  _edit();
674  _impl->replaceField(key, field);
675 }
676 
677 int Schema::contains(Schema const &other, int flags) const {
678  if (_impl == other._impl) return flags;
679  if (_impl->getItems().size() < other._impl->getItems().size()) return 0;
680  int result = flags;
681  if (result & EQUAL_FIELDS) {
682  for (Impl::ItemContainer::const_iterator i1 = _impl->getItems().begin(),
683  i2 = other._impl->getItems().begin();
684  i2 != other._impl->getItems().end(); ++i1, ++i2) {
685  if ((result & EQUAL_KEYS) && !ItemFunctors::compareKeys(*i1, *i2)) result &= ~EQUAL_KEYS;
686  if ((result & EQUAL_NAMES) && !ItemFunctors::compareNames(*i1, *i2)) result &= ~EQUAL_NAMES;
687  if ((result & EQUAL_DOCS) && !ItemFunctors::compareDocs(*i1, *i2)) result &= ~EQUAL_DOCS;
688  if ((result & EQUAL_UNITS) && !ItemFunctors::compareUnits(*i1, *i2)) result &= ~EQUAL_UNITS;
689  if (!result) break;
690  }
691  }
692  if ((result & EQUAL_ALIASES) && !getAliasMap()->contains(*other.getAliasMap())) result &= ~EQUAL_ALIASES;
693  return result;
694 }
695 
696 int Schema::compare(Schema const &other, int flags) const {
697  int result = contains(other, flags);
698  if (_impl->getItems().size() != other._impl->getItems().size()) {
699  result &= ~EQUAL_FIELDS;
700  }
701  if (getAliasMap()->size() != other.getAliasMap()->size()) {
702  result &= ~EQUAL_ALIASES;
703  }
704  return result;
705 }
706 
707 template <typename T>
708 int Schema::contains(SchemaItem<T> const &item, int flags) const {
709  return _impl->contains(item, flags);
710 }
711 
713  if (!aliases) {
714  aliases = std::make_shared<AliasMap>();
715  }
716  _aliases = aliases;
717 }
718 
719 void Schema::disconnectAliases() { _aliases = std::make_shared<AliasMap>(*_aliases); }
720 
721 //----- Stringification -------------------------------------------------------------------------------------
722 
723 namespace {
724 
725 // Schema::forEach functor used for stringificationx
726 struct Stream {
727  typedef void result_type;
728 
729  template <typename T>
730  void operator()(SchemaItem<T> const &item) const {
731  *os << " (" << item.field << ", " << item.key << "),\n";
732  }
733 
734  explicit Stream(std::ostream *os_) : os(os_) {}
735 
737 };
738 
739 } // anonymous
740 
742  os << "Schema(\n";
743  schema.forEach(Stream(&os));
744  for (auto iter = schema.getAliasMap()->begin(); iter != schema.getAliasMap()->end(); ++iter) {
745  os << " '" << iter->first << "'->'" << iter->second << "'\n";
746  }
747  return os << ")\n";
748 }
749 
750 //-----------------------------------------------------------------------------------------------------------
751 //----- SubSchema implementation ----------------------------------------------------------------------------
752 //-----------------------------------------------------------------------------------------------------------
753 
755  // delegate to utility funcs at top of this file
756  return afw::table::join(a, b, getDelimiter());
757 }
758 
759 SubSchema::SubSchema(std::shared_ptr<Impl> impl, std::shared_ptr<AliasMap> aliases, std::string const &name)
760  : _impl(impl), _aliases(aliases), _name(name) {}
761 
762 template <typename T>
764  return _impl->find<T>(_aliases->apply(join(_name, name)));
765 }
766 
768  return SubSchema(_impl, _aliases, join(_name, name));
769 }
770 
771 std::set<std::string> SubSchema::getNames(bool topOnly) const { return _impl->getNames(topOnly, _name); }
772 
773 //-----------------------------------------------------------------------------------------------------------
774 //----- Explicit instantiation ------------------------------------------------------------------------------
775 //-----------------------------------------------------------------------------------------------------------
776 
777 // Note: by instantiating the public functions below, we also instantiate a lot of the private
778 // implementation functions. If you move some of those to a different source file, you'll need
779 // more explicit instantiation.
780 
781 #define INSTANTIATE_LAYOUT(r, data, elem) \
782  template Key<elem> Schema::addField(Field<elem> const &, bool); \
783  template SchemaItem<elem> Schema::find(std::string const &) const; \
784  template SchemaItem<elem> Schema::find(Key<elem> const &) const; \
785  template SchemaItem<elem> detail::SchemaImpl::find(std::string const &name) const; \
786  template int Schema::contains(SchemaItem<elem> const &, int) const; \
787  template void Schema::replaceField(Key<elem> const &, Field<elem> const &); \
788  template SchemaItem<elem> SubSchema::find(std::string const &) const;
789 
791  BOOST_PP_TUPLE_TO_SEQ(AFW_TABLE_FIELD_TYPE_N, AFW_TABLE_FIELD_TYPE_TUPLE))
792 }
793 }
794 } // namespace lsst::afw::table
Defines the fields and offsets for a table.
Definition: Schema.h:47
friend class SubSchema
Definition: Schema.h:313
std::string join(std::string const &a, std::string const &b) const
Join strings using the field delimiter appropriate for this Schema.
Definition: Schema.cc:754
void setAliasMap(std::shared_ptr< AliasMap > aliases)
Set the alias map.
Definition: Schema.cc:712
Schema()
Construct an empty Schema.
Definition: Schema.cc:607
char * data
Definition: BaseTable.cc:204
A proxy type for name lookups in a Schema.
Definition: Schema.h:354
int compare(Schema const &other, int flags=EQUAL_KEYS) const
Do a detailed equality comparison of two schemas.
Definition: Schema.cc:696
Keys have the same types offsets, and sizes.
Definition: Schema.h:62
std::string const & _name
Definition: Mask.cc:576
int getOffset() const
Return the offset (in bytes) of this field within a record.
Definition: Key.h:79
afw::table::Schema schema
Definition: GaussianPsf.cc:43
std::string join(std::string const &a, std::string const &b) const
Join strings using the field delimiter appropriate for this Schema.
Definition: Schema.cc:639
static Schema fromFitsMetadata(daf::base::PropertyList &header, bool stripMetadata=true)
Construct from reading a FITS header.
Definition: Schema.cc:635
Mapping class that holds aliases for a Schema.
Definition: AliasMap.h:36
static Key< T > makeKey(int offset)
Definition: Access.h:65
void disconnectAliases()
Sever the connection between this schema and any others with which it shares aliases.
Definition: Schema.cc:719
STL namespace.
static Schema readFits(std::string const &filename, int hdu=fits::DEFAULT_HDU)
Construct from reading a FITS file.
Definition: Schema.cc:617
Schemas have identical AliasMaps.
Definition: Schema.h:67
std::string const & getName() const
Return the name of the field.
Definition: Field.h:77
T end(T... args)
A class that describes a mapping from a FITS binary table to an afw::table Schema.
boost::make_variant_over< ItemTypes >::type ItemVariant
A Boost.Variant type that can hold any one of the allowed SchemaItem types.
Definition: SchemaImpl.h:69
SubSchema operator[](std::string const &name) const
Return a nested proxy.
Definition: Schema.cc:767
ItemVariant const * other
Definition: Schema.cc:55
A simple struct that combines the two arguments that must be passed to most cfitsio routines and cont...
Definition: fits.h:298
#define AFW_TABLE_FIELD_TYPE_TUPLE
Definition: types.h:43
int getElementCount() const
Return the number of subfield elements (always one for scalars).
Definition: FieldBase.h:51
void forEach(F &&func) const
Apply a functor to each SchemaItem in the Schema.
Definition: Schema.h:209
STL class.
T push_back(T... args)
Fields have the same units (ordered).
Definition: Schema.h:65
SchemaItem< T > find(std::string const &name) const
Find a SchemaItem in the Schema by name.
Definition: Schema.cc:654
Fields have the same names (ordered).
Definition: Schema.h:63
A base class for image defects.
int contains(Schema const &other, int flags=EQUAL_KEYS) const
Test whether the given schema is a subset of this.
Definition: Schema.cc:677
Lifetime-management for memory that goes into FITS memory files.
Definition: fits.h:120
char delimiter
Definition: Schema.cc:192
static Key< typename Key< T >::Element > extractElement(KeyBase< T > const &kb, int n)
Definition: Access.h:35
table::Key< int > b
A description of a field in a table.
Definition: Field.h:24
Key< U > key
Definition: Schema.cc:280
T make_pair(T... args)
Tag types used to declare specialized field types.
Definition: misc.h:32
int getBit() const
The index of this field&#39;s bit within the integer it shares with other Flag fields.
Definition: Flag.h:121
std::unique_ptr< SchemaItem< U > > result
Definition: Schema.cc:194
std::set< std::string > getNames(bool topOnly=false) const
Return a set of nested names that start with the SubSchema&#39;s prefix.
Definition: Schema.cc:771
A private implementation class to hide the messy details of Schema.
Definition: SchemaImpl.h:53
T insert(T... args)
BOOST_PP_SEQ_FOR_EACH(INSTANTIATE_COLUMNVIEW_SCALAR, _, BOOST_PP_TUPLE_TO_SEQ(AFW_TABLE_SCALAR_FIELD_TYPE_N, AFW_TABLE_SCALAR_FIELD_TYPE_TUPLE)) BOOST_PP_SEQ_FOR_EACH(INSTANTIATE_COLUMNVIEW_ARRAY
T find(T... args)
T size(T... args)
STL class.
#define LSST_EXCEPT(type,...)
std::shared_ptr< AliasMap > getAliasMap() const
Return the map of aliases.
Definition: Schema.h:263
STL class.
friend std::ostream & operator<<(std::ostream &os, Schema const &schema)
Stringification.
Definition: Schema.cc:741
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.
Key specialization for Flag.
Definition: Flag.h:92
#define INSTANTIATE_LAYOUT(r, data, elem)
Definition: Schema.cc:781
void replaceField(Key< T > const &key, Field< T > const &field)
Replace the Field (name/description) for an existing Key.
Definition: Schema.cc:672
FieldBase< T >::Element Element
Type used to store field data in the table (a field may have multiple elements).
Definition: Field.h:26
std::string prefix
Definition: SchemaMapper.cc:79
std::string name
Definition: Schema.cc:193
int getElementCount() const
Return the number of subfield elements (always one for scalars).
Definition: Flag.h:36
table::Key< int > a
int getOffset() const
Return the offset in bytes of the integer element that holds this field&#39;s bit.
Definition: Flag.h:118
std::ostream * os
Definition: Schema.cc:736
static std::string getTypeString()
Return a string description of the field type.
Definition: FieldBase.cc:56
Fields have the same documentation (ordered).
Definition: Schema.h:64
STL class.
std::set< std::string > getNames(bool topOnly=false) const
Return a set of field names in the schema.
Definition: Schema.cc:651
Schema & operator=(Schema const &other)
Fields are identical (but aliases may not be).
Definition: Schema.h:66
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
SchemaItem< T > find(std::string const &name) const
Find a nested SchemaItem by name.
Definition: Schema.cc:763
table::Key< int > field
Definition: ApCorrMap.cc:72
void readMetadata(daf::base::PropertySet &metadata, bool strip=false)
Read a FITS header into a PropertySet or PropertyList.
Definition: fits.cc:961
T compare(T... args)
#define AFW_TABLE_FIELD_TYPE_N
Definition: types.h:38
T reserve(T... args)
A simple pair-like struct for mapping a Field (name and description) with a Key (used for actual data...
Definition: SchemaImpl.h:27