rsarray 1.2.10__cp315-cp315-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rsarray/__init__.py +12028 -0
- rsarray/_core/__init__.py +213 -0
- rsarray/_core/_exceptions.py +83 -0
- rsarray/_core/_internal.py +331 -0
- rsarray/_core/_multiarray_tests.py +129 -0
- rsarray/_core/_multiarray_umath.py +121 -0
- rsarray/_core/_rational_tests.py +52 -0
- rsarray/_core/arrayprint.py +36 -0
- rsarray/_core/fromnumeric.py +31 -0
- rsarray/_core/function_base.py +84 -0
- rsarray/_core/multiarray.py +385 -0
- rsarray/_core/numeric.py +28 -0
- rsarray/_core/numerictypes.py +233 -0
- rsarray/_core/records.py +14 -0
- rsarray/_core/shape_base.py +23 -0
- rsarray/_core/strings.py +78 -0
- rsarray/_core/umath.py +176 -0
- rsarray/_dtypes.py +1229 -0
- rsarray/_extra.py +6621 -0
- rsarray/_typing.py +24 -0
- rsarray/array_methods.py +1224 -0
- rsarray/array_ops.py +1585 -0
- rsarray/char.py +1590 -0
- rsarray/exceptions.py +45 -0
- rsarray/fft/__init__.py +231 -0
- rsarray/io.py +453 -0
- rsarray/lib/__init__.py +102 -0
- rsarray/lib/_function_base_impl.py +37 -0
- rsarray/lib/_index_tricks_impl.py +98 -0
- rsarray/lib/_nanfunctions_impl.py +1637 -0
- rsarray/lib/_stride_tricks_impl.py +110 -0
- rsarray/lib/recfunctions.py +1222 -0
- rsarray/lib/stride_tricks.py +106 -0
- rsarray/linalg/__init__.py +2603 -0
- rsarray/linalg/_linalg.py +91 -0
- rsarray/linalg/_pylinalg.py +1008 -0
- rsarray/linalg/lapack_lite.py +13 -0
- rsarray/ma/__init__.py +92 -0
- rsarray/ma/core.py +1385 -0
- rsarray/ma/extras.py +711 -0
- rsarray/ma/mrecords.py +144 -0
- rsarray/math_functions.py +965 -0
- rsarray/matlib.py +67 -0
- rsarray/num_core.cp315-win_amd64.pyd +0 -0
- rsarray/polynomial/__init__.py +148 -0
- rsarray/polynomial/_npcompat.py +721 -0
- rsarray/polynomial/polynomial.py +1082 -0
- rsarray/random/__init__.py +2266 -0
- rsarray/random/_distributions.py +773 -0
- rsarray/rec.py +207 -0
- rsarray/statistics.py +1360 -0
- rsarray/strings.py +349 -0
- rsarray/typing/__init__.py +26 -0
- rsarray-1.2.10.dist-info/METADATA +280 -0
- rsarray-1.2.10.dist-info/RECORD +59 -0
- rsarray-1.2.10.dist-info/WHEEL +4 -0
- rsarray-1.2.10.dist-info/licenses/LICENSE +21 -0
- rsarray-1.2.10.dist-info/licenses/NOTICE +7 -0
- rsarray-1.2.10.dist-info/sboms/rsarray.cyclonedx.json +2789 -0
|
@@ -0,0 +1,2603 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""rsarray.linalg - 线性代数模块 - 薄包装,所有实现位于 Rust。"""
|
|
3
|
+
|
|
4
|
+
import sys as _sys
|
|
5
|
+
from collections import namedtuple
|
|
6
|
+
|
|
7
|
+
import rsarray.num_core as _core
|
|
8
|
+
|
|
9
|
+
from ._pylinalg import NoValue
|
|
10
|
+
|
|
11
|
+
# 2.x 语义:qr 的 reduced/complete 结果是有 .Q/.R 属性的命名元组
|
|
12
|
+
QRResult = namedtuple('QRResult', ['Q', 'R'])
|
|
13
|
+
# svd compute_uv=True 结果是有 .U/.S/.Vh 属性的命名元组(可作 3 元组解包)
|
|
14
|
+
SVDResult = namedtuple('SVDResult', ['U', 'S', 'Vh'])
|
|
15
|
+
# eig 结果是有 .eigenvalues/.eigenvectors 属性的命名元组(2.x 语义)
|
|
16
|
+
EigResult = namedtuple('EigResult', ['eigenvalues', 'eigenvectors'])
|
|
17
|
+
# eigh 结果是有 .eigenvalues/.eigenvectors 属性的命名元组(2.x 语义)
|
|
18
|
+
EighResult = namedtuple('EighResult', ['eigenvalues', 'eigenvectors'])
|
|
19
|
+
# slogdet 结果是有 .sign/.logabsdet 属性的命名元组(2.x 语义)
|
|
20
|
+
SlogdetResult = namedtuple('SlogdetResult', ['sign', 'logabsdet'])
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class LinAlgError(ValueError):
|
|
24
|
+
"""线性代数相关错误。"""
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _ensure(x):
|
|
29
|
+
if isinstance(x, (list, tuple)):
|
|
30
|
+
return _core.ndarray(x)
|
|
31
|
+
elif hasattr(x, '_array'):
|
|
32
|
+
return x._array
|
|
33
|
+
return x
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _round_float(v):
|
|
37
|
+
"""对浮点数进行四舍五入,避免出现 .999999999999999 等精度问题。"""
|
|
38
|
+
if abs(v - round(v)) < 1e-10:
|
|
39
|
+
return round(v)
|
|
40
|
+
return v
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _round_array(arr):
|
|
44
|
+
"""对数组中的每个元素进行四舍五入处理。"""
|
|
45
|
+
if hasattr(arr, '__class__') and arr.__class__.__name__ == 'ndarray':
|
|
46
|
+
raw = arr.tolist()
|
|
47
|
+
|
|
48
|
+
def round_nested(data):
|
|
49
|
+
if isinstance(data, list):
|
|
50
|
+
return [round_nested(x) for x in data]
|
|
51
|
+
return _round_float(data)
|
|
52
|
+
|
|
53
|
+
rounded = round_nested(raw)
|
|
54
|
+
return _core.ndarray(rounded)
|
|
55
|
+
return arr
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _wrap(x):
|
|
59
|
+
"""包装/转换数组,避免类身份不一致问题。"""
|
|
60
|
+
from rsarray import ndarray
|
|
61
|
+
# 注意:裸 Rust 绑定类型 (builtins.ndarray) 与 Python 包装类的类名都叫
|
|
62
|
+
# 'ndarray',不能只靠类名判断"已包装"(旧逻辑把裸类型原样放行,导致
|
|
63
|
+
# cholesky/svd 等返回 builtins.ndarray,`wrapper @ raw` 直接 TypeError)。
|
|
64
|
+
# _round_array 对数组输入返回裸类型,所以这里统一 round 后用包装类重新构造。
|
|
65
|
+
if (getattr(x, '__class__', None) and x.__class__.__name__ == 'ndarray') \
|
|
66
|
+
or hasattr(x, 'tolist'):
|
|
67
|
+
x = _round_array(x)
|
|
68
|
+
return ndarray(x)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _flatten_scalars(data):
|
|
72
|
+
"""将嵌套列表展平为一维标量列表。"""
|
|
73
|
+
if isinstance(data, (list, tuple)):
|
|
74
|
+
# 使用列表推导 + extend 替代显式 for 循环
|
|
75
|
+
out = []
|
|
76
|
+
for x in data:
|
|
77
|
+
out.extend(_flatten_scalars(x))
|
|
78
|
+
return out
|
|
79
|
+
return [data]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _is_complex_arr(a):
|
|
83
|
+
"""判断 rsarray 数组是否为复数数组。"""
|
|
84
|
+
return bool(getattr(getattr(a, '_array', None), 'is_complex', False))
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _matmul_2d(mat_a, mat_b):
|
|
88
|
+
"""朴素二维矩阵乘 A(m×n)·B(n×p),元素可为 float 或 complex。"""
|
|
89
|
+
# n = len(mat_b)
|
|
90
|
+
p = len(mat_b[0]) if mat_b and isinstance(mat_b[0], list) else 0
|
|
91
|
+
if not mat_a or p == 0:
|
|
92
|
+
# 保持 (m, 0) 嵌套结构(flat [] 会让 ndarray 推成 1-d (0,))
|
|
93
|
+
return [[] for _ in range(len(mat_a))]
|
|
94
|
+
# ikj 顺序:使用 enumerate 缓存索引与值,跳过零元素加速稀疏场景
|
|
95
|
+
out = [[0] * p for _ in range(len(mat_a))]
|
|
96
|
+
for i, row_a in enumerate(mat_a):
|
|
97
|
+
row_o = out[i]
|
|
98
|
+
for k, aik in enumerate(row_a):
|
|
99
|
+
if aik == 0:
|
|
100
|
+
continue
|
|
101
|
+
row_b = mat_b[k]
|
|
102
|
+
for j in range(p):
|
|
103
|
+
row_o[j] += aik * row_b[j]
|
|
104
|
+
return out
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _matmul_nested(a, na, b, nb):
|
|
108
|
+
"""支持复数与批量(>2 维广播)的 matmul,操作于嵌套列表。"""
|
|
109
|
+
if na == 2 and nb == 2:
|
|
110
|
+
return _matmul_2d(a, b)
|
|
111
|
+
if na == 1 and nb == 1:
|
|
112
|
+
return sum(x * y for x, y in zip(a, b))
|
|
113
|
+
if na == 2 and nb == 1:
|
|
114
|
+
return [sum(a[i][k] * b[k] for k in range(len(b))) for i in range(len(a))]
|
|
115
|
+
if na == 1 and nb == 2:
|
|
116
|
+
return [sum(a[k] * b[k][j] for k in range(len(a))) for j in range(len(b[0]))]
|
|
117
|
+
if na >= 3 and nb == 2:
|
|
118
|
+
return [_matmul_nested(sub, na - 1, b, 2) for sub in a]
|
|
119
|
+
if na == 2 and nb >= 3:
|
|
120
|
+
return [_matmul_nested(a, 2, sub, nb - 1) for sub in b]
|
|
121
|
+
if na >= 3 and nb >= 3:
|
|
122
|
+
# 前导维须同形(rsarray 无完整广播;同形 zip 即可)
|
|
123
|
+
return [_matmul_nested(sa, na - 1, sb, nb - 1) for sa, sb in zip(a, b)]
|
|
124
|
+
raise ValueError("unsupported matmul shapes: {}D and {}D".format(na, nb))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _matmul_wrap(res, a_shape, b_shape, is_c, a_dtype, b_dtype):
|
|
128
|
+
"""包装 matmul Python 回退结果:恢复空矩阵形状与复数 dtype。
|
|
129
|
+
|
|
130
|
+
Python 嵌套列表无法表达 (0, p) 这类零维形状(ndarray 会推成 1-d),
|
|
131
|
+
且空列表推得 float64——须按 (lead, m, p) 显式 reshape/astype。
|
|
132
|
+
"""
|
|
133
|
+
from rsarray import ndarray
|
|
134
|
+
|
|
135
|
+
out = ndarray(res) if isinstance(res, list) else res
|
|
136
|
+
if not isinstance(out, ndarray):
|
|
137
|
+
return out
|
|
138
|
+
if len(a_shape) == 1 or len(b_shape) == 1:
|
|
139
|
+
# 向量结果:(m,n)@(n,)→(m,);(n,)@(n,k)→(k,)
|
|
140
|
+
if len(b_shape) == 1:
|
|
141
|
+
exp = a_shape[:-2] + (a_shape[-2],)
|
|
142
|
+
else:
|
|
143
|
+
exp = b_shape[1:]
|
|
144
|
+
else:
|
|
145
|
+
lead = [max(x, y) for x, y in
|
|
146
|
+
zip(reversed(a_shape[:-2]), reversed(b_shape[:-2]))]
|
|
147
|
+
exp = tuple(reversed(lead)) + (a_shape[-2], b_shape[-1])
|
|
148
|
+
if tuple(out.shape) != exp:
|
|
149
|
+
out = out.reshape(exp)
|
|
150
|
+
# Python 列表只能表达 float64/complex128:按 提升规则还原位宽
|
|
151
|
+
# (f32@f32→f32;c64@c64→c64;任一侧更宽则更宽)
|
|
152
|
+
if is_c or 'complex' in a_dtype or 'complex' in b_dtype:
|
|
153
|
+
res_dt = 'complex128' if 'complex128' in (a_dtype, b_dtype) \
|
|
154
|
+
else 'complex64'
|
|
155
|
+
else:
|
|
156
|
+
res_dt = 'float64' if 'float64' in (a_dtype, b_dtype) else 'float32'
|
|
157
|
+
if getattr(out, '_dtype', None) != res_dt:
|
|
158
|
+
out = out.astype(res_dt)
|
|
159
|
+
return out
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _dot_res_dtype(a_dtype, b_dtype):
|
|
163
|
+
"""提升规则(linalg inexact/int 场景):c64×c64→c64、
|
|
164
|
+
c64×其它→c128、f32×f32→f32(旧实现硬编码 float64 会破坏
|
|
165
|
+
32 位结果的 dtype,测试按 dtype 选精度阈值)。"""
|
|
166
|
+
if 'complex128' in (a_dtype, b_dtype):
|
|
167
|
+
return 'complex128'
|
|
168
|
+
if 'complex64' in (a_dtype, b_dtype):
|
|
169
|
+
return 'complex64' if a_dtype == b_dtype == 'complex64' \
|
|
170
|
+
else 'complex128'
|
|
171
|
+
if 'float64' in (a_dtype, b_dtype):
|
|
172
|
+
return 'float64'
|
|
173
|
+
if 'float32' in (a_dtype, b_dtype):
|
|
174
|
+
return 'float32'
|
|
175
|
+
if 'float16' in (a_dtype, b_dtype):
|
|
176
|
+
return 'float16'
|
|
177
|
+
return 'int64'
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _dot_nested(a, na, b, nb):
|
|
181
|
+
"""支持复数的 dot,覆盖 1D/2D 组合(更高维按批量 matmul 处理)。"""
|
|
182
|
+
if na == 1 and nb == 1:
|
|
183
|
+
return sum(x * y for x, y in zip(a, b))
|
|
184
|
+
if na == 2 and nb == 2:
|
|
185
|
+
return _matmul_2d(a, b)
|
|
186
|
+
if na == 2 and nb == 1:
|
|
187
|
+
return [sum(a[i][k] * b[k] for k in range(len(b))) for i in range(len(a))]
|
|
188
|
+
if na == 1 and nb == 2:
|
|
189
|
+
return [sum(a[k] * b[k][j] for k in range(len(a))) for j in range(len(b[0]))]
|
|
190
|
+
return _matmul_nested(a, na, b, nb)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _solve_pinv(a, b):
|
|
194
|
+
"""使用伪逆求解线性方程组 x = pinv(A) @ b。"""
|
|
195
|
+
pinv_a = _pinv_general(a)
|
|
196
|
+
return _matmul_2d(pinv_a, b)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _gauss_jordan_inv(mat):
|
|
200
|
+
"""高斯-约当消元求逆(列主元),元素可为 float 或 complex,支持任意 n×n。"""
|
|
201
|
+
n = len(mat)
|
|
202
|
+
work = [list(row) for row in mat]
|
|
203
|
+
inv = [[(1.0 if i == j else 0.0) for j in range(n)] for i in range(n)]
|
|
204
|
+
max_abs = max((abs(v) for row in work for v in row), default=0.0)
|
|
205
|
+
eps = n * max_abs * 2.220446049250313e-16 if max_abs != 0 else 1e-10
|
|
206
|
+
for col in range(n):
|
|
207
|
+
pivot = max(range(col, n), key=lambda r: abs(work[r][col]))
|
|
208
|
+
if abs(work[pivot][col]) < eps:
|
|
209
|
+
raise LinAlgError("Singular matrix")
|
|
210
|
+
if pivot != col:
|
|
211
|
+
work[col], work[pivot] = work[pivot], work[col]
|
|
212
|
+
inv[col], inv[pivot] = inv[pivot], inv[col]
|
|
213
|
+
pv = work[col][col]
|
|
214
|
+
wcol = work[col]
|
|
215
|
+
icol = inv[col]
|
|
216
|
+
# 使用列表推导 + 切片赋值代替逐元素循环
|
|
217
|
+
wcol[:] = [x / pv for x in wcol]
|
|
218
|
+
icol[:] = [x / pv for x in icol]
|
|
219
|
+
for r in range(n):
|
|
220
|
+
if r == col:
|
|
221
|
+
continue
|
|
222
|
+
factor = work[r][col]
|
|
223
|
+
if abs(factor) < eps:
|
|
224
|
+
continue
|
|
225
|
+
wr = work[r]
|
|
226
|
+
ir = inv[r]
|
|
227
|
+
# 列表推导 + zip 代替显式索引循环
|
|
228
|
+
wr[:] = [a - factor * w for a, w in zip(wr, wcol)]
|
|
229
|
+
ir[:] = [a - factor * w for a, w in zip(ir, icol)]
|
|
230
|
+
return inv
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _pinv_general(mat):
|
|
234
|
+
"""通用伪逆实现,基于特征值分解处理复数矩阵。"""
|
|
235
|
+
n = len(mat)
|
|
236
|
+
m = len(mat[0]) if mat else 0
|
|
237
|
+
|
|
238
|
+
ata = [[sum(mat[i][k].conjugate() * mat[j][k] for k in range(m)) for j in range(n)] for i in range(n)]
|
|
239
|
+
|
|
240
|
+
evals, evecs = _eig_general(ata)
|
|
241
|
+
|
|
242
|
+
tol = max(n, m) * max(abs(e) for e in evals) * 1e-15
|
|
243
|
+
|
|
244
|
+
inv_sqrt = [1.0 / e**0.5 if abs(e) > tol else 0.0 for e in evals]
|
|
245
|
+
|
|
246
|
+
v_inv = [[evecs[j][i] * inv_sqrt[i] for i in range(n)] for j in range(n)]
|
|
247
|
+
|
|
248
|
+
at = [[mat[j][i].conjugate() for j in range(n)] for i in range(m)]
|
|
249
|
+
|
|
250
|
+
return _matmul_2d(v_inv, _matmul_2d(v_inv, at))
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _eig_general(mat):
|
|
254
|
+
"""通用特征值分解实现,支持复数矩阵。"""
|
|
255
|
+
n = len(mat)
|
|
256
|
+
if n == 1:
|
|
257
|
+
return [mat[0][0]], [[1.0]]
|
|
258
|
+
if n == 2:
|
|
259
|
+
a, b = mat[0][0], mat[0][1]
|
|
260
|
+
c, d = mat[1][0], mat[1][1]
|
|
261
|
+
tr = a + d
|
|
262
|
+
det = a * d - b * c
|
|
263
|
+
import cmath
|
|
264
|
+
disc = cmath.sqrt(tr * tr - 4.0 * det)
|
|
265
|
+
evals = [(tr + disc) / 2.0, (tr - disc) / 2.0]
|
|
266
|
+
evecs = [[0.0, 0.0], [0.0, 0.0]]
|
|
267
|
+
for idx, lam in enumerate(evals):
|
|
268
|
+
if abs(b) > 1e-12 or abs(lam - a) > 1e-12:
|
|
269
|
+
v0, v1 = b, lam - a
|
|
270
|
+
else:
|
|
271
|
+
v0, v1 = lam - d, c
|
|
272
|
+
norm = abs(v0)**2 + abs(v1)**2
|
|
273
|
+
if norm < 1e-24:
|
|
274
|
+
evecs[0][idx] = 1.0
|
|
275
|
+
evecs[1][idx] = 0.0
|
|
276
|
+
else:
|
|
277
|
+
norm = cmath.sqrt(norm)
|
|
278
|
+
evecs[0][idx] = v0 / norm
|
|
279
|
+
evecs[1][idx] = v1 / norm
|
|
280
|
+
return evals, evecs
|
|
281
|
+
|
|
282
|
+
# n≥3:对称/厄米保持幂迭代;一般矩阵走特征多项式(FL+DK)特征值
|
|
283
|
+
# + 正规方程特征向量(与 eigvals 的 FL+DK 结果同序)。
|
|
284
|
+
if _is_symmetricish(mat):
|
|
285
|
+
return _eig_power_iteration(mat)
|
|
286
|
+
from ._pylinalg import _eigvals_qr, _eigenvectors_general
|
|
287
|
+
evals = _eigvals_qr(mat)
|
|
288
|
+
return evals, _eigenvectors_general(mat, evals)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _is_symmetricish(mat, tol=1e-10):
|
|
292
|
+
"""判断嵌套 list 矩阵是否(近似)厄米:mat[i][j] ≈ conj(mat[j][i])。"""
|
|
293
|
+
n = len(mat)
|
|
294
|
+
for i in range(n):
|
|
295
|
+
for j in range(i + 1, n):
|
|
296
|
+
a = mat[i][j]
|
|
297
|
+
b = mat[j][i].conjugate()
|
|
298
|
+
if abs(a - b) > tol * (1.0 + abs(a) + abs(b)):
|
|
299
|
+
return False
|
|
300
|
+
return True
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _eig_power_iteration(mat):
|
|
304
|
+
"""幂迭代法计算特征值和特征向量(仅适用于对称/厄米矩阵)。"""
|
|
305
|
+
import cmath
|
|
306
|
+
n = len(mat)
|
|
307
|
+
evals = []
|
|
308
|
+
evecs = [[0.0] * n for _ in range(n)]
|
|
309
|
+
|
|
310
|
+
for k in range(n):
|
|
311
|
+
v = [complex(1.0 if i == k else 0.0) for i in range(n)]
|
|
312
|
+
for _ in range(100):
|
|
313
|
+
# 列表推导:mat @ v
|
|
314
|
+
new_v = [sum(mat[i][j] * v[j] for j in range(n)) for i in range(n)]
|
|
315
|
+
norm_sq = sum(abs(x)**2 for x in new_v)
|
|
316
|
+
if norm_sq < 1e-24:
|
|
317
|
+
break
|
|
318
|
+
norm = cmath.sqrt(norm_sq)
|
|
319
|
+
v = [x / norm for x in new_v]
|
|
320
|
+
# Rayleigh 商:v^H @ mat @ v
|
|
321
|
+
mat_v = [sum(mat[i][j] * v[j] for j in range(n)) for i in range(n)]
|
|
322
|
+
lam = sum(v[i].conjugate() * mat_v[i] for i in range(n))
|
|
323
|
+
evals.append(lam)
|
|
324
|
+
# 列表推导:填充第 k 列特征向量
|
|
325
|
+
for i, vi in enumerate(v):
|
|
326
|
+
evecs[i][k] = vi
|
|
327
|
+
|
|
328
|
+
return evals, evecs
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _eig_one(mat):
|
|
332
|
+
"""单个 2-d 矩阵特征分解:Rust 快路径(2x2/3x3 实输入),其余尺寸
|
|
333
|
+
(含空/1x1)与全部复数输入走纯 Python 回退(Rust eig 不处理复数)。
|
|
334
|
+
返回 (evals, evecs) 的嵌套 list。"""
|
|
335
|
+
from rsarray import ndarray as _nd
|
|
336
|
+
|
|
337
|
+
dt = getattr(mat, '_dtype', 'float64')
|
|
338
|
+
if dt in ('complex64', 'complex128'):
|
|
339
|
+
return _eig_general(mat.tolist())
|
|
340
|
+
try:
|
|
341
|
+
ev, ec = _core.linalg.eig(mat._array)
|
|
342
|
+
return (_nd._wrap(ev).tolist(), _nd._wrap(ec).tolist())
|
|
343
|
+
except ValueError:
|
|
344
|
+
return _eig_general(mat.tolist())
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _gauss_jordan_solve(mat, b):
|
|
348
|
+
"""高斯-约当消元求解 Ax = b(列主元),元素可为 float 或 complex,支持任意 n×n。"""
|
|
349
|
+
n = len(mat)
|
|
350
|
+
work = [list(row) for row in mat]
|
|
351
|
+
# 列表推导 + 闭包提取行转换逻辑
|
|
352
|
+
|
|
353
|
+
def _conv_row(row):
|
|
354
|
+
if isinstance(row, (list, tuple)):
|
|
355
|
+
return list(row)
|
|
356
|
+
if hasattr(row, 'tolist'):
|
|
357
|
+
return row.tolist()
|
|
358
|
+
return [row]
|
|
359
|
+
rhs = [_conv_row(row) for row in b]
|
|
360
|
+
max_abs = max((abs(v) for row in work for v in row), default=0.0)
|
|
361
|
+
eps = n * max_abs * 2.220446049250313e-16 if max_abs != 0 else 1e-10
|
|
362
|
+
for col in range(n):
|
|
363
|
+
pivot = max(range(col, n), key=lambda r: abs(work[r][col]))
|
|
364
|
+
if abs(work[pivot][col]) < eps:
|
|
365
|
+
raise LinAlgError("Singular matrix")
|
|
366
|
+
if pivot != col:
|
|
367
|
+
work[col], work[pivot] = work[pivot], work[col]
|
|
368
|
+
rhs[col], rhs[pivot] = rhs[pivot], rhs[col]
|
|
369
|
+
pv = work[col][col]
|
|
370
|
+
wcol = work[col]
|
|
371
|
+
rcol = rhs[col]
|
|
372
|
+
# 列表推导 + 切片赋值代替逐元素循环
|
|
373
|
+
wcol[:] = [x / pv for x in wcol]
|
|
374
|
+
rcol[:] = [x / pv for x in rcol]
|
|
375
|
+
for r in range(n):
|
|
376
|
+
if r == col:
|
|
377
|
+
continue
|
|
378
|
+
factor = work[r][col]
|
|
379
|
+
if factor == 0:
|
|
380
|
+
continue
|
|
381
|
+
wr = work[r]
|
|
382
|
+
rr = rhs[r]
|
|
383
|
+
wr[:] = [a - factor * w for a, w in zip(wr, wcol)]
|
|
384
|
+
rr[:] = [a - factor * w for a, w in zip(rr, rcol)]
|
|
385
|
+
if n and len(rhs[0]) == 1 and len(rhs) == n:
|
|
386
|
+
return [[row[0]] for row in rhs]
|
|
387
|
+
return rhs
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _inv_nested(data):
|
|
391
|
+
"""对嵌套列表递归求逆:最内两维视为待求逆的方阵,外层为批量维。"""
|
|
392
|
+
if isinstance(data, list) and data and isinstance(data[0], list) \
|
|
393
|
+
and (not data[0] or not isinstance(data[0][0], list)):
|
|
394
|
+
return _gauss_jordan_inv(data)
|
|
395
|
+
return [_inv_nested(sub) for sub in data]
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def _solve_nested(a, b):
|
|
399
|
+
"""对嵌套列表递归求解 Ax = b:最内两维视为矩阵,外层为批量维。"""
|
|
400
|
+
if isinstance(a, list) and a and isinstance(a[0], list):
|
|
401
|
+
if not a[0] or not isinstance(a[0][0], list):
|
|
402
|
+
try:
|
|
403
|
+
return _gauss_jordan_solve(a, b)
|
|
404
|
+
except LinAlgError:
|
|
405
|
+
return _solve_pinv(a, b)
|
|
406
|
+
return [_solve_nested(sa, sb) for sa, sb in zip(a, b)]
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _svd_jacobi(mat, full_matrices=True, compute_uv=True):
|
|
410
|
+
"""通用 SVD(单侧 Jacobi 旋转),支持任意 m×n、float/complex。
|
|
411
|
+
|
|
412
|
+
Rust 核心只覆盖 2×2,这里补齐一般形状,并实现 ``full_matrices`` /
|
|
413
|
+
``compute_uv`` 语义(与 一致:u 为 m×m(full)或 m×min(reduced),
|
|
414
|
+
vh 为 n×n(full)或 min×n(reduced),s 降序)。
|
|
415
|
+
"""
|
|
416
|
+
import math
|
|
417
|
+
|
|
418
|
+
m = len(mat)
|
|
419
|
+
n = len(mat[0]) if m else 0
|
|
420
|
+
k = min(m, n)
|
|
421
|
+
|
|
422
|
+
if m == 0 or n == 0:
|
|
423
|
+
from rsarray import ndarray
|
|
424
|
+
if not compute_uv:
|
|
425
|
+
return ndarray([])
|
|
426
|
+
if full_matrices:
|
|
427
|
+
u = [[1.0 if i == j else 0.0 for j in range(m)] for i in range(m)]
|
|
428
|
+
vh = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
|
|
429
|
+
else:
|
|
430
|
+
u = [[1.0 if i == j else 0.0 for j in range(k)] for i in range(m)]
|
|
431
|
+
vh = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(k)]
|
|
432
|
+
return (ndarray(u), ndarray([]), ndarray(vh))
|
|
433
|
+
|
|
434
|
+
is_complex = any(isinstance(v, complex) for row in mat for v in row)
|
|
435
|
+
conj = (lambda z: z.conjugate()) if is_complex else (lambda z: z)
|
|
436
|
+
|
|
437
|
+
transposed = m < n
|
|
438
|
+
if transposed:
|
|
439
|
+
work = [[mat[i][j] for i in range(m)] for j in range(n)]
|
|
440
|
+
mm, nn = n, m
|
|
441
|
+
else:
|
|
442
|
+
work = [list(row) for row in mat]
|
|
443
|
+
mm, nn = m, n
|
|
444
|
+
# work: mm×nn, mm >= nn. Column rotations are accumulated in V (nn×nn).
|
|
445
|
+
V = [[1.0 if i == j else 0.0 for j in range(nn)] for i in range(nn)]
|
|
446
|
+
|
|
447
|
+
def col_dot(p, q):
|
|
448
|
+
return sum(conj(work[i][p]) * work[i][q] for i in range(mm))
|
|
449
|
+
|
|
450
|
+
for _sweep in range(100):
|
|
451
|
+
off = 0.0
|
|
452
|
+
diag = [abs(col_dot(p, p)) for p in range(nn)]
|
|
453
|
+
for p in range(nn):
|
|
454
|
+
for q in range(p + 1, nn):
|
|
455
|
+
g = col_dot(p, q)
|
|
456
|
+
off += abs(g) * abs(g)
|
|
457
|
+
if off <= 1e-28 * sum(d * d for d in diag) + 1e-300:
|
|
458
|
+
break
|
|
459
|
+
for p in range(nn):
|
|
460
|
+
for q in range(p + 1, nn):
|
|
461
|
+
alpha = abs(col_dot(p, p))
|
|
462
|
+
beta = abs(col_dot(q, q))
|
|
463
|
+
gamma = col_dot(p, q)
|
|
464
|
+
ag = abs(gamma)
|
|
465
|
+
if ag <= 1e-15 * math.sqrt(alpha * beta):
|
|
466
|
+
continue
|
|
467
|
+
if is_complex and ag > 0.0:
|
|
468
|
+
# rotate column q so the cross term becomes |gamma|
|
|
469
|
+
phase = conj(gamma) / ag
|
|
470
|
+
if abs(phase) > 0.0:
|
|
471
|
+
for i in range(mm):
|
|
472
|
+
work[i][q] *= phase
|
|
473
|
+
for i in range(nn):
|
|
474
|
+
V[i][q] *= phase
|
|
475
|
+
gamma = abs(gamma)
|
|
476
|
+
z = (beta - alpha) / (2.0 * gamma)
|
|
477
|
+
# small-magnitude root of t^2 - 2*z*t - 1 = 0, matching the
|
|
478
|
+
# rotation convention [cp,cq] -> [c*cp+s*cq, -s*cp+c*cq]
|
|
479
|
+
t = (-1.0 if z >= 0 else 1.0) / (abs(z) + math.sqrt(1.0 + z * z))
|
|
480
|
+
c = 1.0 / math.sqrt(1.0 + t * t)
|
|
481
|
+
s = t * c
|
|
482
|
+
for i in range(mm):
|
|
483
|
+
wp = work[i][p]
|
|
484
|
+
wq = work[i][q]
|
|
485
|
+
work[i][p] = c * wp + s * wq
|
|
486
|
+
work[i][q] = -s * wp + c * wq
|
|
487
|
+
for i in range(nn):
|
|
488
|
+
vp = V[i][p]
|
|
489
|
+
vq = V[i][q]
|
|
490
|
+
V[i][p] = c * vp + s * vq
|
|
491
|
+
V[i][q] = -s * vp + c * vq
|
|
492
|
+
|
|
493
|
+
sig = [math.sqrt(abs(col_dot(p, p))) for p in range(nn)]
|
|
494
|
+
order = sorted(range(nn), key=lambda p: -sig[p])
|
|
495
|
+
sig = [sig[p] for p in order]
|
|
496
|
+
U = [[0.0] * nn for _ in range(mm)]
|
|
497
|
+
smax = sig[0] if sig else 0.0
|
|
498
|
+
for new_p, old_p in enumerate(order):
|
|
499
|
+
sp = sig[new_p]
|
|
500
|
+
if sp > 1e-15 * smax:
|
|
501
|
+
for i in range(mm):
|
|
502
|
+
U[i][new_p] = work[i][old_p] / sp
|
|
503
|
+
Vh = [[conj(V[j][order[i]]) for j in range(nn)] for i in range(nn)]
|
|
504
|
+
|
|
505
|
+
def _complete_orthonormal(cols, mm, ncols):
|
|
506
|
+
"""把 ncols 个正交列扩展为 mm 列正交基(Gram-Schmidt on e_i)。"""
|
|
507
|
+
basis = [list(col) for col in cols] # list of columns
|
|
508
|
+
for i in range(mm):
|
|
509
|
+
e = [1.0 if r == i else 0.0 for r in range(mm)]
|
|
510
|
+
for b in basis:
|
|
511
|
+
proj = sum(conj(b[r]) * e[r] for r in range(mm))
|
|
512
|
+
e = [e[r] - proj * b[r] for r in range(mm)]
|
|
513
|
+
ne = math.sqrt(sum(abs(x) ** 2 for x in e))
|
|
514
|
+
if ne < 1e-8:
|
|
515
|
+
continue
|
|
516
|
+
basis.append([x / ne for x in e])
|
|
517
|
+
if len(basis) == mm:
|
|
518
|
+
break
|
|
519
|
+
return basis
|
|
520
|
+
|
|
521
|
+
# rows are nn long; pad to mm so extra columns can be filled and the
|
|
522
|
+
# transposed branch can index U[j][i] for i in range(mm)
|
|
523
|
+
U = [row + [0.0] * (mm - len(row)) for row in U]
|
|
524
|
+
if full_matrices and mm > nn:
|
|
525
|
+
extra = _complete_orthonormal(
|
|
526
|
+
[[U[i][p] for i in range(mm)] for p in range(nn)], mm, nn)
|
|
527
|
+
for col_idx in range(nn, len(extra)):
|
|
528
|
+
col = extra[col_idx]
|
|
529
|
+
for i in range(mm):
|
|
530
|
+
U[i][col_idx] = col[i]
|
|
531
|
+
|
|
532
|
+
if transposed:
|
|
533
|
+
# B = A^T = U_b Σ Vh_b => A = Vh_b^T Σ U_b^T (plain transposes)
|
|
534
|
+
u_out = [[Vh[i][j] for i in range(nn)] for j in range(nn)]
|
|
535
|
+
vh_out = [[U[j][i] for j in range(mm)] for i in range(mm)]
|
|
536
|
+
else:
|
|
537
|
+
u_out = U
|
|
538
|
+
vh_out = Vh
|
|
539
|
+
|
|
540
|
+
if not compute_uv:
|
|
541
|
+
from rsarray import ndarray
|
|
542
|
+
return ndarray(sig)
|
|
543
|
+
|
|
544
|
+
if not full_matrices:
|
|
545
|
+
u_out = [row[:k] for row in u_out]
|
|
546
|
+
vh_out = vh_out[:k]
|
|
547
|
+
|
|
548
|
+
from rsarray import ndarray
|
|
549
|
+
return (ndarray(u_out), ndarray(sig), ndarray(vh_out))
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def _norm_out_dtype(dt):
|
|
553
|
+
"""norm 结果 dtype:inexact → 对应实 dtype;int/bool/其它 → float64。"""
|
|
554
|
+
if dt == 'complex64':
|
|
555
|
+
return 'float32'
|
|
556
|
+
if dt == 'complex128':
|
|
557
|
+
return 'float64'
|
|
558
|
+
if dt in ('float16', 'float32', 'float64'):
|
|
559
|
+
return dt
|
|
560
|
+
return 'float64'
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def _norm_vec(vals, ord):
|
|
564
|
+
"""一维向量范数(数组语义):None/2→L2,1→L1,-1→1/Σ1/|x|(含 0 元
|
|
565
|
+
inf 传播 → 0),0→非零计数,±inf→max/min,p>0→(Σ|x|^p)^{1/p},
|
|
566
|
+
p<0(p≠-1)→(Σ1/|x|^(-p))^{1/p}。"""
|
|
567
|
+
import math
|
|
568
|
+
|
|
569
|
+
if ord is None:
|
|
570
|
+
o = 2
|
|
571
|
+
elif isinstance(ord, str):
|
|
572
|
+
if ord == 'inf':
|
|
573
|
+
o = float('inf')
|
|
574
|
+
elif ord == '-inf':
|
|
575
|
+
o = float('-inf')
|
|
576
|
+
else:
|
|
577
|
+
raise ValueError("Invalid norm order for vector norm.")
|
|
578
|
+
elif isinstance(ord, bool):
|
|
579
|
+
o = int(ord)
|
|
580
|
+
elif isinstance(ord, (int, float)):
|
|
581
|
+
o = ord
|
|
582
|
+
else:
|
|
583
|
+
o = float(ord)
|
|
584
|
+
|
|
585
|
+
if not vals:
|
|
586
|
+
return 0.0 # 空向量:±inf 用 initial=0,其余范数空和为 0
|
|
587
|
+
absx = [abs(v) for v in vals]
|
|
588
|
+
if o == 2:
|
|
589
|
+
return math.sqrt(sum(a * a for a in absx))
|
|
590
|
+
if o == 1:
|
|
591
|
+
return sum(absx)
|
|
592
|
+
if o == 0:
|
|
593
|
+
return float(sum(1 for v in vals if v != 0))
|
|
594
|
+
if o == float('inf'):
|
|
595
|
+
return max(absx)
|
|
596
|
+
if o == float('-inf'):
|
|
597
|
+
return min(absx)
|
|
598
|
+
if o == -1:
|
|
599
|
+
s = 0.0
|
|
600
|
+
for a in absx:
|
|
601
|
+
s += (1.0 / a) if a != 0 else float('inf')
|
|
602
|
+
return 1.0 / s
|
|
603
|
+
if o < 0:
|
|
604
|
+
s = 0.0
|
|
605
|
+
for a in absx:
|
|
606
|
+
s += (1.0 / (a ** (-o))) if a != 0 else float('inf')
|
|
607
|
+
return s ** (1.0 / o)
|
|
608
|
+
return sum(a ** o for a in absx) ** (1.0 / o)
|
|
609
|
+
|
|
610
|
+
|
|
611
|
+
def _norm_mat(M, ord):
|
|
612
|
+
"""二维矩阵范数(数组语义):None→Frobenius,±1→列和 max/min,
|
|
613
|
+
±inf→行和 max/min,2/-2→最大/最小奇异值,'nuc'→核范数(奇异值和)。"""
|
|
614
|
+
import math
|
|
615
|
+
|
|
616
|
+
m = len(M)
|
|
617
|
+
n = len(M[0]) if m else 0
|
|
618
|
+
absM = [[abs(v) for v in row] for row in M]
|
|
619
|
+
if ord is None:
|
|
620
|
+
return math.sqrt(sum(v * v for row in absM for v in row))
|
|
621
|
+
if ord == 1 or ord == -1:
|
|
622
|
+
if n == 0:
|
|
623
|
+
return 0.0
|
|
624
|
+
colsums = [sum(absM[i][j] for i in range(m)) for j in range(n)]
|
|
625
|
+
return max(colsums) if ord == 1 else min(colsums)
|
|
626
|
+
if ord == float('inf') or ord == float('-inf'):
|
|
627
|
+
if m == 0:
|
|
628
|
+
return 0.0
|
|
629
|
+
rowsums = [sum(row) for row in absM]
|
|
630
|
+
return max(rowsums) if ord == float('inf') else min(rowsums)
|
|
631
|
+
if ord in (2, -2, 'nuc'):
|
|
632
|
+
svals = [float(abs(v)) for v in _svd_jacobi(M, False, False).tolist()]
|
|
633
|
+
if not svals:
|
|
634
|
+
return 0.0
|
|
635
|
+
if ord == 2:
|
|
636
|
+
return svals[0]
|
|
637
|
+
if ord == -2:
|
|
638
|
+
return svals[-1]
|
|
639
|
+
return sum(svals)
|
|
640
|
+
raise ValueError("Invalid norm order for matrix norm.")
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
class linalg_module:
|
|
644
|
+
"""线性代数模块 - 提供矩阵运算、求解、分解等功能。
|
|
645
|
+
|
|
646
|
+
【核心功能】
|
|
647
|
+
- dot/matmul: 矩阵乘法
|
|
648
|
+
- inv/pinv: 矩阵求逆和伪逆
|
|
649
|
+
- solve/lstsq: 线性方程组求解和最小二乘
|
|
650
|
+
- det/norm: 行列式和范数
|
|
651
|
+
- eig/eigvals: 特征值分解
|
|
652
|
+
- svd: 奇异值分解
|
|
653
|
+
|
|
654
|
+
【性能特点】
|
|
655
|
+
- 核心运算由Rust实现,性能接近原生
|
|
656
|
+
- 支持复数矩阵运算
|
|
657
|
+
- 支持批量矩阵操作(3D及以上)
|
|
658
|
+
|
|
659
|
+
【线程安全提示】
|
|
660
|
+
⚠️ 本模块的函数在多线程环境下需要注意:
|
|
661
|
+
1. 读取操作是线程安全的
|
|
662
|
+
2. 写入操作需要外部加锁
|
|
663
|
+
3. 推荐使用copy()创建独立副本再共享
|
|
664
|
+
|
|
665
|
+
【使用示例】
|
|
666
|
+
>>> import rsarray as np
|
|
667
|
+
>>> # 矩阵乘法
|
|
668
|
+
>>> A = np.array([[1, 2], [3, 4]])
|
|
669
|
+
>>> B = np.array([[5, 6], [7, 8]])
|
|
670
|
+
>>> np.linalg.matmul(A, B)
|
|
671
|
+
array([[19., 22.],
|
|
672
|
+
[43., 50.]])
|
|
673
|
+
|
|
674
|
+
>>> # 矩阵求逆
|
|
675
|
+
>>> A_inv = np.linalg.inv(A)
|
|
676
|
+
>>> A @ A_inv # 应该接近单位矩阵
|
|
677
|
+
array([[1., 0.],
|
|
678
|
+
[0., 1.]])
|
|
679
|
+
|
|
680
|
+
>>> # 解线性方程组
|
|
681
|
+
>>> b = np.array([1, 2])
|
|
682
|
+
>>> x = np.linalg.solve(A, b)
|
|
683
|
+
>>> A @ x # 应该等于b
|
|
684
|
+
array([1., 2.])
|
|
685
|
+
"""
|
|
686
|
+
|
|
687
|
+
LinAlgError = LinAlgError
|
|
688
|
+
|
|
689
|
+
@staticmethod
|
|
690
|
+
def dot(a, b):
|
|
691
|
+
"""计算两个数组的点积(内积)。
|
|
692
|
+
|
|
693
|
+
【使用示例】
|
|
694
|
+
>>> import rsarray as np
|
|
695
|
+
>>> # 向量内积
|
|
696
|
+
>>> v1 = np.array([1, 2, 3])
|
|
697
|
+
>>> v2 = np.array([4, 5, 6])
|
|
698
|
+
>>> np.linalg.dot(v1, v2) # 1*4 + 2*5 + 3*6 = 32
|
|
699
|
+
32.0
|
|
700
|
+
|
|
701
|
+
>>> # 矩阵乘法
|
|
702
|
+
>>> A = np.array([[1, 2], [3, 4]])
|
|
703
|
+
>>> B = np.array([[5, 6], [7, 8]])
|
|
704
|
+
>>> np.linalg.dot(A, B) # 等价于 A @ B
|
|
705
|
+
array([[19., 22.],
|
|
706
|
+
[43., 50.]])
|
|
707
|
+
|
|
708
|
+
>>> # 高维点积
|
|
709
|
+
>>> T = np.random.rand(2, 3, 4)
|
|
710
|
+
>>> V = np.random.rand(4)
|
|
711
|
+
>>> result = np.linalg.dot(T, V) # shape: (2, 3)
|
|
712
|
+
|
|
713
|
+
【参数说明】
|
|
714
|
+
a, b: array_like
|
|
715
|
+
输入数组,可以是向量、矩阵或高维张量
|
|
716
|
+
- 一维:计算内积
|
|
717
|
+
- 二维:计算矩阵乘法
|
|
718
|
+
- 更高维:按规则进行张量收缩
|
|
719
|
+
|
|
720
|
+
【返回值】
|
|
721
|
+
标量或数组:
|
|
722
|
+
- 两个向量:返回标量(内积)
|
|
723
|
+
- 矩阵:返回矩阵
|
|
724
|
+
- 高维:返回张量
|
|
725
|
+
|
|
726
|
+
【注意事项】
|
|
727
|
+
- 与matmul的区别:dot对高维数组的处理规则更灵活
|
|
728
|
+
- 复数数组:支持复数运算
|
|
729
|
+
- 性能:对于简单矩阵乘法,推荐使用matmul
|
|
730
|
+
"""
|
|
731
|
+
from rsarray import ndarray
|
|
732
|
+
|
|
733
|
+
def _to_arr(z):
|
|
734
|
+
if hasattr(z, '_array'):
|
|
735
|
+
return z
|
|
736
|
+
if isinstance(z, (list, tuple)):
|
|
737
|
+
return ndarray(z)
|
|
738
|
+
if hasattr(z, '__iter__') and not isinstance(z, (str, bytes)):
|
|
739
|
+
# .flat 等迭代器参数(数组语义:dot 接受可迭代对象)
|
|
740
|
+
return ndarray(list(z))
|
|
741
|
+
return ndarray(z)
|
|
742
|
+
|
|
743
|
+
a_arr = _to_arr(a)
|
|
744
|
+
b_arr = _to_arr(b)
|
|
745
|
+
a_dtype = getattr(a_arr, '_dtype', 'float64')
|
|
746
|
+
b_dtype = getattr(b_arr, '_dtype', 'float64')
|
|
747
|
+
# f32 同样不走 Rust dot:Rust 侧 32 位缓冲在连续调用后可能
|
|
748
|
+
# 读到脏状态(实测 f32 2x2 dot 返回全 0),Python 路径无此问题
|
|
749
|
+
if _is_complex_arr(a_arr) or _is_complex_arr(b_arr) \
|
|
750
|
+
or a_dtype == 'float32' or b_dtype == 'float32':
|
|
751
|
+
res = _dot_nested(a_arr.tolist(), len(a_arr.shape), b_arr.tolist(), len(b_arr.shape))
|
|
752
|
+
out = ndarray(res) if isinstance(res, list) else res
|
|
753
|
+
# Python 列表推断出 c128/f64:按提升规则还原位宽
|
|
754
|
+
if isinstance(out, ndarray):
|
|
755
|
+
out = out.astype(_dot_res_dtype(a_dtype, b_dtype))
|
|
756
|
+
return out
|
|
757
|
+
try:
|
|
758
|
+
result = _core.linalg.dot(a_arr._array, b_arr._array)
|
|
759
|
+
except ValueError:
|
|
760
|
+
# 回退:a 为 N-D、b 为 1-D 时按 数组语义沿 a 末轴收缩
|
|
761
|
+
if b_arr.ndim == 1 and a_arr.ndim >= 1 and a_arr.shape[-1] == b_arr.shape[0]:
|
|
762
|
+
lead = tuple(a_arr.shape[:-1])
|
|
763
|
+
a2 = a_arr.reshape((-1, a_arr.shape[-1]))
|
|
764
|
+
result = _core.linalg.dot(a2._array, b_arr._array)
|
|
765
|
+
out = ndarray._wrap(result, _dtype=_dot_res_dtype(a_dtype, b_dtype))
|
|
766
|
+
return out.reshape(lead) if lead else out
|
|
767
|
+
raise
|
|
768
|
+
return ndarray._wrap(result, _dtype=_dot_res_dtype(a_dtype, b_dtype))
|
|
769
|
+
|
|
770
|
+
@staticmethod
|
|
771
|
+
def vdot(a, b):
|
|
772
|
+
"""计算两个向量的点积(展开为一维)。"""
|
|
773
|
+
result = _core.linalg.vdot(_ensure(a), _ensure(b))
|
|
774
|
+
return _round_float(result)
|
|
775
|
+
|
|
776
|
+
@staticmethod
|
|
777
|
+
def inner(a, b):
|
|
778
|
+
"""计算两个数组的内积。"""
|
|
779
|
+
from rsarray import ndarray
|
|
780
|
+
result = _core.linalg.inner(_ensure(a), _ensure(b))
|
|
781
|
+
a_dtype = getattr(a, '_dtype', 'float64')
|
|
782
|
+
b_dtype = getattr(b, '_dtype', 'float64')
|
|
783
|
+
if a_dtype in ('float64', 'float32', 'float16') or b_dtype in ('float64', 'float32', 'float16'):
|
|
784
|
+
return ndarray._wrap(result, _dtype='float64')
|
|
785
|
+
return ndarray._wrap(result, _dtype='int64')
|
|
786
|
+
|
|
787
|
+
@staticmethod
|
|
788
|
+
def matmul(a, b):
|
|
789
|
+
"""计算两个数组的矩阵乘积。
|
|
790
|
+
|
|
791
|
+
【使用示例】
|
|
792
|
+
>>> import rsarray as np
|
|
793
|
+
>>> # 基本矩阵乘法
|
|
794
|
+
>>> A = np.array([[1, 2], [3, 4]])
|
|
795
|
+
>>> B = np.array([[5, 6], [7, 8]])
|
|
796
|
+
>>> np.linalg.matmul(A, B)
|
|
797
|
+
array([[19., 22.],
|
|
798
|
+
[43., 50.]])
|
|
799
|
+
|
|
800
|
+
>>> # 批量矩阵乘法
|
|
801
|
+
>>> batch_A = np.random.rand(5, 3, 4) # 5个 3x4 矩阵
|
|
802
|
+
>>> batch_B = np.random.rand(5, 4, 6) # 5个 4x6 矩阵
|
|
803
|
+
>>> result = np.linalg.matmul(batch_A, batch_B)
|
|
804
|
+
>>> result.shape # (5, 3, 6)
|
|
805
|
+
(5, 3, 6)
|
|
806
|
+
|
|
807
|
+
>>> # 广播矩阵乘法
|
|
808
|
+
>>> A = np.random.rand(3, 4) # 单个矩阵
|
|
809
|
+
>>> batch_B = np.random.rand(5, 4, 6) # 5个矩阵
|
|
810
|
+
>>> result = np.linalg.matmul(A, batch_B)
|
|
811
|
+
>>> result.shape # (5, 3, 6)
|
|
812
|
+
(5, 3, 6)
|
|
813
|
+
|
|
814
|
+
【参数说明】
|
|
815
|
+
a, b: array_like
|
|
816
|
+
输入数组,必须满足矩阵乘法的形状要求:
|
|
817
|
+
- 最后两个维度必须满足矩阵乘法规则
|
|
818
|
+
- 前面的维度进行广播
|
|
819
|
+
|
|
820
|
+
【与dot的区别】
|
|
821
|
+
- matmul不支持标量相乘
|
|
822
|
+
- matmul的广播规则更严格
|
|
823
|
+
- 批量操作时matmul语义更清晰
|
|
824
|
+
- 推荐用于矩阵乘法场景
|
|
825
|
+
|
|
826
|
+
【性能提示】
|
|
827
|
+
- 本函数由Rust实现,性能接近原生BLAS
|
|
828
|
+
- 大型矩阵会自动使用多线程(如支持)
|
|
829
|
+
- 批量操作比Python循环快很多
|
|
830
|
+
"""
|
|
831
|
+
from rsarray import _broadcast_shape, ndarray, zeros
|
|
832
|
+
a_arr = a if hasattr(a, '_array') else ndarray(a)
|
|
833
|
+
b_arr = b if hasattr(b, '_array') else ndarray(b)
|
|
834
|
+
# 空维快捷路径:k/m/n 任一为 0 → 结果为广播形状的全零数组
|
|
835
|
+
# (Rust/_matmul_nested 对空形状不可靠),dtype 与实数路径一致
|
|
836
|
+
if (0 in a_arr.shape[-2:] + b_arr.shape[-2:]
|
|
837
|
+
and len(a_arr.shape) >= 2 and len(b_arr.shape) >= 2):
|
|
838
|
+
a_dt = getattr(a_arr, '_dtype', 'float64')
|
|
839
|
+
b_dt = getattr(b_arr, '_dtype', 'float64')
|
|
840
|
+
return zeros(_broadcast_shape(
|
|
841
|
+
a_arr.shape[:-2], b_arr.shape[:-2])
|
|
842
|
+
+ (a_arr.shape[-2], b_arr.shape[-1]),
|
|
843
|
+
dtype=_dot_res_dtype(a_dt, b_dt))
|
|
844
|
+
if _is_complex_arr(a_arr) or _is_complex_arr(b_arr):
|
|
845
|
+
res = _matmul_nested(a_arr.tolist(), len(a_arr.shape), b_arr.tolist(), len(b_arr.shape))
|
|
846
|
+
return _matmul_wrap(res, a_arr.shape, b_arr.shape, True,
|
|
847
|
+
getattr(a_arr, '_dtype', 'float64'),
|
|
848
|
+
getattr(b_arr, '_dtype', 'float64'))
|
|
849
|
+
try:
|
|
850
|
+
result = _core.linalg.matmul(_ensure(a), _ensure(b))
|
|
851
|
+
except ValueError:
|
|
852
|
+
# stacked/broadcast (>2-d):Rust 只覆盖 2-d → 纯 Python 回退
|
|
853
|
+
res = _matmul_nested(a_arr.tolist(), len(a_arr.shape),
|
|
854
|
+
b_arr.tolist(), len(b_arr.shape))
|
|
855
|
+
return _matmul_wrap(res, a_arr.shape, b_arr.shape, False,
|
|
856
|
+
getattr(a_arr, '_dtype', 'float64'),
|
|
857
|
+
getattr(b_arr, '_dtype', 'float64'))
|
|
858
|
+
a_dtype = getattr(a, '_dtype', 'float64')
|
|
859
|
+
b_dtype = getattr(b, '_dtype', 'float64')
|
|
860
|
+
if a_dtype in ('float64', 'float32', 'float16') or b_dtype in ('float64', 'float32', 'float16'):
|
|
861
|
+
return ndarray._wrap(result, _dtype=_dot_res_dtype(a_dtype, b_dtype))
|
|
862
|
+
return ndarray._wrap(result, _dtype='int64')
|
|
863
|
+
|
|
864
|
+
@staticmethod
|
|
865
|
+
def inv(a):
|
|
866
|
+
"""计算矩阵的逆。
|
|
867
|
+
|
|
868
|
+
【使用示例】
|
|
869
|
+
>>> import rsarray as np
|
|
870
|
+
>>> # 单个矩阵求逆
|
|
871
|
+
>>> A = np.array([[1, 2], [3, 4]])
|
|
872
|
+
>>> A_inv = np.linalg.inv(A)
|
|
873
|
+
>>> A @ A_inv # 应该接近单位矩阵
|
|
874
|
+
array([[1., 0.],
|
|
875
|
+
[0., 1.]])
|
|
876
|
+
|
|
877
|
+
>>> # 批量求逆
|
|
878
|
+
>>> batch = np.random.rand(3, 4, 4) # 3个 4x4 矩阵
|
|
879
|
+
>>> batch_inv = np.linalg.inv(batch)
|
|
880
|
+
>>> batch_inv.shape
|
|
881
|
+
(3, 4, 4)
|
|
882
|
+
|
|
883
|
+
>>> # 复数矩阵求逆
|
|
884
|
+
>>> C = np.array([[2+1j, 1-1j], [1+1j, 3+2j]])
|
|
885
|
+
>>> C_inv = np.linalg.inv(C)
|
|
886
|
+
|
|
887
|
+
【参数说明】
|
|
888
|
+
a: array_like
|
|
889
|
+
方阵或方阵堆栈(shape为(..., N, N))
|
|
890
|
+
矩阵必须可逆(非奇异)
|
|
891
|
+
|
|
892
|
+
【返回值】
|
|
893
|
+
数组,形状与输入相同,为逆矩阵
|
|
894
|
+
|
|
895
|
+
【异常】
|
|
896
|
+
LinAlgError: 矩阵奇异(不可逆)
|
|
897
|
+
|
|
898
|
+
【性能提示】
|
|
899
|
+
- 单个矩阵:由Rust BLAS实现,高性能
|
|
900
|
+
- 批量矩阵:使用rayon并行,充分利用多核
|
|
901
|
+
- 大矩阵建议使用pinv(伪逆)更稳定
|
|
902
|
+
|
|
903
|
+
【注意事项】
|
|
904
|
+
- 输入必须是方阵
|
|
905
|
+
- 对于病态矩阵,可能数值不稳定
|
|
906
|
+
- 建议先用det()检查是否接近奇异
|
|
907
|
+
"""
|
|
908
|
+
from rsarray import ndarray
|
|
909
|
+
from ._pylinalg import _common_type, _stacked_2d
|
|
910
|
+
|
|
911
|
+
a_arr = a if hasattr(a, '_array') else ndarray(a)
|
|
912
|
+
shape = tuple(a_arr.shape)
|
|
913
|
+
if len(shape) < 2 or shape[-2] != shape[-1]:
|
|
914
|
+
raise LinAlgError(
|
|
915
|
+
"inv: last 2 dimensions of the array must be square")
|
|
916
|
+
res_dt = _common_type(getattr(a_arr, '_dtype', 'float64'))[1]
|
|
917
|
+
n = shape[-1]
|
|
918
|
+
|
|
919
|
+
def _as_result(arr):
|
|
920
|
+
# 结果保留输入的 ndarray 子类(数组语义)
|
|
921
|
+
at = type(a_arr)
|
|
922
|
+
if at is not ndarray and isinstance(a_arr, ndarray):
|
|
923
|
+
return at(arr)
|
|
924
|
+
return arr
|
|
925
|
+
|
|
926
|
+
if n == 0:
|
|
927
|
+
return _as_result(ndarray([]).astype(res_dt).reshape(shape))
|
|
928
|
+
if len(shape) == 2:
|
|
929
|
+
# Rust 快路径仅 2x2/3x3 实输入;1x1/大尺寸/复数走纯 Python
|
|
930
|
+
# 高斯-约当(列主元)。
|
|
931
|
+
if not _is_complex_arr(a_arr) and n in (2, 3):
|
|
932
|
+
try:
|
|
933
|
+
return _as_result(
|
|
934
|
+
_wrap(_core.linalg.inv(_ensure(a_arr))).astype(
|
|
935
|
+
res_dt))
|
|
936
|
+
except ValueError:
|
|
937
|
+
pass
|
|
938
|
+
return _as_result(
|
|
939
|
+
ndarray(_gauss_jordan_inv(a_arr.tolist())).astype(res_dt))
|
|
940
|
+
lead, subs = _stacked_2d(a_arr)
|
|
941
|
+
out = [_gauss_jordan_inv(sub.tolist()) for sub in subs]
|
|
942
|
+
return _as_result(ndarray(out).astype(res_dt).reshape(shape))
|
|
943
|
+
|
|
944
|
+
@staticmethod
|
|
945
|
+
def det(a):
|
|
946
|
+
"""计算矩阵的行列式(2.x 语义)。
|
|
947
|
+
|
|
948
|
+
2-d 返回保输入 dtype 的 0-d 数组(整型输入 → float64);
|
|
949
|
+
stacked (...,M,M) 返回 (lead...) 数组;空矩阵 (0×0) 行列式为 1;
|
|
950
|
+
全部尺寸走纯 Python LU(``_py_det``,列主元,复数支持)。
|
|
951
|
+
"""
|
|
952
|
+
from rsarray import (ndarray, float32, float64, complex64,
|
|
953
|
+
complex128)
|
|
954
|
+
from ._pylinalg import _common_type, _py_det, _stacked_2d
|
|
955
|
+
_SCALAR = {'float32': float32, 'float64': float64,
|
|
956
|
+
'complex64': complex64, 'complex128': complex128}
|
|
957
|
+
|
|
958
|
+
a_arr = a if hasattr(a, '_array') else ndarray(a)
|
|
959
|
+
shape = tuple(a_arr.shape)
|
|
960
|
+
if len(shape) < 2 or shape[-2] != shape[-1]:
|
|
961
|
+
raise ValueError("det requires a square matrix")
|
|
962
|
+
_, res_dt = _common_type(getattr(a_arr, '_dtype', 'float64'))
|
|
963
|
+
if len(shape) == 2:
|
|
964
|
+
# 2-d 返回标量(dtype 随输入;整型输入 → float64 标量)
|
|
965
|
+
return _SCALAR[res_dt](_py_det(a_arr.tolist()))
|
|
966
|
+
lead, subs = _stacked_2d(a_arr)
|
|
967
|
+
vals = [_py_det(sub.tolist()) for sub in subs]
|
|
968
|
+
return ndarray(vals).astype(res_dt).reshape(lead)
|
|
969
|
+
|
|
970
|
+
@staticmethod
|
|
971
|
+
def norm(x, ord=None, axis=None, keepdims=False):
|
|
972
|
+
"""向量或矩阵范数(2.x 语义)。
|
|
973
|
+
|
|
974
|
+
向量范数(1-d / axis 为整数):None/2→L2、1→L1、-1、0、±inf、
|
|
975
|
+
任意 p;矩阵范数(2-d axis=None / axis 为 2-元组):None/'fro'→
|
|
976
|
+
Frobenius、±1→列和 max/min、±inf→行和 max/min、2/-2→最大/最小
|
|
977
|
+
奇异值、'nuc'→核范数。返回输入实 dtype(inexact)或 float64
|
|
978
|
+
(整型)的 0-d 数组;axis/keepdims 时返回相应形状数组。
|
|
979
|
+
"""
|
|
980
|
+
import itertools
|
|
981
|
+
import rsarray as _np
|
|
982
|
+
from ..exceptions import AxisError
|
|
983
|
+
|
|
984
|
+
x_arr = x if hasattr(x, '_array') else _np.asarray(x)
|
|
985
|
+
ndim = x_arr.ndim
|
|
986
|
+
shape = x_arr.shape
|
|
987
|
+
|
|
988
|
+
# ---- 归一化与校验 axis ----
|
|
989
|
+
if axis is None:
|
|
990
|
+
axis_kind = 'none'
|
|
991
|
+
axes = None
|
|
992
|
+
elif isinstance(axis, (tuple, list)):
|
|
993
|
+
if len(axis) != 2:
|
|
994
|
+
raise ValueError("axis must be an integer or a 2-tuple")
|
|
995
|
+
a0, a1 = int(axis[0]), int(axis[1])
|
|
996
|
+
a0n = a0 + ndim if a0 < 0 else a0
|
|
997
|
+
a1n = a1 + ndim if a1 < 0 else a1
|
|
998
|
+
if a0n < 0 or a0n >= ndim or a1n < 0 or a1n >= ndim:
|
|
999
|
+
raise AxisError(
|
|
1000
|
+
"axis out of bounds for array of dimension %d" % ndim)
|
|
1001
|
+
if a0n == a1n:
|
|
1002
|
+
raise ValueError("axis %d is repeated" % a0n)
|
|
1003
|
+
axis_kind = 'matrix'
|
|
1004
|
+
axes = (a0n, a1n)
|
|
1005
|
+
else:
|
|
1006
|
+
axn = int(axis)
|
|
1007
|
+
axn = axn + ndim if axn < 0 else axn
|
|
1008
|
+
if axn < 0 or axn >= ndim:
|
|
1009
|
+
raise AxisError(
|
|
1010
|
+
"axis out of bounds for array of dimension %d" % ndim)
|
|
1011
|
+
axis_kind = 'vector'
|
|
1012
|
+
axes = (axn,)
|
|
1013
|
+
|
|
1014
|
+
# ---- 上下文与 ord 校验 ----
|
|
1015
|
+
if axis_kind == 'none':
|
|
1016
|
+
ctx = 'vector' if ndim == 1 else ('matrix' if ndim == 2
|
|
1017
|
+
else 'flat')
|
|
1018
|
+
elif axis_kind == 'vector':
|
|
1019
|
+
ctx = 'vector'
|
|
1020
|
+
else:
|
|
1021
|
+
ctx = 'matrix'
|
|
1022
|
+
|
|
1023
|
+
if ord in ('fro', 'nuc') and ctx != 'matrix':
|
|
1024
|
+
raise ValueError("Invalid norm order for matrix norm.")
|
|
1025
|
+
if ord == 'fro':
|
|
1026
|
+
ord = None # Frobenius ≡ 矩阵范数 ord None
|
|
1027
|
+
if ctx == 'matrix' and ord not in (None, 1, -1, 2, -2,
|
|
1028
|
+
float('inf'), float('-inf'),
|
|
1029
|
+
'nuc'):
|
|
1030
|
+
raise ValueError("Invalid norm order for matrix norm.")
|
|
1031
|
+
|
|
1032
|
+
out_dt = _norm_out_dtype(getattr(x_arr, '_dtype', 'float64'))
|
|
1033
|
+
|
|
1034
|
+
def _scalar(res):
|
|
1035
|
+
a = _np.asarray(res).astype(out_dt)
|
|
1036
|
+
if keepdims and axis_kind == 'none':
|
|
1037
|
+
a = a.reshape((1,) * ndim)
|
|
1038
|
+
return a
|
|
1039
|
+
|
|
1040
|
+
if ctx == 'vector' and axis_kind == 'none':
|
|
1041
|
+
return _scalar(_norm_vec(x_arr.tolist(), ord))
|
|
1042
|
+
if ctx == 'matrix' and axis_kind == 'none':
|
|
1043
|
+
return _scalar(_norm_mat(x_arr.tolist(), ord))
|
|
1044
|
+
if ctx == 'flat':
|
|
1045
|
+
# ndim>2 且 axis=None:全元素逐元素范数
|
|
1046
|
+
flat = x_arr.reshape((x_arr.size,)).tolist()
|
|
1047
|
+
return _scalar(_norm_vec(flat, ord))
|
|
1048
|
+
|
|
1049
|
+
# axis 非 None:按 batch 维循环
|
|
1050
|
+
reduced = set(axes)
|
|
1051
|
+
batch_axes = [i for i in range(ndim) if i not in reduced]
|
|
1052
|
+
batch_shape = tuple(shape[i] for i in batch_axes)
|
|
1053
|
+
ranges = [range(shape[i]) for i in batch_axes]
|
|
1054
|
+
vals = []
|
|
1055
|
+
for combo in itertools.product(*ranges):
|
|
1056
|
+
idx = []
|
|
1057
|
+
ci = 0
|
|
1058
|
+
for ax in range(ndim):
|
|
1059
|
+
if ax in reduced:
|
|
1060
|
+
idx.append(slice(None))
|
|
1061
|
+
else:
|
|
1062
|
+
idx.append(combo[ci])
|
|
1063
|
+
ci += 1
|
|
1064
|
+
sub = x_arr[tuple(idx)]
|
|
1065
|
+
if axis_kind == 'matrix':
|
|
1066
|
+
m = sub.tolist()
|
|
1067
|
+
if axes[0] > axes[1]:
|
|
1068
|
+
m = [list(r) for r in zip(*m)] # 转为 (row, col) 序
|
|
1069
|
+
vals.append(_norm_mat(m, ord))
|
|
1070
|
+
else:
|
|
1071
|
+
vals.append(_norm_vec(sub.tolist(), ord))
|
|
1072
|
+
|
|
1073
|
+
if not batch_axes:
|
|
1074
|
+
return _scalar(vals[0])
|
|
1075
|
+
out = _np.asarray(vals).reshape(batch_shape)
|
|
1076
|
+
if keepdims:
|
|
1077
|
+
full = tuple(1 if ax in reduced else shape[ax]
|
|
1078
|
+
for ax in range(ndim))
|
|
1079
|
+
out = out.reshape(full)
|
|
1080
|
+
return out.astype(out_dt)
|
|
1081
|
+
|
|
1082
|
+
@staticmethod
|
|
1083
|
+
def vector_norm(x, /, *, ord=None, axis=None, keepdims=False):
|
|
1084
|
+
"""Array-API compatible vector norm (linalg.vector_norm)."""
|
|
1085
|
+
import rsarray as _np
|
|
1086
|
+
x_arr = x if hasattr(x, '_array') else _np.array(x)
|
|
1087
|
+
if x_arr.size == 0:
|
|
1088
|
+
# 数组语义:ord=±inf 用 initial=0,其余范数空和为 0
|
|
1089
|
+
r = _np.asarray(0.0)
|
|
1090
|
+
if keepdims and axis is None:
|
|
1091
|
+
r = r.reshape((1,) * x_arr.ndim) if x_arr.ndim else r
|
|
1092
|
+
return r
|
|
1093
|
+
absx = _np.abs(x_arr)
|
|
1094
|
+
o = 2 if ord is None else ord
|
|
1095
|
+
if o == 1:
|
|
1096
|
+
return _np.sum(absx, axis=axis, keepdims=keepdims)
|
|
1097
|
+
if o in (float('inf'), 'inf'):
|
|
1098
|
+
return _np.max(absx, axis=axis, keepdims=keepdims)
|
|
1099
|
+
if o in (float('-inf'), '-inf'):
|
|
1100
|
+
return _np.min(absx, axis=axis, keepdims=keepdims)
|
|
1101
|
+
if o in (2, 2.0, 'fro'):
|
|
1102
|
+
return _np.sum(absx ** 2, axis=axis, keepdims=keepdims) ** 0.5
|
|
1103
|
+
return _np.sum(absx ** o, axis=axis, keepdims=keepdims) ** (1.0 / o)
|
|
1104
|
+
|
|
1105
|
+
@staticmethod
|
|
1106
|
+
def solve(a, b):
|
|
1107
|
+
"""求解线性方程组 ax = b(数组语义)。
|
|
1108
|
+
|
|
1109
|
+
a: (..., M, M) 方阵或堆栈;b: (M,) 或 (..., M, K)——b 的 lead
|
|
1110
|
+
维与 a 广播(b (M,) 对所有批次广播);x 形状同 b((M,) →
|
|
1111
|
+
(..., M));奇异矩阵抛 LinAlgError;dtype 随 a(整型 → float64)。
|
|
1112
|
+
"""
|
|
1113
|
+
from rsarray import ndarray
|
|
1114
|
+
from ._pylinalg import _common_type, _stacked_2d
|
|
1115
|
+
|
|
1116
|
+
a_arr = a if hasattr(a, '_array') else ndarray(a)
|
|
1117
|
+
b_arr = b if hasattr(b, '_array') else ndarray(b)
|
|
1118
|
+
a_shape = tuple(a_arr.shape)
|
|
1119
|
+
b_shape = tuple(b_arr.shape)
|
|
1120
|
+
if len(a_shape) < 2 or a_shape[-2] != a_shape[-1]:
|
|
1121
|
+
raise LinAlgError(
|
|
1122
|
+
"solve: last 2 dimensions of `a` must be square")
|
|
1123
|
+
m = a_shape[-1]
|
|
1124
|
+
# b 三种形态(gufunc (m,m),(m,n)->(m,n) 语义):
|
|
1125
|
+
# (m,) → 单向量,广播过 a 全部 lead;(m, k) → 单个矩阵(无
|
|
1126
|
+
# lead,广播过 a 全部 lead);(..., m, k) → lead 维与 a 广播。
|
|
1127
|
+
if len(b_shape) == 1:
|
|
1128
|
+
b_is_1d = True
|
|
1129
|
+
b_lead = ()
|
|
1130
|
+
k = 1
|
|
1131
|
+
core = b_shape[0]
|
|
1132
|
+
elif len(b_shape) == 2:
|
|
1133
|
+
b_is_1d = False
|
|
1134
|
+
b_lead = ()
|
|
1135
|
+
k = b_shape[1]
|
|
1136
|
+
core = b_shape[0]
|
|
1137
|
+
else:
|
|
1138
|
+
b_is_1d = False
|
|
1139
|
+
b_lead = b_shape[:-2]
|
|
1140
|
+
k = b_shape[-1]
|
|
1141
|
+
core = b_shape[-2]
|
|
1142
|
+
if core != m:
|
|
1143
|
+
raise ValueError(
|
|
1144
|
+
"solve: shape of `b` is incompatible with `a`")
|
|
1145
|
+
out_lead = list(a_shape[:-2])
|
|
1146
|
+
pad = len(b_lead) - len(out_lead)
|
|
1147
|
+
if pad > 0:
|
|
1148
|
+
out_lead = [1] * pad + out_lead
|
|
1149
|
+
for i, d in enumerate(b_lead):
|
|
1150
|
+
if out_lead[i] != d and out_lead[i] != 1 and d != 1:
|
|
1151
|
+
raise ValueError(
|
|
1152
|
+
"solve: shape of `b` is incompatible with `a`")
|
|
1153
|
+
out_lead[i] = max(out_lead[i], d)
|
|
1154
|
+
out_lead = tuple(out_lead)
|
|
1155
|
+
|
|
1156
|
+
res_dt = _common_type(getattr(a_arr, '_dtype', 'float64'))[1]
|
|
1157
|
+
# Rust 快路径:实数 2x2/3x3 且 b 为 2-d
|
|
1158
|
+
use_rust = (not _is_complex_arr(a_arr)
|
|
1159
|
+
and not _is_complex_arr(b_arr) and m in (2, 3)
|
|
1160
|
+
and not b_is_1d)
|
|
1161
|
+
|
|
1162
|
+
def _solve_one(A, B, b1d):
|
|
1163
|
+
if use_rust:
|
|
1164
|
+
try:
|
|
1165
|
+
return _wrap(_core.linalg.solve(
|
|
1166
|
+
_ensure(A), _ensure(B))).tolist()
|
|
1167
|
+
except ValueError:
|
|
1168
|
+
pass
|
|
1169
|
+
b_rows = B.tolist()
|
|
1170
|
+
if b1d:
|
|
1171
|
+
b_rows = [[v] for v in b_rows]
|
|
1172
|
+
try:
|
|
1173
|
+
return _gauss_jordan_solve(A.tolist(), b_rows)
|
|
1174
|
+
except LinAlgError:
|
|
1175
|
+
return _solve_pinv(A.tolist(), b_rows)
|
|
1176
|
+
|
|
1177
|
+
def _as_result(arr):
|
|
1178
|
+
# 结果保留 b 的 ndarray 子类(数组语义)
|
|
1179
|
+
bt = type(b_arr)
|
|
1180
|
+
if bt is not ndarray and isinstance(b_arr, ndarray):
|
|
1181
|
+
return bt(arr)
|
|
1182
|
+
return arr
|
|
1183
|
+
|
|
1184
|
+
if k == 0 and not b_is_1d:
|
|
1185
|
+
# b (..., m, 0):零个右端列,无需解算,直接给空结构
|
|
1186
|
+
if len(a_shape) == 2:
|
|
1187
|
+
rows = [[] for _ in range(m)]
|
|
1188
|
+
return _as_result(ndarray(rows).astype(res_dt).reshape(
|
|
1189
|
+
(m, 0)))
|
|
1190
|
+
lead, subs = _stacked_2d(a_arr)
|
|
1191
|
+
rows = [[[] for _ in range(m)] for _ in subs]
|
|
1192
|
+
return _as_result(ndarray(rows).astype(res_dt).reshape(
|
|
1193
|
+
out_lead + (m, 0)))
|
|
1194
|
+
|
|
1195
|
+
if m == 0:
|
|
1196
|
+
# 空矩阵:不解算,直接给形状 out_lead + (0, k)
|
|
1197
|
+
target = out_lead + (0,) if b_is_1d else out_lead + (0, k)
|
|
1198
|
+
return _as_result(ndarray([]).astype(res_dt).reshape(target))
|
|
1199
|
+
|
|
1200
|
+
if len(a_shape) == 2:
|
|
1201
|
+
rows = _solve_one(a_arr, b_arr, b_is_1d)
|
|
1202
|
+
if b_is_1d:
|
|
1203
|
+
return _as_result(
|
|
1204
|
+
ndarray([r[0] for r in rows]).astype(res_dt))
|
|
1205
|
+
return _as_result(ndarray(rows).astype(res_dt))
|
|
1206
|
+
|
|
1207
|
+
# stacked: a (lead..., m, m);b (m,)/(m,k) 整体广播,
|
|
1208
|
+
# (..., m, k) 按 广播规则逐子矩阵取 b 的对应子块
|
|
1209
|
+
lead, subs = _stacked_2d(a_arr)
|
|
1210
|
+
b_lead_full = (1,) * (len(out_lead) - len(b_lead)) + b_lead
|
|
1211
|
+
|
|
1212
|
+
def _t_index(t, shape):
|
|
1213
|
+
idx = []
|
|
1214
|
+
for d in reversed(shape):
|
|
1215
|
+
idx.append(t % d)
|
|
1216
|
+
t //= d
|
|
1217
|
+
return list(reversed(idx))
|
|
1218
|
+
|
|
1219
|
+
a_lead = a_shape[:-2]
|
|
1220
|
+
a_lead_full = (1,) * (len(out_lead) - len(a_lead)) + a_lead
|
|
1221
|
+
b_flat = None
|
|
1222
|
+
if not (b_is_1d or len(b_shape) == 2):
|
|
1223
|
+
b_total = 1
|
|
1224
|
+
for d in b_lead:
|
|
1225
|
+
b_total *= d
|
|
1226
|
+
b_flat = b_arr.reshape((b_total,) + b_shape[-2:])
|
|
1227
|
+
total = 1
|
|
1228
|
+
for d in out_lead:
|
|
1229
|
+
total *= d
|
|
1230
|
+
out_rows = []
|
|
1231
|
+
for t in range(total):
|
|
1232
|
+
ti = _t_index(t, out_lead)
|
|
1233
|
+
ai = 0
|
|
1234
|
+
for d_a, i in zip(a_lead_full, ti):
|
|
1235
|
+
ai = ai * d_a + (i if d_a > 1 else 0)
|
|
1236
|
+
A = subs[ai]
|
|
1237
|
+
if b_flat is None:
|
|
1238
|
+
B = b_arr
|
|
1239
|
+
else:
|
|
1240
|
+
bi = 0
|
|
1241
|
+
for d_b, i in zip(b_lead_full, ti):
|
|
1242
|
+
bi = bi * d_b + (i if d_b > 1 else 0)
|
|
1243
|
+
B = b_flat[bi]
|
|
1244
|
+
out_rows.append(_solve_one(A, B, b_is_1d))
|
|
1245
|
+
if b_is_1d:
|
|
1246
|
+
flat = [r[0] for rows in out_rows for r in rows]
|
|
1247
|
+
return _as_result(ndarray(flat).astype(res_dt).reshape(
|
|
1248
|
+
out_lead + (m,)))
|
|
1249
|
+
return _as_result(ndarray(out_rows).astype(res_dt).reshape(
|
|
1250
|
+
out_lead + (m, k)))
|
|
1251
|
+
|
|
1252
|
+
@staticmethod
|
|
1253
|
+
def lstsq(a, b, rcond=None):
|
|
1254
|
+
"""最小二乘解 min ||a·x - b||₂(SVD 法,2.x 语义)。
|
|
1255
|
+
|
|
1256
|
+
返回 (x, residuals, rank, s):s 为降序奇异值;rank = 大于
|
|
1257
|
+
``rcond·s_max`` 的奇异值个数(rcond=None → 1e-15;rcond<0 → 机器
|
|
1258
|
+
精度,LAPACK 约定);residuals 为各列残差平方和(仅 rank==n 且
|
|
1259
|
+
m>n 时非空),实浮点 dtype;a/b 含 inf/nan 抛 LinAlgError;
|
|
1260
|
+
维度不匹配抛 LinAlgError("Incompatible dimensions")。
|
|
1261
|
+
"""
|
|
1262
|
+
import math
|
|
1263
|
+
from rsarray import ndarray
|
|
1264
|
+
from ._pylinalg import (_common_type, _real_dtype, _finfo_eps)
|
|
1265
|
+
|
|
1266
|
+
a_arr = a if hasattr(a, '_array') else ndarray(a)
|
|
1267
|
+
b_arr = b if hasattr(b, '_array') else ndarray(b)
|
|
1268
|
+
if len(a_arr.shape) != 2:
|
|
1269
|
+
raise LinAlgError("expected square matrix")
|
|
1270
|
+
m, n = a_arr.shape
|
|
1271
|
+
if len(b_arr.shape) not in (1, 2) or b_arr.shape[0] != m:
|
|
1272
|
+
raise LinAlgError("Incompatible dimensions")
|
|
1273
|
+
b_is_1d = len(b_arr.shape) == 1
|
|
1274
|
+
n_rhs = 1 if b_is_1d else b_arr.shape[1]
|
|
1275
|
+
|
|
1276
|
+
a_dt = getattr(a_arr, '_dtype', 'float64')
|
|
1277
|
+
res_dt = _common_type(a_dt)[1]
|
|
1278
|
+
s_dt = _real_dtype(res_dt)
|
|
1279
|
+
|
|
1280
|
+
a_rows = a_arr.tolist()
|
|
1281
|
+
b_rows = b_arr.tolist()
|
|
1282
|
+
if b_is_1d:
|
|
1283
|
+
b_rows = [[v] for v in b_rows]
|
|
1284
|
+
|
|
1285
|
+
def _scan_nonfinite(data):
|
|
1286
|
+
for row in data:
|
|
1287
|
+
if not isinstance(row, (list, tuple)):
|
|
1288
|
+
row = [row]
|
|
1289
|
+
for v in row:
|
|
1290
|
+
if isinstance(v, complex):
|
|
1291
|
+
r, i = v.real, v.imag
|
|
1292
|
+
else:
|
|
1293
|
+
r, i = float(v), 0.0
|
|
1294
|
+
if r != r or i != i or math.isinf(r) or math.isinf(i):
|
|
1295
|
+
raise LinAlgError(
|
|
1296
|
+
"Array must not contain infs or NaNs")
|
|
1297
|
+
|
|
1298
|
+
_scan_nonfinite(a_rows)
|
|
1299
|
+
_scan_nonfinite(b_rows)
|
|
1300
|
+
|
|
1301
|
+
u, s, vt = linalg_module.svd(a_arr, full_matrices=False)
|
|
1302
|
+
s_list = [float(abs(v)) for v in s.tolist()]
|
|
1303
|
+
|
|
1304
|
+
if rcond is None:
|
|
1305
|
+
rcond_val = 1.0e-15
|
|
1306
|
+
elif rcond < 0:
|
|
1307
|
+
rcond_val = _finfo_eps(s_dt)
|
|
1308
|
+
else:
|
|
1309
|
+
rcond_val = float(rcond)
|
|
1310
|
+
s_max = max(s_list) if s_list else 0.0
|
|
1311
|
+
cutoff = rcond_val * s_max
|
|
1312
|
+
rank = int(sum(1 for v in s_list if v > cutoff))
|
|
1313
|
+
|
|
1314
|
+
# x = Vh^H · diag(1/s_i) · U^H · b(s_i ≤ cutoff 置 0)
|
|
1315
|
+
k = min(m, n)
|
|
1316
|
+
u_rows = u.tolist() # m × k
|
|
1317
|
+
vh_rows = vt.tolist() # k × n
|
|
1318
|
+
|
|
1319
|
+
def _conj(z):
|
|
1320
|
+
return z.conjugate() if isinstance(z, complex) else z
|
|
1321
|
+
|
|
1322
|
+
s_inv = [(1.0 / v) if v > cutoff else 0.0 for v in s_list]
|
|
1323
|
+
x_rows = [[0.0] * n_rhs for _ in range(n)]
|
|
1324
|
+
for c in range(n_rhs):
|
|
1325
|
+
uhb = [0.0] * k
|
|
1326
|
+
for j in range(k):
|
|
1327
|
+
acc = 0
|
|
1328
|
+
for i in range(m):
|
|
1329
|
+
acc += _conj(u_rows[i][j]) * b_rows[i][c]
|
|
1330
|
+
uhb[j] = acc
|
|
1331
|
+
for i in range(n):
|
|
1332
|
+
acc = 0
|
|
1333
|
+
for j in range(k):
|
|
1334
|
+
acc += _conj(vh_rows[j][i]) * s_inv[j] * uhb[j]
|
|
1335
|
+
x_rows[i][c] = acc
|
|
1336
|
+
|
|
1337
|
+
if b_is_1d:
|
|
1338
|
+
x = ndarray([x_rows[i][0] for i in range(n)]).astype(res_dt)
|
|
1339
|
+
elif n == 0:
|
|
1340
|
+
x = ndarray([]).reshape((0, n_rhs)).astype(res_dt)
|
|
1341
|
+
else:
|
|
1342
|
+
x = ndarray(x_rows).astype(res_dt)
|
|
1343
|
+
|
|
1344
|
+
if m > n and rank == n and n_rhs > 0:
|
|
1345
|
+
res_vals = []
|
|
1346
|
+
for c in range(n_rhs):
|
|
1347
|
+
acc = 0.0
|
|
1348
|
+
for i in range(m):
|
|
1349
|
+
r = b_rows[i][c]
|
|
1350
|
+
for kk in range(n):
|
|
1351
|
+
r -= a_rows[i][kk] * x_rows[kk][c]
|
|
1352
|
+
acc += abs(r) ** 2
|
|
1353
|
+
res_vals.append(acc)
|
|
1354
|
+
res = ndarray(res_vals).astype(s_dt)
|
|
1355
|
+
else:
|
|
1356
|
+
res = ndarray([]).astype(s_dt)
|
|
1357
|
+
return (x, res, rank, ndarray(s_list).astype(s_dt))
|
|
1358
|
+
|
|
1359
|
+
@staticmethod
|
|
1360
|
+
def matrix_rank(a, tol=None, hermitian=False, *, rtol=None):
|
|
1361
|
+
"""矩阵秩(2.x 语义):2-d/1-d 返回 int;stacked (...,M,N)
|
|
1362
|
+
返回 intp 计数数组(rank = count(S > tol),tol 默认
|
|
1363
|
+
``S.max() * max(M,N) * eps``)。rtol 与 tol 互斥(2.0+)。"""
|
|
1364
|
+
from rsarray import ndarray
|
|
1365
|
+
from ._pylinalg import (_common_type, _real_dtype, _finfo_eps)
|
|
1366
|
+
|
|
1367
|
+
if tol is not None and rtol is not None:
|
|
1368
|
+
raise ValueError("`tol` and `rtol` can't be both set.")
|
|
1369
|
+
a_arr = a if hasattr(a, '_array') else ndarray(a)
|
|
1370
|
+
shape = a_arr.shape
|
|
1371
|
+
if len(shape) > 2:
|
|
1372
|
+
s = linalg_module.svd(a_arr, compute_uv=False, hermitian=hermitian)
|
|
1373
|
+
dt = getattr(a_arr, '_dtype', 'float64')
|
|
1374
|
+
try:
|
|
1375
|
+
s_dt = _real_dtype(_common_type(dt)[1])
|
|
1376
|
+
except TypeError:
|
|
1377
|
+
s_dt = 'float64'
|
|
1378
|
+
eps = _finfo_eps(s_dt)
|
|
1379
|
+
m, n = shape[-2], shape[-1]
|
|
1380
|
+
|
|
1381
|
+
def _count(vec, rtol_i=None):
|
|
1382
|
+
if tol is not None:
|
|
1383
|
+
t = tol
|
|
1384
|
+
elif rtol is not None:
|
|
1385
|
+
# 数组语义:tol = S.max() * rtol(rtol 可逐批次)
|
|
1386
|
+
_ri = rtol_i if rtol_i is not None else float(rtol)
|
|
1387
|
+
t = (max(vec) if vec else 0.0) * _ri
|
|
1388
|
+
else:
|
|
1389
|
+
t = (max(vec) * max(m, n) * eps if vec else 0.0)
|
|
1390
|
+
return sum(1 for v in vec if v > t)
|
|
1391
|
+
|
|
1392
|
+
# s 带完整 lead 形状((lead..., K)):先压成 2-d (total, K)
|
|
1393
|
+
# 逐行计数,再 reshape 回 lead 形状
|
|
1394
|
+
total = 1
|
|
1395
|
+
for d in shape[:-2]:
|
|
1396
|
+
total *= d
|
|
1397
|
+
s2 = s.reshape((total, min(m, n)))
|
|
1398
|
+
# rtol 支持标量或数组(2.0+:广播到批次形状,逐批次
|
|
1399
|
+
# tol = S.max() * rtol[i])
|
|
1400
|
+
rtols = None
|
|
1401
|
+
if rtol is not None:
|
|
1402
|
+
try:
|
|
1403
|
+
rtols = [float(rtol)] * total
|
|
1404
|
+
except (TypeError, ValueError):
|
|
1405
|
+
_rv = ndarray(rtol)
|
|
1406
|
+
_flat = _rv.reshape(total).tolist() \
|
|
1407
|
+
if _rv.size == total else \
|
|
1408
|
+
list(_rv.reshape((-1,)).tolist()) * (total // max(_rv.size, 1))
|
|
1409
|
+
if len(_flat) < total:
|
|
1410
|
+
_flat = (_flat * (total // len(_flat) + 1))[:total]
|
|
1411
|
+
rtols = [float(v) for v in _flat]
|
|
1412
|
+
if rtols is None:
|
|
1413
|
+
parts = [_count(v) for v in s2.tolist()]
|
|
1414
|
+
else:
|
|
1415
|
+
parts = [_count(v, r) for v, r in
|
|
1416
|
+
zip(s2.tolist(), rtols)]
|
|
1417
|
+
return ndarray(parts).reshape(shape[:-2]).astype('int64')
|
|
1418
|
+
rows = a_arr.tolist()
|
|
1419
|
+
if not isinstance(rows, list):
|
|
1420
|
+
return 0 if float(rows) == 0.0 else 1
|
|
1421
|
+
if not rows:
|
|
1422
|
+
return 0
|
|
1423
|
+
if not isinstance(rows[0], list):
|
|
1424
|
+
rows = [rows]
|
|
1425
|
+
mat = [[v for v in r] for r in rows]
|
|
1426
|
+
nrows = len(mat)
|
|
1427
|
+
ncols = len(mat[0])
|
|
1428
|
+
if tol is None:
|
|
1429
|
+
max_abs = max((abs(v) for r in mat for v in r), default=0.0)
|
|
1430
|
+
if rtol is not None:
|
|
1431
|
+
# 数组语义:tol = S.max() * rtol(max_abs 近似 S.max())
|
|
1432
|
+
tol = max_abs * rtol
|
|
1433
|
+
else:
|
|
1434
|
+
tol = max(nrows, ncols) * max_abs * 2.220446049250313e-16
|
|
1435
|
+
rank = 0
|
|
1436
|
+
pivot_row = 0
|
|
1437
|
+
for col in range(ncols):
|
|
1438
|
+
sel = -1
|
|
1439
|
+
best = tol
|
|
1440
|
+
for r in range(pivot_row, nrows):
|
|
1441
|
+
if abs(mat[r][col]) > best:
|
|
1442
|
+
best = abs(mat[r][col])
|
|
1443
|
+
sel = r
|
|
1444
|
+
if sel == -1:
|
|
1445
|
+
continue
|
|
1446
|
+
mat[pivot_row], mat[sel] = mat[sel], mat[pivot_row]
|
|
1447
|
+
pv = mat[pivot_row][col]
|
|
1448
|
+
for r in range(nrows):
|
|
1449
|
+
if r != pivot_row and mat[r][col] != 0.0:
|
|
1450
|
+
factor = mat[r][col] / pv
|
|
1451
|
+
for c in range(col, ncols):
|
|
1452
|
+
mat[r][c] -= factor * mat[pivot_row][c]
|
|
1453
|
+
pivot_row += 1
|
|
1454
|
+
rank += 1
|
|
1455
|
+
if pivot_row == nrows:
|
|
1456
|
+
break
|
|
1457
|
+
return rank
|
|
1458
|
+
|
|
1459
|
+
@staticmethod
|
|
1460
|
+
def eig(a):
|
|
1461
|
+
"""计算矩阵的特征值和特征向量(2.x 语义)。
|
|
1462
|
+
|
|
1463
|
+
返回 EigResult(eigenvalues, eigenvectors):eigenvalues (..., n)
|
|
1464
|
+
恒为复数 dtype(f32→c64、f64/int→c128、c64→c64、c128→c128),
|
|
1465
|
+
eigenvectors (..., n, n) 同 dtype 且保留 a 的 ndarray 子类;
|
|
1466
|
+
stacked (..., n, n) 支持任意 lead 维;空尺寸返回同形状空复数数组。
|
|
1467
|
+
"""
|
|
1468
|
+
from rsarray import ndarray
|
|
1469
|
+
from ._pylinalg import _stacked_2d
|
|
1470
|
+
a = a if hasattr(a, '_array') else ndarray(a)
|
|
1471
|
+
shape = tuple(a.shape)
|
|
1472
|
+
if len(shape) < 2 or shape[-2] != shape[-1]:
|
|
1473
|
+
raise LinAlgError(
|
|
1474
|
+
"eig: last 2 dimensions of the array must be square")
|
|
1475
|
+
# —eig 输出恒为复数 dtype(实数输入 → 对应复数)
|
|
1476
|
+
dt = getattr(a, '_dtype', 'float64')
|
|
1477
|
+
if dt.startswith('complex'):
|
|
1478
|
+
res_dt = dt
|
|
1479
|
+
elif dt == 'float32':
|
|
1480
|
+
res_dt = 'complex64'
|
|
1481
|
+
else:
|
|
1482
|
+
res_dt = 'complex128'
|
|
1483
|
+
|
|
1484
|
+
def _as_result(arr):
|
|
1485
|
+
# eigenvectors 保留 a 的 ndarray 子类(数组语义)
|
|
1486
|
+
at = type(a)
|
|
1487
|
+
if at is not ndarray and isinstance(a, ndarray):
|
|
1488
|
+
return at(arr)
|
|
1489
|
+
return arr
|
|
1490
|
+
|
|
1491
|
+
lead, subs = _stacked_2d(a)
|
|
1492
|
+
n = shape[-1]
|
|
1493
|
+
if n == 0:
|
|
1494
|
+
ev = ndarray([]).astype(res_dt).reshape(lead + (0,))
|
|
1495
|
+
ec = ndarray([]).astype(res_dt).reshape(lead + (0, 0))
|
|
1496
|
+
return EigResult(_as_result(ev), _as_result(ec))
|
|
1497
|
+
if len(shape) == 2:
|
|
1498
|
+
ev, ec = _eig_one(a)
|
|
1499
|
+
return EigResult(_as_result(ndarray(ev).astype(res_dt)),
|
|
1500
|
+
_as_result(ndarray(ec).astype(res_dt)))
|
|
1501
|
+
eval_list = []
|
|
1502
|
+
evec_list = []
|
|
1503
|
+
for sub in subs:
|
|
1504
|
+
ev, ec = _eig_one(sub)
|
|
1505
|
+
eval_list.append(ev)
|
|
1506
|
+
evec_list.append(ec)
|
|
1507
|
+
# 空 lead((0,1,1) 等)时嵌套 list 为空,用 reshape 补回 lead 维
|
|
1508
|
+
ev = ndarray(eval_list).reshape(lead + (n,)).astype(res_dt)
|
|
1509
|
+
ec = ndarray(evec_list).reshape(lead + (n, n)).astype(res_dt)
|
|
1510
|
+
return EigResult(_as_result(ev), _as_result(ec))
|
|
1511
|
+
|
|
1512
|
+
@staticmethod
|
|
1513
|
+
def eigvals(a):
|
|
1514
|
+
"""计算矩阵特征值(数组语义:2-d 返回 (n,),stacked 返回
|
|
1515
|
+
(lead..., n);输出 complex128,float32/complex64 输入为 complex64)。
|
|
1516
|
+
2x2/3x3 实输入走 Rust 快路径,其余尺寸走纯 Python QR 算法
|
|
1517
|
+
(``_eigvals_qr``,Hessenberg + 单位移 QR 迭代)。
|
|
1518
|
+
"""
|
|
1519
|
+
from rsarray import ndarray
|
|
1520
|
+
from ._pylinalg import _eigvals_qr, _stacked_2d
|
|
1521
|
+
|
|
1522
|
+
a_arr = a if hasattr(a, '_array') else ndarray(a)
|
|
1523
|
+
shape = tuple(a_arr.shape)
|
|
1524
|
+
if len(shape) < 2 or shape[-2] != shape[-1]:
|
|
1525
|
+
raise LinAlgError(
|
|
1526
|
+
"eigvals: last 2 dimensions of the array must be square")
|
|
1527
|
+
dt = getattr(a_arr, '_dtype', 'float64')
|
|
1528
|
+
out_dt = 'complex64' if dt in ('float32', 'complex64') \
|
|
1529
|
+
else 'complex128'
|
|
1530
|
+
if len(shape) == 2 and shape[-1] in (2, 3) \
|
|
1531
|
+
and dt in ('float32', 'float64'):
|
|
1532
|
+
try:
|
|
1533
|
+
return _wrap(_core.linalg.eigvals(_ensure(a_arr))) \
|
|
1534
|
+
.astype(out_dt)
|
|
1535
|
+
except ValueError:
|
|
1536
|
+
pass
|
|
1537
|
+
lead, subs = _stacked_2d(a_arr)
|
|
1538
|
+
if len(shape) == 2:
|
|
1539
|
+
return ndarray(_eigvals_qr(a_arr.tolist())).astype(out_dt)
|
|
1540
|
+
evals_list = [_eigvals_qr(sub.tolist()) for sub in subs]
|
|
1541
|
+
return ndarray(evals_list).reshape(lead + (shape[-1],)) \
|
|
1542
|
+
.astype(out_dt)
|
|
1543
|
+
|
|
1544
|
+
@staticmethod
|
|
1545
|
+
def svd(a, full_matrices=True, compute_uv=True, hermitian=False,
|
|
1546
|
+
lapack_driver=None):
|
|
1547
|
+
"""计算奇异值分解 A = u @ diag(s) @ vh。
|
|
1548
|
+
|
|
1549
|
+
支持 的 ``full_matrices`` / ``compute_uv`` 关键字;2×2 走 Rust
|
|
1550
|
+
核心,其余形状用单侧 Jacobi(``_svd_jacobi``)。stacked (...,M,N)
|
|
1551
|
+
按切片循环;dtype 按 _commonType 规则传播(U/Vh 保持输入
|
|
1552
|
+
dtype、S 为对应实 dtype);含 inf/nan 抛 LinAlgError(模拟 LAPACK
|
|
1553
|
+
"SVD did not converge")。
|
|
1554
|
+
"""
|
|
1555
|
+
from rsarray import ndarray, empty, eye
|
|
1556
|
+
from ._pylinalg import (_common_type, _real_dtype, _nonfinite_check,
|
|
1557
|
+
_stacked_2d)
|
|
1558
|
+
|
|
1559
|
+
a_arr = a if hasattr(a, '_array') else ndarray(a)
|
|
1560
|
+
shape = tuple(a_arr.shape)
|
|
1561
|
+
if len(shape) < 2:
|
|
1562
|
+
raise LinAlgError(
|
|
1563
|
+
"1-dimensional array given. Array must be at least "
|
|
1564
|
+
"two-dimensional")
|
|
1565
|
+
_, res_dt = _common_type(getattr(a_arr, '_dtype', 'float64'))
|
|
1566
|
+
s_dt = _real_dtype(res_dt)
|
|
1567
|
+
|
|
1568
|
+
lead, subs = _stacked_2d(a_arr)
|
|
1569
|
+
for sub in subs:
|
|
1570
|
+
_nonfinite_check(sub.tolist())
|
|
1571
|
+
m, n = shape[-2], shape[-1]
|
|
1572
|
+
k = min(m, n)
|
|
1573
|
+
|
|
1574
|
+
# ---- 空矩阵:U/Vh 为单位阵(full_matrices)或约定形状零阵,S 空 ----
|
|
1575
|
+
def _empty_result():
|
|
1576
|
+
if len(shape) > 2:
|
|
1577
|
+
total = 1
|
|
1578
|
+
for d in lead:
|
|
1579
|
+
total *= d
|
|
1580
|
+
|
|
1581
|
+
def _block(r, c, identity):
|
|
1582
|
+
if identity and r > 0 and r == c:
|
|
1583
|
+
return (ndarray([eye(r).tolist()] * total)
|
|
1584
|
+
.reshape(lead + (r, c)).astype(res_dt))
|
|
1585
|
+
return ndarray([]).reshape(lead + (r, c)).astype(res_dt)
|
|
1586
|
+
|
|
1587
|
+
if not compute_uv:
|
|
1588
|
+
return ndarray([]).reshape(lead + (0,)).astype(s_dt)
|
|
1589
|
+
s = ndarray([]).reshape(lead + (0,)).astype(s_dt)
|
|
1590
|
+
return SVDResult(
|
|
1591
|
+
_block(m, m if full_matrices else k, full_matrices), s,
|
|
1592
|
+
_block(n if full_matrices else k, n, full_matrices))
|
|
1593
|
+
|
|
1594
|
+
if not compute_uv:
|
|
1595
|
+
return ndarray([]).astype(s_dt)
|
|
1596
|
+
|
|
1597
|
+
def _block2(r, c, identity):
|
|
1598
|
+
if identity and r > 0 and r == c:
|
|
1599
|
+
return eye(r).astype(res_dt)
|
|
1600
|
+
return empty((r, c)).astype(res_dt)
|
|
1601
|
+
|
|
1602
|
+
u = _block2(m, m if full_matrices else k, full_matrices)
|
|
1603
|
+
vt = _block2(n if full_matrices else k, n, full_matrices)
|
|
1604
|
+
return SVDResult(u, ndarray([]).astype(s_dt), vt)
|
|
1605
|
+
|
|
1606
|
+
if m == 0 or n == 0:
|
|
1607
|
+
return _empty_result()
|
|
1608
|
+
|
|
1609
|
+
if hermitian:
|
|
1610
|
+
if m != n:
|
|
1611
|
+
raise LinAlgError(
|
|
1612
|
+
"Last 2 dimensions of the array must be square")
|
|
1613
|
+
|
|
1614
|
+
def _one_h(sub):
|
|
1615
|
+
# Hermitian:特征分解 A = V diag(w) V^H;S = |w| 降序,
|
|
1616
|
+
# 负特征值符号吸收进 U 的对应列,Vh = 重排后的 V^H
|
|
1617
|
+
w, v = linalg_module.eig(sub)
|
|
1618
|
+
w_list = w.tolist()
|
|
1619
|
+
v_rows = v.tolist()
|
|
1620
|
+
size = len(w_list)
|
|
1621
|
+
s_abs = [abs(complex(x)) for x in w_list]
|
|
1622
|
+
signs = [1.0 if complex(x).real >= 0 else -1.0
|
|
1623
|
+
for x in w_list]
|
|
1624
|
+
perm = sorted(range(size), key=lambda i: -s_abs[i])
|
|
1625
|
+
s_out = [s_abs[i] for i in perm]
|
|
1626
|
+
|
|
1627
|
+
def _conj(z):
|
|
1628
|
+
return z.conjugate() if isinstance(z, complex) else z
|
|
1629
|
+
|
|
1630
|
+
if not compute_uv:
|
|
1631
|
+
return ndarray(s_out).astype(s_dt)
|
|
1632
|
+
u_rows = [[signs[perm[j]] * v_rows[i][perm[j]]
|
|
1633
|
+
for j in range(size)] for i in range(size)]
|
|
1634
|
+
# Vh = V^H(共轭转置):Vh[j][i] = conj(V[i][perm[j]])
|
|
1635
|
+
vh_rows = [[_conj(v_rows[i][perm[j]])
|
|
1636
|
+
for i in range(size)] for j in range(size)]
|
|
1637
|
+
return SVDResult(ndarray(u_rows).astype(res_dt),
|
|
1638
|
+
ndarray(s_out).astype(s_dt),
|
|
1639
|
+
ndarray(vh_rows).astype(res_dt))
|
|
1640
|
+
|
|
1641
|
+
if len(shape) == 2:
|
|
1642
|
+
return _one_h(a_arr)
|
|
1643
|
+
results = [_one_h(sub) for sub in subs]
|
|
1644
|
+
if not compute_uv:
|
|
1645
|
+
s = ndarray([r.tolist() for r in results]).astype(s_dt)
|
|
1646
|
+
return s.reshape(lead + (s.shape[-1],))
|
|
1647
|
+
# results 按 lead 维行主序排列,恢复完整 leading 形状
|
|
1648
|
+
u = ndarray([r.U.tolist() for r in results]).astype(res_dt)
|
|
1649
|
+
s = ndarray([r.S.tolist() for r in results]).astype(s_dt)
|
|
1650
|
+
vt = ndarray([r.Vh.tolist() for r in results]).astype(res_dt)
|
|
1651
|
+
return SVDResult(u.reshape(lead + tuple(results[0].U.shape)),
|
|
1652
|
+
s.reshape(lead + tuple(results[0].S.shape)),
|
|
1653
|
+
vt.reshape(lead + tuple(results[0].Vh.shape)))
|
|
1654
|
+
|
|
1655
|
+
def _one(sub):
|
|
1656
|
+
if not compute_uv:
|
|
1657
|
+
s = _svd_jacobi(sub.tolist(), False, False)
|
|
1658
|
+
return s.astype(s_dt)
|
|
1659
|
+
# Rust 2x2 SVD 只处理实输入(复数输入返回实 U/Vh,结果错误),
|
|
1660
|
+
# 复数 2x2 走 _svd_jacobi 的复数路径
|
|
1661
|
+
if tuple(sub.shape) == (2, 2) and not _is_complex_arr(sub):
|
|
1662
|
+
try:
|
|
1663
|
+
u, s, vt = _core.linalg.svd(_ensure(sub))
|
|
1664
|
+
u = _round_array(u)
|
|
1665
|
+
s = _round_array(s)
|
|
1666
|
+
vt = _round_array(vt)
|
|
1667
|
+
# Rust 2x2 的 s 是 2-d 对角矩阵,归一为 1-d 对角
|
|
1668
|
+
# (与 3x3+ Jacobi 路径的 1-d s 一致)
|
|
1669
|
+
s_list = s.tolist()
|
|
1670
|
+
if (isinstance(s_list, list) and s_list
|
|
1671
|
+
and isinstance(s_list[0], (list, tuple))):
|
|
1672
|
+
s_list = [row[i] for i, row in enumerate(s_list)]
|
|
1673
|
+
return SVDResult(ndarray._wrap(u).astype(res_dt),
|
|
1674
|
+
ndarray(s_list).astype(s_dt),
|
|
1675
|
+
ndarray._wrap(vt).astype(res_dt))
|
|
1676
|
+
except Exception:
|
|
1677
|
+
pass
|
|
1678
|
+
u, s, vt = _svd_jacobi(sub.tolist(), full_matrices, True)
|
|
1679
|
+
return SVDResult(u.astype(res_dt), s.astype(s_dt),
|
|
1680
|
+
vt.astype(res_dt))
|
|
1681
|
+
|
|
1682
|
+
if len(shape) == 2:
|
|
1683
|
+
return _one(a_arr)
|
|
1684
|
+
results = [_one(sub) for sub in subs]
|
|
1685
|
+
if not compute_uv:
|
|
1686
|
+
s = ndarray([r.tolist() for r in results]).astype(s_dt)
|
|
1687
|
+
return s.reshape(lead + (s.shape[-1],))
|
|
1688
|
+
# results 按 lead 维行主序排列,恢复完整 leading 形状
|
|
1689
|
+
u = ndarray([r.U.tolist() for r in results]).astype(res_dt)
|
|
1690
|
+
s = ndarray([r.S.tolist() for r in results]).astype(s_dt)
|
|
1691
|
+
vt = ndarray([r.Vh.tolist() for r in results]).astype(res_dt)
|
|
1692
|
+
return SVDResult(u.reshape(lead + tuple(results[0].U.shape)),
|
|
1693
|
+
s.reshape(lead + tuple(results[0].S.shape)),
|
|
1694
|
+
vt.reshape(lead + tuple(results[0].Vh.shape)))
|
|
1695
|
+
|
|
1696
|
+
@staticmethod
|
|
1697
|
+
def qr(a, mode='reduced'):
|
|
1698
|
+
"""计算 QR 分解(数组语义)。
|
|
1699
|
+
|
|
1700
|
+
modes: 'reduced'(默认)/ 'complete' / 'r' / 'raw';>= 1.8 已移除
|
|
1701
|
+
弃用别名 'full'/'f'/'economic'/'e'。2×2/3×3 reduced 走 Rust 核心,
|
|
1702
|
+
其余形状用纯 Python Householder(``_qr_householder``);stacked
|
|
1703
|
+
(...,M,N) 按切片循环;空矩阵返回约定形状(complete 时 Q=I_m);
|
|
1704
|
+
'raw' 返回 (h, tau)(FORTRAN 序 h (n,m) + tau (k,))。
|
|
1705
|
+
"""
|
|
1706
|
+
from rsarray import ndarray, empty, eye
|
|
1707
|
+
from ._pylinalg import (_common_type, _stacked_2d, _qr_raw)
|
|
1708
|
+
|
|
1709
|
+
# >= 1.8:弃用别名 'full'/'f'/'economic'/'e' 已移除。
|
|
1710
|
+
if mode in ('full', 'f'):
|
|
1711
|
+
raise ValueError(
|
|
1712
|
+
f"mode {mode!r} is deprecated in 1.8, use 'complete'")
|
|
1713
|
+
if mode in ('economic', 'e'):
|
|
1714
|
+
raise ValueError(
|
|
1715
|
+
f"mode {mode!r} is deprecated in 1.8, use 'reduced'")
|
|
1716
|
+
if mode not in ('reduced', 'complete', 'r', 'raw'):
|
|
1717
|
+
raise ValueError(
|
|
1718
|
+
f"mode {mode!r} is not recognized. Must be one of "
|
|
1719
|
+
"'raw', 'reduced', 'complete', 'r'.")
|
|
1720
|
+
|
|
1721
|
+
a_arr = a if hasattr(a, '_array') else ndarray(a)
|
|
1722
|
+
shape = tuple(a_arr.shape)
|
|
1723
|
+
if len(shape) < 2:
|
|
1724
|
+
raise LinAlgError(
|
|
1725
|
+
"1-dimensional array given. Array must be at least "
|
|
1726
|
+
"two-dimensional")
|
|
1727
|
+
res_dt = _common_type(getattr(a_arr, '_dtype', 'float64'))[1]
|
|
1728
|
+
m, n = shape[-2], shape[-1]
|
|
1729
|
+
k = min(m, n)
|
|
1730
|
+
|
|
1731
|
+
def _empty_res():
|
|
1732
|
+
if mode == 'raw':
|
|
1733
|
+
return (ndarray(empty((n, m))).astype(res_dt),
|
|
1734
|
+
ndarray(empty((k,))).astype(res_dt))
|
|
1735
|
+
if mode in ('reduced', 'r'):
|
|
1736
|
+
return (ndarray(empty((m, k))).astype(res_dt),
|
|
1737
|
+
ndarray(empty((k, n))).astype(res_dt))
|
|
1738
|
+
return (ndarray(eye(m)).astype(res_dt),
|
|
1739
|
+
ndarray(empty((m, n))).astype(res_dt))
|
|
1740
|
+
|
|
1741
|
+
if m == 0 or n == 0:
|
|
1742
|
+
res = _empty_res()
|
|
1743
|
+
if len(shape) > 2:
|
|
1744
|
+
# stacked 空矩阵:数组语义把各分量广播到 (lead, ...)
|
|
1745
|
+
# ('r'/'raw' 同样适用,否则回 2-d 形状)
|
|
1746
|
+
from rsarray import broadcast_to
|
|
1747
|
+
lead = shape[:-2]
|
|
1748
|
+
res = tuple(broadcast_to(x, lead + x.shape) for x in res)
|
|
1749
|
+
if mode == 'r':
|
|
1750
|
+
return res[1]
|
|
1751
|
+
if mode == 'raw':
|
|
1752
|
+
return res
|
|
1753
|
+
return QRResult(res[0], res[1])
|
|
1754
|
+
|
|
1755
|
+
def _one(sub):
|
|
1756
|
+
sm, sn = sub.shape
|
|
1757
|
+
if mode == 'raw':
|
|
1758
|
+
h, tau = _qr_raw(sub.tolist())
|
|
1759
|
+
return (ndarray(h).astype(res_dt), ndarray(tau).astype(res_dt))
|
|
1760
|
+
# 32 位(f32/c64)与 c128 不走 Rust 2x2/3x3 快捷路径:Rust 侧
|
|
1761
|
+
# 缓冲在连续调用(同一会话内前序 QR/SVD)后可能读到脏状态
|
|
1762
|
+
# (实测 c64 返回全 1、f32 返回全 0、c128 返回全 1),
|
|
1763
|
+
# Python Householder 无此问题且精度足够
|
|
1764
|
+
if sm == sn and sm in (2, 3) and mode == 'reduced' \
|
|
1765
|
+
and getattr(sub, '_dtype', '') not in ('float32',
|
|
1766
|
+
'complex64',
|
|
1767
|
+
'complex128'):
|
|
1768
|
+
try:
|
|
1769
|
+
q, r = _core.linalg.qr(_ensure(sub))
|
|
1770
|
+
q = _round_array(q)
|
|
1771
|
+
r = _round_array(r)
|
|
1772
|
+
return (ndarray._wrap(q).astype(res_dt),
|
|
1773
|
+
ndarray._wrap(r).astype(res_dt))
|
|
1774
|
+
except Exception:
|
|
1775
|
+
pass
|
|
1776
|
+
q, r = linalg_module._qr_householder(
|
|
1777
|
+
sub, mode if mode in ('reduced', 'complete') else 'reduced')
|
|
1778
|
+
q = q.astype(res_dt)
|
|
1779
|
+
r = r.astype(res_dt)
|
|
1780
|
+
if mode == 'r':
|
|
1781
|
+
return r
|
|
1782
|
+
return (q, r)
|
|
1783
|
+
|
|
1784
|
+
if len(shape) == 2:
|
|
1785
|
+
out = _one(a_arr)
|
|
1786
|
+
if mode == 'r':
|
|
1787
|
+
return out
|
|
1788
|
+
return QRResult(out[0], out[1])
|
|
1789
|
+
|
|
1790
|
+
lead, subs = _stacked_2d(a_arr)
|
|
1791
|
+
parts = [_one(sub) for sub in subs]
|
|
1792
|
+
if mode == 'raw':
|
|
1793
|
+
h = ndarray([p[0].tolist() for p in parts]).reshape(lead + (n, m))
|
|
1794
|
+
tau = ndarray([p[1].tolist() for p in parts]).reshape(lead + (k,))
|
|
1795
|
+
return (h.astype(res_dt), tau.astype(res_dt))
|
|
1796
|
+
if mode == 'r':
|
|
1797
|
+
return ndarray([p.tolist() for p in parts]).reshape(
|
|
1798
|
+
lead + (k, n)).astype(res_dt)
|
|
1799
|
+
q = ndarray([p[0].tolist() for p in parts]).reshape(
|
|
1800
|
+
lead + ((m, m) if mode == 'complete' else (m, k))).astype(res_dt)
|
|
1801
|
+
r = ndarray([p[1].tolist() for p in parts]).reshape(
|
|
1802
|
+
lead + ((m, n) if mode == 'complete' else (k, n))).astype(res_dt)
|
|
1803
|
+
return QRResult(q, r)
|
|
1804
|
+
|
|
1805
|
+
@staticmethod
|
|
1806
|
+
def _qr_householder(a, mode='reduced'):
|
|
1807
|
+
"""Householder 反射 QR,支持任意 m x n 与 reduced/complete 形态。"""
|
|
1808
|
+
import math
|
|
1809
|
+
|
|
1810
|
+
from rsarray import ndarray
|
|
1811
|
+
|
|
1812
|
+
if mode == 'reduced':
|
|
1813
|
+
want_complete = False
|
|
1814
|
+
elif mode == 'complete':
|
|
1815
|
+
want_complete = True
|
|
1816
|
+
else:
|
|
1817
|
+
raise ValueError(
|
|
1818
|
+
"mode must be one of 'reduced' or 'complete', "
|
|
1819
|
+
f"got {mode!r}")
|
|
1820
|
+
|
|
1821
|
+
rows = [list(row) for row in _ensure(a).tolist()]
|
|
1822
|
+
m = len(rows)
|
|
1823
|
+
n = len(rows[0]) if m else 0
|
|
1824
|
+
if m == 0 or n == 0:
|
|
1825
|
+
raise ValueError('cannot factor an empty matrix')
|
|
1826
|
+
|
|
1827
|
+
is_complex = any(isinstance(v, complex) for row in rows for v in row)
|
|
1828
|
+
conj = (lambda z: z.conjugate()) if is_complex else (lambda z: z)
|
|
1829
|
+
|
|
1830
|
+
def dot2(xs, ys):
|
|
1831
|
+
return sum(conj(x) * y for x, y in zip(xs, ys)) if is_complex \
|
|
1832
|
+
else sum(x * y for x, y in zip(xs, ys))
|
|
1833
|
+
|
|
1834
|
+
# R 就地化为上三角,Q 同步累积每一次反射。
|
|
1835
|
+
q_mat = [[1.0 if i == j else 0.0 for j in range(m)] for i in range(m)]
|
|
1836
|
+
for j in range(min(m, n)):
|
|
1837
|
+
width = m - j
|
|
1838
|
+
col_j = [rows[j + i][j] for i in range(width)]
|
|
1839
|
+
norm = math.sqrt(sum(abs(x) ** 2 for x in col_j))
|
|
1840
|
+
if norm == 0.0:
|
|
1841
|
+
continue
|
|
1842
|
+
# v = x - alpha*e1。复数时 alpha 必须与 x0 同相
|
|
1843
|
+
# (alpha = -x0/|x0|·||x||),Hx 才能精确落到 e1 方向;
|
|
1844
|
+
# 实数 alpha = -sign(x0)·||x||。均取首分量相加以避相消。
|
|
1845
|
+
lead = col_j[0]
|
|
1846
|
+
if is_complex:
|
|
1847
|
+
mag = abs(lead)
|
|
1848
|
+
alpha = (-lead / mag * norm) if mag > 0 else complex(-norm)
|
|
1849
|
+
else:
|
|
1850
|
+
alpha = -norm if lead < 0 else norm
|
|
1851
|
+
v = list(col_j)
|
|
1852
|
+
v[0] = v[0] - alpha
|
|
1853
|
+
vv = sum(abs(t) ** 2 for t in v)
|
|
1854
|
+
if vv == 0.0:
|
|
1855
|
+
continue
|
|
1856
|
+
|
|
1857
|
+
for c in range(j, n):
|
|
1858
|
+
factor = 2.0 * dot2(v, [rows[j + i][c] for i in range(width)]) / vv
|
|
1859
|
+
for i in range(width):
|
|
1860
|
+
rows[j + i][c] -= factor * v[i]
|
|
1861
|
+
|
|
1862
|
+
for r_row in range(m):
|
|
1863
|
+
# Q_new = Q_old @ H,H = I - 2 v v^H/v^H v:
|
|
1864
|
+
# (QH)[r][c] = Q[r][c] - (2/vv)(Qv)[r]·conj(v[c-j])。
|
|
1865
|
+
# dot2(Qseg, conj(v)) = conj((Qv)[r]),复数时须再取共轭。
|
|
1866
|
+
factor = 2.0 * dot2([q_mat[r_row][j + i] for i in range(width)],
|
|
1867
|
+
[conj(t) for t in v]) / vv
|
|
1868
|
+
if is_complex:
|
|
1869
|
+
factor = factor.conjugate()
|
|
1870
|
+
for i in range(width):
|
|
1871
|
+
q_mat[r_row][j + i] -= factor * conj(v[i])
|
|
1872
|
+
|
|
1873
|
+
# 反射残留的下三角应恰为 0,显式置零以便上三角/形状判定通过。
|
|
1874
|
+
for i in range(m):
|
|
1875
|
+
for j in range(min(i, n)):
|
|
1876
|
+
rows[i][j] = 0.0
|
|
1877
|
+
|
|
1878
|
+
if want_complete:
|
|
1879
|
+
out_q, out_r = q_mat, rows
|
|
1880
|
+
else:
|
|
1881
|
+
k = min(m, n)
|
|
1882
|
+
out_q = [row[:k] for row in q_mat]
|
|
1883
|
+
out_r = rows[:k]
|
|
1884
|
+
|
|
1885
|
+
return (ndarray._wrap(_core.ndarray(out_q)),
|
|
1886
|
+
ndarray._wrap(_core.ndarray(out_r)))
|
|
1887
|
+
|
|
1888
|
+
@staticmethod
|
|
1889
|
+
def cholesky(a, /, *, upper=False):
|
|
1890
|
+
"""计算 Cholesky 分解:A = L·L^H(lower)或 U^H·U(upper)。
|
|
1891
|
+
|
|
1892
|
+
A 须 Hermitian 正定(不校验 Hermitian,只用对应三角 + 对角)。
|
|
1893
|
+
纯 Python Cholesky-Crout(任意尺寸);stacked (...,M,M) 按切片;
|
|
1894
|
+
空 2-d 返回同形状空数组(dtype 按 _commonType:int→f64);
|
|
1895
|
+
float16 抛 TypeError("unsupported in linalg");非正定/含
|
|
1896
|
+
inf/nan 抛 LinAlgError。
|
|
1897
|
+
"""
|
|
1898
|
+
from rsarray import ndarray, empty
|
|
1899
|
+
from ._pylinalg import (_common_type, _stacked_2d, _is_empty_2d,
|
|
1900
|
+
_py_cholesky, _nonfinite_check)
|
|
1901
|
+
|
|
1902
|
+
a_arr = a if hasattr(a, '_array') else ndarray(a)
|
|
1903
|
+
shape = tuple(a_arr.shape)
|
|
1904
|
+
if len(shape) < 2:
|
|
1905
|
+
raise LinAlgError(
|
|
1906
|
+
"1-dimensional array given. Array must be at least "
|
|
1907
|
+
"two-dimensional")
|
|
1908
|
+
if shape[-1] != shape[-2]:
|
|
1909
|
+
raise LinAlgError("Last 2 dimensions of the array must be square")
|
|
1910
|
+
res_dt = _common_type(getattr(a_arr, '_dtype', 'float64'))[1]
|
|
1911
|
+
if _is_empty_2d(a_arr):
|
|
1912
|
+
return empty(shape, dtype=res_dt)
|
|
1913
|
+
|
|
1914
|
+
lead, subs = _stacked_2d(a_arr)
|
|
1915
|
+
|
|
1916
|
+
def _one(sub):
|
|
1917
|
+
mat = sub.tolist()
|
|
1918
|
+
_nonfinite_check(
|
|
1919
|
+
mat, "matrix is not positive-definite (cholesky)")
|
|
1920
|
+
return _py_cholesky(mat, upper)
|
|
1921
|
+
|
|
1922
|
+
if len(shape) == 2:
|
|
1923
|
+
return ndarray(_one(a_arr)).astype(res_dt)
|
|
1924
|
+
parts = [_one(sub) for sub in subs]
|
|
1925
|
+
total = 1
|
|
1926
|
+
for d in lead:
|
|
1927
|
+
total *= d
|
|
1928
|
+
return (ndarray(parts).reshape((total,) + shape[-2:])
|
|
1929
|
+
.reshape(lead + shape[-2:]).astype(res_dt))
|
|
1930
|
+
|
|
1931
|
+
@staticmethod
|
|
1932
|
+
def matrix_power(a, n):
|
|
1933
|
+
"""计算矩阵的幂(2.x 语义)。
|
|
1934
|
+
|
|
1935
|
+
``n`` 须为整数(否则 TypeError);0 → 单位矩阵(保持 dtype 与
|
|
1936
|
+
stacked 形状);n>0 二进制快速幂(纯 Python,任意尺寸 / stacked
|
|
1937
|
+
(...,M,M));n<0 先求逆再乘方(奇异矩阵抛 LinAlgError,与
|
|
1938
|
+
一致);非方阵抛 LinAlgError。
|
|
1939
|
+
"""
|
|
1940
|
+
from rsarray import ndarray, array
|
|
1941
|
+
from ._pylinalg import (_matrix_power_mat, _stacked_2d)
|
|
1942
|
+
|
|
1943
|
+
if not isinstance(n, int):
|
|
1944
|
+
idx = getattr(n, '__index__', None)
|
|
1945
|
+
if idx is None:
|
|
1946
|
+
raise TypeError("Power must be an integer")
|
|
1947
|
+
n = idx()
|
|
1948
|
+
|
|
1949
|
+
a_arr = a if hasattr(a, '_array') else ndarray(a)
|
|
1950
|
+
shape = tuple(a_arr.shape)
|
|
1951
|
+
if len(shape) < 2 or shape[-1] != shape[-2]:
|
|
1952
|
+
raise LinAlgError("Square matrix expected")
|
|
1953
|
+
|
|
1954
|
+
dtype = getattr(a_arr, '_dtype', 'float64')
|
|
1955
|
+
# subok:输入为 matrix 时结果保持 matrix(matrix_power 语义)
|
|
1956
|
+
_is_mat = type(a).__name__ == 'matrix'
|
|
1957
|
+
|
|
1958
|
+
def _fin(res):
|
|
1959
|
+
if _is_mat:
|
|
1960
|
+
from rsarray import matrix as _mx
|
|
1961
|
+
return _mx(res)
|
|
1962
|
+
return res
|
|
1963
|
+
|
|
1964
|
+
if n < 0:
|
|
1965
|
+
try:
|
|
1966
|
+
inv_a = linalg_module.inv(a_arr)
|
|
1967
|
+
except LinAlgError:
|
|
1968
|
+
raise
|
|
1969
|
+
except ValueError:
|
|
1970
|
+
# 奇异:底层抛 ValueError("Singular matrix"),的
|
|
1971
|
+
# matrix_power 抛 LinAlgError
|
|
1972
|
+
raise LinAlgError("Singular matrix")
|
|
1973
|
+
return _fin(linalg_module.matrix_power(inv_a, -n))
|
|
1974
|
+
|
|
1975
|
+
lead, subs = _stacked_2d(a_arr)
|
|
1976
|
+
if dtype == 'object':
|
|
1977
|
+
# object 数组平铺存储(astype/reshape 不重嵌套),须手动嵌套
|
|
1978
|
+
# 并用 array(dtype=) 直接构造结果
|
|
1979
|
+
m = shape[-1]
|
|
1980
|
+
|
|
1981
|
+
def _unflat(lst):
|
|
1982
|
+
if isinstance(lst, list) and lst \
|
|
1983
|
+
and not isinstance(lst[0], (list, tuple)):
|
|
1984
|
+
return [lst[i * m:(i + 1) * m] for i in range(m)]
|
|
1985
|
+
return lst
|
|
1986
|
+
|
|
1987
|
+
if len(shape) == 2:
|
|
1988
|
+
return _fin(array(_matrix_power_mat(_unflat(subs.tolist()), n),
|
|
1989
|
+
dtype='object'))
|
|
1990
|
+
parts = [_matrix_power_mat(_unflat(sub.tolist()), n)
|
|
1991
|
+
for sub in subs]
|
|
1992
|
+
return _fin(array(parts, dtype='object'))
|
|
1993
|
+
|
|
1994
|
+
if len(shape) == 2:
|
|
1995
|
+
return _fin(ndarray(_matrix_power_mat(subs.tolist(), n)).astype(dtype))
|
|
1996
|
+
parts = [_matrix_power_mat(sub.tolist(), n) for sub in subs]
|
|
1997
|
+
total = len(parts)
|
|
1998
|
+
return _fin(ndarray(parts).reshape((total,) + shape[-2:])
|
|
1999
|
+
.reshape(lead + shape[-2:]).astype(dtype))
|
|
2000
|
+
|
|
2001
|
+
@staticmethod
|
|
2002
|
+
def pinv(a, rcond=None, hermitian=False, rtol=NoValue):
|
|
2003
|
+
"""计算 Moore-Penrose 伪逆(2.x 参数语义)。
|
|
2004
|
+
|
|
2005
|
+
``rcond``/``rtol`` 二选一:都未给用 1e-15;``rtol=None`` 用
|
|
2006
|
+
``max(M,N)*eps(结果 dtype)``(按 Array API 标准,dtype 取
|
|
2007
|
+
伪逆实际计算/返回的 dtype——int/bool 输入在 float64 上计算);
|
|
2008
|
+
同时给两者抛 ValueError。空 2-d 输入走 empty 快捷路径(返回
|
|
2009
|
+
转置形状、正确 dtype 的空数组)。
|
|
2010
|
+
"""
|
|
2011
|
+
from rsarray import ndarray, empty
|
|
2012
|
+
from ._pylinalg import (_common_type, _is_empty_2d, _real_dtype,
|
|
2013
|
+
_finfo_eps)
|
|
2014
|
+
|
|
2015
|
+
a_arr = a if hasattr(a, '_array') else ndarray(a)
|
|
2016
|
+
dtype = getattr(a_arr, '_dtype', 'float64')
|
|
2017
|
+
res_dt = _common_type(dtype)[1]
|
|
2018
|
+
|
|
2019
|
+
if rcond is not None and rtol is not NoValue:
|
|
2020
|
+
raise ValueError("`rtol` and `rcond` can't be both set.")
|
|
2021
|
+
if rcond is None:
|
|
2022
|
+
if rtol is NoValue:
|
|
2023
|
+
rcond_val = 1e-15
|
|
2024
|
+
elif rtol is None:
|
|
2025
|
+
rcond_val = max(a_arr.shape[-2:]) * _finfo_eps(
|
|
2026
|
+
_real_dtype(res_dt))
|
|
2027
|
+
else:
|
|
2028
|
+
rcond_val = rtol
|
|
2029
|
+
else:
|
|
2030
|
+
rcond_val = rcond
|
|
2031
|
+
|
|
2032
|
+
if _is_empty_2d(a_arr):
|
|
2033
|
+
m, n = a_arr.shape[-2:]
|
|
2034
|
+
return empty(a_arr.shape[:-2] + (n, m), dtype=res_dt)
|
|
2035
|
+
|
|
2036
|
+
# A^+ = V Σ^+ U^H,其中 (U, s, Vh) = svd(A, full_matrices=False)
|
|
2037
|
+
#(对 A 本身做 SVD;_one 按 V[i,j]=vt[j,i].conj() 组装)
|
|
2038
|
+
u, s, vt = linalg_module.svd(a_arr, full_matrices=False,
|
|
2039
|
+
hermitian=hermitian)
|
|
2040
|
+
|
|
2041
|
+
def _one(u_m, s_list, vt_k):
|
|
2042
|
+
m = len(u_m)
|
|
2043
|
+
n = len(vt_k[0]) if vt_k else 0
|
|
2044
|
+
k = len(s_list)
|
|
2045
|
+
s_max = max(s_list) if s_list else 0.0
|
|
2046
|
+
cutoff = float(rcond_val) * s_max
|
|
2047
|
+
res = [[0.0] * m for _ in range(n)]
|
|
2048
|
+
for j in range(k):
|
|
2049
|
+
si = (1.0 / s_list[j]) if s_list[j] > cutoff else 0.0
|
|
2050
|
+
if si == 0.0:
|
|
2051
|
+
continue
|
|
2052
|
+
for i in range(n):
|
|
2053
|
+
vij = vt_k[j][i].conjugate() * si
|
|
2054
|
+
if vij == 0:
|
|
2055
|
+
continue
|
|
2056
|
+
res_i = res[i]
|
|
2057
|
+
for r in range(m):
|
|
2058
|
+
res_i[r] += vij * u_m[r][j].conjugate()
|
|
2059
|
+
return res
|
|
2060
|
+
|
|
2061
|
+
shape = a_arr.shape
|
|
2062
|
+
if len(shape) == 2:
|
|
2063
|
+
res = _one(u.tolist(), s.tolist(), vt.tolist())
|
|
2064
|
+
return ndarray(res).astype(res_dt)
|
|
2065
|
+
lead = shape[:-2]
|
|
2066
|
+
total = 1
|
|
2067
|
+
for d in lead:
|
|
2068
|
+
total *= d
|
|
2069
|
+
flat_u = u.reshape((total,) + u.shape[-2:])
|
|
2070
|
+
flat_s = s.reshape((total,) + s.shape[-1:])
|
|
2071
|
+
flat_vt = vt.reshape((total,) + vt.shape[-2:])
|
|
2072
|
+
parts = [_one(flat_u[i].tolist(), flat_s[i].tolist(),
|
|
2073
|
+
flat_vt[i].tolist())
|
|
2074
|
+
for i in range(flat_u.shape[0])]
|
|
2075
|
+
m, n = shape[-2], shape[-1]
|
|
2076
|
+
return ndarray(parts).reshape(lead + (n, m)).astype(res_dt)
|
|
2077
|
+
|
|
2078
|
+
@staticmethod
|
|
2079
|
+
def trace(a, offset=0, axis1=-2, axis2=-1, dtype=None, out=None):
|
|
2080
|
+
"""计算矩阵的迹(linalg.trace 语义:默认 axis1=-2, axis2=-1;
|
|
2081
|
+
stacked (...,M,N) 返回最后两轴各矩阵的迹;2-d offset=0 走 Rust 快路径)。"""
|
|
2082
|
+
from rsarray import ndarray
|
|
2083
|
+
_ = dtype, out
|
|
2084
|
+
a_arr = a if hasattr(a, '_array') else ndarray(a)
|
|
2085
|
+
sh = tuple(a_arr.shape)
|
|
2086
|
+
if len(sh) < 2:
|
|
2087
|
+
raise ValueError(
|
|
2088
|
+
"trace requires an array of at least 2 dimensions")
|
|
2089
|
+
if len(sh) == 2 and offset == 0:
|
|
2090
|
+
result = _core.linalg.trace(_ensure(a))
|
|
2091
|
+
return _round_float(result)
|
|
2092
|
+
return linalg_module.diagonal(a_arr, offset, axis1, axis2).sum(-1)
|
|
2093
|
+
|
|
2094
|
+
@staticmethod
|
|
2095
|
+
def diagonal(a, offset=0, axis1=-2, axis2=-1):
|
|
2096
|
+
"""返回矩阵的对角线元素(linalg.diagonal 语义:默认
|
|
2097
|
+
axis1=-2, axis2=-1,支持任意维数组)。"""
|
|
2098
|
+
from rsarray import ndarray
|
|
2099
|
+
a_arr = a if hasattr(a, '_array') else ndarray(a)
|
|
2100
|
+
sh = tuple(a_arr.shape)
|
|
2101
|
+
if len(sh) < 2:
|
|
2102
|
+
raise ValueError(
|
|
2103
|
+
"diagonal requires an array of at least 2 dimensions")
|
|
2104
|
+
if len(sh) == 2:
|
|
2105
|
+
return a_arr.diagonal(offset, 0, 1)
|
|
2106
|
+
# ndim>2:逐批次提取 a1/a2 两轴对角(核心 diagonal 不返回
|
|
2107
|
+
# 批次形状):先把 a1/a2 移到末尾,逐 2-d 切片取对角
|
|
2108
|
+
nd = len(sh)
|
|
2109
|
+
a1, a2 = axis1 % nd, axis2 % nd
|
|
2110
|
+
order = [i for i in range(nd) if i not in (a1, a2)] + [a1, a2]
|
|
2111
|
+
moved = a_arr.transpose(order)
|
|
2112
|
+
msh = tuple(moved.shape)
|
|
2113
|
+
m, n = msh[-2], msh[-1]
|
|
2114
|
+
lead = 1
|
|
2115
|
+
for d in msh[:-2]:
|
|
2116
|
+
lead *= d
|
|
2117
|
+
flat = moved.reshape((lead, m, n)).tolist()
|
|
2118
|
+
if offset >= 0:
|
|
2119
|
+
dlen = max(min(m, n) - offset, 0)
|
|
2120
|
+
parts = [[b[i + offset][i] for i in range(dlen)]
|
|
2121
|
+
for b in flat]
|
|
2122
|
+
else:
|
|
2123
|
+
dlen = max(min(m, n) + offset, 0)
|
|
2124
|
+
parts = [[b[i][i - offset] for i in range(dlen)]
|
|
2125
|
+
for b in flat]
|
|
2126
|
+
return ndarray(parts).reshape(msh[:-2] + (dlen,))
|
|
2127
|
+
|
|
2128
|
+
@staticmethod
|
|
2129
|
+
def svdvals(a):
|
|
2130
|
+
"""计算奇异值(委托 svd(compute_uv=False):dtype/stacked/nonfinite 一致)。"""
|
|
2131
|
+
return linalg_module.svd(a, full_matrices=False, compute_uv=False)
|
|
2132
|
+
|
|
2133
|
+
@staticmethod
|
|
2134
|
+
def cond(x, p=None):
|
|
2135
|
+
"""计算矩阵的条件数。
|
|
2136
|
+
|
|
2137
|
+
条件数 ``kappa = ||x|| * ||inv(x)||`` 衡量线性系统的敏感度:接近 1 表示
|
|
2138
|
+
良态,很大表示接近奇异(奇异矩阵返回 `inf`)。
|
|
2139
|
+
|
|
2140
|
+
Parameters
|
|
2141
|
+
----------
|
|
2142
|
+
x : array_like
|
|
2143
|
+
方阵。
|
|
2144
|
+
p : {None, 1, -1, 2, -2, inf, -inf, 'fro'}, optional
|
|
2145
|
+
范数类型。默认(及 2 / -2)走 SVD,其余用 ``norm(x, p) * norm(inv(x), p)``。
|
|
2146
|
+
|
|
2147
|
+
【使用示例】
|
|
2148
|
+
>>> import rsarray as np
|
|
2149
|
+
>>> np.linalg.cond(np.array([[1., 0.], [0., 1.]]))
|
|
2150
|
+
1.0
|
|
2151
|
+
>>> np.linalg.cond(np.array([[1., 2.], [2., 4.]])) # 奇异
|
|
2152
|
+
inf
|
|
2153
|
+
"""
|
|
2154
|
+
from rsarray import ndarray
|
|
2155
|
+
from ._pylinalg import (_common_type, _real_dtype, _stacked_2d,
|
|
2156
|
+
_is_empty_2d)
|
|
2157
|
+
|
|
2158
|
+
x_arr = x if hasattr(x, '_array') else ndarray(x)
|
|
2159
|
+
if _is_empty_2d(x_arr):
|
|
2160
|
+
raise LinAlgError("cond is not defined on empty arrays")
|
|
2161
|
+
shape = x_arr.shape
|
|
2162
|
+
if len(shape) < 2:
|
|
2163
|
+
raise LinAlgError(
|
|
2164
|
+
"1-dimensional array given. Array must be at least "
|
|
2165
|
+
"two-dimensional")
|
|
2166
|
+
_, res_dt = _common_type(getattr(x_arr, '_dtype', 'float64'))
|
|
2167
|
+
res_dt = _real_dtype(res_dt) # 条件数恒为实数
|
|
2168
|
+
|
|
2169
|
+
import rsarray as _np
|
|
2170
|
+
lead, subs = _stacked_2d(x_arr)
|
|
2171
|
+
is_2d = len(shape) == 2
|
|
2172
|
+
|
|
2173
|
+
def _has_nan(arr):
|
|
2174
|
+
def _rec(x):
|
|
2175
|
+
if isinstance(x, list):
|
|
2176
|
+
return any(_rec(y) for y in x)
|
|
2177
|
+
if isinstance(x, complex):
|
|
2178
|
+
return x.real != x.real or x.imag != x.imag
|
|
2179
|
+
return float(x) != float(x)
|
|
2180
|
+
return _rec(arr.tolist())
|
|
2181
|
+
|
|
2182
|
+
def _div(a, b):
|
|
2183
|
+
# IEEE 浮点除法语义(Python 的 x/0.0 会抛异常)
|
|
2184
|
+
if b == 0.0:
|
|
2185
|
+
if a == 0.0 or a != a:
|
|
2186
|
+
return float('nan')
|
|
2187
|
+
return float('inf') if a > 0 else float('-inf')
|
|
2188
|
+
return a / b
|
|
2189
|
+
|
|
2190
|
+
def _flat0(val):
|
|
2191
|
+
v = val.tolist()
|
|
2192
|
+
while isinstance(v, list):
|
|
2193
|
+
v = v[0]
|
|
2194
|
+
return float(v)
|
|
2195
|
+
|
|
2196
|
+
def _inv_or_nan(sub):
|
|
2197
|
+
# 求逆失败(奇异/非有限)→ 全 nan 矩阵(gufunc errstate
|
|
2198
|
+
# 语义);返回 (矩阵, 是否失败)
|
|
2199
|
+
try:
|
|
2200
|
+
return linalg_module.inv(sub), False
|
|
2201
|
+
except Exception:
|
|
2202
|
+
n2 = sub.shape[-1]
|
|
2203
|
+
is_c = _is_complex_arr(sub)
|
|
2204
|
+
nv = complex(0.0, float('nan')) if is_c else float('nan')
|
|
2205
|
+
return ndarray([[nv] * n2 for _ in range(n2)]), True
|
|
2206
|
+
|
|
2207
|
+
def _sum_axis(vals, ax):
|
|
2208
|
+
# 2-d 嵌套列表轴和(ax=-2 列和 / ax=-1 行和);nan 传播
|
|
2209
|
+
if ax == -2:
|
|
2210
|
+
n = len(vals[0]) if vals else 0
|
|
2211
|
+
return [sum(vals[i][j] for i in range(len(vals)))
|
|
2212
|
+
for j in range(n)]
|
|
2213
|
+
return [sum(row) for row in vals]
|
|
2214
|
+
|
|
2215
|
+
def _extreme(vals, mode):
|
|
2216
|
+
# max/min 语义:任一 nan → nan(Rust 归约用 f64::max/min
|
|
2217
|
+
# fold:忽略 nan、全 nan 返回 ∓inf,不兼容)
|
|
2218
|
+
m = None
|
|
2219
|
+
for v in vals:
|
|
2220
|
+
if v != v:
|
|
2221
|
+
return float('nan')
|
|
2222
|
+
if m is None or (v > m if mode == 'max' else v < m):
|
|
2223
|
+
m = v
|
|
2224
|
+
return m if m is not None else float('nan')
|
|
2225
|
+
|
|
2226
|
+
def _one(sub):
|
|
2227
|
+
if p is None or p in (2, -2):
|
|
2228
|
+
# 与公开 svd 同算法/同 dtype → 值与测试参照位级一致;
|
|
2229
|
+
# 非有限输入公开 svd 抛异常 → 回退裸 _svd_jacobi
|
|
2230
|
+
# (nan/inf 传播到结果,与 errstate 语义一致)
|
|
2231
|
+
try:
|
|
2232
|
+
s = linalg_module.svd(sub, compute_uv=False).tolist()
|
|
2233
|
+
except Exception:
|
|
2234
|
+
s = [float(abs(v)) for v in
|
|
2235
|
+
_svd_jacobi(sub.tolist(), False, False).tolist()]
|
|
2236
|
+
if not s:
|
|
2237
|
+
r = float('nan')
|
|
2238
|
+
elif p == -2:
|
|
2239
|
+
r = _div(s[-1], s[0])
|
|
2240
|
+
else:
|
|
2241
|
+
r = _div(s[0], s[-1])
|
|
2242
|
+
else:
|
|
2243
|
+
invx, inv_failed = _inv_or_nan(sub)
|
|
2244
|
+
if p == 'nuc':
|
|
2245
|
+
# 不能用 norm():nan 会使其抛异常;svd 对 nan/不收敛
|
|
2246
|
+
# 输入抛 LinAlgError → nan(errstate 语义)
|
|
2247
|
+
try:
|
|
2248
|
+
sx = _flat0(linalg_module.svd(
|
|
2249
|
+
sub, compute_uv=False).sum(-1))
|
|
2250
|
+
si = _flat0(linalg_module.svd(
|
|
2251
|
+
invx, compute_uv=False).sum(-1))
|
|
2252
|
+
r = sx * si
|
|
2253
|
+
except Exception:
|
|
2254
|
+
r = float('nan')
|
|
2255
|
+
elif p == 'fro':
|
|
2256
|
+
r = _flat0(_np.sqrt(
|
|
2257
|
+
(_np.abs(sub) ** 2).sum(-1).sum(-1)
|
|
2258
|
+
* (_np.abs(invx) ** 2).sum(-1).sum(-1)))
|
|
2259
|
+
elif _has_nan(sub) or inv_failed:
|
|
2260
|
+
# max/min 语义路径(结果必为 nan 或转 inf,
|
|
2261
|
+
# 无精度要求)
|
|
2262
|
+
asub = [[abs(v) for v in row] for row in sub.tolist()]
|
|
2263
|
+
ainv = [[abs(v) for v in row] for row in invx.tolist()]
|
|
2264
|
+
ax = -2 if p in (1, -1) else -1
|
|
2265
|
+
mode = 'max' if p in (1, _np.inf) else 'min'
|
|
2266
|
+
r = _extreme(_sum_axis(asub, ax), mode) * \
|
|
2267
|
+
_extreme(_sum_axis(ainv, ax), mode)
|
|
2268
|
+
else:
|
|
2269
|
+
# 与 _cond_impl 同运算链(同 dtype/同顺序)
|
|
2270
|
+
if p == 1:
|
|
2271
|
+
r = _flat0(_np.abs(sub).sum(-2).max(-1)) * \
|
|
2272
|
+
_flat0(_np.abs(invx).sum(-2).max(-1))
|
|
2273
|
+
elif p == -1:
|
|
2274
|
+
r = _flat0(_np.abs(sub).sum(-2).min(-1)) * \
|
|
2275
|
+
_flat0(_np.abs(invx).sum(-2).min(-1))
|
|
2276
|
+
elif p == _np.inf:
|
|
2277
|
+
r = _flat0(_np.abs(sub).sum(-1).max(-1)) * \
|
|
2278
|
+
_flat0(_np.abs(invx).sum(-1).max(-1))
|
|
2279
|
+
else:
|
|
2280
|
+
r = _flat0(_np.abs(sub).sum(-1).min(-1)) * \
|
|
2281
|
+
_flat0(_np.abs(invx).sum(-1).min(-1))
|
|
2282
|
+
# nan→inf:仅当 x 本身无 nan(nan 来自奇异/求逆失败)
|
|
2283
|
+
if r != r and not _has_nan(sub):
|
|
2284
|
+
r = float('inf')
|
|
2285
|
+
return r
|
|
2286
|
+
|
|
2287
|
+
if is_2d:
|
|
2288
|
+
r = _one(x_arr)
|
|
2289
|
+
scalar_cls = _np.float32 if res_dt == 'float32' else _np.float64
|
|
2290
|
+
return scalar_cls(r)
|
|
2291
|
+
parts = [_one(sub) for sub in subs]
|
|
2292
|
+
return ndarray(parts).reshape(lead).astype(res_dt)
|
|
2293
|
+
|
|
2294
|
+
@staticmethod
|
|
2295
|
+
def eigh(a, UPLO='L'):
|
|
2296
|
+
"""Hermitian 或对称矩阵特征分解(2.x 语义)。
|
|
2297
|
+
|
|
2298
|
+
返回 EighResult(eigenvalues, eigenvectors):eigenvalues (..., n)
|
|
2299
|
+
实数 dtype(f32/c64→f32,f64/c128/int→f64)升序;eigenvectors
|
|
2300
|
+
(..., n, n) dtype 随输入(int→f64)且保留 a 的 ndarray 子类;
|
|
2301
|
+
UPLO ∈ {'L','l','U','u'} 指定使用哪一三角;stacked (..., n, n)
|
|
2302
|
+
支持任意 lead 维;空尺寸返回同形状空数组;非方阵/非法 UPLO
|
|
2303
|
+
抛 ValueError。实对称走循环 Jacobi,复 Hermitian 走 2n 实嵌入。
|
|
2304
|
+
"""
|
|
2305
|
+
from rsarray import ndarray
|
|
2306
|
+
from ._pylinalg import _stacked_2d, _herm_eigh
|
|
2307
|
+
|
|
2308
|
+
u = UPLO if isinstance(UPLO, str) else ''
|
|
2309
|
+
if u not in ('L', 'l', 'U', 'u'):
|
|
2310
|
+
raise ValueError(
|
|
2311
|
+
"eigh: UPLO must be one of ['L', 'l', 'U', 'u']")
|
|
2312
|
+
uplo = u.upper()
|
|
2313
|
+
|
|
2314
|
+
a = a if hasattr(a, '_array') else ndarray(a)
|
|
2315
|
+
shape = tuple(a.shape)
|
|
2316
|
+
if len(shape) < 2 or shape[-2] != shape[-1]:
|
|
2317
|
+
raise ValueError("eigh requires a square matrix")
|
|
2318
|
+
dt = getattr(a, '_dtype', 'float64')
|
|
2319
|
+
real_dt = 'float32' if dt in ('float32', 'complex64') \
|
|
2320
|
+
else 'float64'
|
|
2321
|
+
vec_dt = dt if dt.startswith(('float', 'complex')) else 'float64'
|
|
2322
|
+
|
|
2323
|
+
def _as_result(arr):
|
|
2324
|
+
# eigenvectors 保留 a 的 ndarray 子类(数组语义)
|
|
2325
|
+
at = type(a)
|
|
2326
|
+
if at is not ndarray and isinstance(a, ndarray):
|
|
2327
|
+
return at(arr)
|
|
2328
|
+
return arr
|
|
2329
|
+
|
|
2330
|
+
lead, subs = _stacked_2d(a)
|
|
2331
|
+
n = shape[-1]
|
|
2332
|
+
if n == 0:
|
|
2333
|
+
ev = ndarray([]).astype(real_dt).reshape(lead + (0,))
|
|
2334
|
+
ec = ndarray([]).astype(vec_dt).reshape(lead + (0, 0))
|
|
2335
|
+
return EighResult(_as_result(ev), _as_result(ec))
|
|
2336
|
+
if len(shape) == 2:
|
|
2337
|
+
ev, ec = _herm_eigh(a.tolist(), uplo)
|
|
2338
|
+
return EighResult(_as_result(ndarray(ev).astype(real_dt)),
|
|
2339
|
+
_as_result(ndarray(ec).astype(vec_dt)))
|
|
2340
|
+
eval_list = []
|
|
2341
|
+
evec_list = []
|
|
2342
|
+
for sub in subs:
|
|
2343
|
+
ev, ec = _herm_eigh(sub.tolist(), uplo)
|
|
2344
|
+
eval_list.append(ev)
|
|
2345
|
+
evec_list.append(ec)
|
|
2346
|
+
ev = ndarray(eval_list).reshape(lead + (n,)).astype(real_dt)
|
|
2347
|
+
ec = ndarray(evec_list).reshape(lead + (n, n)).astype(vec_dt)
|
|
2348
|
+
return EighResult(_as_result(ev), _as_result(ec))
|
|
2349
|
+
|
|
2350
|
+
@staticmethod
|
|
2351
|
+
def solve_banded(lower, upper, ab, b):
|
|
2352
|
+
"""求解带状线性方程组。"""
|
|
2353
|
+
return _wrap(_core.linalg.solve_banded(lower, upper, _ensure(ab), _ensure(b)))
|
|
2354
|
+
|
|
2355
|
+
@staticmethod
|
|
2356
|
+
def outer(a, b):
|
|
2357
|
+
"""外积(linalg.outer 兼容):输入必须为一维。"""
|
|
2358
|
+
import rsarray as _np
|
|
2359
|
+
a = _np.asarray(a)
|
|
2360
|
+
b = _np.asarray(b)
|
|
2361
|
+
if a.ndim != 1 or b.ndim != 1:
|
|
2362
|
+
raise ValueError("Input arrays must be one-dimensional")
|
|
2363
|
+
return a.reshape((-1, 1)) * b.reshape((1, -1))
|
|
2364
|
+
|
|
2365
|
+
@staticmethod
|
|
2366
|
+
def slogdet(a):
|
|
2367
|
+
"""(sign, log|det|) —— 2.x 语义:返回 SlogdetResult 命名元组
|
|
2368
|
+
(.sign/.logabsdet,可作 2 元组解包)。2-d 输入字段为标量(实输入
|
|
2369
|
+
float、复输入 complex,dtype 随输入);stacked 返回 (lead...) 数组;
|
|
2370
|
+
空矩阵 (0×0) → (1, 0);奇异 → (0, -inf);全部尺寸走纯 Python
|
|
2371
|
+
LU(``_py_slogdet``)。
|
|
2372
|
+
"""
|
|
2373
|
+
from rsarray import (ndarray, float32, float64, complex64,
|
|
2374
|
+
complex128)
|
|
2375
|
+
from ._pylinalg import (_common_type, _real_dtype, _py_slogdet,
|
|
2376
|
+
_stacked_2d)
|
|
2377
|
+
_SCALAR = {'float32': float32, 'float64': float64,
|
|
2378
|
+
'complex64': complex64, 'complex128': complex128}
|
|
2379
|
+
|
|
2380
|
+
a_arr = a if hasattr(a, '_array') else ndarray(a)
|
|
2381
|
+
shape = tuple(a_arr.shape)
|
|
2382
|
+
if len(shape) < 2 or shape[-2] != shape[-1]:
|
|
2383
|
+
raise ValueError("slogdet requires a square matrix")
|
|
2384
|
+
_, res_dt = _common_type(getattr(a_arr, '_dtype', 'float64'))
|
|
2385
|
+
real_dt = _real_dtype(res_dt)
|
|
2386
|
+
if len(shape) == 2:
|
|
2387
|
+
sign, logabs = _py_slogdet(a_arr.tolist())
|
|
2388
|
+
return SlogdetResult(_SCALAR[res_dt](sign),
|
|
2389
|
+
_SCALAR[real_dt](logabs))
|
|
2390
|
+
lead, subs = _stacked_2d(a_arr)
|
|
2391
|
+
signs, logabs = zip(*(_py_slogdet(sub.tolist()) for sub in subs))
|
|
2392
|
+
return SlogdetResult(
|
|
2393
|
+
ndarray(list(signs)).astype(res_dt).reshape(lead),
|
|
2394
|
+
ndarray(list(logabs)).astype(real_dt).reshape(lead))
|
|
2395
|
+
|
|
2396
|
+
@staticmethod
|
|
2397
|
+
def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
|
|
2398
|
+
"""向量叉积(linalg.cross 兼容)。"""
|
|
2399
|
+
import rsarray as _np
|
|
2400
|
+
if axis is not None:
|
|
2401
|
+
axisa = axisb = axisc = axis
|
|
2402
|
+
a = _np.asarray(a)
|
|
2403
|
+
b = _np.asarray(b)
|
|
2404
|
+
if a.ndim:
|
|
2405
|
+
a = _np.moveaxis(a, axisa, -1)
|
|
2406
|
+
if b.ndim:
|
|
2407
|
+
b = _np.moveaxis(b, axisb, -1)
|
|
2408
|
+
if a.shape[-1] != 3 or b.shape[-1] != 3:
|
|
2409
|
+
raise ValueError(
|
|
2410
|
+
"input arrays must be (arrays of) 3-dimensional vectors")
|
|
2411
|
+
c0 = a[..., 1] * b[..., 2] - a[..., 2] * b[..., 1]
|
|
2412
|
+
c1 = a[..., 2] * b[..., 0] - a[..., 0] * b[..., 2]
|
|
2413
|
+
c2 = a[..., 0] * b[..., 1] - a[..., 1] * b[..., 0]
|
|
2414
|
+
out = _np.stack((c0, c1, c2), axis=-1)
|
|
2415
|
+
if axisc != -1:
|
|
2416
|
+
out = _np.moveaxis(out, -1, axisc)
|
|
2417
|
+
return out
|
|
2418
|
+
|
|
2419
|
+
@staticmethod
|
|
2420
|
+
def tensordot(a, b, axes=2):
|
|
2421
|
+
"""张量收缩(linalg.tensordot 兼容)。"""
|
|
2422
|
+
import rsarray as _np
|
|
2423
|
+
a = _np.asarray(a)
|
|
2424
|
+
b = _np.asarray(b)
|
|
2425
|
+
if isinstance(axes, int):
|
|
2426
|
+
axa = tuple(range(a.ndim - axes, a.ndim))
|
|
2427
|
+
axb = tuple(range(axes))
|
|
2428
|
+
else:
|
|
2429
|
+
axa, axb = tuple(axes[0]), tuple(axes[1])
|
|
2430
|
+
akeep = [i for i in range(a.ndim) if i not in axa]
|
|
2431
|
+
bkeep = [i for i in range(b.ndim) if i not in axb]
|
|
2432
|
+
pa = akeep + list(axa)
|
|
2433
|
+
pb = list(axb) + bkeep
|
|
2434
|
+
a2 = a.transpose(pa) if a.ndim > 1 else a
|
|
2435
|
+
b2 = b.transpose(pb) if b.ndim > 1 else b
|
|
2436
|
+
k = 1
|
|
2437
|
+
for i in axa:
|
|
2438
|
+
k *= a.shape[i]
|
|
2439
|
+
if k == 0:
|
|
2440
|
+
k = 1
|
|
2441
|
+
a3 = a2.reshape((-1, k)) if a2.ndim > 0 and a2.size >= 0 else a2.reshape((k,))
|
|
2442
|
+
b3 = b2.reshape((k, -1)) if b2.ndim > 0 and b2.size >= 0 else b2.reshape((k,))
|
|
2443
|
+
c = _np.matmul(a3, b3)
|
|
2444
|
+
out_shape = (tuple(a.shape[i] for i in akeep)
|
|
2445
|
+
+ tuple(b.shape[i] for i in bkeep))
|
|
2446
|
+
return c.reshape(out_shape)
|
|
2447
|
+
|
|
2448
|
+
@staticmethod
|
|
2449
|
+
def tensorinv(a, ind=2):
|
|
2450
|
+
"""N 维数组的'逆'(linalg.tensorinv 兼容)。
|
|
2451
|
+
|
|
2452
|
+
a 的形状须'square':prod(a.shape[:ind]) == prod(a.shape[ind:]),
|
|
2453
|
+
否则抛 LinAlgError;ind 为不超过 a.ndim 的正整数(否则
|
|
2454
|
+
ValueError)。返回相对 tensordot(a, b, ind) 的逆,形状
|
|
2455
|
+
a.shape[ind:] + a.shape[:ind]。
|
|
2456
|
+
"""
|
|
2457
|
+
import rsarray as _np
|
|
2458
|
+
a = a if hasattr(a, '_array') else _np.asarray(a)
|
|
2459
|
+
shape = tuple(a.shape)
|
|
2460
|
+
nd = len(shape)
|
|
2461
|
+
if not (0 < ind <= nd):
|
|
2462
|
+
raise ValueError("Invalid value for ind.")
|
|
2463
|
+
m = 1
|
|
2464
|
+
for d in shape[:ind]:
|
|
2465
|
+
m *= d
|
|
2466
|
+
n = 1
|
|
2467
|
+
for d in shape[ind:]:
|
|
2468
|
+
n *= d
|
|
2469
|
+
if m != n:
|
|
2470
|
+
raise LinAlgError("Shape of a is not 'square'")
|
|
2471
|
+
A = a.reshape((m, n))
|
|
2472
|
+
return linalg_module.inv(A).reshape(shape[ind:] + shape[:ind])
|
|
2473
|
+
|
|
2474
|
+
@staticmethod
|
|
2475
|
+
def tensorsolve(a, b, axes=None):
|
|
2476
|
+
"""张量方程 a x = b 求解(linalg.tensorsolve 兼容)。
|
|
2477
|
+
|
|
2478
|
+
x 的全部指标与 a 的最右指标求和:tensordot(a, x,
|
|
2479
|
+
axes=x.ndim) == b;axes(int 元组)指定反转前移到 a 右端
|
|
2480
|
+
的轴,默认 None(不重排)。a 须满足
|
|
2481
|
+
prod(a.shape[b.ndim:]) == prod(a.shape[:b.ndim]),否则抛
|
|
2482
|
+
LinAlgError;x 形状为 a 的末 (a.ndim - b.ndim) 轴。
|
|
2483
|
+
"""
|
|
2484
|
+
import rsarray as _np
|
|
2485
|
+
a = a if hasattr(a, '_array') else _np.asarray(a)
|
|
2486
|
+
b = b if hasattr(b, '_array') else _np.asarray(b)
|
|
2487
|
+
an = len(tuple(a.shape))
|
|
2488
|
+
if axes is not None:
|
|
2489
|
+
allaxes = list(range(an))
|
|
2490
|
+
for k in axes:
|
|
2491
|
+
allaxes.remove(k)
|
|
2492
|
+
allaxes.insert(an, k)
|
|
2493
|
+
a = a.transpose(allaxes)
|
|
2494
|
+
bndim = len(tuple(b.shape))
|
|
2495
|
+
oldshape = a.shape[-(an - bndim):]
|
|
2496
|
+
prod = 1
|
|
2497
|
+
for k in oldshape:
|
|
2498
|
+
prod *= k
|
|
2499
|
+
if a.size != prod * prod:
|
|
2500
|
+
raise LinAlgError(
|
|
2501
|
+
"Input arrays must satisfy the requirement "
|
|
2502
|
+
"prod(a.shape[b.ndim:]) == prod(a.shape[:b.ndim])")
|
|
2503
|
+
A = a.reshape((prod, prod))
|
|
2504
|
+
bflat = b.reshape((-1,))
|
|
2505
|
+
x = linalg_module.solve(A, bflat)
|
|
2506
|
+
return x.reshape(tuple(oldshape))
|
|
2507
|
+
|
|
2508
|
+
@staticmethod
|
|
2509
|
+
def matrix_norm(x, ord=None, axis=(-2, -1), keepdims=False, **kwargs):
|
|
2510
|
+
"""矩阵范数(linalg.matrix_norm 兼容)。
|
|
2511
|
+
|
|
2512
|
+
Rust 层 norm 不接受元组 axis,这里按 数组语义纯 Python 实现:
|
|
2513
|
+
ord=None/'fro' 弗罗贝尼乌斯范数、1/-1 列和范数、2/-2 奇异值
|
|
2514
|
+
范数、'nuc' 核范数;支持 ndim>2 的批量切片与 keepdims。
|
|
2515
|
+
"""
|
|
2516
|
+
import rsarray as _np
|
|
2517
|
+
|
|
2518
|
+
def _mat_norm_2d(m, o):
|
|
2519
|
+
if 0 in tuple(m.shape):
|
|
2520
|
+
# 数组语义:空矩阵的各阶范数均为 0
|
|
2521
|
+
return 0.0
|
|
2522
|
+
if o in (None, 'fro'):
|
|
2523
|
+
return _np.sqrt(_np.sum(abs(m) ** 2))
|
|
2524
|
+
if o == 1:
|
|
2525
|
+
return _np.max(_np.sum(abs(m), axis=0))
|
|
2526
|
+
if o == -1:
|
|
2527
|
+
return _np.min(_np.sum(abs(m), axis=0))
|
|
2528
|
+
sv = linalg_module.svd(m, compute_uv=False)
|
|
2529
|
+
if sv.size == 0:
|
|
2530
|
+
return 0.0
|
|
2531
|
+
if o == 2:
|
|
2532
|
+
return sv.max()
|
|
2533
|
+
if o == -2:
|
|
2534
|
+
return sv.min()
|
|
2535
|
+
if o == 'nuc':
|
|
2536
|
+
return sv.sum()
|
|
2537
|
+
raise ValueError(f"invalid norm order {o!r} for matrix norm")
|
|
2538
|
+
|
|
2539
|
+
x = _np.asarray(x)
|
|
2540
|
+
axes = tuple(axis) if isinstance(axis, tuple) else (axis,)
|
|
2541
|
+
a0, a1 = axes[0] % x.ndim, axes[1] % x.ndim
|
|
2542
|
+
if x.ndim == 2:
|
|
2543
|
+
res = _mat_norm_2d(x, ord)
|
|
2544
|
+
else:
|
|
2545
|
+
other = [i for i in range(x.ndim) if i not in (a0, a1)]
|
|
2546
|
+
moved = x.transpose(other + [a0, a1])
|
|
2547
|
+
shp = moved.shape
|
|
2548
|
+
flat = moved.reshape((-1, shp[-2], shp[-1]))
|
|
2549
|
+
parts = [_mat_norm_2d(flat[i], ord) for i in range(flat.shape[0])]
|
|
2550
|
+
res = _np.asarray(parts).reshape(tuple(shp[:-2]))
|
|
2551
|
+
if keepdims:
|
|
2552
|
+
shp = list(x.shape)
|
|
2553
|
+
shp[a0] = 1
|
|
2554
|
+
shp[a1] = 1
|
|
2555
|
+
res = _np.asarray(res).reshape(tuple(shp))
|
|
2556
|
+
return res
|
|
2557
|
+
|
|
2558
|
+
@staticmethod
|
|
2559
|
+
def matrix_transpose(x, axes=None):
|
|
2560
|
+
"""矩阵转置(linalg.matrix_transpose 兼容)。"""
|
|
2561
|
+
import rsarray as _np
|
|
2562
|
+
x = _np.asarray(x)
|
|
2563
|
+
if x.ndim < 2:
|
|
2564
|
+
raise ValueError("array must be at least 2-dimensional")
|
|
2565
|
+
if axes is None:
|
|
2566
|
+
return x.T
|
|
2567
|
+
return x.transpose(axes)
|
|
2568
|
+
|
|
2569
|
+
@staticmethod
|
|
2570
|
+
def eigvalsh(a, UPLO='L'):
|
|
2571
|
+
"""Hermitian/对称矩阵特征值(linalg.eigvalsh 兼容)。
|
|
2572
|
+
|
|
2573
|
+
返回升序实数 dtype ndarray(f32/c64→f32,f64/c128/int→f64);
|
|
2574
|
+
UPLO/stacked/空尺寸语义同 eigh。
|
|
2575
|
+
"""
|
|
2576
|
+
return linalg_module.eigh(a, UPLO)[0]
|
|
2577
|
+
|
|
2578
|
+
|
|
2579
|
+
def issymmetric(a, tol=None):
|
|
2580
|
+
"""判断矩阵是否对称。"""
|
|
2581
|
+
from rsarray import ndarray
|
|
2582
|
+
a_arr = a if hasattr(a, '_array') else ndarray(a)
|
|
2583
|
+
if len(a_arr.shape) != 2 or a_arr.shape[0] != a_arr.shape[1]:
|
|
2584
|
+
return False
|
|
2585
|
+
at = a_arr.T
|
|
2586
|
+
if tol is None:
|
|
2587
|
+
diff = abs(a_arr - at)
|
|
2588
|
+
return diff.max() < 1e-10
|
|
2589
|
+
diff = abs(a_arr - at)
|
|
2590
|
+
return diff.max() <= tol
|
|
2591
|
+
|
|
2592
|
+
|
|
2593
|
+
# 将 linalg_module 的公有方法同时暴露为模块级函数,
|
|
2594
|
+
# 兼容 风格的 `from rsarray.linalg import det, inv, norm, solve, ...`。
|
|
2595
|
+
_this_module = _sys.modules[__name__]
|
|
2596
|
+
for _name in dir(linalg_module):
|
|
2597
|
+
if not _name.startswith('_'):
|
|
2598
|
+
setattr(_this_module, _name, getattr(linalg_module, _name))
|
|
2599
|
+
del _this_module, _name
|
|
2600
|
+
|
|
2601
|
+
|
|
2602
|
+
# 多矩阵连乘(linalg.multi_dot 兼容):DP 求最优乘法顺序。
|
|
2603
|
+
from ._linalg import _multi_dot_matrix_chain_order, multi_dot # noqa: E402,F401
|