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
rsarray/statistics.py
ADDED
|
@@ -0,0 +1,1360 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""统计函数模块 - 所有实现位于 Rust,这里仅保留薄包装。"""
|
|
3
|
+
|
|
4
|
+
import builtins as _builtins
|
|
5
|
+
|
|
6
|
+
import rsarray.num_core as _core
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _nd():
|
|
10
|
+
from .__init__ import ndarray as _n
|
|
11
|
+
return _n
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _is_ndarray(obj):
|
|
15
|
+
return hasattr(obj, '_array')
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _wrap(result):
|
|
19
|
+
if hasattr(result, 'ndim') and result.ndim == 0:
|
|
20
|
+
val = result.tolist()
|
|
21
|
+
if isinstance(val, float) and val.is_integer():
|
|
22
|
+
return int(val)
|
|
23
|
+
return val
|
|
24
|
+
return _nd()(result)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _ensure_raw(a):
|
|
28
|
+
if hasattr(a, '_array'):
|
|
29
|
+
return a._array
|
|
30
|
+
return _core.ndarray(a)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _is_complex_raw(a):
|
|
34
|
+
raw = a._array if hasattr(a, '_array') else a
|
|
35
|
+
return bool(getattr(raw, 'is_complex', False))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _flatten_c(data):
|
|
39
|
+
out = []
|
|
40
|
+
|
|
41
|
+
def rec(d):
|
|
42
|
+
if isinstance(d, list):
|
|
43
|
+
for x in d:
|
|
44
|
+
rec(x)
|
|
45
|
+
else:
|
|
46
|
+
out.append(d)
|
|
47
|
+
|
|
48
|
+
rec(data)
|
|
49
|
+
return out
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _reshape_nested(flat, shape):
|
|
53
|
+
if not shape:
|
|
54
|
+
return flat[0]
|
|
55
|
+
if len(shape) == 1:
|
|
56
|
+
return list(flat)
|
|
57
|
+
block = 1
|
|
58
|
+
for s in shape[1:]:
|
|
59
|
+
block *= s
|
|
60
|
+
return [_reshape_nested(flat[i * block:(i + 1) * block], shape[1:]) for i in range(shape[0])]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _py_var_std(a, axis, ddof, want_std):
|
|
64
|
+
"""方差/标准差的原生实现(无外部依赖),支持实数与复数数组。
|
|
65
|
+
|
|
66
|
+
与 数组语义一致:var = mean(|x - mean|^2),std = sqrt(var);复数输入结果为实数。
|
|
67
|
+
支持 axis=None 或整数 axis。用于补齐 Rust 端在高维/复数场景下的能力缺口。
|
|
68
|
+
"""
|
|
69
|
+
a_arr = a if hasattr(a, '_array') else _nd()(a)
|
|
70
|
+
shape = list(a_arr.shape)
|
|
71
|
+
flat = _flatten_c(a_arr.tolist())
|
|
72
|
+
|
|
73
|
+
def reduce_vals(vals):
|
|
74
|
+
n = len(vals)
|
|
75
|
+
m = _builtins.sum(vals) / n
|
|
76
|
+
v = _builtins.sum(abs(x - m) ** 2 for x in vals) / (n - ddof)
|
|
77
|
+
return (v ** 0.5) if want_std else v
|
|
78
|
+
|
|
79
|
+
if axis is None:
|
|
80
|
+
# 全归约返回带 .dtype 的 0-d ndarray(var/std 结果恒为实数 float64),
|
|
81
|
+
# 与标准语义一致(np.var(complex) 返回带 .dtype 的 float64 标量)。
|
|
82
|
+
return _nd()(reduce_vals(flat), _dtype='float64')
|
|
83
|
+
|
|
84
|
+
nd = len(shape)
|
|
85
|
+
if axis < 0:
|
|
86
|
+
axis += nd
|
|
87
|
+
# 使用一次性累乘代替循环
|
|
88
|
+
strides = [1] * nd
|
|
89
|
+
for i in range(nd - 2, -1, -1):
|
|
90
|
+
strides[i] = strides[i + 1] * shape[i + 1]
|
|
91
|
+
axis_len = shape[axis]
|
|
92
|
+
axis_stride = strides[axis]
|
|
93
|
+
out_shape = shape[:axis] + shape[axis + 1:]
|
|
94
|
+
out_strides = strides[:axis] + strides[axis + 1:]
|
|
95
|
+
out_size = 1
|
|
96
|
+
for s in out_shape:
|
|
97
|
+
out_size *= s
|
|
98
|
+
|
|
99
|
+
# 预计算所有 base 偏移,避免嵌套循环中重复计算
|
|
100
|
+
result = [0.0] * out_size
|
|
101
|
+
idx = [0] * len(out_shape)
|
|
102
|
+
# 预生成所有 axis 索引的 stride 偏移
|
|
103
|
+
axis_offsets = [t * axis_stride for t in range(axis_len)]
|
|
104
|
+
for i in range(out_size):
|
|
105
|
+
# 计算 base 偏移:用内建 sum 代替显式循环
|
|
106
|
+
base = _builtins.sum(idx[k] * out_strides[k] for k in range(len(out_strides)))
|
|
107
|
+
# 列表推导代替显式循环
|
|
108
|
+
vals = [flat[base + off] for off in axis_offsets]
|
|
109
|
+
result[i] = reduce_vals(vals)
|
|
110
|
+
# 推进 idx(从最低维度开始)
|
|
111
|
+
for k in range(len(out_shape) - 1, -1, -1):
|
|
112
|
+
idx[k] += 1
|
|
113
|
+
if idx[k] < out_shape[k]:
|
|
114
|
+
break
|
|
115
|
+
idx[k] = 0
|
|
116
|
+
|
|
117
|
+
nested = _reshape_nested(result, out_shape)
|
|
118
|
+
if not out_shape:
|
|
119
|
+
# 0-d 结果(全轴归约)返回带 .dtype 的 0-d ndarray,与标准语义一致
|
|
120
|
+
return _nd()(nested, _dtype='float64')
|
|
121
|
+
return _nd()(nested)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _f64_scalar(v):
|
|
125
|
+
"""把 Python float 包装为 rsarray float64 标量(带 shape/itemsize 语义)。"""
|
|
126
|
+
try:
|
|
127
|
+
from .__init__ import _SCALAR_CLASS_BY_DTYPE
|
|
128
|
+
_cls = _SCALAR_CLASS_BY_DTYPE.get('float64')
|
|
129
|
+
if _cls is not None:
|
|
130
|
+
return _cls(v)
|
|
131
|
+
except Exception:
|
|
132
|
+
pass
|
|
133
|
+
return v
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _insert_keepdims(res, nd0, axes):
|
|
137
|
+
"""在归约轴位置为 res 插入 size-1 轴(keepdims=True 语义)。"""
|
|
138
|
+
_axset = set(axes)
|
|
139
|
+
_new_shape = []
|
|
140
|
+
_si = 0
|
|
141
|
+
for d in range(nd0):
|
|
142
|
+
if d in _axset:
|
|
143
|
+
_new_shape.append(1)
|
|
144
|
+
else:
|
|
145
|
+
_new_shape.append(res.shape[_si])
|
|
146
|
+
_si += 1
|
|
147
|
+
return res.reshape(tuple(_new_shape))
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _reduce_given_mean(a, mean, axis, keepdims, ddof, want_std, out,
|
|
151
|
+
res_dt=None):
|
|
152
|
+
"""基于预计算 mean 的 var/std(mean= 语义)。
|
|
153
|
+
|
|
154
|
+
直接信任传入 mean(不重算):var = sum(|x-mean|^2)/n_eff,
|
|
155
|
+
std = sqrt(var)。支持 axis=None/int/tuple;keepdims 恢复 size-1 轴;
|
|
156
|
+
out 被填充并原样返回(数组语义);res_dt 非空时按 规则重标
|
|
157
|
+
结果 dtype(如 float16 输入保持 float16)。
|
|
158
|
+
"""
|
|
159
|
+
_m = mean
|
|
160
|
+
try:
|
|
161
|
+
if hasattr(_m, 'ndim') and getattr(_m, 'ndim', 0) == 0:
|
|
162
|
+
_m = _m.item()
|
|
163
|
+
except Exception:
|
|
164
|
+
pass
|
|
165
|
+
if not hasattr(a, '_array') and not hasattr(a, '_data'):
|
|
166
|
+
# list/tuple 输入(非 array 参数包装语义);MaskedArray 有
|
|
167
|
+
# _data(非 _array),不可包装降级(否则 a - _m 走 ndarray 算术)
|
|
168
|
+
a = _nd()(a)
|
|
169
|
+
diff = a - _m
|
|
170
|
+
nd = diff.ndim
|
|
171
|
+
if axis is None:
|
|
172
|
+
_axes = tuple(range(nd))
|
|
173
|
+
elif isinstance(axis, (tuple, list)):
|
|
174
|
+
_axes = tuple(_ax % nd for _ax in axis)
|
|
175
|
+
else:
|
|
176
|
+
_axes = (axis % nd,)
|
|
177
|
+
_n = 1
|
|
178
|
+
for _ax in _axes:
|
|
179
|
+
_n *= diff.shape[_ax]
|
|
180
|
+
_n -= ddof
|
|
181
|
+
_axset = set(_axes)
|
|
182
|
+
# 元素级 |x-mean|^2(实数即 (x-mean)^2,复数取模平方——数组语义)
|
|
183
|
+
_s = abs(diff) ** 2
|
|
184
|
+
if _axset == set(range(nd)):
|
|
185
|
+
# 全归约:展平后直接求和;返回 float64 标量(数组语义带 .shape==())
|
|
186
|
+
_vals = _flatten_c(_s.tolist())
|
|
187
|
+
_v = _builtins.sum(_vals) / _n
|
|
188
|
+
res = _f64_scalar((_v ** 0.5) if want_std else _v)
|
|
189
|
+
if res_dt is not None and str(res_dt) != 'float64':
|
|
190
|
+
from rsarray.lib._nanfunctions_impl import _scalar_of
|
|
191
|
+
res = _scalar_of(res_dt, float(res))
|
|
192
|
+
if out is not None:
|
|
193
|
+
try:
|
|
194
|
+
out[...] = res
|
|
195
|
+
except Exception:
|
|
196
|
+
pass
|
|
197
|
+
return out
|
|
198
|
+
return res
|
|
199
|
+
# 部分轴归约:降序逐轴求和(高轴先减,低轴号不变;等价联合归约)
|
|
200
|
+
for _ax in sorted(_axes, reverse=True):
|
|
201
|
+
_s = sum(_s, axis=_ax)
|
|
202
|
+
_v = _s / _n
|
|
203
|
+
if want_std:
|
|
204
|
+
_v = _v ** 0.5
|
|
205
|
+
if res_dt is not None and str(res_dt) != str(getattr(_v, '_dtype', '')):
|
|
206
|
+
# 重标注须数据转换(tolist 重建),不能只换标签(f16 存储标 f64 会错位)
|
|
207
|
+
_v = _nd()(_v.tolist(), _dtype=res_dt)
|
|
208
|
+
if keepdims:
|
|
209
|
+
_new_shape = []
|
|
210
|
+
_si = 0
|
|
211
|
+
for d in range(nd):
|
|
212
|
+
if d in _axset:
|
|
213
|
+
_new_shape.append(1)
|
|
214
|
+
else:
|
|
215
|
+
_new_shape.append(_s.shape[_si])
|
|
216
|
+
_si += 1
|
|
217
|
+
_v = _v.reshape(tuple(_new_shape))
|
|
218
|
+
if out is not None:
|
|
219
|
+
try:
|
|
220
|
+
out[...] = _v
|
|
221
|
+
except Exception:
|
|
222
|
+
pass
|
|
223
|
+
return out
|
|
224
|
+
return _v
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _check_reduce_axis(a, axis):
|
|
228
|
+
"""归约 axis 校验(数组语义:越界 → AxisError)。
|
|
229
|
+
|
|
230
|
+
越界 axis 直达 _core 会触发 Rust panic(进程 abort)。
|
|
231
|
+
返回归一化 axis:0-d 数组仅允许 axis=0(历史语义细节,返回自身),
|
|
232
|
+
归一化为 None(全归约)——Rust 对 0-d 的 axis=0 也会 panic。
|
|
233
|
+
"""
|
|
234
|
+
if axis is None:
|
|
235
|
+
return None
|
|
236
|
+
if hasattr(a, 'ndim'):
|
|
237
|
+
_dim = int(a.ndim)
|
|
238
|
+
else:
|
|
239
|
+
_dim = int(_nd()(_ensure_raw(a)).ndim)
|
|
240
|
+
if isinstance(axis, (tuple, list)):
|
|
241
|
+
_axes = [x + _dim if x < 0 else x for x in axis]
|
|
242
|
+
else:
|
|
243
|
+
_axes = [axis + _dim if axis < 0 else axis]
|
|
244
|
+
if _dim == 0:
|
|
245
|
+
if any(x != 0 for x in _axes):
|
|
246
|
+
from rsarray.exceptions import AxisError
|
|
247
|
+
raise AxisError(
|
|
248
|
+
f"axis {axis} is out of bounds for array of dimension {_dim}")
|
|
249
|
+
return None
|
|
250
|
+
if any(x < 0 or x >= _dim for x in _axes):
|
|
251
|
+
from rsarray.exceptions import AxisError
|
|
252
|
+
raise AxisError(
|
|
253
|
+
f"axis {axis} is out of bounds for array of dimension {_dim}")
|
|
254
|
+
return axis
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def sum(a, axis=None, dtype=None, out=None, keepdims=False, initial=None, where=True):
|
|
258
|
+
"""计算数组元素之和。"""
|
|
259
|
+
# matrix:保持 2-D 方向(数组语义),委托 matrix.sum(在 .A 上计算,无递归)
|
|
260
|
+
if type(a).__name__ == 'matrix':
|
|
261
|
+
return a.sum(axis=axis, dtype=dtype)
|
|
262
|
+
_ = out, initial, where
|
|
263
|
+
# 0-d 短路:Rust 归约对 0-d 输入会 abort;返回保持原 dtype 的 0-d
|
|
264
|
+
_a_raw = _ensure_raw(a)
|
|
265
|
+
arr_dtype = getattr(a, '_dtype', 'float64') if hasattr(a, '_dtype') else 'float64'
|
|
266
|
+
res_dt = dtype if dtype is not None else arr_dtype
|
|
267
|
+
if not tuple(getattr(_a_raw, 'shape', ())):
|
|
268
|
+
return _nd()(_a_raw, _dtype=res_dt)
|
|
269
|
+
axis = _check_reduce_axis(a, axis)
|
|
270
|
+
raw_result = _core.sum(_a_raw, axis, keepdims)
|
|
271
|
+
if axis is None and not keepdims:
|
|
272
|
+
# 数组语义:全归约(0-d)返回带 .dtype 的标量对象(np.generic),
|
|
273
|
+
# 而非 Python 标量。按输入 dtype 包装,保留 int64/float64。
|
|
274
|
+
return _nd()._wrap(raw_result, _dtype=res_dt)
|
|
275
|
+
return _nd()(raw_result, _dtype=res_dt)
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def mean(a, axis=None, dtype=None, out=None, keepdims=False, where=True):
|
|
279
|
+
"""计算数组元素的平均值。"""
|
|
280
|
+
_ = where
|
|
281
|
+
# 0-d 短路:Rust 归约会 abort;返回按 dtype 规则标注的 0-d
|
|
282
|
+
_a_raw = _ensure_raw(a)
|
|
283
|
+
arr_dtype = getattr(a, '_dtype', 'float64') if hasattr(a, '_dtype') else 'float64'
|
|
284
|
+
res_dt = _mean_result_dtype(dtype if dtype is not None else arr_dtype)
|
|
285
|
+
if not tuple(getattr(_a_raw, 'shape', ())):
|
|
286
|
+
return _nd()(_a_raw, _dtype=res_dt)
|
|
287
|
+
axis = _check_reduce_axis(a, axis)
|
|
288
|
+
# 数组语义:空数组 → NaN + "Mean of empty slice" 告警
|
|
289
|
+
try:
|
|
290
|
+
if _ensure_raw(a).size == 0:
|
|
291
|
+
import warnings as _warn_mean
|
|
292
|
+
_warn_mean.warn("Mean of empty slice", RuntimeWarning, stacklevel=3)
|
|
293
|
+
return float('nan')
|
|
294
|
+
except Exception:
|
|
295
|
+
pass
|
|
296
|
+
if isinstance(axis, (tuple, list)) and len(axis) > 0:
|
|
297
|
+
# 元组 axis:降序逐轴归约(高轴先减,低轴号不变;等价联合归约),
|
|
298
|
+
# keepdims 恢复 size-1 轴
|
|
299
|
+
nd0 = getattr(a, 'ndim', 0)
|
|
300
|
+
_axes = tuple(_ax % nd0 for _ax in axis)
|
|
301
|
+
_cur = a
|
|
302
|
+
for _ax in sorted(_axes, reverse=True):
|
|
303
|
+
_cur = mean(_cur, axis=_ax)
|
|
304
|
+
if keepdims:
|
|
305
|
+
_cur = _insert_keepdims(_cur, nd0, _axes)
|
|
306
|
+
if out is not None:
|
|
307
|
+
try:
|
|
308
|
+
out[...] = _cur
|
|
309
|
+
except Exception:
|
|
310
|
+
pass
|
|
311
|
+
return out
|
|
312
|
+
return _cur
|
|
313
|
+
raw_result = _core.mean(_ensure_raw(a), axis, keepdims)
|
|
314
|
+
if axis is not None:
|
|
315
|
+
# semantics: reduction along an explicit axis returns an ndarray
|
|
316
|
+
# (0-d when all dimensions are reduced), never a Python scalar。
|
|
317
|
+
# 结果 dtype 按 规则(float/complex 保留精度,其余 float64)。
|
|
318
|
+
res = _nd()(raw_result, _dtype=res_dt)
|
|
319
|
+
elif hasattr(raw_result, 'ndim') and raw_result.ndim == 0:
|
|
320
|
+
# 数组语义:全归约(0-d)返回带 .dtype 的标量对象(np.generic),
|
|
321
|
+
# 而非 Python float。
|
|
322
|
+
res = _nd()._wrap(raw_result, _dtype=res_dt)
|
|
323
|
+
else:
|
|
324
|
+
res = _wrap(raw_result)
|
|
325
|
+
# 数组语义:out 被填充且被返回
|
|
326
|
+
if out is not None:
|
|
327
|
+
try:
|
|
328
|
+
out[...] = res
|
|
329
|
+
except Exception:
|
|
330
|
+
pass
|
|
331
|
+
return out
|
|
332
|
+
return res
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _needs_py_var_std(a, axis):
|
|
336
|
+
"""判断是否需要走原生实现:复数,或任何指定 axis 的归约。
|
|
337
|
+
|
|
338
|
+
Rust 端 _core.std/_core.var 对指定 axis 的归约会 panic(1D/2D 亦如此),
|
|
339
|
+
而 _py_var_std 是完整且正确的实现,故凡指定 axis 一律走原生实现。
|
|
340
|
+
"""
|
|
341
|
+
if _is_complex_raw(a):
|
|
342
|
+
return True
|
|
343
|
+
if str(getattr(a, '_dtype', '')) == 'object' and \
|
|
344
|
+
getattr(a, '_raw_data', None) is not None:
|
|
345
|
+
# object 数组:底层 f64 存储是占位值(真实值在 _raw_data,
|
|
346
|
+
# 可能是复数等),必须走 Python 路径
|
|
347
|
+
return True
|
|
348
|
+
return axis is not None
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _flat_vals(x):
|
|
352
|
+
out = []
|
|
353
|
+
for v in x:
|
|
354
|
+
if isinstance(v, (list, tuple)):
|
|
355
|
+
out.extend(_flat_vals(v))
|
|
356
|
+
else:
|
|
357
|
+
out.append(v)
|
|
358
|
+
return out
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def _values_equal(a, b):
|
|
362
|
+
"""逐元素比较(支持 0-d 标量与同形状数组)。"""
|
|
363
|
+
try:
|
|
364
|
+
import builtins
|
|
365
|
+
la = _flat_vals(a.tolist())
|
|
366
|
+
lb = _flat_vals(b.tolist()) if hasattr(b, 'tolist') else _flat_vals([b])
|
|
367
|
+
if len(la) != len(lb):
|
|
368
|
+
return False
|
|
369
|
+
return _builtins.all(x == y for x, y in zip(la, lb))
|
|
370
|
+
except Exception:
|
|
371
|
+
return False
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _var_std_result_dtype(dt):
|
|
375
|
+
"""var/std 结果 dtype(数组语义):int/uint/bool/complex/object → float64,
|
|
376
|
+
float 保留精度(float16/32/64/longdouble)。"""
|
|
377
|
+
if isinstance(dt, str):
|
|
378
|
+
s = dt.lstrip('<>=|')
|
|
379
|
+
k = s[:1] if s else ''
|
|
380
|
+
if k in 'iubcO' or dt.startswith('complex'):
|
|
381
|
+
return 'float64'
|
|
382
|
+
return dt
|
|
383
|
+
k = getattr(dt, 'kind', None)
|
|
384
|
+
return dt if isinstance(k, str) and k in 'efgd' else 'float64'
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _mean_result_dtype(dt):
|
|
388
|
+
"""mean 结果 dtype(数组语义):float/complex 保留精度,其余 float64。"""
|
|
389
|
+
if isinstance(dt, str):
|
|
390
|
+
s = dt.lstrip('<>=|')
|
|
391
|
+
k = s[:1] if s else ''
|
|
392
|
+
else:
|
|
393
|
+
k = getattr(dt, 'kind', '')
|
|
394
|
+
return dt if k in 'efc' else 'float64'
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, where=True,
|
|
398
|
+
correction=None, mean=None):
|
|
399
|
+
"""计算数组元素的标准差。"""
|
|
400
|
+
_ = where
|
|
401
|
+
# 0-d 短路:Rust 归约会 abort;返回按 dtype 规则标注的 0-d
|
|
402
|
+
# oracle 语义:未显式指定 dtype 时 var/std 结果恒 float64
|
|
403
|
+
_a_raw = _ensure_raw(a)
|
|
404
|
+
res_dt = dtype if dtype is not None else 'float64'
|
|
405
|
+
if not tuple(getattr(_a_raw, 'shape', ())):
|
|
406
|
+
return _nd()(0.0, _dtype=res_dt)
|
|
407
|
+
axis = _check_reduce_axis(a, axis)
|
|
408
|
+
# 兼容:correction 与 ddof 同义且互斥(ddof 非零且给了 correction 报错)
|
|
409
|
+
if correction is not None:
|
|
410
|
+
if ddof != 0:
|
|
411
|
+
raise ValueError(
|
|
412
|
+
"ddof and correction can't be provided simultaneously.")
|
|
413
|
+
ddof = correction
|
|
414
|
+
# 数组语义:空数组 → NaN + "Mean of empty slice" 告警
|
|
415
|
+
try:
|
|
416
|
+
if _ensure_raw(a).size == 0:
|
|
417
|
+
import warnings as _warn_std
|
|
418
|
+
_warn_std.warn("Mean of empty slice", RuntimeWarning, stacklevel=3)
|
|
419
|
+
return _nd()(float('nan'), _dtype=res_dt)
|
|
420
|
+
except Exception:
|
|
421
|
+
pass
|
|
422
|
+
if mean is not None:
|
|
423
|
+
# mean= 语义:信任预计算 mean(参数名遮蔽模块级 mean,
|
|
424
|
+
# 旧实现误将其当函数调用致整个分支被 except 跳过)
|
|
425
|
+
return _reduce_given_mean(a, mean, axis, keepdims, ddof, True, out,
|
|
426
|
+
res_dt)
|
|
427
|
+
if axis is not None:
|
|
428
|
+
# 数值路径统一:std() 与 std(mean=np.mean(...)) 走同一实现,
|
|
429
|
+
# 保证 assert_equal 级别的逐位一致(元组 axis 由内部统一处理)。
|
|
430
|
+
# 注意:参数名 mean 遮蔽模块级 mean 函数,须经 globals() 取用。
|
|
431
|
+
_m = globals()['mean'](a, axis=axis, keepdims=True)
|
|
432
|
+
return _reduce_given_mean(a, _m, axis, keepdims, ddof, True, out,
|
|
433
|
+
res_dt)
|
|
434
|
+
if _needs_py_var_std(a, axis):
|
|
435
|
+
# axis=None 的复数/object 数组:|x-m|^2 语义
|
|
436
|
+
return _py_var_std(a, axis, ddof, want_std=True)
|
|
437
|
+
raw_result = _core.std(_ensure_raw(a), axis, ddof, keepdims)
|
|
438
|
+
res = _nd()(raw_result, _dtype=res_dt)
|
|
439
|
+
if out is not None:
|
|
440
|
+
try:
|
|
441
|
+
out[...] = res
|
|
442
|
+
except Exception:
|
|
443
|
+
pass
|
|
444
|
+
return out
|
|
445
|
+
return res
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, where=True,
|
|
449
|
+
correction=None, mean=None):
|
|
450
|
+
"""计算数组元素的方差。"""
|
|
451
|
+
_ = where
|
|
452
|
+
# 0-d 短路:Rust 归约会 abort;返回按 dtype 规则标注的 0-d
|
|
453
|
+
# oracle 语义:未显式指定 dtype 时 var/std 结果恒 float64
|
|
454
|
+
_a_raw = _ensure_raw(a)
|
|
455
|
+
res_dt = dtype if dtype is not None else 'float64'
|
|
456
|
+
if not tuple(getattr(_a_raw, 'shape', ())):
|
|
457
|
+
return _nd()(0.0, _dtype=res_dt)
|
|
458
|
+
axis = _check_reduce_axis(a, axis)
|
|
459
|
+
if correction is not None:
|
|
460
|
+
if ddof != 0:
|
|
461
|
+
raise ValueError(
|
|
462
|
+
"ddof and correction can't be provided simultaneously.")
|
|
463
|
+
ddof = correction
|
|
464
|
+
# 数组语义:空数组 → NaN + "Mean of empty slice" 告警
|
|
465
|
+
try:
|
|
466
|
+
if _ensure_raw(a).size == 0:
|
|
467
|
+
import warnings as _warn_var
|
|
468
|
+
_warn_var.warn("Mean of empty slice", RuntimeWarning, stacklevel=3)
|
|
469
|
+
return _nd()(float('nan'), _dtype=res_dt)
|
|
470
|
+
except Exception:
|
|
471
|
+
pass
|
|
472
|
+
if mean is not None:
|
|
473
|
+
# mean= 语义:信任预计算 mean(参数名遮蔽模块级 mean)
|
|
474
|
+
return _reduce_given_mean(a, mean, axis, keepdims, ddof, False, out,
|
|
475
|
+
res_dt)
|
|
476
|
+
if axis is not None:
|
|
477
|
+
# 数值路径统一:var() 与 var(mean=np.mean(...)) 走同一实现,
|
|
478
|
+
# 保证 assert_equal 级别的逐位一致。
|
|
479
|
+
# 注意:参数名 mean 遮蔽模块级 mean 函数,须经 globals() 取用。
|
|
480
|
+
_m = globals()['mean'](a, axis=axis, keepdims=True)
|
|
481
|
+
return _reduce_given_mean(a, _m, axis, keepdims, ddof, False, out,
|
|
482
|
+
res_dt)
|
|
483
|
+
if _needs_py_var_std(a, axis):
|
|
484
|
+
# axis=None 的复数/object 数组:|x-m|^2 语义
|
|
485
|
+
return _py_var_std(a, axis, ddof, want_std=False)
|
|
486
|
+
raw_result = _core.var(_ensure_raw(a), axis, ddof, keepdims)
|
|
487
|
+
res = _nd()(raw_result, _dtype=res_dt)
|
|
488
|
+
if out is not None:
|
|
489
|
+
try:
|
|
490
|
+
out[...] = res
|
|
491
|
+
except Exception:
|
|
492
|
+
pass
|
|
493
|
+
return out
|
|
494
|
+
return res
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def min(a, axis=None, out=None, keepdims=False, initial=None, where=True):
|
|
498
|
+
"""计算数组元素的最小值。"""
|
|
499
|
+
if type(a).__name__ == 'matrix':
|
|
500
|
+
return a.min(axis=axis)
|
|
501
|
+
_ = out, initial, where
|
|
502
|
+
axis = _check_reduce_axis(a, axis)
|
|
503
|
+
raw_result = _core.min(_ensure_raw(a), axis, keepdims)
|
|
504
|
+
dtype = getattr(a, '_dtype', 'float64') if hasattr(a, '_dtype') else 'float64'
|
|
505
|
+
return _nd()(raw_result, _dtype=dtype)
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def max(a, axis=None, out=None, keepdims=False, initial=None, where=True):
|
|
509
|
+
"""计算数组元素的最大值。"""
|
|
510
|
+
if type(a).__name__ == 'matrix':
|
|
511
|
+
return a.max(axis=axis)
|
|
512
|
+
_ = out, initial, where
|
|
513
|
+
axis = _check_reduce_axis(a, axis)
|
|
514
|
+
raw_result = _core.max(_ensure_raw(a), axis, keepdims)
|
|
515
|
+
dtype = getattr(a, '_dtype', 'float64') if hasattr(a, '_dtype') else 'float64'
|
|
516
|
+
return _nd()(raw_result, _dtype=dtype)
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
amin = min # min 的别名,计算数组中的最小值
|
|
520
|
+
amax = max # max 的别名,计算数组中的最大值
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def ptp(a, axis=None, out=None, keepdims=False):
|
|
524
|
+
"""计算数组元素的峰-峰值(最大值-最小值)。"""
|
|
525
|
+
if type(a).__name__ == 'matrix':
|
|
526
|
+
return a.ptp(axis=axis)
|
|
527
|
+
_ = out, keepdims
|
|
528
|
+
axis = _check_reduce_axis(a, axis)
|
|
529
|
+
raw_result = _core.ptp(_ensure_raw(a), axis)
|
|
530
|
+
arr_dtype = getattr(a, '_dtype', 'float64') if hasattr(a, '_dtype') else 'float64'
|
|
531
|
+
return _nd()(raw_result, _dtype=arr_dtype)
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def _median_1d(col):
|
|
535
|
+
"""1-d 中位数(数组语义:NaN 视为最大值排到末尾,取中间;偶数取均值)。"""
|
|
536
|
+
col = list(col)
|
|
537
|
+
if not col:
|
|
538
|
+
import warnings as _w_med
|
|
539
|
+
_w_med.warn("Mean of empty slice", RuntimeWarning, stacklevel=4)
|
|
540
|
+
return float('nan')
|
|
541
|
+
s = sorted(v for v in col if not (isinstance(v, float) and v != v))
|
|
542
|
+
total = len(col)
|
|
543
|
+
k = total // 2
|
|
544
|
+
|
|
545
|
+
def at(i):
|
|
546
|
+
if i < len(s):
|
|
547
|
+
return s[i]
|
|
548
|
+
return float('nan')
|
|
549
|
+
|
|
550
|
+
if total % 2:
|
|
551
|
+
return at(k)
|
|
552
|
+
return (at(k - 1) + at(k)) / 2
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def _shape_of(lst):
|
|
556
|
+
s = []
|
|
557
|
+
d = lst
|
|
558
|
+
while isinstance(d, (list, tuple)):
|
|
559
|
+
s.append(len(d))
|
|
560
|
+
d = d[0] if d else []
|
|
561
|
+
return tuple(s)
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def _geti(d, idx):
|
|
565
|
+
for i in idx:
|
|
566
|
+
d = d[i]
|
|
567
|
+
return d
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def _seti(d, idx, v):
|
|
571
|
+
for i in idx[:-1]:
|
|
572
|
+
d = d[i]
|
|
573
|
+
d[idx[-1]] = v
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def _median_reduce(vals, axis, fn):
|
|
577
|
+
"""嵌套列表沿 axis 逐切片应用 fn(纯 Python,归约语义)。"""
|
|
578
|
+
import itertools as _it
|
|
579
|
+
|
|
580
|
+
def rec(data, depth):
|
|
581
|
+
if depth == axis:
|
|
582
|
+
rest0 = data[0] if data else None
|
|
583
|
+
rshape = _shape_of(rest0) if isinstance(rest0, (list, tuple)) else ()
|
|
584
|
+
cols = list(_it.product(*[range(x) for x in rshape])) if rshape else [()]
|
|
585
|
+
if rshape:
|
|
586
|
+
def mk(shape):
|
|
587
|
+
if len(shape) == 1:
|
|
588
|
+
return [None] * shape[0]
|
|
589
|
+
return [mk(shape[1:]) for _ in range(shape[0])]
|
|
590
|
+
out = mk(rshape)
|
|
591
|
+
for ri in cols:
|
|
592
|
+
_seti(out, ri, fn([_geti(blk, ri) for blk in data]))
|
|
593
|
+
else:
|
|
594
|
+
out = fn(list(data))
|
|
595
|
+
return out
|
|
596
|
+
return [rec(blk, depth + 1) for blk in data]
|
|
597
|
+
|
|
598
|
+
return rec(vals, 0)
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
def _percentile_1d(col, q):
|
|
602
|
+
"""1-d 百分位数('linear' 语义;NaN 视为最大值排到末尾)。"""
|
|
603
|
+
col = list(col)
|
|
604
|
+
n = len(col)
|
|
605
|
+
if n == 0:
|
|
606
|
+
import warnings as _w_p
|
|
607
|
+
_w_p.warn("Percentile of empty slice", RuntimeWarning, stacklevel=4)
|
|
608
|
+
return float('nan')
|
|
609
|
+
s = sorted(v for v in col if not (isinstance(v, float) and v != v))
|
|
610
|
+
pos = (float(q) / 100.0) * (n - 1)
|
|
611
|
+
lo = int(pos)
|
|
612
|
+
hi = lo + 1
|
|
613
|
+
|
|
614
|
+
def at(i):
|
|
615
|
+
if i < len(s):
|
|
616
|
+
return s[i]
|
|
617
|
+
return float('nan')
|
|
618
|
+
|
|
619
|
+
if hi >= n:
|
|
620
|
+
return at(lo)
|
|
621
|
+
frac = pos - lo
|
|
622
|
+
return at(lo) + (at(hi) - at(lo)) * frac
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
def median(a, axis=None, out=None, overwrite_input=False, keepdims=False):
|
|
626
|
+
"""计算数组的中位数(2.x 签名:overwrite_input/keepdims;
|
|
627
|
+
axis 支持 int/元组;NaN 传染 slice;m8/M8 支持 NaT;子类保留)。
|
|
628
|
+
纯 Python 实现(委托 _nanfunctions_impl._median_py)——Rust _core.median
|
|
629
|
+
仅支持 f64/2D/线性,int/高维/元组轴会 panic abort。"""
|
|
630
|
+
_ = overwrite_input
|
|
631
|
+
from rsarray.lib import _nanfunctions_impl as _nfi
|
|
632
|
+
arr = a if hasattr(a, '_array') else _wrap(a)
|
|
633
|
+
# 子类钩子(gh-3846):override 了 mean 的 ndarray 子类 → 委托其 mean
|
|
634
|
+
_NDC = _nd()
|
|
635
|
+
t = _builtins.type(arr)
|
|
636
|
+
if (t is not _NDC and _builtins.isinstance(t, _builtins.type)
|
|
637
|
+
and _builtins.issubclass(t, _NDC)
|
|
638
|
+
and not t.__name__.startswith('Masked')
|
|
639
|
+
and getattr(t, 'mean', None) is not getattr(_NDC, 'mean', None)):
|
|
640
|
+
return arr.mean()
|
|
641
|
+
return _nfi._median_py(arr, axis, out, keepdims)
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
def average(a, axis=None, weights=None, returned=False):
|
|
645
|
+
"""计算数组的加权平均值。"""
|
|
646
|
+
if weights is not None:
|
|
647
|
+
weights = _ensure_raw(weights)
|
|
648
|
+
raw_result = _core.average(_ensure_raw(a), axis, weights, returned)
|
|
649
|
+
if returned:
|
|
650
|
+
if hasattr(raw_result, 'tolist'):
|
|
651
|
+
result_list = raw_result.tolist()
|
|
652
|
+
else:
|
|
653
|
+
result_list = list(raw_result)
|
|
654
|
+
if axis is None:
|
|
655
|
+
avg_val = float(result_list[0])
|
|
656
|
+
sum_weights = float(result_list[1])
|
|
657
|
+
return avg_val, sum_weights
|
|
658
|
+
else:
|
|
659
|
+
if isinstance(result_list[0], (list, tuple)):
|
|
660
|
+
avg_vals = [item[0] for item in result_list]
|
|
661
|
+
sum_ws = [item[1] for item in result_list]
|
|
662
|
+
else:
|
|
663
|
+
avg_vals = result_list[0]
|
|
664
|
+
sum_ws = result_list[1]
|
|
665
|
+
return _nd()(avg_vals, _dtype='float64'), _nd()(sum_ws, _dtype='float64')
|
|
666
|
+
return _wrap(raw_result)
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
def percentile(a, q, axis=None, out=None, overwrite_input=False,
|
|
670
|
+
method='linear', keepdims=False, weights=None,
|
|
671
|
+
interpolation=None):
|
|
672
|
+
"""计算数组的百分位数(2.x:method/weights;interpolation 为弃用别名)。"""
|
|
673
|
+
from rsarray.lib import _nanfunctions_impl as _nfi
|
|
674
|
+
if interpolation is not None:
|
|
675
|
+
if method == 'linear':
|
|
676
|
+
method = interpolation
|
|
677
|
+
else:
|
|
678
|
+
raise ValueError(
|
|
679
|
+
"interpolation and method cannot be used simultaneously")
|
|
680
|
+
return _nfi._percentile_public(a, q, axis, out, overwrite_input, method,
|
|
681
|
+
keepdims, weights, nan_filter=False,
|
|
682
|
+
scale=100.0)
|
|
683
|
+
|
|
684
|
+
|
|
685
|
+
def quantile(a, q, axis=None, out=None, method='linear', keepdims=False,
|
|
686
|
+
weights=None, interpolation=None):
|
|
687
|
+
"""计算数组的分位数(q ∈ [0,1];2.x:method/weights)。"""
|
|
688
|
+
if interpolation is not None:
|
|
689
|
+
if method == 'linear':
|
|
690
|
+
method = interpolation
|
|
691
|
+
else:
|
|
692
|
+
raise ValueError(
|
|
693
|
+
"interpolation and method cannot be used simultaneously")
|
|
694
|
+
# * 100(整数乘法):Fraction q 保持精确(Fraction*int=Fraction);
|
|
695
|
+
# 嵌套列表递归缩放(结果形状按平铺 q,断言可广播)
|
|
696
|
+
def _scale_q(qq):
|
|
697
|
+
if isinstance(qq, (list, tuple)):
|
|
698
|
+
return [_scale_q(v) for v in qq]
|
|
699
|
+
return qq * 100
|
|
700
|
+
qs = _scale_q(q)
|
|
701
|
+
return percentile(a, qs, axis=axis, out=out, method=method,
|
|
702
|
+
keepdims=keepdims, weights=weights)
|
|
703
|
+
|
|
704
|
+
|
|
705
|
+
def nanmedian(a, axis=None, out=None, overwrite_input=False, keepdims=False):
|
|
706
|
+
"""忽略 NaN 的中位数(委托 _nanfunctions_impl:Rust 快路径 + 逐 slice 归约)。"""
|
|
707
|
+
from rsarray.lib import _nanfunctions_impl as _nfi
|
|
708
|
+
return _nfi.nanmedian(a, axis=axis, out=out,
|
|
709
|
+
overwrite_input=overwrite_input, keepdims=keepdims)
|
|
710
|
+
|
|
711
|
+
|
|
712
|
+
def nanpercentile(a, q, axis=None, out=None, overwrite_input=False,
|
|
713
|
+
method='linear', keepdims=False, weights=None,
|
|
714
|
+
interpolation=None):
|
|
715
|
+
"""忽略 NaN 的百分位数(委托 _nanfunctions_impl)。"""
|
|
716
|
+
from rsarray.lib import _nanfunctions_impl as _nfi
|
|
717
|
+
return _nfi.nanpercentile(a, q, axis=axis, out=out,
|
|
718
|
+
overwrite_input=overwrite_input, method=method,
|
|
719
|
+
keepdims=keepdims, weights=weights,
|
|
720
|
+
interpolation=interpolation)
|
|
721
|
+
|
|
722
|
+
|
|
723
|
+
def argmax(a, axis=None, out=None, keepdims=False):
|
|
724
|
+
"""返回数组沿指定轴的最大值索引(全归约返回 intp 标量,数组语义)。"""
|
|
725
|
+
_ = out
|
|
726
|
+
arr = a if hasattr(a, '_array') else _wrap(a)
|
|
727
|
+
if axis is not None and axis < 0:
|
|
728
|
+
axis += arr.ndim
|
|
729
|
+
raw = _core.argmax_axis(_ensure_raw(arr), axis)
|
|
730
|
+
if axis is None:
|
|
731
|
+
# 全归约返回带 .dtype 的 0-d intp(数组语义),而非 Python int
|
|
732
|
+
return _nd()._wrap(raw, _dtype='int64')
|
|
733
|
+
result = _nd()._wrap(raw, _dtype='int64')
|
|
734
|
+
if keepdims:
|
|
735
|
+
shape = list(tuple(arr.shape))
|
|
736
|
+
shape[axis] = 1
|
|
737
|
+
result = result.reshape(tuple(shape))
|
|
738
|
+
return result
|
|
739
|
+
|
|
740
|
+
|
|
741
|
+
def argmin(a, axis=None, out=None, keepdims=False):
|
|
742
|
+
"""返回数组沿指定轴的最小值索引。"""
|
|
743
|
+
_ = out
|
|
744
|
+
arr = a if hasattr(a, '_array') else _wrap(a)
|
|
745
|
+
if axis is not None and axis < 0:
|
|
746
|
+
axis += arr.ndim
|
|
747
|
+
raw = _core.argmin_axis(_ensure_raw(arr), axis)
|
|
748
|
+
if axis is None:
|
|
749
|
+
# 全归约返回带 .dtype 的 0-d intp(数组语义),而非 Python int
|
|
750
|
+
return _nd()._wrap(raw, _dtype='int64')
|
|
751
|
+
result = _nd()._wrap(raw, _dtype='int64')
|
|
752
|
+
if keepdims:
|
|
753
|
+
shape = list(tuple(arr.shape))
|
|
754
|
+
shape[axis] = 1
|
|
755
|
+
result = result.reshape(tuple(shape))
|
|
756
|
+
return result
|
|
757
|
+
|
|
758
|
+
|
|
759
|
+
def argsort(a, axis=-1, kind=None, order=None):
|
|
760
|
+
"""返回数组排序后的索引。"""
|
|
761
|
+
_ = kind, order
|
|
762
|
+
if axis is None:
|
|
763
|
+
a = a.ravel() if _is_ndarray(a) else _nd()(a).ravel()
|
|
764
|
+
axis = -1
|
|
765
|
+
return _nd()._wrap(_core.argsort(_ensure_raw(a), axis), _dtype='int64')
|
|
766
|
+
|
|
767
|
+
|
|
768
|
+
def sort(a, axis=-1, kind=None, order=None):
|
|
769
|
+
"""对数组进行排序。"""
|
|
770
|
+
_ = kind
|
|
771
|
+
arr = _nd()(a) if not _is_ndarray(a) else a
|
|
772
|
+
fields = getattr(arr, '_fields', None)
|
|
773
|
+
if fields and order is not None:
|
|
774
|
+
field_names = [f[0] for f in fields]
|
|
775
|
+
if order not in field_names:
|
|
776
|
+
raise ValueError(f"field {order!r} not found in dtype")
|
|
777
|
+
field_idx = field_names.index(order)
|
|
778
|
+
raw_data = getattr(arr, '_raw_data', None)
|
|
779
|
+
if raw_data is not None:
|
|
780
|
+
sorted_data = sorted(raw_data, key=lambda x: x[field_idx])
|
|
781
|
+
return _nd()(sorted_data, _dtype=arr._dtype, _fields=fields, _raw_data=sorted_data)
|
|
782
|
+
if axis is None:
|
|
783
|
+
arr = arr.ravel()
|
|
784
|
+
axis = -1
|
|
785
|
+
return _wrap(_core.sort(_ensure_raw(arr), axis))
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
def lexsort(keys, axis=-1):
|
|
789
|
+
"""使用多个键进行间接排序。优先按最后一个键排序。"""
|
|
790
|
+
if not isinstance(keys, (tuple, list)):
|
|
791
|
+
keys = (keys,)
|
|
792
|
+
nd = _nd()
|
|
793
|
+
# 数组语义(gh-7528):越界 axis → AxisError(避免 Rust panic)
|
|
794
|
+
_first = keys[0]
|
|
795
|
+
_dim = int(_first.ndim) if hasattr(_first, 'ndim') else int(nd(_first).ndim)
|
|
796
|
+
_ax = axis + _dim if axis < 0 else axis
|
|
797
|
+
if _ax < 0 or _ax >= _dim:
|
|
798
|
+
from rsarray.exceptions import AxisError
|
|
799
|
+
raise AxisError(
|
|
800
|
+
f"axis {axis} is out of bounds for array of dimension {_dim}")
|
|
801
|
+
raw_keys = []
|
|
802
|
+
for k in keys:
|
|
803
|
+
if hasattr(k, '_array'):
|
|
804
|
+
raw_keys.append(k._array)
|
|
805
|
+
else:
|
|
806
|
+
raw_keys.append(nd(k)._array)
|
|
807
|
+
return nd._wrap(_core.lexsort(raw_keys), _dtype='int64')
|
|
808
|
+
|
|
809
|
+
|
|
810
|
+
def msort(a):
|
|
811
|
+
"""数组按第一个轴排序,返回排序后的数组副本。"""
|
|
812
|
+
return sort(a, axis=0)
|
|
813
|
+
|
|
814
|
+
|
|
815
|
+
def sort_complex(a):
|
|
816
|
+
"""对复数按照先实部后虚部的顺序进行排序。"""
|
|
817
|
+
arr = _nd()(a) if not _is_ndarray(a) else a
|
|
818
|
+
return _nd()._wrap(_core.sort_complex(arr._array, -1), _dtype=getattr(arr, '_dtype', 'float64'))
|
|
819
|
+
|
|
820
|
+
|
|
821
|
+
def partition(a, kth, axis=-1, kind=None, order=None):
|
|
822
|
+
"""指定一个数,对数组进行分区。"""
|
|
823
|
+
_ = kind, order
|
|
824
|
+
arr = _nd()(a) if not _is_ndarray(a) else a
|
|
825
|
+
if isinstance(kth, int):
|
|
826
|
+
kth = [kth]
|
|
827
|
+
return _nd()._wrap(_core.partition(arr._array, list(kth), axis), _dtype=getattr(arr, '_dtype', 'float64'))
|
|
828
|
+
|
|
829
|
+
|
|
830
|
+
def argpartition(a, kth, axis=-1, kind=None, order=None):
|
|
831
|
+
"""对数组进行分区并返回索引。"""
|
|
832
|
+
_ = kind, order
|
|
833
|
+
arr = _nd()(a) if not _is_ndarray(a) else a
|
|
834
|
+
if isinstance(kth, int):
|
|
835
|
+
kth = [kth]
|
|
836
|
+
return _nd()._wrap(_core.argpartition(arr._array, list(kth), axis), _dtype='int64')
|
|
837
|
+
|
|
838
|
+
|
|
839
|
+
def searchsorted(a, v, side='left', sorter=None):
|
|
840
|
+
"""查找元素在有序数组中的插入位置。"""
|
|
841
|
+
_ = sorter
|
|
842
|
+
arr = a if hasattr(a, '_array') else _wrap(a)
|
|
843
|
+
|
|
844
|
+
# 一维数组 + 标量 v:保持返回 Python int 的语义
|
|
845
|
+
if len(arr.shape) <= 1:
|
|
846
|
+
if hasattr(v, '_array') and len(v.shape) == 0:
|
|
847
|
+
return _core.searchsorted(_ensure_raw(arr), float(v.item()), side)
|
|
848
|
+
try:
|
|
849
|
+
v_val = float(v)
|
|
850
|
+
return _core.searchsorted(_ensure_raw(arr), v_val, side)
|
|
851
|
+
except (TypeError, ValueError):
|
|
852
|
+
pass
|
|
853
|
+
|
|
854
|
+
# 多维或 v 为数组:使用 Rust 多维实现
|
|
855
|
+
v_raw = v._array if hasattr(v, '_array') else v
|
|
856
|
+
return _nd()._wrap(_core.searchsorted_axis(_ensure_raw(arr), v_raw, side), _dtype='int64')
|
|
857
|
+
|
|
858
|
+
|
|
859
|
+
def extract(condition, a):
|
|
860
|
+
"""根据条件从数组中抽取元素。"""
|
|
861
|
+
cond_arr = condition if hasattr(condition, '_array') else _nd()(condition)
|
|
862
|
+
data_arr = a if hasattr(a, '_array') else _nd()(a)
|
|
863
|
+
return _wrap(_core.extract(cond_arr._array, data_arr._array))
|
|
864
|
+
|
|
865
|
+
|
|
866
|
+
def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None, *, dtype=None):
|
|
867
|
+
"""计算协方差矩阵。"""
|
|
868
|
+
_ = y, bias, ddof, fweights, aweights, dtype
|
|
869
|
+
arr = m if hasattr(m, '_array') else _wrap(m)
|
|
870
|
+
return _wrap(_core.cov(_ensure_raw(arr), rowvar))
|
|
871
|
+
|
|
872
|
+
|
|
873
|
+
def corrcoef(x, y=None, rowvar=True, bias=False, ddof=None, *, dtype=None):
|
|
874
|
+
"""计算相关系数矩阵。"""
|
|
875
|
+
_ = y, bias, ddof, dtype
|
|
876
|
+
arr = x if hasattr(x, '_array') else _wrap(x)
|
|
877
|
+
return _wrap(_core.corrcoef_rs(_ensure_raw(arr)))
|
|
878
|
+
|
|
879
|
+
|
|
880
|
+
def _hist_is_int_dtype(dt):
|
|
881
|
+
s = _builtins.str(dt)
|
|
882
|
+
return 'int' in s or 'bool' in s
|
|
883
|
+
|
|
884
|
+
|
|
885
|
+
def _hist_bin_sqrt(vals, first, last):
|
|
886
|
+
return (last - first) / (len(vals) ** 0.5)
|
|
887
|
+
|
|
888
|
+
|
|
889
|
+
def _hist_bin_sturges(vals, first, last):
|
|
890
|
+
import math
|
|
891
|
+
return (last - first) / (math.log2(len(vals)) + 1.0)
|
|
892
|
+
|
|
893
|
+
|
|
894
|
+
def _hist_bin_rice(vals, first, last):
|
|
895
|
+
return (last - first) / (2.0 * len(vals) ** (1.0 / 3))
|
|
896
|
+
|
|
897
|
+
|
|
898
|
+
def _hist_bin_scott(vals, first, last):
|
|
899
|
+
m = _builtins.sum(vals) / len(vals)
|
|
900
|
+
var = _builtins.sum((v - m) ** 2 for v in vals) / len(vals)
|
|
901
|
+
return (24.0 * 3.141592653589793 ** 0.5 / len(vals)) ** (1.0 / 3.0) * var ** 0.5
|
|
902
|
+
|
|
903
|
+
|
|
904
|
+
def _hist_bin_stone(vals, first, last):
|
|
905
|
+
n = len(vals)
|
|
906
|
+
ptp = last - first
|
|
907
|
+
if n <= 1 or ptp == 0:
|
|
908
|
+
return 0.0
|
|
909
|
+
ub = _builtins.max(100, _builtins.int(len(vals) ** 0.5))
|
|
910
|
+
|
|
911
|
+
def jhat(nb):
|
|
912
|
+
step = ptp / nb
|
|
913
|
+
cnt = [0] * nb
|
|
914
|
+
for v in vals:
|
|
915
|
+
i = _builtins.int((v - first) / step)
|
|
916
|
+
if i < 0:
|
|
917
|
+
i = 0
|
|
918
|
+
if i >= nb:
|
|
919
|
+
i = nb - 1
|
|
920
|
+
cnt[i] += 1
|
|
921
|
+
p2 = _builtins.sum((c / n) ** 2 for c in cnt)
|
|
922
|
+
return (2 - (n + 1) * p2) / step
|
|
923
|
+
|
|
924
|
+
best = 1
|
|
925
|
+
bestj = None
|
|
926
|
+
for nb in _builtins.range(1, ub + 1):
|
|
927
|
+
j = jhat(nb)
|
|
928
|
+
if bestj is None or j < bestj:
|
|
929
|
+
bestj, best = j, nb
|
|
930
|
+
return ptp / best
|
|
931
|
+
|
|
932
|
+
|
|
933
|
+
def _hist_bin_doane(vals, first, last):
|
|
934
|
+
import math
|
|
935
|
+
n = len(vals)
|
|
936
|
+
if n > 2:
|
|
937
|
+
sg1 = (6.0 * (n - 2) / ((n + 1.0) * (n + 3))) ** 0.5
|
|
938
|
+
m = _builtins.sum(vals) / n
|
|
939
|
+
var = _builtins.sum((v - m) ** 2 for v in vals) / n
|
|
940
|
+
sigma = var ** 0.5
|
|
941
|
+
if sigma > 0.0:
|
|
942
|
+
g1 = _builtins.sum(((v - m) / sigma) ** 3 for v in vals) / n
|
|
943
|
+
return (last - first) / (1.0 + math.log2(n) +
|
|
944
|
+
math.log2(1.0 + _builtins.abs(g1) / sg1))
|
|
945
|
+
return 0.0
|
|
946
|
+
|
|
947
|
+
|
|
948
|
+
def _hist_bin_fd(vals, first, last):
|
|
949
|
+
s = sorted(vals)
|
|
950
|
+
n = len(s)
|
|
951
|
+
|
|
952
|
+
def q(p):
|
|
953
|
+
idx = p * (n - 1)
|
|
954
|
+
lo = _builtins.int(idx)
|
|
955
|
+
hi = _builtins.min(lo + 1, n - 1)
|
|
956
|
+
frac = idx - lo
|
|
957
|
+
return s[lo] * (1 - frac) + s[hi] * frac
|
|
958
|
+
|
|
959
|
+
iqr = q(0.75) - q(0.25)
|
|
960
|
+
return 2.0 * iqr * n ** (-1.0 / 3.0)
|
|
961
|
+
|
|
962
|
+
|
|
963
|
+
def _hist_bin_auto(vals, first, last):
|
|
964
|
+
fd = _hist_bin_fd(vals, first, last)
|
|
965
|
+
st = _hist_bin_sturges(vals, first, last)
|
|
966
|
+
sq = _hist_bin_sqrt(vals, first, last)
|
|
967
|
+
return _builtins.min(_builtins.max(fd, sq / 2), st)
|
|
968
|
+
|
|
969
|
+
|
|
970
|
+
_hist_bin_selectors = {'stone': _hist_bin_stone, 'auto': _hist_bin_auto,
|
|
971
|
+
'doane': _hist_bin_doane, 'fd': _hist_bin_fd,
|
|
972
|
+
'rice': _hist_bin_rice, 'scott': _hist_bin_scott,
|
|
973
|
+
'sqrt': _hist_bin_sqrt, 'sturges': _hist_bin_sturges}
|
|
974
|
+
|
|
975
|
+
|
|
976
|
+
def _hist_outer_edges(vals, rng):
|
|
977
|
+
import math
|
|
978
|
+
if rng is not None:
|
|
979
|
+
fe, le = _builtins.float(rng[0]), _builtins.float(rng[1])
|
|
980
|
+
if fe > le:
|
|
981
|
+
raise ValueError('max must be larger than min in range parameter.')
|
|
982
|
+
if not (math.isfinite(fe) and math.isfinite(le)):
|
|
983
|
+
raise ValueError(
|
|
984
|
+
f"supplied range of [{fe}, {le}] is not finite")
|
|
985
|
+
elif len(vals) == 0:
|
|
986
|
+
fe, le = 0.0, 1.0
|
|
987
|
+
else:
|
|
988
|
+
fe, le = _builtins.min(vals), _builtins.max(vals)
|
|
989
|
+
if not (math.isfinite(fe) and math.isfinite(le)):
|
|
990
|
+
raise ValueError(
|
|
991
|
+
f"autodetected range of [{fe}, {le}] is not finite")
|
|
992
|
+
if fe == le:
|
|
993
|
+
fe, le = fe - 0.5, le + 0.5
|
|
994
|
+
return fe, le
|
|
995
|
+
|
|
996
|
+
|
|
997
|
+
def _hist_get_bin_edges(vals, bins, rng, weights):
|
|
998
|
+
n_equal = None
|
|
999
|
+
edges = None
|
|
1000
|
+
if isinstance(bins, _builtins.str):
|
|
1001
|
+
if bins not in _hist_bin_selectors:
|
|
1002
|
+
raise ValueError(f"{bins!r} is not a valid estimator for `bins`")
|
|
1003
|
+
if weights is not None:
|
|
1004
|
+
raise TypeError("Automated estimation of the number of "
|
|
1005
|
+
"bins is not supported for weighted data")
|
|
1006
|
+
fe, le = _hist_outer_edges(vals, rng)
|
|
1007
|
+
if rng is not None:
|
|
1008
|
+
keep = [v for v in vals if fe <= v <= le]
|
|
1009
|
+
if len(keep) != len(vals):
|
|
1010
|
+
vals = keep
|
|
1011
|
+
if len(vals) == 0:
|
|
1012
|
+
n_equal = 1
|
|
1013
|
+
else:
|
|
1014
|
+
width = _hist_bin_selectors[bins](vals, fe, le)
|
|
1015
|
+
if width:
|
|
1016
|
+
if _hist_is_int_dtype(_rs_dtype_of(vals)) and width < 1:
|
|
1017
|
+
width = 1
|
|
1018
|
+
n_equal = _builtins.int(-_builtins.int(-(le - fe) / width))
|
|
1019
|
+
else:
|
|
1020
|
+
n_equal = 1
|
|
1021
|
+
elif isinstance(bins, (int, float)) and not isinstance(bins, bool):
|
|
1022
|
+
if isinstance(bins, float):
|
|
1023
|
+
raise TypeError('`bins` must be an integer, a string, or an array')
|
|
1024
|
+
n_equal = bins
|
|
1025
|
+
if n_equal < 1:
|
|
1026
|
+
raise ValueError('`bins` must be positive, when an integer')
|
|
1027
|
+
fe, le = _hist_outer_edges(vals, rng)
|
|
1028
|
+
else:
|
|
1029
|
+
import rsarray as _rs
|
|
1030
|
+
b_arr = bins if hasattr(bins, '_array') else _rs.array(bins)
|
|
1031
|
+
if b_arr.ndim > 1:
|
|
1032
|
+
raise ValueError('`bins` must be 1d, when an array')
|
|
1033
|
+
edges = [_builtins.float(e) for e in _rs_flat(bins)]
|
|
1034
|
+
for i in _builtins.range(len(edges) - 1):
|
|
1035
|
+
if edges[i] > edges[i + 1]:
|
|
1036
|
+
raise ValueError(
|
|
1037
|
+
'`bins` must increase monotonically, when an array')
|
|
1038
|
+
if n_equal is not None:
|
|
1039
|
+
if _builtins.all(_builtins.isinstance(v, int) for v in vals) and \
|
|
1040
|
+
rng is None:
|
|
1041
|
+
fe, le = _builtins.float(fe), _builtins.float(le)
|
|
1042
|
+
edges = [fe + (le - fe) * i / n_equal for i in _builtins.range(n_equal + 1)]
|
|
1043
|
+
edges[-1] = le
|
|
1044
|
+
for i in _builtins.range(len(edges) - 1):
|
|
1045
|
+
if edges[i] >= edges[i + 1]:
|
|
1046
|
+
raise ValueError(
|
|
1047
|
+
f'Too many bins for data range. Cannot create '
|
|
1048
|
+
f'{n_equal} finite-sized bins.')
|
|
1049
|
+
return edges, (fe, le, n_equal)
|
|
1050
|
+
return edges, None
|
|
1051
|
+
|
|
1052
|
+
|
|
1053
|
+
def _rs_flat(a):
|
|
1054
|
+
import rsarray as _rs
|
|
1055
|
+
if hasattr(a, '_array'):
|
|
1056
|
+
return a.reshape((-1,)).tolist()
|
|
1057
|
+
return _rs.array(a).reshape((-1,)).tolist()
|
|
1058
|
+
|
|
1059
|
+
|
|
1060
|
+
def _rs_dtype_of(a):
|
|
1061
|
+
import rsarray as _rs
|
|
1062
|
+
return (a if hasattr(a, '_array') else _rs.array(a)).dtype
|
|
1063
|
+
|
|
1064
|
+
|
|
1065
|
+
def histogram(a, bins=10, range=None, weights=None, density=None):
|
|
1066
|
+
"""计算直方图(纯 Python:int/边界数组/字符串 bins、range、density、weights)。"""
|
|
1067
|
+
import bisect
|
|
1068
|
+
import math
|
|
1069
|
+
import warnings
|
|
1070
|
+
import rsarray as _rs
|
|
1071
|
+
_ = density is None # density 默认 None,等价 False
|
|
1072
|
+
if density is None:
|
|
1073
|
+
density = False
|
|
1074
|
+
a_arr = a if hasattr(a, '_array') else _rs.array(a)
|
|
1075
|
+
if _builtins.str(a_arr.dtype) == 'bool':
|
|
1076
|
+
warnings.warn(
|
|
1077
|
+
f"Converting input from {a_arr.dtype} to bool for compatibility.",
|
|
1078
|
+
RuntimeWarning)
|
|
1079
|
+
vals = [_builtins.float(v) for v in a_arr.reshape((-1,)).tolist()]
|
|
1080
|
+
n = len(vals)
|
|
1081
|
+
if weights is not None:
|
|
1082
|
+
w_arr = weights if hasattr(weights, '_array') else _rs.array(weights)
|
|
1083
|
+
if tuple(w_arr.shape) != tuple(a_arr.shape):
|
|
1084
|
+
raise ValueError('weights should have the same shape as a.')
|
|
1085
|
+
w = w_arr.reshape((-1,)).tolist()
|
|
1086
|
+
else:
|
|
1087
|
+
w = None
|
|
1088
|
+
if range is not None and len(range) != 2:
|
|
1089
|
+
raise ValueError('range must be a sequence of two numbers')
|
|
1090
|
+
edges, _uniform = _hist_get_bin_edges(vals, bins, range, w)
|
|
1091
|
+
nb = len(edges) - 1
|
|
1092
|
+
w_float = w is not None and not _hist_is_int_dtype(
|
|
1093
|
+
(weights if hasattr(weights, '_array') else _rs.array(weights)).dtype)
|
|
1094
|
+
counts = [0.0] * nb if w_float else [0] * nb
|
|
1095
|
+
for i in _builtins.range(n):
|
|
1096
|
+
v = vals[i]
|
|
1097
|
+
b = bisect.bisect_right(edges, v) - 1
|
|
1098
|
+
if b == nb and v == edges[-1]:
|
|
1099
|
+
b = nb - 1
|
|
1100
|
+
if 0 <= b < nb:
|
|
1101
|
+
counts[b] += (w[i] if w is not None else 1)
|
|
1102
|
+
if density:
|
|
1103
|
+
# —n / db / n.sum(),n 是入界计数(含 outlier 会失真)
|
|
1104
|
+
total = _builtins.sum(_builtins.float(c) for c in counts)
|
|
1105
|
+
if total > 0:
|
|
1106
|
+
counts = [_builtins.float(counts[i]) / (total * (edges[i + 1] - edges[i]))
|
|
1107
|
+
for i in _builtins.range(nb)]
|
|
1108
|
+
else:
|
|
1109
|
+
counts = [0.0] * nb
|
|
1110
|
+
return _rs.array(counts, dtype='float64'), _rs.array(edges, dtype='float64')
|
|
1111
|
+
if w_float:
|
|
1112
|
+
counts_arr = _rs.array([_builtins.float(c) for c in counts],
|
|
1113
|
+
dtype='float64')
|
|
1114
|
+
else:
|
|
1115
|
+
counts_arr = _rs.array([_builtins.int(c) for c in counts],
|
|
1116
|
+
dtype='int64')
|
|
1117
|
+
return counts_arr, _rs.array(edges, dtype='float64')
|
|
1118
|
+
|
|
1119
|
+
|
|
1120
|
+
_H2D_DEFAULT = object()
|
|
1121
|
+
|
|
1122
|
+
|
|
1123
|
+
def _hist2d_1d(a):
|
|
1124
|
+
"""把输入展平为 float 列表。"""
|
|
1125
|
+
import rsarray as _rs
|
|
1126
|
+
if hasattr(a, '_array'):
|
|
1127
|
+
return [_builtins.float(v) for v in a.reshape((-1,)).tolist()]
|
|
1128
|
+
return [_builtins.float(v) for v in _rs.array(a).reshape((-1,)).tolist()]
|
|
1129
|
+
|
|
1130
|
+
|
|
1131
|
+
def _hist2d_edges(spec, vals, rng):
|
|
1132
|
+
"""bin 规格(int 数 或 显式边界序列)+ range → 边界 float 列表。"""
|
|
1133
|
+
import rsarray as _rs
|
|
1134
|
+
if isinstance(spec, (int, float)) and not isinstance(spec, bool):
|
|
1135
|
+
nb = _builtins.int(spec)
|
|
1136
|
+
if nb <= 0:
|
|
1137
|
+
raise ValueError("bins must be positive")
|
|
1138
|
+
if rng is not None:
|
|
1139
|
+
lo, hi = _builtins.float(rng[0]), _builtins.float(rng[1])
|
|
1140
|
+
elif len(vals) == 0:
|
|
1141
|
+
lo, hi = 0.0, 1.0
|
|
1142
|
+
else:
|
|
1143
|
+
lo, hi = _builtins.min(vals), _builtins.max(vals)
|
|
1144
|
+
if lo == hi:
|
|
1145
|
+
lo, hi = lo - 0.5, hi + 0.5
|
|
1146
|
+
step = (hi - lo) / nb
|
|
1147
|
+
return [lo + step * i for i in _builtins.range(nb + 1)]
|
|
1148
|
+
if hasattr(spec, '_array'):
|
|
1149
|
+
return [_builtins.float(e) for e in spec.reshape((-1,)).tolist()]
|
|
1150
|
+
return [_builtins.float(e) for e in _rs.array(spec).reshape((-1,)).tolist()]
|
|
1151
|
+
|
|
1152
|
+
|
|
1153
|
+
def _hist2d_dispatch(x, y, bins, weights, kw):
|
|
1154
|
+
"""__array_function__ dispatch:x/y/weights/bins 中非 ndarray 的 dispatchable 触发。"""
|
|
1155
|
+
import rsarray as _rs
|
|
1156
|
+
cands = [x, y, weights]
|
|
1157
|
+
if isinstance(bins, (list, tuple)):
|
|
1158
|
+
cands.extend(bins)
|
|
1159
|
+
else:
|
|
1160
|
+
cands.append(bins)
|
|
1161
|
+
types = []
|
|
1162
|
+
func = None
|
|
1163
|
+
for o in cands:
|
|
1164
|
+
if o is None or isinstance(o, (list, tuple, int, float, bool)):
|
|
1165
|
+
continue
|
|
1166
|
+
if isinstance(o, _rs.ndarray):
|
|
1167
|
+
continue
|
|
1168
|
+
f = getattr(o, '__array_function__', None)
|
|
1169
|
+
if f is not None:
|
|
1170
|
+
types.append(type(o))
|
|
1171
|
+
func = f
|
|
1172
|
+
if func is None:
|
|
1173
|
+
return None
|
|
1174
|
+
return func(_rs.histogram2d, tuple(types), (x, y), kw)
|
|
1175
|
+
|
|
1176
|
+
|
|
1177
|
+
def histogram2d(x, y, bins=_H2D_DEFAULT, range=_H2D_DEFAULT,
|
|
1178
|
+
density=_H2D_DEFAULT, weights=_H2D_DEFAULT):
|
|
1179
|
+
"""计算二维直方图(纯 Python:标量/显式边界/非对称 bins、range、density、weights)。
|
|
1180
|
+
|
|
1181
|
+
H 形状 (nbins_x, nbins_y),H[i, j] = x 落在第 i 个 x-bin、y 落在第 j 个 y-bin 的计数。
|
|
1182
|
+
"""
|
|
1183
|
+
import bisect
|
|
1184
|
+
import rsarray as _rs
|
|
1185
|
+
kw = {}
|
|
1186
|
+
if bins is not _H2D_DEFAULT:
|
|
1187
|
+
kw['bins'] = bins
|
|
1188
|
+
if range is not _H2D_DEFAULT:
|
|
1189
|
+
kw['range'] = range
|
|
1190
|
+
if density is not _H2D_DEFAULT:
|
|
1191
|
+
kw['density'] = density
|
|
1192
|
+
if weights is not _H2D_DEFAULT:
|
|
1193
|
+
kw['weights'] = weights
|
|
1194
|
+
if bins is _H2D_DEFAULT:
|
|
1195
|
+
bins = 10
|
|
1196
|
+
if range is _H2D_DEFAULT:
|
|
1197
|
+
range = None
|
|
1198
|
+
if density is _H2D_DEFAULT:
|
|
1199
|
+
density = False
|
|
1200
|
+
if weights is _H2D_DEFAULT:
|
|
1201
|
+
weights = None
|
|
1202
|
+
if isinstance(bins, (list, tuple)) and len(bins) != 2:
|
|
1203
|
+
raise ValueError("bins must be a scalar or a sequence of length 2")
|
|
1204
|
+
d = _hist2d_dispatch(x, y, bins, weights, kw)
|
|
1205
|
+
if d is not None:
|
|
1206
|
+
return d
|
|
1207
|
+
xa = _hist2d_1d(x)
|
|
1208
|
+
ya = _hist2d_1d(y)
|
|
1209
|
+
N = len(xa)
|
|
1210
|
+
if len(ya) != N:
|
|
1211
|
+
raise ValueError("x and y must have the same length.")
|
|
1212
|
+
w = [1.0] * N
|
|
1213
|
+
if weights is not None:
|
|
1214
|
+
w_raw = weights if hasattr(weights, '_array') else _rs.array(weights)
|
|
1215
|
+
if w_raw.ndim != 1 or w_raw.size != N:
|
|
1216
|
+
raise ValueError("weights must have the same shape as x")
|
|
1217
|
+
w = [_builtins.float(v) for v in w_raw.reshape((-1,)).tolist()]
|
|
1218
|
+
if isinstance(bins, (list, tuple)):
|
|
1219
|
+
bx_spec, by_spec = bins[0], bins[1]
|
|
1220
|
+
else:
|
|
1221
|
+
bx_spec = by_spec = bins
|
|
1222
|
+
rng_x = range[0] if range is not None else None
|
|
1223
|
+
rng_y = range[1] if range is not None else None
|
|
1224
|
+
xed = _hist2d_edges(bx_spec, xa, rng_x)
|
|
1225
|
+
yed = _hist2d_edges(by_spec, ya, rng_y)
|
|
1226
|
+
nbx = len(xed) - 1
|
|
1227
|
+
nby = len(yed) - 1
|
|
1228
|
+
count = [[0.0] * nby for _ in _builtins.range(nbx)]
|
|
1229
|
+
for i in _builtins.range(N):
|
|
1230
|
+
bx = bisect.bisect_right(xed, xa[i]) - 1
|
|
1231
|
+
if bx == nbx and xa[i] == xed[-1]:
|
|
1232
|
+
bx = nbx - 1
|
|
1233
|
+
by = bisect.bisect_right(yed, ya[i]) - 1
|
|
1234
|
+
if by == nby and ya[i] == yed[-1]:
|
|
1235
|
+
by = nby - 1
|
|
1236
|
+
if 0 <= bx < nbx and 0 <= by < nby:
|
|
1237
|
+
count[bx][by] += w[i]
|
|
1238
|
+
if density:
|
|
1239
|
+
total = _builtins.sum(w)
|
|
1240
|
+
if total > 0:
|
|
1241
|
+
for i in _builtins.range(nbx):
|
|
1242
|
+
dx = xed[i + 1] - xed[i]
|
|
1243
|
+
for j in _builtins.range(nby):
|
|
1244
|
+
dy = yed[j + 1] - yed[j]
|
|
1245
|
+
count[i][j] = count[i][j] / (total * dx * dy)
|
|
1246
|
+
H = _rs.array(count, dtype='float64')
|
|
1247
|
+
return H, _rs.array(xed), _rs.array(yed)
|
|
1248
|
+
|
|
1249
|
+
|
|
1250
|
+
def histogramdd(sample, bins=10, range=None, density=False, weights=None):
|
|
1251
|
+
"""计算多维直方图(纯 Python:支持标量/序列/显式边界 bins)。"""
|
|
1252
|
+
import bisect
|
|
1253
|
+
_range = _builtins.range # range 参数遮蔽内置函数
|
|
1254
|
+
# 规范化 sample:2-d 矩阵 (N, d) 或序列 of arrays(每维一个)
|
|
1255
|
+
if hasattr(sample, 'shape'):
|
|
1256
|
+
rows = sample.tolist()
|
|
1257
|
+
if len(sample.shape) <= 1:
|
|
1258
|
+
cols = [list(rows)]
|
|
1259
|
+
else:
|
|
1260
|
+
d = len(rows[0])
|
|
1261
|
+
cols = [[r[i] for r in rows] for i in _range(d)]
|
|
1262
|
+
else:
|
|
1263
|
+
first = sample[0] if len(sample) else None
|
|
1264
|
+
if hasattr(first, 'tolist') or isinstance(first, (list, tuple)):
|
|
1265
|
+
cols = [list(v) for v in sample]
|
|
1266
|
+
else:
|
|
1267
|
+
cols = [list(sample)]
|
|
1268
|
+
d = len(cols)
|
|
1269
|
+
if d == 0:
|
|
1270
|
+
raise ValueError("sample must contain at least one dimension")
|
|
1271
|
+
# bins 规范化:标量 → 每维同数;序列 → 每维 bin 数或显式边界
|
|
1272
|
+
if isinstance(bins, (int, float)) and not isinstance(bins, bool):
|
|
1273
|
+
bins_spec = [bins] * d
|
|
1274
|
+
else:
|
|
1275
|
+
bins_spec = list(bins)
|
|
1276
|
+
if len(bins_spec) != d:
|
|
1277
|
+
raise ValueError(
|
|
1278
|
+
f"bins must have length {d}, got {len(bins_spec)}")
|
|
1279
|
+
if weights is not None:
|
|
1280
|
+
w = weights.tolist() if hasattr(weights, 'tolist') else list(weights)
|
|
1281
|
+
else:
|
|
1282
|
+
w = None
|
|
1283
|
+
edges = []
|
|
1284
|
+
nbins = []
|
|
1285
|
+
for i in _range(d):
|
|
1286
|
+
spec = bins_spec[i]
|
|
1287
|
+
if hasattr(spec, 'tolist'):
|
|
1288
|
+
e = list(spec.tolist())
|
|
1289
|
+
elif isinstance(spec, (list, tuple)):
|
|
1290
|
+
e = list(spec)
|
|
1291
|
+
else:
|
|
1292
|
+
n = int(spec)
|
|
1293
|
+
if n <= 0:
|
|
1294
|
+
raise ValueError("each bins dimension must be positive")
|
|
1295
|
+
if range is not None:
|
|
1296
|
+
lo, hi = range[i][0], range[i][1]
|
|
1297
|
+
else:
|
|
1298
|
+
lo, hi = min(cols[i]), max(cols[i])
|
|
1299
|
+
if lo == hi:
|
|
1300
|
+
lo -= 0.5
|
|
1301
|
+
hi += 0.5
|
|
1302
|
+
step = (hi - lo) / n
|
|
1303
|
+
e = [lo + step * t for t in _range(n + 1)]
|
|
1304
|
+
e[-1] = hi
|
|
1305
|
+
edges.append(e)
|
|
1306
|
+
nbins.append(len(e) - 1)
|
|
1307
|
+
# 计数(C 序扁平;范围外的样本不计)
|
|
1308
|
+
size = 1
|
|
1309
|
+
for n in nbins:
|
|
1310
|
+
size *= n
|
|
1311
|
+
# bin 总数过大(如 10 维 bins=2**10 → 2**100)→ 数组语义抛 ValueError
|
|
1312
|
+
try:
|
|
1313
|
+
H = [0.0] * size
|
|
1314
|
+
except OverflowError:
|
|
1315
|
+
raise ValueError("too many bins")
|
|
1316
|
+
strides = [1] * d
|
|
1317
|
+
for i in _range(d - 2, -1, -1):
|
|
1318
|
+
strides[i] = strides[i + 1] * nbins[i + 1]
|
|
1319
|
+
n_samples = len(cols[0])
|
|
1320
|
+
for s in _range(n_samples):
|
|
1321
|
+
idx = []
|
|
1322
|
+
ok = True
|
|
1323
|
+
for i in _range(d):
|
|
1324
|
+
v = cols[i][s]
|
|
1325
|
+
e = edges[i]
|
|
1326
|
+
bi = bisect.bisect_right(e, v) - 1
|
|
1327
|
+
if bi == len(e) - 1 and v == e[-1]:
|
|
1328
|
+
bi -= 1 # 末 bin 闭区间
|
|
1329
|
+
if bi < 0 or v < e[0] or v > e[-1]:
|
|
1330
|
+
ok = False
|
|
1331
|
+
break
|
|
1332
|
+
idx.append(bi)
|
|
1333
|
+
if not ok:
|
|
1334
|
+
continue
|
|
1335
|
+
flat = 0
|
|
1336
|
+
for i in _range(d):
|
|
1337
|
+
flat += idx[i] * strides[i]
|
|
1338
|
+
H[flat] += w[s] if w is not None else 1.0
|
|
1339
|
+
if density:
|
|
1340
|
+
total = sum(H)
|
|
1341
|
+
widths = [[edges[i][j + 1] - edges[i][j]
|
|
1342
|
+
for j in _range(nbins[i])] for i in _range(d)]
|
|
1343
|
+
flat_w = []
|
|
1344
|
+
for fi in _range(size):
|
|
1345
|
+
vol = 1.0
|
|
1346
|
+
rem = fi
|
|
1347
|
+
for i in _range(d - 1, -1, -1):
|
|
1348
|
+
vol *= widths[i][rem % nbins[i]]
|
|
1349
|
+
rem //= nbins[i]
|
|
1350
|
+
flat_w.append(vol)
|
|
1351
|
+
H = [h / (total * v) if v else h for h, v in zip(H, flat_w)]
|
|
1352
|
+
import rsarray as _npmod
|
|
1353
|
+
H_arr = _npmod.array(H).reshape(tuple(nbins))
|
|
1354
|
+
return H_arr, [_wrap(e) for e in edges]
|
|
1355
|
+
|
|
1356
|
+
|
|
1357
|
+
def digitize(x, bins, right=False):
|
|
1358
|
+
"""返回输入数组中每个值所属的 bins 的索引。"""
|
|
1359
|
+
_ = right
|
|
1360
|
+
return _wrap(_core.digitize(_ensure_raw(x), _ensure_raw(bins)))
|