rsarray 1.2.10__cp315-cp315-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rsarray/__init__.py +12028 -0
- rsarray/_core/__init__.py +213 -0
- rsarray/_core/_exceptions.py +83 -0
- rsarray/_core/_internal.py +331 -0
- rsarray/_core/_multiarray_tests.py +129 -0
- rsarray/_core/_multiarray_umath.py +121 -0
- rsarray/_core/_rational_tests.py +52 -0
- rsarray/_core/arrayprint.py +36 -0
- rsarray/_core/fromnumeric.py +31 -0
- rsarray/_core/function_base.py +84 -0
- rsarray/_core/multiarray.py +385 -0
- rsarray/_core/numeric.py +28 -0
- rsarray/_core/numerictypes.py +233 -0
- rsarray/_core/records.py +14 -0
- rsarray/_core/shape_base.py +23 -0
- rsarray/_core/strings.py +78 -0
- rsarray/_core/umath.py +176 -0
- rsarray/_dtypes.py +1229 -0
- rsarray/_extra.py +6621 -0
- rsarray/_typing.py +24 -0
- rsarray/array_methods.py +1224 -0
- rsarray/array_ops.py +1585 -0
- rsarray/char.py +1590 -0
- rsarray/exceptions.py +45 -0
- rsarray/fft/__init__.py +231 -0
- rsarray/io.py +453 -0
- rsarray/lib/__init__.py +102 -0
- rsarray/lib/_function_base_impl.py +37 -0
- rsarray/lib/_index_tricks_impl.py +98 -0
- rsarray/lib/_nanfunctions_impl.py +1637 -0
- rsarray/lib/_stride_tricks_impl.py +110 -0
- rsarray/lib/recfunctions.py +1222 -0
- rsarray/lib/stride_tricks.py +106 -0
- rsarray/linalg/__init__.py +2603 -0
- rsarray/linalg/_linalg.py +91 -0
- rsarray/linalg/_pylinalg.py +1008 -0
- rsarray/linalg/lapack_lite.py +13 -0
- rsarray/ma/__init__.py +92 -0
- rsarray/ma/core.py +1385 -0
- rsarray/ma/extras.py +711 -0
- rsarray/ma/mrecords.py +144 -0
- rsarray/math_functions.py +965 -0
- rsarray/matlib.py +67 -0
- rsarray/num_core.cp315-win_amd64.pyd +0 -0
- rsarray/polynomial/__init__.py +148 -0
- rsarray/polynomial/_npcompat.py +721 -0
- rsarray/polynomial/polynomial.py +1082 -0
- rsarray/random/__init__.py +2266 -0
- rsarray/random/_distributions.py +773 -0
- rsarray/rec.py +207 -0
- rsarray/statistics.py +1360 -0
- rsarray/strings.py +349 -0
- rsarray/typing/__init__.py +26 -0
- rsarray-1.2.10.dist-info/METADATA +280 -0
- rsarray-1.2.10.dist-info/RECORD +59 -0
- rsarray-1.2.10.dist-info/WHEEL +4 -0
- rsarray-1.2.10.dist-info/licenses/LICENSE +21 -0
- rsarray-1.2.10.dist-info/licenses/NOTICE +7 -0
- rsarray-1.2.10.dist-info/sboms/rsarray.cyclonedx.json +2789 -0
rsarray/io.py
ADDED
|
@@ -0,0 +1,453 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""I/O 模块 - 所有实现位于 Rust,这里仅保留薄包装。"""
|
|
3
|
+
|
|
4
|
+
from itertools import accumulate as _accumulate
|
|
5
|
+
|
|
6
|
+
import rsarray.num_core as _core
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _get_ndarray():
|
|
10
|
+
from .__init__ import ndarray as _n
|
|
11
|
+
return _n
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _ensure_raw(a):
|
|
15
|
+
if hasattr(a, '_array'):
|
|
16
|
+
return a._array
|
|
17
|
+
return _core.ndarray(a)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _wrap(result):
|
|
21
|
+
return _get_ndarray()(result)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def save(file, arr):
|
|
25
|
+
"""将数组保存为二进制文件 (.npy)。"""
|
|
26
|
+
_core.save_npy(file, _ensure_raw(arr))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class NpzFile:
|
|
30
|
+
"""用于表示加载的 .npz 文件的类。"""
|
|
31
|
+
def __init__(self, data):
|
|
32
|
+
self._data = data
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def files(self):
|
|
36
|
+
"""返回文件中所有数组的名称列表。"""
|
|
37
|
+
return list(self._data.keys())
|
|
38
|
+
|
|
39
|
+
def __getitem__(self, key):
|
|
40
|
+
"""通过键名获取数组。"""
|
|
41
|
+
return self._data[key]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def load(file, mmap_mode=None, allow_pickle=False, fix_imports=True, encoding='ASCII'):
|
|
45
|
+
"""从二进制文件加载数组 (.npy 或 .npz)。"""
|
|
46
|
+
if file.endswith('.npz'):
|
|
47
|
+
return NpzFile(load_npz(file))
|
|
48
|
+
return _wrap(_core.load_npy(file))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='',
|
|
52
|
+
footer='', comments='# ', encoding=None):
|
|
53
|
+
"""将数组保存为文本文件。"""
|
|
54
|
+
_core.save_text(fname, _ensure_raw(X), fmt, delimiter)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _strip_comments(line, comments):
|
|
58
|
+
"""剥离行内注释:comments 可为单个字符串或多个注释字符的集合。"""
|
|
59
|
+
if not comments:
|
|
60
|
+
return line
|
|
61
|
+
for c in ([comments] if isinstance(comments, str) else comments):
|
|
62
|
+
if c:
|
|
63
|
+
idx = line.find(c)
|
|
64
|
+
if idx >= 0:
|
|
65
|
+
line = line[:idx]
|
|
66
|
+
return line
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _parse_loadtxt_text(text, comments, delimiter, skiprows, keep_str=False):
|
|
70
|
+
rows = []
|
|
71
|
+
for line in text.splitlines()[skiprows:]:
|
|
72
|
+
line = _strip_comments(line, comments).strip()
|
|
73
|
+
if not line:
|
|
74
|
+
continue
|
|
75
|
+
parts = line.split(delimiter) if delimiter else line.split()
|
|
76
|
+
if not keep_str:
|
|
77
|
+
parts = [float(p) for p in parts]
|
|
78
|
+
rows.append(parts)
|
|
79
|
+
return rows
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _convert_field(token, dt):
|
|
83
|
+
"""按字段 dtype 转换 token(structured loadtxt 用)。"""
|
|
84
|
+
s = str(dt).lstrip('|<>=')
|
|
85
|
+
if s.startswith('S'):
|
|
86
|
+
return token.encode()
|
|
87
|
+
if s.startswith('U'):
|
|
88
|
+
return token
|
|
89
|
+
if s[0] in 'iu':
|
|
90
|
+
return int(token)
|
|
91
|
+
return float(token)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def loadtxt(fname, dtype=float, comments='#', delimiter=None, converters=None,
|
|
95
|
+
skiprows=0, usecols=None, unpack=False, ndmin=0, encoding='bytes',
|
|
96
|
+
max_rows=None, *, quotechar=None, like=None):
|
|
97
|
+
"""从文本文件加载数据(路径、类文件对象或字符串列表均可)。"""
|
|
98
|
+
if delimiter is None:
|
|
99
|
+
delimiter = ""
|
|
100
|
+
keep_str = dtype is str or dtype is bytes
|
|
101
|
+
try:
|
|
102
|
+
if hasattr(dtype, 'names') and dtype.names:
|
|
103
|
+
keep_str = True # 结构化 dtype:字段按声明转换,不强制 float
|
|
104
|
+
except Exception:
|
|
105
|
+
pass
|
|
106
|
+
if isinstance(fname, (list, tuple)) and all(
|
|
107
|
+
isinstance(s, str) for s in fname):
|
|
108
|
+
text = "\n".join(fname)
|
|
109
|
+
rows = _parse_loadtxt_text(text, comments, delimiter, skiprows,
|
|
110
|
+
keep_str)
|
|
111
|
+
if keep_str and getattr(dtype, 'names', None):
|
|
112
|
+
names = dtype.names
|
|
113
|
+
converted = [
|
|
114
|
+
tuple(_convert_field(t, dtype[nm]) for nm, t in zip(names, row))
|
|
115
|
+
for row in rows]
|
|
116
|
+
import rsarray as _npmod
|
|
117
|
+
result = _npmod.array(converted, dtype=dtype)
|
|
118
|
+
return result[0] if len(result) == 1 else result
|
|
119
|
+
result = _get_ndarray()(rows)
|
|
120
|
+
elif hasattr(fname, 'read'):
|
|
121
|
+
# File-like object: parse in Python (Rust core only accepts paths).
|
|
122
|
+
text = fname.read()
|
|
123
|
+
if isinstance(text, bytes):
|
|
124
|
+
text = text.decode('utf-8', errors='replace')
|
|
125
|
+
rows = _parse_loadtxt_text(text, comments, delimiter, skiprows,
|
|
126
|
+
keep_str)
|
|
127
|
+
if keep_str and getattr(dtype, 'names', None):
|
|
128
|
+
names = dtype.names
|
|
129
|
+
converted = [
|
|
130
|
+
tuple(_convert_field(t, dtype[nm]) for nm, t in zip(names, row))
|
|
131
|
+
for row in rows]
|
|
132
|
+
import rsarray as _npmod
|
|
133
|
+
result = _npmod.array(converted, dtype=dtype)
|
|
134
|
+
return result[0] if len(result) == 1 else result
|
|
135
|
+
result = _get_ndarray()(rows)
|
|
136
|
+
else:
|
|
137
|
+
result = _wrap(_core.load_text(fname, delimiter, skiprows))
|
|
138
|
+
if dtype == int:
|
|
139
|
+
result = result.astype("int")
|
|
140
|
+
elif dtype == float:
|
|
141
|
+
pass
|
|
142
|
+
elif isinstance(dtype, type):
|
|
143
|
+
result = result.astype(dtype.__name__)
|
|
144
|
+
else:
|
|
145
|
+
result = result.astype(dtype)
|
|
146
|
+
if len(result) == 1:
|
|
147
|
+
return result[0]
|
|
148
|
+
else:
|
|
149
|
+
return result
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _is_string_dtype(dt):
|
|
153
|
+
"""判断 dtype 是否为字符串类型(如 str、'|U5'、'<U10'、'S20')。"""
|
|
154
|
+
if dt is str or dt is bytes:
|
|
155
|
+
return True
|
|
156
|
+
if isinstance(dt, str):
|
|
157
|
+
s = dt.lstrip('|<>=')
|
|
158
|
+
if s and s[0] in ('U', 'S'):
|
|
159
|
+
return True
|
|
160
|
+
if dt in ('str', 'unicode', 'bytes', 'str_', 'bytes_'):
|
|
161
|
+
return True
|
|
162
|
+
return False
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _string_width(dt):
|
|
166
|
+
"""从字符串 dtype 中解析固定宽度(如 '|U5' -> 5),无宽度返回 None。"""
|
|
167
|
+
if not isinstance(dt, str):
|
|
168
|
+
return None
|
|
169
|
+
s = dt.lstrip('|<>=')
|
|
170
|
+
if s and s[0] in ('U', 'S') and s[1:].isdigit():
|
|
171
|
+
return int(s[1:])
|
|
172
|
+
return None
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _field_code_from_type(t):
|
|
176
|
+
"""将字段类型解析为结构化字段码:'i8'(整型/布尔)或 'f8'(其余)。"""
|
|
177
|
+
from .__init__ import _resolve_type_name
|
|
178
|
+
name = _resolve_type_name(t)
|
|
179
|
+
if isinstance(name, str):
|
|
180
|
+
low = name.lower()
|
|
181
|
+
if low.startswith('int') or low.startswith('uint') or low.startswith('bool'):
|
|
182
|
+
return 'i8'
|
|
183
|
+
return 'f8'
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _classify_gft_dtype(dtype):
|
|
187
|
+
"""分类 genfromtxt 的 dtype 参数。
|
|
188
|
+
|
|
189
|
+
返回 (kind, names, codes):
|
|
190
|
+
- kind='struct':结构化(names 为字段名列表或 None,codes 为每列字段码)。
|
|
191
|
+
- kind='scalar':标量 dtype,names=None,codes 为单个字段码字符串。
|
|
192
|
+
"""
|
|
193
|
+
if isinstance(dtype, list):
|
|
194
|
+
names = [f[0] for f in dtype]
|
|
195
|
+
codes = [_field_code_from_type(f[1]) for f in dtype]
|
|
196
|
+
return ('struct', names, codes)
|
|
197
|
+
if isinstance(dtype, tuple):
|
|
198
|
+
return ('struct', None, [_field_code_from_type(t) for t in dtype])
|
|
199
|
+
return ('scalar', None, _field_code_from_type(dtype))
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _split_fields(line, delimiter):
|
|
203
|
+
"""按 LineSplitter 规则将一行拆成字段。
|
|
204
|
+
|
|
205
|
+
- delimiter=None:先去除首尾换行,再按空白拆分。
|
|
206
|
+
- 整数:定宽切片(空格有意义,仅去除换行)。
|
|
207
|
+
- 序列:按累积宽度切片(仅去除换行)。
|
|
208
|
+
- 字符串:去除首尾空白与换行后按分隔符拆分。
|
|
209
|
+
空行返回 []。
|
|
210
|
+
"""
|
|
211
|
+
if delimiter is None:
|
|
212
|
+
line = line.strip("\r\n")
|
|
213
|
+
return line.split() if line else []
|
|
214
|
+
if isinstance(delimiter, int):
|
|
215
|
+
line = line.strip("\r\n")
|
|
216
|
+
if not line:
|
|
217
|
+
return []
|
|
218
|
+
return [line[i:i + delimiter] for i in range(0, len(line), delimiter)]
|
|
219
|
+
if isinstance(delimiter, (list, tuple)):
|
|
220
|
+
line = line.strip("\r\n")
|
|
221
|
+
if not line:
|
|
222
|
+
return []
|
|
223
|
+
# 使用 accumulate 计算累积结束位置,列表推导代替显式循环
|
|
224
|
+
ends = list(_accumulate(delimiter))
|
|
225
|
+
starts = [0] + ends[:-1]
|
|
226
|
+
return [line[s:e] for s, e in zip(starts, ends)]
|
|
227
|
+
line = line.strip(" \r\n")
|
|
228
|
+
return line.split(delimiter) if line else []
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def genfromtxt(fname, dtype=float, comments='#', delimiter=None, skip_header=0,
|
|
232
|
+
skip_footer=0, converters=None, missing_values=None,
|
|
233
|
+
filling_values=None, usecols=None, names=None, excludelist=None,
|
|
234
|
+
deletechars=None, replace_space='_', autostrip=False,
|
|
235
|
+
case_sensitive=True, defaultfmt='f%i', unpack=None, usemask=False,
|
|
236
|
+
loose=True, invalid_raise=True, max_rows=None, encoding=None):
|
|
237
|
+
"""从文本文件或类文件对象加载数据,缺失值填充为 NaN(兼容 genfromtxt)。"""
|
|
238
|
+
if hasattr(fname, 'read'):
|
|
239
|
+
content = fname.read()
|
|
240
|
+
if isinstance(content, bytes):
|
|
241
|
+
content = content.decode('utf-8')
|
|
242
|
+
else:
|
|
243
|
+
with open(fname, 'r') as fh:
|
|
244
|
+
content = fh.read()
|
|
245
|
+
|
|
246
|
+
lines = content.splitlines()
|
|
247
|
+
if skip_header:
|
|
248
|
+
lines = lines[skip_header:]
|
|
249
|
+
if skip_footer:
|
|
250
|
+
lines = lines[:len(lines) - skip_footer]
|
|
251
|
+
|
|
252
|
+
string_dtype = _is_string_dtype(dtype)
|
|
253
|
+
str_width = _string_width(dtype) if string_dtype else None
|
|
254
|
+
|
|
255
|
+
# 解析 names:字符串 "a, b, c"、序列,或 True(从首行读取,去除前导注释符)。
|
|
256
|
+
name_list = None
|
|
257
|
+
if isinstance(names, str):
|
|
258
|
+
name_list = [n.strip() for n in names.split(',')]
|
|
259
|
+
elif isinstance(names, (list, tuple)):
|
|
260
|
+
name_list = [str(n).strip() for n in names]
|
|
261
|
+
elif names is True:
|
|
262
|
+
for idx, line in enumerate(lines):
|
|
263
|
+
hl = line
|
|
264
|
+
if comments and hl.lstrip().startswith(comments):
|
|
265
|
+
hl = hl.lstrip()[len(comments):]
|
|
266
|
+
header_parts = _split_fields(hl, delimiter)
|
|
267
|
+
if header_parts:
|
|
268
|
+
name_list = [p.strip() for p in header_parts]
|
|
269
|
+
lines = lines[idx + 1:]
|
|
270
|
+
break
|
|
271
|
+
|
|
272
|
+
# dtype 分类(字符串 dtype 单独处理,不在此结构化)。
|
|
273
|
+
if string_dtype:
|
|
274
|
+
dt_kind, dt_names, dt_codes = ('scalar', None, None)
|
|
275
|
+
else:
|
|
276
|
+
dt_kind, dt_names, dt_codes = _classify_gft_dtype(dtype)
|
|
277
|
+
is_struct = (not string_dtype) and (dt_kind == 'struct' or name_list is not None)
|
|
278
|
+
|
|
279
|
+
if usecols is not None and not isinstance(usecols, (list, tuple)):
|
|
280
|
+
usecols = (usecols,)
|
|
281
|
+
|
|
282
|
+
# 第一遍:按行拆成字符串字段(去注释、拆分)。
|
|
283
|
+
# 抽取注释剥离为闭包,便于列表推导复用,避免显式 for 循环
|
|
284
|
+
def _strip_comment(line):
|
|
285
|
+
if comments:
|
|
286
|
+
ci = line.find(comments)
|
|
287
|
+
if ci != -1:
|
|
288
|
+
return line[:ci]
|
|
289
|
+
return line
|
|
290
|
+
|
|
291
|
+
# 生成器推导:惰性计算每行拆分结果,列表推导过滤空行
|
|
292
|
+
str_rows = [
|
|
293
|
+
parts for parts in (_split_fields(_strip_comment(line), delimiter) for line in lines)
|
|
294
|
+
if parts
|
|
295
|
+
]
|
|
296
|
+
if max_rows is not None:
|
|
297
|
+
str_rows = str_rows[:max_rows]
|
|
298
|
+
|
|
299
|
+
ndarray_cls = _get_ndarray()
|
|
300
|
+
total_ncols = len(str_rows[0]) if str_rows else 0
|
|
301
|
+
|
|
302
|
+
# 完整字段名:提供的 names 填充前若干列,其余用 defaultfmt 编号(从 0 计未命名列)。
|
|
303
|
+
full_names = None
|
|
304
|
+
if name_list is not None:
|
|
305
|
+
n_provided = len(name_list)
|
|
306
|
+
# 使用列表推导代替显式循环,避免 k 计数器
|
|
307
|
+
full_names = [
|
|
308
|
+
name_list[i] if i < n_provided else defaultfmt % (i - n_provided)
|
|
309
|
+
for i in range(total_ncols)
|
|
310
|
+
]
|
|
311
|
+
elif dt_names is not None:
|
|
312
|
+
full_names = list(dt_names)
|
|
313
|
+
elif is_struct:
|
|
314
|
+
full_names = [defaultfmt % i for i in range(total_ncols)]
|
|
315
|
+
|
|
316
|
+
# 完整字段码(整型/浮点)。
|
|
317
|
+
if dt_kind == 'struct' and dt_codes is not None:
|
|
318
|
+
full_codes = list(dt_codes)
|
|
319
|
+
elif is_struct:
|
|
320
|
+
full_codes = ['f8'] * total_ncols
|
|
321
|
+
else:
|
|
322
|
+
full_codes = None
|
|
323
|
+
|
|
324
|
+
# 解析 usecols(字符串列名→索引,负索引归一)。
|
|
325
|
+
if usecols is not None:
|
|
326
|
+
# 使用列表推导代替显式 for 循环
|
|
327
|
+
sel_indices = [
|
|
328
|
+
full_names.index(c) if isinstance(c, str)
|
|
329
|
+
else (total_ncols + c if c < 0 else c)
|
|
330
|
+
for c in usecols
|
|
331
|
+
]
|
|
332
|
+
else:
|
|
333
|
+
sel_indices = list(range(total_ncols))
|
|
334
|
+
|
|
335
|
+
# converters:键(列名或索引)映射到完整列索引。
|
|
336
|
+
# 使用字典推导代替显式 for 循环
|
|
337
|
+
if converters:
|
|
338
|
+
conv_by_idx = {
|
|
339
|
+
(full_names.index(key) if isinstance(key, str)
|
|
340
|
+
else (total_ncols + key if key < 0 else key)): fn
|
|
341
|
+
for key, fn in converters.items()
|
|
342
|
+
}
|
|
343
|
+
else:
|
|
344
|
+
conv_by_idx = {}
|
|
345
|
+
|
|
346
|
+
# 字符串 dtype 分支:保留字段文本。
|
|
347
|
+
if string_dtype:
|
|
348
|
+
# 抽取行处理逻辑为闭包,便于列表推导复用
|
|
349
|
+
def _process_row(parts):
|
|
350
|
+
sel = [parts[i] for i in sel_indices]
|
|
351
|
+
if autostrip:
|
|
352
|
+
sel = [p.strip() for p in sel]
|
|
353
|
+
if str_width is not None:
|
|
354
|
+
sel = [p[:str_width] for p in sel]
|
|
355
|
+
return sel
|
|
356
|
+
|
|
357
|
+
# 使用列表推导代替显式 for 循环
|
|
358
|
+
rows = [_process_row(parts) for parts in str_rows]
|
|
359
|
+
if rows and all(len(r) == 1 for r in rows):
|
|
360
|
+
data = [r[0] for r in rows]
|
|
361
|
+
elif len(rows) == 1:
|
|
362
|
+
data = rows[0]
|
|
363
|
+
else:
|
|
364
|
+
data = rows
|
|
365
|
+
return ndarray_cls(data)
|
|
366
|
+
|
|
367
|
+
def parse_val(raw, ci, code):
|
|
368
|
+
if autostrip:
|
|
369
|
+
raw = raw.strip()
|
|
370
|
+
if ci in conv_by_idx:
|
|
371
|
+
v = conv_by_idx[ci](raw)
|
|
372
|
+
else:
|
|
373
|
+
s = raw.strip()
|
|
374
|
+
if s == '':
|
|
375
|
+
v = float('nan')
|
|
376
|
+
else:
|
|
377
|
+
try:
|
|
378
|
+
v = float(s)
|
|
379
|
+
except ValueError:
|
|
380
|
+
v = float('nan')
|
|
381
|
+
if code == 'i8':
|
|
382
|
+
try:
|
|
383
|
+
return int(round(float(v)))
|
|
384
|
+
except (ValueError, OverflowError):
|
|
385
|
+
return v
|
|
386
|
+
return float(v)
|
|
387
|
+
|
|
388
|
+
# 结构化数组分支。
|
|
389
|
+
if is_struct:
|
|
390
|
+
out_names = [full_names[i] for i in sel_indices]
|
|
391
|
+
out_codes = [full_codes[i] for i in sel_indices]
|
|
392
|
+
fields = list(zip(out_names, out_codes))
|
|
393
|
+
raw = [
|
|
394
|
+
tuple(parse_val(parts[ci], ci, out_codes[p])
|
|
395
|
+
for p, ci in enumerate(sel_indices))
|
|
396
|
+
for parts in str_rows
|
|
397
|
+
]
|
|
398
|
+
return ndarray_cls(raw, _dtype='void', _fields=fields, _raw_data=raw)
|
|
399
|
+
|
|
400
|
+
# 非结构化(标量 dtype):先按浮点解析,必要时 astype。
|
|
401
|
+
rows = [
|
|
402
|
+
[parse_val(parts[ci], ci, 'f8') for ci in sel_indices]
|
|
403
|
+
for parts in str_rows
|
|
404
|
+
]
|
|
405
|
+
# 单列数据压成一维,与标准语义一致(如逐行单值 -> [0. 1. 2. ...])。
|
|
406
|
+
if rows and all(len(r) == 1 for r in rows):
|
|
407
|
+
data = [r[0] for r in rows]
|
|
408
|
+
elif len(rows) == 1:
|
|
409
|
+
data = rows[0]
|
|
410
|
+
else:
|
|
411
|
+
data = rows
|
|
412
|
+
|
|
413
|
+
result = ndarray_cls(data)
|
|
414
|
+
if dtype == int or dtype == 'int':
|
|
415
|
+
result = result.astype('int')
|
|
416
|
+
elif dtype not in (float, 'float', None):
|
|
417
|
+
result = result.astype(dtype.__name__ if isinstance(dtype, type) else dtype)
|
|
418
|
+
|
|
419
|
+
if unpack:
|
|
420
|
+
return result.T
|
|
421
|
+
return result
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def savez(file, *args, **kwds):
|
|
425
|
+
"""将多个数组保存为未压缩的 .npz 文件。"""
|
|
426
|
+
# 使用 sorted + 列表推导代替显式 for 循环
|
|
427
|
+
sorted_names = sorted(kwds.keys())
|
|
428
|
+
arrays = [_ensure_raw(kwds[name]) for name in sorted_names] + [_ensure_raw(arg) for arg in args]
|
|
429
|
+
names = sorted_names + ['arr_%d' % i for i in range(len(args))]
|
|
430
|
+
_core.savez_npz(file, arrays, names)
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def _is_integer_array(arr):
|
|
434
|
+
"""检查数组是否应该是整数类型。"""
|
|
435
|
+
raw_list = arr.tolist()
|
|
436
|
+
|
|
437
|
+
def check_nested(data):
|
|
438
|
+
if isinstance(data, list):
|
|
439
|
+
return all(check_nested(x) for x in data)
|
|
440
|
+
return abs(data - round(data)) < 1e-10
|
|
441
|
+
|
|
442
|
+
return check_nested(raw_list)
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def load_npz(file):
|
|
446
|
+
"""从 .npz 文件加载数组(返回 dict)。"""
|
|
447
|
+
pairs = _core.load_npz(file)
|
|
448
|
+
ndarray_cls = _get_ndarray()
|
|
449
|
+
# 使用字典推导代替显式 for 循环
|
|
450
|
+
return {
|
|
451
|
+
key: ndarray_cls._wrap(raw, _dtype='int64' if _is_integer_array(raw) else 'float64')
|
|
452
|
+
for key, raw in pairs
|
|
453
|
+
}
|
rsarray/lib/__init__.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""rsarray.lib - 工具子模块集合。"""
|
|
3
|
+
|
|
4
|
+
from . import recfunctions
|
|
5
|
+
from . import stride_tricks
|
|
6
|
+
from . import _index_tricks_impl
|
|
7
|
+
|
|
8
|
+
# 形状操作 impl 的兼容引用(suppress_warnings 等按模块过滤用)
|
|
9
|
+
from .. import _extra as _shape_base_impl
|
|
10
|
+
|
|
11
|
+
__all__ = ['recfunctions', 'stride_tricks', 'add_newdoc', 'Version',
|
|
12
|
+
'_index_tricks_impl', '_shape_base_impl']
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def add_newdoc(where, obj, doc):
|
|
16
|
+
"""Stub: record a docstring for ``where.obj`` (no-op in rsarray)."""
|
|
17
|
+
pass
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Version:
|
|
21
|
+
"""版本字符串比较器(x.y.z 三段基线 + 预发布/dev/本地后缀次序)。
|
|
22
|
+
|
|
23
|
+
支持 '1.21.0'、'1.21.0rc1'、'1.21.0.dev0+git...'、'1.21.0.dev-<hash>'
|
|
24
|
+
等形式;与字符串或其他 Version 比较(<, <=, >, >=, ==, !=)。
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, version, strict=False):
|
|
28
|
+
import re
|
|
29
|
+
self.vstring = str(version)
|
|
30
|
+
self.strict = strict
|
|
31
|
+
# 语义:x.y.z 三段基线必须完整,可选预发布(aN/bN/rcN)、
|
|
32
|
+
# dev 后缀(.dev0 / .dev-<hash>)与本地后缀(+<...>);
|
|
33
|
+
# '1.9'、'1,9.0'、'1.7.x' 等非法形式抛 ValueError。
|
|
34
|
+
m = re.match(
|
|
35
|
+
r'^(\d+)\.(\d+)\.(\d+)'
|
|
36
|
+
r'(?:(a|b|rc)(\d+))?'
|
|
37
|
+
r'((?:\.dev[-\w]*)?)'
|
|
38
|
+
r'(?:\+.*)?$', self.vstring)
|
|
39
|
+
if not m:
|
|
40
|
+
raise ValueError(f"invalid version string: {version!r}")
|
|
41
|
+
self._parts = (int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
|
42
|
+
self._pre = m.group(4) # None / 'a' / 'b' / 'rc'
|
|
43
|
+
self._pre_num = int(m.group(5)) if m.group(5) else 0
|
|
44
|
+
self._is_dev = bool(m.group(6))
|
|
45
|
+
|
|
46
|
+
def _key(self):
|
|
47
|
+
# 次序(同一 x.y.z 内):
|
|
48
|
+
# final.dev < aN.dev < aN < aN+1.dev < ... < bN.dev < bN <
|
|
49
|
+
# rcN.dev < rcN < final
|
|
50
|
+
# - dev 版本比其所属基线低半步;
|
|
51
|
+
# - final 基线的 dev 版本低于所有预发布(1.0.dev0 < 1.0a1);
|
|
52
|
+
# - dev 后缀(hash 等)不参与比较('1.9.0.dev-a' == '1.9.0.dev-b')。
|
|
53
|
+
if self._pre is None:
|
|
54
|
+
base = (4, 0)
|
|
55
|
+
else:
|
|
56
|
+
base = ({'a': 1, 'b': 2, 'rc': 3}[self._pre], self._pre_num)
|
|
57
|
+
if self._is_dev:
|
|
58
|
+
base = (0, 0) if self._pre is None else (base[0], base[1] - 0.5)
|
|
59
|
+
return (self._parts, base)
|
|
60
|
+
|
|
61
|
+
def __str__(self):
|
|
62
|
+
return self.vstring
|
|
63
|
+
|
|
64
|
+
def __repr__(self):
|
|
65
|
+
return f'<rsarray.lib.Version {self.vstring!r}>'
|
|
66
|
+
|
|
67
|
+
def __eq__(self, other):
|
|
68
|
+
return self._compare(other) == 0
|
|
69
|
+
|
|
70
|
+
def __lt__(self, other):
|
|
71
|
+
return self._compare(other) < 0
|
|
72
|
+
|
|
73
|
+
def __le__(self, other):
|
|
74
|
+
return self._compare(other) <= 0
|
|
75
|
+
|
|
76
|
+
def __gt__(self, other):
|
|
77
|
+
return self._compare(other) > 0
|
|
78
|
+
|
|
79
|
+
def __ge__(self, other):
|
|
80
|
+
return self._compare(other) >= 0
|
|
81
|
+
|
|
82
|
+
def __ne__(self, other):
|
|
83
|
+
return self._compare(other) != 0
|
|
84
|
+
|
|
85
|
+
def __hash__(self):
|
|
86
|
+
return hash(self.vstring)
|
|
87
|
+
|
|
88
|
+
def _compare(self, other):
|
|
89
|
+
if isinstance(other, str):
|
|
90
|
+
other = Version(other)
|
|
91
|
+
if not isinstance(other, Version):
|
|
92
|
+
return NotImplemented
|
|
93
|
+
return (self._key() > other._key()) - (self._key() < other._key())
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def __getattr__(name):
|
|
97
|
+
# 惰性导入私有 impl 模块(避免顶层循环导入)
|
|
98
|
+
if name in ('_function_base_impl', '_nanfunctions_impl',
|
|
99
|
+
'_stride_tricks_impl'):
|
|
100
|
+
from importlib import import_module
|
|
101
|
+
return import_module(f'.{name}', __name__)
|
|
102
|
+
raise AttributeError(f"module 'rsarray.lib' has no attribute {name!r}")
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""lib._function_base_impl 兼容实现。
|
|
3
|
+
|
|
4
|
+
rsarray 的 function_base 公共实现在 ``rsarray._core.function_base``;
|
|
5
|
+
本模块按其 2.x 布局再导出,并补齐移植测试直接引用的私有名。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from rsarray._core.function_base import ( # noqa: F401
|
|
9
|
+
add_newdoc,
|
|
10
|
+
add_docstring,
|
|
11
|
+
_add_docstring,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
import enum
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class _QuantileMethods(str, enum.Enum):
|
|
19
|
+
"""Valid methods for computing quantiles(_QuantileMethods 兼容)。
|
|
20
|
+
|
|
21
|
+
``list(_QuantileMethods)`` 返回五个方法成员;成员为 str 子类,
|
|
22
|
+
可直接作为 method= 参数传给 quantile/nanquantile。
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
LINEAR = 'linear'
|
|
26
|
+
LOWER = 'lower'
|
|
27
|
+
HIGHER = 'higher'
|
|
28
|
+
MIDPOINT = 'midpoint'
|
|
29
|
+
NEAREST = 'nearest'
|
|
30
|
+
|
|
31
|
+
@classmethod
|
|
32
|
+
def is_valid(cls, value):
|
|
33
|
+
return value in [m.value for m in cls]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
__all__ = ['add_newdoc', 'add_docstring', '_add_docstring',
|
|
37
|
+
'_QuantileMethods']
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""mgrid/ogrid/r_ 的实现模块(lib._index_tricks_impl 对应)。
|
|
3
|
+
|
|
4
|
+
rsarray 的 mgrid/ogrid/r_ 实现位于顶层模块;本模块以带完整文档的
|
|
5
|
+
包装对象暴露 mgrid,使 ``np.lib._index_tricks_impl.mgrid.__doc__``
|
|
6
|
+
满足 测试的文档长度契约。
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
_MGRID_DOC = """\
|
|
10
|
+
mgrid(*ranges)
|
|
11
|
+
=============
|
|
12
|
+
|
|
13
|
+
An `ndarray` subclass that returns a filled multi-dimensional or
|
|
14
|
+
"meshgrid" ndarray based on the specified axes, which can be ranges
|
|
15
|
+
or coordinate arrays.
|
|
16
|
+
|
|
17
|
+
Parameters
|
|
18
|
+
----------
|
|
19
|
+
*args : list of scalar or array_like
|
|
20
|
+
Scalars or arrays describing the length and shape of each axis.
|
|
21
|
+
The following examples will yield the same 3-by-4-by-5 by-5
|
|
22
|
+
meshgrid::
|
|
23
|
+
|
|
24
|
+
>>> x = np.mgrid[0:3, 0:4, 0:5:2] # doctest: +SKIP
|
|
25
|
+
>>> y = np.mgrid[:3, :4, 0:5:2] # doctest: +SKIP
|
|
26
|
+
>>> z = np.mgrid[0:3, 4, np.arange(0, 5, 2)] # doctest: +SKIP
|
|
27
|
+
|
|
28
|
+
Returns
|
|
29
|
+
-------
|
|
30
|
+
out : ndarray
|
|
31
|
+
A "meshgrid" of shape (3, 4, 5). For N input *ranges*, a
|
|
32
|
+
sequence of N coordinate arrays of the specified shape is
|
|
33
|
+
returned, broadcast against each other so that each has the
|
|
34
|
+
specified shape. The i-th element of the returned sequence
|
|
35
|
+
indexes along the i-th axis.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class _MGrid:
|
|
40
|
+
"""``np.mgrid`` 的带文档包装(调用转发到 rsarray 顶层实现)。"""
|
|
41
|
+
|
|
42
|
+
__doc__ = _MGRID_DOC
|
|
43
|
+
|
|
44
|
+
def __call__(self, *ranges):
|
|
45
|
+
import rsarray
|
|
46
|
+
return rsarray.mgrid(*ranges)
|
|
47
|
+
|
|
48
|
+
def __getitem__(self, item):
|
|
49
|
+
# 数组语义:mgrid[start:stop:step, ...] 等价于 mgrid(start:stop:step, ...)
|
|
50
|
+
import rsarray
|
|
51
|
+
if not isinstance(item, tuple):
|
|
52
|
+
item = (item,)
|
|
53
|
+
return rsarray.mgrid(*item)
|
|
54
|
+
|
|
55
|
+
def __repr__(self):
|
|
56
|
+
return "mgrid"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
mgrid = _MGrid()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class _OGGrid:
|
|
63
|
+
"""``np.ogrid`` 的带文档包装(调用/下标转发到 rsarray 顶层实现)。"""
|
|
64
|
+
|
|
65
|
+
def __call__(self, *ranges):
|
|
66
|
+
import rsarray
|
|
67
|
+
return rsarray.ogrid(*ranges)
|
|
68
|
+
|
|
69
|
+
def __getitem__(self, item):
|
|
70
|
+
# 数组语义:ogrid[start:stop:step, ...] 等价于 ogrid(start:stop:step, ...)
|
|
71
|
+
import rsarray
|
|
72
|
+
if not isinstance(item, tuple):
|
|
73
|
+
item = (item,)
|
|
74
|
+
return rsarray.ogrid(*item)
|
|
75
|
+
|
|
76
|
+
def __repr__(self):
|
|
77
|
+
return "ogrid"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
ogrid = _OGGrid()
|
|
81
|
+
|
|
82
|
+
_REEXPORT_NAMES = (
|
|
83
|
+
'c_', 'diag_indices', 'diag_indices_from', 'fill_diagonal',
|
|
84
|
+
'index_exp', 'ix_', 'ndenumerate', 'ndindex', 'r_', 's_',
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def __getattr__(name):
|
|
89
|
+
# 惰性从 rsarray 顶层取回(lib 在 rsarray 初始化期间导入,
|
|
90
|
+
# 模块级取属性会撞上部分初始化的命名空间)。
|
|
91
|
+
if name in _REEXPORT_NAMES:
|
|
92
|
+
import rsarray
|
|
93
|
+
return getattr(rsarray, name)
|
|
94
|
+
raise AttributeError(f"module 'rsarray.lib._index_tricks_impl' has no "
|
|
95
|
+
f"attribute {name!r}")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
__all__ = ['mgrid'] + list(_REEXPORT_NAMES)
|