From d39a994b907425c055b16a5e5526d27d48534d2c Mon Sep 17 00:00:00 2001 From: "Ryan M. Richard" Date: Mon, 23 Nov 2026 15:35:46 -0600 Subject: [PATCH] TW now supports UQ types from Python --- .../tensorwrapper/tensor/export_tensor.cpp | 112 ++++++++++++++++++ tests/python/conftest.py | 6 + .../unit_tests/export_test_tensorwrapper.cpp | 36 ++++++ .../unit_tests/tensor/test_tensor_sigma.py | 105 ++++++++++++++++ .../python/unit_tests/test_tensorwrapper.hpp | 8 ++ 5 files changed, 267 insertions(+) create mode 100644 tests/python/unit_tests/tensor/test_tensor_sigma.py diff --git a/cxx/src/tensorwrapper/tensor/export_tensor.cpp b/cxx/src/tensorwrapper/tensor/export_tensor.cpp index 0bb14ed0..bced7160 100644 --- a/cxx/src/tensorwrapper/tensor/export_tensor.cpp +++ b/cxx/src/tensorwrapper/tensor/export_tensor.cpp @@ -95,6 +95,101 @@ Tensor make_tensor_(py::buffer_info& info) { return Tensor(shape, std::move(pBuffer)); } +/** @brief Makes a Tensor whose elements are the objects in @p arr. + * + * @tparam FloatType The type each element of @p arr is cast to. + * + * @param[in] arr A NumPy array of Python objects. + * + * @return A Tensor with the shape and elements of @p arr. + * + * @throw py::type_error if an element of @p arr is not a @p FloatType. + * Strong throw guarantee. + */ +template +Tensor make_tensor_from_objects_(const py::array& arr) { + std::vector dims(arr.shape(), arr.shape() + arr.ndim()); + shape::Smooth shape(dims.begin(), dims.end()); + + std::vector data; + data.reserve(arr.size()); + try { + for(auto x : arr.attr("flat")) data.push_back(x.cast()); + } catch(const py::cast_error&) { + throw py::type_error("The elements of a Tensor must all be the same " + "type!"); + } + auto pBuffer = std::make_unique(std::move(data), shape); + + return Tensor(shape, std::move(pBuffer)); +} + +/** @brief Makes a Tensor from a (possibly nested) sequence of scalars. + * + * The element type of the Tensor is set by the first scalar. At present the + * only scalars supported this way are the sigma types which sigma's Python + * module binds: intervals and triplexes. + * + * @param[in] obj A scalar, a nested sequence of scalars, or a NumPy array of + * Python objects. + * + * @return A Tensor with the shape and elements of @p obj. + * + * @throw std::runtime_error if the scalars are not of a supported type. + * Strong throw guarantee. + * @throw py::type_error if the scalars are not all of the same type. Strong + * throw guarantee. + */ +Tensor make_tensor_from_objects(py::object obj) { +#ifdef ENABLE_SIGMA + auto np = py::module_::import("numpy"); + py::array arr = np.attr("asarray")(obj, py::arg("dtype") = "object"); + if(arr.size() > 0) { + py::object first = arr.attr("flat")[py::int_(0)]; + if(py::isinstance(first)) + return make_tensor_from_objects_(arr); + if(py::isinstance(first)) + return make_tensor_from_objects_(arr); + if(py::isinstance(first)) + return make_tensor_from_objects_(arr); + if(py::isinstance(first)) + return make_tensor_from_objects_(arr); + } +#endif + throw std::runtime_error( + "Incompatible format: expected a double array or sigma scalars!"); +} + +/// Copies the elements of a buffer into a new NumPy array +struct ToNumpyKernel { + template + py::array operator()(std::span buffer) { + using clean_type = std::decay_t; + + if constexpr(std::is_floating_point_v) { + return py::array_t(m_shape, buffer.data()); + } else if constexpr(types::is_interval_v || + types::is_triplex_v) { + // Registers the sigma types with pybind11, so they can be cast + py::module_::import("sigma"); + auto np = py::module_::import("numpy"); + py::tuple shape(m_shape.size()); + for(std::size_t i = 0; i < m_shape.size(); ++i) + shape[i] = m_shape[i]; + py::array rv = np.attr("empty")(shape, py::arg("dtype") = "object"); + auto flat = rv.attr("flat"); + for(std::size_t i = 0; i < buffer.size(); ++i) + flat[py::int_(i)] = py::cast(buffer[i]); + return rv; + } else { + throw std::runtime_error( + "The tensor's element type has no Python binding!"); + } + } + + std::vector m_shape; +}; + } // namespace auto make_buffer_info(buffer::Contiguous& buffer) { @@ -111,6 +206,8 @@ Tensor make_tensor(py::buffer b) { py::buffer_info info = b.request(); if(info.format == py::format_descriptor::format()) return make_tensor_(info); + else if(info.format == "O") // A NumPy array of Python objects + return make_tensor_from_objects(b); else throw std::runtime_error( "Incompatible format: expected a double array!"); @@ -120,10 +217,25 @@ void export_tensor(py_module_reference m) { py_class_type(m, "Tensor", py::buffer_protocol()) .def(py::init<>()) .def(py::init([](py::buffer b) { return make_tensor(b); })) + .def(py::init([](py::object o) { return make_tensor_from_objects(o); })) .def("rank", &Tensor::rank) .def(py::self == py::self) .def(py::self != py::self) .def("__str__", [](Tensor& self) { return self.to_string(); }) + // NumPy falls back to this when the buffer protocol fails, i.e., for + // element types NumPy can not describe, like sigma's intervals + .def( + "__array__", + [](Tensor& self, py::object dtype, py::object) { + auto& buffer = buffer::make_contiguous(self.buffer()); + const auto smooth_shape = buffer.layout().shape().as_smooth(); + ToNumpyKernel kernel; + for(std::size_t i = 0; i < smooth_shape.rank(); ++i) + kernel.m_shape.push_back(smooth_shape.extent(i)); + py::object rv = buffer::visit_contiguous_buffer(kernel, buffer); + return dtype.is_none() ? rv : rv.attr("astype")(dtype); + }, + py::arg("dtype") = py::none(), py::arg("copy") = py::none()) .def_buffer([](Tensor& t) { auto pbuffer = dynamic_cast(&t.buffer()); if(pbuffer == nullptr) diff --git a/tests/python/conftest.py b/tests/python/conftest.py index 9ca83291..ffed5a74 100644 --- a/tests/python/conftest.py +++ b/tests/python/conftest.py @@ -27,6 +27,12 @@ if _build_dir.is_dir(): sys.path.insert(0, str(_build_dir)) +# When built with ENABLE_SIGMA (and Python bindings), sigma's own Python module +# is likewise only in the build directory, under its FetchContent build tree. +_sigma_build_dir = _build_dir / "_deps" / "sigma-build" +if _sigma_build_dir.is_dir(): + sys.path.insert(0, str(_sigma_build_dir)) + @pytest.fixture(scope="session", autouse=True) def _session_runtime_view(): diff --git a/tests/python/unit_tests/export_test_tensorwrapper.cpp b/tests/python/unit_tests/export_test_tensorwrapper.cpp index 72d7cf2e..66e86968 100644 --- a/tests/python/unit_tests/export_test_tensorwrapper.cpp +++ b/tests/python/unit_tests/export_test_tensorwrapper.cpp @@ -24,6 +24,10 @@ PYBIND11_MODULE(py_test_tensorwrapper, m) { get_scalar(m_testing); get_vector(m_testing); get_matrix(m_testing); +#ifdef ENABLE_SIGMA + get_interval_matrix(m_testing); + get_triplex_matrix(m_testing); +#endif } void get_scalar(pybind11::module_& m) { @@ -36,4 +40,36 @@ void get_matrix(pybind11::module_& m) { m.def("get_matrix", []() { return Tensor{{1.0, 2.0}, {3.0, 4.0}}; }); } +#ifdef ENABLE_SIGMA +namespace { + +/// Wraps the four elements of a row-major 2x2 matrix in a Tensor +template +Tensor make_2x2_(std::vector elements) { + shape::Smooth shape{2, 2}; + auto pbuffer = + std::make_unique(std::move(elements), shape); + return Tensor(shape, std::move(pbuffer)); +} + +} // namespace + +void get_interval_matrix(pybind11::module_& m) { + m.def("get_interval_matrix", []() { + using types::idouble; + return make_2x2_({idouble(0.5, 1.5), idouble(1.5, 2.5), + idouble(2.5, 3.5), idouble(3.5, 4.5)}); + }); +} + +void get_triplex_matrix(pybind11::module_& m) { + m.def("get_triplex_matrix", []() { + using types::tpdouble; + return make_2x2_( + {tpdouble(0.5, 1.0, 1.5), tpdouble(1.5, 2.0, 2.5), + tpdouble(2.5, 3.0, 3.5), tpdouble(3.5, 4.0, 4.5)}); + }); +} +#endif + } // namespace tensorwrapper::testing diff --git a/tests/python/unit_tests/tensor/test_tensor_sigma.py b/tests/python/unit_tests/tensor/test_tensor_sigma.py new file mode 100644 index 00000000..5b7da0cd --- /dev/null +++ b/tests/python/unit_tests/tensor/test_tensor_sigma.py @@ -0,0 +1,105 @@ +# Copyright 2026 NWChemEx-Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +import numpy as np +import py_test_tensorwrapper.testing as testing +import tensorwrapper + +try: + import sigma +except ImportError: + sigma = None + +# The fixtures only exist when TensorWrapper was built with ENABLE_SIGMA +has_sigma = sigma is not None and hasattr(testing, "get_interval_matrix") + + +@unittest.skipUnless(has_sigma, "TensorWrapper was not built with sigma") +class TestTensorSigma(unittest.TestCase): + def check_round_trip(self, t, corr): + """Asserts that np.array(t) is an object array equal to corr""" + arr = np.array(t) + self.assertEqual(arr.dtype, object) + self.assertEqual(arr.shape, np.shape(corr)) + for x, y in zip(arr.flat, np.asarray(corr, dtype=object).flat): + self.assertIs(type(x), type(y)) + self.assertEqual(x, y) + + def test_interval_from_list(self): + t = tensorwrapper.Tensor(self.intervals) + self.assertEqual(t.rank(), 2) + self.assertTrue(t == testing.get_interval_matrix()) + self.check_round_trip(t, self.intervals) + + def test_interval_from_object_array(self): + t = tensorwrapper.Tensor(np.array(self.intervals, dtype=object)) + self.assertTrue(t == testing.get_interval_matrix()) + + def test_interval_scalar(self): + i = sigma.IDouble(1.0, 2.0) + t = tensorwrapper.Tensor(i) + self.assertEqual(t.rank(), 0) + self.check_round_trip(t, i) + + def test_interval_from_cpp(self): + self.check_round_trip(testing.get_interval_matrix(), self.intervals) + + def test_triplex_from_list(self): + t = tensorwrapper.Tensor(self.triplexes) + self.assertEqual(t.rank(), 2) + self.assertTrue(t == testing.get_triplex_matrix()) + self.check_round_trip(t, self.triplexes) + + def test_triplex_from_object_array(self): + t = tensorwrapper.Tensor(np.array(self.triplexes, dtype=object)) + self.assertTrue(t == testing.get_triplex_matrix()) + + def test_triplex_scalar(self): + tp = sigma.TPDouble(0.9, 1.0, 1.1) + t = tensorwrapper.Tensor(tp) + self.assertEqual(t.rank(), 0) + self.check_round_trip(t, tp) + + def test_triplex_from_cpp(self): + t = testing.get_triplex_matrix() + self.check_round_trip(t, self.triplexes) + nominals = [x.nominal() for x in np.array(t).flat] + self.assertEqual(nominals, [1.0, 2.0, 3.0, 4.0]) + + def test_float_types(self): + intervals = [sigma.IFloat(1.0, 2.0), sigma.IFloat(3.0, 4.0)] + self.check_round_trip(tensorwrapper.Tensor(intervals), intervals) + triplexes = [sigma.TPFloat(0.5, 1.0, 1.5), sigma.TPFloat(2.0)] + self.check_round_trip(tensorwrapper.Tensor(triplexes), triplexes) + + def test_mixed_types_raise(self): + mixed = [sigma.IDouble(1.0, 2.0), sigma.TPDouble(1.0)] + with self.assertRaises(TypeError): + tensorwrapper.Tensor(mixed) + + def test_unsupported_objects_raise(self): + with self.assertRaises(RuntimeError): + tensorwrapper.Tensor(["not", "a", "number"]) + + def setUp(self): + self.intervals = [ + [sigma.IDouble(0.5, 1.5), sigma.IDouble(1.5, 2.5)], + [sigma.IDouble(2.5, 3.5), sigma.IDouble(3.5, 4.5)], + ] + self.triplexes = [ + [sigma.TPDouble(0.5, 1.0, 1.5), sigma.TPDouble(1.5, 2.0, 2.5)], + [sigma.TPDouble(2.5, 3.0, 3.5), sigma.TPDouble(3.5, 4.0, 4.5)], + ] diff --git a/tests/python/unit_tests/test_tensorwrapper.hpp b/tests/python/unit_tests/test_tensorwrapper.hpp index 0ea98ebd..a62ed331 100644 --- a/tests/python/unit_tests/test_tensorwrapper.hpp +++ b/tests/python/unit_tests/test_tensorwrapper.hpp @@ -23,4 +23,12 @@ void get_scalar(pybind11::module_& m); void get_vector(pybind11::module_& m); void get_matrix(pybind11::module_& m); +#ifdef ENABLE_SIGMA +/// Exposes a C++-built 2x2 tensor of types::idouble to Python +void get_interval_matrix(pybind11::module_& m); + +/// Exposes a C++-built 2x2 tensor of types::tpdouble to Python +void get_triplex_matrix(pybind11::module_& m); +#endif + } // namespace tensorwrapper::testing