Skip to content
Merged
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
26 changes: 25 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ nwx_cxx_api_docs("${project_inc_dir}" "${project_src_dir}")
### Options ###
cmaize_option_list(
BUILD_TESTING OFF "Should we build the tests?"
BUILD_PYBIND11_PYBINDINGS OFF "Should we build Python3 bindings?"
BUILD_PYBIND11_PYBINDINGS ON "Should we build Python3 bindings?"
ENABLE_SIGMA OFF "Should we enable Sigma for uncertainty tracking?"
)

Expand Down Expand Up @@ -73,9 +73,19 @@ cmaize_add_library(
)
target_include_directories(${PROJECT_NAME} PUBLIC "${CMAKE_CURRENT_BINARY_DIR}")

include(nwx_pybind11)
nwx_add_pybind11_module(
${PROJECT_NAME}
SOURCE_DIR "${CMAKE_CURRENT_LIST_DIR}/src/python"
DEPENDS "${PROJECT_NAME}"
)


if("${BUILD_TESTING}")
set(cxx_test_dir "${CMAKE_CURRENT_LIST_DIR}/tests/cxx")
set(cxx_unit_test_dir "${cxx_test_dir}/unit_tests/${PROJECT_NAME}")
set(python_test_dir "${CMAKE_CURRENT_LIST_DIR}/tests/python")
set(python_unit_test_dir "${python_test_dir}/unit_tests")

include(get_catch2)

Expand All @@ -85,6 +95,20 @@ if("${BUILD_TESTING}")
INCLUDE_DIRS "${project_src_dir}"
DEPENDS Catch2 ${PROJECT_NAME}
)

nwx_add_pybind11_module(
py_test_${PROJECT_NAME}
INSTALL OFF
SOURCE_DIR "${python_unit_test_dir}"
INCLUDE_DIRS "${project_inc_dir}"
DEPENDS ${PROJECT_NAME}
)

nwx_pybind11_tests(
py_${PROJECT_NAME} ${python_unit_test_dir}/test_tensorwrapper.py
SUBMODULES parallelzone pluginplay
DEPENDS py_test_${PROJECT_NAME}
)
endif()

cmaize_add_package(${PROJECT_NAME} NAMESPACE nwx::)
Expand Down
36 changes: 36 additions & 0 deletions src/python/export_tensorwrapper.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Copyright 2025 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.
*/

#pragma once
#include <pybind11/pybind11.h>

namespace tensorwrapper {

// -----------------------------------------------------------------------------
// -- Type factorization used throughout the Python component
// -----------------------------------------------------------------------------

/// Type of a C++ handle to a Python module
using py_module_type = pybind11::module_;

/// Type of a reference to an object of type py_module_type
using py_module_reference = py_module_type&;

/// Type of Python object binding for a C++ class of type @p T
template<typename... T>
using py_class_type = pybind11::class_<T...>;

} // namespace tensorwrapper
29 changes: 29 additions & 0 deletions src/python/module.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* Copyright 2023 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.
*/

#include "tensor/export_tensor.hpp"
#include <pybind11/pybind11.h>
#include <tensorwrapper/tensorwrapper.hpp>

namespace tensorwrapper {

PYBIND11_MODULE(tensorwrapper, m) {
m.doc() = "PyTensorWrapper : Python bindings for TensorWrapper";

export_tensor(m);
}

} // namespace tensorwrapper
64 changes: 64 additions & 0 deletions src/python/tensor/export_tensor.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* Copyright 2025 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.
*/

#include "export_tensor.hpp"
#include <pybind11/numpy.h>
#include <pybind11/operators.h>
#include <tensorwrapper/tensorwrapper.hpp>

namespace tensorwrapper {

using float_type = double;
using buffer_type = buffer::Contiguous<float_type>;

template<typename FloatType>
auto make_buffer_info(buffer::Contiguous<FloatType>& buffer) {
using size_type = std::size_t;
constexpr auto nbytes = sizeof(FloatType);
const auto desc = pybind11::format_descriptor<FloatType>::format();
const auto rank = buffer.rank();

const auto smooth_shape = buffer.layout().shape().as_smooth();

std::vector<size_type> shape(rank);
std::vector<size_type> strides(rank);
for(size_type rank_i = 0; rank_i < rank; ++rank_i) {
shape[rank_i] = smooth_shape.extent(rank_i);
size_type stride_i = 1;
for(size_type mode_i = rank_i + 1; mode_i < rank; ++mode_i)
stride_i *= smooth_shape.extent(mode_i);
strides[rank_i] = stride_i * nbytes;
}
return pybind11::buffer_info(buffer.data(), nbytes, desc, rank, shape,
strides);
}

void export_tensor(py_module_reference m) {
py_class_type<Tensor>(m, "Tensor", pybind11::buffer_protocol())
.def(pybind11::init<>())
.def("rank", &Tensor::rank)
.def(pybind11::self == pybind11::self)
.def(pybind11::self != pybind11::self)
.def("__str__", [](Tensor& self) { return self.to_string(); })
.def_buffer([](Tensor& t) {
auto pbuffer = dynamic_cast<buffer_type*>(&t.buffer());
if(pbuffer == nullptr)
throw std::runtime_error("Expected buffer to hold doubles");
return make_buffer_info(*pbuffer);
});
}

} // namespace tensorwrapper
24 changes: 24 additions & 0 deletions src/python/tensor/export_tensor.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* Copyright 2025 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.
*/

#pragma once
#include "../export_tensorwrapper.hpp"

namespace tensorwrapper {

void export_tensor(py_module_reference m);

}
13 changes: 13 additions & 0 deletions tests/python/unit_tests/tensor/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Copyright 2025 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.
43 changes: 43 additions & 0 deletions tests/python/unit_tests/tensor/test_tensor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Copyright 2025 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 tensorwrapper
import numpy as np
import py_test_tensorwrapper.testing as testing
import unittest


class TestTensor(unittest.TestCase):

def test_ctor(self):
self.assertEqual(self.scalar.rank(), 0)
self.assertEqual(self.vector.rank(), 1)
self.assertEqual(self.matrix.rank(), 2)

def test_numpy(self):
np_scalar = np.array(self.scalar)
np_vector = np.array(self.vector)
np_matrix = np.array(self.matrix)

scalar_corr = np.array(42)
vector_corr = np.array([0.0, 1.0, 2.0, 3.0, 4.0])
matrix_corr = np.array([[1.0, 2.0], [3.0, 4.0]])
self.assertFalse((np_scalar - scalar_corr).any())
self.assertFalse((np_vector - vector_corr).any())
self.assertFalse((np_matrix - matrix_corr).any())

def setUp(self):
self.scalar = testing.get_scalar()
self.vector = testing.get_vector()
self.matrix = testing.get_matrix()
39 changes: 39 additions & 0 deletions tests/python/unit_tests/test_tensorwrapper.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Copyright 2025 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.
*/

#include "test_tensorwrapper.hpp"
#include <tensorwrapper/tensorwrapper.hpp>

namespace tensorwrapper::testing {

PYBIND11_MODULE(py_test_tensorwrapper, m) {
auto m_testing = m.def_submodule("testing");
get_scalar(m_testing);
get_vector(m_testing);
get_matrix(m_testing);
}

void get_scalar(pybind11::module_& m) {
m.def("get_scalar", []() { return Tensor(42.0); });
}
void get_vector(pybind11::module_& m) {
m.def("get_vector", []() { return Tensor{0.0, 1.0, 2.0, 3.0, 4.0}; });
}
void get_matrix(pybind11::module_& m) {
m.def("get_matrix", []() { return Tensor{{1.0, 2.0}, {3.0, 4.0}}; });
}

} // namespace tensorwrapper::testing
26 changes: 26 additions & 0 deletions tests/python/unit_tests/test_tensorwrapper.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* Copyright 2025 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.
*/

#pragma once
#include <pybind11/pybind11.h>

namespace tensorwrapper::testing {

void get_scalar(pybind11::module_& m);
void get_vector(pybind11::module_& m);
void get_matrix(pybind11::module_& m);

} // namespace tensorwrapper::testing
31 changes: 31 additions & 0 deletions tests/python/unit_tests/test_tensorwrapper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#
# Copyright 2023 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 os
import parallelzone as pz
import sys
import unittest

if __name__ == '__main__':
rv = pz.runtime.RuntimeView()

my_dir = os.path.dirname(os.path.realpath(__file__))

loader = unittest.TestLoader()
tests = loader.discover(my_dir)
testrunner = unittest.runner.TextTestRunner()
ret = not testrunner.run(tests).wasSuccessful()
sys.exit(ret)