23 #include "pybind11/pybind11.h"
24 #include "pybind11/stl.h"
28 #include "numpy/arrayobject.h"
29 #include "ndarray/pybind11.h"
36 namespace py = pybind11;
37 using namespace pybind11::literals;
45 using PySchema = py::class_<Schema>;
47 using PySubSchema = py::class_<SubSchema>;
50 using PyFieldBase = py::class_<FieldBase<T>>;
53 using PyKeyBase = py::class_<KeyBase<T>>;
56 using PyField = py::class_<Field<T>, FieldBase<T>>;
59 using PyKey = py::class_<Key<T>, KeyBase<T>, FieldBase<T>>;
62 using PySchemaItem = py::class_<SchemaItem<T>>;
65 std::string streamStr(T
const &
self) {
66 std::ostringstream os;
74 void declareFieldBaseSpecializations(PyFieldBase<T> &
cls) {
75 cls.def(py::init<>());
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);
85 void declareFieldBaseSpecializations(PyFieldBase<std::string> &cls) {
86 cls.def(py::init<int>(),
"size"_a = -1);
87 cls.def(
"getSize", &FieldBase<std::string>::getSize);
93 void declareKeyBaseSpecializations(PyKeyBase<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();
104 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
105 "Step for array Key indexing must be 1.");
107 return py::cast(
self.slice(start, stop));
109 return py::cast(
self[py::cast<int>(index)]);
112 cls.def(
"slice", &KeyBase<Array<T>>::slice);
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);
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> {
130 auto setter = [](Key<Array<U>>
const &
self, BaseRecord &record, py::object
const &value) {
131 if (
self.getSize() == 0) {
134 record.set(
self, py::cast<ndarray::Array<U, 1, 1>>(value));
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()) {
143 pex::exceptions::LengthError,
144 (boost::format(
"Array sizes do not agree: %s != %s") % v.size() % ref.size()).str());
150 cls.def(
"get", getter);
151 cls.def(
"set", setter);
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(); });
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);
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 {
173 for (
int i = 0; i <
self.getSize(); ++i) {
174 result.append(py::cast(i));
176 return py::tuple(result);
178 cls.def_property_readonly(
"subkeys", [](Key<Array<U>>
const &
self) -> py::object {
180 for (
int i = 0; i <
self.getSize(); ++i) {
181 result.append(py::cast(
self[i]));
183 return py::tuple(result);
188 template <
typename T>
189 void declareSchemaType(py::module &mod) {
190 std::string suffix = FieldBase<T>::getTypeString();
191 py::str pySuffix(suffix);
193 py::object astropyUnit = py::module::import(
"astropy.units").attr(
"Unit");
196 PyFieldBase<T> clsFieldBase(mod, (
"FieldBase" + suffix).c_str());
197 clsFieldBase.def_static(
"getTypeString", &FieldBase<T>::getTypeString);
198 declareFieldBaseSpecializations(clsFieldBase);
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);
206 PyField<T> clsField(mod, (
"Field" + suffix).c_str());
207 mod.attr(
"_Field")[pySuffix] = clsField;
208 clsField.def(
"__init__",
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);
217 int s = py::cast<int>(size);
218 new (&
self) Field<T>(name, doc, u, s);
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);
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>>);
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; },
238 clsKey.def(
"__ne__", [](Key<T>
const &
self, Key<T>
const &other) ->
bool {
return self != other; },
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>>);
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);
259 PySchemaItem<T> clsSchemaItem(mod, (
"SchemaItem" + suffix).c_str());
260 mod.attr(
"_SchemaItem")[pySuffix] = clsSchemaItem;
261 clsSchemaItem.def_readonly(
"key", &SchemaItem<T>::key);
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 {
267 return self.attr(
"key");
268 }
else if (index == 1) {
269 return self.attr(
"field");
273 throw py::index_error(
"Index to SchemaItem must be 0 or 1.");
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);
284 struct MakePythonSchemaItem {
285 template <
typename T>
286 void operator()(SchemaItem<T>
const &item) {
287 result = py::cast(item);
293 void declareSchema(py::module &mod) {
294 py::module::import(
"lsst.afw.table.aliasMap");
296 PySchema
cls(mod,
"Schema");
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));
307 cls.attr(
"VERSION") = py::cast(
int(Schema::VERSION));
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; },
314 cls.def(
"__ne__", [](Schema
const &
self, Schema
const &other) {
return self != other; },
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 {
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);
330 return key.attr(
"_findIn")(
self);
331 }
catch (pex::exceptions::NotFoundError &err) {
333 PyErr_SetString(PyExc_KeyError, err.what());
334 throw py::error_already_set();
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) {
347 self.attr(
"find")(key);
348 }
catch (py::error_already_set &err) {
354 cls.def_static(
"readFits", (Schema(*)(std::string
const &,
int)) & Schema::readFits,
"filename"_a,
356 cls.def_static(
"readFits", (Schema(*)(fits::MemFileManager &,
int)) & Schema::readFits,
"manager"_a,
359 cls.def(
"join", (std::string (Schema::*)(std::string
const &, std::string
const &)
const) & Schema::join,
362 (std::string (Schema::*)(std::string
const &, std::string
const &, std::string
const &)
const) &
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) &
368 "a"_a,
"b"_a,
"c"_a,
"d"_a);
369 cls.def(
"__str__", &streamStr<Schema>);
370 cls.def(
"__repr__", &streamStr<Schema>);
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;
380 return func.result.attr(
"key");
382 cls.def(
"asField", [](SubSchema
const &
self) -> py::object {
383 MakePythonSchemaItem func;
385 return func.result.attr(
"field");
387 cls.def(
"find", [](SubSchema
const &
self, std::string
const &name) -> py::object {
388 MakePythonSchemaItem func;
389 self.findAndApply(name, func);
392 cls.def(
"__getitem__", [](SubSchema &
self, std::string
const &name) {
return self[
name]; });
396 py::module mod(
"schema");
398 if (_import_array() < 0) {
399 PyErr_SetString(PyExc_ImportError,
"numpy.core.multiarray failed to import");
406 mod.attr(
"_Field") = py::dict();
407 mod.attr(
"_Key") = py::dict();
408 mod.attr(
"_SchemaItem") = py::dict();
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);
424 declareSubSchema(mod);
PYBIND11_PLUGIN(_cameraPoint)
table::Key< std::string > name
afw::table::Schema schema