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/array_methods.py
ADDED
|
@@ -0,0 +1,1224 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""
|
|
3
|
+
ndarray 对象方法模块
|
|
4
|
+
|
|
5
|
+
此模块包含 rsarray.ndarray 类的所有对象方法和属性。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import builtins
|
|
9
|
+
|
|
10
|
+
import rsarray.num_core as _core
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _get_deps():
|
|
14
|
+
"""延迟获取 ndarray 和 _ensure,避免循环导入导致的 import 缓慢。"""
|
|
15
|
+
import rsarray
|
|
16
|
+
return rsarray.ndarray, rsarray._ensure
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _wrap_result(result, dtype="float64"):
|
|
20
|
+
"""包装结果为 ndarray 对象"""
|
|
21
|
+
ndarray, _ = _get_deps()
|
|
22
|
+
if hasattr(result, '__class__') and result.__class__.__name__ == 'ndarray':
|
|
23
|
+
return ndarray._wrap(result, _dtype=dtype)
|
|
24
|
+
return result
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class NdArrayMethods:
|
|
28
|
+
"""ndarray 对象方法集合"""
|
|
29
|
+
|
|
30
|
+
@staticmethod
|
|
31
|
+
def astype(arr, dtype, copy=True):
|
|
32
|
+
"""将数组转换为指定的数据类型。"""
|
|
33
|
+
# 结构化目标含 object 字段:底层 float 存储无法表示,显式拒绝
|
|
34
|
+
# (静默降级会损坏数据;对 object 字段的 axis 运算同样抛
|
|
35
|
+
# TypeError)。
|
|
36
|
+
if isinstance(dtype, (list, tuple)) and dtype and builtins.all(
|
|
37
|
+
isinstance(f, (list, tuple)) and len(f) >= 2 for f in dtype):
|
|
38
|
+
if builtins.any(f[1] is object or f[1] in ('object', 'O')
|
|
39
|
+
for f in dtype):
|
|
40
|
+
raise TypeError(
|
|
41
|
+
"cannot astype to a structured dtype containing object "
|
|
42
|
+
"fields (rsarray cannot represent object fields)")
|
|
43
|
+
# 非结构化 → 结构化:逐元素逐字段 cast(astype 语义:
|
|
44
|
+
# 每个标量按各字段 dtype 转换成一个记录)
|
|
45
|
+
try:
|
|
46
|
+
import rsarray as _rn_ast
|
|
47
|
+
_dst_dt = _rn_ast.dtype(dtype)
|
|
48
|
+
_dst_names = getattr(_dst_dt, 'names', None)
|
|
49
|
+
if _dst_names is not None:
|
|
50
|
+
_src_dt = getattr(arr, '_dtype_obj', None)
|
|
51
|
+
_src_structured = (_src_dt is not None
|
|
52
|
+
and getattr(_src_dt, '_names', None)
|
|
53
|
+
is not None)
|
|
54
|
+
if not _src_structured:
|
|
55
|
+
_recs = []
|
|
56
|
+
for _v in arr.tolist():
|
|
57
|
+
_recs.append(tuple(
|
|
58
|
+
_rn_ast._coerce_field_value(
|
|
59
|
+
_v, _dst_dt._fields[_n][0])
|
|
60
|
+
for _n in _dst_names))
|
|
61
|
+
res = _rn_ast.array(_recs, dtype=dtype)
|
|
62
|
+
if res.ndim < arr.ndim and arr.shape:
|
|
63
|
+
res = res.reshape(arr.shape)
|
|
64
|
+
return res
|
|
65
|
+
except Exception:
|
|
66
|
+
pass
|
|
67
|
+
# 字符串目标(S/U):_resolve_dtype 会把 S/U 降解成 float64,须单独
|
|
68
|
+
# 处理(数组语义:S 源解码并在 null 截断、U 源编码、宽度变更截断/
|
|
69
|
+
# 补零;裸 S/U(无宽度)= 自动宽度)
|
|
70
|
+
_str_tgt = None
|
|
71
|
+
try:
|
|
72
|
+
import rsarray as _rn_st
|
|
73
|
+
import rsarray._dtypes as _dts_st2
|
|
74
|
+
_DType_st = _dts_st2.DType
|
|
75
|
+
if isinstance(dtype, str):
|
|
76
|
+
_core_st = dtype[1:] if dtype and dtype[0] in '<>|=' else dtype
|
|
77
|
+
_st_exp_w = (bool(_core_st) and _core_st[0] in 'SU'
|
|
78
|
+
and _core_st[1:].isdigit())
|
|
79
|
+
else:
|
|
80
|
+
_st_exp_w = True
|
|
81
|
+
_tdt_st = dtype if isinstance(dtype, _DType_st) \
|
|
82
|
+
else _rn_st.dtype(dtype)
|
|
83
|
+
if getattr(_tdt_st, 'kind', None) in ('S', 'U', 'T'):
|
|
84
|
+
_str_tgt = (getattr(_tdt_st, '_kind', None), _st_exp_w)
|
|
85
|
+
except Exception:
|
|
86
|
+
_str_tgt = None
|
|
87
|
+
if _str_tgt is not None and getattr(arr, '_raw_data', None) is not None \
|
|
88
|
+
and getattr(arr, '_str_dtype', None) is not None:
|
|
89
|
+
_tk, _st_exp_w = _str_tgt
|
|
90
|
+
_st_vals = arr.tolist()
|
|
91
|
+
if not isinstance(_st_vals, list):
|
|
92
|
+
_st_vals = [_st_vals]
|
|
93
|
+
_st_norm = []
|
|
94
|
+
for _v in _st_vals:
|
|
95
|
+
if isinstance(_v, (bytes, bytearray)):
|
|
96
|
+
_st_norm.append(
|
|
97
|
+
bytes(_v).decode('latin-1').split('\x00')[0])
|
|
98
|
+
else:
|
|
99
|
+
_st_norm.append(str(_v).split('\x00')[0])
|
|
100
|
+
# 裸目标(无显式宽度):宽度保持语义——源有显式宽度时
|
|
101
|
+
# 目标宽度 = 源宽度(否则按内容推断最小宽度)
|
|
102
|
+
_src_sd = getattr(arr, '_str_dtype', None)
|
|
103
|
+
_src_w = _src_sd[1] if _src_sd is not None else 0
|
|
104
|
+
if not _src_w:
|
|
105
|
+
_src_w = 0
|
|
106
|
+
if _tk in ('U', 'T'):
|
|
107
|
+
_st_w = (_tdt_st._itemsize // 4) if _st_exp_w else \
|
|
108
|
+
(_src_w if _src_w > 0 else
|
|
109
|
+
max([len(_s) for _s in _st_norm] + [1]))
|
|
110
|
+
_st_out = [_s[:_st_w] for _s in _st_norm]
|
|
111
|
+
else:
|
|
112
|
+
_st_w = _tdt_st._itemsize if _st_exp_w else \
|
|
113
|
+
(_src_w if _src_w > 0 else
|
|
114
|
+
max([len(_s) for _s in _st_norm] + [1]))
|
|
115
|
+
_st_out = [_s.encode('latin-1')[:_st_w] for _s in _st_norm]
|
|
116
|
+
# 数组语义:目标 itemsize 不得超 intc max(超 → TypeError,
|
|
117
|
+
# large_string_cast 回归);T 按 U 存储计 4 字节/字符
|
|
118
|
+
if _st_w * (4 if _tk in ('U', 'T') else 1) > 2147483647:
|
|
119
|
+
raise TypeError(
|
|
120
|
+
f"string target of itemsize {_st_w * (4 if _tk in ('U', 'T') else 1)} "
|
|
121
|
+
"bytes exceeds the maximum representable size (intc max)")
|
|
122
|
+
_st_bo = getattr(_tdt_st, '_byteorder', None)
|
|
123
|
+
_st_prefix = '>' if _st_bo == '>' else '<'
|
|
124
|
+
if _tk == 'T':
|
|
125
|
+
# T 无固定宽度记法:按 U 构造后打变长标记(内部存储仍为 U)
|
|
126
|
+
_st_res = _rn_st.array(_st_out, dtype=f'U{max(_st_w, 1)}')
|
|
127
|
+
_st_res._strdtype_T = True
|
|
128
|
+
else:
|
|
129
|
+
_st_res = _rn_st.array(_st_out, dtype=f'{_tk}{max(_st_w, 1)}')
|
|
130
|
+
if _st_bo in ('<', '>'):
|
|
131
|
+
try:
|
|
132
|
+
import rsarray._dtypes as _dts_st
|
|
133
|
+
_st_res._dtype_obj = _dts_st._clone_with_byteorder(
|
|
134
|
+
_dts_st.DType(f'{_tk}{max(_st_w, 1)}'), _st_bo)
|
|
135
|
+
except Exception:
|
|
136
|
+
pass
|
|
137
|
+
if _st_res.ndim < arr.ndim and arr.shape:
|
|
138
|
+
_st_res = _st_res.reshape(arr.shape)
|
|
139
|
+
return _st_res
|
|
140
|
+
if isinstance(dtype, str):
|
|
141
|
+
try:
|
|
142
|
+
import rsarray as _rn_asm
|
|
143
|
+
name = str(_rn_asm._resolve_dtype(dtype))
|
|
144
|
+
except Exception:
|
|
145
|
+
name = dtype
|
|
146
|
+
else:
|
|
147
|
+
_dn = getattr(dtype, 'name', None)
|
|
148
|
+
name = _dn if isinstance(_dn, str) else getattr(dtype, "__name__", str(dtype))
|
|
149
|
+
# DType 类本身(type(np.dtype(...))):按裸 S 处理
|
|
150
|
+
if isinstance(dtype, type):
|
|
151
|
+
try:
|
|
152
|
+
import rsarray._dtypes as _dts_asm
|
|
153
|
+
if issubclass(dtype, _dts_asm.DType):
|
|
154
|
+
name = "bytes_"
|
|
155
|
+
except Exception:
|
|
156
|
+
pass
|
|
157
|
+
name = str(name)
|
|
158
|
+
# 提取目标 dtype 的字节序(保留非 native 标记,结果上还原)
|
|
159
|
+
_bo = None
|
|
160
|
+
try:
|
|
161
|
+
if isinstance(dtype, str):
|
|
162
|
+
if dtype and dtype[0] in '<>':
|
|
163
|
+
_bo = dtype[0]
|
|
164
|
+
else:
|
|
165
|
+
_dbo = getattr(dtype, 'byteorder', None)
|
|
166
|
+
if isinstance(_dbo, str) and _dbo not in ('|', '=', '@', 'n', 'native'):
|
|
167
|
+
_bo = _dbo
|
|
168
|
+
except Exception:
|
|
169
|
+
_bo = None
|
|
170
|
+
ndarray_cls, _ = _get_deps()
|
|
171
|
+
|
|
172
|
+
def _fin(res):
|
|
173
|
+
if _bo is not None and res is not None:
|
|
174
|
+
try:
|
|
175
|
+
import rsarray._dtypes as _dts_bo
|
|
176
|
+
_d = _dts_bo.DType(name)
|
|
177
|
+
res._dtype_obj = _dts_bo._clone_with_byteorder(_d, _bo)
|
|
178
|
+
except Exception:
|
|
179
|
+
pass
|
|
180
|
+
return res
|
|
181
|
+
# 数组语义:目标 dtype 相同且 copy=False → 返回自身(视图)
|
|
182
|
+
if copy is False and name == str(getattr(arr, '_dtype', '')):
|
|
183
|
+
return _fin(arr)
|
|
184
|
+
# raw-data 数组(object/complex 标量/字符串)的底层存储是占位存储而非
|
|
185
|
+
# 真实值,经构造器重建以保证转换正确
|
|
186
|
+
_raw = getattr(arr, '_raw_data', None)
|
|
187
|
+
if _raw is not None:
|
|
188
|
+
try:
|
|
189
|
+
if getattr(arr, 'ndim', 0) == 0:
|
|
190
|
+
res = ndarray_cls(_raw[0] if _raw else None, _dtype=name)
|
|
191
|
+
else:
|
|
192
|
+
res = ndarray_cls(_raw, _dtype=name)
|
|
193
|
+
if res.ndim < arr.ndim and arr.shape:
|
|
194
|
+
res = res.reshape(arr.shape)
|
|
195
|
+
return _fin(res)
|
|
196
|
+
except Exception:
|
|
197
|
+
pass
|
|
198
|
+
# Rust astype 对整数目标转换不正确(int→int 回绕错误、float→int
|
|
199
|
+
# 只重标注):统一用 Python 语义计算——NaN→0、float 向零截断、
|
|
200
|
+
# int 按目标位宽补码回绕(与 same-kind cast 一致)
|
|
201
|
+
# bool 目标:数组语义——掩码成 0/1(存原值会使 astype 往返泄漏
|
|
202
|
+
# 原值,与 tolist 的 bool 掩码自相矛盾)
|
|
203
|
+
if name == 'bool':
|
|
204
|
+
try:
|
|
205
|
+
def _recb(x):
|
|
206
|
+
out = []
|
|
207
|
+
for v in x:
|
|
208
|
+
if isinstance(v, list):
|
|
209
|
+
out.extend(_recb(v))
|
|
210
|
+
else:
|
|
211
|
+
out.append(v)
|
|
212
|
+
return out
|
|
213
|
+
_t = arr.tolist()
|
|
214
|
+
fv = _recb(_t) if isinstance(_t, list) else [_t]
|
|
215
|
+
out = [1 if v else 0 for v in fv]
|
|
216
|
+
if getattr(arr, 'ndim', 0) == 0:
|
|
217
|
+
tmp = ndarray_cls(out[0])
|
|
218
|
+
else:
|
|
219
|
+
tmp = ndarray_cls(out)
|
|
220
|
+
if tmp.ndim < arr.ndim and arr.shape:
|
|
221
|
+
tmp = tmp.reshape(arr.shape)
|
|
222
|
+
return _fin(ndarray_cls._wrap(tmp._array, _dtype=name))
|
|
223
|
+
except Exception:
|
|
224
|
+
pass
|
|
225
|
+
_INT_BITS = {'int8': 8, 'int16': 16, 'int32': 32, 'int64': 64,
|
|
226
|
+
'uint8': 8, 'uint16': 16, 'uint32': 32, 'uint64': 64}
|
|
227
|
+
if name in _INT_BITS:
|
|
228
|
+
_storage = str(getattr(arr._array, 'dtype', '') or '')
|
|
229
|
+
if _storage in ("float16", "float32", "float64") or _storage in _INT_BITS:
|
|
230
|
+
try:
|
|
231
|
+
def _rec(x):
|
|
232
|
+
out = []
|
|
233
|
+
for v in x:
|
|
234
|
+
if isinstance(v, list):
|
|
235
|
+
out.extend(_rec(v))
|
|
236
|
+
else:
|
|
237
|
+
out.append(v)
|
|
238
|
+
return out
|
|
239
|
+
_t = arr.tolist()
|
|
240
|
+
fv = _rec(_t) if isinstance(_t, list) else [_t]
|
|
241
|
+
bits = _INT_BITS[name]
|
|
242
|
+
signed = name.startswith('int') # noqa: F841
|
|
243
|
+
mask = (1 << bits) - 1
|
|
244
|
+
half = 1 << (bits - 1)
|
|
245
|
+
_signed = name.startswith('int')
|
|
246
|
+
out = []
|
|
247
|
+
for v in fv:
|
|
248
|
+
if isinstance(v, float) and v != v:
|
|
249
|
+
out.append(0) # NaN→0(未定义行为,与 array() 路径一致)
|
|
250
|
+
elif _signed:
|
|
251
|
+
iv = int(v) & mask
|
|
252
|
+
if iv >= half:
|
|
253
|
+
# 有符号越界:存 i64 补码负值(与 asarray 一致)
|
|
254
|
+
iv -= 1 << bits
|
|
255
|
+
out.append(iv)
|
|
256
|
+
else:
|
|
257
|
+
# 无符号 <2^63:存值本身(与 asarray 约定一致);符号扩展
|
|
258
|
+
# 会把 u8 255 存成 -1.0,== 比较(f64 原值)必挂。
|
|
259
|
+
# uint64 高位(≥2^63)f64 舍入会越界(2^64-5→2^64.0,
|
|
260
|
+
# 下游 _check_int_coerce 抛 OverflowError),回落补码负值
|
|
261
|
+
iv = int(v) & mask
|
|
262
|
+
if bits == 64 and iv >= half:
|
|
263
|
+
iv -= 1 << bits
|
|
264
|
+
out.append(iv)
|
|
265
|
+
if getattr(arr, 'ndim', 0) == 0:
|
|
266
|
+
tmp = ndarray_cls(out[0])
|
|
267
|
+
else:
|
|
268
|
+
tmp = ndarray_cls(out)
|
|
269
|
+
if tmp.ndim < arr.ndim and arr.shape:
|
|
270
|
+
tmp = tmp.reshape(arr.shape)
|
|
271
|
+
return _fin(ndarray_cls._wrap(tmp._array, _dtype=name))
|
|
272
|
+
except Exception:
|
|
273
|
+
pass
|
|
274
|
+
# float 目标(f64→f32/f16):真正舍入到目标精度(NEP50 语义)
|
|
275
|
+
if name in ('float32', 'float16'):
|
|
276
|
+
_storage = str(getattr(arr._array, 'dtype', '') or '')
|
|
277
|
+
if _storage in ('float64', 'float32'):
|
|
278
|
+
try:
|
|
279
|
+
import struct as _struct
|
|
280
|
+
fmt = 'f' if name == 'float32' else 'e'
|
|
281
|
+
lim = 3.4028235e38 if fmt == 'f' else 65504.0
|
|
282
|
+
|
|
283
|
+
def _rec2(x):
|
|
284
|
+
o = []
|
|
285
|
+
for v in x:
|
|
286
|
+
if isinstance(v, list):
|
|
287
|
+
o.extend(_rec2(v))
|
|
288
|
+
else:
|
|
289
|
+
o.append(v)
|
|
290
|
+
return o
|
|
291
|
+
|
|
292
|
+
def _rnd(v):
|
|
293
|
+
if isinstance(v, float) and v == v and abs(v) < lim:
|
|
294
|
+
try:
|
|
295
|
+
return _struct.unpack(fmt, _struct.pack(fmt, v))[0]
|
|
296
|
+
except Exception:
|
|
297
|
+
return v
|
|
298
|
+
return v
|
|
299
|
+
|
|
300
|
+
_t = arr.tolist()
|
|
301
|
+
fv = _rec2(_t) if isinstance(_t, list) else [_t]
|
|
302
|
+
rv = [_rnd(v) for v in fv]
|
|
303
|
+
if getattr(arr, 'ndim', 0) == 0:
|
|
304
|
+
tmp = ndarray_cls(rv[0])
|
|
305
|
+
else:
|
|
306
|
+
tmp = ndarray_cls(rv)
|
|
307
|
+
if tmp.ndim < arr.ndim and arr.shape:
|
|
308
|
+
tmp = tmp.reshape(arr.shape)
|
|
309
|
+
return _fin(ndarray_cls._wrap(tmp._array, _dtype=name))
|
|
310
|
+
except Exception:
|
|
311
|
+
pass
|
|
312
|
+
# 复数目标:用复数值列表重建(避免 Rust 复数转换缺口)
|
|
313
|
+
if name in ('complex64', 'complex128'):
|
|
314
|
+
try:
|
|
315
|
+
def _flatc(x):
|
|
316
|
+
if isinstance(x, list):
|
|
317
|
+
out = []
|
|
318
|
+
for v in x:
|
|
319
|
+
out.extend(_flatc(v))
|
|
320
|
+
return out
|
|
321
|
+
return [x]
|
|
322
|
+
_t = arr.tolist()
|
|
323
|
+
fv = [complex(v) for v in (_flatc(_t) if isinstance(_t, list) else [_t])]
|
|
324
|
+
tmp = ndarray_cls(fv)
|
|
325
|
+
if getattr(arr, 'ndim', 0) == 0:
|
|
326
|
+
tmp = tmp.reshape(())
|
|
327
|
+
elif tmp.ndim < arr.ndim and arr.shape:
|
|
328
|
+
tmp = tmp.reshape(arr.shape)
|
|
329
|
+
return ndarray_cls._wrap(tmp._array, _dtype=name)
|
|
330
|
+
except Exception:
|
|
331
|
+
pass
|
|
332
|
+
# S/U 字符串目标:Rust astype 不支持字符串存储。数组语义:
|
|
333
|
+
# 值转字符串后取最小宽度;裸 'S'/'U' 按数据推断(astype('S')→'S3'),
|
|
334
|
+
# 显式宽度('S4')直接用(np.array 自带截断)。
|
|
335
|
+
_su_kind = None
|
|
336
|
+
_su_width = None
|
|
337
|
+
if isinstance(dtype, str):
|
|
338
|
+
_core = dtype[1:] if dtype and dtype[0] in '<>|=' else dtype
|
|
339
|
+
if _core and _core[0] in 'SU':
|
|
340
|
+
_su_kind = _core[0]
|
|
341
|
+
_tail = _core[1:]
|
|
342
|
+
_su_width = builtins.int(_tail) if _tail.isdigit() else None
|
|
343
|
+
elif name in ('bytes_', 'string_'):
|
|
344
|
+
_su_kind = 'S' if name == 'bytes_' else 'U'
|
|
345
|
+
if _su_kind is not None:
|
|
346
|
+
try:
|
|
347
|
+
import rsarray as _rn_su
|
|
348
|
+
|
|
349
|
+
def _flats(x):
|
|
350
|
+
if isinstance(x, list):
|
|
351
|
+
out = []
|
|
352
|
+
for v in x:
|
|
353
|
+
out.extend(_flats(v))
|
|
354
|
+
return out
|
|
355
|
+
return [x]
|
|
356
|
+
|
|
357
|
+
_t = arr.tolist()
|
|
358
|
+
_vals = _flats(_t) if isinstance(_t, list) else [_t]
|
|
359
|
+
_strs = [str(v) for v in _vals]
|
|
360
|
+
if _su_width is None:
|
|
361
|
+
if _su_kind == 'S':
|
|
362
|
+
_w = builtins.max(
|
|
363
|
+
(len(s.encode('utf-8')) for s in _strs), default=0)
|
|
364
|
+
else:
|
|
365
|
+
_w = builtins.max((len(s) for s in _strs), default=0)
|
|
366
|
+
_su_width = _w
|
|
367
|
+
_spec = f'{_su_kind}{_su_width}'
|
|
368
|
+
if getattr(arr, 'ndim', 0) == 0:
|
|
369
|
+
# 0-d 直接标量构造:reshape(()) 会抹掉字符串宽度
|
|
370
|
+
return _fin(_rn_su.array(_strs[0], dtype=_spec))
|
|
371
|
+
_res = _rn_su.array(_strs, dtype=_spec)
|
|
372
|
+
return _fin(_res)
|
|
373
|
+
except Exception:
|
|
374
|
+
pass
|
|
375
|
+
# object 目标:Rust 无 object 存储,按 Python 值重建(数组语义:
|
|
376
|
+
# 对象原样保留)。0-d object 源(_raw_data 单元素)与数值源都覆盖。
|
|
377
|
+
if name in ('object', 'O'):
|
|
378
|
+
try:
|
|
379
|
+
def _flo(x):
|
|
380
|
+
if isinstance(x, list):
|
|
381
|
+
out = []
|
|
382
|
+
for v in x:
|
|
383
|
+
out.extend(_flo(v))
|
|
384
|
+
return out
|
|
385
|
+
return [x]
|
|
386
|
+
src = getattr(arr, '_raw_data', None)
|
|
387
|
+
if src is not None:
|
|
388
|
+
fv = list(src) if isinstance(src, (list, tuple)) else [src]
|
|
389
|
+
else:
|
|
390
|
+
_t = arr.tolist()
|
|
391
|
+
fv = _flo(_t) if isinstance(_t, list) else [_t]
|
|
392
|
+
tmp = ndarray_cls(fv, _dtype='object')
|
|
393
|
+
if getattr(arr, 'ndim', 0) == 0:
|
|
394
|
+
tmp = tmp.reshape(())
|
|
395
|
+
elif tmp.ndim < arr.ndim and arr.shape:
|
|
396
|
+
tmp = tmp.reshape(arr.shape)
|
|
397
|
+
return _fin(tmp)
|
|
398
|
+
except Exception:
|
|
399
|
+
pass
|
|
400
|
+
return _fin(_wrap_result(arr._array.astype(name), dtype=name))
|
|
401
|
+
|
|
402
|
+
@staticmethod
|
|
403
|
+
def reshape(arr, *shape, copy=None):
|
|
404
|
+
"""改变数组形状而不改变数据。"""
|
|
405
|
+
ndarray, _ = _get_deps()
|
|
406
|
+
if len(shape) == 1 and isinstance(shape[0], (tuple, list)):
|
|
407
|
+
shape = builtins.tuple(shape[0])
|
|
408
|
+
else:
|
|
409
|
+
shape = builtins.tuple(shape)
|
|
410
|
+
# 0 尺寸数组:Rust 不接受 0 维——占位 + shape override(数组语义)。
|
|
411
|
+
_sz = 1
|
|
412
|
+
for _d in shape:
|
|
413
|
+
_sz *= _d
|
|
414
|
+
if _sz == 0:
|
|
415
|
+
# 数组语义:零尺寸 reshape 保留目标形状(如 (1,0,1));
|
|
416
|
+
# Rust 拒绝零尺寸 → 经 zeros 按目标形状构造(继承元数据)。
|
|
417
|
+
import rsarray as _rn
|
|
418
|
+
_dt = getattr(arr, '_dtype', "float64")
|
|
419
|
+
try:
|
|
420
|
+
_z = _rn.zeros(shape, dtype=_dt)
|
|
421
|
+
_z._dtype_obj = getattr(arr, '_dtype_obj', None)
|
|
422
|
+
_z._str_dtype = getattr(arr, '_str_dtype', None)
|
|
423
|
+
_z._fields = getattr(arr, '_fields', None)
|
|
424
|
+
_z._raw_data = getattr(arr, '_raw_data', None)
|
|
425
|
+
try:
|
|
426
|
+
_z._rs_parent = arr
|
|
427
|
+
except Exception:
|
|
428
|
+
pass
|
|
429
|
+
return _z
|
|
430
|
+
except Exception:
|
|
431
|
+
pass
|
|
432
|
+
out = ndarray._wrap(_rn.zeros((1,)),
|
|
433
|
+
_dtype=_dt,
|
|
434
|
+
_fields=getattr(arr, '_fields', None),
|
|
435
|
+
_raw_data=getattr(arr, '_raw_data', None))
|
|
436
|
+
out._rs_shape_override = shape
|
|
437
|
+
try:
|
|
438
|
+
out._rs_parent = arr
|
|
439
|
+
except Exception:
|
|
440
|
+
pass
|
|
441
|
+
return out
|
|
442
|
+
try:
|
|
443
|
+
result = arr._array.reshape(shape)
|
|
444
|
+
except ValueError:
|
|
445
|
+
result = arr._array.flatten().reshape(shape)
|
|
446
|
+
out = ndarray._wrap(result, _dtype=getattr(arr, '_dtype', "float64"), _fields=getattr(arr, '_fields', None), _raw_data=getattr(arr, '_raw_data', None))
|
|
447
|
+
# 继承结构化 DType(缺失会导致字段访问/属性查找失效)
|
|
448
|
+
out._dtype_obj = getattr(arr, '_dtype_obj', None)
|
|
449
|
+
# 字符串数组:宽度存 _str_dtype(_dtype 是 'string_' 占位),缺失时
|
|
450
|
+
# 结果退化成裸 |S0(如 str 数组 reshape 后 dtype 失真)
|
|
451
|
+
out._str_dtype = getattr(arr, '_str_dtype', None)
|
|
452
|
+
try:
|
|
453
|
+
out._rs_parent = arr
|
|
454
|
+
except Exception:
|
|
455
|
+
pass
|
|
456
|
+
# 子类保持(数组语义:recarray.reshape → recarray;其余子类
|
|
457
|
+
# 如 matrix/chararray 有各自语义,不在此统一保持)
|
|
458
|
+
_src_cls = builtins.type(arr)
|
|
459
|
+
if _src_cls is not ndarray:
|
|
460
|
+
try:
|
|
461
|
+
import rsarray as _rn_rs
|
|
462
|
+
_rec_cls = _rn_rs.recarray
|
|
463
|
+
if issubclass(_src_cls, _rec_cls):
|
|
464
|
+
out.__class__ = _src_cls
|
|
465
|
+
except Exception:
|
|
466
|
+
pass
|
|
467
|
+
if copy is True:
|
|
468
|
+
out = out.copy()
|
|
469
|
+
try:
|
|
470
|
+
out._rs_parent = None
|
|
471
|
+
except Exception:
|
|
472
|
+
pass
|
|
473
|
+
return out
|
|
474
|
+
|
|
475
|
+
@staticmethod
|
|
476
|
+
def resize(arr, new_shape):
|
|
477
|
+
"""改变数组形状和大小。"""
|
|
478
|
+
if isinstance(new_shape, int):
|
|
479
|
+
new_shape = (new_shape,)
|
|
480
|
+
elif isinstance(new_shape, list):
|
|
481
|
+
new_shape = tuple(new_shape)
|
|
482
|
+
# 逻辑空数组:Rust 层对空数据 resize 会死循环(copy_len 恒 0);
|
|
483
|
+
# 数组语义:扩大时新元素以 0 填充 → Python 层直接重建。
|
|
484
|
+
if arr.size == 0:
|
|
485
|
+
try:
|
|
486
|
+
arr._array = _core.zeros(list(new_shape))
|
|
487
|
+
except Exception:
|
|
488
|
+
pass
|
|
489
|
+
_ov = getattr(arr, '_rs_shape_override', None)
|
|
490
|
+
if _ov is not None:
|
|
491
|
+
arr._rs_shape_override = None
|
|
492
|
+
return
|
|
493
|
+
arr._array.resize(new_shape)
|
|
494
|
+
|
|
495
|
+
@staticmethod
|
|
496
|
+
def ravel(arr, order='C'):
|
|
497
|
+
"""将数组展平为一维。"""
|
|
498
|
+
if order == 'A' or order == 'K':
|
|
499
|
+
order = 'C'
|
|
500
|
+
return NdArrayMethods.flatten(arr, order)
|
|
501
|
+
|
|
502
|
+
@staticmethod
|
|
503
|
+
def flatten(arr, order='C'):
|
|
504
|
+
"""展平数组为一维。"""
|
|
505
|
+
dtype = getattr(arr, '_dtype', "float64")
|
|
506
|
+
result = _core.flatten_full(arr._array, order)
|
|
507
|
+
return _wrap_result(result, dtype)
|
|
508
|
+
|
|
509
|
+
@staticmethod
|
|
510
|
+
def transpose(arr, *axes):
|
|
511
|
+
"""转置数组(视图:标记 base 供 flags.OWNDATA 判定)。"""
|
|
512
|
+
ndarray, _ = _get_deps()
|
|
513
|
+
dtype = getattr(arr, '_dtype', "float64")
|
|
514
|
+
fields = getattr(arr, '_fields', None)
|
|
515
|
+
raw = getattr(arr, '_raw_data', None)
|
|
516
|
+
if len(axes) == 1:
|
|
517
|
+
a0 = axes[0]
|
|
518
|
+
if isinstance(a0, (tuple, list)):
|
|
519
|
+
axes = a0
|
|
520
|
+
elif hasattr(a0, 'ndim') and getattr(a0, 'ndim', 1) == 1:
|
|
521
|
+
# 接受一维数组作为轴置换
|
|
522
|
+
axes = [int(x) for x in a0.reshape((-1,)).tolist()]
|
|
523
|
+
if len(axes) == 0:
|
|
524
|
+
result = arr._array.T
|
|
525
|
+
else:
|
|
526
|
+
_ax = [int(x) for x in axes]
|
|
527
|
+
_nd = arr.ndim
|
|
528
|
+
if len(_ax) != _nd:
|
|
529
|
+
# 数组语义:轴数必须与数组维度一致
|
|
530
|
+
raise ValueError("axes don't match array")
|
|
531
|
+
_norm = [x + _nd if x < 0 else x for x in _ax]
|
|
532
|
+
if len(set(_norm)) != len(_norm):
|
|
533
|
+
# 数组语义:轴不可重复
|
|
534
|
+
raise ValueError("repeated axis in transpose")
|
|
535
|
+
for x in _norm:
|
|
536
|
+
if x < 0 or x >= _nd:
|
|
537
|
+
raise ValueError(
|
|
538
|
+
f"axis {x} is out of bounds for array of "
|
|
539
|
+
f"dimension {_nd}")
|
|
540
|
+
result = _core.transpose_axes(arr._array, _norm)
|
|
541
|
+
out = ndarray._wrap(result, _dtype=dtype, _fields=fields, _raw_data=raw)
|
|
542
|
+
if raw is None:
|
|
543
|
+
out.base = arr
|
|
544
|
+
return out
|
|
545
|
+
|
|
546
|
+
@staticmethod
|
|
547
|
+
def swapaxes(arr, axis1, axis2):
|
|
548
|
+
"""交换两个轴的位置(视图:标记 base 供 flags.OWNDATA 判定)。"""
|
|
549
|
+
ndarray, _ = _get_deps()
|
|
550
|
+
dtype = getattr(arr, '_dtype', "float64")
|
|
551
|
+
fields = getattr(arr, '_fields', None)
|
|
552
|
+
raw_data = getattr(arr, '_raw_data', None)
|
|
553
|
+
# Rust 层只接受非负轴:负轴先归一化(数组语义)
|
|
554
|
+
ndim = len(arr.shape)
|
|
555
|
+
if axis1 < 0:
|
|
556
|
+
axis1 += ndim
|
|
557
|
+
if axis2 < 0:
|
|
558
|
+
axis2 += ndim
|
|
559
|
+
result = _core.swapaxes(arr._array, axis1, axis2)
|
|
560
|
+
out = ndarray._wrap(result, _dtype=dtype, _fields=fields, _raw_data=raw_data)
|
|
561
|
+
if raw_data is None:
|
|
562
|
+
out.base = arr
|
|
563
|
+
return out
|
|
564
|
+
|
|
565
|
+
@staticmethod
|
|
566
|
+
def squeeze(arr, axis=None):
|
|
567
|
+
"""移除长度为1的轴(视图:标记 base 供 flags.OWNDATA 判定)。"""
|
|
568
|
+
result = arr._array.squeeze()
|
|
569
|
+
if getattr(arr, '_raw_data', None) is not None:
|
|
570
|
+
return _wrap_result(result)
|
|
571
|
+
out = _wrap_result(result)
|
|
572
|
+
if hasattr(out, 'base'):
|
|
573
|
+
out.base = arr
|
|
574
|
+
return out
|
|
575
|
+
|
|
576
|
+
@staticmethod
|
|
577
|
+
def _reduce_axis_check(arr, axis):
|
|
578
|
+
"""归约 axis 校验(数组语义:越界 → AxisError;0-d 允许 axis=0)。
|
|
579
|
+
|
|
580
|
+
越界 axis 直达 Rust 会 panic abort 整个进程;0-d + axis=0
|
|
581
|
+
归一化为 None(全归约)——Rust 对 0-d 的 axis=0 也会 panic。
|
|
582
|
+
"""
|
|
583
|
+
if axis is None:
|
|
584
|
+
return None
|
|
585
|
+
_dim = int(arr.ndim)
|
|
586
|
+
_ax = axis + _dim if axis < 0 else axis
|
|
587
|
+
if _dim == 0:
|
|
588
|
+
if _ax != 0:
|
|
589
|
+
from rsarray.exceptions import AxisError
|
|
590
|
+
raise AxisError(
|
|
591
|
+
f"axis {axis} is out of bounds for array of "
|
|
592
|
+
f"dimension {_dim}")
|
|
593
|
+
return None
|
|
594
|
+
if _ax < 0 or _ax >= _dim:
|
|
595
|
+
from rsarray.exceptions import AxisError
|
|
596
|
+
raise AxisError(
|
|
597
|
+
f"axis {axis} is out of bounds for array of "
|
|
598
|
+
f"dimension {_dim}")
|
|
599
|
+
return axis
|
|
600
|
+
|
|
601
|
+
@staticmethod
|
|
602
|
+
def max(arr, axis=None, out=None, keepdims=False):
|
|
603
|
+
"""返回数组的最大值。"""
|
|
604
|
+
_ = out
|
|
605
|
+
axis = NdArrayMethods._reduce_axis_check(arr, axis)
|
|
606
|
+
result = arr._array.max(axis, keepdims)
|
|
607
|
+
if axis is None and not keepdims and hasattr(result, 'tolist'):
|
|
608
|
+
return result.tolist()
|
|
609
|
+
return _wrap_result(result)
|
|
610
|
+
|
|
611
|
+
@staticmethod
|
|
612
|
+
def min(arr, axis=None, out=None, keepdims=False):
|
|
613
|
+
"""返回数组的最小值。"""
|
|
614
|
+
_ = out
|
|
615
|
+
axis = NdArrayMethods._reduce_axis_check(arr, axis)
|
|
616
|
+
result = arr._array.min(axis, keepdims)
|
|
617
|
+
if axis is None and not keepdims and hasattr(result, 'tolist'):
|
|
618
|
+
return result.tolist()
|
|
619
|
+
return _wrap_result(result)
|
|
620
|
+
|
|
621
|
+
@staticmethod
|
|
622
|
+
def mean(arr, axis=None, dtype=None, out=None, keepdims=False):
|
|
623
|
+
"""计算数组的平均值。"""
|
|
624
|
+
_ = dtype, out
|
|
625
|
+
axis = NdArrayMethods._reduce_axis_check(arr, axis)
|
|
626
|
+
result = arr._array.mean(axis, keepdims)
|
|
627
|
+
if axis is None and not keepdims and hasattr(result, 'tolist'):
|
|
628
|
+
return result.tolist()
|
|
629
|
+
return _wrap_result(result)
|
|
630
|
+
|
|
631
|
+
@staticmethod
|
|
632
|
+
def std(arr, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
|
|
633
|
+
"""计算数组的标准差。"""
|
|
634
|
+
_ = dtype, out
|
|
635
|
+
axis = NdArrayMethods._reduce_axis_check(arr, axis)
|
|
636
|
+
result = arr._array.std(axis, ddof, keepdims)
|
|
637
|
+
if axis is None and not keepdims and hasattr(result, 'tolist'):
|
|
638
|
+
return result.tolist()
|
|
639
|
+
return _wrap_result(result)
|
|
640
|
+
|
|
641
|
+
@staticmethod
|
|
642
|
+
def var(arr, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
|
|
643
|
+
"""计算数组的方差。"""
|
|
644
|
+
_ = dtype, out
|
|
645
|
+
axis = NdArrayMethods._reduce_axis_check(arr, axis)
|
|
646
|
+
result = arr._array.var(axis, ddof, keepdims)
|
|
647
|
+
if axis is None and not keepdims and hasattr(result, 'tolist'):
|
|
648
|
+
return result.tolist()
|
|
649
|
+
return _wrap_result(result)
|
|
650
|
+
|
|
651
|
+
@staticmethod
|
|
652
|
+
def sum(arr, axis=None, dtype=None, out=None, keepdims=False):
|
|
653
|
+
"""计算数组元素的和。"""
|
|
654
|
+
_ = dtype, out
|
|
655
|
+
# 0-d 短路:Rust 归约对 0-d 输入会 abort;返回保持原 dtype 的 0-d
|
|
656
|
+
if not tuple(getattr(arr._array, 'shape', ())):
|
|
657
|
+
nd = _nd()
|
|
658
|
+
return nd(arr._array, _dtype=getattr(arr, '_dtype', 'float64'))
|
|
659
|
+
# complex 短路:Rust 归约对 complex 会 abort,纯 Python 求和
|
|
660
|
+
_k = getattr(getattr(arr, '_dtype_obj', None), 'kind', None)
|
|
661
|
+
if _k is None:
|
|
662
|
+
_dn = str(getattr(arr, '_dtype', ''))
|
|
663
|
+
_k = _dn[0] if _dn else '?'
|
|
664
|
+
if _k == 'c':
|
|
665
|
+
axis = NdArrayMethods._reduce_axis_check(arr, axis)
|
|
666
|
+
_vals = arr.tolist()
|
|
667
|
+
|
|
668
|
+
def _cs(x):
|
|
669
|
+
if isinstance(x, (list, tuple)):
|
|
670
|
+
return _cs(x[0]) + sum(_cs(y) for y in x[1:])
|
|
671
|
+
return x
|
|
672
|
+
|
|
673
|
+
if axis is None:
|
|
674
|
+
return _cs(_vals)
|
|
675
|
+
# axis 归约:展平为 (lead × size_ax × trail),对每个 (lead, trail)
|
|
676
|
+
# 位置求和,结果形状为去掉 axis 维(keepdims 时置 1)
|
|
677
|
+
shape = arr.shape
|
|
678
|
+
size_ax = shape[axis]
|
|
679
|
+
lead = 1
|
|
680
|
+
for d in shape[:axis]:
|
|
681
|
+
lead *= d
|
|
682
|
+
trail = 1
|
|
683
|
+
for d in shape[axis + 1:]:
|
|
684
|
+
trail *= d
|
|
685
|
+
|
|
686
|
+
def _flat(x):
|
|
687
|
+
out = []
|
|
688
|
+
for w in (x if isinstance(x, (list, tuple)) else [x]):
|
|
689
|
+
if isinstance(w, (list, tuple)):
|
|
690
|
+
out.extend(_flat(w))
|
|
691
|
+
else:
|
|
692
|
+
out.append(w)
|
|
693
|
+
return out
|
|
694
|
+
|
|
695
|
+
_flatv = _flat(_vals)
|
|
696
|
+
res_flat = []
|
|
697
|
+
for li in range(lead):
|
|
698
|
+
for ti in range(trail):
|
|
699
|
+
s = 0j
|
|
700
|
+
for ai in range(size_ax):
|
|
701
|
+
s += _flatv[(li * size_ax + ai) * trail + ti]
|
|
702
|
+
res_flat.append(s)
|
|
703
|
+
out_shape = list(shape[:axis]) + list(shape[axis + 1:])
|
|
704
|
+
if keepdims:
|
|
705
|
+
out_shape = list(shape[:axis]) + [1] + list(shape[axis + 1:])
|
|
706
|
+
nd = _nd()
|
|
707
|
+
if not res_flat:
|
|
708
|
+
return nd([]).reshape(tuple(out_shape))
|
|
709
|
+
return nd(res_flat).reshape(tuple(out_shape)).astype(
|
|
710
|
+
getattr(arr, '_dtype', 'complex128'))
|
|
711
|
+
axis = NdArrayMethods._reduce_axis_check(arr, axis)
|
|
712
|
+
try:
|
|
713
|
+
result = arr._array.sum(axis, keepdims)
|
|
714
|
+
except ValueError as _e:
|
|
715
|
+
if 'ncompatible' not in str(_e) and 'ayout' not in str(_e):
|
|
716
|
+
raise
|
|
717
|
+
# 非连续/负步长布局:Rust 归约不支持 → 纯 Python 轴归约
|
|
718
|
+
# (与上方复数回退同构)
|
|
719
|
+
ndarray_cls, _ = _get_deps()
|
|
720
|
+
_vals = arr.tolist()
|
|
721
|
+
if axis is None:
|
|
722
|
+
s = 0.0
|
|
723
|
+
|
|
724
|
+
def _csr(x):
|
|
725
|
+
if isinstance(x, (list, tuple)):
|
|
726
|
+
return sum(_csr(y) for y in x)
|
|
727
|
+
return x
|
|
728
|
+
|
|
729
|
+
return _csr(_vals)
|
|
730
|
+
shape = arr.shape
|
|
731
|
+
if axis < 0:
|
|
732
|
+
axis = axis + len(shape)
|
|
733
|
+
size_ax = shape[axis]
|
|
734
|
+
lead = 1
|
|
735
|
+
for d in shape[:axis]:
|
|
736
|
+
lead *= d
|
|
737
|
+
trail = 1
|
|
738
|
+
for d in shape[axis + 1:]:
|
|
739
|
+
trail *= d
|
|
740
|
+
|
|
741
|
+
def _flat(x):
|
|
742
|
+
out = []
|
|
743
|
+
for w in (x if isinstance(x, (list, tuple)) else [x]):
|
|
744
|
+
if isinstance(w, (list, tuple)):
|
|
745
|
+
out.extend(_flat(w))
|
|
746
|
+
else:
|
|
747
|
+
out.append(w)
|
|
748
|
+
return out
|
|
749
|
+
|
|
750
|
+
_flatv = _flat(_vals)
|
|
751
|
+
res_flat = []
|
|
752
|
+
for li in range(lead):
|
|
753
|
+
for ti in range(trail):
|
|
754
|
+
s = 0
|
|
755
|
+
for ai in range(size_ax):
|
|
756
|
+
s += _flatv[(li * size_ax + ai) * trail + ti]
|
|
757
|
+
res_flat.append(s)
|
|
758
|
+
out_shape = list(shape[:axis]) + list(shape[axis + 1:])
|
|
759
|
+
if keepdims:
|
|
760
|
+
out_shape = list(shape[:axis]) + [1] + \
|
|
761
|
+
list(shape[axis + 1:])
|
|
762
|
+
if not res_flat:
|
|
763
|
+
return ndarray_cls([]).reshape(tuple(out_shape))
|
|
764
|
+
res = ndarray_cls(res_flat).reshape(tuple(out_shape))
|
|
765
|
+
_dt = getattr(arr, '_dtype', '')
|
|
766
|
+
if _dt in ('float32', 'float64'):
|
|
767
|
+
res = res.astype(_dt)
|
|
768
|
+
return res
|
|
769
|
+
if axis is None and not keepdims and hasattr(result, 'tolist'):
|
|
770
|
+
return result.tolist()
|
|
771
|
+
return _wrap_result(result)
|
|
772
|
+
|
|
773
|
+
@staticmethod
|
|
774
|
+
def prod(arr, axis=None, dtype=None, out=None, keepdims=False):
|
|
775
|
+
"""计算数组元素的乘积。"""
|
|
776
|
+
_ = dtype, out
|
|
777
|
+
# 0-d 短路:Rust 归约对 0-d 输入会 abort;返回保持原 dtype 的 0-d
|
|
778
|
+
if not tuple(getattr(arr._array, 'shape', ())):
|
|
779
|
+
nd = _nd()
|
|
780
|
+
return nd(arr._array, _dtype=getattr(arr, '_dtype', 'float64'))
|
|
781
|
+
axis = NdArrayMethods._reduce_axis_check(arr, axis)
|
|
782
|
+
result = arr._array.prod(axis, keepdims)
|
|
783
|
+
if axis is None and not keepdims and hasattr(result, 'tolist'):
|
|
784
|
+
return result.tolist()
|
|
785
|
+
return _wrap_result(result)
|
|
786
|
+
|
|
787
|
+
@staticmethod
|
|
788
|
+
def cumsum(arr, axis=None):
|
|
789
|
+
"""计算累积和。"""
|
|
790
|
+
axis = NdArrayMethods._reduce_axis_check(arr, axis)
|
|
791
|
+
result = arr._array.cumsum(axis)
|
|
792
|
+
return _wrap_result(result)
|
|
793
|
+
|
|
794
|
+
@staticmethod
|
|
795
|
+
def cumprod(arr, axis=None):
|
|
796
|
+
"""计算累积乘积。"""
|
|
797
|
+
axis = NdArrayMethods._reduce_axis_check(arr, axis)
|
|
798
|
+
result = arr._array.cumprod(axis)
|
|
799
|
+
return _wrap_result(result)
|
|
800
|
+
|
|
801
|
+
@staticmethod
|
|
802
|
+
def argmax(arr, axis=None):
|
|
803
|
+
"""返回最大值的索引(全归约返回 intp 标量,数组语义)。"""
|
|
804
|
+
axis = NdArrayMethods._reduce_axis_check(arr, axis)
|
|
805
|
+
result = _wrap_result(_core.argmax_axis(arr._array, axis))
|
|
806
|
+
if result.ndim == 0:
|
|
807
|
+
import rsarray as _rsn
|
|
808
|
+
return _rsn.int64(result.item())
|
|
809
|
+
return result
|
|
810
|
+
|
|
811
|
+
@staticmethod
|
|
812
|
+
def argmin(arr, axis=None):
|
|
813
|
+
"""返回最小值的索引。"""
|
|
814
|
+
axis = NdArrayMethods._reduce_axis_check(arr, axis)
|
|
815
|
+
result = _wrap_result(_core.argmin_axis(arr._array, axis))
|
|
816
|
+
if isinstance(result, int):
|
|
817
|
+
return result
|
|
818
|
+
if hasattr(result, 'ndim') and result.ndim == 0:
|
|
819
|
+
return int(result.item())
|
|
820
|
+
return result
|
|
821
|
+
|
|
822
|
+
@staticmethod
|
|
823
|
+
def argsort(arr, axis=-1):
|
|
824
|
+
"""返回排序后的索引。"""
|
|
825
|
+
result = arr._array.argsort(axis)
|
|
826
|
+
return _wrap_result(result)
|
|
827
|
+
|
|
828
|
+
@staticmethod
|
|
829
|
+
def sort(arr, axis=-1):
|
|
830
|
+
"""原地排序数组。"""
|
|
831
|
+
result = arr._array.sort(axis)
|
|
832
|
+
if hasattr(result, 'shape') and result.shape == arr.shape:
|
|
833
|
+
arr._array = result
|
|
834
|
+
else:
|
|
835
|
+
arr._array.data = result.data
|
|
836
|
+
|
|
837
|
+
@staticmethod
|
|
838
|
+
def diagonal(arr, offset=0, axis1=0, axis2=1):
|
|
839
|
+
"""返回数组的对角线元素。"""
|
|
840
|
+
result = arr._array.diagonal(offset, axis1, axis2)
|
|
841
|
+
return _wrap_result(result)
|
|
842
|
+
|
|
843
|
+
@staticmethod
|
|
844
|
+
def trace(arr, offset=0, axis1=0, axis2=1):
|
|
845
|
+
"""计算数组的迹(对角线元素之和)。"""
|
|
846
|
+
return arr._array.trace(offset, axis1, axis2)
|
|
847
|
+
|
|
848
|
+
@staticmethod
|
|
849
|
+
def fill(arr, value):
|
|
850
|
+
"""用指定值填充数组。"""
|
|
851
|
+
kind = getattr(getattr(arr, 'dtype', None), 'kind', None)
|
|
852
|
+
if kind in ('S', 'U'):
|
|
853
|
+
# Rust 层 fill 只收数值;字符串 dtype 走 setitem 强转
|
|
854
|
+
if arr.ndim == 0:
|
|
855
|
+
arr[()] = value
|
|
856
|
+
else:
|
|
857
|
+
for _i in range(int(arr.size)):
|
|
858
|
+
arr[_i] = value
|
|
859
|
+
return
|
|
860
|
+
arr._array.fill(value)
|
|
861
|
+
|
|
862
|
+
@staticmethod
|
|
863
|
+
def item(arr, *args):
|
|
864
|
+
"""获取数组的单个元素。"""
|
|
865
|
+
_cpx_i = getattr(arr, '_complex_data', None)
|
|
866
|
+
if _cpx_i is not None:
|
|
867
|
+
return _cpx_i[0] if _cpx_i else 0j
|
|
868
|
+
# item 语义:item(0, 0) 与 item((0, 0)) 等价;越界索引抛
|
|
869
|
+
# IndexError(Python 层预检——Rust item 只收扁平 int,传 tuple 会
|
|
870
|
+
# TypeError 而非 数组的 IndexError)。
|
|
871
|
+
if len(args) == 1 and isinstance(args[0], (tuple, list)):
|
|
872
|
+
idx = tuple(int(i) for i in args[0])
|
|
873
|
+
else:
|
|
874
|
+
idx = tuple(int(i) for i in args)
|
|
875
|
+
shp = tuple(arr.shape)
|
|
876
|
+
if len(idx) > len(shp):
|
|
877
|
+
raise IndexError(
|
|
878
|
+
f"too many indices for array: array is {len(shp)}-dimensional, "
|
|
879
|
+
f"but {len(idx)} were indexed")
|
|
880
|
+
for _ai, (_i, _d) in enumerate(zip(idx, shp)):
|
|
881
|
+
if _d == 0 or _i < -_d or _i >= _d:
|
|
882
|
+
raise IndexError(
|
|
883
|
+
f"index {_i} is out of bounds for axis {_ai} with size {_d}")
|
|
884
|
+
# object 数组:返回 _raw_data 存储的 Python 引用(保持对象身份;
|
|
885
|
+
# Rust 侧 f64 占位值对 object 无意义)
|
|
886
|
+
if str(getattr(arr, '_dtype', '')) == 'object':
|
|
887
|
+
_raw_i = getattr(arr, '_raw_data', None)
|
|
888
|
+
if _raw_i is not None:
|
|
889
|
+
if not idx:
|
|
890
|
+
if int(arr.size) != 1:
|
|
891
|
+
raise ValueError(
|
|
892
|
+
"can only convert an array of size 1 "
|
|
893
|
+
"to a Python scalar")
|
|
894
|
+
cur = _raw_i
|
|
895
|
+
while isinstance(cur, list) and len(cur) == 1:
|
|
896
|
+
cur = cur[0]
|
|
897
|
+
return cur
|
|
898
|
+
if len(idx) == 1 and isinstance(_raw_i, list):
|
|
899
|
+
_i0 = idx[0]
|
|
900
|
+
if _i0 < 0:
|
|
901
|
+
_i0 += shp[0]
|
|
902
|
+
if 0 <= _i0 < len(_raw_i) \
|
|
903
|
+
and not isinstance(_raw_i[_i0], list):
|
|
904
|
+
return _raw_i[_i0]
|
|
905
|
+
if len(idx) == 1:
|
|
906
|
+
v = arr._array.item(idx[0])
|
|
907
|
+
elif idx:
|
|
908
|
+
_flat = 0
|
|
909
|
+
for _i, _d in zip(idx, shp):
|
|
910
|
+
_flat = _flat * _d + _i
|
|
911
|
+
v = arr._array.item(_flat)
|
|
912
|
+
else:
|
|
913
|
+
v = arr._array.item()
|
|
914
|
+
# 无符号高位值以 i64 补码负值存储:还原无符号值
|
|
915
|
+
_u_bits = {'uint8': 8, 'uint16': 16, 'uint32': 32,
|
|
916
|
+
'uint64': 64}.get(str(getattr(arr, '_dtype', '')))
|
|
917
|
+
if _u_bits and isinstance(v, (int, float)) and v < 0:
|
|
918
|
+
v = int(v) & ((1 << _u_bits) - 1)
|
|
919
|
+
return v
|
|
920
|
+
|
|
921
|
+
@staticmethod
|
|
922
|
+
def tolist(arr):
|
|
923
|
+
"""将数组转换为 Python 列表。"""
|
|
924
|
+
# 超大广播 override 视图:物化会 OOM abort 进程 → MemoryError
|
|
925
|
+
_ovr_t = getattr(arr, '_rs_shape_override', None)
|
|
926
|
+
if _ovr_t is not None:
|
|
927
|
+
_n_t = 1
|
|
928
|
+
for _v_t in _ovr_t:
|
|
929
|
+
_n_t *= int(_v_t)
|
|
930
|
+
if _n_t > 2**40:
|
|
931
|
+
raise MemoryError(
|
|
932
|
+
"rsarray: cannot materialize huge broadcast array via tolist()")
|
|
933
|
+
# _complex_data(Python 级复数)优先:_array 只有实部
|
|
934
|
+
_cpx_t = getattr(arr, '_complex_data', None)
|
|
935
|
+
if _cpx_t is not None:
|
|
936
|
+
shp = getattr(arr, 'shape', None) or ()
|
|
937
|
+
if not shp:
|
|
938
|
+
return _cpx_t[0] if _cpx_t else 0j
|
|
939
|
+
|
|
940
|
+
def _nest_c(vals, dims):
|
|
941
|
+
if len(dims) == 1:
|
|
942
|
+
return list(vals)
|
|
943
|
+
n = dims[0] or 0
|
|
944
|
+
step = (len(vals) // n) if n else 0
|
|
945
|
+
return [_nest_c(vals[i * step:(i + 1) * step], dims[1:])
|
|
946
|
+
for i in range(n)]
|
|
947
|
+
return _nest_c(list(_cpx_t), shp)
|
|
948
|
+
v = arr._array.tolist()
|
|
949
|
+
# 无符号高位值以 i64 补码负值存储:还原无符号值
|
|
950
|
+
_u_bits = {'uint8': 8, 'uint16': 16, 'uint32': 32,
|
|
951
|
+
'uint64': 64}.get(str(getattr(arr, '_dtype', '')))
|
|
952
|
+
if _u_bits:
|
|
953
|
+
_mask = (1 << _u_bits) - 1
|
|
954
|
+
|
|
955
|
+
def _mk(x):
|
|
956
|
+
if isinstance(x, list):
|
|
957
|
+
return [_mk(y) for y in x]
|
|
958
|
+
if isinstance(x, (int, float)) and not isinstance(x, bool) \
|
|
959
|
+
and x < 0:
|
|
960
|
+
return int(x) & _mask
|
|
961
|
+
return x
|
|
962
|
+
return _mk(v)
|
|
963
|
+
return v
|
|
964
|
+
|
|
965
|
+
@staticmethod
|
|
966
|
+
def take(arr, indices, axis=None, mode='raise', out=None):
|
|
967
|
+
"""根据索引获取元素(保留输入数组 dtype;兼容 mode 语义)。
|
|
968
|
+
|
|
969
|
+
越界索引抛 IndexError(直达 Rust 会 panic abort 整个进程)。
|
|
970
|
+
全部索引合法时走 Rust 快路径,否则 Python 回退(含 clip/wrap)。
|
|
971
|
+
"""
|
|
972
|
+
ndarray, _ensure = _get_deps()
|
|
973
|
+
dt = getattr(arr, '_dtype', 'float64')
|
|
974
|
+
|
|
975
|
+
def _norm(i, size, ax):
|
|
976
|
+
if size == 0:
|
|
977
|
+
raise IndexError(
|
|
978
|
+
f"index {i} is out of bounds for axis {ax} "
|
|
979
|
+
f"with size {size}")
|
|
980
|
+
if mode == 'clip':
|
|
981
|
+
if i > size - 1:
|
|
982
|
+
i = size - 1
|
|
983
|
+
if i < -size:
|
|
984
|
+
i = -size
|
|
985
|
+
elif mode != 'wrap':
|
|
986
|
+
if i < -size or i >= size:
|
|
987
|
+
raise IndexError(
|
|
988
|
+
f"index {i} is out of bounds for axis {ax} "
|
|
989
|
+
f"with size {size}")
|
|
990
|
+
return i % size
|
|
991
|
+
|
|
992
|
+
if isinstance(indices, int) and not isinstance(indices, bool):
|
|
993
|
+
# 标量索引:Python 混合索引实现(Rust take 只接 ndarray 索引,
|
|
994
|
+
# 裸 int 会 TypeError);数组语义:axis 维被移除
|
|
995
|
+
ndim = arr.ndim
|
|
996
|
+
if axis is None:
|
|
997
|
+
if ndim == 1:
|
|
998
|
+
ax = 0
|
|
999
|
+
else:
|
|
1000
|
+
size = 1
|
|
1001
|
+
for d in arr.shape:
|
|
1002
|
+
size *= d
|
|
1003
|
+
i = _norm(indices, size, 0)
|
|
1004
|
+
flat = arr.ravel().tolist()
|
|
1005
|
+
v = flat[i]
|
|
1006
|
+
return ndarray(v, _dtype=dt)
|
|
1007
|
+
else:
|
|
1008
|
+
ax = axis % ndim
|
|
1009
|
+
i = _norm(indices, arr.shape[ax], axis)
|
|
1010
|
+
idx = [slice(None)] * ndim
|
|
1011
|
+
idx[ax] = i
|
|
1012
|
+
return arr[tuple(idx)]
|
|
1013
|
+
idxs = indices.tolist() if hasattr(indices, 'tolist') else list(indices)
|
|
1014
|
+
if axis is None:
|
|
1015
|
+
n = 1
|
|
1016
|
+
for d in arr.shape:
|
|
1017
|
+
n *= d
|
|
1018
|
+
# indices 可以是多维:结果与 indices 同形状(数组语义:沿展平取)。
|
|
1019
|
+
_idx_shape = getattr(indices, 'shape', None)
|
|
1020
|
+
_is_nd_idx = _idx_shape is not None and len(tuple(_idx_shape)) > 1
|
|
1021
|
+
_flat_idxs = []
|
|
1022
|
+
|
|
1023
|
+
def _rec_idx(x):
|
|
1024
|
+
if isinstance(x, (list, tuple)):
|
|
1025
|
+
for w in x:
|
|
1026
|
+
_rec_idx(w)
|
|
1027
|
+
else:
|
|
1028
|
+
_flat_idxs.append(x)
|
|
1029
|
+
|
|
1030
|
+
_rec_idx(idxs)
|
|
1031
|
+
norm = [_norm(i, n, 0) for i in _flat_idxs]
|
|
1032
|
+
if (mode == 'raise' and all(0 <= i < n for i in _flat_idxs)
|
|
1033
|
+
and not _is_nd_idx):
|
|
1034
|
+
result = arr._array.take(_ensure(list(_flat_idxs)), None)
|
|
1035
|
+
return _wrap_result(result, dt)
|
|
1036
|
+
flat = arr.ravel().tolist()
|
|
1037
|
+
if not isinstance(flat, list):
|
|
1038
|
+
flat = [flat]
|
|
1039
|
+
res = [flat[i] for i in norm]
|
|
1040
|
+
if _is_nd_idx:
|
|
1041
|
+
def _shp(flatv, sh):
|
|
1042
|
+
if len(sh) == 1:
|
|
1043
|
+
return list(flatv)
|
|
1044
|
+
_sub = 1
|
|
1045
|
+
for _x in sh[1:]:
|
|
1046
|
+
_sub *= _x
|
|
1047
|
+
return [_shp(flatv[_i * _sub:(_i + 1) * _sub], sh[1:])
|
|
1048
|
+
for _i in range(sh[0])]
|
|
1049
|
+
return ndarray(_shp(res, tuple(_idx_shape)), _dtype=dt)
|
|
1050
|
+
return ndarray(res, _dtype=dt)
|
|
1051
|
+
ax = axis % arr.ndim
|
|
1052
|
+
size = arr.shape[ax]
|
|
1053
|
+
norm = [_norm(i, size, axis) for i in idxs]
|
|
1054
|
+
if mode == 'raise' and all(0 <= i < size for i in idxs):
|
|
1055
|
+
result = arr._array.take(_ensure(list(idxs)), axis)
|
|
1056
|
+
return _wrap_result(result, dt)
|
|
1057
|
+
other = tuple(arr.shape[i] for i in range(arr.ndim) if i != ax)
|
|
1058
|
+
rows = (arr.moveaxis(ax, -1).reshape((-1, size)).tolist()
|
|
1059
|
+
if size > 0 else [])
|
|
1060
|
+
out_rows = [[row[i] for i in norm] for row in rows]
|
|
1061
|
+
return ndarray(out_rows, _dtype=dt).reshape(other + (len(idxs),))
|
|
1062
|
+
|
|
1063
|
+
@staticmethod
|
|
1064
|
+
def put(arr, indices, values, mode='raise'):
|
|
1065
|
+
"""将值放入数组的指定位置(兼容 mode 语义)。
|
|
1066
|
+
|
|
1067
|
+
空 values 为 no-op;越界索引抛 IndexError(避免 Rust panic abort)。
|
|
1068
|
+
"""
|
|
1069
|
+
ndarray, _ensure = _get_deps()
|
|
1070
|
+
n = 1
|
|
1071
|
+
for d in arr.shape:
|
|
1072
|
+
n *= d
|
|
1073
|
+
# indices 可为标量 int / ndarray 标量 / 数组 / list(put 语义)
|
|
1074
|
+
if hasattr(indices, 'tolist'):
|
|
1075
|
+
_t = indices.tolist()
|
|
1076
|
+
if isinstance(_t, (bool, int, float)):
|
|
1077
|
+
idxs = [int(_t)]
|
|
1078
|
+
else:
|
|
1079
|
+
idxs = [int(v) for v in _t]
|
|
1080
|
+
elif isinstance(indices, (bool, int)):
|
|
1081
|
+
idxs = [int(indices)]
|
|
1082
|
+
else:
|
|
1083
|
+
idxs = [int(v) for v in list(indices)]
|
|
1084
|
+
# values 可为标量(填到全部索引,put 语义)——先展开,避免
|
|
1085
|
+
# list(scalar) 报 'int' object is not iterable
|
|
1086
|
+
if hasattr(values, 'tolist'):
|
|
1087
|
+
_vt = values.tolist()
|
|
1088
|
+
else:
|
|
1089
|
+
_vt = values
|
|
1090
|
+
if isinstance(_vt, (bool, int, float, complex)):
|
|
1091
|
+
values = [_vt] * len(idxs)
|
|
1092
|
+
vals = values.tolist() if hasattr(values, 'tolist') else list(values)
|
|
1093
|
+
if not vals:
|
|
1094
|
+
# 数组语义:空 values 不修改数组
|
|
1095
|
+
return
|
|
1096
|
+
|
|
1097
|
+
def _norm(i):
|
|
1098
|
+
if n == 0:
|
|
1099
|
+
raise IndexError(
|
|
1100
|
+
f"index {i} is out of bounds for axis 0 with size 0")
|
|
1101
|
+
if mode == 'clip':
|
|
1102
|
+
if i > n - 1:
|
|
1103
|
+
i = n - 1
|
|
1104
|
+
if i < -n:
|
|
1105
|
+
i = -n
|
|
1106
|
+
elif mode != 'wrap':
|
|
1107
|
+
if i < -n or i >= n:
|
|
1108
|
+
raise IndexError(
|
|
1109
|
+
f"index {i} is out of bounds for axis 0 "
|
|
1110
|
+
f"with size {n}")
|
|
1111
|
+
return i % n
|
|
1112
|
+
|
|
1113
|
+
norm = [_norm(i) for i in idxs]
|
|
1114
|
+
if mode == 'raise' and all(0 <= i < n for i in idxs):
|
|
1115
|
+
arr._array.put(_ensure(idxs), _ensure(values))
|
|
1116
|
+
return
|
|
1117
|
+
# 越界/clip/wrap:就地修改扁平缓冲
|
|
1118
|
+
flat = arr.ravel().tolist()
|
|
1119
|
+
if not isinstance(flat, list):
|
|
1120
|
+
flat = [flat]
|
|
1121
|
+
for i, v in zip(norm, vals):
|
|
1122
|
+
flat[i] = v
|
|
1123
|
+
dt = getattr(arr, '_dtype', 'float64')
|
|
1124
|
+
arr._array = ndarray(flat, _dtype=dt).reshape(
|
|
1125
|
+
tuple(arr.shape))._array
|
|
1126
|
+
|
|
1127
|
+
@staticmethod
|
|
1128
|
+
def repeat(arr, repeats, axis=None):
|
|
1129
|
+
"""重复数组元素。"""
|
|
1130
|
+
# 数组 repeats:Rust 仅支持标量 → Python 展开(1-D;2-D 轴展开)
|
|
1131
|
+
if (isinstance(repeats, (list, tuple))
|
|
1132
|
+
or (hasattr(repeats, 'ndim')
|
|
1133
|
+
and getattr(repeats, 'ndim', 0) > 0)):
|
|
1134
|
+
from rsarray import ndarray as _ND
|
|
1135
|
+
shp = tuple(arr.shape)
|
|
1136
|
+
cnts = repeats.tolist() if hasattr(repeats, 'tolist') \
|
|
1137
|
+
else list(repeats)
|
|
1138
|
+
if not isinstance(cnts, (list, tuple)):
|
|
1139
|
+
cnts = [cnts]
|
|
1140
|
+
cnts = [int(c) for c in cnts]
|
|
1141
|
+
if len(shp) <= 1:
|
|
1142
|
+
flat = arr.ravel().tolist()
|
|
1143
|
+
if not isinstance(flat, list):
|
|
1144
|
+
flat = [flat]
|
|
1145
|
+
out = []
|
|
1146
|
+
for v, c in zip(flat, cnts):
|
|
1147
|
+
out.extend([v] * c)
|
|
1148
|
+
return _ND(out, _dtype=getattr(arr, '_dtype', 'float64'))
|
|
1149
|
+
rows = arr.tolist()
|
|
1150
|
+
if axis == 0:
|
|
1151
|
+
out = []
|
|
1152
|
+
for i, row in enumerate(rows):
|
|
1153
|
+
out.extend([row] * cnts[i])
|
|
1154
|
+
return _ND(out, _dtype=getattr(arr, '_dtype', 'float64'))
|
|
1155
|
+
out = []
|
|
1156
|
+
for row in rows:
|
|
1157
|
+
nr = []
|
|
1158
|
+
for v, c in zip(row, cnts):
|
|
1159
|
+
nr.extend([v] * c)
|
|
1160
|
+
out.append(nr)
|
|
1161
|
+
return _ND(out, _dtype=getattr(arr, '_dtype', 'float64'))
|
|
1162
|
+
# 字符串数组:Rust repeat 作用于 f64 占位存储(产出 float 零、丢
|
|
1163
|
+
# 字符串数据)——标量 repeats 路径须在 Python 层按元素重复
|
|
1164
|
+
#(数组 repeats 已在上方分支 Python 展开)
|
|
1165
|
+
_sd_r = getattr(arr, '_str_dtype', None)
|
|
1166
|
+
if _sd_r is not None and getattr(arr, '_raw_data', None) is not None:
|
|
1167
|
+
import rsarray as _rn_r
|
|
1168
|
+
_rdt = f'{_sd_r[0]}{max(int(_sd_r[1]), 1)}'
|
|
1169
|
+
_r = int(repeats)
|
|
1170
|
+
shp = [int(s) for s in arr.shape]
|
|
1171
|
+
if not shp:
|
|
1172
|
+
_out = [arr.tolist()] * _r
|
|
1173
|
+
elif axis is None:
|
|
1174
|
+
# tolist 平铺 C 序(ravel 走 Rust 占位存储会丢字符串数据)
|
|
1175
|
+
_t = arr.tolist()
|
|
1176
|
+
if not isinstance(_t, list):
|
|
1177
|
+
_t = [_t]
|
|
1178
|
+
|
|
1179
|
+
def _fl(x):
|
|
1180
|
+
o = []
|
|
1181
|
+
for v in x:
|
|
1182
|
+
o.extend(_fl(v) if isinstance(v, list) else [v])
|
|
1183
|
+
return o
|
|
1184
|
+
_flat = _fl(_t)
|
|
1185
|
+
_out = [v for v in _flat for _ in range(_r)]
|
|
1186
|
+
else:
|
|
1187
|
+
_ax = int(axis) % len(shp)
|
|
1188
|
+
|
|
1189
|
+
def _ra(nested, a):
|
|
1190
|
+
if a == 0:
|
|
1191
|
+
return [v for v in nested for _ in range(_r)]
|
|
1192
|
+
return [_ra(row, a - 1) for row in nested]
|
|
1193
|
+
|
|
1194
|
+
def _unflat(flat, shape):
|
|
1195
|
+
if not shape or len(shape) == 1:
|
|
1196
|
+
return list(flat)
|
|
1197
|
+
_cnt = 1
|
|
1198
|
+
for _s in shape[1:]:
|
|
1199
|
+
_cnt *= _s
|
|
1200
|
+
return [_unflat(flat[i * _cnt:(i + 1) * _cnt], shape[1:])
|
|
1201
|
+
for i in range(shape[0])]
|
|
1202
|
+
_t = arr.tolist()
|
|
1203
|
+
if not isinstance(_t, list):
|
|
1204
|
+
_t = [[_t]]
|
|
1205
|
+
# 多维字符串 tolist 可能返回平铺(C 序):先重建嵌套
|
|
1206
|
+
if len(shp) > 1 and _t and not isinstance(_t[0], list):
|
|
1207
|
+
_t = _unflat(_t, shp)
|
|
1208
|
+
_out = _ra(_t, _ax)
|
|
1209
|
+
shp[_ax] *= _r
|
|
1210
|
+
# 模块级 array() 走真正的字符串构造路径(ndarray() 构造器
|
|
1211
|
+
# 对 _dtype='U1' 只做重标注,会丢 _str_dtype/_raw_data)
|
|
1212
|
+
_res = _rn_r.array(_out, dtype=_rdt)
|
|
1213
|
+
if shp and axis is not None and _res.ndim < len(shp):
|
|
1214
|
+
_res = _res.reshape(tuple(shp))
|
|
1215
|
+
return _res
|
|
1216
|
+
result = arr._array.repeat(repeats, axis)
|
|
1217
|
+
return _wrap_result(result)
|
|
1218
|
+
|
|
1219
|
+
@staticmethod
|
|
1220
|
+
def nonzero(arr):
|
|
1221
|
+
"""返回非零元素的索引。"""
|
|
1222
|
+
ndarray, _ = _get_deps()
|
|
1223
|
+
raw = _core.nonzero_arrs(arr._array)
|
|
1224
|
+
return tuple(ndarray._wrap(r) for r in raw)
|