rsarray 1.2.10__cp313-cp313-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rsarray/__init__.py +12028 -0
- rsarray/_core/__init__.py +213 -0
- rsarray/_core/_exceptions.py +83 -0
- rsarray/_core/_internal.py +331 -0
- rsarray/_core/_multiarray_tests.py +129 -0
- rsarray/_core/_multiarray_umath.py +121 -0
- rsarray/_core/_rational_tests.py +52 -0
- rsarray/_core/arrayprint.py +36 -0
- rsarray/_core/fromnumeric.py +31 -0
- rsarray/_core/function_base.py +84 -0
- rsarray/_core/multiarray.py +385 -0
- rsarray/_core/numeric.py +28 -0
- rsarray/_core/numerictypes.py +233 -0
- rsarray/_core/records.py +14 -0
- rsarray/_core/shape_base.py +23 -0
- rsarray/_core/strings.py +78 -0
- rsarray/_core/umath.py +176 -0
- rsarray/_dtypes.py +1229 -0
- rsarray/_extra.py +6621 -0
- rsarray/_typing.py +24 -0
- rsarray/array_methods.py +1224 -0
- rsarray/array_ops.py +1585 -0
- rsarray/char.py +1590 -0
- rsarray/exceptions.py +45 -0
- rsarray/fft/__init__.py +231 -0
- rsarray/io.py +453 -0
- rsarray/lib/__init__.py +102 -0
- rsarray/lib/_function_base_impl.py +37 -0
- rsarray/lib/_index_tricks_impl.py +98 -0
- rsarray/lib/_nanfunctions_impl.py +1637 -0
- rsarray/lib/_stride_tricks_impl.py +110 -0
- rsarray/lib/recfunctions.py +1222 -0
- rsarray/lib/stride_tricks.py +106 -0
- rsarray/linalg/__init__.py +2603 -0
- rsarray/linalg/_linalg.py +91 -0
- rsarray/linalg/_pylinalg.py +1008 -0
- rsarray/linalg/lapack_lite.py +13 -0
- rsarray/ma/__init__.py +92 -0
- rsarray/ma/core.py +1385 -0
- rsarray/ma/extras.py +711 -0
- rsarray/ma/mrecords.py +144 -0
- rsarray/math_functions.py +965 -0
- rsarray/matlib.py +67 -0
- rsarray/num_core.cp313-win_amd64.pyd +0 -0
- rsarray/polynomial/__init__.py +148 -0
- rsarray/polynomial/_npcompat.py +721 -0
- rsarray/polynomial/polynomial.py +1082 -0
- rsarray/random/__init__.py +2266 -0
- rsarray/random/_distributions.py +773 -0
- rsarray/rec.py +207 -0
- rsarray/statistics.py +1360 -0
- rsarray/strings.py +349 -0
- rsarray/typing/__init__.py +26 -0
- rsarray-1.2.10.dist-info/METADATA +280 -0
- rsarray-1.2.10.dist-info/RECORD +59 -0
- rsarray-1.2.10.dist-info/WHEEL +4 -0
- rsarray-1.2.10.dist-info/licenses/LICENSE +21 -0
- rsarray-1.2.10.dist-info/licenses/NOTICE +7 -0
- rsarray-1.2.10.dist-info/sboms/rsarray.cyclonedx.json +2789 -0
rsarray/array_ops.py
ADDED
|
@@ -0,0 +1,1585 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
import builtins
|
|
3
|
+
import itertools
|
|
4
|
+
import math
|
|
5
|
+
|
|
6
|
+
"""数组操作模块 - 所有实现位于 Rust,这里仅保留薄包装。"""
|
|
7
|
+
|
|
8
|
+
import rsarray.num_core as _core
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _nd():
|
|
12
|
+
from .__init__ import ndarray as _n
|
|
13
|
+
return _n
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _np():
|
|
17
|
+
import rsarray as _m
|
|
18
|
+
return _m
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _wrap(result):
|
|
22
|
+
return _nd()(result)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _scalar_or_wrap(a):
|
|
26
|
+
"""Python 标量按 数组语义保 dtype(bool→bool、int→int64);
|
|
27
|
+
ndarray 构造器默认 float64(Rust f64 存储),直接 nd() 会丢 int 语义。"""
|
|
28
|
+
if isinstance(a, builtins.bool):
|
|
29
|
+
return _nd()(a, _dtype='bool')
|
|
30
|
+
if isinstance(a, builtins.int):
|
|
31
|
+
return _nd()(a, _dtype='int64')
|
|
32
|
+
return _wrap(a)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _nested_to_list(x):
|
|
36
|
+
"""Recursively turn nested arrays / lists / tuples into pure nested lists."""
|
|
37
|
+
if hasattr(x, '_array'):
|
|
38
|
+
return x.tolist()
|
|
39
|
+
if isinstance(x, (list, tuple)):
|
|
40
|
+
return [_nested_to_list(i) for i in x]
|
|
41
|
+
return x
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _ensure_raw(a):
|
|
45
|
+
if hasattr(a, '_array'):
|
|
46
|
+
return a._array
|
|
47
|
+
if isinstance(a, (list, tuple)):
|
|
48
|
+
# Rust core cannot parse lists that contain array objects; promote
|
|
49
|
+
# them to pure nested lists first (e.g. concatenate([[X[0]], [X[1]]])).
|
|
50
|
+
return _core.ndarray(_nested_to_list(a))
|
|
51
|
+
if isinstance(a, range):
|
|
52
|
+
# 数组语义:range 是 array-like(reshape(range(20),(5,4)) 等须可用)
|
|
53
|
+
return _core.ndarray(list(a))
|
|
54
|
+
return _core.ndarray(a)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _as_data(a):
|
|
58
|
+
"""concat/stack 族:Python list/tuple/range/标量 → 数据语义 ndarray。
|
|
59
|
+
不能用 _wrap:ndarray() 构造器把裸 tuple 当 shape(np.zeros((2,3)) 契约),
|
|
60
|
+
concatenate((tuple,)) 会被误判成高维空数组。"""
|
|
61
|
+
if hasattr(a, '_array'):
|
|
62
|
+
return a
|
|
63
|
+
from .__init__ import array as _array_fn
|
|
64
|
+
return _array_fn(a)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _scalar_idx(x):
|
|
68
|
+
"""标量下标/形状参数:Python int/bool 或 rsarray 整数标量(非序列/数组)。
|
|
69
|
+
rsarray 整型标量不再是 int 子类,需用 __index__ 协议识别。"""
|
|
70
|
+
if isinstance(x, int):
|
|
71
|
+
return True
|
|
72
|
+
return (hasattr(x, '__index__') and not hasattr(x, '__iter__')
|
|
73
|
+
and not hasattr(x, '_array'))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def reshape(a, shape=None, order='C', *, newshape=None, copy=None):
|
|
77
|
+
"""改变数组形状而不改变数据。
|
|
78
|
+
|
|
79
|
+
shape 为新形状(整数或整数元组)。newshape 为已弃用的旧参数名,
|
|
80
|
+
order 支持 'C'(行优先)与 'F'(列优先)。
|
|
81
|
+
"""
|
|
82
|
+
if shape is None:
|
|
83
|
+
shape = newshape
|
|
84
|
+
if shape is None:
|
|
85
|
+
raise TypeError("reshape() missing 1 required positional argument: 'shape'")
|
|
86
|
+
if isinstance(shape, int) or _scalar_idx(shape):
|
|
87
|
+
shape = (int(shape),)
|
|
88
|
+
else:
|
|
89
|
+
shape = tuple(shape)
|
|
90
|
+
arr = a if hasattr(a, '_array') else _wrap(a)
|
|
91
|
+
_tot = 1
|
|
92
|
+
for _s in shape:
|
|
93
|
+
_tot *= int(_s)
|
|
94
|
+
if _tot == 0:
|
|
95
|
+
# 数组语义:零尺寸数组 reshape 保留目标形状(如 (1,0,1));
|
|
96
|
+
# Rust _core.reshape 拒绝零尺寸 → 经 zeros 按目标形状构造(继承元数据)。
|
|
97
|
+
_z = _np().zeros(shape, dtype=getattr(arr, '_dtype', 'float64'))
|
|
98
|
+
_z._dtype_obj = getattr(arr, '_dtype_obj', None)
|
|
99
|
+
_z._str_dtype = getattr(arr, '_str_dtype', None)
|
|
100
|
+
_z._fields = getattr(arr, '_fields', None)
|
|
101
|
+
_z._raw_data = getattr(arr, '_raw_data', None)
|
|
102
|
+
return _z
|
|
103
|
+
if order == 'F':
|
|
104
|
+
flat = arr.ravel(order='F')
|
|
105
|
+
out = _wrap(_core.reshape(flat._array, shape))
|
|
106
|
+
# 数组语义:F 序输入 + F 序 reshape = 视图(保血缘);
|
|
107
|
+
# C 序输入 + F 序 reshape = 新拷贝(断血缘,shares_memory False)。
|
|
108
|
+
# 数组语义:copy=False 要求视图,无法视图时必须拷贝 → ValueError;
|
|
109
|
+
# copy=None 时 F 序输入 = 视图(保血缘),C 序输入 = 新拷贝(断血缘)。
|
|
110
|
+
_in_f = getattr(arr, '_rs_order', None) == 'F'
|
|
111
|
+
if copy is False and not _in_f:
|
|
112
|
+
raise ValueError("Unable to avoid creating a copy while reshaping.")
|
|
113
|
+
if _in_f:
|
|
114
|
+
try:
|
|
115
|
+
out._rs_parent = arr
|
|
116
|
+
out._rs_order = 'F'
|
|
117
|
+
except Exception:
|
|
118
|
+
pass
|
|
119
|
+
else:
|
|
120
|
+
try:
|
|
121
|
+
out._rs_parent = None
|
|
122
|
+
except Exception:
|
|
123
|
+
pass
|
|
124
|
+
if getattr(out, '_raw_data', None) is getattr(arr, '_raw_data', None):
|
|
125
|
+
try:
|
|
126
|
+
out._raw_data = None
|
|
127
|
+
except Exception:
|
|
128
|
+
pass
|
|
129
|
+
else:
|
|
130
|
+
_in_c = getattr(arr, '_rs_order', None) != 'F'
|
|
131
|
+
if copy is False and not _in_c:
|
|
132
|
+
raise ValueError("Unable to avoid creating a copy while reshaping.")
|
|
133
|
+
out = _wrap(_core.reshape(_ensure_raw(a), shape))
|
|
134
|
+
try:
|
|
135
|
+
out._rs_parent = arr
|
|
136
|
+
except Exception:
|
|
137
|
+
pass
|
|
138
|
+
if copy is True:
|
|
139
|
+
# 数组语义:copy=True 恒返回新数组(不与输入共享内存)
|
|
140
|
+
out = out.copy()
|
|
141
|
+
try:
|
|
142
|
+
out._rs_parent = None
|
|
143
|
+
except Exception:
|
|
144
|
+
pass
|
|
145
|
+
return out
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def ravel(a, order='C'):
|
|
149
|
+
"""展平数组。"""
|
|
150
|
+
# 数组语义:np.ravel(matrix) 返回 1-d ndarray(matrix.ravel() 才是 (1,N) 矩阵)
|
|
151
|
+
if type(a).__name__ == 'matrix':
|
|
152
|
+
return a.A.ravel(order=order)
|
|
153
|
+
arr = a if hasattr(a, '_array') else _wrap(a)
|
|
154
|
+
return arr.ravel(order=order)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def moveaxis(a, source, destination):
|
|
158
|
+
"""将数组的轴从 source 移动到 destination(数组语义,纯 Python 实现)。
|
|
159
|
+
|
|
160
|
+
校验与 normalize_axis_tuple 一致:AxisError(source/destination
|
|
161
|
+
越界)、ValueError(repeated axis、source/destination 数量不一致)。
|
|
162
|
+
非 ndarray 输入(MaskedArray/list)计算后转换回原类型。
|
|
163
|
+
"""
|
|
164
|
+
np = _np()
|
|
165
|
+
if getattr(a, 'ndim', None) is None:
|
|
166
|
+
a = np.array(a)
|
|
167
|
+
ndim = a.ndim
|
|
168
|
+
|
|
169
|
+
def _norm(axes, what):
|
|
170
|
+
if isinstance(axes, int) or _scalar_idx(axes):
|
|
171
|
+
axes = [int(axes)]
|
|
172
|
+
else:
|
|
173
|
+
axes = [int(x) for x in axes]
|
|
174
|
+
if len(set(axes)) != len(axes):
|
|
175
|
+
raise ValueError(f"repeated axis in `{what}`")
|
|
176
|
+
for ax in axes:
|
|
177
|
+
if not (-ndim <= ax < ndim):
|
|
178
|
+
raise np.AxisError(
|
|
179
|
+
f"{what} axis {ax} is out of bounds for array "
|
|
180
|
+
f"of dimension {ndim}")
|
|
181
|
+
return axes
|
|
182
|
+
|
|
183
|
+
source = _norm(source, 'source')
|
|
184
|
+
destination = _norm(destination, 'destination')
|
|
185
|
+
if len(source) != len(destination):
|
|
186
|
+
raise ValueError("source and destination must have the same number of values")
|
|
187
|
+
# 标准算法(先归一化非负):剩余轴 + 按 destination 位置插入 source 轴
|
|
188
|
+
source_n = [s % ndim for s in source]
|
|
189
|
+
dest_n = [d % ndim for d in destination]
|
|
190
|
+
order = [n for n in range(ndim) if n not in source_n]
|
|
191
|
+
for dest, src in sorted(zip(dest_n, source_n)):
|
|
192
|
+
order.insert(dest, src)
|
|
193
|
+
if isinstance(a, _nd()):
|
|
194
|
+
return a.transpose(order)
|
|
195
|
+
# 非 ndarray(MaskedArray/list 等):ndarray 计算后转回原类型
|
|
196
|
+
result = np.array(a).transpose(order)
|
|
197
|
+
if not isinstance(a, (list, tuple)):
|
|
198
|
+
try:
|
|
199
|
+
result = type(a)(result)
|
|
200
|
+
except Exception:
|
|
201
|
+
pass
|
|
202
|
+
return result
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def rollaxis(a, axis, start=0):
|
|
206
|
+
"""滚动指定轴到 start 位置(rollaxis 语义)。
|
|
207
|
+
|
|
208
|
+
与 moveaxis 的区别(数组语义):start 可取 [ -ndim, ndim ];
|
|
209
|
+
归一化后若 start > axis 则 start -= 1(轴"越过自己"时不占位)。
|
|
210
|
+
等价:moveaxis(a, axis, start if start <= axis else start - 1)。
|
|
211
|
+
"""
|
|
212
|
+
np = _np()
|
|
213
|
+
arr = a if getattr(a, 'ndim', None) is not None else np.array(a)
|
|
214
|
+
ndim = arr.ndim
|
|
215
|
+
if not (-ndim <= axis < ndim):
|
|
216
|
+
raise np.AxisError(
|
|
217
|
+
f"axis {axis} is out of bounds for array of dimension {ndim}")
|
|
218
|
+
if not (-ndim <= start <= ndim):
|
|
219
|
+
raise np.AxisError(
|
|
220
|
+
f"start {start} is out of bounds for array of dimension {ndim}")
|
|
221
|
+
axis_n = axis % ndim
|
|
222
|
+
# 数组语义:start 归一化到 [0, ndim]——负 start 按 +ndim 折算
|
|
223
|
+
# (-1 → ndim-1),而非模 ndim+1(那会把 -1 错映成 ndim)。
|
|
224
|
+
start_n = start + ndim if start < 0 else start
|
|
225
|
+
if start_n > axis_n:
|
|
226
|
+
start_n -= 1
|
|
227
|
+
return moveaxis(arr, axis_n, start_n)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def broadcast_to(a, shape, subok=None, device=None):
|
|
231
|
+
"""将数组广播到新形状。subok/device 仅为兼容标准签名,忽略。"""
|
|
232
|
+
arr = a if hasattr(a, '_array') else _wrap(a)
|
|
233
|
+
nd = _nd()
|
|
234
|
+
dtype = getattr(arr, '_dtype', "float64")
|
|
235
|
+
fields = getattr(arr, '_fields', None)
|
|
236
|
+
raw_data = getattr(arr, '_raw_data', None)
|
|
237
|
+
if getattr(arr, '_array', None) is None:
|
|
238
|
+
# 无 Rust 层 _array(None/object 等 Python 层数据):Python 层
|
|
239
|
+
# 物化。—broadcast_to(None, (2,)) → object 数组 [None, None]。
|
|
240
|
+
if shape == () or shape == []:
|
|
241
|
+
return nd(a)
|
|
242
|
+
_shp = ((int(shape),) if (isinstance(shape, int) or _scalar_idx(shape))
|
|
243
|
+
else tuple(int(s) for s in shape))
|
|
244
|
+
_tot = 1
|
|
245
|
+
for _s in _shp:
|
|
246
|
+
_tot *= _s
|
|
247
|
+
_out = nd([a] * _tot)
|
|
248
|
+
return _out.reshape(_shp)
|
|
249
|
+
# 数组语义:Python int(/整数列表)广播结果保持整型(int64),
|
|
250
|
+
# 迭代出可 __index__ 的 int;rsarray 默认 int→f64 会让元素变成
|
|
251
|
+
# float 而无法用作切片下标。
|
|
252
|
+
if isinstance(a, (list, tuple)) and a and all(
|
|
253
|
+
isinstance(x, int) and not isinstance(x, bool) for x in a):
|
|
254
|
+
_flat_src = a
|
|
255
|
+
elif isinstance(a, int) and not isinstance(a, bool):
|
|
256
|
+
_flat_src = [a]
|
|
257
|
+
else:
|
|
258
|
+
_flat_src = None
|
|
259
|
+
if _flat_src is not None:
|
|
260
|
+
if shape == () or shape == []:
|
|
261
|
+
_out = nd(_flat_src[0])
|
|
262
|
+
_out._dtype = 'int64'
|
|
263
|
+
return _out
|
|
264
|
+
_shp = ((int(shape),) if (isinstance(shape, int) or _scalar_idx(shape))
|
|
265
|
+
else tuple(int(s) for s in shape))
|
|
266
|
+
_tot = 1
|
|
267
|
+
for _s in _shp:
|
|
268
|
+
_tot *= _s
|
|
269
|
+
_out = nd([_flat_src[0] if len(_flat_src) == 1 else
|
|
270
|
+
_flat_src[i % len(_flat_src)] for i in range(_tot)])
|
|
271
|
+
_out._dtype = 'int64'
|
|
272
|
+
if _shp:
|
|
273
|
+
_out = _out.reshape(_shp)
|
|
274
|
+
return _out
|
|
275
|
+
# Rust _core.broadcast_to 对复数丢虚部(与 _core.prod 复数 bug 同源):
|
|
276
|
+
# 复数 dtype 走 Python 侧物化(tolist 保留复数)。
|
|
277
|
+
if isinstance(dtype, str) and dtype.startswith('complex') \
|
|
278
|
+
and getattr(arr, '_array', None) is not None:
|
|
279
|
+
_shp = ((int(shape),) if (isinstance(shape, int) or _scalar_idx(shape))
|
|
280
|
+
else tuple(int(s) for s in shape))
|
|
281
|
+
_src = arr.tolist()
|
|
282
|
+
_src_shape = tuple(arr.shape)
|
|
283
|
+
_off = len(_shp) - len(_src_shape)
|
|
284
|
+
_total = 1
|
|
285
|
+
for _s in _shp:
|
|
286
|
+
_total *= _s
|
|
287
|
+
_out = []
|
|
288
|
+
for _t in range(_total):
|
|
289
|
+
_idx = []
|
|
290
|
+
_rem = _t
|
|
291
|
+
for _s in reversed(_shp):
|
|
292
|
+
_idx.append(_rem % _s)
|
|
293
|
+
_rem //= _s
|
|
294
|
+
_idx = list(reversed(_idx))
|
|
295
|
+
_v = _src
|
|
296
|
+
for _j, _s in enumerate(_src_shape):
|
|
297
|
+
_v = _v[_idx[_off + _j] % _s]
|
|
298
|
+
_out.append(_v)
|
|
299
|
+
if not _shp:
|
|
300
|
+
_res = nd(_out[0])
|
|
301
|
+
_res._dtype = dtype
|
|
302
|
+
return _res
|
|
303
|
+
_res = nd(_out).reshape(_shp)
|
|
304
|
+
if getattr(_res, '_dtype', None) != dtype:
|
|
305
|
+
_res = _res.astype(dtype)
|
|
306
|
+
return _res
|
|
307
|
+
# Handle broadcasting to scalar shape ()
|
|
308
|
+
if shape == () or shape == []:
|
|
309
|
+
result = arr._array # 0-d array is already scalar-shaped
|
|
310
|
+
else:
|
|
311
|
+
_shp = ((int(shape),) if (isinstance(shape, int) or _scalar_idx(shape))
|
|
312
|
+
else tuple(int(s) for s in shape))
|
|
313
|
+
_tot = 1
|
|
314
|
+
for _s in _shp:
|
|
315
|
+
_tot *= _s
|
|
316
|
+
if _tot > 2**28: # 2GB 量级:Rust 物化会 OOM / capacity overflow abort
|
|
317
|
+
# 超大广播:零分配 Python 层视图(Rust 物化会 OOM / capacity overflow
|
|
318
|
+
# abort 进程)。数组语义:broadcast_to 从不分配;物化时抛 MemoryError。
|
|
319
|
+
res = nd._wrap(arr._array, _dtype=dtype, _fields=fields, _raw_data=raw_data)
|
|
320
|
+
res._rs_shape_override = _shp
|
|
321
|
+
return res
|
|
322
|
+
result = _core.broadcast_to(arr._array, shape)
|
|
323
|
+
return nd._wrap(result, _dtype=dtype, _fields=fields, _raw_data=raw_data)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def transpose(a, axes=None):
|
|
327
|
+
"""转置数组。axes 为 None 时反转所有轴,否则按给定顺序置换。"""
|
|
328
|
+
# 等形状 ndarray 列表:先堆叠再转置(数组语义 (n, k) → (k, n))
|
|
329
|
+
if isinstance(a, (list, tuple)) and a and all(
|
|
330
|
+
hasattr(_x, '_array') for _x in a):
|
|
331
|
+
a = [_x.tolist() for _x in a]
|
|
332
|
+
arr = a if hasattr(a, '_array') else _wrap(a)
|
|
333
|
+
nd = _nd()
|
|
334
|
+
dtype = getattr(arr, '_dtype', "float64")
|
|
335
|
+
fields = getattr(arr, '_fields', None)
|
|
336
|
+
raw_data = getattr(arr, '_raw_data', None)
|
|
337
|
+
result = _core.transpose_axes(arr._array, axes)
|
|
338
|
+
return nd._wrap(result, _dtype=dtype, _fields=fields, _raw_data=raw_data)
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def swapaxes(a, axis1, axis2):
|
|
342
|
+
"""交换数组的两个轴。"""
|
|
343
|
+
arr = a if hasattr(a, '_array') else _wrap(a)
|
|
344
|
+
nd = _nd()
|
|
345
|
+
dtype = getattr(arr, '_dtype', "float64")
|
|
346
|
+
fields = getattr(arr, '_fields', None)
|
|
347
|
+
raw_data = getattr(arr, '_raw_data', None)
|
|
348
|
+
# Rust 层只接受非负轴:负轴先归一化(数组语义)
|
|
349
|
+
ndim = len(arr.shape)
|
|
350
|
+
if axis1 < 0:
|
|
351
|
+
axis1 += ndim
|
|
352
|
+
if axis2 < 0:
|
|
353
|
+
axis2 += ndim
|
|
354
|
+
result = _core.swapaxes(arr._array, axis1, axis2)
|
|
355
|
+
return nd._wrap(result, _dtype=dtype, _fields=fields, _raw_data=raw_data)
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _flat_to_nested(flat, shape):
|
|
359
|
+
"""扁平列表按 C 序重塑为嵌套列表(插 1 维不改 C 序 flat,掩码用)。"""
|
|
360
|
+
if not shape:
|
|
361
|
+
return flat[0]
|
|
362
|
+
if len(shape) == 1:
|
|
363
|
+
return list(flat)
|
|
364
|
+
_sub = 1
|
|
365
|
+
for _x in shape[1:]:
|
|
366
|
+
_sub *= _x
|
|
367
|
+
return [_flat_to_nested(flat[_i * _sub:(_i + 1) * _sub], shape[1:])
|
|
368
|
+
for _i in range(shape[0])]
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def expand_dims(a, axis):
|
|
372
|
+
"""扩展数组的形状。"""
|
|
373
|
+
# ma.MaskedArray 是独立类(非 ndarray 子类):subok 语义 →
|
|
374
|
+
# 数据与掩码一起扩展,重建为 MaskedArray(插 1 维不改 C 序 flat)。
|
|
375
|
+
_MA = getattr(getattr(_np(), 'ma', None), 'MaskedArray', None)
|
|
376
|
+
if _MA is not None and type(a) is _MA:
|
|
377
|
+
_ed = expand_dims(a._data, axis)
|
|
378
|
+
_m = _flat_to_nested(list(a._mask), tuple(getattr(_ed, 'shape', ())))
|
|
379
|
+
return _MA(_ed, mask=_m)
|
|
380
|
+
arr = a if hasattr(a, '_array') else _scalar_or_wrap(a)
|
|
381
|
+
nd = _nd()
|
|
382
|
+
dtype = getattr(arr, '_dtype', "float64")
|
|
383
|
+
fields = getattr(arr, '_fields', None)
|
|
384
|
+
raw_data = getattr(arr, '_raw_data', None)
|
|
385
|
+
_shp = tuple(getattr(arr, 'shape', ()))
|
|
386
|
+
axes = tuple(axis) if isinstance(axis, (list, tuple)) else (axis,)
|
|
387
|
+
# 标准语义(_shape_base_impl.expand_dims):axis 在
|
|
388
|
+
# out_ndim = len(axis)+ndim 上归一化;重复 axis → ValueError;
|
|
389
|
+
# 越界 → AxisError(勿让越界值直达 Rust 崩溃)。
|
|
390
|
+
out_ndim = len(axes) + len(_shp)
|
|
391
|
+
_norm = []
|
|
392
|
+
for _ax in axes:
|
|
393
|
+
_n = _ax + out_ndim if _ax < 0 else _ax
|
|
394
|
+
if not 0 <= _n < out_ndim:
|
|
395
|
+
from rsarray.exceptions import AxisError as _AxisError
|
|
396
|
+
raise _AxisError(
|
|
397
|
+
f"axis {_ax} is out of bounds for array of dimension {len(_shp)}")
|
|
398
|
+
_norm.append(_n)
|
|
399
|
+
if len(set(_norm)) != len(_norm):
|
|
400
|
+
raise ValueError(f"repeated axis {axes}")
|
|
401
|
+
# 保持子类型(subok 语义);matrix 除外——matrix 恒为 2-d,
|
|
402
|
+
# expand_dims 必须降级为 ndarray(数组语义)。
|
|
403
|
+
_t = type(arr)
|
|
404
|
+
if _t is not nd and hasattr(_t, '_wrap') and \
|
|
405
|
+
_t is not getattr(_np(), 'matrix', None):
|
|
406
|
+
_cls = _t
|
|
407
|
+
else:
|
|
408
|
+
_cls = nd
|
|
409
|
+
if len(axes) == 1:
|
|
410
|
+
result = _core.expand_dims(arr._array, axes[0])
|
|
411
|
+
else:
|
|
412
|
+
_rs = list(_shp)
|
|
413
|
+
for _n in sorted(_norm):
|
|
414
|
+
_rs.insert(_n, 1)
|
|
415
|
+
result = _core.reshape(arr._array, tuple(_rs))
|
|
416
|
+
return _cls._wrap(result, _dtype=dtype, _fields=fields, _raw_data=raw_data)
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def squeeze(a, axis=None):
|
|
420
|
+
"""从数组形状中删除单维度条目(axis 指定时只删除指定轴)。"""
|
|
421
|
+
# list 输入(可能含 ndarray 元素):先递归转纯嵌套列表再构造,
|
|
422
|
+
# 使 np.squeeze([np.zeros((3, 1))]) 得到 (1, 3, 1) 而非 object 数组
|
|
423
|
+
arr = a if hasattr(a, '_array') else _nd()(_nested_to_list(a))
|
|
424
|
+
nd = _nd()
|
|
425
|
+
dtype = getattr(arr, '_dtype', "float64")
|
|
426
|
+
fields = getattr(arr, '_fields', None)
|
|
427
|
+
raw_data = getattr(arr, '_raw_data', None)
|
|
428
|
+
if axis is None:
|
|
429
|
+
result = _core.squeeze(arr._array)
|
|
430
|
+
return nd._wrap(result, _dtype=dtype, _fields=fields, _raw_data=raw_data)
|
|
431
|
+
# 数组语义:只删除指定轴(该轴大小须为 1)
|
|
432
|
+
shape = tuple(arr.shape)
|
|
433
|
+
ndim = len(shape)
|
|
434
|
+
if isinstance(axis, int):
|
|
435
|
+
_axes = (axis,)
|
|
436
|
+
else:
|
|
437
|
+
_axes = tuple(axis)
|
|
438
|
+
_axes = tuple(_x % ndim for _x in _axes)
|
|
439
|
+
new_shape = []
|
|
440
|
+
for _i, _s in enumerate(shape):
|
|
441
|
+
if _i in _axes:
|
|
442
|
+
if _s != 1:
|
|
443
|
+
raise ValueError(
|
|
444
|
+
"cannot select an axis to squeeze out which has size "
|
|
445
|
+
"not equal to one")
|
|
446
|
+
else:
|
|
447
|
+
new_shape.append(_s)
|
|
448
|
+
result = arr.reshape(tuple(new_shape))
|
|
449
|
+
return nd._wrap(result._array, _dtype=dtype, _fields=fields,
|
|
450
|
+
_raw_data=raw_data)
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
_CASTING_VALUES = ("no", "equiv", "safe", "same_kind", "unsafe")
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def _check_casting(casting):
|
|
457
|
+
"""数组语义:casting 合法值校验(非法值抛 ValueError)。"""
|
|
458
|
+
if casting is not None and casting not in _CASTING_VALUES:
|
|
459
|
+
raise ValueError(
|
|
460
|
+
"casting must be one of 'no', 'equiv', 'safe', 'same_kind', or "
|
|
461
|
+
f"'unsafe'; got {casting!r}")
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def _apply_dtype(res, dtype):
|
|
465
|
+
"""显式 dtype 转换;非 native 字节序经 _dtype_obj 保留(astype 同款)。"""
|
|
466
|
+
_name = _dtype_name(dtype)
|
|
467
|
+
# S/U 类目标:astype 不支持字符串存储,经 array 构造重建
|
|
468
|
+
_kind = None
|
|
469
|
+
try:
|
|
470
|
+
from .__init__ import dtype as _dtype_fn
|
|
471
|
+
_kind = getattr(_dtype_fn(dtype), 'kind', None)
|
|
472
|
+
except Exception:
|
|
473
|
+
pass
|
|
474
|
+
if _kind in ('S', 'U'):
|
|
475
|
+
from .__init__ import array as _array_fn
|
|
476
|
+
try:
|
|
477
|
+
_spec = str(_dtype_fn(dtype))
|
|
478
|
+
except Exception:
|
|
479
|
+
_spec = _name
|
|
480
|
+
# 值先字符串化:rsarray 的 S-dtype 数组对数值输入保留数值占位存储,
|
|
481
|
+
# 不转会让 out 路径与 dtype 路径(真字符串)不一致
|
|
482
|
+
try:
|
|
483
|
+
_flat = res.tolist()
|
|
484
|
+
if not isinstance(_flat, list):
|
|
485
|
+
_flat = [_flat]
|
|
486
|
+
|
|
487
|
+
def _flatten_all(x):
|
|
488
|
+
out = []
|
|
489
|
+
for v in x:
|
|
490
|
+
if isinstance(v, list):
|
|
491
|
+
out.extend(_flatten_all(v))
|
|
492
|
+
else:
|
|
493
|
+
out.append(v)
|
|
494
|
+
return out
|
|
495
|
+
|
|
496
|
+
_flat = _flatten_all(_flat)
|
|
497
|
+
return _array_fn([str(v) for v in _flat], dtype=_spec)
|
|
498
|
+
except Exception:
|
|
499
|
+
return _array_fn(res.tolist(), dtype=_spec)
|
|
500
|
+
res = res.astype(_name)
|
|
501
|
+
try:
|
|
502
|
+
from .__init__ import dtype as _dtype_fn
|
|
503
|
+
import rsarray._dtypes as _dts
|
|
504
|
+
_dbo = getattr(_dtype_fn(dtype), 'byteorder', None)
|
|
505
|
+
if isinstance(_dbo, str) and _dbo not in ('|', '=', '@', 'n', 'native'):
|
|
506
|
+
_d = _dts.DType(_name)
|
|
507
|
+
res._dtype_obj = _dts._clone_with_byteorder(_d, _dbo)
|
|
508
|
+
elif _name == 'complex64' and str(getattr(res, '_dtype', '')) != 'complex64':
|
|
509
|
+
# astype 复数路径强制 complex128 标签;按 np.array 语义重挂 complex64
|
|
510
|
+
res._dtype = 'complex64'
|
|
511
|
+
except Exception:
|
|
512
|
+
pass
|
|
513
|
+
return res
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _check_cast_allowed(arr_list, dtype, casting):
|
|
517
|
+
"""casting 语义:non-unsafe 转换需 can_cast 许可,否则 TypeError。
|
|
518
|
+
|
|
519
|
+
检查**所有**输入数组(不止第一个)——如 stack((int, float),
|
|
520
|
+
dtype=int64, casting='safe') 必须因 float→int64 被拒。arr_list 可传单个
|
|
521
|
+
数组或数组列表。"""
|
|
522
|
+
if casting == "unsafe" or casting is None:
|
|
523
|
+
return
|
|
524
|
+
try:
|
|
525
|
+
from .__init__ import dtype as _dtype_fn, can_cast as _can_cast
|
|
526
|
+
_dst_dt = _dtype_fn(dtype)
|
|
527
|
+
_dst = _dst_dt.name
|
|
528
|
+
_srcs = arr_list if isinstance(arr_list, (builtins.list, builtins.tuple)) \
|
|
529
|
+
else [arr_list]
|
|
530
|
+
# 纯 Python 标量走 copyto 标量语义(pyscalar casting),不参与 can_cast
|
|
531
|
+
for _arr in _srcs:
|
|
532
|
+
if not hasattr(_arr, '_dtype'):
|
|
533
|
+
continue
|
|
534
|
+
_src = getattr(_arr, '_dtype', 'float64')
|
|
535
|
+
if _src in ('object', 'O'):
|
|
536
|
+
continue # object 数组可自由转换(数组语义)
|
|
537
|
+
try:
|
|
538
|
+
_src_kind = getattr(_dtype_fn(_src), 'kind', None)
|
|
539
|
+
except Exception:
|
|
540
|
+
_src_kind = None
|
|
541
|
+
if _src_kind in ('S', 'U') and getattr(_dst_dt, 'kind', None) in ('S', 'U'):
|
|
542
|
+
continue # 字符串类别间转换自由(string_→U5 等名称差异不算降级)
|
|
543
|
+
# 传 DType 实例(保留字节序):'no' 模式须字节序敏感(f8→>f8 拒)
|
|
544
|
+
if not _can_cast(_src, _dst_dt, casting=casting):
|
|
545
|
+
raise TypeError(
|
|
546
|
+
f"Cannot cast array data from dtype('{_src}') to "
|
|
547
|
+
f"dtype('{_dst}') according to the rule '{casting}'")
|
|
548
|
+
except TypeError:
|
|
549
|
+
raise
|
|
550
|
+
except Exception:
|
|
551
|
+
pass
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def _dtype_name(dtype):
|
|
555
|
+
"""把 dtype 参数解析为 dtype 名字符串(np.float32 类/DType 实例/字符串)。"""
|
|
556
|
+
from .__init__ import dtype as _dtype_fn
|
|
557
|
+
try:
|
|
558
|
+
return _dtype_fn(dtype).name
|
|
559
|
+
except Exception:
|
|
560
|
+
return builtins.str(dtype)
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def _str_parses(s):
|
|
564
|
+
"""字符串能否解析为数值(copyto 宽松转换的前置判定)。"""
|
|
565
|
+
try:
|
|
566
|
+
builtins.float(s)
|
|
567
|
+
return True
|
|
568
|
+
except Exception:
|
|
569
|
+
return False
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
def _out_dtype_of(out):
|
|
573
|
+
"""取 out 数组的富 dtype(_dtype_obj 优先,否则存储标签)。"""
|
|
574
|
+
dt = getattr(out, '_dtype_obj', None)
|
|
575
|
+
if dt is None:
|
|
576
|
+
dt = getattr(out, '_dtype', 'float64')
|
|
577
|
+
return dt
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def _finalize_out(res, out, arr_list, casting):
|
|
581
|
+
"""stack 家族与 concatenate 共用的 out= 收尾:
|
|
582
|
+
① casting 许可检查(TypeError);② 写入前按 out.dtype 精度转换
|
|
583
|
+
(如 f32 舍入);③ S/U 类字符串 out 经 _raw_data 直搬(浮点 setitem
|
|
584
|
+
写不进字符串占位存储);④ out 与 dtype 同传由调用方先行抛 TypeError。"""
|
|
585
|
+
_out_dt = _out_dtype_of(out)
|
|
586
|
+
if not hasattr(_out_dt, 'kind') and _out_dt in ('string_', 'bytes_'):
|
|
587
|
+
# 字符串数组构造(_string_filled)只带 _str_dtype 宽度信息:
|
|
588
|
+
# 还原显式 spec(('S',4)→'S4'),避免裸 'string_' 探出 S3
|
|
589
|
+
_sd = getattr(out, '_str_dtype', None)
|
|
590
|
+
if _sd and _sd[0] in ('S', 'U') and isinstance(_sd[1], int):
|
|
591
|
+
_out_dt = f'{_sd[0]}{_sd[1]}'
|
|
592
|
+
_check_cast_allowed(arr_list, _out_dt, casting)
|
|
593
|
+
# 数组语义:out 形状与结果不一致 → ValueError(不可静默吞掉)
|
|
594
|
+
try:
|
|
595
|
+
_res_shape = builtins.tuple(res.shape)
|
|
596
|
+
except Exception:
|
|
597
|
+
_res_shape = None
|
|
598
|
+
if _res_shape is not None \
|
|
599
|
+
and builtins.tuple(out.shape) != _res_shape:
|
|
600
|
+
raise ValueError(
|
|
601
|
+
f"output array is not the expected shape "
|
|
602
|
+
f"{_res_shape}, got {builtins.tuple(out.shape)}")
|
|
603
|
+
try:
|
|
604
|
+
res = _apply_dtype(res, _out_dt)
|
|
605
|
+
except Exception:
|
|
606
|
+
pass
|
|
607
|
+
_handled = False
|
|
608
|
+
try:
|
|
609
|
+
from .__init__ import dtype as _dtype_fn
|
|
610
|
+
if getattr(_dtype_fn(_out_dt), 'kind', None) in ('S', 'U'):
|
|
611
|
+
_vals = getattr(res, '_raw_data', None)
|
|
612
|
+
if _vals is not None:
|
|
613
|
+
out._raw_data = list(_vals)
|
|
614
|
+
out._str_dtype = getattr(res, '_str_dtype', None)
|
|
615
|
+
_handled = True
|
|
616
|
+
except Exception:
|
|
617
|
+
_handled = False
|
|
618
|
+
if not _handled:
|
|
619
|
+
try:
|
|
620
|
+
out[...] = res
|
|
621
|
+
except Exception:
|
|
622
|
+
pass
|
|
623
|
+
return out
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def concatenate(arrays, axis=0, out=None, dtype=None, casting="same_kind"):
|
|
627
|
+
"""沿着指定轴连接数组(支持 数组的 out/dtype 参数)。"""
|
|
628
|
+
_check_casting(casting)
|
|
629
|
+
if out is not None and dtype is not None:
|
|
630
|
+
raise TypeError(
|
|
631
|
+
"concatenate() only takes `out` or `dtype` as an argument, "
|
|
632
|
+
"not both")
|
|
633
|
+
# 子数组 dtype(如 '(2,)i',DType 解析为 kind 'V' + shape)不支持拼接
|
|
634
|
+
if dtype is not None:
|
|
635
|
+
try:
|
|
636
|
+
from .__init__ import dtype as _dtype_fn
|
|
637
|
+
_pdt = _dtype_fn(dtype)
|
|
638
|
+
if getattr(_pdt, 'kind', None) == 'V' \
|
|
639
|
+
and builtins.tuple(getattr(_pdt, 'shape', ()) or ()):
|
|
640
|
+
raise TypeError(
|
|
641
|
+
f"concatenate() does not support subarray dtype "
|
|
642
|
+
f"{builtins.str(dtype)!r}")
|
|
643
|
+
except TypeError:
|
|
644
|
+
raise
|
|
645
|
+
except Exception:
|
|
646
|
+
pass
|
|
647
|
+
# 数组语义:len 超过 intc 上限须在迭代(访问任何元素)之前抛
|
|
648
|
+
try:
|
|
649
|
+
_max_intc = (1 << 31) - 1
|
|
650
|
+
_arr_len = builtins.len(arrays)
|
|
651
|
+
if _arr_len > _max_intc:
|
|
652
|
+
raise ValueError(
|
|
653
|
+
f"concatenate() only supports up to {_max_intc} arrays "
|
|
654
|
+
f"but got {_arr_len}.")
|
|
655
|
+
except ValueError:
|
|
656
|
+
raise
|
|
657
|
+
except Exception:
|
|
658
|
+
pass
|
|
659
|
+
arr_list = list(arrays)
|
|
660
|
+
if not arr_list:
|
|
661
|
+
raise ValueError("concatenate requires at least one array")
|
|
662
|
+
first = _as_data(arr_list[0])
|
|
663
|
+
# S/U 目标 dtype:Rust concatenate 不支持字符串存储,改走 Python
|
|
664
|
+
# 字符串重建。数组语义:裸 'S'/'U' 的宽度 = double 转字符串的宽度
|
|
665
|
+
# (测试注释 "identical to a cast (of a double array)" → 'S3'),
|
|
666
|
+
# 显式宽度('S0'/'S4')直接用(np.array 自带截断)。
|
|
667
|
+
_su_spec = None
|
|
668
|
+
_su_zero_width = False
|
|
669
|
+
if dtype is not None:
|
|
670
|
+
try:
|
|
671
|
+
from .__init__ import dtype as _dtype_fn
|
|
672
|
+
_pd = _dtype_fn(dtype)
|
|
673
|
+
if getattr(_pd, 'kind', None) in ('S', 'U'):
|
|
674
|
+
_su_spec = str(dtype)
|
|
675
|
+
_kind = getattr(_pd, 'kind', None)
|
|
676
|
+
_its = getattr(_pd, 'itemsize', None)
|
|
677
|
+
# DType 实例带宽度(S4 itemsize=4 / U5 itemsize=20=5×4)→
|
|
678
|
+
# 还原显式宽度 spec,避免裸 'string_' 语义探出 S3
|
|
679
|
+
if isinstance(_its, int) and _its > 0:
|
|
680
|
+
if _kind == 'S':
|
|
681
|
+
_su_spec = f'S{_its}'
|
|
682
|
+
elif _kind == 'U' and _its % 4 == 0:
|
|
683
|
+
_su_spec = f'U{_its // 4}'
|
|
684
|
+
# 裸 'S'/'U' 与零宽度 'S0'/'U0' 同规:宽度 = double 转字符串
|
|
685
|
+
# 的宽度(测试语义 "identical to a cast of a double
|
|
686
|
+
# array" → 'S3'),而非按数据推断
|
|
687
|
+
if _su_spec.lstrip('<>|=')[1:] in ('', '0'):
|
|
688
|
+
_su_zero_width = True
|
|
689
|
+
from .__init__ import array as _array_fn
|
|
690
|
+
_probe = _array_fn([1.0], dtype=_su_spec)
|
|
691
|
+
_su_spec = str(_probe.dtype)
|
|
692
|
+
except Exception:
|
|
693
|
+
_su_spec = None
|
|
694
|
+
if _su_spec is not None:
|
|
695
|
+
from .__init__ import array as _array_fn
|
|
696
|
+
# casting 检查先行(如 no/equiv/safe 下 float64→S4 必须 TypeError);
|
|
697
|
+
# 零宽度目标豁免——对裸 'U'/'S' 的数值→字符串转换按 safe 对待
|
|
698
|
+
if not _su_zero_width:
|
|
699
|
+
_check_cast_allowed(arr_list, dtype, casting)
|
|
700
|
+
_vals = []
|
|
701
|
+
|
|
702
|
+
def _flatten_all(x):
|
|
703
|
+
out = []
|
|
704
|
+
for v in x:
|
|
705
|
+
if isinstance(v, list):
|
|
706
|
+
out.extend(_flatten_all(v))
|
|
707
|
+
else:
|
|
708
|
+
out.append(v)
|
|
709
|
+
return out
|
|
710
|
+
|
|
711
|
+
for a in arr_list:
|
|
712
|
+
if isinstance(a, (builtins.list, builtins.tuple)):
|
|
713
|
+
# Python list 元素保留原始值(int 0 → '0' 而非数值化 '0.0')
|
|
714
|
+
_vals.extend(_flatten_all(builtins.list(a)))
|
|
715
|
+
continue
|
|
716
|
+
arr = a if hasattr(a, '_array') else _wrap(a)
|
|
717
|
+
_t = arr.tolist()
|
|
718
|
+
_vals.extend(_flatten_all(_t) if isinstance(_t, list) else [_t])
|
|
719
|
+
# 数组语义:dtype='S' 不检查/字符串化 None → TypeError
|
|
720
|
+
if builtins.any(v is None for v in _vals):
|
|
721
|
+
raise TypeError(
|
|
722
|
+
"cannot concatenate None values with a string dtype")
|
|
723
|
+
_strs = [str(v) for v in _vals]
|
|
724
|
+
return _array_fn(_strs, dtype=_su_spec)
|
|
725
|
+
nd = _nd()
|
|
726
|
+
_dt = dtype if dtype is not None else getattr(first, '_dtype', "float64")
|
|
727
|
+
# 数组语义:0-d 数组不能直接拼接("Scalars cannot be concatenated")
|
|
728
|
+
if axis is not None and builtins.any(
|
|
729
|
+
(hasattr(a, '_array') and getattr(a, 'ndim', 0) == 0)
|
|
730
|
+
or (not hasattr(a, '_array') and not isinstance(
|
|
731
|
+
a, (builtins.list, builtins.tuple, builtins.str)))
|
|
732
|
+
for a in arr_list):
|
|
733
|
+
raise ValueError("zero-dimensional arraylets cannot be concatenated")
|
|
734
|
+
# 数组语义:ndim 不一致时报 "all the input arrays must have same
|
|
735
|
+
# number of dimensions..."(Rust 层只有笼统的 incompatible shapes)
|
|
736
|
+
if axis is not None:
|
|
737
|
+
_ndims = [getattr(_as_data(_a), 'ndim', 0) for _a in arr_list]
|
|
738
|
+
if _ndims and builtins.len(builtins.set(_ndims)) > 1:
|
|
739
|
+
_i1 = builtins.next(
|
|
740
|
+
(i for i, d in builtins.enumerate(_ndims) if d != _ndims[0]), 1)
|
|
741
|
+
raise ValueError(
|
|
742
|
+
"all the input arrays must have same number of dimensions, "
|
|
743
|
+
f"but the array at index 0 has {_ndims[0]} dimension(s) "
|
|
744
|
+
f"and the array at index {_i1} has {_ndims[_i1]} dimension(s)")
|
|
745
|
+
# 同 ndim 但拼接轴外维度尺寸不一致 → 格式消息
|
|
746
|
+
if axis is not None and _ndims and builtins.len(
|
|
747
|
+
builtins.set(_ndims)) == 1:
|
|
748
|
+
_ax = axis % max(_ndims[0], 1)
|
|
749
|
+
_shapes = [
|
|
750
|
+
builtins.tuple(_as_data(_a).shape)
|
|
751
|
+
for _a in arr_list]
|
|
752
|
+
for _i in range(1, builtins.len(_shapes)):
|
|
753
|
+
for _d in range(_ndims[0]):
|
|
754
|
+
if _d == _ax:
|
|
755
|
+
continue
|
|
756
|
+
if _shapes[_i][_d] != _shapes[0][_d]:
|
|
757
|
+
raise ValueError(
|
|
758
|
+
"all the input array dimensions except for the "
|
|
759
|
+
"concatenation axis must match exactly, but along "
|
|
760
|
+
f"dimension {_d}, the array at index 0 has size "
|
|
761
|
+
f"{_shapes[0][_d]} and the array at index {_i} "
|
|
762
|
+
f"has size {_shapes[_i][_d]}")
|
|
763
|
+
# 负 axis 归一化:越界直达 Rust 会 abort,须在 Python 边界校验
|
|
764
|
+
if axis is not None:
|
|
765
|
+
from .exceptions import AxisError
|
|
766
|
+
_first_ndim = getattr(first, 'ndim', 0)
|
|
767
|
+
if axis < 0:
|
|
768
|
+
axis += _first_ndim
|
|
769
|
+
if not 0 <= axis < _first_ndim:
|
|
770
|
+
raise AxisError(
|
|
771
|
+
f'axis {axis} is out of bounds for array of '
|
|
772
|
+
f'dimension {_first_ndim}')
|
|
773
|
+
# copyto 语义对齐:str 标量元素按宽松转换(无法解析按 0),
|
|
774
|
+
# 与 np.copyto(dst, 'x', casting=...) 成功的行为一致
|
|
775
|
+
if builtins.any(isinstance(a, builtins.str) for a in arr_list):
|
|
776
|
+
arr_list = [
|
|
777
|
+
(builtins.float(a) if _str_parses(a) else 0.0)
|
|
778
|
+
if isinstance(a, builtins.str) else a
|
|
779
|
+
for a in arr_list
|
|
780
|
+
]
|
|
781
|
+
# 数组语义:pyscalar 越界(如 300→int8、2**64→int64)构造时抛
|
|
782
|
+
# OverflowError——仅在无显式 dtype= 时(目标由输入推断);显式 dtype=
|
|
783
|
+
# 时标量走 copyto 宽松语义(wrap,不抛)。first 为标量时推断出
|
|
784
|
+
# float64 不可信,out 的 dtype 也参与检查。
|
|
785
|
+
if dtype is None and casting != "unsafe":
|
|
786
|
+
try:
|
|
787
|
+
from .__init__ import _INT_RANGES, dtype as _dtype_fn
|
|
788
|
+
_tgt_candidates = [_dt]
|
|
789
|
+
if out is not None:
|
|
790
|
+
_tgt_candidates.append(_out_dtype_of(out))
|
|
791
|
+
for _tgt_dt in _tgt_candidates:
|
|
792
|
+
_tgt_name = getattr(_dtype_fn(_tgt_dt), 'name', None) \
|
|
793
|
+
if not isinstance(_tgt_dt, str) else _tgt_dt
|
|
794
|
+
if _tgt_name not in _INT_RANGES:
|
|
795
|
+
continue
|
|
796
|
+
_lo, _hi = _INT_RANGES[_tgt_name]
|
|
797
|
+
for _a in arr_list:
|
|
798
|
+
if isinstance(_a, builtins.int) \
|
|
799
|
+
and not isinstance(_a, builtins.bool) \
|
|
800
|
+
and not (_lo <= _a <= _hi):
|
|
801
|
+
raise OverflowError(
|
|
802
|
+
f"Python int too large to convert to {_tgt_name}")
|
|
803
|
+
except OverflowError:
|
|
804
|
+
raise
|
|
805
|
+
except Exception:
|
|
806
|
+
pass
|
|
807
|
+
fields = getattr(first, '_fields', None)
|
|
808
|
+
raw_data = getattr(first, '_raw_data', None)
|
|
809
|
+
raw_list = [_ensure_raw(a) for a in arr_list]
|
|
810
|
+
if axis is None:
|
|
811
|
+
# 数组语义:axis=None 时各数组展平后做一维拼接
|
|
812
|
+
flat_list = []
|
|
813
|
+
for a in arr_list:
|
|
814
|
+
arr = _as_data(a)
|
|
815
|
+
flat_list.append(_ensure_raw(arr.reshape((arr.size,))))
|
|
816
|
+
result = _core.concatenate(flat_list, 0)
|
|
817
|
+
else:
|
|
818
|
+
result = _core.concatenate(raw_list, axis)
|
|
819
|
+
res = nd._wrap(result, _dtype=getattr(first, '_dtype', "float64"),
|
|
820
|
+
_fields=fields, _raw_data=raw_data)
|
|
821
|
+
if dtype is not None:
|
|
822
|
+
_check_cast_allowed(arr_list, dtype, casting)
|
|
823
|
+
res = _apply_dtype(res, dtype)
|
|
824
|
+
if out is not None:
|
|
825
|
+
return _finalize_out(res, out, arr_list, casting)
|
|
826
|
+
return res
|
|
827
|
+
|
|
828
|
+
|
|
829
|
+
# 数组的 __array_function__ dispatcher 会访问 ._implementation 直调实现
|
|
830
|
+
concatenate._implementation = concatenate
|
|
831
|
+
|
|
832
|
+
|
|
833
|
+
def stack(arrays, axis=0, out=None, dtype=None, casting="same_kind"):
|
|
834
|
+
"""沿着新轴堆叠数组(支持 数组的 out/dtype 参数)。"""
|
|
835
|
+
_check_casting(casting)
|
|
836
|
+
if out is not None and dtype is not None:
|
|
837
|
+
raise TypeError(
|
|
838
|
+
"stack() only takes `out` or `dtype` as an argument, not both")
|
|
839
|
+
# 数组语义:ndarray 本身是合法序列(按其元素堆叠);标量/生成器拒绝
|
|
840
|
+
if not isinstance(arrays, (builtins.list, builtins.tuple)) \
|
|
841
|
+
and not hasattr(arrays, '_array'):
|
|
842
|
+
raise TypeError(
|
|
843
|
+
f"arrays to stack must be array_like sequences, not "
|
|
844
|
+
f"{builtins.type(arrays).__name__}")
|
|
845
|
+
arr_list = list(arrays)
|
|
846
|
+
if not arr_list:
|
|
847
|
+
raise ValueError("need at least one array to stack")
|
|
848
|
+
first = _as_data(arr_list[0])
|
|
849
|
+
nd = _nd()
|
|
850
|
+
_dt0 = getattr(first, '_dtype', "float64")
|
|
851
|
+
fields = getattr(first, '_fields', None)
|
|
852
|
+
raw_data = getattr(first, '_raw_data', None)
|
|
853
|
+
raw_list = [_ensure_raw(a) for a in arr_list]
|
|
854
|
+
# axis 归一化与越界校验(越界直接传 Rust 会 abort,不可捕获):
|
|
855
|
+
# 允许 axis ∈ [-(nd+1), nd],结果 ndim = 输入 nd+1
|
|
856
|
+
from .exceptions import AxisError
|
|
857
|
+
_in_ndim = getattr(first, 'ndim', 0)
|
|
858
|
+
if axis < 0:
|
|
859
|
+
axis += _in_ndim + 1
|
|
860
|
+
if not 0 <= axis <= _in_ndim:
|
|
861
|
+
raise AxisError(f'axis {axis} is out of bounds for array of '
|
|
862
|
+
f'dimension {_in_ndim + 1}')
|
|
863
|
+
result = _core.stack(raw_list, axis)
|
|
864
|
+
res = nd._wrap(result, _dtype=_dt0, _fields=fields, _raw_data=raw_data)
|
|
865
|
+
if dtype is not None:
|
|
866
|
+
_check_cast_allowed(arr_list, dtype, casting)
|
|
867
|
+
res = _apply_dtype(res, dtype)
|
|
868
|
+
if out is not None:
|
|
869
|
+
return _finalize_out(res, out, arr_list, casting)
|
|
870
|
+
return res
|
|
871
|
+
|
|
872
|
+
|
|
873
|
+
def vstack(arrays, out=None, dtype=None, casting="same_kind"):
|
|
874
|
+
"""垂直堆叠数组(沿行)。"""
|
|
875
|
+
_check_casting(casting)
|
|
876
|
+
if out is not None and dtype is not None:
|
|
877
|
+
raise TypeError(
|
|
878
|
+
"vstack() only takes `out` or `dtype` as an argument, not both")
|
|
879
|
+
# 数组语义:ndarray 本身是合法序列;标量/生成器拒绝
|
|
880
|
+
if not isinstance(arrays, (builtins.list, builtins.tuple)) \
|
|
881
|
+
and not hasattr(arrays, '_array'):
|
|
882
|
+
raise TypeError(
|
|
883
|
+
f"arrays to stack must be array_like sequences, not "
|
|
884
|
+
f"{builtins.type(arrays).__name__}")
|
|
885
|
+
arr_list = list(arrays)
|
|
886
|
+
if not arr_list:
|
|
887
|
+
raise ValueError("vstack requires at least one array")
|
|
888
|
+
# 数组语义:0-d 数组先按 (1,) 展平再堆叠
|
|
889
|
+
for _i, _a in builtins.enumerate(arr_list):
|
|
890
|
+
if hasattr(_a, '_array') and getattr(_a, 'ndim', 0) == 0:
|
|
891
|
+
arr_list[_i] = _a.reshape((1,))
|
|
892
|
+
first = _as_data(arr_list[0])
|
|
893
|
+
nd = _nd()
|
|
894
|
+
dtype0 = getattr(first, '_dtype', "float64")
|
|
895
|
+
fields = getattr(first, '_fields', None)
|
|
896
|
+
raw_data = getattr(first, '_raw_data', None)
|
|
897
|
+
raw_list = [_ensure_raw(a) for a in arr_list]
|
|
898
|
+
result = _core.vstack(raw_list)
|
|
899
|
+
res = nd._wrap(result, _dtype=dtype0, _fields=fields, _raw_data=raw_data)
|
|
900
|
+
if dtype is not None:
|
|
901
|
+
_check_cast_allowed(arr_list, dtype, casting)
|
|
902
|
+
res = _apply_dtype(res, dtype)
|
|
903
|
+
if out is not None:
|
|
904
|
+
return _finalize_out(res, out, arr_list, casting)
|
|
905
|
+
return res
|
|
906
|
+
|
|
907
|
+
|
|
908
|
+
def hstack(arrays, out=None, dtype=None, casting="same_kind"):
|
|
909
|
+
"""水平堆叠数组(沿列)。"""
|
|
910
|
+
_check_casting(casting)
|
|
911
|
+
if out is not None and dtype is not None:
|
|
912
|
+
raise TypeError(
|
|
913
|
+
"hstack() only takes `out` or `dtype` as an argument, not both")
|
|
914
|
+
# 数组语义:ndarray 本身是合法序列;标量/生成器拒绝
|
|
915
|
+
if not isinstance(arrays, (builtins.list, builtins.tuple)) \
|
|
916
|
+
and not hasattr(arrays, '_array'):
|
|
917
|
+
raise TypeError(
|
|
918
|
+
f"arrays to stack must be array_like sequences, not "
|
|
919
|
+
f"{builtins.type(arrays).__name__}")
|
|
920
|
+
arr_list = list(arrays)
|
|
921
|
+
if not arr_list:
|
|
922
|
+
raise ValueError("hstack requires at least one array")
|
|
923
|
+
# 数组语义:0-d 数组先按 (1,) 展平再堆叠
|
|
924
|
+
for _i, _a in builtins.enumerate(arr_list):
|
|
925
|
+
if hasattr(_a, '_array') and getattr(_a, 'ndim', 0) == 0:
|
|
926
|
+
arr_list[_i] = _a.reshape((1,))
|
|
927
|
+
first = _as_data(arr_list[0])
|
|
928
|
+
nd = _nd()
|
|
929
|
+
dtype0 = getattr(first, '_dtype', "float64")
|
|
930
|
+
fields = getattr(first, '_fields', None)
|
|
931
|
+
raw_data = getattr(first, '_raw_data', None)
|
|
932
|
+
raw_list = [_ensure_raw(a) for a in arr_list]
|
|
933
|
+
result = _core.hstack(raw_list)
|
|
934
|
+
res = nd._wrap(result, _dtype=dtype0, _fields=fields, _raw_data=raw_data)
|
|
935
|
+
if dtype is not None:
|
|
936
|
+
_check_cast_allowed(arr_list, dtype, casting)
|
|
937
|
+
res = _apply_dtype(res, dtype)
|
|
938
|
+
if out is not None:
|
|
939
|
+
return _finalize_out(res, out, arr_list, casting)
|
|
940
|
+
return res
|
|
941
|
+
|
|
942
|
+
|
|
943
|
+
def dstack(arrays):
|
|
944
|
+
"""沿深度方向堆叠数组(数组语义:1-D→(1,n,1)、2-D→(m,n,1) 后
|
|
945
|
+
沿新 axis=2 拼接)。"""
|
|
946
|
+
if not isinstance(arrays, (list, tuple)) and not hasattr(arrays, '_array'):
|
|
947
|
+
raise TypeError("arrays to stack must be array_like or sequences")
|
|
948
|
+
arr_list = [_ensure_raw(a) if not hasattr(a, '_array') else a
|
|
949
|
+
for a in arrays]
|
|
950
|
+
if not arr_list:
|
|
951
|
+
raise ValueError("dstack requires at least one array")
|
|
952
|
+
first = arr_list[0]
|
|
953
|
+
nd = _nd()
|
|
954
|
+
dtype = getattr(first, '_dtype', "float64")
|
|
955
|
+
fields = getattr(first, '_fields', None)
|
|
956
|
+
raw_data = getattr(first, '_raw_data', None)
|
|
957
|
+
# 数组语义:先统一升到 3-D(避免对低维数组沿 axis=2 拼接越界)
|
|
958
|
+
lifted = []
|
|
959
|
+
for a in arr_list:
|
|
960
|
+
sh = tuple(a.shape)
|
|
961
|
+
if len(sh) == 1:
|
|
962
|
+
a = a.reshape((1,) + sh + (1,))
|
|
963
|
+
elif len(sh) == 2:
|
|
964
|
+
a = a.reshape(sh + (1,))
|
|
965
|
+
elif len(sh) == 0:
|
|
966
|
+
a = a.reshape((1, 1, 1))
|
|
967
|
+
lifted.append(a)
|
|
968
|
+
result = _core.concatenate([_ensure_raw(a) for a in lifted], 2)
|
|
969
|
+
return nd._wrap(result, _dtype=dtype, _fields=fields, _raw_data=raw_data)
|
|
970
|
+
|
|
971
|
+
|
|
972
|
+
def column_stack(arrays):
|
|
973
|
+
"""将 1-D 数组作为列堆叠成 2-D 数组。"""
|
|
974
|
+
if not isinstance(arrays, (list, tuple)) and not hasattr(arrays, '_array'):
|
|
975
|
+
raise TypeError("arrays to stack must be array_like or sequences")
|
|
976
|
+
arr_list = list(arrays)
|
|
977
|
+
if not arr_list:
|
|
978
|
+
raise ValueError("column_stack requires at least one array")
|
|
979
|
+
first = arr_list[0] if hasattr(arr_list[0], '_array') else _wrap(arr_list[0])
|
|
980
|
+
nd = _nd()
|
|
981
|
+
dtype = getattr(first, '_dtype', "float64")
|
|
982
|
+
fields = getattr(first, '_fields', None)
|
|
983
|
+
raw_data = getattr(first, '_raw_data', None)
|
|
984
|
+
raw_list = [_ensure_raw(a) for a in arr_list]
|
|
985
|
+
result = _core.column_stack(raw_list)
|
|
986
|
+
return nd._wrap(result, _dtype=dtype, _fields=fields, _raw_data=raw_data)
|
|
987
|
+
|
|
988
|
+
|
|
989
|
+
def split(ary, indices_or_sections, axis=0):
|
|
990
|
+
"""将数组拆分为多个子数组(使用 Rust 实现)。"""
|
|
991
|
+
arr = ary if hasattr(ary, '_array') else _wrap(ary)
|
|
992
|
+
# 数组语义:整数份数不能整除该轴长度时抛 ValueError
|
|
993
|
+
if isinstance(indices_or_sections, (int, builtins.int)) and not isinstance(indices_or_sections, bool):
|
|
994
|
+
axis_len = arr.shape[axis] if arr.ndim > axis else 0
|
|
995
|
+
if axis_len % indices_or_sections != 0:
|
|
996
|
+
raise ValueError(
|
|
997
|
+
"array split does not result in an equal division")
|
|
998
|
+
nd = _nd()
|
|
999
|
+
dtype = getattr(arr, '_dtype', "float64")
|
|
1000
|
+
fields = getattr(arr, '_fields', None)
|
|
1001
|
+
raw_data = getattr(arr, '_raw_data', None)
|
|
1002
|
+
result_raw = _core.split_rs(arr._array, indices_or_sections, axis)
|
|
1003
|
+
return [nd._wrap(r, _dtype=dtype, _fields=fields, _raw_data=raw_data) for r in result_raw]
|
|
1004
|
+
|
|
1005
|
+
|
|
1006
|
+
def hsplit(ary, indices_or_sections):
|
|
1007
|
+
"""水平拆分数组(数组语义:1-D 数组沿唯一轴 axis=0 拆)。"""
|
|
1008
|
+
arr = ary if hasattr(ary, '_array') else _wrap(ary)
|
|
1009
|
+
if arr.ndim == 1:
|
|
1010
|
+
return split(ary, indices_or_sections, axis=0)
|
|
1011
|
+
return split(ary, indices_or_sections, axis=1)
|
|
1012
|
+
|
|
1013
|
+
|
|
1014
|
+
def vsplit(ary, indices_or_sections):
|
|
1015
|
+
"""垂直拆分数组(数组语义:1-D 数组无轴 1,抛 ValueError)。"""
|
|
1016
|
+
arr = ary if hasattr(ary, '_array') else _wrap(ary)
|
|
1017
|
+
if arr.ndim < 2:
|
|
1018
|
+
raise ValueError(
|
|
1019
|
+
"vsplit only works on arrays of 2 or more dimensions")
|
|
1020
|
+
return split(ary, indices_or_sections, axis=0)
|
|
1021
|
+
|
|
1022
|
+
|
|
1023
|
+
def dsplit(ary, indices_or_sections):
|
|
1024
|
+
"""沿深度拆分数组。"""
|
|
1025
|
+
return split(ary, indices_or_sections, axis=2)
|
|
1026
|
+
|
|
1027
|
+
|
|
1028
|
+
def tile(A, reps):
|
|
1029
|
+
"""重复数组(数组语义:reps 短于 ndim 时前置补 1,即沿末轴重复;
|
|
1030
|
+
长于 ndim 时前导补新轴)。"""
|
|
1031
|
+
arr = A if hasattr(A, '_array') else _wrap(A)
|
|
1032
|
+
if isinstance(reps, int) or _scalar_idx(reps):
|
|
1033
|
+
reps = [int(reps)]
|
|
1034
|
+
reps = [int(r) for r in reps]
|
|
1035
|
+
sh = tuple(arr.shape)
|
|
1036
|
+
nd = len(sh)
|
|
1037
|
+
if len(reps) < nd:
|
|
1038
|
+
reps = [1] * (nd - len(reps)) + reps
|
|
1039
|
+
out = arr
|
|
1040
|
+
if len(reps) > nd:
|
|
1041
|
+
out = out.reshape((1,) * (len(reps) - nd) + sh)
|
|
1042
|
+
nd = len(reps)
|
|
1043
|
+
# 空数组:直接构造目标形状的空结果
|
|
1044
|
+
if getattr(arr, 'size', 0) == 0:
|
|
1045
|
+
new_sh = tuple(r * s for r, s in zip(reps, tuple(out.shape)))
|
|
1046
|
+
return _np().zeros(new_sh, dtype=getattr(arr, '_dtype', None) or 'float64')
|
|
1047
|
+
for i, r in enumerate(reps):
|
|
1048
|
+
if r == 1:
|
|
1049
|
+
continue
|
|
1050
|
+
if r == 0:
|
|
1051
|
+
sl = [slice(None)] * nd
|
|
1052
|
+
sl[i] = slice(0, 0)
|
|
1053
|
+
out = out[tuple(sl)]
|
|
1054
|
+
else:
|
|
1055
|
+
out = _np().concatenate([out] * r, axis=i)
|
|
1056
|
+
return _wrap(_ensure_raw(out))
|
|
1057
|
+
|
|
1058
|
+
|
|
1059
|
+
def repeat(a, repeats, axis=None):
|
|
1060
|
+
"""重复数组元素。"""
|
|
1061
|
+
arr = a if hasattr(a, '_array') else _wrap(a)
|
|
1062
|
+
return arr.repeat(repeats, axis)
|
|
1063
|
+
|
|
1064
|
+
|
|
1065
|
+
def flip(m, axis=None):
|
|
1066
|
+
"""沿指定轴翻转数组。"""
|
|
1067
|
+
arr = m if hasattr(m, '_array') else _wrap(m)
|
|
1068
|
+
return _wrap(_core.flip(_ensure_raw(arr), axis))
|
|
1069
|
+
|
|
1070
|
+
|
|
1071
|
+
def fliplr(m):
|
|
1072
|
+
"""左右翻转数组(axis=1,需 ndim>=2;否则对齐 AxisError 抛 ValueError)。"""
|
|
1073
|
+
if hasattr(m, 'ndim') and m.ndim < 2:
|
|
1074
|
+
raise ValueError(
|
|
1075
|
+
f"axis 1 is out of bounds for array of dimension {m.ndim}")
|
|
1076
|
+
return flip(m, axis=1)
|
|
1077
|
+
|
|
1078
|
+
|
|
1079
|
+
def flipud(m):
|
|
1080
|
+
"""上下翻转数组。"""
|
|
1081
|
+
return flip(m, axis=0)
|
|
1082
|
+
|
|
1083
|
+
|
|
1084
|
+
def roll(a, shift, axis=None):
|
|
1085
|
+
"""沿指定轴滚动数组(数组语义)。
|
|
1086
|
+
|
|
1087
|
+
axis=None:滚动整个展平数组;axis 为 list/tuple:各轴独立滚动
|
|
1088
|
+
(shift 可为标量广播或等长 tuple)。标量 shift 先在 Python 层按
|
|
1089
|
+
size 取模(size 是各轴长度的公倍数,(s % size) % len_i == s % len_i),
|
|
1090
|
+
规避 Rust 侧 Python 大整数 / uint64(>2^63) 转 C long 的溢出。
|
|
1091
|
+
"""
|
|
1092
|
+
arr = a if hasattr(a, '_array') else _wrap(a)
|
|
1093
|
+
# 空数组 roll 是恒等映射:Rust 侧 shift % 0 会 panic(除零)。
|
|
1094
|
+
if getattr(arr, 'size', 0) == 0:
|
|
1095
|
+
return arr.copy()
|
|
1096
|
+
|
|
1097
|
+
def _to_int(v):
|
|
1098
|
+
return int(v) if (isinstance(v, int) or _scalar_idx(v)) else v
|
|
1099
|
+
|
|
1100
|
+
if isinstance(axis, (list, tuple)):
|
|
1101
|
+
axes = [_to_int(x) % arr.ndim for x in axis]
|
|
1102
|
+
if isinstance(shift, (list, tuple)):
|
|
1103
|
+
shifts = [_to_int(s) for s in shift]
|
|
1104
|
+
else:
|
|
1105
|
+
shifts = [_to_int(shift)] * len(axes)
|
|
1106
|
+
if len(shifts) != len(axes):
|
|
1107
|
+
raise ValueError("shift and axis must have the same length")
|
|
1108
|
+
result = arr
|
|
1109
|
+
for sh, ax in zip(shifts, axes):
|
|
1110
|
+
result = _roll_axis(result, sh, ax)
|
|
1111
|
+
return result
|
|
1112
|
+
if axis is None:
|
|
1113
|
+
# 数组语义:滚动整个展平数组
|
|
1114
|
+
flat = arr.ravel()
|
|
1115
|
+
s = _to_int(shift)
|
|
1116
|
+
if s % flat.size != 0:
|
|
1117
|
+
r = _wrap(_core.roll(_ensure_raw(flat), s % flat.size, None))
|
|
1118
|
+
return r.reshape(arr.shape)
|
|
1119
|
+
return arr.copy()
|
|
1120
|
+
return _roll_axis(arr, _to_int(shift), _to_int(axis) % arr.ndim)
|
|
1121
|
+
|
|
1122
|
+
|
|
1123
|
+
def _roll_axis(arr, shift, axis):
|
|
1124
|
+
"""沿单轴滚动(Rust 实现 + Python 层取模)。"""
|
|
1125
|
+
size = arr.size
|
|
1126
|
+
if shift % size != 0:
|
|
1127
|
+
return _wrap(_core.roll(_ensure_raw(arr), shift % size, axis))
|
|
1128
|
+
return arr.copy()
|
|
1129
|
+
|
|
1130
|
+
|
|
1131
|
+
def rot90(m, k=1, axes=(0, 1)):
|
|
1132
|
+
"""将数组旋转 90 度。"""
|
|
1133
|
+
return _wrap(_core.rot90(_ensure_raw(m), k, axes[0], axes[1]))
|
|
1134
|
+
|
|
1135
|
+
|
|
1136
|
+
def resize(a, new_shape):
|
|
1137
|
+
"""返回指定形状的新数组,数据重复填充至新形状。"""
|
|
1138
|
+
arr = a if hasattr(a, '_array') else _wrap(a)
|
|
1139
|
+
nd = _nd()
|
|
1140
|
+
dtype = getattr(arr, '_dtype', "float64")
|
|
1141
|
+
fields = getattr(arr, '_fields', None)
|
|
1142
|
+
raw_data = getattr(arr, '_raw_data', None)
|
|
1143
|
+
|
|
1144
|
+
if isinstance(new_shape, int) or _scalar_idx(new_shape):
|
|
1145
|
+
new_shape = (int(new_shape),)
|
|
1146
|
+
new_shape = [builtins.int(d) for d in new_shape]
|
|
1147
|
+
# 数组语义:负尺寸非法
|
|
1148
|
+
if builtins.any(d < 0 for d in new_shape):
|
|
1149
|
+
raise ValueError("negative dimensions are not allowed")
|
|
1150
|
+
_size = 1
|
|
1151
|
+
for d in new_shape:
|
|
1152
|
+
_size *= d
|
|
1153
|
+
if _size == 0 or getattr(arr, 'size', 0) == 0:
|
|
1154
|
+
# 目标含 0 维或源为空数组 → 零填充(数组语义)
|
|
1155
|
+
_dt = getattr(arr, 'dtype', None)
|
|
1156
|
+
result = _np().zeros(tuple(new_shape), dtype=_dt)
|
|
1157
|
+
else:
|
|
1158
|
+
result = nd._wrap(_core.resize_rs(arr._array, list(new_shape)),
|
|
1159
|
+
_dtype=dtype, _fields=fields, _raw_data=raw_data)
|
|
1160
|
+
# 数组语义:resize 保留输入的子类类型
|
|
1161
|
+
if isinstance(a, nd) and builtins.type(a) is not nd:
|
|
1162
|
+
try:
|
|
1163
|
+
result = result.view(builtins.type(a))
|
|
1164
|
+
except Exception:
|
|
1165
|
+
pass
|
|
1166
|
+
return result
|
|
1167
|
+
|
|
1168
|
+
|
|
1169
|
+
def append(arr, values, axis=None):
|
|
1170
|
+
"""将值附加到数组末尾。"""
|
|
1171
|
+
arr = arr if hasattr(arr, '_array') else _wrap(arr)
|
|
1172
|
+
values_nd = values if hasattr(values, '_array') else _wrap(values)
|
|
1173
|
+
nd = _nd()
|
|
1174
|
+
dtype = getattr(arr, '_dtype', "float64")
|
|
1175
|
+
fields = getattr(arr, '_fields', None)
|
|
1176
|
+
raw_data = getattr(arr, '_raw_data', None)
|
|
1177
|
+
if axis is None:
|
|
1178
|
+
a_flat = arr.ravel()
|
|
1179
|
+
v_flat = values_nd.ravel()
|
|
1180
|
+
return concatenate((a_flat, v_flat))
|
|
1181
|
+
raw_list = [arr._array, values_nd._array]
|
|
1182
|
+
result = _core.concatenate(raw_list, axis)
|
|
1183
|
+
return nd._wrap(result, _dtype=dtype, _fields=fields, _raw_data=raw_data)
|
|
1184
|
+
|
|
1185
|
+
|
|
1186
|
+
def delete(arr, obj, axis=None):
|
|
1187
|
+
"""删除指定位置的元素。"""
|
|
1188
|
+
arr = arr if hasattr(arr, '_array') else _wrap(arr)
|
|
1189
|
+
nd = _nd()
|
|
1190
|
+
dtype = getattr(arr, '_dtype', "float64")
|
|
1191
|
+
fields = getattr(arr, '_fields', None)
|
|
1192
|
+
raw_data = getattr(arr, '_raw_data', None)
|
|
1193
|
+
|
|
1194
|
+
if isinstance(obj, slice):
|
|
1195
|
+
start, stop, step = obj.indices(arr.size if axis is None else arr.shape[axis])
|
|
1196
|
+
obj = list(range(start, stop, step))
|
|
1197
|
+
elif isinstance(obj, int) or _scalar_idx(obj):
|
|
1198
|
+
obj = [int(obj)]
|
|
1199
|
+
obj = sorted(set(obj))
|
|
1200
|
+
|
|
1201
|
+
result = _core.delete_rs(arr._array, obj, axis)
|
|
1202
|
+
return nd._wrap(result, _dtype=dtype, _fields=fields, _raw_data=raw_data)
|
|
1203
|
+
|
|
1204
|
+
|
|
1205
|
+
def insert(arr, obj, values, axis=None):
|
|
1206
|
+
"""沿指定轴在指定下标前插入值。"""
|
|
1207
|
+
arr = arr if hasattr(arr, '_array') else _wrap(arr)
|
|
1208
|
+
nd = _nd()
|
|
1209
|
+
dtype = getattr(arr, '_dtype', "float64")
|
|
1210
|
+
fields = getattr(arr, '_fields', None)
|
|
1211
|
+
raw_data = getattr(arr, '_raw_data', None)
|
|
1212
|
+
|
|
1213
|
+
if isinstance(obj, int):
|
|
1214
|
+
obj = [obj]
|
|
1215
|
+
|
|
1216
|
+
if not hasattr(values, '_array'):
|
|
1217
|
+
if isinstance(values, (list, tuple)):
|
|
1218
|
+
values_nd = _nd()(values)
|
|
1219
|
+
else:
|
|
1220
|
+
values_nd = _nd()([values])
|
|
1221
|
+
else:
|
|
1222
|
+
values_nd = values
|
|
1223
|
+
|
|
1224
|
+
values_flat = values_nd.ravel().tolist()
|
|
1225
|
+
|
|
1226
|
+
# 检查数据中是否包含复数(即使 dtype 声明为 float64)
|
|
1227
|
+
def _contains_complex(data):
|
|
1228
|
+
"""递归检查数据中是否包含复数"""
|
|
1229
|
+
if isinstance(data, complex):
|
|
1230
|
+
return True
|
|
1231
|
+
if isinstance(data, (list, tuple)):
|
|
1232
|
+
return any(_contains_complex(x) for x in data)
|
|
1233
|
+
return False
|
|
1234
|
+
|
|
1235
|
+
# 处理复数数据:展平为 [real, imag, real, imag, ...]
|
|
1236
|
+
if dtype == 'complex128' or _contains_complex(values_flat):
|
|
1237
|
+
# 递归展平嵌套复数列表
|
|
1238
|
+
def _flatten_complex_nested(lst):
|
|
1239
|
+
result = []
|
|
1240
|
+
for x in lst:
|
|
1241
|
+
if isinstance(x, complex):
|
|
1242
|
+
result.extend([x.real, x.imag])
|
|
1243
|
+
elif isinstance(x, (list, tuple)):
|
|
1244
|
+
result.extend(_flatten_complex_nested(x))
|
|
1245
|
+
else:
|
|
1246
|
+
result.extend([float(x), 0.0])
|
|
1247
|
+
return result
|
|
1248
|
+
|
|
1249
|
+
# 列表推导 + 闭包,避免在循环中重复定义函数
|
|
1250
|
+
flat_real_imag = []
|
|
1251
|
+
for item in values_flat:
|
|
1252
|
+
if isinstance(item, complex):
|
|
1253
|
+
flat_real_imag.extend([item.real, item.imag])
|
|
1254
|
+
elif isinstance(item, (list, tuple)):
|
|
1255
|
+
flat_real_imag.extend(_flatten_complex_nested(item))
|
|
1256
|
+
else:
|
|
1257
|
+
flat_real_imag.extend([float(item), 0.0])
|
|
1258
|
+
values_flat = flat_real_imag
|
|
1259
|
+
|
|
1260
|
+
result = _core.insert_rs(arr._array, obj, values_flat, axis)
|
|
1261
|
+
return nd._wrap(result, _dtype=dtype, _fields=fields, _raw_data=raw_data)
|
|
1262
|
+
|
|
1263
|
+
|
|
1264
|
+
def unique(a, return_index=False, return_inverse=False, return_counts=False,
|
|
1265
|
+
axis=None, *, equal_nan=True, sorted=True):
|
|
1266
|
+
"""查找数组内的唯一元素(纯 Python 实现,对齐 数组语义)。
|
|
1267
|
+
|
|
1268
|
+
axis=None 展平后去重;axis=k 将该轴上的每个子数组视为一个元素去重
|
|
1269
|
+
(按元素字典序)。equal_nan=True 时全部 NaN 视为相等只留一个;
|
|
1270
|
+
False 时各 NaN 互不相等各占一席。return_inverse 在 axis=None 时
|
|
1271
|
+
按输入形状展平,axis=k 时为沿该轴的一维数组。
|
|
1272
|
+
"""
|
|
1273
|
+
npmod = _np()
|
|
1274
|
+
nd = _nd()
|
|
1275
|
+
|
|
1276
|
+
# MaskedArray 输入:对 data 计算 unique,结果再挂回掩码。
|
|
1277
|
+
_ma_input = None
|
|
1278
|
+
if (not hasattr(a, '_array')) and type(a).__name__ == 'MaskedArray':
|
|
1279
|
+
_ma_input = a
|
|
1280
|
+
a = a.data
|
|
1281
|
+
arr = a if hasattr(a, '_array') else _wrap(a)
|
|
1282
|
+
dtype = getattr(arr, '_dtype', "float64")
|
|
1283
|
+
fields = getattr(arr, '_fields', None)
|
|
1284
|
+
shape = tuple(getattr(arr, 'shape', ()))
|
|
1285
|
+
ndim = len(shape)
|
|
1286
|
+
|
|
1287
|
+
# ---------- axis 校验(数组语义:非整数 -> TypeError,越界 -> AxisError) ----------
|
|
1288
|
+
if axis is not None:
|
|
1289
|
+
if not (isinstance(axis, int) and not isinstance(axis, bool)):
|
|
1290
|
+
if hasattr(axis, '__index__'):
|
|
1291
|
+
axis = axis.__index__()
|
|
1292
|
+
else:
|
|
1293
|
+
raise TypeError(
|
|
1294
|
+
f"unique(): axis={axis!r} cannot be interpreted as an integer")
|
|
1295
|
+
if axis >= ndim or axis < -ndim:
|
|
1296
|
+
from .exceptions import AxisError
|
|
1297
|
+
raise AxisError(
|
|
1298
|
+
f"axis {axis} is out of bounds for array of dimension {ndim}")
|
|
1299
|
+
_ax = axis + ndim if axis < 0 else axis
|
|
1300
|
+
else:
|
|
1301
|
+
_ax = None
|
|
1302
|
+
|
|
1303
|
+
if int(getattr(arr, 'size', 0)) == 0:
|
|
1304
|
+
# 数组语义(issue 15559):零尺寸数组沿轴的各切片全为空且相等;
|
|
1305
|
+
# Python 层处理避免 Rust 崩溃。
|
|
1306
|
+
_shp = shape
|
|
1307
|
+
_intp = "int64"
|
|
1308
|
+
if _ax is None:
|
|
1309
|
+
uniq = npmod.empty((0,), dtype=dtype)
|
|
1310
|
+
idx = inv = cnt = npmod.empty((0,), dtype=_intp)
|
|
1311
|
+
else:
|
|
1312
|
+
n_axis = _shp[_ax]
|
|
1313
|
+
if n_axis == 0:
|
|
1314
|
+
uniq = npmod.empty(_shp, dtype=dtype)
|
|
1315
|
+
idx = inv = cnt = npmod.empty((0,), dtype=_intp)
|
|
1316
|
+
else:
|
|
1317
|
+
_us = list(_shp)
|
|
1318
|
+
_us[_ax] = 1
|
|
1319
|
+
uniq = npmod.empty(tuple(_us), dtype=dtype)
|
|
1320
|
+
idx = npmod.empty((1,), dtype=_intp)
|
|
1321
|
+
idx[0] = 0
|
|
1322
|
+
inv = npmod.zeros((n_axis,), dtype=_intp)
|
|
1323
|
+
cnt = npmod.empty((1,), dtype=_intp)
|
|
1324
|
+
cnt[0] = n_axis
|
|
1325
|
+
if not (return_index or return_inverse or return_counts):
|
|
1326
|
+
return uniq
|
|
1327
|
+
outputs = [uniq]
|
|
1328
|
+
if return_index:
|
|
1329
|
+
outputs.append(idx)
|
|
1330
|
+
if return_inverse:
|
|
1331
|
+
outputs.append(inv)
|
|
1332
|
+
if return_counts:
|
|
1333
|
+
outputs.append(cnt)
|
|
1334
|
+
return tuple(outputs)
|
|
1335
|
+
|
|
1336
|
+
# object 类型(及含 object 字段的结构化)不支持 axis 路径(抛 TypeError)。
|
|
1337
|
+
if _ax is not None:
|
|
1338
|
+
_obj = (dtype in ('object', 'O')
|
|
1339
|
+
or getattr(dtype, 'name', '') in ('object', 'O'))
|
|
1340
|
+
if not _obj and fields:
|
|
1341
|
+
for _nm, _fd in fields:
|
|
1342
|
+
if _fd in ('object', 'O') or 'object' in str(_fd):
|
|
1343
|
+
_obj = True
|
|
1344
|
+
break
|
|
1345
|
+
if _obj:
|
|
1346
|
+
raise TypeError("unique() with axis is not supported for object arrays")
|
|
1347
|
+
|
|
1348
|
+
# ---------- 取行:axis=k 时行 = 沿轴的子数组(C 序下为连续块);None 时每个标量一行 ----------
|
|
1349
|
+
def _flat_of(x):
|
|
1350
|
+
out = []
|
|
1351
|
+
|
|
1352
|
+
def rec(v):
|
|
1353
|
+
if isinstance(v, (list, tuple)):
|
|
1354
|
+
for w in v:
|
|
1355
|
+
rec(w)
|
|
1356
|
+
else:
|
|
1357
|
+
out.append(v)
|
|
1358
|
+
|
|
1359
|
+
rec(x.tolist())
|
|
1360
|
+
return out
|
|
1361
|
+
|
|
1362
|
+
if fields is not None:
|
|
1363
|
+
flat = [tuple(r) for r in arr.tolist()]
|
|
1364
|
+
else:
|
|
1365
|
+
flat = _flat_of(arr)
|
|
1366
|
+
if _ax is None:
|
|
1367
|
+
rows = [[v] for v in flat]
|
|
1368
|
+
n_rows = len(rows)
|
|
1369
|
+
else:
|
|
1370
|
+
# axis=k 的元素 = “固定第 k 轴位置的切片”(如 2D 数组 axis=1 是列),
|
|
1371
|
+
# C 序下不一定连续,按索引分解采样。
|
|
1372
|
+
_strides = [1] * ndim
|
|
1373
|
+
for _d in range(ndim - 2, -1, -1):
|
|
1374
|
+
_strides[_d] = _strides[_d + 1] * shape[_d + 1]
|
|
1375
|
+
n_rows = shape[_ax]
|
|
1376
|
+
rows = []
|
|
1377
|
+
for _p in range(n_rows):
|
|
1378
|
+
_row = []
|
|
1379
|
+
for _idx in itertools.product(*[range(_s) for _s in shape]):
|
|
1380
|
+
if _idx[_ax] == _p:
|
|
1381
|
+
_row.append(
|
|
1382
|
+
flat[sum(_i * _st for _i, _st in zip(_idx, _strides))])
|
|
1383
|
+
rows.append(_row)
|
|
1384
|
+
|
|
1385
|
+
# ---------- NA / NaN 判定与相等性 ----------
|
|
1386
|
+
# StringDType(可空字符串):NA 对象可为 None / 任意 NaN / 任意身份对象;
|
|
1387
|
+
# 字符串 na_object 按普通字符串值处理(无 NA 语义)。
|
|
1388
|
+
_vstr_dt = getattr(arr, '_dtype_obj', None)
|
|
1389
|
+
_is_vstr = _vstr_dt is not None and type(_vstr_dt).__name__ == 'StrDType'
|
|
1390
|
+
_na_obj = getattr(arr, '_na_object', None)
|
|
1391
|
+
_na_semantics = _is_vstr and not isinstance(_na_obj, str)
|
|
1392
|
+
# 数组语义:na_object=None 时 equal_nan=False 仅支持 hash 路径
|
|
1393
|
+
# (sorted=False);默认排序路径抛 ValueError。
|
|
1394
|
+
if _na_semantics and not equal_nan and _na_obj is None and sorted:
|
|
1395
|
+
raise ValueError(
|
|
1396
|
+
"unique with equal_nan=False is not supported for StringDType "
|
|
1397
|
+
"arrays with na_object=None when sorted")
|
|
1398
|
+
|
|
1399
|
+
def _is_nan(v):
|
|
1400
|
+
if isinstance(v, float):
|
|
1401
|
+
return v != v
|
|
1402
|
+
if isinstance(v, complex):
|
|
1403
|
+
return v.real != v.real or v.imag != v.imag
|
|
1404
|
+
return False
|
|
1405
|
+
|
|
1406
|
+
def _is_na_obj(v):
|
|
1407
|
+
if not _na_semantics:
|
|
1408
|
+
return False
|
|
1409
|
+
if v is _na_obj or v is None:
|
|
1410
|
+
return True
|
|
1411
|
+
try:
|
|
1412
|
+
if v != v: # 任意浮点型 NaN 都视为 NA
|
|
1413
|
+
return True
|
|
1414
|
+
except Exception:
|
|
1415
|
+
pass
|
|
1416
|
+
return False
|
|
1417
|
+
|
|
1418
|
+
def _same_elem(x, y):
|
|
1419
|
+
# NA 对象 / NaN:仅 equal_nan=True 时相等——先于身份短路判定,
|
|
1420
|
+
# 使 equal_nan=False 时多个 NA 保持独立(即使是同一实例)
|
|
1421
|
+
if _is_na_obj(x) or _is_na_obj(y):
|
|
1422
|
+
return bool(equal_nan) and _is_na_obj(x) and _is_na_obj(y)
|
|
1423
|
+
if x is y:
|
|
1424
|
+
return True
|
|
1425
|
+
if _is_nan(x) or _is_nan(y):
|
|
1426
|
+
return bool(equal_nan) and _is_nan(x) and _is_nan(y)
|
|
1427
|
+
try:
|
|
1428
|
+
r = x == y
|
|
1429
|
+
except Exception:
|
|
1430
|
+
return False
|
|
1431
|
+
try:
|
|
1432
|
+
return bool(r)
|
|
1433
|
+
except Exception:
|
|
1434
|
+
return False
|
|
1435
|
+
|
|
1436
|
+
def _same_row(ra, rb):
|
|
1437
|
+
return all(_same_elem(x, y) for x, y in zip(ra, rb))
|
|
1438
|
+
|
|
1439
|
+
# ---------- 去重(记录首次出现位置) ----------
|
|
1440
|
+
_uniq_rows, _first, _inv, _cnt = [], [], [], []
|
|
1441
|
+
for _i, _row in enumerate(rows):
|
|
1442
|
+
for _j, _urow in enumerate(_uniq_rows):
|
|
1443
|
+
if _same_row(_row, _urow):
|
|
1444
|
+
_inv.append(_j)
|
|
1445
|
+
_cnt[_j] += 1
|
|
1446
|
+
break
|
|
1447
|
+
else:
|
|
1448
|
+
_inv.append(len(_uniq_rows))
|
|
1449
|
+
_uniq_rows.append(_row)
|
|
1450
|
+
_first.append(_i)
|
|
1451
|
+
_cnt.append(1)
|
|
1452
|
+
_k = len(_uniq_rows)
|
|
1453
|
+
|
|
1454
|
+
# ---------- 排序(NaN 最后;-0.0 在 0.0 前;复数按 (实部, 虚部) 字典序) ----------
|
|
1455
|
+
def _key_elem(v):
|
|
1456
|
+
if _is_na_obj(v) or _is_nan(v):
|
|
1457
|
+
return (1, 0.0)
|
|
1458
|
+
if isinstance(v, complex):
|
|
1459
|
+
return (0, 0.0, _key_elem(v.real), _key_elem(v.imag))
|
|
1460
|
+
return (0, 0.0, v)
|
|
1461
|
+
|
|
1462
|
+
def _key_row(row):
|
|
1463
|
+
return tuple(_key_elem(v) for v in row)
|
|
1464
|
+
|
|
1465
|
+
if sorted:
|
|
1466
|
+
order = list(range(_k))
|
|
1467
|
+
try:
|
|
1468
|
+
order.sort(key=lambda _j: _key_row(_uniq_rows[_j]))
|
|
1469
|
+
except TypeError:
|
|
1470
|
+
order = list(range(_k)) # 不可比较类型(object 等):保持首次出现序
|
|
1471
|
+
else:
|
|
1472
|
+
order = list(range(_k))
|
|
1473
|
+
_pos = [0] * _k
|
|
1474
|
+
for _new, _old in enumerate(order):
|
|
1475
|
+
_pos[_old] = _new
|
|
1476
|
+
uniq_rows = [_uniq_rows[_j] for _j in order]
|
|
1477
|
+
idx_arr = [_first[_j] for _j in order]
|
|
1478
|
+
inv_arr = [_pos[_j] for _j in _inv]
|
|
1479
|
+
cnt_arr = [_cnt[_j] for _j in order]
|
|
1480
|
+
|
|
1481
|
+
# ---------- 结果数组 ----------
|
|
1482
|
+
# 结果数组布局:第 k 轴换成唯一数,其余位置按 C 序收集各唯一“行”的值。
|
|
1483
|
+
def _layout_axis(res_rows):
|
|
1484
|
+
_So = 1
|
|
1485
|
+
for _d in shape[:_ax]:
|
|
1486
|
+
_So *= _d
|
|
1487
|
+
_St = 1
|
|
1488
|
+
for _d in shape[_ax + 1:]:
|
|
1489
|
+
_St *= _d
|
|
1490
|
+
_L = _So * _St
|
|
1491
|
+
_fr = [None] * (_k * _L)
|
|
1492
|
+
for _j, _row in enumerate(res_rows):
|
|
1493
|
+
for _r in range(_L):
|
|
1494
|
+
_o = _r // _St
|
|
1495
|
+
_t = _r % _St
|
|
1496
|
+
_fr[_o * (_k * _St) + _j * _St + _t] = _row[_r]
|
|
1497
|
+
return _fr
|
|
1498
|
+
|
|
1499
|
+
if fields is not None:
|
|
1500
|
+
# 结构化:每条记录是一个元素
|
|
1501
|
+
_recs = [list(r) for r in uniq_rows]
|
|
1502
|
+
if _ax is None:
|
|
1503
|
+
uniq_arr = npmod.array(_recs, dtype=list(fields))
|
|
1504
|
+
else:
|
|
1505
|
+
_shp_us = shape[:_ax] + (_k,) + shape[_ax + 1:]
|
|
1506
|
+
uniq_arr = npmod.array(_flat_to_nested(_layout_axis(_recs), _shp_us),
|
|
1507
|
+
dtype=list(fields))
|
|
1508
|
+
else:
|
|
1509
|
+
if _ax is None:
|
|
1510
|
+
if _is_vstr:
|
|
1511
|
+
# 保留 NA 对象身份,并把原始 dtype 实例挂回结果
|
|
1512
|
+
uniq_arr = nd([v for r in uniq_rows for v in r],
|
|
1513
|
+
_dtype='string_', _na_object=_na_obj,
|
|
1514
|
+
_vstring=True)
|
|
1515
|
+
uniq_arr._dtype_obj = _vstr_dt
|
|
1516
|
+
else:
|
|
1517
|
+
uniq_arr = nd([v for r in uniq_rows for v in r], _dtype=dtype)
|
|
1518
|
+
else:
|
|
1519
|
+
_shp_us = shape[:_ax] + (_k,) + shape[_ax + 1:]
|
|
1520
|
+
uniq_arr = nd(_flat_to_nested(_layout_axis(uniq_rows), _shp_us),
|
|
1521
|
+
_dtype=dtype)
|
|
1522
|
+
|
|
1523
|
+
def _intp_arr(lst, shp=None):
|
|
1524
|
+
if shp and len(shp) > 1:
|
|
1525
|
+
return nd(_flat_to_nested(list(lst), shp), _dtype='int64')
|
|
1526
|
+
return nd(list(lst), _dtype='int64')
|
|
1527
|
+
|
|
1528
|
+
# 数组语义:结果保持输入的数组子类型(如 Subclass)
|
|
1529
|
+
if uniq_arr.__class__ is not arr.__class__:
|
|
1530
|
+
uniq_arr.__class__ = arr.__class__
|
|
1531
|
+
|
|
1532
|
+
def _assemble(res0):
|
|
1533
|
+
if not (return_index or return_inverse or return_counts):
|
|
1534
|
+
return res0
|
|
1535
|
+
_outs = [res0]
|
|
1536
|
+
if return_index:
|
|
1537
|
+
_outs.append(_intp_arr(idx_arr))
|
|
1538
|
+
if return_inverse:
|
|
1539
|
+
_outs.append(_intp_arr(inv_arr, shape if _ax is None else None))
|
|
1540
|
+
if return_counts:
|
|
1541
|
+
_outs.append(_intp_arr(cnt_arr))
|
|
1542
|
+
return _outs[0] if len(_outs) == 1 else tuple(_outs)
|
|
1543
|
+
|
|
1544
|
+
if _ma_input is not None:
|
|
1545
|
+
from .ma.core import MaskedArray
|
|
1546
|
+
# 每个唯一值的掩码:其任一出现位置被掩码则整体被掩码
|
|
1547
|
+
_mflat = list(_ma_input._mask)
|
|
1548
|
+
_um_old = [builtins.any(_mflat[_i] for _i, _j in enumerate(_inv)
|
|
1549
|
+
if _j == _t) for _t in range(_k)]
|
|
1550
|
+
_umask = [_um_old[_j] for _j in order]
|
|
1551
|
+
return _assemble(MaskedArray(uniq_arr, mask=_umask))
|
|
1552
|
+
|
|
1553
|
+
return _assemble(uniq_arr)
|
|
1554
|
+
|
|
1555
|
+
|
|
1556
|
+
# ========== Array API 风格的 unique 包装 ==========
|
|
1557
|
+
from collections import namedtuple
|
|
1558
|
+
|
|
1559
|
+
_UniqueInv = namedtuple("UniqueAll", ["values", "inverse_indices"])
|
|
1560
|
+
_UniqueAll = namedtuple("UniqueAll", ["values", "indices",
|
|
1561
|
+
"inverse_indices", "counts"])
|
|
1562
|
+
|
|
1563
|
+
|
|
1564
|
+
def unique_values(x):
|
|
1565
|
+
"""Array API:唯一值(equal_nan=False 语义)。"""
|
|
1566
|
+
return unique(x, equal_nan=False)
|
|
1567
|
+
|
|
1568
|
+
|
|
1569
|
+
def unique_counts(x):
|
|
1570
|
+
"""Array API:唯一值与计数(equal_nan=False 语义)。"""
|
|
1571
|
+
v, c = unique(x, return_counts=True, equal_nan=False)
|
|
1572
|
+
return v, c
|
|
1573
|
+
|
|
1574
|
+
|
|
1575
|
+
def unique_inverse(x):
|
|
1576
|
+
"""Array API:唯一值与逆映射(按输入形状,equal_nan=False 语义)。"""
|
|
1577
|
+
v, inv = unique(x, return_inverse=True, equal_nan=False)
|
|
1578
|
+
return _UniqueInv(values=v, inverse_indices=inv)
|
|
1579
|
+
|
|
1580
|
+
|
|
1581
|
+
def unique_all(x):
|
|
1582
|
+
"""Array API:唯一值 / 索引 / 逆映射 / 计数(equal_nan=False 语义)。"""
|
|
1583
|
+
v, idx, inv, c = unique(x, return_index=True, return_inverse=True,
|
|
1584
|
+
return_counts=True, equal_nan=False)
|
|
1585
|
+
return _UniqueAll(values=v, indices=idx, inverse_indices=inv, counts=c)
|