Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 112 additions & 0 deletions cxx/src/tensorwrapper/tensor/export_tensor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<typename FloatType>
Tensor make_tensor_from_objects_(const py::array& arr) {
std::vector<std::size_t> dims(arr.shape(), arr.shape() + arr.ndim());
shape::Smooth shape(dims.begin(), dims.end());

std::vector<FloatType> data;
data.reserve(arr.size());
try {
for(auto x : arr.attr("flat")) data.push_back(x.cast<FloatType>());
} 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<buffer::Contiguous>(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<types::idouble>(first))
return make_tensor_from_objects_<types::idouble>(arr);
if(py::isinstance<types::ifloat>(first))
return make_tensor_from_objects_<types::ifloat>(arr);
if(py::isinstance<types::tpdouble>(first))
return make_tensor_from_objects_<types::tpdouble>(arr);
if(py::isinstance<types::tpfloat>(first))
return make_tensor_from_objects_<types::tpfloat>(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<concepts::FloatingPoint FloatType>
py::array operator()(std::span<FloatType> buffer) {
using clean_type = std::decay_t<FloatType>;

if constexpr(std::is_floating_point_v<clean_type>) {
return py::array_t<clean_type>(m_shape, buffer.data());
} else if constexpr(types::is_interval_v<clean_type> ||
types::is_triplex_v<clean_type>) {
// 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<std::size_t> m_shape;
};

} // namespace

auto make_buffer_info(buffer::Contiguous& buffer) {
Expand All @@ -111,6 +206,8 @@ Tensor make_tensor(py::buffer b) {
py::buffer_info info = b.request();
if(info.format == py::format_descriptor<double>::format())
return make_tensor_<double>(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!");
Expand All @@ -120,10 +217,25 @@ void export_tensor(py_module_reference m) {
py_class_type<Tensor>(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<buffer::Contiguous*>(&t.buffer());
if(pbuffer == nullptr)
Expand Down
6 changes: 6 additions & 0 deletions tests/python/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down
36 changes: 36 additions & 0 deletions tests/python/unit_tests/export_test_tensorwrapper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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<typename FloatType>
Tensor make_2x2_(std::vector<FloatType> elements) {
shape::Smooth shape{2, 2};
auto pbuffer =
std::make_unique<buffer::Contiguous>(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>({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>(
{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
105 changes: 105 additions & 0 deletions tests/python/unit_tests/tensor/test_tensor_sigma.py
Original file line number Diff line number Diff line change
@@ -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)],
]
8 changes: 8 additions & 0 deletions tests/python/unit_tests/test_tensorwrapper.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading