lsst.afw  13.0-92-g8ecf155+1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
schema.cc
Go to the documentation of this file.
1 /*
2  * LSST Data Management System
3  * Copyright 2008-2016 AURA/LSST.
4  *
5  * This product includes software developed by the
6  * LSST Project (http://www.lsst.org/).
7  *
8  * This program is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the LSST License Statement and
19  * the GNU General Public License along with this program. If not,
20  * see <https://www.lsstcorp.org/LegalNotices/>.
21  */
22 
23 #include "pybind11/pybind11.h"
24 #include "pybind11/stl.h"
25 
26 #include <sstream>
27 
28 #include "numpy/arrayobject.h"
29 #include "ndarray/pybind11.h"
30 
31 #include "lsst/afw/fits.h"
32 #include "lsst/afw/table/Schema.h"
35 
36 namespace py = pybind11;
37 using namespace pybind11::literals;
38 
39 namespace lsst {
40 namespace afw {
41 namespace table {
42 
43 namespace {
44 
45 using PySchema = py::class_<Schema>;
46 
47 using PySubSchema = py::class_<SubSchema>;
48 
49 template <typename T>
50 using PyFieldBase = py::class_<FieldBase<T>>;
51 
52 template <typename T>
53 using PyKeyBase = py::class_<KeyBase<T>>;
54 
55 template <typename T>
56 using PyField = py::class_<Field<T>, FieldBase<T>>;
57 
58 template <typename T>
59 using PyKey = py::class_<Key<T>, KeyBase<T>, FieldBase<T>>;
60 
61 template <typename T>
62 using PySchemaItem = py::class_<SchemaItem<T>>;
63 
64 template <typename T>
65 std::string streamStr(T const &self) {
66  std::ostringstream os;
67  os << self;
68  return os.str();
69 }
70 
71 // Specializations for FieldBase
72 
73 template <typename T>
74 void declareFieldBaseSpecializations(PyFieldBase<T> &cls) {
75  cls.def(py::init<>());
76 }
77 
78 template <typename T>
79 void declareFieldBaseSpecializations(PyFieldBase<Array<T>> &cls) {
80  cls.def(py::init<int>(), "size"_a = 0);
81  cls.def("getSize", &FieldBase<Array<T>>::getSize);
82  cls.def("isVariableLength", &FieldBase<Array<T>>::isVariableLength);
83 }
84 
85 void declareFieldBaseSpecializations(PyFieldBase<std::string> &cls) {
86  cls.def(py::init<int>(), "size"_a = -1);
87  cls.def("getSize", &FieldBase<std::string>::getSize);
88 }
89 
90 // Specializations for KeyBase
91 
92 template <typename T>
93 void declareKeyBaseSpecializations(PyKeyBase<T> &) {}
94 
95 template <typename T>
96 void declareKeyBaseSpecializations(PyKeyBase<Array<T>> &cls) {
97  cls.def("__getitem__", [](Key<Array<T>> const &self, py::object const &index) -> py::object {
98  if (py::isinstance<py::slice>(index)) {
99  py::slice slice(index);
100  py::size_t start = 0, stop = 0, step = 0, length = 0;
101  bool valid = slice.compute(self.getSize(), &start, &stop, &step, &length);
102  if (!valid) throw py::error_already_set();
103  if (step != 1) {
104  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
105  "Step for array Key indexing must be 1.");
106  }
107  return py::cast(self.slice(start, stop));
108  } else {
109  return py::cast(self[py::cast<int>(index)]);
110  }
111  });
112  cls.def("slice", &KeyBase<Array<T>>::slice);
113 }
114 
115 // Specializations for Key
116 
117 template <typename T>
118 void declareKeyAccessors(PyKey<T> &cls) {
119  cls.def("get", [](Key<T> const &self, BaseRecord &record) { return record.get(self); });
120  cls.def("set", [](Key<T> const &self, BaseRecord &record, typename Key<T>::Value const &value) {
121  record.set(self, value);
122  });
123 }
124 
125 template <typename U>
126 void declareKeyAccessors(PyKey<Array<U>> &cls) {
127  auto getter = [](Key<Array<U>> const &self, BaseRecord &record) -> ndarray::Array<U, 1, 1> {
128  return record[self];
129  };
130  auto setter = [](Key<Array<U>> const &self, BaseRecord &record, py::object const &value) {
131  if (self.getSize() == 0) {
132  // Variable-length array field: do a shallow copy, which requires a non-const
133  // contiguous array.
134  record.set(self, py::cast<ndarray::Array<U, 1, 1>>(value));
135  } else {
136  // Fixed-length array field: do a deep copy, which can work with a const
137  // noncontiguous array. But we need to check the size first, since the
138  // penalty for getting that wrong is assert->abort.
139  auto v = py::cast<ndarray::Array<U const, 1, 0>>(value);
140  ndarray::ArrayRef<U, 1, 1> ref = record[self];
141  if (v.size() != ref.size()) {
142  throw LSST_EXCEPT(
143  pex::exceptions::LengthError,
144  (boost::format("Array sizes do not agree: %s != %s") % v.size() % ref.size()).str());
145  }
146  ref = v;
147  }
148  return;
149  };
150  cls.def("get", getter);
151  cls.def("set", setter);
152 }
153 
154 template <typename T>
155 void declareKeySpecializations(PyKey<T> &cls) {
156  declareKeyAccessors(cls);
157  cls.def_property_readonly("subfields", [](py::object const &) { return py::none(); });
158  cls.def_property_readonly("subkeys", [](py::object const &) { return py::none(); });
159 }
160 
161 void declareKeySpecializations(PyKey<Flag> &cls) {
162  declareKeyAccessors(cls);
163  cls.def_property_readonly("subfields", [](py::object const &) { return py::none(); });
164  cls.def_property_readonly("subkeys", [](py::object const &) { return py::none(); });
165  cls.def("getBit", &Key<Flag>::getBit);
166 }
167 
168 template <typename U>
169 void declareKeySpecializations(PyKey<Array<U>> &cls) {
170  declareKeyAccessors(cls);
171  cls.def_property_readonly("subfields", [](Key<Array<U>> const &self) -> py::object {
172  py::list result;
173  for (int i = 0; i < self.getSize(); ++i) {
174  result.append(py::cast(i));
175  }
176  return py::tuple(result);
177  });
178  cls.def_property_readonly("subkeys", [](Key<Array<U>> const &self) -> py::object {
179  py::list result;
180  for (int i = 0; i < self.getSize(); ++i) {
181  result.append(py::cast(self[i]));
182  }
183  return py::tuple(result);
184  });
185 }
186 
187 // Wrap all helper classes (FieldBase, KeyBase, Key, Field, SchemaItem) declarefor a Schema field type.
188 template <typename T>
189 void declareSchemaType(py::module &mod) {
190  std::string suffix = FieldBase<T>::getTypeString();
191  py::str pySuffix(suffix);
192 
193  py::object astropyUnit = py::module::import("astropy.units").attr("Unit");
194 
195  // FieldBase
196  PyFieldBase<T> clsFieldBase(mod, ("FieldBase" + suffix).c_str());
197  clsFieldBase.def_static("getTypeString", &FieldBase<T>::getTypeString);
198  declareFieldBaseSpecializations(clsFieldBase);
199 
200  // KeyBase
201  PyKeyBase<T> clsKeyBase(mod, ("KeyBase" + suffix).c_str());
202  clsKeyBase.def_readonly_static("HAS_NAMED_SUBFIELDS", &KeyBase<T>::HAS_NAMED_SUBFIELDS);
203  declareKeyBaseSpecializations(clsKeyBase);
204 
205  // Field
206  PyField<T> clsField(mod, ("Field" + suffix).c_str());
207  mod.attr("_Field")[pySuffix] = clsField;
208  clsField.def("__init__",
209  [astropyUnit]( // capture by value to refcount in Python instead of dangle in C++
210  Field<T> &self, std::string const &name, std::string const &doc,
211  py::str const &units, py::object const &size, py::str const &parse_strict) {
212  astropyUnit(units, "parse_strict"_a = parse_strict);
213  std::string u = py::cast<std::string>(units);
214  if (size == py::none()) {
215  new (&self) Field<T>(name, doc, u);
216  } else {
217  int s = py::cast<int>(size);
218  new (&self) Field<T>(name, doc, u, s);
219  }
220  },
221  "name"_a, "doc"_a = "", "units"_a = "", "size"_a = py::none(), "parse_strict"_a = "raise");
222  clsField.def("_addTo", [](Field<T> const &self, Schema &schema, bool doReplace) -> Key<T> {
223  return schema.addField(self, doReplace);
224  });
225  clsField.def("getName", &Field<T>::getName);
226  clsField.def("getDoc", &Field<T>::getDoc);
227  clsField.def("getUnits", &Field<T>::getUnits);
228  clsField.def("copyRenamed", &Field<T>::copyRenamed);
229  clsField.def("__str__", &streamStr<Field<T>>);
230  clsField.def("__repr__", &streamStr<Field<T>>);
231 
232  // Key
233  PyKey<T> clsKey(mod, ("Key" + suffix).c_str());
234  mod.attr("_Key")[pySuffix] = clsKey;
235  clsKey.def(py::init<>());
236  clsKey.def("__eq__", [](Key<T> const &self, Key<T> const &other) -> bool { return self == other; },
237  py::is_operator());
238  clsKey.def("__ne__", [](Key<T> const &self, Key<T> const &other) -> bool { return self != other; },
239  py::is_operator());
240  clsKey.def("isValid", &Key<T>::isValid);
241  clsKey.def("getOffset", &Key<T>::getOffset);
242  clsKey.def("__str__", &streamStr<Key<T>>);
243  clsKey.def("__repr__", &streamStr<Key<T>>);
244  // The Key methods below actually wrap templated methods on Schema and
245  // SchemaMapper. Rather than doing many-type overload resolution by
246  // wrapping those methods directly, we use the visitor pattern by having
247  // the wrappers for those methods delegate back to these non-templated
248  // methods on the templated Key classes.
249  clsKey.def("_findIn", [](Key<T> const &self, Schema const &schema) { return schema.find(self); });
250  clsKey.def("_addMappingTo", [](Key<T> const &self, SchemaMapper &mapper, Field<T> const &field,
251  bool doReplace) { return mapper.addMapping(self, field, doReplace); });
252  clsKey.def("_addMappingTo", [](Key<T> const &self, SchemaMapper &mapper, std::string const &name,
253  bool doReplace) { return mapper.addMapping(self, name, doReplace); });
254  clsKey.def("_addMappingTo", [](Key<T> const &self, SchemaMapper &mapper, py::object const &,
255  bool doReplace) { return mapper.addMapping(self, doReplace); });
256  declareKeySpecializations(clsKey);
257 
258  // SchemaItem
259  PySchemaItem<T> clsSchemaItem(mod, ("SchemaItem" + suffix).c_str());
260  mod.attr("_SchemaItem")[pySuffix] = clsSchemaItem;
261  clsSchemaItem.def_readonly("key", &SchemaItem<T>::key);
262  clsSchemaItem.def_readonly("field", &SchemaItem<T>::field);
263  clsSchemaItem.def("getKey", [](SchemaItem<T> const &self) { return self.key; });
264  clsSchemaItem.def("getField", [](SchemaItem<T> const &self) { return self.field; });
265  clsSchemaItem.def("__getitem__", [](py::object const &self, int index) -> py::object {
266  if (index == 0) {
267  return self.attr("key");
268  } else if (index == 1) {
269  return self.attr("field");
270  }
271  // Have to raise IndexError not some LSST exception to get the
272  // right behavior when unpacking.
273  throw py::index_error("Index to SchemaItem must be 0 or 1.");
274  });
275  clsSchemaItem.def("__len__", [](py::object const &self) -> int { return 2; });
276  clsSchemaItem.def("__str__", [](py::object const &self) -> py::str { return py::str(py::tuple(self)); });
277  clsSchemaItem.def("__repr__", [](py::object const &self) -> py::str {
278  return py::str("SchemaItem(key={0.key}, field={0.field})").format(self);
279  });
280 }
281 
282 // Helper class for Schema::find(name, func) that converts the result to Python.
283 // In C++14, this should be converted to a universal lambda.
284 struct MakePythonSchemaItem {
285  template <typename T>
286  void operator()(SchemaItem<T> const &item) {
287  result = py::cast(item);
288  }
289 
290  py::object result;
291 };
292 
293 void declareSchema(py::module &mod) {
294  py::module::import("lsst.afw.table.aliasMap");
295 
296  PySchema cls(mod, "Schema");
297  // wrap ComparisonFlags values as ints since we use them as bitflags,
298  // not true enums
299  cls.attr("EQUAL_KEYS") = py::cast(int(Schema::EQUAL_KEYS));
300  cls.attr("EQUAL_NAMES") = py::cast(int(Schema::EQUAL_NAMES));
301  cls.attr("EQUAL_DOCS") = py::cast(int(Schema::EQUAL_DOCS));
302  cls.attr("EQUAL_UNITS") = py::cast(int(Schema::EQUAL_UNITS));
303  cls.attr("EQUAL_FIELDS") = py::cast(int(Schema::EQUAL_FIELDS));
304  cls.attr("EQUAL_ALIASES") = py::cast(int(Schema::EQUAL_ALIASES));
305  cls.attr("IDENTICAL") = py::cast(int(Schema::IDENTICAL));
306 
307  cls.attr("VERSION") = py::cast(int(Schema::VERSION));
308 
309  cls.def(py::init<>());
310  cls.def(py::init<Schema const &>());
311  cls.def("__getitem__", [](Schema &self, std::string const &name) { return self[name]; });
312  cls.def("__eq__", [](Schema const &self, Schema const &other) { return self == other; },
313  py::is_operator());
314  cls.def("__ne__", [](Schema const &self, Schema const &other) { return self != other; },
315  py::is_operator());
316  cls.def("getCitizen", &Schema::getCitizen, py::return_value_policy::reference_internal);
317  cls.def("getRecordSize", &Schema::getRecordSize);
318  cls.def("getFieldCount", &Schema::getFieldCount);
319  cls.def("getFlagFieldCount", &Schema::getFlagFieldCount);
320  cls.def("getNonFlagFieldCount", &Schema::getNonFlagFieldCount);
321  cls.def("find", [](py::object const &self, py::object const &key) -> py::object {
322  try {
323  if (py::isinstance<py::str>(key) || py::isinstance<py::bytes>(key)) {
324  Schema const &s = py::cast<Schema const &>(self);
325  std::string name = py::cast<std::string>(key);
326  MakePythonSchemaItem func;
327  s.findAndApply(name, func);
328  return func.result;
329  }
330  return key.attr("_findIn")(self);
331  } catch (pex::exceptions::NotFoundError &err) {
332  // Avoid API change by re-throwing as KeyError.
333  PyErr_SetString(PyExc_KeyError, err.what());
334  throw py::error_already_set();
335  }
336  });
337  cls.def("getNames", &Schema::getNames, "topOnly"_a = false);
338  cls.def("getAliasMap", &Schema::getAliasMap);
339  cls.def("setAliasMap", &Schema::setAliasMap, "aliases"_a);
340  cls.def("disconnectAliases", &Schema::disconnectAliases);
341  cls.def("forEach", [](Schema &self, py::object &obj) { self.forEach(obj); });
342  cls.def("compare", &Schema::compare, "other"_a, "flags"_a = int(Schema::EQUAL_KEYS));
343  cls.def("contains", (int (Schema::*)(Schema const &, int) const) & Schema::contains, "other"_a,
344  "flags"_a = int(Schema::EQUAL_KEYS));
345  cls.def("__contains__", [](py::object const &self, py::object const &key) {
346  try {
347  self.attr("find")(key);
348  } catch (py::error_already_set &err) {
349  err.clear();
350  return false;
351  }
352  return true;
353  });
354  cls.def_static("readFits", (Schema(*)(std::string const &, int)) & Schema::readFits, "filename"_a,
355  "hdu"_a = INT_MIN);
356  cls.def_static("readFits", (Schema(*)(fits::MemFileManager &, int)) & Schema::readFits, "manager"_a,
357  "hdu"_a = INT_MIN);
358 
359  cls.def("join", (std::string (Schema::*)(std::string const &, std::string const &) const) & Schema::join,
360  "a"_a, "b"_a);
361  cls.def("join",
362  (std::string (Schema::*)(std::string const &, std::string const &, std::string const &) const) &
363  Schema::join,
364  "a"_a, "b"_a, "c"_a);
365  cls.def("join", (std::string (Schema::*)(std::string const &, std::string const &, std::string const &,
366  std::string const &) const) &
367  Schema::join,
368  "a"_a, "b"_a, "c"_a, "d"_a);
369  cls.def("__str__", &streamStr<Schema>);
370  cls.def("__repr__", &streamStr<Schema>);
371 }
372 
373 void declareSubSchema(py::module &mod) {
374  PySubSchema cls(mod, "SubSchema");
375  cls.def("getNames", &SubSchema::getNames, "topOnly"_a = false);
376  cls.def("getPrefix", &SubSchema::getPrefix);
377  cls.def("asKey", [](SubSchema const &self) -> py::object {
378  MakePythonSchemaItem func;
379  self.apply(func);
380  return func.result.attr("key");
381  });
382  cls.def("asField", [](SubSchema const &self) -> py::object {
383  MakePythonSchemaItem func;
384  self.apply(func);
385  return func.result.attr("field");
386  });
387  cls.def("find", [](SubSchema const &self, std::string const &name) -> py::object {
388  MakePythonSchemaItem func;
389  self.findAndApply(name, func);
390  return func.result;
391  });
392  cls.def("__getitem__", [](SubSchema &self, std::string const &name) { return self[name]; });
393 }
394 
395 PYBIND11_PLUGIN(schema) {
396  py::module mod("schema");
397 
398  if (_import_array() < 0) {
399  PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import");
400  return nullptr;
401  };
402 
403  // We'll add instantiations of Field, Key, and SchemaItem to these private
404  // dicts, and then in schemaContinued.py we'll add them to a TemplateMeta
405  // ABC.
406  mod.attr("_Field") = py::dict();
407  mod.attr("_Key") = py::dict();
408  mod.attr("_SchemaItem") = py::dict();
409 
410  declareSchemaType<std::uint16_t>(mod);
411  declareSchemaType<std::int32_t>(mod);
412  declareSchemaType<std::int64_t>(mod);
413  declareSchemaType<float>(mod);
414  declareSchemaType<double>(mod);
415  declareSchemaType<std::string>(mod);
416  declareSchemaType<geom::Angle>(mod);
417  declareSchemaType<Array<std::uint16_t>>(mod);
418  declareSchemaType<Array<int>>(mod);
419  declareSchemaType<Array<float>>(mod);
420  declareSchemaType<Array<double>>(mod);
421  declareSchemaType<Flag>(mod);
422 
423  declareSchema(mod);
424  declareSubSchema(mod);
425 
426  return mod.ptr();
427 }
428 }
429 }
430 }
431 } // namespace lsst::afw::table::<anonymous>
table::Key< int > field
Definition: ApCorrMap.cc:72
PYBIND11_PLUGIN(_cameraPoint)
Definition: cameraPoint.cc:35
int const step
Definition: BoundedField.cc:97
table::Key< std::string > name
Definition: ApCorrMap.cc:71
double const _a
Definition: RandomImage.cc:77
py::object result
Definition: schema.cc:290
afw::table::Schema schema
Definition: GaussianPsf.cc:43