Skip to content

Commit 0588ed0

Browse files
committed
Add: Small Matrix (6x6, F)
Add the implementation for the new small matrix (and small vector) types and their operators. Specialize for now for the most common type we need in accelerator physics, a 6x6, F-ordered, 1-indexed matrix.
1 parent f3de107 commit 0588ed0

File tree

9 files changed

+527
-5
lines changed

9 files changed

+527
-5
lines changed

docs/source/usage/api.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,13 @@ Data Containers
174174
:members:
175175
:undoc-members:
176176

177+
Small Matrices and Vectors
178+
""""""""""""""""""""""""""
179+
180+
.. autoclass:: amrex.space3d.SmallMatrix_6x6_F_SI1_double
181+
:members:
182+
:undoc-members:
183+
177184
Utility
178185
"""""""
179186

src/Base/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ foreach(D IN LISTS AMReX_SPACEDIM)
2525
IndexType.cpp
2626
IntVect.cpp
2727
RealVect.cpp
28+
SmallMatrix.cpp
2829
MultiFab.cpp
2930
ParallelDescriptor.cpp
3031
ParmParse.cpp

src/Base/SmallMatrix.H

Lines changed: 319 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,319 @@
1+
/* Copyright 2021-2025 The AMReX Community
2+
*
3+
* Authors: Axel Huebl
4+
* License: BSD-3-Clause-LBNL
5+
*/
6+
#pragma once
7+
8+
#include "pyAMReX.H"
9+
10+
#include <AMReX_SmallMatrix.H>
11+
12+
#include <complex>
13+
#include <cstdint>
14+
#include <iterator>
15+
#include <sstream>
16+
#include <type_traits>
17+
#include <vector>
18+
19+
20+
namespace
21+
{
22+
// helper type traits
23+
template <typename T>
24+
struct get_value_type { using value_type = T; };
25+
template <typename T>
26+
struct get_value_type<std::complex<T>> { using value_type = T; };
27+
template <typename T>
28+
using get_value_type_t = typename get_value_type<T>::value_type;
29+
30+
// helper to check if Array4<T> is of constant value type T
31+
template <typename T>
32+
constexpr bool is_not_const ()
33+
{
34+
return std::is_same_v<
35+
std::remove_cv_t<
36+
T
37+
>,
38+
T
39+
> &&
40+
std::is_same_v<
41+
std::remove_cv_t<
42+
get_value_type_t<T>
43+
>,
44+
get_value_type_t<T>
45+
>;
46+
}
47+
}
48+
49+
namespace pyAMReX
50+
{
51+
using namespace amrex;
52+
53+
/** CPU: __array_interface__ v3
54+
*
55+
* https://numpy.org/doc/stable/reference/arrays.interface.html
56+
*/
57+
template<
58+
class T,
59+
int NRows,
60+
int NCols,
61+
Order ORDER = Order::F,
62+
int StartIndex = 0
63+
>
64+
py::dict
65+
array_interface (SmallMatrix<T, NRows, NCols, ORDER, StartIndex> const & m)
66+
{
67+
auto d = py::dict();
68+
// provide C index order for shape and strides
69+
auto shape = m.ordering == Order::F ? py::make_tuple(
70+
py::ssize_t(NRows),
71+
py::ssize_t(NCols) // fastest varying index
72+
) : py::make_tuple(
73+
py::ssize_t(NCols),
74+
py::ssize_t(NRows) // fastest varying index
75+
);
76+
// buffer protocol strides are in bytes
77+
auto const strides = m.ordering == Order::F ? py::make_tuple(
78+
py::ssize_t(sizeof(T) * NCols),
79+
py::ssize_t(sizeof(T)) // fastest varying index
80+
) : py::make_tuple(
81+
py::ssize_t(sizeof(T) * NRows),
82+
py::ssize_t(sizeof(T)) // fastest varying index
83+
);
84+
bool const read_only = false; // note: we could decide on is_not_const,
85+
// but many libs, e.g. PyTorch, do not
86+
// support read-only and will raise
87+
// warnings, casting to read-write
88+
d["data"] = py::make_tuple(std::intptr_t(&m.template get<0>()), read_only);
89+
// note: if we want to keep the same global indexing with non-zero
90+
// box small_end as in AMReX, then we can explore playing with
91+
// this offset as well
92+
//d["offset"] = 0; // default
93+
//d["mask"] = py::none(); // default
94+
95+
d["shape"] = shape;
96+
// we could also set this after checking the strides are C-style contiguous:
97+
//if (is_contiguous<T>(shape, strides))
98+
// d["strides"] = py::none(); // C-style contiguous
99+
//else
100+
d["strides"] = strides;
101+
102+
// type description
103+
// for more complicated types, e.g., tuples/structs
104+
//d["descr"] = ...;
105+
// we currently only need this
106+
using T_no_cv = std::remove_cv_t<T>;
107+
d["typestr"] = py::format_descriptor<T_no_cv>::format();
108+
109+
d["version"] = 3;
110+
return d;
111+
}
112+
113+
template<
114+
class T,
115+
int NRows,
116+
int NCols,
117+
Order ORDER = Order::F,
118+
int StartIndex = 0
119+
>
120+
void make_SmallMatrix(py::module &m, std::string typestr)
121+
{
122+
using namespace amrex;
123+
124+
using T_no_cv = std::remove_cv_t<T>;
125+
126+
// dispatch simpler via: py::format_descriptor<T>::format() naming
127+
// but note the _const suffix that might be needed
128+
auto const sm_name = std::string("SmallMatrix_")
129+
.append(std::to_string(NRows)).append("x").append(std::to_string(NCols))
130+
.append("_").append(ORDER == Order::F ? "F" : "C")
131+
.append("_SI").append(std::to_string(StartIndex))
132+
.append("_").append(typestr);
133+
using SM = SmallMatrix<T, NRows, NCols, ORDER, StartIndex>;
134+
py::class_< SM > py_sm(m, sm_name.c_str());
135+
py_sm
136+
.def("__repr__",
137+
[sm_name](SM const &) {
138+
return "<amrex." + sm_name + ">";
139+
}
140+
)
141+
.def("__str__",
142+
[sm_name](SM const & sm) {
143+
std::stringstream ss;
144+
ss << sm;
145+
return ss.str();
146+
}
147+
)
148+
149+
.def_property_readonly("size", [](SM const &){ return SM::row_size * SM::column_size; })
150+
.def_property_readonly("row_size", [](SM const &){ return SM::row_size; })
151+
.def_property_readonly("column_size", [](SM const &){ return SM::column_size; })
152+
.def_property_readonly("order", [](SM const &){ return SM::ordering == Order::F ? "F" : "C"; }) // NumPy name
153+
.def_property_readonly("starting_index", [](SM const &){ return SM::starting_index; })
154+
155+
.def_static("zero", [](){ return SM::Zero(); })
156+
157+
.def(py::init([](){ return SM{}; })) // zero-init
158+
.def(py::init<SM const &>()) // copy-init
159+
160+
/* init from a numpy or other buffer protocol array: copy
161+
*/
162+
.def(py::init([](py::array_t<T> & arr)
163+
{
164+
py::buffer_info buf = arr.request();
165+
166+
constexpr bool is_vector = SM::column_size == 1 || SM::row_size == 1;
167+
constexpr int sm_dim = is_vector ? 1 : 2;
168+
if (buf.ndim != sm_dim)
169+
throw std::runtime_error("The SmallMatrix to create is " + std::to_string(sm_dim) +
170+
"D, but the passed array is " + std::to_string(buf.ndim) + "D.");
171+
if (buf.size != SM::column_size * SM::row_size)
172+
throw std::runtime_error("Array size mismatch: Expected " + std::to_string(SM::column_size * SM::row_size) +
173+
" elements, but passed " + std::to_string(buf.size) + " elements.");
174+
175+
if (buf.format != py::format_descriptor<T_no_cv>::format())
176+
throw std::runtime_error("Incompatible format: expected '" +
177+
py::format_descriptor<T_no_cv>::format() +
178+
"' and received '" + buf.format + "'!");
179+
180+
// TODO: check that strides are either exact or None in buf
181+
// TODO: transpose if SM order is not C?
182+
183+
auto sm = std::make_unique< SM >();
184+
auto * src = static_cast<T*>(buf.ptr);
185+
std::copy(src, src + buf.size, &sm->template get<0>());
186+
187+
// todo: we could check and store here if the array buffer we got is read-only
188+
189+
return sm;
190+
}))
191+
192+
/* init from __cuda_array_interface__: device-to-host copy
193+
* TODO
194+
*/
195+
196+
197+
// CPU: __array_interface__ v3
198+
// https://numpy.org/doc/stable/reference/arrays.interface.html
199+
.def_property_readonly("__array_interface__", [](SM const & sm) {
200+
return pyAMReX::array_interface(sm);
201+
})
202+
203+
// CPU: __array_function__ interface (TODO)
204+
//
205+
// NEP 18 — A dispatch mechanism for NumPy's high level array functions.
206+
// https://numpy.org/neps/nep-0018-array-function-protocol.html
207+
// This enables code using NumPy to be directly operated on Array4 arrays.
208+
// __array_function__ feature requires NumPy 1.16 or later.
209+
210+
211+
// Nvidia GPUs: __cuda_array_interface__ v3
212+
// https://numba.readthedocs.io/en/latest/cuda/cuda_array_interface.html
213+
.def_property_readonly("__cuda_array_interface__", [](SM const & sm) {
214+
auto d = pyAMReX::array_interface(sm);
215+
216+
// data:
217+
// Because the user of the interface may or may not be in the same context, the most common case is to use cuPointerGetAttribute with CU_POINTER_ATTRIBUTE_DEVICE_POINTER in the CUDA driver API (or the equivalent CUDA Runtime API) to retrieve a device pointer that is usable in the currently active context.
218+
// TODO For zero-size arrays, use 0 here.
219+
220+
// None or integer
221+
// An optional stream upon which synchronization must take place at the point of consumption, either by synchronizing on the stream or enqueuing operations on the data on the given stream. Integer values in this entry are as follows:
222+
// 0: This is disallowed as it would be ambiguous between None and the default stream, and also between the legacy and per-thread default streams. Any use case where 0 might be given should either use None, 1, or 2 instead for clarity.
223+
// 1: The legacy default stream.
224+
// 2: The per-thread default stream.
225+
// Any other integer: a cudaStream_t represented as a Python integer.
226+
// When None, no synchronization is required.
227+
d["stream"] = py::none();
228+
229+
d["version"] = 3;
230+
return d;
231+
})
232+
233+
234+
// TODO: __dlpack__ __dlpack_device__
235+
// DLPack protocol (CPU, NVIDIA GPU, AMD GPU, Intel GPU, etc.)
236+
// https://dmlc.github.io/dlpack/latest/
237+
// https://data-apis.org/array-api/latest/design_topics/data_interchange.html
238+
// https://github.com/data-apis/consortium-feedback/issues/1
239+
// https://github.com/dmlc/dlpack/blob/master/include/dlpack/dlpack.h
240+
// https://docs.cupy.dev/en/stable/user_guide/interoperability.html#dlpack-data-exchange-protocol
241+
242+
.def("dot", &SM::dot)
243+
.def("prod", &SM::product) // NumPy name
244+
.def("set_val", &SM::setVal)
245+
.def("sum", &SM::sum)
246+
.def_property_readonly("T", &SM::transpose) // NumPy name
247+
248+
// operators
249+
.def(py::self + py::self)
250+
.def(py::self - py::self)
251+
.def(py::self * amrex::Real())
252+
.def(amrex::Real() * py::self)
253+
.def(-py::self)
254+
255+
// getter
256+
.def("__getitem__", [](SM & sm, std::array<int, 2> const & key){
257+
if (key[0] < SM::starting_index || key[0] >= SM::row_size + SM::starting_index ||
258+
key[1] < SM::starting_index || key[1] >= SM::column_size + SM::starting_index)
259+
throw std::runtime_error(
260+
"Index out of bounds: [" +
261+
std::to_string(key[0]) + ", " +
262+
std::to_string(key[1]) + "]");
263+
return sm(key[0], key[1]);
264+
})
265+
;
266+
// setter
267+
if constexpr (is_not_const<T>())
268+
{
269+
py_sm
270+
.def("__setitem__", [](SM & sm, std::array<int, 2> const & key, T const value){
271+
if (key[0] < SM::starting_index || key[0] >= SM::row_size + SM::starting_index ||
272+
key[1] < SM::starting_index || key[1] >= SM::column_size + SM::starting_index)
273+
throw std::runtime_error(
274+
"Index out of bounds: [" +
275+
std::to_string(key[0]) + ", " +
276+
std::to_string(key[1]) + "]");
277+
sm(key[0], key[1]) = value;
278+
})
279+
;
280+
}
281+
282+
// square matrix
283+
if constexpr (NRows == NCols)
284+
{
285+
py_sm
286+
.def_static("identity", [](){ return SM::Identity(); })
287+
.def("trace", &SM::trace)
288+
.def("transpose_in_place", &SM::transposeInPlace)
289+
;
290+
}
291+
292+
// vector
293+
if constexpr (NRows == 1 || NCols == 1)
294+
{
295+
py_sm
296+
.def("__getitem__", [](SM & sm, int key){
297+
if (key < SM::starting_index || key >= SM::column_size * SM::row_size + SM::starting_index)
298+
throw std::runtime_error("Index out of bounds: " + std::to_string(key));
299+
return sm(key);
300+
})
301+
.def("__setitem__", [](SM & sm, int key, T const value){
302+
if (key < SM::starting_index || key >= SM::column_size * SM::row_size + SM::starting_index)
303+
throw std::runtime_error("Index out of bounds: " + std::to_string(key));
304+
sm(key) = value;
305+
})
306+
;
307+
} else {
308+
using SV = SmallMatrix<T, NRows, 1, Order::F, StartIndex>;
309+
using SRV = SmallMatrix<T, 1, NCols, Order::F, StartIndex>;
310+
311+
// operators for matrix-matrix & matrix-vector
312+
py_sm
313+
.def(py::self * py::self)
314+
.def(py::self * SV())
315+
.def(SRV() * py::self)
316+
;
317+
}
318+
}
319+
}

src/Base/SmallMatrix.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/* Copyright 2021-2025 The AMReX Community
2+
*
3+
* Authors: Axel Huebl
4+
* License: BSD-3-Clause-LBNL
5+
*/
6+
#include "pyAMReX.H"
7+
8+
#include "SmallMatrix.H"
9+
10+
11+
void init_SmallMatrix (py::module &m)
12+
{
13+
using namespace pyAMReX;
14+
15+
// 6x6 Matrix as commonly used in accelerator physics
16+
{
17+
constexpr int NRows = 6;
18+
constexpr int NCols = 6;
19+
constexpr Order ORDER = Order::F;
20+
constexpr int StartIndex = 1;
21+
22+
// Vector
23+
make_SmallMatrix< float, NRows, 1, ORDER, StartIndex >(m, "float");
24+
make_SmallMatrix< double, NRows, 1, ORDER, StartIndex >(m, "double");
25+
make_SmallMatrix< long double, NRows, 1, ORDER, StartIndex >(m, "longdouble");
26+
27+
// RowVector
28+
make_SmallMatrix< float, 1, NCols, ORDER, StartIndex >(m, "float");
29+
make_SmallMatrix< double, 1, NCols, ORDER, StartIndex >(m, "double");
30+
make_SmallMatrix< long double, 1, NCols, ORDER, StartIndex >(m, "longdouble");
31+
32+
// Matrix
33+
make_SmallMatrix< float, NRows, NCols, ORDER, StartIndex >(m, "float");
34+
make_SmallMatrix< double, NRows, NCols, ORDER, StartIndex >(m, "double");
35+
make_SmallMatrix< long double, NRows, NCols, ORDER, StartIndex >(m, "longdouble");
36+
/*
37+
make_SmallMatrix< float const, NRows, NCols, ORDER, StartIndex >(m, "float_const");
38+
make_SmallMatrix< double const, NRows, NCols, ORDER, StartIndex >(m, "double_const");
39+
make_SmallMatrix< long double const, NRows, NCols, ORDER, StartIndex >(m, "longdouble_const");
40+
*/
41+
}
42+
}

0 commit comments

Comments
 (0)