Skip to content

Commit 53483a4

Browse files
authored
Small Matrix (6x6, F) (#399)
Add the implementation for the new [small matrix](AMReX-Codes/amrex#4176) (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](AMReX-Codes/amrex#4188) matrix. (X-ref: BLAST-ImpactX/impactx#736, BLAST-ImpactX/impactx#743) cc @cemitch99
1 parent f3de107 commit 53483a4

File tree

10 files changed

+824
-5
lines changed

10 files changed

+824
-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: 367 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,367 @@
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+
/** CPU: __array_interface__ v3
49+
*
50+
* https://numpy.org/doc/stable/reference/arrays.interface.html
51+
*/
52+
template<
53+
class T,
54+
int NRows,
55+
int NCols,
56+
amrex::Order ORDER = amrex::Order::F,
57+
int StartIndex = 0
58+
>
59+
py::dict
60+
array_interface (amrex::SmallMatrix<T, NRows, NCols, ORDER, StartIndex> const & m)
61+
{
62+
using namespace amrex;
63+
64+
auto d = py::dict();
65+
// provide C index order for shape and strides
66+
auto shape = m.ordering == Order::F ? py::make_tuple(
67+
py::ssize_t(NRows),
68+
py::ssize_t(NCols) // fastest varying index
69+
) : py::make_tuple(
70+
py::ssize_t(NCols),
71+
py::ssize_t(NRows) // fastest varying index
72+
);
73+
// buffer protocol strides are in bytes
74+
auto const strides = m.ordering == Order::F ? py::make_tuple(
75+
py::ssize_t(sizeof(T) * NCols),
76+
py::ssize_t(sizeof(T)) // fastest varying index
77+
) : py::make_tuple(
78+
py::ssize_t(sizeof(T) * NRows),
79+
py::ssize_t(sizeof(T)) // fastest varying index
80+
);
81+
bool const read_only = false; // note: we could decide on is_not_const,
82+
// but many libs, e.g. PyTorch, do not
83+
// support read-only and will raise
84+
// warnings, casting to read-write
85+
d["data"] = py::make_tuple(std::intptr_t(&m.template get<0>()), read_only);
86+
// note: if we want to keep the same global indexing with non-zero
87+
// box small_end as in AMReX, then we can explore playing with
88+
// this offset as well
89+
//d["offset"] = 0; // default
90+
//d["mask"] = py::none(); // default
91+
92+
d["shape"] = shape;
93+
// we could also set this after checking the strides are C-style contiguous:
94+
//if (is_contiguous<T>(shape, strides))
95+
// d["strides"] = py::none(); // C-style contiguous
96+
//else
97+
d["strides"] = strides;
98+
99+
// type description
100+
// for more complicated types, e.g., tuples/structs
101+
//d["descr"] = ...;
102+
// we currently only need this
103+
using T_no_cv = std::remove_cv_t<T>;
104+
d["typestr"] = py::format_descriptor<T_no_cv>::format();
105+
106+
d["version"] = 3;
107+
return d;
108+
}
109+
110+
template<class SM>
111+
py::class_<SM>
112+
make_SmallMatrix_or_Vector (py::module &m, std::string typestr)
113+
{
114+
using namespace amrex;
115+
116+
using T = typename SM::value_type;
117+
using T_no_cv = std::remove_cv_t<T>;
118+
static constexpr int row_size = SM::row_size;
119+
static constexpr int column_size = SM::column_size;
120+
static constexpr Order ordering = SM::ordering;
121+
static constexpr int starting_index = SM::starting_index;
122+
123+
// dispatch simpler via: py::format_descriptor<T>::format() naming
124+
// but note the _const suffix that might be needed
125+
auto const sm_name = std::string("SmallMatrix_")
126+
.append(std::to_string(row_size)).append("x").append(std::to_string(column_size))
127+
.append("_").append(ordering == Order::F ? "F" : "C")
128+
.append("_SI").append(std::to_string(starting_index))
129+
.append("_").append(typestr);
130+
py::class_< SM > py_sm(m, sm_name.c_str());
131+
py_sm
132+
.def("__repr__",
133+
[sm_name](SM const &) {
134+
return "<amrex." + sm_name + ">";
135+
}
136+
)
137+
.def("__str__",
138+
[sm_name](SM const & sm) {
139+
std::stringstream ss;
140+
ss << sm;
141+
return ss.str();
142+
}
143+
)
144+
145+
.def_property_readonly("size", [](SM const &){ return SM::row_size * SM::column_size; })
146+
.def_property_readonly("row_size", [](SM const &){ return SM::row_size; })
147+
.def_property_readonly("column_size", [](SM const &){ return SM::column_size; })
148+
.def_property_readonly("order", [](SM const &){ return SM::ordering == Order::F ? "F" : "C"; }) // NumPy name
149+
.def_property_readonly("starting_index", [](SM const &){ return SM::starting_index; })
150+
151+
.def_static("zero", [](){ return SM::Zero(); })
152+
153+
.def(py::init([](){ return SM{}; })) // zero-init
154+
.def(py::init<SM const &>()) // copy-init
155+
156+
/* init from a numpy or other buffer protocol array: copy
157+
*/
158+
.def(py::init([](py::array_t<T> & arr)
159+
{
160+
py::buffer_info buf = arr.request();
161+
162+
constexpr bool is_vector = SM::column_size == 1 || SM::row_size == 1;
163+
constexpr int sm_dim = is_vector ? 1 : 2;
164+
if (buf.ndim != sm_dim)
165+
throw std::runtime_error("The SmallMatrix to create is " + std::to_string(sm_dim) +
166+
"D, but the passed array is " + std::to_string(buf.ndim) + "D.");
167+
if (buf.size != SM::column_size * SM::row_size)
168+
throw std::runtime_error("Array size mismatch: Expected " + std::to_string(SM::column_size * SM::row_size) +
169+
" elements, but passed " + std::to_string(buf.size) + " elements.");
170+
171+
if (buf.format != py::format_descriptor<T_no_cv>::format())
172+
throw std::runtime_error("Incompatible format: expected '" +
173+
py::format_descriptor<T_no_cv>::format() +
174+
"' and received '" + buf.format + "'!");
175+
176+
// TODO: check that strides are either exact or None in buf (e.g., F or C contiguous)
177+
// TODO: transpose if SM order is not C?
178+
179+
auto sm = std::make_unique< SM >();
180+
auto * src = static_cast<T*>(buf.ptr);
181+
std::copy(src, src + buf.size, &sm->template get<0>());
182+
183+
// todo: we could check and store here if the array buffer we got is read-only
184+
185+
return sm;
186+
}))
187+
188+
/* init from __cuda_array_interface__: device-to-host copy
189+
* TODO
190+
*/
191+
192+
193+
// CPU: __array_interface__ v3
194+
// https://numpy.org/doc/stable/reference/arrays.interface.html
195+
.def_property_readonly("__array_interface__", [](SM const & sm) {
196+
return array_interface(sm);
197+
})
198+
199+
// CPU: __array_function__ interface (TODO)
200+
//
201+
// NEP 18 — A dispatch mechanism for NumPy's high level array functions.
202+
// https://numpy.org/neps/nep-0018-array-function-protocol.html
203+
// This enables code using NumPy to be directly operated on Array4 arrays.
204+
// __array_function__ feature requires NumPy 1.16 or later.
205+
206+
207+
// Nvidia GPUs: __cuda_array_interface__ v3
208+
// https://numba.readthedocs.io/en/latest/cuda/cuda_array_interface.html
209+
.def_property_readonly("__cuda_array_interface__", [](SM const & sm)
210+
{
211+
auto d = array_interface(sm);
212+
213+
// data:
214+
// 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.
215+
// TODO For zero-size arrays, use 0 here.
216+
217+
// None or integer
218+
// 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:
219+
// 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.
220+
// 1: The legacy default stream.
221+
// 2: The per-thread default stream.
222+
// Any other integer: a cudaStream_t represented as a Python integer.
223+
// When None, no synchronization is required.
224+
d["stream"] = py::none();
225+
226+
d["version"] = 3;
227+
return d;
228+
})
229+
230+
231+
// TODO: __dlpack__ __dlpack_device__
232+
// DLPack protocol (CPU, NVIDIA GPU, AMD GPU, Intel GPU, etc.)
233+
// https://dmlc.github.io/dlpack/latest/
234+
// https://data-apis.org/array-api/latest/design_topics/data_interchange.html
235+
// https://github.com/data-apis/consortium-feedback/issues/1
236+
// https://github.com/dmlc/dlpack/blob/master/include/dlpack/dlpack.h
237+
// https://docs.cupy.dev/en/stable/user_guide/interoperability.html#dlpack-data-exchange-protocol
238+
239+
;
240+
241+
return py_sm;
242+
}
243+
244+
template<class SM>
245+
void add_matrix_methods (py::class_<SM> & py_sm)
246+
{
247+
using T = typename SM::value_type;
248+
using T_no_cv = std::remove_cv_t<T>;
249+
static constexpr int row_size = SM::row_size;
250+
static constexpr int column_size = SM::column_size;
251+
static constexpr int starting_index = SM::starting_index;
252+
253+
py_sm
254+
.def("dot", &SM::dot)
255+
.def("prod", &SM::product) // NumPy name
256+
.def("set_val", &SM::setVal)
257+
.def("sum", &SM::sum)
258+
.def_property_readonly("T", &SM::transpose) // NumPy name
259+
260+
// operators
261+
.def(py::self + py::self)
262+
.def(py::self - py::self)
263+
.def(py::self * amrex::Real())
264+
.def(amrex::Real() * py::self)
265+
.def(-py::self)
266+
267+
// getter
268+
.def("__getitem__", [](SM & sm, std::array<int, 2> const & key){
269+
if (key[0] < starting_index || key[0] >= row_size + starting_index ||
270+
key[1] < starting_index || key[1] >= column_size + starting_index)
271+
throw std::runtime_error(
272+
"Index out of bounds: [" +
273+
std::to_string(key[0]) + ", " +
274+
std::to_string(key[1]) + "]");
275+
return sm(key[0], key[1]);
276+
})
277+
;
278+
279+
// setter
280+
if constexpr (is_not_const<T>())
281+
{
282+
py_sm
283+
.def("__setitem__", [](SM & sm, std::array<int, 2> const & key, T_no_cv const value){
284+
if (key[0] < SM::starting_index || key[0] >= SM::row_size + SM::starting_index ||
285+
key[1] < SM::starting_index || key[1] >= SM::column_size + SM::starting_index)
286+
{
287+
throw std::runtime_error(
288+
"Index out of bounds: [" +
289+
std::to_string(key[0]) + ", " +
290+
std::to_string(key[1]) + "]");
291+
}
292+
sm(key[0], key[1]) = value;
293+
})
294+
;
295+
}
296+
297+
// square matrix
298+
if constexpr (row_size == column_size)
299+
{
300+
py_sm
301+
.def_static("identity", []() { return SM::Identity(); })
302+
.def("trace", [](SM & sm){ return sm.trace(); })
303+
.def("transpose_in_place", [](SM & sm){ return sm.transposeInPlace(); })
304+
;
305+
}
306+
}
307+
308+
template<class T_SV>
309+
void add_get_set_Vector (py::class_<T_SV> &py_v)
310+
{
311+
using self = T_SV;
312+
using T = typename T_SV::value_type;
313+
using T_no_cv = std::remove_cv_t<T>;
314+
315+
py_v
316+
.def("__getitem__", [](self & sm, int key){
317+
if (key < self::starting_index || key >= self::column_size * self::row_size + self::starting_index)
318+
throw std::runtime_error("Index out of bounds: " + std::to_string(key));
319+
return sm(key);
320+
})
321+
.def("__setitem__", [](self & sm, int key, T_no_cv const value){
322+
if (key < self::starting_index || key >= self::column_size * self::row_size + self::starting_index)
323+
throw std::runtime_error("Index out of bounds: " + std::to_string(key));
324+
sm(key) = value;
325+
})
326+
;
327+
}
328+
}
329+
330+
namespace pyAMReX
331+
{
332+
template<
333+
class T,
334+
int NRows,
335+
int NCols,
336+
amrex::Order ORDER = amrex::Order::F,
337+
int StartIndex = 0
338+
>
339+
void make_SmallMatrix (py::module &m, std::string typestr)
340+
{
341+
using namespace amrex;
342+
343+
using SM = SmallMatrix<T, NRows, NCols, ORDER, StartIndex>;
344+
using SV = SmallMatrix<T, NRows, 1, Order::F, StartIndex>;
345+
using SRV = SmallMatrix<T, 1, NCols, Order::F, StartIndex>;
346+
347+
py::class_<SM> py_sm = make_SmallMatrix_or_Vector<SM>(m, typestr);
348+
py::class_<SV> py_sv = make_SmallMatrix_or_Vector<SV>(m, typestr);
349+
py::class_<SRV> py_srv = make_SmallMatrix_or_Vector<SRV>(m, typestr);
350+
351+
// methods, getter, setter
352+
add_matrix_methods(py_sm);
353+
add_matrix_methods(py_sv);
354+
add_matrix_methods(py_srv);
355+
356+
// vector setter/getter
357+
add_get_set_Vector(py_sv);
358+
add_get_set_Vector(py_srv);
359+
360+
// operators for matrix-matrix & matrix-vector
361+
py_sm
362+
.def(py::self * py::self)
363+
.def(py::self * SV())
364+
.def(SRV() * py::self)
365+
;
366+
}
367+
}

0 commit comments

Comments
 (0)