rsarray 1.2.10__cp313-cp313-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.cp313-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,965 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""数学函数模块 - 所有实现位于 Rust,这里仅保留薄包装。"""
|
|
3
|
+
|
|
4
|
+
import builtins
|
|
5
|
+
import cmath as _cmath
|
|
6
|
+
import math as _math
|
|
7
|
+
import operator as _pyop
|
|
8
|
+
|
|
9
|
+
import rsarray.num_core as _core
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _nd():
|
|
13
|
+
from .__init__ import ndarray as _n
|
|
14
|
+
return _n
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _wrap(result):
|
|
18
|
+
dt = "complex128" if getattr(result, 'is_complex', False) else "float64"
|
|
19
|
+
return _nd()._wrap(result, _dtype=dt)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _wrap_bool(result):
|
|
23
|
+
"""比较/逻辑运算结果按布尔数组返回(与标准语义一致,可直接用作掩码索引)。"""
|
|
24
|
+
return _nd()._wrap(result, _dtype="bool")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _ensure_raw(a):
|
|
28
|
+
if hasattr(a, '_array'):
|
|
29
|
+
return a._array
|
|
30
|
+
if hasattr(a, '_data'):
|
|
31
|
+
# ma MaskedArray / masked 常量:递归取底层 ndarray
|
|
32
|
+
return _ensure_raw(a._data)
|
|
33
|
+
if hasattr(a, '__class__') and a.__class__.__name__ == 'ndarray':
|
|
34
|
+
return a
|
|
35
|
+
return _core.ndarray(a)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# ========== 复数 ufunc 路径(Rust core 无复数循环,Python 层逐元素) ==========
|
|
39
|
+
def _is_complex_arr(x):
|
|
40
|
+
return str(getattr(x, '_dtype', '')).startswith('complex')
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _cflat(v):
|
|
44
|
+
out = []
|
|
45
|
+
|
|
46
|
+
def rec(x):
|
|
47
|
+
if isinstance(x, list):
|
|
48
|
+
for y in x:
|
|
49
|
+
rec(y)
|
|
50
|
+
else:
|
|
51
|
+
out.append(x)
|
|
52
|
+
|
|
53
|
+
rec(v)
|
|
54
|
+
return out
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
# C99 复数特殊值语义(G.6.2 clog / G.6.1 cexp / G.6.5 cpow)。
|
|
58
|
+
# CPython 内建 complex **(bpo-44698)及部分平台 libm cpow 不严格符合
|
|
59
|
+
# C99(如 (inf+0j)**2 应为 inf+nanj),按 数组的 C99 规则实现。
|
|
60
|
+
def _c_log_c99(z):
|
|
61
|
+
x, y = z.real, z.imag
|
|
62
|
+
if _math.isnan(x) or _math.isnan(y):
|
|
63
|
+
return complex(_math.nan, _math.nan)
|
|
64
|
+
if _math.isinf(x) or _math.isinf(y):
|
|
65
|
+
if _math.isinf(y):
|
|
66
|
+
return complex(_math.inf, _math.copysign(0.25 * _math.pi, y))
|
|
67
|
+
if y == 0.0:
|
|
68
|
+
if x > 0:
|
|
69
|
+
return complex(_math.inf, _math.copysign(0.0, y))
|
|
70
|
+
return complex(_math.inf, _math.pi)
|
|
71
|
+
if x > 0:
|
|
72
|
+
return complex(_math.inf, _math.copysign(0.0, y))
|
|
73
|
+
if x < 0:
|
|
74
|
+
return complex(_math.inf, _math.copysign(_math.pi, y))
|
|
75
|
+
return complex(_math.inf, _math.copysign(0.5 * _math.pi, y))
|
|
76
|
+
if x == 0.0 and y == 0.0:
|
|
77
|
+
return complex(-_math.inf, _math.copysign(0.0, y))
|
|
78
|
+
return complex(_math.log(_math.hypot(x, y)), _math.atan2(y, x))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _c_exp_c99(z):
|
|
82
|
+
x, y = z.real, z.imag
|
|
83
|
+
if _math.isinf(x):
|
|
84
|
+
if y == 0.0:
|
|
85
|
+
return complex(_math.copysign(_math.inf, x),
|
|
86
|
+
_math.copysign(0.0, y))
|
|
87
|
+
if _math.isfinite(y):
|
|
88
|
+
return complex(_math.copysign(_math.inf, x), _math.nan)
|
|
89
|
+
return complex(_math.inf if x > 0 else _math.nan, _math.nan)
|
|
90
|
+
if _math.isinf(y) or _math.isnan(y):
|
|
91
|
+
return complex(_math.nan, _math.nan)
|
|
92
|
+
if _math.isnan(x):
|
|
93
|
+
return complex(_math.nan, _math.nan)
|
|
94
|
+
r = _math.exp(x)
|
|
95
|
+
return complex(r * _math.cos(y), r * _math.sin(y))
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _c_pow_c99(a, b):
|
|
99
|
+
"""C99 G.6.5 c_pow:z^w = exp(w log z),含 z^±0=1、1^z=1 特殊值规则。"""
|
|
100
|
+
x, y = a.real, a.imag
|
|
101
|
+
u, v = b.real, b.imag
|
|
102
|
+
if u == 0.0 and v == 0.0:
|
|
103
|
+
return complex(1.0, 0.0)
|
|
104
|
+
if x == 1.0 and y == 0.0:
|
|
105
|
+
return complex(1.0, 0.0)
|
|
106
|
+
return _c_exp_c99(complex(b) * _c_log_c99(a))
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _complex_unary(x, fn):
|
|
110
|
+
t = x.tolist()
|
|
111
|
+
f = _cflat(t) if isinstance(t, list) else [t]
|
|
112
|
+
res = [fn(complex(v)) for v in f]
|
|
113
|
+
sh = tuple(getattr(x, 'shape', ()))
|
|
114
|
+
out = _nd()(res, _dtype=getattr(x, '_dtype', 'complex128'))
|
|
115
|
+
if sh == ():
|
|
116
|
+
return out.reshape(())
|
|
117
|
+
if out.ndim < len(sh) and sh:
|
|
118
|
+
return out.reshape(sh)
|
|
119
|
+
return out
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _sqrt_complex(x):
|
|
123
|
+
# libm csqrt 自带无溢出 rescaling 与 C99 特殊值
|
|
124
|
+
return _complex_unary(x, lambda z: _cmath.sqrt(z))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _square_complex(x):
|
|
128
|
+
# Python 复数乘法即 C99 IEEE 语义(0×inf→nan、inf−inf→nan)
|
|
129
|
+
return _complex_unary(x, lambda z: z * z)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _power_complex(x1, x2):
|
|
133
|
+
from . import char as _char
|
|
134
|
+
is1 = hasattr(x1, '_array')
|
|
135
|
+
is2 = hasattr(x2, '_array')
|
|
136
|
+
sh1 = tuple(getattr(x1, 'shape', ())) if is1 else ()
|
|
137
|
+
sh2 = tuple(getattr(x2, 'shape', ())) if is2 else ()
|
|
138
|
+
bshape = _char._bc_shapes([sh1, sh2])
|
|
139
|
+
f1 = _cflat(x1.tolist()) if is1 else [complex(x1)]
|
|
140
|
+
f2 = _cflat(x2.tolist()) if is2 else [complex(x2)]
|
|
141
|
+
if bshape == ():
|
|
142
|
+
res = [_c_pow_c99(complex(f1[0]), complex(f2[0]))]
|
|
143
|
+
else:
|
|
144
|
+
res = [_c_pow_c99(complex(_char._bc_get(f1, sh1, i)),
|
|
145
|
+
complex(_char._bc_get(f2, sh2, i)))
|
|
146
|
+
for i in _char._iter_indices(bshape)]
|
|
147
|
+
dts = [str(getattr(a, '_dtype', '')) for a in (x1, x2)
|
|
148
|
+
if str(getattr(a, '_dtype', '')).startswith('complex')]
|
|
149
|
+
dt = 'complex128' if 'complex128' in dts else (dts[0] if dts else 'complex128')
|
|
150
|
+
out = _nd()(res, _dtype=dt)
|
|
151
|
+
if bshape == ():
|
|
152
|
+
return out.reshape(())
|
|
153
|
+
if out.ndim < len(bshape) and bshape:
|
|
154
|
+
return out.reshape(bshape)
|
|
155
|
+
return out
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
# ========== 三角函数 ==========
|
|
159
|
+
def sin(x):
|
|
160
|
+
"""计算正弦值。"""
|
|
161
|
+
return _wrap(_core.sin(_ensure_raw(x)))
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def cos(x):
|
|
165
|
+
"""计算余弦值。"""
|
|
166
|
+
return _wrap(_core.cos(_ensure_raw(x)))
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def tan(x):
|
|
170
|
+
"""计算正切值。"""
|
|
171
|
+
return _wrap(_core.tan(_ensure_raw(x)))
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def arcsin(x):
|
|
175
|
+
"""计算反正弦值。"""
|
|
176
|
+
return _wrap(_core.asin(_ensure_raw(x)))
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def arccos(x):
|
|
180
|
+
"""计算反余弦值。"""
|
|
181
|
+
return _wrap(_core.acos(_ensure_raw(x)))
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def arctan(x):
|
|
185
|
+
"""计算反正切值。"""
|
|
186
|
+
return _wrap(_core.atan(_ensure_raw(x)))
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def arctan2(x1, x2):
|
|
190
|
+
"""计算 x1/x2 的反正切值。"""
|
|
191
|
+
return _wrap(_core.arctan2(_ensure_raw(x1), _ensure_raw(x2)))
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def deg2rad(x):
|
|
195
|
+
"""将角度转换为弧度。"""
|
|
196
|
+
return _wrap(_core.deg2rad(_ensure_raw(x)))
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def rad2deg(x):
|
|
200
|
+
"""将弧度转换为角度。"""
|
|
201
|
+
return _wrap(_core.rad2deg(_ensure_raw(x)))
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
# ========== 双曲函数 ==========
|
|
205
|
+
def sinh(x):
|
|
206
|
+
"""计算双曲正弦值。"""
|
|
207
|
+
return _wrap(_core.sinh(_ensure_raw(x)))
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def cosh(x):
|
|
211
|
+
"""计算双曲余弦值。"""
|
|
212
|
+
return _wrap(_core.cosh(_ensure_raw(x)))
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def tanh(x):
|
|
216
|
+
"""计算双曲正切值。"""
|
|
217
|
+
return _wrap(_core.tanh(_ensure_raw(x)))
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def arcsinh(x):
|
|
221
|
+
"""计算反双曲正弦值。"""
|
|
222
|
+
return _wrap(_core.asinh(_ensure_raw(x)))
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def arccosh(x):
|
|
226
|
+
"""计算反双曲余弦值。"""
|
|
227
|
+
return _wrap(_core.acosh(_ensure_raw(x)))
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def arctanh(x):
|
|
231
|
+
"""计算反双曲正切值。"""
|
|
232
|
+
return _wrap(_core.atanh(_ensure_raw(x)))
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
# ========== 指数和对数函数 ==========
|
|
236
|
+
def exp(x):
|
|
237
|
+
"""计算指数值 e^x。"""
|
|
238
|
+
return _wrap(_core.exp(_ensure_raw(x)))
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def expm1(x):
|
|
242
|
+
"""计算 exp(x) - 1。"""
|
|
243
|
+
return _wrap(_core.expm1(_ensure_raw(x)))
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def log(x):
|
|
247
|
+
"""计算自然对数。"""
|
|
248
|
+
return _wrap(_core.log(_ensure_raw(x)))
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def log10(x):
|
|
252
|
+
"""计算以 10 为底的对数。"""
|
|
253
|
+
return _wrap(_core.log10(_ensure_raw(x)))
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def log2(x):
|
|
257
|
+
"""计算以 2 为底的对数。"""
|
|
258
|
+
return _wrap(_core.log2(_ensure_raw(x)))
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def log1p(x):
|
|
262
|
+
"""计算 log(1 + x)。"""
|
|
263
|
+
return _wrap(_core.log1p(_ensure_raw(x)))
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
# ========== 舍入函数 ==========
|
|
267
|
+
def around(a, decimals=0):
|
|
268
|
+
"""四舍六入五成双(数组语义:rint(x*10^d)/10^d 的 half-even)。
|
|
269
|
+
|
|
270
|
+
与 Python round 的十进制正确舍入算法不同:6.35*10 恰好二进制舍入到
|
|
271
|
+
63.5 → rint half-even → 64 → 6.4(行为)。
|
|
272
|
+
"""
|
|
273
|
+
import builtins as _b
|
|
274
|
+
arr = a if hasattr(a, '_array') else _nd()(a)
|
|
275
|
+
_dt = str(getattr(arr, '_dtype', 'float64'))
|
|
276
|
+
if _dt in ('int8', 'int16', 'int32', 'int64', 'uint8', 'uint16',
|
|
277
|
+
'uint32', 'uint64', 'bool') and decimals >= 0:
|
|
278
|
+
# 数组语义:整数数组 decimals>=0 时 around 为无操作
|
|
279
|
+
return arr.copy()
|
|
280
|
+
|
|
281
|
+
def _rnd(v):
|
|
282
|
+
if decimals >= 0:
|
|
283
|
+
_f = 10 ** decimals
|
|
284
|
+
return _b.round(v * _f) / _f
|
|
285
|
+
_f = 10 ** (-decimals)
|
|
286
|
+
return _b.round(v / _f) * _f
|
|
287
|
+
|
|
288
|
+
def _rec(x):
|
|
289
|
+
out = []
|
|
290
|
+
for v in x:
|
|
291
|
+
if isinstance(v, list):
|
|
292
|
+
out.append(_rec(v))
|
|
293
|
+
else:
|
|
294
|
+
out.append(_rnd(v))
|
|
295
|
+
return out
|
|
296
|
+
|
|
297
|
+
try:
|
|
298
|
+
tl = arr.tolist()
|
|
299
|
+
if not isinstance(tl, list):
|
|
300
|
+
tl = [tl]
|
|
301
|
+
res = _nd()(_rec(tl))
|
|
302
|
+
if getattr(arr, 'ndim', 0) == 0:
|
|
303
|
+
res = res.reshape(())
|
|
304
|
+
return res.astype(_dt) if _dt != 'float64' else res
|
|
305
|
+
return res.astype(_dt) if _dt != 'float64' else res
|
|
306
|
+
except Exception:
|
|
307
|
+
return arr.round(decimals)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def floor(x):
|
|
311
|
+
"""向下取整。"""
|
|
312
|
+
return _wrap(_core.floor(_ensure_raw(x)))
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def ceil(x):
|
|
316
|
+
"""向上取整。"""
|
|
317
|
+
return _wrap(_core.ceil(_ensure_raw(x)))
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def trunc(x):
|
|
321
|
+
"""截断小数部分。"""
|
|
322
|
+
return _wrap(_core.trunc(_ensure_raw(x)))
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def fix(x, out=None, **kwargs):
|
|
326
|
+
"""向零取整(与标准语义一致:已弃用,等价于 trunc/ceil)。"""
|
|
327
|
+
import warnings as _warnings
|
|
328
|
+
_warnings.warn(
|
|
329
|
+
"rsarray.fix is deprecated: use rsarray.trunc/ceil instead",
|
|
330
|
+
DeprecationWarning, stacklevel=2)
|
|
331
|
+
np = _nd()
|
|
332
|
+
raw = _core.fix(_ensure_raw(x))
|
|
333
|
+
if hasattr(x, '_array'):
|
|
334
|
+
res = _wrap(raw)
|
|
335
|
+
# ufunc 子类保持:经输入对象的 __array_wrap__ 包装(数组语义)。
|
|
336
|
+
# 注意 _nd() 返回的就是 ndarray 类本身。
|
|
337
|
+
if type(x) is not np and hasattr(type(x), '__array_wrap__'):
|
|
338
|
+
res = x.__array_wrap__(res, context=None, return_scalar=False)
|
|
339
|
+
if out is not None:
|
|
340
|
+
out[...] = res
|
|
341
|
+
return out
|
|
342
|
+
return res
|
|
343
|
+
# 标量输入返回 float64 标量(数组语义),不衰减为 ndarray。
|
|
344
|
+
from .__init__ import float64 as _float64
|
|
345
|
+
val = float(raw.tolist())
|
|
346
|
+
if out is not None:
|
|
347
|
+
out[...] = val
|
|
348
|
+
return out
|
|
349
|
+
return _float64(val)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
# ========== 特殊函数 ==========
|
|
353
|
+
def _sqrt_has_negative(x):
|
|
354
|
+
try:
|
|
355
|
+
from ._extra import _fp_flat
|
|
356
|
+
if hasattr(x, '_array'):
|
|
357
|
+
return builtins.any(v < 0 for v in _fp_flat(x.tolist()))
|
|
358
|
+
return x < 0
|
|
359
|
+
except Exception:
|
|
360
|
+
return False
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def sqrt(x):
|
|
364
|
+
"""计算平方根(负数输入按 errstate 触发 invalid 浮点错误事件)。"""
|
|
365
|
+
if _is_complex_arr(x):
|
|
366
|
+
return _sqrt_complex(x)
|
|
367
|
+
raw = _ensure_raw(x)
|
|
368
|
+
res = _wrap(_core.sqrt(raw))
|
|
369
|
+
if _sqrt_has_negative(x):
|
|
370
|
+
from ._extra import _fp_fire
|
|
371
|
+
_fp_fire('invalid', "invalid value encountered in sqrt")
|
|
372
|
+
return res
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def square(x):
|
|
376
|
+
"""计算平方。"""
|
|
377
|
+
if _is_complex_arr(x):
|
|
378
|
+
return _square_complex(x)
|
|
379
|
+
return _wrap(_core.square(_ensure_raw(x)))
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def cbrt(x):
|
|
383
|
+
"""计算立方根。"""
|
|
384
|
+
return _wrap(_core.cbrt(_ensure_raw(x)))
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def absolute(x, out=None):
|
|
388
|
+
"""计算绝对值。"""
|
|
389
|
+
import builtins
|
|
390
|
+
if isinstance(x, complex):
|
|
391
|
+
from .__init__ import ndarray
|
|
392
|
+
res = ndarray([builtins.abs(x)])
|
|
393
|
+
# 数组语义:bool 数组的 abs 保持 bool(恒等映射);float 化后
|
|
394
|
+
# 位运算会失真(~0.0f 按位翻转 = -1.0)。
|
|
395
|
+
elif getattr(x, '_dtype', None) == 'bool':
|
|
396
|
+
res = x.copy()
|
|
397
|
+
else:
|
|
398
|
+
res = _wrap(_core.abs(_ensure_raw(x)))
|
|
399
|
+
if out is not None:
|
|
400
|
+
try:
|
|
401
|
+
out[...] = res
|
|
402
|
+
return out
|
|
403
|
+
except Exception:
|
|
404
|
+
pass
|
|
405
|
+
return res
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
abs = absolute
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def sign(x):
|
|
412
|
+
"""计算符号函数。"""
|
|
413
|
+
return _wrap(_core.sign(_ensure_raw(x)))
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def clip(a, a_min, a_max):
|
|
417
|
+
"""限制数组值在指定范围内。"""
|
|
418
|
+
return _wrap(_core.clip(_ensure_raw(a), a_min, a_max))
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def sinc(x):
|
|
422
|
+
"""计算 sinc 函数。"""
|
|
423
|
+
return _wrap(_core.sinc(_ensure_raw(x)))
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def heaviside(x, h0=0.5):
|
|
427
|
+
"""计算 Heaviside 阶跃函数。"""
|
|
428
|
+
return _wrap(_core.heaviside(_ensure_raw(x), h0))
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
# ========== 算术运算 ==========
|
|
432
|
+
def add(x1, x2, out=None, **kwargs):
|
|
433
|
+
"""逐元素加法。NEP50:Python 弱标量不提升结果 dtype(uint8+3→uint8);
|
|
434
|
+
str 标量按 np.copyto 同款宽松转换(无法解析按 0),使 ufunc 与
|
|
435
|
+
copyto 的 casting 行为一致(casting 关键字接受但不参与弱标量判定)。"""
|
|
436
|
+
# ma.masked 常量短路(数组语义:add(masked, x) → masked 单例)
|
|
437
|
+
if getattr(x1, '_ma_masked_self', False):
|
|
438
|
+
return x1
|
|
439
|
+
if getattr(x2, '_ma_masked_self', False):
|
|
440
|
+
return x2
|
|
441
|
+
kwargs.pop('casting', None)
|
|
442
|
+
# 字符串数组 + 字符串数组/标量 = 逐元素连接(数组语义);结果超
|
|
443
|
+
# intc max → TypeError(large_string_addition 回归)
|
|
444
|
+
if getattr(x1, '_str_dtype', None) is not None:
|
|
445
|
+
from rsarray import char as _char_add
|
|
446
|
+
res = _char_add.add(x1, x2)
|
|
447
|
+
if out is not None:
|
|
448
|
+
try:
|
|
449
|
+
out[...] = res
|
|
450
|
+
except Exception:
|
|
451
|
+
pass
|
|
452
|
+
return out
|
|
453
|
+
return res
|
|
454
|
+
if (hasattr(x1, '_array')
|
|
455
|
+
and isinstance(x2, (builtins.int, builtins.float,
|
|
456
|
+
builtins.complex, builtins.str))):
|
|
457
|
+
dt = getattr(x1, '_dtype', 'float64')
|
|
458
|
+
if isinstance(x2, builtins.str):
|
|
459
|
+
# copyto 语义:无法解析的字符串标量按 0 参与数值运算
|
|
460
|
+
try:
|
|
461
|
+
x2v = builtins.float(x2)
|
|
462
|
+
except ValueError:
|
|
463
|
+
x2v = 0.0
|
|
464
|
+
if dt == 'string_':
|
|
465
|
+
res = x1.copy()
|
|
466
|
+
else:
|
|
467
|
+
res = x1 + x2v
|
|
468
|
+
else:
|
|
469
|
+
res = x1 + x2
|
|
470
|
+
if out is not None:
|
|
471
|
+
try:
|
|
472
|
+
out[...] = res
|
|
473
|
+
except Exception:
|
|
474
|
+
pass
|
|
475
|
+
return out
|
|
476
|
+
return res
|
|
477
|
+
res = _wrap(_core.add(_ensure_raw(x1), _ensure_raw(x2)))
|
|
478
|
+
if out is not None:
|
|
479
|
+
try:
|
|
480
|
+
out[...] = res
|
|
481
|
+
except Exception:
|
|
482
|
+
pass
|
|
483
|
+
return res
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _add_outer(x1, x2):
|
|
487
|
+
"""ufunc.outer 语义:输入先 flatten 为一维,外积 a[i]+b[j]。"""
|
|
488
|
+
import rsarray as _rn
|
|
489
|
+
a = _rn.asarray(x1).reshape((-1,))
|
|
490
|
+
b = _rn.asarray(x2).reshape((-1,))
|
|
491
|
+
return a.reshape((-1, 1)) + b.reshape((1, -1))
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
add.outer = _add_outer
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def subtract(x1, x2, out=None, **kwargs):
|
|
498
|
+
"""逐元素减法。"""
|
|
499
|
+
res = _wrap(_core.subtract(_ensure_raw(x1), _ensure_raw(x2)))
|
|
500
|
+
if out is not None:
|
|
501
|
+
try:
|
|
502
|
+
out[...] = res
|
|
503
|
+
except Exception:
|
|
504
|
+
pass
|
|
505
|
+
return res
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def multiply(x1, x2, out=None, **kwargs):
|
|
509
|
+
"""逐元素乘法。"""
|
|
510
|
+
res = _wrap(_core.multiply(_ensure_raw(x1), _ensure_raw(x2)))
|
|
511
|
+
if out is not None:
|
|
512
|
+
try:
|
|
513
|
+
out[...] = res
|
|
514
|
+
except Exception:
|
|
515
|
+
pass
|
|
516
|
+
return res
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def divide(x1, x2, out=None, **kwargs):
|
|
520
|
+
"""逐元素除法。"""
|
|
521
|
+
res = _wrap(_core.divide(_ensure_raw(x1), _ensure_raw(x2)))
|
|
522
|
+
from . import _extra as _ex
|
|
523
|
+
_ex._fp_divide_check(x1, x2, res, 'true_divide')
|
|
524
|
+
if out is not None:
|
|
525
|
+
try:
|
|
526
|
+
out[...] = res
|
|
527
|
+
except Exception:
|
|
528
|
+
pass
|
|
529
|
+
return res
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
_INT_BITS = {
|
|
533
|
+
'int8': (8, True), 'int16': (16, True), 'int32': (32, True), 'int64': (64, True),
|
|
534
|
+
'uint8': (8, False), 'uint16': (16, False), 'uint32': (32, False), 'uint64': (64, False),
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
_FLOAT_NAMES = frozenset(('float16', 'float32', 'float64', 'float', 'half', 'single', 'double'))
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def _dtype_name(dtype):
|
|
541
|
+
"""将 dtype 类型对象/字符串解析为名称。"""
|
|
542
|
+
if isinstance(dtype, str):
|
|
543
|
+
return dtype
|
|
544
|
+
return getattr(dtype, '__name__', str(dtype))
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def _is_arr(x):
|
|
548
|
+
return hasattr(x, '_array') or (hasattr(x, '__class__') and x.__class__.__name__ == 'ndarray')
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def _wrap_int(val, bits, signed):
|
|
552
|
+
"""按位宽将整数按二补数回绕(模拟定宽整数溢出)。"""
|
|
553
|
+
val &= (1 << bits) - 1
|
|
554
|
+
if signed and (val >> (bits - 1)):
|
|
555
|
+
val -= (1 << bits)
|
|
556
|
+
return val
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
def power(x1, x2, dtype=None):
|
|
560
|
+
"""逐元素幂运算。
|
|
561
|
+
|
|
562
|
+
指定 dtype 且 x1/x2 均为标量时,按目标类型语义计算:整数类型精确幂后
|
|
563
|
+
按位宽二补数回绕(与 定宽整数溢出一致),浮点类型返回浮点标量。
|
|
564
|
+
"""
|
|
565
|
+
if dtype is not None and not _is_arr(x1) and not _is_arr(x2):
|
|
566
|
+
name = _dtype_name(dtype)
|
|
567
|
+
if name in _INT_BITS:
|
|
568
|
+
bits, signed = _INT_BITS[name]
|
|
569
|
+
return _wrap_int(int(x1) ** int(x2), bits, signed)
|
|
570
|
+
if name in _FLOAT_NAMES:
|
|
571
|
+
return float(x1) ** float(x2)
|
|
572
|
+
if _is_complex_arr(x1) or _is_complex_arr(x2):
|
|
573
|
+
return _power_complex(x1, x2)
|
|
574
|
+
raw_result = _core.power(_ensure_raw(x1), _ensure_raw(x2))
|
|
575
|
+
dtype = getattr(x1, '_dtype', 'float64') if hasattr(x1, '_dtype') else 'float64'
|
|
576
|
+
return _nd()(raw_result, _dtype=dtype)
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
def mod(x1, x2):
|
|
580
|
+
"""逐元素取模。"""
|
|
581
|
+
raw_result = _core.mod_(_ensure_raw(x1), _ensure_raw(x2))
|
|
582
|
+
dtype = getattr(x1, '_dtype', 'float64') if hasattr(x1, '_dtype') else 'float64'
|
|
583
|
+
return _nd()(raw_result, _dtype=dtype)
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
remainder = mod # mod 的别名
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
# ========== 比较运算 ==========
|
|
590
|
+
def _str_kind_of(x):
|
|
591
|
+
"""字符串数组种类('S'/'U');非字符串返回 None。"""
|
|
592
|
+
dt = getattr(x, 'dtype', None)
|
|
593
|
+
k = getattr(dt, 'kind', None)
|
|
594
|
+
if k in ('S', 'U'):
|
|
595
|
+
return k
|
|
596
|
+
d = str(getattr(x, '_dtype', '') or '')
|
|
597
|
+
return d.lstrip('<>=|')[:1] if d.lstrip('<>=|')[:1] in ('S', 'U') else None
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
def _string_cmp(opname, py_op, core_fn, x1, x2, signature=None, casting=None):
|
|
601
|
+
"""字符串数组比较的 ufunc 语义:
|
|
602
|
+
|
|
603
|
+
- 同种类(S/S 或 U/U):底层是 f64 占位,须按原始 Python 值逐元素比较;
|
|
604
|
+
- 混合 S/U:无匹配 loop → _UFuncNoLoopError(TypeError,消息含
|
|
605
|
+
"did not contain a loop");显式 signature + casting='unsafe' 时
|
|
606
|
+
先把双方 cast 到目标种类再比较(数组语义)。
|
|
607
|
+
"""
|
|
608
|
+
k1 = _str_kind_of(x1)
|
|
609
|
+
k2 = _str_kind_of(x2)
|
|
610
|
+
if not (k1 in ('S', 'U') and k2 in ('S', 'U')):
|
|
611
|
+
return _wrap_bool(core_fn(_ensure_raw(x1), _ensure_raw(x2)))
|
|
612
|
+
if k1 != k2:
|
|
613
|
+
from rsarray._core._exceptions import _UFuncNoLoopError
|
|
614
|
+
if signature is None or casting != 'unsafe':
|
|
615
|
+
raise _UFuncNoLoopError(
|
|
616
|
+
f"'{opname}' ufunc did not contain a loop with signature "
|
|
617
|
+
f"matching types (dtype('{x1.dtype}'), dtype('{x2.dtype}')).")
|
|
618
|
+
_tgt = str(signature).lstrip('<>=|')[:1]
|
|
619
|
+
x1 = x1.astype(_tgt)
|
|
620
|
+
x2 = x2.astype(_tgt)
|
|
621
|
+
from rsarray import _flatten_vals
|
|
622
|
+
from rsarray import char as _char
|
|
623
|
+
a = (x1._raw_data if getattr(x1, '_raw_data', None) is not None
|
|
624
|
+
else x1.tolist())
|
|
625
|
+
b = (x2._raw_data if getattr(x2, '_raw_data', None) is not None
|
|
626
|
+
else x2.tolist())
|
|
627
|
+
flat_a = _flatten_vals(a)
|
|
628
|
+
flat_b = _flatten_vals(b)
|
|
629
|
+
sh_a = tuple(getattr(x1, 'shape', ()))
|
|
630
|
+
sh_b = tuple(getattr(x2, 'shape', ()))
|
|
631
|
+
bshape = _char._bc_shapes([sh_a, sh_b])
|
|
632
|
+
res = [py_op(_char._bc_get(flat_a, sh_a, idx),
|
|
633
|
+
_char._bc_get(flat_b, sh_b, idx))
|
|
634
|
+
for idx in _char._iter_indices(bshape)]
|
|
635
|
+
out = _nd()(res)
|
|
636
|
+
out._dtype = 'bool'
|
|
637
|
+
return out.reshape(bshape)
|
|
638
|
+
|
|
639
|
+
|
|
640
|
+
def greater(x1, x2, signature=None, casting=None):
|
|
641
|
+
"""逐元素大于比较。"""
|
|
642
|
+
return _string_cmp('greater', _pyop.gt, _core.greater, x1, x2,
|
|
643
|
+
signature, casting)
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
def less(x1, x2, signature=None, casting=None):
|
|
647
|
+
"""逐元素小于比较。"""
|
|
648
|
+
return _string_cmp('less', _pyop.lt, _core.less, x1, x2,
|
|
649
|
+
signature, casting)
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
def equal(x1, x2, signature=None, casting=None):
|
|
653
|
+
"""逐元素相等比较。"""
|
|
654
|
+
if _str_kind_of(x1) in ('S', 'U') and _str_kind_of(x2) in ('S', 'U'):
|
|
655
|
+
return _string_cmp('equal', _pyop.eq, _core.equal, x1, x2,
|
|
656
|
+
signature, casting)
|
|
657
|
+
# object dtype:Rust 层对 object 占位失真,逐元素 Python ==
|
|
658
|
+
_a1 = x1 if hasattr(x1, '_array') else None
|
|
659
|
+
if _a1 is not None and getattr(_a1, '_dtype', None) == 'object':
|
|
660
|
+
from rsarray import _flatten_vals
|
|
661
|
+
flat = (_a1.flatten().tolist() if getattr(_a1, '_raw_data', None) is None
|
|
662
|
+
else _flatten_vals(_a1._raw_data))
|
|
663
|
+
if hasattr(x2, '_array') and getattr(x2, 'ndim', 0) == 0:
|
|
664
|
+
x2 = x2.item()
|
|
665
|
+
if hasattr(x2, '_array') and getattr(x2, '_dtype', None) == 'object':
|
|
666
|
+
flat2 = (x2.flatten().tolist()
|
|
667
|
+
if getattr(x2, '_raw_data', None) is None
|
|
668
|
+
else _flatten_vals(x2._raw_data))
|
|
669
|
+
flat_r = ([a == b for a, b in zip(flat, flat2)]
|
|
670
|
+
if len(flat) == len(flat2) else [False] * len(flat))
|
|
671
|
+
else:
|
|
672
|
+
flat_r = [a == x2 for a in flat]
|
|
673
|
+
res = _nd()._wrap(_nd()(flat_r), _dtype='bool')
|
|
674
|
+
return res.reshape(_a1.shape)
|
|
675
|
+
return _wrap_bool(_core.equal(_ensure_raw(x1), _ensure_raw(x2)))
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
def not_equal(x1, x2, signature=None, casting=None):
|
|
679
|
+
"""逐元素不相等比较。"""
|
|
680
|
+
return _string_cmp('not_equal', _pyop.ne, _core.not_equal, x1, x2,
|
|
681
|
+
signature, casting)
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
def greater_equal(x1, x2, signature=None, casting=None):
|
|
685
|
+
"""逐元素大于等于比较。"""
|
|
686
|
+
return _string_cmp('greater_equal', _pyop.ge, _core.greater_equal, x1, x2,
|
|
687
|
+
signature, casting)
|
|
688
|
+
|
|
689
|
+
|
|
690
|
+
def less_equal(x1, x2, signature=None, casting=None):
|
|
691
|
+
"""逐元素小于等于比较。"""
|
|
692
|
+
return _string_cmp('less_equal', _pyop.le, _core.less_equal, x1, x2,
|
|
693
|
+
signature, casting)
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
def logical_and(x1, x2, out=None, **kwargs):
|
|
697
|
+
"""逐元素逻辑与。"""
|
|
698
|
+
res = _wrap_bool(_core.logical_and(_ensure_raw(x1), _ensure_raw(x2)))
|
|
699
|
+
if out is not None:
|
|
700
|
+
try:
|
|
701
|
+
out[...] = res
|
|
702
|
+
except Exception:
|
|
703
|
+
pass
|
|
704
|
+
return res
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def logical_or(x1, x2, out=None, **kwargs):
|
|
708
|
+
"""逐元素逻辑或。"""
|
|
709
|
+
res = _wrap_bool(_core.logical_or(_ensure_raw(x1), _ensure_raw(x2)))
|
|
710
|
+
if out is not None:
|
|
711
|
+
try:
|
|
712
|
+
out[...] = res
|
|
713
|
+
except Exception:
|
|
714
|
+
pass
|
|
715
|
+
return res
|
|
716
|
+
|
|
717
|
+
|
|
718
|
+
def logical_xor(x1, x2, out=None, **kwargs):
|
|
719
|
+
"""逐元素逻辑异或。"""
|
|
720
|
+
res = _wrap_bool(_core.logical_xor(_ensure_raw(x1), _ensure_raw(x2)))
|
|
721
|
+
if out is not None:
|
|
722
|
+
try:
|
|
723
|
+
out[...] = res
|
|
724
|
+
except Exception:
|
|
725
|
+
pass
|
|
726
|
+
return res
|
|
727
|
+
|
|
728
|
+
|
|
729
|
+
def _isclose_arrays(arr_a, arr_b, rtol, atol, equal_nan):
|
|
730
|
+
"""isclose 的数值核心(数组语义,Python 逐元素实现)。
|
|
731
|
+
|
|
732
|
+
底层 Rust 数组比较对非有限值有缺口(inf==inf → False、
|
|
733
|
+
nan != nan → False),故展平后用 Python 原生浮点语义逐元素判断:
|
|
734
|
+
两者皆有限 → |a-b| <= atol + rtol*|b|;非有限 → 仅 a == b 时 True;
|
|
735
|
+
双 NaN → equal_nan。atol/rtol 支持 list/tuple 数组。
|
|
736
|
+
形状不可广播 → ValueError(数组语义,避免直达 Rust panic)。
|
|
737
|
+
"""
|
|
738
|
+
import math as _m
|
|
739
|
+
nd = _nd()
|
|
740
|
+
|
|
741
|
+
def _fin(x):
|
|
742
|
+
# 复数元素:math.isfinite 不接受 complex → 实/虚部分别判
|
|
743
|
+
if isinstance(x, builtins.complex):
|
|
744
|
+
return _m.isfinite(x.real) and _m.isfinite(x.imag)
|
|
745
|
+
return _m.isfinite(x)
|
|
746
|
+
|
|
747
|
+
def _num(x):
|
|
748
|
+
if isinstance(x, (list, tuple)):
|
|
749
|
+
return nd(list(x))
|
|
750
|
+
return x
|
|
751
|
+
|
|
752
|
+
def _flat(x):
|
|
753
|
+
if not isinstance(x, (list, tuple)):
|
|
754
|
+
# 0-d 数组 tolist() 返回标量
|
|
755
|
+
return [x]
|
|
756
|
+
o = []
|
|
757
|
+
for v in x:
|
|
758
|
+
if isinstance(v, list):
|
|
759
|
+
o.extend(_flat(v))
|
|
760
|
+
else:
|
|
761
|
+
o.append(v)
|
|
762
|
+
return o
|
|
763
|
+
|
|
764
|
+
_rt, _at = _num(rtol), _num(atol)
|
|
765
|
+
# 广播前置校验(形状不匹配 → ValueError)
|
|
766
|
+
try:
|
|
767
|
+
_sa = builtins.tuple(arr_a.shape)
|
|
768
|
+
except Exception:
|
|
769
|
+
_sa = ()
|
|
770
|
+
for _x in (arr_b, _at, _rt):
|
|
771
|
+
try:
|
|
772
|
+
_sx = builtins.tuple(_x.shape)
|
|
773
|
+
except Exception:
|
|
774
|
+
_sx = ()
|
|
775
|
+
for _da, _db in zip(builtins.reversed(_sa), builtins.reversed(_sx)):
|
|
776
|
+
if _da != _db and _da != 1 and _db != 1:
|
|
777
|
+
raise ValueError(
|
|
778
|
+
"operands could not be broadcast together with shapes "
|
|
779
|
+
f"{_sa} {_sx}")
|
|
780
|
+
# 0-d 数组提升为 1-d:Rust 广播对 0-d 参与运算会静默降维
|
|
781
|
+
# (0d - (3,) → 0-d),先 reshape 成 (1,) 让 (1,) 广播语义生效
|
|
782
|
+
if getattr(arr_a, 'shape', None) == () and hasattr(arr_a, 'reshape'):
|
|
783
|
+
arr_a = arr_a.reshape((1,))
|
|
784
|
+
if getattr(arr_b, 'shape', None) == () and hasattr(arr_b, 'reshape'):
|
|
785
|
+
arr_b = arr_b.reshape((1,))
|
|
786
|
+
# 全 Python 广播 + 逐元素计算:Rust 广播算术对 (1,) vs (N,) 也会
|
|
787
|
+
# 静默产出 size-1 结果,不可信
|
|
788
|
+
|
|
789
|
+
def _shp(x):
|
|
790
|
+
try:
|
|
791
|
+
return builtins.tuple(x.shape)
|
|
792
|
+
except Exception:
|
|
793
|
+
return ()
|
|
794
|
+
|
|
795
|
+
_sa, _sb = _shp(arr_a), _shp(arr_b)
|
|
796
|
+
_at_is_arr = hasattr(_at, 'shape')
|
|
797
|
+
_rt_is_arr = hasattr(_rt, 'shape')
|
|
798
|
+
_st = _shp(_at) if _at_is_arr else ()
|
|
799
|
+
_sr = _shp(_rt) if _rt_is_arr else ()
|
|
800
|
+
_ndim = builtins.max(len(_sa), len(_sb), len(_st), len(_sr))
|
|
801
|
+
_out_shape = []
|
|
802
|
+
for _d in range(_ndim):
|
|
803
|
+
_dims = []
|
|
804
|
+
for _s in (_sa, _sb, _st, _sr):
|
|
805
|
+
_l = len(_s)
|
|
806
|
+
_dims.append(_s[_l - _ndim + _d] if _d >= _ndim - _l else 1)
|
|
807
|
+
_mx = builtins.max(_dims)
|
|
808
|
+
if builtins.any(x != 1 and x != _mx for x in _dims):
|
|
809
|
+
raise ValueError(
|
|
810
|
+
"operands could not be broadcast together with shapes "
|
|
811
|
+
f"{_sa} {_sb} {_st} {_sr}")
|
|
812
|
+
_out_shape.append(_mx)
|
|
813
|
+
_total = 1
|
|
814
|
+
for _s in _out_shape:
|
|
815
|
+
_total *= _s
|
|
816
|
+
|
|
817
|
+
def _bcast(flat, shp):
|
|
818
|
+
"""把 flat 值按 shp 广播到 _out_shape,返回展平列表。"""
|
|
819
|
+
shp = (1,) * (_ndim - len(shp)) + tuple(shp)
|
|
820
|
+
_strides = [1] * _ndim
|
|
821
|
+
for _i in range(_ndim - 2, -1, -1):
|
|
822
|
+
_strides[_i] = _strides[_i + 1] * _out_shape[_i + 1]
|
|
823
|
+
_ost = [0 if shp[_i] == 1 else _strides[_i] for _i in range(_ndim)]
|
|
824
|
+
_res = []
|
|
825
|
+
_idx = [0] * _ndim
|
|
826
|
+
for _ in range(_total):
|
|
827
|
+
_off = builtins.sum(_idx[_k] * _ost[_k] for _k in range(_ndim))
|
|
828
|
+
_res.append(flat[_off])
|
|
829
|
+
for _k in range(_ndim - 1, -1, -1):
|
|
830
|
+
_idx[_k] += 1
|
|
831
|
+
if _idx[_k] < _out_shape[_k]:
|
|
832
|
+
break
|
|
833
|
+
_idx[_k] = 0
|
|
834
|
+
return _res
|
|
835
|
+
|
|
836
|
+
_bva = _bcast(_flat(arr_a.tolist()), _sa)
|
|
837
|
+
_bvb = _bcast(_flat(arr_b.tolist()), _sb)
|
|
838
|
+
_bat = _bcast(_flat(_at.tolist()), _st) if _at_is_arr else None
|
|
839
|
+
_brt = _bcast(_flat(_rt.tolist()), _sr) if _rt_is_arr else None
|
|
840
|
+
_out = []
|
|
841
|
+
for _i in range(_total):
|
|
842
|
+
_av, _bv = _bva[_i], _bvb[_i]
|
|
843
|
+
_atv = _bat[_i] if _bat is not None else atol
|
|
844
|
+
_rtv = _brt[_i] if _brt is not None else rtol
|
|
845
|
+
if _av != _av and _bv != _bv:
|
|
846
|
+
# 双 NaN
|
|
847
|
+
_out.append(builtins.bool(equal_nan))
|
|
848
|
+
elif _av == _bv:
|
|
849
|
+
# 相等值(含 inf==inf / -inf==-inf)恒 close
|
|
850
|
+
_out.append(True)
|
|
851
|
+
elif _fin(_av) and _fin(_bv):
|
|
852
|
+
_out.append(builtins.bool(abs(_av - _bv) <=
|
|
853
|
+
_atv + _rtv * abs(_bv)))
|
|
854
|
+
else:
|
|
855
|
+
# 非有限对(inf/-inf 不相等)→ False
|
|
856
|
+
_out.append(False)
|
|
857
|
+
_shape = builtins.tuple(_out_shape)
|
|
858
|
+
res = nd([1.0 if v else 0.0 for v in _out])
|
|
859
|
+
if _shape:
|
|
860
|
+
res = res.reshape(_shape)
|
|
861
|
+
res._dtype = 'bool'
|
|
862
|
+
return res
|
|
863
|
+
|
|
864
|
+
|
|
865
|
+
def isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False):
|
|
866
|
+
"""逐元素判断是否接近(数组语义,Python 层实现)。
|
|
867
|
+
|
|
868
|
+
|a-b| <= atol + rtol*|b|;相等值(含 inf==inf)恒 close;
|
|
869
|
+
NaN 默认 False,equal_nan=True 时同位 NaN 为 True。
|
|
870
|
+
标量输入返回 np.bool 标量单例(np.True_/np.False_)。
|
|
871
|
+
"""
|
|
872
|
+
import math as _m
|
|
873
|
+
try:
|
|
874
|
+
if (not _m.isfinite(rtol) or rtol < 0 or
|
|
875
|
+
not _m.isfinite(atol) or atol < 0):
|
|
876
|
+
import warnings as _warn_is
|
|
877
|
+
_warn_is.warn(
|
|
878
|
+
f"One of rtol or atol is not valid, atol: {atol}, "
|
|
879
|
+
f"rtol: {rtol}", RuntimeWarning, stacklevel=3)
|
|
880
|
+
except (TypeError, ValueError):
|
|
881
|
+
pass
|
|
882
|
+
nd = _nd()
|
|
883
|
+
_a_arr = hasattr(a, '_array')
|
|
884
|
+
_b_arr = hasattr(b, '_array')
|
|
885
|
+
if not _a_arr and not _b_arr and \
|
|
886
|
+
not isinstance(a, (list, tuple)) and \
|
|
887
|
+
not isinstance(b, (list, tuple)):
|
|
888
|
+
# 标量 × 标量:纯 Python 计算(绕开 0-d 数组 item/bool 缺口),
|
|
889
|
+
# 返回 np.bool 标量单例(数组语义)
|
|
890
|
+
try:
|
|
891
|
+
_va, _vb = a, b
|
|
892
|
+
if isinstance(_va, builtins.bool) or isinstance(_vb, builtins.bool):
|
|
893
|
+
_va, _vb = builtins.bool(_va), builtins.bool(_vb)
|
|
894
|
+
else:
|
|
895
|
+
_va, _vb = builtins.complex(_va), builtins.complex(_vb)
|
|
896
|
+
if _va != _va and _vb != _vb:
|
|
897
|
+
_val = builtins.bool(equal_nan)
|
|
898
|
+
elif _va == _vb:
|
|
899
|
+
# 相等值(含 inf==inf / -inf==-inf)恒 close
|
|
900
|
+
_val = True
|
|
901
|
+
else:
|
|
902
|
+
# 数组语义:非有限对(含 inf/-inf)仅在相等时 close
|
|
903
|
+
_va_f = builtins.bool(_va == _va and
|
|
904
|
+
abs(_va) != builtins.float('inf'))
|
|
905
|
+
_vb_f = builtins.bool(_vb == _vb and
|
|
906
|
+
abs(_vb) != builtins.float('inf'))
|
|
907
|
+
if _va_f and _vb_f:
|
|
908
|
+
_val = builtins.bool(abs(_va - _vb) <=
|
|
909
|
+
atol + rtol * abs(_vb))
|
|
910
|
+
else:
|
|
911
|
+
_val = False
|
|
912
|
+
except Exception:
|
|
913
|
+
_val = False
|
|
914
|
+
try:
|
|
915
|
+
from .__init__ import True_ as _t_one, False_ as _f_one
|
|
916
|
+
except Exception:
|
|
917
|
+
return _val
|
|
918
|
+
return _t_one if _val else _f_one
|
|
919
|
+
arr_a = a if _a_arr else nd(a)
|
|
920
|
+
arr_b = b if _b_arr else nd(b)
|
|
921
|
+
# NEP50 弱类型:f32/f16 数组与 Python float(type 精确匹配;float64/
|
|
922
|
+
# float32 标量为强类型不降级)比较 → float 降到数组精度
|
|
923
|
+
_dt_a = getattr(arr_a, '_dtype', '')
|
|
924
|
+
if _dt_a in ('float32', 'float16'):
|
|
925
|
+
try:
|
|
926
|
+
from .__init__ import _round_scalar_to_f
|
|
927
|
+
if not _b_arr and type(b) is float:
|
|
928
|
+
b = _round_scalar_to_f(_dt_a, b)
|
|
929
|
+
arr_b = nd(b)
|
|
930
|
+
if type(atol) is float:
|
|
931
|
+
atol = _round_scalar_to_f(_dt_a, atol)
|
|
932
|
+
if type(rtol) is float:
|
|
933
|
+
rtol = _round_scalar_to_f(_dt_a, rtol)
|
|
934
|
+
except Exception:
|
|
935
|
+
pass
|
|
936
|
+
res = _isclose_arrays(arr_a, arr_b, rtol, atol, equal_nan)
|
|
937
|
+
return res
|
|
938
|
+
|
|
939
|
+
|
|
940
|
+
def allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False, *args, **kwargs):
|
|
941
|
+
"""判断两个数组是否全部元素级接近(数组语义)。
|
|
942
|
+
|
|
943
|
+
与 对齐:``equal_nan=True`` 时同位置的 NaN 视为相等。
|
|
944
|
+
标量输入返回 Python bool。
|
|
945
|
+
"""
|
|
946
|
+
_ = args, kwargs
|
|
947
|
+
res = isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)
|
|
948
|
+
try:
|
|
949
|
+
if hasattr(res, 'all'):
|
|
950
|
+
return builtins.bool(res.all())
|
|
951
|
+
return builtins.bool(res)
|
|
952
|
+
except Exception:
|
|
953
|
+
return False
|
|
954
|
+
|
|
955
|
+
|
|
956
|
+
# 反双曲函数别名
|
|
957
|
+
asinh = arcsinh
|
|
958
|
+
acosh = arccosh
|
|
959
|
+
atanh = arctanh
|
|
960
|
+
|
|
961
|
+
|
|
962
|
+
# 其他数学函数
|
|
963
|
+
def reciprocal(x):
|
|
964
|
+
"""逐元素返回倒数(1/x)。"""
|
|
965
|
+
return _wrap(_core.reciprocal(_ensure_raw(x)))
|