diff --git a/src/pyunit/CMakeLists.txt b/src/pyunit/CMakeLists.txt index c67d1d48..9ef0a302 100644 --- a/src/pyunit/CMakeLists.txt +++ b/src/pyunit/CMakeLists.txt @@ -7,3 +7,5 @@ set(SELF_SRCS pyunit.cpp) xo_pybind11_library(${SELF_LIB} ${PROJECT_NAME}Targets ${SELF_SRCS}) xo_pybind11_dependency(${SELF_LIB} xo_unit) + +# CMakeLists.txt diff --git a/src/pyunit/pyunit.cpp b/src/pyunit/pyunit.cpp index 21a4872c..9384e308 100644 --- a/src/pyunit/pyunit.cpp +++ b/src/pyunit/pyunit.cpp @@ -3,6 +3,7 @@ // note: need pyreflect/ here bc pyreflect.hpp is generated, located in build directory #include "pyunit.hpp" #include "xo/unit/xquantity.hpp" +#include "xo/unit/xquantity_iostream.hpp" #include "xo/pyutil/pyutil.hpp" //#include //#include @@ -11,17 +12,63 @@ namespace xo { namespace py = pybind11; + using Unit = xo::qty::natural_unit; + using XoQuantity = xo::qty::Quantity; namespace qty { PYBIND11_MODULE(PYUNIT_MODULE_NAME(), m) { - py::class_(m, "Quantity") + m.doc() = "pybind11 plugin for xo.unit"; + + py::class_(m, "Unit") .def("__repr__", - [](Quantity & x) + [](Unit & x) + { + /* e.g. "1g" for xo::qty::nu::gram */ + return tostr(1, x.abbrev()); + }) + ; + + py::module unit = m.def_submodule("unit"); + + unit.attr("microgram") = &xo::qty::nu::microgram; + unit.attr("milligram") = &xo::qty::nu::milligram; + unit.attr("gram") = &xo::qty::nu::gram; + unit.attr("kilogram") = &xo::qty::nu::kilogram; + unit.attr("tonne") = &xo::qty::nu::tonne; + + py::module qty = m.def_submodule("qty"); + + qty.def("micrograms", [](double x) { return XoQuantity(x, nu::microgram); }); + qty.def("milligrams", [](double x) { return XoQuantity(x, nu::milligram); }); + qty.def("grams", [](double x) { return XoQuantity(x, nu::gram); }); + qty.def("kilograms", [](double x) { return XoQuantity(x, nu::kilogram); }); + qty.def("tonnes", [](double x) { return XoQuantity(x, nu::tonne); }); + + py::class_(m, "Quantity") + .def(py::init(), + py::arg("scale"), py::arg("unit")) + .def("__mul__", + [](const XoQuantity & x, const XoQuantity & y) + { + return x * y; + }) + .def("__mul__", + [](const XoQuantity & x, double y) + { + return x * y; + }) + .def("__rmul__", + [](const XoQuantity & y, double x) + { + return x * y; + }) + .def("__repr__", + [](const XoQuantity & x) { return tostr(x); }) - py::arg("qty")); + ; } } } /*namespace xo*/