Skip to content

Commit 39f5a77

Browse files
committed
Bug fix for python bindings for non-contiguous input vectors
When a non-contiguous numpy vector (e.g. a sliced view into a numpy array) is used as an input argument to a bound function, the underlying C++ object does not properly account for strides in the input array. Use the pybind11 numpy interface to handle this properly, while still allowing type conversion.
1 parent 31c17e8 commit 39f5a77

File tree

3 files changed

+15
-9
lines changed

3 files changed

+15
-9
lines changed

core/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,7 @@ add_spt3g_test(timestrings)
136136
add_spt3g_test(testcomplexconv)
137137
add_spt3g_test(droporphanmetadata)
138138
add_spt3g_test(networktest SLOWTEST)
139+
add_spt3g_test(non_contiguous_vectors)
139140
add_spt3g_test(non_double_timestreams)
140141
add_spt3g_test(endprocessing)
141142
add_spt3g_test(lazyreader)

core/src/G3Vector.cxx

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -80,14 +80,6 @@ auto vector_from_python(const py::array_t<T> &buf) {
8080
if (buf.ndim() != 1)
8181
throw py::type_error("Only valid 1D buffers can be copied to a vector");
8282

83-
return std::make_shared<V>(buf.data(), buf.data() + buf.size());
84-
}
85-
86-
template <typename V>
87-
auto time_vector_from_python(const py::array_t<G3TimeStamp> &buf) {
88-
if (buf.ndim() != 1)
89-
throw py::type_error("Only valid 1D buffers can be copied to a vector");
90-
9183
auto rbuf = buf.template unchecked<1>();
9284
auto vec = std::make_shared<V>(rbuf.shape(0));
9385

@@ -124,7 +116,7 @@ struct vector_buffer<G3Time, V, C, Args...> {
124116
static void impl(C &cls) {
125117
cls.def_buffer(&time_vector_buffer_info<V>);
126118
cls.def(py::init([](const py::array &v) {
127-
return time_vector_from_python<V>(v);
119+
return vector_from_python<G3TimeStamp, V>(v);
128120
}), "Constructor from numpy array");
129121
py::implicitly_convertible<py::buffer, V>();
130122
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from spt3g import core
2+
import numpy as np
3+
4+
data = np.random.randn(10, 10)
5+
6+
# check that vectors created from non-contiguous input arrays
7+
# store the correct elements
8+
9+
vec = core.G3VectorDouble(data[:, 0])
10+
np.testing.assert_array_equal(np.asarray(vec), data[:, 0])
11+
12+
vec = core.G3VectorDouble(data[0, :])
13+
np.testing.assert_array_equal(np.asarray(vec), data[0, :])

0 commit comments

Comments
 (0)