rsarray 1.2.10__cp313-cp313-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rsarray/__init__.py +12028 -0
- rsarray/_core/__init__.py +213 -0
- rsarray/_core/_exceptions.py +83 -0
- rsarray/_core/_internal.py +331 -0
- rsarray/_core/_multiarray_tests.py +129 -0
- rsarray/_core/_multiarray_umath.py +121 -0
- rsarray/_core/_rational_tests.py +52 -0
- rsarray/_core/arrayprint.py +36 -0
- rsarray/_core/fromnumeric.py +31 -0
- rsarray/_core/function_base.py +84 -0
- rsarray/_core/multiarray.py +385 -0
- rsarray/_core/numeric.py +28 -0
- rsarray/_core/numerictypes.py +233 -0
- rsarray/_core/records.py +14 -0
- rsarray/_core/shape_base.py +23 -0
- rsarray/_core/strings.py +78 -0
- rsarray/_core/umath.py +176 -0
- rsarray/_dtypes.py +1229 -0
- rsarray/_extra.py +6621 -0
- rsarray/_typing.py +24 -0
- rsarray/array_methods.py +1224 -0
- rsarray/array_ops.py +1585 -0
- rsarray/char.py +1590 -0
- rsarray/exceptions.py +45 -0
- rsarray/fft/__init__.py +231 -0
- rsarray/io.py +453 -0
- rsarray/lib/__init__.py +102 -0
- rsarray/lib/_function_base_impl.py +37 -0
- rsarray/lib/_index_tricks_impl.py +98 -0
- rsarray/lib/_nanfunctions_impl.py +1637 -0
- rsarray/lib/_stride_tricks_impl.py +110 -0
- rsarray/lib/recfunctions.py +1222 -0
- rsarray/lib/stride_tricks.py +106 -0
- rsarray/linalg/__init__.py +2603 -0
- rsarray/linalg/_linalg.py +91 -0
- rsarray/linalg/_pylinalg.py +1008 -0
- rsarray/linalg/lapack_lite.py +13 -0
- rsarray/ma/__init__.py +92 -0
- rsarray/ma/core.py +1385 -0
- rsarray/ma/extras.py +711 -0
- rsarray/ma/mrecords.py +144 -0
- rsarray/math_functions.py +965 -0
- rsarray/matlib.py +67 -0
- rsarray/num_core.cp313-win_amd64.pyd +0 -0
- rsarray/polynomial/__init__.py +148 -0
- rsarray/polynomial/_npcompat.py +721 -0
- rsarray/polynomial/polynomial.py +1082 -0
- rsarray/random/__init__.py +2266 -0
- rsarray/random/_distributions.py +773 -0
- rsarray/rec.py +207 -0
- rsarray/statistics.py +1360 -0
- rsarray/strings.py +349 -0
- rsarray/typing/__init__.py +26 -0
- rsarray-1.2.10.dist-info/METADATA +280 -0
- rsarray-1.2.10.dist-info/RECORD +59 -0
- rsarray-1.2.10.dist-info/WHEEL +4 -0
- rsarray-1.2.10.dist-info/licenses/LICENSE +21 -0
- rsarray-1.2.10.dist-info/licenses/NOTICE +7 -0
- rsarray-1.2.10.dist-info/sboms/rsarray.cyclonedx.json +2789 -0
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""rsarray._core.multiarray 兼容实现(C-helper 的 Python 版)。
|
|
3
|
+
|
|
4
|
+
提供 ``_vec_string``(字符串方法向量化)、``scalar``(pickle 协议
|
|
5
|
+
构造标量)以及结构化数组二进制 pack/unpack 辅助。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import struct
|
|
9
|
+
|
|
10
|
+
__all__ = ['_vec_string', 'scalar', '_get_madvise_hugepage']
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _rs():
|
|
14
|
+
import rsarray
|
|
15
|
+
return rsarray
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _flat_values(arr):
|
|
19
|
+
vals = []
|
|
20
|
+
|
|
21
|
+
def rec(x):
|
|
22
|
+
if isinstance(x, (list, tuple)):
|
|
23
|
+
for e in x:
|
|
24
|
+
rec(e)
|
|
25
|
+
else:
|
|
26
|
+
vals.append(x)
|
|
27
|
+
|
|
28
|
+
rec(arr.tolist())
|
|
29
|
+
return vals
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _is_string_array(arr):
|
|
33
|
+
rs = _rs()
|
|
34
|
+
return isinstance(arr, rs.ndarray) and arr.dtype.kind in ('S', 'U')
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _vec_string(a, descr, func, args=()):
|
|
38
|
+
"""对字符串数组逐元素应用 str/bytes 方法(``_vec_string`` 兼容)。
|
|
39
|
+
|
|
40
|
+
校验顺序与标准语义一致:args 类型 → 输入类型 → 广播 →
|
|
41
|
+
结果 dtype → 方法存在 → 逐元素应用。
|
|
42
|
+
"""
|
|
43
|
+
rs = _rs()
|
|
44
|
+
if args is None:
|
|
45
|
+
args = ()
|
|
46
|
+
if not isinstance(args, tuple):
|
|
47
|
+
raise TypeError("The fourth argument must be a tuple")
|
|
48
|
+
arr = a if isinstance(a, rs.ndarray) else rs.asarray(a)
|
|
49
|
+
if not _is_string_array(arr):
|
|
50
|
+
raise TypeError(f"input {a!r} is not a string array")
|
|
51
|
+
# 广播检查:数组型参数必须能广播到 arr.shape
|
|
52
|
+
arraylike = [x for x in args if isinstance(x, (list, tuple, rs.ndarray))]
|
|
53
|
+
if arraylike:
|
|
54
|
+
try:
|
|
55
|
+
rs.broadcast(arr, *[rs.asarray(x) for x in arraylike])
|
|
56
|
+
except Exception:
|
|
57
|
+
raise ValueError("could not broadcast input array") from None
|
|
58
|
+
try:
|
|
59
|
+
dt = rs.dtype(descr)
|
|
60
|
+
except Exception:
|
|
61
|
+
raise TypeError(f"invalid type description {descr!r}") from None
|
|
62
|
+
if dt.kind not in ('S', 'U'):
|
|
63
|
+
raise TypeError(f"invalid result type {descr!r}")
|
|
64
|
+
sample = '' if dt.kind == 'U' else b''
|
|
65
|
+
if not hasattr(sample, func):
|
|
66
|
+
raise AttributeError(f"string has no function {func!r}")
|
|
67
|
+
flat_in = _flat_values(arr)
|
|
68
|
+
n = len(flat_in)
|
|
69
|
+
flat_args = []
|
|
70
|
+
for x in args:
|
|
71
|
+
if isinstance(x, (list, tuple, rs.ndarray)):
|
|
72
|
+
ax = rs.asarray(x)
|
|
73
|
+
if ax.ndim == 0:
|
|
74
|
+
flat_args.append([ax.item()] * n)
|
|
75
|
+
else:
|
|
76
|
+
flat_args.append(
|
|
77
|
+
_flat_values(rs.broadcast_to(ax, arr.shape)))
|
|
78
|
+
else:
|
|
79
|
+
flat_args.append([x] * n)
|
|
80
|
+
out = []
|
|
81
|
+
for i, v in enumerate(flat_in):
|
|
82
|
+
call_args = [fa[i] for fa in flat_args]
|
|
83
|
+
out.append(getattr(v, func)(*call_args))
|
|
84
|
+
if dt.kind == 'U':
|
|
85
|
+
out = [v if isinstance(v, str) else str(v) for v in out]
|
|
86
|
+
res = rs.array(out, dtype='U')
|
|
87
|
+
else:
|
|
88
|
+
out = [v if isinstance(v, (bytes, bytearray))
|
|
89
|
+
else str(v).encode('utf-8') for v in out]
|
|
90
|
+
res = rs.array(out, dtype='S')
|
|
91
|
+
if arr.shape:
|
|
92
|
+
res = res.reshape(arr.shape)
|
|
93
|
+
return res
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def scalar(dtype, obj):
|
|
97
|
+
"""从 (dtype, value) 构造标量(``core.multiarray.scalar`` 兼容)。
|
|
98
|
+
|
|
99
|
+
- int 值按 C 语义视为内存地址:rsarray 无地址协议,恒抛
|
|
100
|
+
RuntimeError(pickle 兼容性测试依赖此行为)。
|
|
101
|
+
- 结构化 dtype 接受字段值元组,返回记录标量(_Record)。
|
|
102
|
+
- 纯 object dtype 不接受元组/列表(抛 TypeError)。
|
|
103
|
+
"""
|
|
104
|
+
rs = _rs()
|
|
105
|
+
dt = rs.dtype(dtype)
|
|
106
|
+
if isinstance(obj, (int, rs.integer)) and not isinstance(obj, bool):
|
|
107
|
+
raise RuntimeError(f"invalid address {obj} for scalar of dtype {dt}")
|
|
108
|
+
names = getattr(dt, 'names', None)
|
|
109
|
+
if names is not None:
|
|
110
|
+
if not isinstance(obj, tuple) or len(obj) != len(names):
|
|
111
|
+
raise RuntimeError(
|
|
112
|
+
f"invalid value {obj!r} for structured dtype {dt}")
|
|
113
|
+
return rs._Record(list(obj), dt)
|
|
114
|
+
if dt.kind == 'O':
|
|
115
|
+
if isinstance(obj, (tuple, list)):
|
|
116
|
+
raise TypeError(
|
|
117
|
+
f"cannot create object scalar from {type(obj).__name__}")
|
|
118
|
+
return rs.object_(obj)
|
|
119
|
+
try:
|
|
120
|
+
return dt.type(obj)
|
|
121
|
+
except Exception:
|
|
122
|
+
raise RuntimeError(
|
|
123
|
+
f"cannot create scalar of dtype {dt} from {obj!r}") from None
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _get_madvise_hugepage(*args, **kwargs):
|
|
127
|
+
"""rsarray 无 hugepage 支持。"""
|
|
128
|
+
return False
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
# ---------------------------------------------------------------------------
|
|
132
|
+
# 结构化数组二进制 IO(ndarray.tofile / rec.fromfile 共用)
|
|
133
|
+
# ---------------------------------------------------------------------------
|
|
134
|
+
|
|
135
|
+
_STRUCT_CODES = (
|
|
136
|
+
('f', 8, 'd'), ('f', 4, 'f'),
|
|
137
|
+
('i', 8, 'q'), ('i', 4, 'i'), ('i', 2, 'h'), ('i', 1, 'b'),
|
|
138
|
+
('u', 8, 'Q'), ('u', 4, 'I'), ('u', 2, 'H'), ('u', 1, 'B'),
|
|
139
|
+
('c', 16, 'dd'), ('c', 8, 'ff'),
|
|
140
|
+
)
|
|
141
|
+
_INT_CODES = ('q', 'i', 'h', 'b', 'Q', 'I', 'H', 'B')
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _field_dtype(dt, name):
|
|
145
|
+
if hasattr(dt, '_fields'):
|
|
146
|
+
return dt._fields[name][0]
|
|
147
|
+
return dt.fields[name][0]
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _field_code(fdt):
|
|
151
|
+
# 子数组字段:返回基字段码(按基类型逐元素 pack/unpack,
|
|
152
|
+
# 如 (float64, (2**29,)) → 'd')
|
|
153
|
+
_sd = getattr(fdt, '_subdtype', None)
|
|
154
|
+
if _sd is not None:
|
|
155
|
+
return _field_code(_sd[0])
|
|
156
|
+
for kind, size, code in _STRUCT_CODES:
|
|
157
|
+
if fdt.kind == kind and fdt.itemsize == size:
|
|
158
|
+
return code
|
|
159
|
+
if fdt.kind == 'S':
|
|
160
|
+
return f"{fdt.itemsize}s"
|
|
161
|
+
if fdt.kind == 'U':
|
|
162
|
+
return f"{fdt.itemsize * 4}s"
|
|
163
|
+
raise TypeError(f"unsupported dtype for binary IO: {fdt}")
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _pack_record(values, dt, prefix):
|
|
167
|
+
out = bytearray()
|
|
168
|
+
for name, v in zip(dt.names, values):
|
|
169
|
+
fdt = _field_dtype(dt, name)
|
|
170
|
+
if getattr(fdt, 'names', None) is not None:
|
|
171
|
+
out += _pack_record(v, fdt, prefix)
|
|
172
|
+
continue
|
|
173
|
+
_sd = getattr(fdt, '_subdtype', None)
|
|
174
|
+
if _sd is not None:
|
|
175
|
+
# 子数组字段:按基类型逐元素 pack
|
|
176
|
+
_bc = _field_code(_sd[0])
|
|
177
|
+
# 快路径:f8 基类型且小端时整块转换(大子数组逐元素过慢)
|
|
178
|
+
if _bc == 'd' and prefix in ('<', '='):
|
|
179
|
+
try:
|
|
180
|
+
if hasattr(v, 'tobytes'):
|
|
181
|
+
out += v.tobytes()
|
|
182
|
+
else:
|
|
183
|
+
import array as _array_mod
|
|
184
|
+
out += _array_mod.array('d', v).tobytes()
|
|
185
|
+
continue
|
|
186
|
+
except (TypeError, ValueError):
|
|
187
|
+
pass
|
|
188
|
+
for ev in v:
|
|
189
|
+
if _bc in ('dd', 'ff'):
|
|
190
|
+
out += struct.pack(
|
|
191
|
+
prefix + _bc,
|
|
192
|
+
ev.real if isinstance(ev, complex) else float(ev),
|
|
193
|
+
ev.imag if isinstance(ev, complex) else 0.0)
|
|
194
|
+
elif _bc in ('d', 'f'):
|
|
195
|
+
out += struct.pack(prefix + _bc, float(ev))
|
|
196
|
+
elif _bc in _INT_CODES:
|
|
197
|
+
out += struct.pack(prefix + _bc, int(ev))
|
|
198
|
+
elif _bc.endswith('s'):
|
|
199
|
+
_n = int(_bc[:-1])
|
|
200
|
+
_b = (ev.encode('utf-8') if isinstance(ev, str)
|
|
201
|
+
else bytes(ev))
|
|
202
|
+
out += _b[:_n].ljust(_n, b'\x00')
|
|
203
|
+
else:
|
|
204
|
+
raise TypeError(
|
|
205
|
+
f"unsupported dtype for binary IO: {fdt}")
|
|
206
|
+
continue
|
|
207
|
+
code = _field_code(fdt)
|
|
208
|
+
if code.endswith('s'):
|
|
209
|
+
n = int(code[:-1])
|
|
210
|
+
if isinstance(v, str):
|
|
211
|
+
b = v.encode('utf-8')
|
|
212
|
+
elif isinstance(v, (bytes, bytearray)):
|
|
213
|
+
b = bytes(v)
|
|
214
|
+
else:
|
|
215
|
+
b = str(v).encode('utf-8')
|
|
216
|
+
out += b[:n].ljust(n, b'\x00')
|
|
217
|
+
elif code in ('dd', 'ff'):
|
|
218
|
+
out += struct.pack(prefix + code,
|
|
219
|
+
v.real if isinstance(v, complex) else float(v),
|
|
220
|
+
v.imag if isinstance(v, complex) else 0.0)
|
|
221
|
+
elif code in ('d', 'f'):
|
|
222
|
+
out += struct.pack(prefix + code, float(v))
|
|
223
|
+
elif code in _INT_CODES:
|
|
224
|
+
out += struct.pack(prefix + code, int(v))
|
|
225
|
+
return bytes(out)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _unpack_record(chunk, dt, prefix, off):
|
|
229
|
+
vals = []
|
|
230
|
+
for name in dt.names:
|
|
231
|
+
fdt = _field_dtype(dt, name)
|
|
232
|
+
if getattr(fdt, 'names', None) is not None:
|
|
233
|
+
v, off = _unpack_record(chunk, fdt, prefix, off)
|
|
234
|
+
vals.append(v)
|
|
235
|
+
continue
|
|
236
|
+
_sd = getattr(fdt, '_subdtype', None)
|
|
237
|
+
if _sd is not None:
|
|
238
|
+
# 子数组字段:按基类型逐元素 unpack(返回 tuple)
|
|
239
|
+
_base = _sd[0]
|
|
240
|
+
_bc = _field_code(_base)
|
|
241
|
+
_bi = int(getattr(_base, 'itemsize', 8) or 8)
|
|
242
|
+
_n_sub = 1
|
|
243
|
+
for _s in (_sd[1] or ()):
|
|
244
|
+
_n_sub *= _s
|
|
245
|
+
# 快路径:f8 基类型且小端时整块解包(大子数组逐元素过慢)
|
|
246
|
+
if _bc == 'd' and prefix in ('<', '='):
|
|
247
|
+
import array as _array_mod
|
|
248
|
+
_a = _array_mod.array('d')
|
|
249
|
+
_a.frombytes(chunk[off:off + _n_sub * 8])
|
|
250
|
+
off += _n_sub * 8
|
|
251
|
+
vals.append(tuple(_a))
|
|
252
|
+
continue
|
|
253
|
+
_sub = []
|
|
254
|
+
for _j in range(_n_sub):
|
|
255
|
+
(_ev,) = struct.unpack_from(
|
|
256
|
+
prefix + _bc, chunk, off + _j * _bi)
|
|
257
|
+
_sub.append(_ev)
|
|
258
|
+
off += _n_sub * _bi
|
|
259
|
+
vals.append(tuple(_sub))
|
|
260
|
+
continue
|
|
261
|
+
code = _field_code(fdt)
|
|
262
|
+
if code.endswith('s'):
|
|
263
|
+
n = int(code[:-1])
|
|
264
|
+
raw = bytes(chunk[off:off + n])
|
|
265
|
+
off += n
|
|
266
|
+
if fdt.kind == 'U':
|
|
267
|
+
vals.append(raw.decode('utf-8', 'replace'))
|
|
268
|
+
else:
|
|
269
|
+
vals.append(raw)
|
|
270
|
+
elif code in ('dd', 'ff'):
|
|
271
|
+
a, b = struct.unpack_from(prefix + code, chunk, off)
|
|
272
|
+
off += fdt.itemsize
|
|
273
|
+
vals.append(complex(a, b))
|
|
274
|
+
elif code in ('d', 'f'):
|
|
275
|
+
(v,) = struct.unpack_from(prefix + code, chunk, off)
|
|
276
|
+
off += fdt.itemsize
|
|
277
|
+
vals.append(v)
|
|
278
|
+
else:
|
|
279
|
+
(v,) = struct.unpack_from(prefix + code, chunk, off)
|
|
280
|
+
off += fdt.itemsize
|
|
281
|
+
vals.append(v)
|
|
282
|
+
return tuple(vals), off
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _byteorder_prefix(byteorder):
|
|
286
|
+
if byteorder is None:
|
|
287
|
+
return '<'
|
|
288
|
+
if byteorder in ('big', '>', 'BE'):
|
|
289
|
+
return '>'
|
|
290
|
+
if byteorder in ('little', '<', 'LE'):
|
|
291
|
+
return '<'
|
|
292
|
+
if byteorder in ('=', '@', 'native'):
|
|
293
|
+
return '='
|
|
294
|
+
return byteorder
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _extract_records(arr):
|
|
298
|
+
"""逐记录取值:剥掉外层 ndim 层嵌套,返回记录字段值列表(不拍平字段)。"""
|
|
299
|
+
data = arr.tolist()
|
|
300
|
+
if arr.ndim == 0:
|
|
301
|
+
# 0-d 结构化数组 tolist 已返回"记录列表"(如 [(1.0,)]),直接展开;
|
|
302
|
+
# 若已是单条记录(tuple)则包一层。
|
|
303
|
+
if isinstance(data, list):
|
|
304
|
+
return list(data)
|
|
305
|
+
return [data]
|
|
306
|
+
out = []
|
|
307
|
+
|
|
308
|
+
def rec(x, d):
|
|
309
|
+
if d > 0 and isinstance(x, (list, tuple)):
|
|
310
|
+
for e in x:
|
|
311
|
+
rec(e, d - 1)
|
|
312
|
+
else:
|
|
313
|
+
out.append(x)
|
|
314
|
+
|
|
315
|
+
rec(data, arr.ndim)
|
|
316
|
+
return out
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def pack_array_bytes(arr, byteorder=None):
|
|
320
|
+
"""数组 → 原始字节(结构化逐记录 pack;简单数值走 tobytes)。"""
|
|
321
|
+
dt = arr.dtype
|
|
322
|
+
prefix = _byteorder_prefix(byteorder)
|
|
323
|
+
if getattr(dt, 'names', None) is not None:
|
|
324
|
+
return b''.join(_pack_record(r, dt, prefix)
|
|
325
|
+
for r in _extract_records(arr))
|
|
326
|
+
if dt.kind in 'fiuc' and prefix in ('<', '='):
|
|
327
|
+
try:
|
|
328
|
+
return arr.tobytes()
|
|
329
|
+
except Exception:
|
|
330
|
+
pass
|
|
331
|
+
flat = _flat_values(arr)
|
|
332
|
+
code = _field_code(dt)
|
|
333
|
+
parts = []
|
|
334
|
+
for v in flat:
|
|
335
|
+
if code in ('dd', 'ff'):
|
|
336
|
+
parts.append(struct.pack(prefix + code,
|
|
337
|
+
v.real if isinstance(v, complex)
|
|
338
|
+
else float(v),
|
|
339
|
+
v.imag if isinstance(v, complex)
|
|
340
|
+
else 0.0))
|
|
341
|
+
elif code in ('d', 'f'):
|
|
342
|
+
parts.append(struct.pack(prefix + code, float(v)))
|
|
343
|
+
elif code in _INT_CODES:
|
|
344
|
+
parts.append(struct.pack(prefix + code, int(v)))
|
|
345
|
+
else:
|
|
346
|
+
raise TypeError(f"unsupported dtype for binary IO: {dt}")
|
|
347
|
+
return b''.join(parts)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def unpack_array_bytes(data, dt, n, byteorder=None):
|
|
351
|
+
"""原始字节 → 记录元组列表(与 pack_array_bytes 互逆)。"""
|
|
352
|
+
prefix = _byteorder_prefix(byteorder)
|
|
353
|
+
if getattr(dt, 'names', None) is None:
|
|
354
|
+
code = _field_code(dt)
|
|
355
|
+
vals = []
|
|
356
|
+
for k in range(n):
|
|
357
|
+
chunk = data[k * dt.itemsize:(k + 1) * dt.itemsize]
|
|
358
|
+
if code in ('dd', 'ff'):
|
|
359
|
+
a, b = struct.unpack_from(prefix + code, chunk, 0)
|
|
360
|
+
vals.append(complex(a, b))
|
|
361
|
+
elif code in ('d', 'f'):
|
|
362
|
+
(v,) = struct.unpack_from(prefix + code, chunk, 0)
|
|
363
|
+
vals.append(v)
|
|
364
|
+
else:
|
|
365
|
+
(v,) = struct.unpack_from(prefix + code, chunk, 0)
|
|
366
|
+
vals.append(v)
|
|
367
|
+
return vals
|
|
368
|
+
recs = []
|
|
369
|
+
for k in range(n):
|
|
370
|
+
chunk = data[k * dt.itemsize:(k + 1) * dt.itemsize]
|
|
371
|
+
rec, _ = _unpack_record(chunk, dt, prefix, 0)
|
|
372
|
+
recs.append(rec)
|
|
373
|
+
return recs
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def dot(a, b):
|
|
377
|
+
"""ndarray 点积(rsarray._core.multiarray.dot 兼容)。"""
|
|
378
|
+
import rsarray
|
|
379
|
+
return rsarray.dot(a, b)
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _get_ndarray_c_version(*args, **kwargs):
|
|
383
|
+
"""C 层 ndarray 版本号桩:rsarray 无对应 C 实现(相关测试经 conftest skip)。"""
|
|
384
|
+
raise NotImplementedError(
|
|
385
|
+
"rsarray has no C _get_ndarray_c_version; test is expected to be skipped")
|
rsarray/_core/numeric.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
import operator
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def normalize_axis_index(axis, ndim, argname=None):
|
|
6
|
+
if axis < 0:
|
|
7
|
+
axis += ndim
|
|
8
|
+
if not 0 <= axis < ndim:
|
|
9
|
+
if argname:
|
|
10
|
+
raise ValueError(f"axis {axis} is out of bounds for array of dimension {ndim}")
|
|
11
|
+
else:
|
|
12
|
+
raise ValueError(f"axis {axis} is out of bounds for array of dimension {ndim}")
|
|
13
|
+
return axis
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def normalize_axis_tuple(axis, ndim, argname=None, allow_duplicate=False):
|
|
17
|
+
if not isinstance(axis, (tuple, list)):
|
|
18
|
+
try:
|
|
19
|
+
axis = [operator.index(axis)]
|
|
20
|
+
except TypeError:
|
|
21
|
+
pass
|
|
22
|
+
axis = tuple(normalize_axis_index(ax, ndim, argname) for ax in axis)
|
|
23
|
+
if not allow_duplicate and len(set(axis)) != len(axis):
|
|
24
|
+
if argname:
|
|
25
|
+
raise ValueError(f'repeated axis in `{argname}` argument')
|
|
26
|
+
else:
|
|
27
|
+
raise ValueError('repeated axis')
|
|
28
|
+
return axis
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""rsarray._core.numerictypes 兼容实现(标量类型表与转换工具)。
|
|
3
|
+
|
|
4
|
+
对齐 2.x 语义;与更新版 行为不一致处(如 ``sctype2char(1)``
|
|
5
|
+
抛 ValueError)以 rsarray 测试契约为准。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
'sctypes', 'sctypeDict', 'typeDict', 'typecodes',
|
|
10
|
+
'issctype', 'obj2sctype', 'sctype2char',
|
|
11
|
+
'bool', 'int', 'float', 'complex', 'str', 'bytes', 'object',
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
from builtins import bytes, complex, float, int, object, str # noqa: F401
|
|
15
|
+
# 注意:bool 不从此处导入——nt.bool 必须指向 rsarray 标量类(参考实现
|
|
16
|
+
# numerictypes 语义),由模块 __getattr__ 回落到 rsarray.bool。
|
|
17
|
+
|
|
18
|
+
_TYPECODES = {
|
|
19
|
+
'Character': 'c',
|
|
20
|
+
'Integer': 'bhilqnp',
|
|
21
|
+
'UnsignedInteger': 'BHILQNP',
|
|
22
|
+
'Float': 'efdg',
|
|
23
|
+
'Complex': 'FDG',
|
|
24
|
+
'AllInteger': 'bBhHiIlLqQnNpP',
|
|
25
|
+
'AllFloat': 'efdgFDG',
|
|
26
|
+
'Datetime': 'Mm',
|
|
27
|
+
'All': '?bhilqnpBHILQNPefdgFDGSUVOMm',
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _rs():
|
|
32
|
+
import rsarray
|
|
33
|
+
return rsarray
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _concrete_scalar_types():
|
|
37
|
+
"""全部具体标量类型类(不含抽象基类)。"""
|
|
38
|
+
rs = _rs()
|
|
39
|
+
names = (
|
|
40
|
+
'bool', 'int8', 'int16', 'int32', 'int64',
|
|
41
|
+
'uint8', 'uint16', 'uint32', 'uint64',
|
|
42
|
+
'float16', 'float32', 'float64', 'longdouble',
|
|
43
|
+
'complex64', 'complex128', 'clongdouble',
|
|
44
|
+
)
|
|
45
|
+
types_ = [getattr(rs, n) for n in names if hasattr(rs, n)]
|
|
46
|
+
for extra in ('object_', 'unicode_', 'bytes_', 'void'):
|
|
47
|
+
t = getattr(rs, extra, None)
|
|
48
|
+
if t is not None:
|
|
49
|
+
types_.append(t)
|
|
50
|
+
seen = set()
|
|
51
|
+
out = []
|
|
52
|
+
for t in types_:
|
|
53
|
+
if t not in seen:
|
|
54
|
+
seen.add(t)
|
|
55
|
+
out.append(t)
|
|
56
|
+
return out
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _safe_itemsize(t):
|
|
60
|
+
rs = _rs()
|
|
61
|
+
try:
|
|
62
|
+
return rs.dtype(t).itemsize
|
|
63
|
+
except Exception:
|
|
64
|
+
return 0
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
_TYPE_CHAR_FALLBACK = {'void': 'V', 'unicode_': 'U', 'bytes_': 'S',
|
|
68
|
+
'object_': 'O'}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _type_char(t):
|
|
72
|
+
rs = _rs()
|
|
73
|
+
try:
|
|
74
|
+
return rs.dtype(t).char
|
|
75
|
+
except Exception:
|
|
76
|
+
return _TYPE_CHAR_FALLBACK.get(t.__name__, 'O')
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _sctypes_table():
|
|
80
|
+
"""kind 分组 → 标量类型列表(``sctypes`` 语义)。"""
|
|
81
|
+
rs = _rs()
|
|
82
|
+
groups = (
|
|
83
|
+
('int', rs.signedinteger),
|
|
84
|
+
('uint', rs.unsignedinteger),
|
|
85
|
+
('float', rs.floating),
|
|
86
|
+
('complex', rs.complexfloating),
|
|
87
|
+
('others', rs.generic),
|
|
88
|
+
)
|
|
89
|
+
table = {key: [] for key, _ in groups}
|
|
90
|
+
for t in _concrete_scalar_types():
|
|
91
|
+
# object_ 不可带参构造(dtype('O').type(0) 会崩),不入 sctypes
|
|
92
|
+
# 'others'(sctypes 语义下 object 亦非数值分组成员)。
|
|
93
|
+
if getattr(t, '__name__', '') in ('object_', 'object'):
|
|
94
|
+
continue
|
|
95
|
+
for key, abstract in groups:
|
|
96
|
+
if issubclass(t, abstract):
|
|
97
|
+
table[key].append(t)
|
|
98
|
+
break
|
|
99
|
+
for key in table:
|
|
100
|
+
table[key].sort(key=lambda x: (_safe_itemsize(x), x.__name__))
|
|
101
|
+
return table
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _sctype_dict():
|
|
105
|
+
"""名称 → 标量类型类(``sctypeDict`` 语义,含平台别名)。"""
|
|
106
|
+
rs = _rs()
|
|
107
|
+
pairs = (
|
|
108
|
+
('bool', 'bool'),
|
|
109
|
+
('int8', 'int8'), ('int16', 'int16'), ('int32', 'int32'),
|
|
110
|
+
('int64', 'int64'),
|
|
111
|
+
('uint8', 'uint8'), ('uint16', 'uint16'), ('uint32', 'uint32'),
|
|
112
|
+
('uint64', 'uint64'),
|
|
113
|
+
('float16', 'float16'), ('float32', 'float32'),
|
|
114
|
+
('float64', 'float64'), ('longdouble', 'longdouble'),
|
|
115
|
+
('complex64', 'complex64'), ('complex128', 'complex128'),
|
|
116
|
+
('clongdouble', 'clongdouble'),
|
|
117
|
+
('long', 'long'), ('ulong', 'ulong'),
|
|
118
|
+
('intc', 'intc'), ('uintc', 'uintc'), ('intp', 'intp'),
|
|
119
|
+
('uintp', 'uintp'),
|
|
120
|
+
('object', 'object_'), ('str_', 'unicode_'), ('bytes_', 'bytes_'),
|
|
121
|
+
('void', 'void'),
|
|
122
|
+
)
|
|
123
|
+
out = {}
|
|
124
|
+
for key, attr in pairs:
|
|
125
|
+
t = getattr(rs, attr, None)
|
|
126
|
+
if t is not None:
|
|
127
|
+
out[key] = t
|
|
128
|
+
return out
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _module_attr(name):
|
|
132
|
+
"""PEP 562:按需暴露类型表与全部标量类型(numerictypes 兼容)。"""
|
|
133
|
+
if name == 'sctypes':
|
|
134
|
+
return _sctypes_table()
|
|
135
|
+
if name in ('sctypeDict', 'typeDict'):
|
|
136
|
+
return _sctype_dict()
|
|
137
|
+
if name == 'typecodes':
|
|
138
|
+
return _TYPECODES
|
|
139
|
+
rs = _rs()
|
|
140
|
+
obj = getattr(rs, name, None)
|
|
141
|
+
if obj is not None and not name.startswith('_'):
|
|
142
|
+
return obj
|
|
143
|
+
raise AttributeError(
|
|
144
|
+
f"module 'rsarray._core.numerictypes' has no attribute {name!r}")
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def __getattr__(name):
|
|
148
|
+
return _module_attr(name)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def issctype(rep):
|
|
152
|
+
"""判断对象是否代表标量数据型(``issctype`` 兼容)。"""
|
|
153
|
+
rs = _rs()
|
|
154
|
+
if not isinstance(rep, (type, rs.dtype)):
|
|
155
|
+
return False
|
|
156
|
+
try:
|
|
157
|
+
res = obj2sctype(rep)
|
|
158
|
+
except Exception:
|
|
159
|
+
return False
|
|
160
|
+
if res is None:
|
|
161
|
+
return False
|
|
162
|
+
return res is not rs.object_
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def obj2sctype(rep, default=None):
|
|
166
|
+
"""返回对象对应的标量类型(``obj2sctype`` 兼容)。"""
|
|
167
|
+
rs = _rs()
|
|
168
|
+
try:
|
|
169
|
+
if isinstance(rep, type) and issubclass(rep, rs.generic):
|
|
170
|
+
return rep
|
|
171
|
+
if isinstance(rep, rs.ndarray):
|
|
172
|
+
return rep.dtype.type
|
|
173
|
+
if isinstance(rep, type) and issubclass(rep,
|
|
174
|
+
(list, tuple, dict, set, bytearray, rs.ndarray)):
|
|
175
|
+
return rs.object_
|
|
176
|
+
dt = getattr(rep, 'dtype', None)
|
|
177
|
+
if isinstance(dt, rs.dtype):
|
|
178
|
+
t = type(rep)
|
|
179
|
+
if t in _sctype_dict().values():
|
|
180
|
+
return t
|
|
181
|
+
return rs.dtype(rep).type
|
|
182
|
+
except Exception:
|
|
183
|
+
return default
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def sctype2char(sctype):
|
|
187
|
+
"""返回标量类型对应的单字符表示(``sctype2char`` 兼容)。
|
|
188
|
+
|
|
189
|
+
- 数组/标量实例 → 取其 dtype;
|
|
190
|
+
- 抽象 generic 子类、第三方标量类型 → KeyError;
|
|
191
|
+
- 无法推断的非类型值(如裸 int)→ ValueError。
|
|
192
|
+
"""
|
|
193
|
+
rs = _rs()
|
|
194
|
+
d = _sctype_dict()
|
|
195
|
+
if isinstance(sctype, rs.ndarray):
|
|
196
|
+
return rs.dtype(sctype.dtype).char
|
|
197
|
+
if isinstance(sctype, rs.dtype):
|
|
198
|
+
return sctype.char
|
|
199
|
+
if isinstance(sctype, str):
|
|
200
|
+
try:
|
|
201
|
+
return rs.dtype(sctype).char
|
|
202
|
+
except Exception:
|
|
203
|
+
raise ValueError(f"invalid type string {sctype!r}") from None
|
|
204
|
+
if not isinstance(sctype, type):
|
|
205
|
+
dt = getattr(sctype, 'dtype', None)
|
|
206
|
+
if dt is not None:
|
|
207
|
+
sc = type(sctype)
|
|
208
|
+
if sc not in d.values():
|
|
209
|
+
raise KeyError(sc)
|
|
210
|
+
return rs.dtype(sc).char
|
|
211
|
+
raise ValueError(
|
|
212
|
+
"sctype2char only accepts scalar types and dtype objects, "
|
|
213
|
+
f"got {sctype!r}")
|
|
214
|
+
if issubclass(sctype, rs.generic):
|
|
215
|
+
sc = sctype
|
|
216
|
+
else:
|
|
217
|
+
try:
|
|
218
|
+
sc = rs.dtype(sctype).type
|
|
219
|
+
except Exception:
|
|
220
|
+
if issubclass(sctype,
|
|
221
|
+
(list, tuple, dict, set, bytearray, rs.ndarray)):
|
|
222
|
+
sc = rs.object_
|
|
223
|
+
else:
|
|
224
|
+
dt = getattr(sctype, 'dtype', None)
|
|
225
|
+
if dt is not None and not isinstance(dt, rs.dtype):
|
|
226
|
+
# 第三方/测试标量类型(如 rational):不在 sctypeDict 中
|
|
227
|
+
sc = sctype
|
|
228
|
+
else:
|
|
229
|
+
raise ValueError(
|
|
230
|
+
f"sctype2char: unrecognized type {sctype!r}") from None
|
|
231
|
+
if sc not in d.values():
|
|
232
|
+
raise KeyError(sc)
|
|
233
|
+
return _type_char(sc)
|
rsarray/_core/records.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""rsarray._core.records 兼容层:从 rsarray.rec 再导出。"""
|
|
3
|
+
|
|
4
|
+
import rsarray as _rs
|
|
5
|
+
|
|
6
|
+
recarray = _rs.rec.recarray
|
|
7
|
+
fromarrays = _rs.rec.fromarrays
|
|
8
|
+
fromfile = _rs.rec.fromfile
|
|
9
|
+
fromrecords = _rs.rec.fromrecords
|
|
10
|
+
format_parser = getattr(_rs.rec, 'format_parser', None)
|
|
11
|
+
|
|
12
|
+
__all__ = ['recarray', 'fromarrays', 'fromfile', 'fromrecords']
|
|
13
|
+
if format_parser is not None:
|
|
14
|
+
__all__.append('format_parser')
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""rsarray._core.shape_base 内部辅助兼容模块。
|
|
3
|
+
|
|
4
|
+
rsarray 的 ``np.block`` 不经过 内部的 ``_block_*`` 入口;这些
|
|
5
|
+
辅助保留"调用即 skip"行为(与旧 conftest 桩一致),使移植测试的
|
|
6
|
+
依赖可解析且不改变测试结果。
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
__all__ = ['_block_setup', '_block_slicing', '_block_dispatcher',
|
|
12
|
+
'_block_concatenate']
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _skip_c_helper(*args, **kwargs):
|
|
16
|
+
raise pytest.skip(
|
|
17
|
+
"rsarray 不暴露 rsarray._core.shape_base 内部 C 辅助的等价实现")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
_block_setup = _skip_c_helper
|
|
21
|
+
_block_slicing = _skip_c_helper
|
|
22
|
+
_block_dispatcher = _skip_c_helper
|
|
23
|
+
_block_concatenate = _skip_c_helper
|