1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
use crate::npyffi::{NPY_CASTING, NPY_ORDER};
use crate::{Element, PyArray, PY_ARRAY_API};
use ndarray::{Dimension, IxDyn};
use pyo3::{AsPyPointer, FromPyPointer, PyAny, PyNativeType, PyResult};
use std::ffi::CStr;
pub fn inner<'py, T, DIN1, DIN2, DOUT>(
array1: &'py PyArray<T, DIN1>,
array2: &'py PyArray<T, DIN2>,
) -> PyResult<&'py PyArray<T, DOUT>>
where
DIN1: Dimension,
DIN2: Dimension,
DOUT: Dimension,
T: Element,
{
let obj = unsafe {
let result = PY_ARRAY_API.PyArray_InnerProduct(array1.as_ptr(), array2.as_ptr());
PyAny::from_owned_ptr_or_err(array1.py(), result)?
};
obj.extract()
}
pub fn dot<'py, T, DIN1, DIN2, DOUT>(
array1: &'py PyArray<T, DIN1>,
array2: &'py PyArray<T, DIN2>,
) -> PyResult<&'py PyArray<T, DOUT>>
where
DIN1: Dimension,
DIN2: Dimension,
DOUT: Dimension,
T: Element,
{
let obj = unsafe {
let result = PY_ARRAY_API.PyArray_MatrixProduct(array1.as_ptr(), array2.as_ptr());
PyAny::from_owned_ptr_or_err(array1.py(), result)?
};
obj.extract()
}
pub fn einsum_impl<'py, T, DOUT>(
subscripts: &str,
arrays: &[&'py PyArray<T, IxDyn>],
) -> PyResult<&'py PyArray<T, DOUT>>
where
DOUT: Dimension,
T: Element,
{
let subscripts: std::borrow::Cow<CStr> = match CStr::from_bytes_with_nul(subscripts.as_bytes())
{
Ok(subscripts) => subscripts.into(),
Err(_) => std::ffi::CString::new(subscripts).unwrap().into(),
};
let obj = unsafe {
let result = PY_ARRAY_API.PyArray_EinsteinSum(
subscripts.as_ptr() as _,
arrays.len() as _,
arrays.as_ptr() as _,
std::ptr::null_mut(),
NPY_ORDER::NPY_KEEPORDER,
NPY_CASTING::NPY_NO_CASTING,
std::ptr::null_mut(),
);
PyAny::from_owned_ptr_or_err(arrays[0].py(), result)?
};
obj.extract()
}
#[macro_export]
macro_rules! einsum {
($subscripts: literal $(,$array: ident)+ $(,)*) => {{
let arrays = [$($array.to_dyn(),)+];
unsafe { $crate::einsum_impl(concat!($subscripts, "\0"), &arrays) }
}};
}