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.
Files changed (59) hide show
  1. rsarray/__init__.py +12028 -0
  2. rsarray/_core/__init__.py +213 -0
  3. rsarray/_core/_exceptions.py +83 -0
  4. rsarray/_core/_internal.py +331 -0
  5. rsarray/_core/_multiarray_tests.py +129 -0
  6. rsarray/_core/_multiarray_umath.py +121 -0
  7. rsarray/_core/_rational_tests.py +52 -0
  8. rsarray/_core/arrayprint.py +36 -0
  9. rsarray/_core/fromnumeric.py +31 -0
  10. rsarray/_core/function_base.py +84 -0
  11. rsarray/_core/multiarray.py +385 -0
  12. rsarray/_core/numeric.py +28 -0
  13. rsarray/_core/numerictypes.py +233 -0
  14. rsarray/_core/records.py +14 -0
  15. rsarray/_core/shape_base.py +23 -0
  16. rsarray/_core/strings.py +78 -0
  17. rsarray/_core/umath.py +176 -0
  18. rsarray/_dtypes.py +1229 -0
  19. rsarray/_extra.py +6621 -0
  20. rsarray/_typing.py +24 -0
  21. rsarray/array_methods.py +1224 -0
  22. rsarray/array_ops.py +1585 -0
  23. rsarray/char.py +1590 -0
  24. rsarray/exceptions.py +45 -0
  25. rsarray/fft/__init__.py +231 -0
  26. rsarray/io.py +453 -0
  27. rsarray/lib/__init__.py +102 -0
  28. rsarray/lib/_function_base_impl.py +37 -0
  29. rsarray/lib/_index_tricks_impl.py +98 -0
  30. rsarray/lib/_nanfunctions_impl.py +1637 -0
  31. rsarray/lib/_stride_tricks_impl.py +110 -0
  32. rsarray/lib/recfunctions.py +1222 -0
  33. rsarray/lib/stride_tricks.py +106 -0
  34. rsarray/linalg/__init__.py +2603 -0
  35. rsarray/linalg/_linalg.py +91 -0
  36. rsarray/linalg/_pylinalg.py +1008 -0
  37. rsarray/linalg/lapack_lite.py +13 -0
  38. rsarray/ma/__init__.py +92 -0
  39. rsarray/ma/core.py +1385 -0
  40. rsarray/ma/extras.py +711 -0
  41. rsarray/ma/mrecords.py +144 -0
  42. rsarray/math_functions.py +965 -0
  43. rsarray/matlib.py +67 -0
  44. rsarray/num_core.cp313-win_amd64.pyd +0 -0
  45. rsarray/polynomial/__init__.py +148 -0
  46. rsarray/polynomial/_npcompat.py +721 -0
  47. rsarray/polynomial/polynomial.py +1082 -0
  48. rsarray/random/__init__.py +2266 -0
  49. rsarray/random/_distributions.py +773 -0
  50. rsarray/rec.py +207 -0
  51. rsarray/statistics.py +1360 -0
  52. rsarray/strings.py +349 -0
  53. rsarray/typing/__init__.py +26 -0
  54. rsarray-1.2.10.dist-info/METADATA +280 -0
  55. rsarray-1.2.10.dist-info/RECORD +59 -0
  56. rsarray-1.2.10.dist-info/WHEEL +4 -0
  57. rsarray-1.2.10.dist-info/licenses/LICENSE +21 -0
  58. rsarray-1.2.10.dist-info/licenses/NOTICE +7 -0
  59. rsarray-1.2.10.dist-info/sboms/rsarray.cyclonedx.json +2789 -0
rsarray/ma/core.py ADDED
@@ -0,0 +1,1385 @@
1
+ # SPDX-License-Identifier: MIT
2
+ """掩码数组核心(ma.core 兼容子集)。
3
+
4
+ 包装底层 ndarray 与逐元素布尔掩码;提供 ma.core 移植测试
5
+ 直接引用的公共名与辅助函数。
6
+ """
7
+
8
+ import builtins
9
+ import warnings
10
+
11
+ import rsarray as np
12
+
13
+
14
+ def _flatten(seq):
15
+ out = []
16
+ for x in seq:
17
+ if isinstance(x, (list, tuple)):
18
+ out.extend(_flatten(x))
19
+ else:
20
+ out.append(x)
21
+ return out
22
+
23
+
24
+ def _record_count(data):
25
+ dt = getattr(data, '_dtype_obj', None)
26
+ if dt is not None:
27
+ return len(np._flatten_records(data._raw_data))
28
+ return data.size
29
+
30
+
31
+ def _fields_leaf_count(dt):
32
+ """结构化 dtype 的每记录叶子数(嵌套字段/子数组递归展开)。"""
33
+ per = 0
34
+ for _n in dt.names:
35
+ fdt = dt.fields[_n][0]
36
+ if getattr(fdt, '_names', None) is not None:
37
+ per += _fields_leaf_count(fdt)
38
+ elif getattr(fdt, '_subdtype', None) is not None:
39
+ _b, _s = fdt._subdtype
40
+ c = 1
41
+ for s2 in (_s or ()):
42
+ c *= s2
43
+ if getattr(_b, '_names', None) is not None:
44
+ per += c * _fields_leaf_count(_b)
45
+ else:
46
+ per += c
47
+ else:
48
+ per += 1
49
+ return per
50
+
51
+
52
+ def _leaf_count(data):
53
+ """掩码长度语义:普通数组 = size;结构化数组 = size × 每记录字段叶子数
54
+ (—结构化 ma 的掩码为字段级)。"""
55
+ dt = getattr(data, 'dtype', None)
56
+ names = getattr(dt, 'names', None)
57
+ size = int(getattr(data, 'size', 0) or 0)
58
+ if not names:
59
+ return size
60
+ return size * _fields_leaf_count(dt)
61
+
62
+
63
+ def _is_ma(a):
64
+ return isinstance(a, MaskedArray)
65
+
66
+
67
+ class MAError(ValueError):
68
+ """掩码数组错误(ma.core.MAError 兼容)。"""
69
+
70
+
71
+ class MaskError(Exception):
72
+ """掩码相关错误(ma.core.MaskError 兼容)。"""
73
+
74
+
75
+ class MaskedArrayFutureWarning(FutureWarning):
76
+ """ma.core.MaskedArrayFutureWarning 兼容占位。"""
77
+
78
+
79
+ _ma_argsort_default = object()
80
+ _ma_reduce_default = object()
81
+
82
+
83
+ def _ma_mask_or(m1, m2, size):
84
+ """掩码按位或,双方各自广播到 size(广播语义:1 → 全部重复,
85
+ n < size → 平铺裁剪)。"""
86
+ def bc(m):
87
+ if len(m) == size:
88
+ return list(m)
89
+ if len(m) == 1:
90
+ return list(m) * size if size else []
91
+ if len(m) < size:
92
+ reps = (size + len(m) - 1) // len(m)
93
+ return (list(m) * reps)[:size]
94
+ return list(m)[:size]
95
+ a = bc(m1)
96
+ b = bc(m2)
97
+ return [x or y for x, y in zip(a, b)]
98
+
99
+
100
+ class MaskedArray:
101
+ """带掩码的数组:包装底层 ndarray 与逐元素布尔掩码。"""
102
+
103
+ def __init__(self, data=None, mask=False, dtype=None, fill_value=None,
104
+ copy=False, **kwargs):
105
+ _ = copy, kwargs
106
+ _src_ma = None
107
+ if isinstance(data, MaskedArray):
108
+ base_mask = list(data._mask)
109
+ _src_ma = data
110
+ data = data._data
111
+ else:
112
+ base_mask = None
113
+ if not hasattr(data, '_array'):
114
+ data = np.array(data, dtype=dtype) if dtype is not None else np.array(data)
115
+ elif dtype is not None:
116
+ data = data.view(dtype)
117
+ self._data = data
118
+ # 掩码长度语义:普通数组 = size;结构化数组 = size ×
119
+ # 每记录字段叶子数(字段级掩码)。展平后按叶子数对齐:
120
+ # 单值广播、不足补 False、超长截断——不做记录级截断(那会
121
+ # 丢失字段级掩码信息)。
122
+ n = _leaf_count(data)
123
+ if mask is None or mask is False:
124
+ m = base_mask if base_mask is not None else [False]
125
+ elif mask is True:
126
+ m = [True]
127
+ else:
128
+ mm = mask.tolist() if hasattr(mask, 'tolist') else list(mask)
129
+ m = [bool(x) for x in _flatten(mm)]
130
+ if len(m) == 1 and n > 1:
131
+ m = m * n
132
+ if len(m) > n:
133
+ m = m[:n]
134
+ if len(m) < n:
135
+ m = m + [False] * (n - len(m))
136
+ self._mask = m
137
+ self.fill_value = self._as_fill(fill_value)
138
+
139
+ def _as_fill(self, fv):
140
+ """fill_value 规范化:按 data dtype 存为 0-d 数组(ma 语义:
141
+ x.fill_value.dtype == x.dtype;不可转换则存原值)。"""
142
+ if fv is None:
143
+ return None
144
+ try:
145
+ if hasattr(fv, 'astype'):
146
+ # np.array(0-d ndarray, dtype=...) 不改 dtype,须用 astype
147
+ return fv.astype(self._data.dtype)
148
+ return np.array(fv, dtype=self._data.dtype)
149
+ except Exception:
150
+ try:
151
+ return np.array(fv)
152
+ except Exception:
153
+ return fv
154
+
155
+ # ------------------------------------------------------------------
156
+ # 属性
157
+ # ------------------------------------------------------------------
158
+ @property
159
+ def dtype(self):
160
+ return self._data.dtype
161
+
162
+ @dtype.setter
163
+ def dtype(self, value):
164
+ # gh-31192:设置 dtype 为弃用行为(发警告但仍生效)
165
+ warnings.warn(
166
+ "Setting the dtype on a MaskedArray is deprecated and will be "
167
+ "removed in a future version.",
168
+ DeprecationWarning, stacklevel=2)
169
+ self._data = self._data.astype(value)
170
+
171
+ @property
172
+ def shape(self):
173
+ return self._data.shape
174
+
175
+ @property
176
+ def ndim(self):
177
+ return self._data.ndim
178
+
179
+ @property
180
+ def size(self):
181
+ return self._data.size
182
+
183
+ @property
184
+ def data(self):
185
+ return self._data
186
+
187
+ @property
188
+ def mask(self):
189
+ m = np.array(self._mask, dtype='bool')
190
+ if len(self._mask) == int(self.size):
191
+ # 普通数组:掩码形状与数据形状一致
192
+ try:
193
+ return m.reshape(self.shape)
194
+ except Exception:
195
+ return m
196
+ # 结构化字段级掩码:长度 = 叶子数(size × 每记录字段数),平坦表示
197
+ return m
198
+
199
+ @mask.setter
200
+ def mask(self, value):
201
+ if value is None:
202
+ self._mask = [False] * _leaf_count(self._data)
203
+ return
204
+ mask = np.asarray(value, dtype='bool')
205
+ if mask.ndim == 0:
206
+ self._mask = [bool(mask)] * _leaf_count(self._data)
207
+ return
208
+ self._mask = [bool(item) for item in mask.reshape((-1,)).tolist()]
209
+
210
+ def _mask_flat(self):
211
+ return list(self._mask)
212
+
213
+ def tolist(self):
214
+ """ma 语义:返回值(masked 位置保留原数据)。"""
215
+ return self._data.tolist()
216
+
217
+ def copy(self):
218
+ """返回独立副本(data 与 mask 均拷贝)。"""
219
+ return MaskedArray(self._data.copy(), list(self._mask))
220
+
221
+ def _as_fill(self, fv):
222
+ """fill_value 规范化:按 data dtype 存为 0-d 数组(ma 语义:
223
+ x.fill_value.dtype == x.dtype;不可转换则存原值)。"""
224
+ if fv is None:
225
+ return None
226
+ try:
227
+ if hasattr(fv, 'astype'):
228
+ # np.array(0-d ndarray, dtype=...) 不改 dtype,须用 astype
229
+ return fv.astype(self._data.dtype)
230
+ return np.array(fv, dtype=self._data.dtype)
231
+ except Exception:
232
+ try:
233
+ return np.array(fv)
234
+ except Exception:
235
+ return fv
236
+
237
+ def _fill_lossy(self, fv):
238
+ """fill 值向当前 dtype 的转换是否 lossy(浮点静默回绕视为 lossy)。"""
239
+ dt = str(self._data.dtype)
240
+ try:
241
+ if hasattr(fv, 'astype'):
242
+ cast = fv.astype(dt)
243
+ else:
244
+ cast = np.array(fv, dtype=dt)
245
+ except Exception:
246
+ return True
247
+ if isinstance(fv, float) and 'int' in dt and not (abs(fv) < 2 ** 63):
248
+ return True
249
+ try:
250
+ return bool(isinstance(fv, float) and 'int' in dt
251
+ and float(cast) != fv)
252
+ except Exception:
253
+ return False
254
+
255
+ def _inherit_fill(self, src):
256
+ """从源 MaskedArray 继承 fill(exact 保留,lossy 忽略)。"""
257
+ if _is_ma(src) and getattr(src, '_fill_value', None) is not None \
258
+ and not self._fill_lossy(src._fill_value):
259
+ self._fill_value = src._fill_value
260
+
261
+ def astype(self, dtype, **kwargs):
262
+ """dtype 转换:data 走 ndarray.astype,掩码原样保留。"""
263
+ _ = kwargs
264
+ return MaskedArray(self._data.astype(dtype), mask=list(self._mask),
265
+ fill_value=self.fill_value)
266
+
267
+ def _ma_extreme(self, which, axis=None):
268
+ """掩码感知 min/max:掩码位填 ±inf 后归约(ma 语义:忽略
269
+ masked 元素)。axis=None 返回 0-d MaskedArray;axis 返回轴归约。"""
270
+ import math as _math
271
+ d = self._data
272
+ shp = tuple(d.shape)
273
+ msk = np.array(self._mask, dtype='bool')
274
+ if len(msk) == int(self.size):
275
+ msk = msk.reshape(shp)
276
+ flat_v = d.reshape((-1,)).tolist() if d.ndim else [d.tolist()]
277
+ flat_m = msk.reshape((-1,)).tolist()
278
+ fillv = float('inf') if which == 'min' else float('-inf')
279
+ fv = [fillv if mv else v for v, mv in zip(flat_v, flat_m)]
280
+ if axis is None:
281
+ if not fv:
282
+ return MaskedArray(np.array(0.0), mask=[True])
283
+ r = builtins.min(fv) if which == 'min' else builtins.max(fv)
284
+ if r == fillv or (isinstance(r, float) and r != r):
285
+ # 全掩码(或 nan):masked 标量
286
+ return MaskedArray(np.array(flat_v[0]), mask=[True])
287
+ return MaskedArray(np.array(r), mask=[False])
288
+ nd = len(shp)
289
+ ax = axis % nd
290
+ order = [i for i in range(nd) if i != ax] + [ax]
291
+
292
+ def build(flat, dims):
293
+ if not dims:
294
+ return flat[0]
295
+ step = 1
296
+ for s in dims[1:]:
297
+ step *= s
298
+ return [build(flat[i * step:(i + 1) * step], dims[1:])
299
+ for i in range(dims[0])]
300
+
301
+ nest = build(fv, [shp[i] for i in order])
302
+
303
+ def reduce_last(lst):
304
+ if lst and isinstance(lst[0], list):
305
+ return [reduce_last(x) for x in lst]
306
+ return builtins.min(lst) if which == 'min' \
307
+ else builtins.max(lst)
308
+
309
+ red = reduce_last(nest)
310
+ out_shp = tuple(shp[i] for i in order[:-1])
311
+ res = np.array(red)
312
+ if out_shp:
313
+ res = res.reshape(out_shp)
314
+ # 全掩码行 → 掩码位为 True
315
+ _of = [1 if v == fillv else 0 for v in red] if not out_shp \
316
+ else None
317
+ # 逐行掩码:构造行掩码嵌套
318
+ def rowmask(flat, dims):
319
+ if not dims:
320
+ return flat[0]
321
+ step = 1
322
+ for s in dims[1:]:
323
+ step *= s
324
+ return [rowmask(flat[i * step:(i + 1) * step], dims[1:])
325
+ for i in range(dims[0])]
326
+
327
+ fm = [1 if v == fillv else 0 for v in fv]
328
+ nm = build(fm, [shp[i] for i in order])
329
+
330
+ def mask_last(lst):
331
+ if lst and isinstance(lst[0], list):
332
+ return [mask_last(x) for x in lst]
333
+ return 1 if builtins.all(lst) else 0
334
+
335
+ rm = mask_last(nm)
336
+ rm = np.array(rm, dtype='bool').reshape(out_shp)
337
+ out = MaskedArray(res, mask=False)
338
+ out._mask = [bool(x) for x
339
+ in rm.reshape((-1,)).tolist()]
340
+ out.fill_value = self.fill_value
341
+ return out
342
+ if red == fillv:
343
+ return MaskedArray(np.array(flat_v[0]), mask=[True])
344
+ return MaskedArray(np.array(red), mask=[False])
345
+
346
+ def reshape(self, *args, **kwargs):
347
+ """reshape:data 变形,平坦掩码直接沿用(元素总数不变)。"""
348
+ return MaskedArray(self._data.reshape(*args, **kwargs),
349
+ mask=list(self._mask),
350
+ fill_value=self.fill_value)
351
+
352
+ def min(self, axis=None, out=None, keepdims=False):
353
+ """掩码感知最小值(ma 语义:忽略 masked 元素)。"""
354
+ _ = out, keepdims
355
+ return self._ma_extreme('min', axis)
356
+
357
+ def max(self, axis=None, out=None, keepdims=False):
358
+ """掩码感知最大值(ma 语义:忽略 masked 元素)。"""
359
+ _ = out, keepdims
360
+ return self._ma_extreme('max', axis)
361
+
362
+ # ------------------------------------------------------------------
363
+ # 转置族(ma 语义:结果保留掩码)
364
+ # ------------------------------------------------------------------
365
+ def _ma_rebuild(self, data, mask_flat):
366
+ out = MaskedArray(data, mask=False)
367
+ out._mask = list(mask_flat)
368
+ out.fill_value = self.fill_value
369
+ return out
370
+
371
+ def transpose(self, *axes):
372
+ data_t = self._data.transpose(*axes) if axes else self._data.T
373
+ m = np.asarray(self._mask, dtype='bool').reshape(self.shape)
374
+ mask_t = m.transpose(*axes) if axes else m.T
375
+ return self._ma_rebuild(data_t, mask_t.reshape((-1,)).tolist())
376
+
377
+ def swapaxes(self, axis1, axis2):
378
+ data_t = self._data.swapaxes(axis1, axis2)
379
+ m = np.asarray(self._mask, dtype='bool').reshape(self.shape)
380
+ mask_t = m.swapaxes(axis1, axis2)
381
+ return self._ma_rebuild(data_t, mask_t.reshape((-1,)).tolist())
382
+
383
+ @property
384
+ def T(self):
385
+ return self.transpose()
386
+
387
+ @property
388
+ def mT(self):
389
+ if self.ndim < 2:
390
+ raise ValueError("matrix transpose with ndim < 2 is undefined")
391
+ return self.swapaxes(self.ndim - 2, self.ndim - 1)
392
+
393
+ def argsort(self, axis=_ma_argsort_default, kind=None, order=None):
394
+ """掩码感知 argsort(ma.argsort 兼容,gh-8701 警告语义)。"""
395
+ return _ma_argsort_impl(self, axis, kind, order)
396
+
397
+ # ------------------------------------------------------------------
398
+ # 算术/比较 dunder:掩码按位或传播(ma 语义的核心子集)
399
+ # ------------------------------------------------------------------
400
+ def _ma_binop(self, other, op, reflected=False):
401
+ if isinstance(other, _MaskedConstant):
402
+ other = other._as_ma()
403
+ a = self._data
404
+ b = other._data if _is_ma(other) else other
405
+ res = op(b, a) if reflected else op(a, b)
406
+ if not hasattr(res, '_array'):
407
+ res = np.asarray(res)
408
+ if _is_ma(other):
409
+ m = _ma_mask_or(self._mask, other._mask,
410
+ int(getattr(res, 'size', len(self._mask))))
411
+ else:
412
+ m = list(self._mask)
413
+ fill = self.fill_value if self.fill_value is not None else None
414
+ return MaskedArray(res, mask=m, fill_value=fill)
415
+
416
+ def _ma_refop(self, other, op):
417
+ if not _is_ma(other):
418
+ return NotImplemented
419
+ return other._ma_binop(self, op, reflected=True)
420
+
421
+ def __add__(self, other):
422
+ return self._ma_binop(other, np.add)
423
+
424
+ def __radd__(self, other):
425
+ return self._ma_refop(other, np.add)
426
+
427
+ def __sub__(self, other):
428
+ return self._ma_binop(other, np.subtract)
429
+
430
+ def __rsub__(self, other):
431
+ return self._ma_refop(other, np.subtract)
432
+
433
+ def __mul__(self, other):
434
+ return self._ma_binop(other, np.multiply)
435
+
436
+ def __rmul__(self, other):
437
+ return self._ma_refop(other, np.multiply)
438
+
439
+ def __truediv__(self, other):
440
+ return self._ma_binop(other, np.divide)
441
+
442
+ def __rtruediv__(self, other):
443
+ return self._ma_refop(other, np.divide)
444
+
445
+ def __floordiv__(self, other):
446
+ return self._ma_binop(other, np.floor_divide)
447
+
448
+ def __rfloordiv__(self, other):
449
+ return self._ma_refop(other, np.floor_divide)
450
+
451
+ def __mod__(self, other):
452
+ return self._ma_binop(other, np.mod)
453
+
454
+ def __rmod__(self, other):
455
+ return self._ma_refop(other, np.mod)
456
+
457
+ def __pow__(self, other):
458
+ return self._ma_binop(other, np.power)
459
+
460
+ def __rpow__(self, other):
461
+ return self._ma_refop(other, np.power)
462
+
463
+ def __neg__(self):
464
+ return self._ma_binop(-1, np.multiply)
465
+
466
+ def __pos__(self):
467
+ return MaskedArray(self._data, list(self._mask),
468
+ fill_value=self.fill_value)
469
+
470
+ def __abs__(self):
471
+ # abs 是一元算子:不能走二元 _ma_binop(会双参调用 op)。
472
+ # mask 恒等传播(|x| 不改变掩码)。
473
+ res = np.abs(self._data)
474
+ fill = self.fill_value if self.fill_value is not None else None
475
+ return MaskedArray(res, mask=list(self._mask), fill_value=fill)
476
+
477
+ def _ma_cmp(self, other, op):
478
+ # ma _comparison 权威语义:
479
+ # - mask = self.mask OR other.mask
480
+ # - data = op(raw data)
481
+ # - 仅 ==/!=:掩码位的 data 改为 op(self_mask, other_mask)
482
+ # (双掩码视为相等,单掩码视为不等);其余比较 data 保持 raw
483
+ # - fill_value 转 bool(默认 True)
484
+ a = self._data
485
+ if isinstance(other, _MaskedConstant):
486
+ other = other._as_ma()
487
+ b = other._data if _is_ma(other) else other
488
+ res = op(a, b)
489
+ if not hasattr(res, '_array'):
490
+ res = np.asarray(res)
491
+ omask = list(other._mask) if _is_ma(other) else None
492
+ if omask is not None:
493
+ m = _ma_mask_or(self._mask, omask,
494
+ int(getattr(res, 'size', len(self._mask))))
495
+ else:
496
+ m = list(self._mask)
497
+ is_eqne = op is np.equal or op is np.not_equal
498
+ if is_eqne:
499
+ try:
500
+ if res.ndim == 0:
501
+ sm = bool(self._mask[0]) if self._mask else False
502
+ om = bool(omask[0]) if omask else False
503
+ v = (sm == om) if op is np.equal else (sm != om)
504
+ res = np.array([v], dtype='bool').reshape(())
505
+ else:
506
+ flat = res.reshape((-1,)).tolist()
507
+ nf = []
508
+ for i, mv in enumerate(m):
509
+ if mv:
510
+ sm = bool(self._mask[i]) \
511
+ if i < len(self._mask) else False
512
+ om = bool(omask[i]) \
513
+ if omask is not None and i < len(omask) \
514
+ else False
515
+ nf.append((sm == om) if op is np.equal
516
+ else (sm != om))
517
+ else:
518
+ nf.append(flat[i])
519
+ res = np.array(nf, dtype='bool').reshape(res.shape)
520
+ except Exception:
521
+ pass
522
+ if self.fill_value is None:
523
+ fv = True
524
+ else:
525
+ try:
526
+ fv = bool(self.fill_value)
527
+ except Exception:
528
+ fv = True
529
+ return MaskedArray(res, mask=m, fill_value=fv)
530
+
531
+ def __eq__(self, other):
532
+ return self._ma_cmp(other, np.equal)
533
+
534
+ def __ne__(self, other):
535
+ return self._ma_cmp(other, np.not_equal)
536
+
537
+ def __lt__(self, other):
538
+ return self._ma_cmp(other, np.less)
539
+
540
+ def __le__(self, other):
541
+ return self._ma_cmp(other, np.less_equal)
542
+
543
+ def __gt__(self, other):
544
+ return self._ma_cmp(other, np.greater)
545
+
546
+ def __ge__(self, other):
547
+ return self._ma_cmp(other, np.greater_equal)
548
+
549
+ def __and__(self, other):
550
+ return self._ma_binop(other, np.logical_and)
551
+
552
+ def __or__(self, other):
553
+ return self._ma_binop(other, np.logical_or)
554
+
555
+ def __xor__(self, other):
556
+ return self._ma_binop(other, np.logical_xor)
557
+
558
+ def __rand__(self, other):
559
+ return self._ma_refop(other, np.logical_and)
560
+
561
+ def __ror__(self, other):
562
+ return self._ma_refop(other, np.logical_or)
563
+
564
+ def __rxor__(self, other):
565
+ return self._ma_refop(other, np.logical_xor)
566
+
567
+ def view(self, dtype=None, type=None):
568
+ _ = type
569
+ if dtype is None:
570
+ return MaskedArray(self._data, list(self._mask))
571
+ newdata = self._data.view(dtype)
572
+ newn = _leaf_count(newdata)
573
+ newmask = list(self._mask) if len(self._mask) == newn else [False] * newn
574
+ return MaskedArray(newdata, newmask)
575
+
576
+ def filled(self, fill_value=None):
577
+ value = self.fill_value if fill_value is None else fill_value
578
+ if value is None:
579
+ value = 0
580
+ result = self._data.copy()
581
+ result[self.mask] = value
582
+ return result
583
+
584
+ def compressed(self):
585
+ return self._data[~self.mask].copy()
586
+
587
+ def __getitem__(self, key):
588
+ res = self._data[key]
589
+ if hasattr(res, 'ndim') and getattr(res, 'ndim', 0) > 0:
590
+ m = np.array(self._mask, dtype='bool')
591
+ _sz = int(self.size)
592
+ try:
593
+ if len(self._mask) == _sz:
594
+ m = m.reshape(self.shape)
595
+ m_res = m[key]
596
+ else:
597
+ m_res = None
598
+ except Exception:
599
+ m_res = None
600
+ if m_res is not None:
601
+ m_flat = [bool(x) for x
602
+ in np.asarray(m_res).reshape((-1,)).tolist()]
603
+ else:
604
+ m_flat = [False] * (int(res.size)
605
+ if hasattr(res, 'size') else 0)
606
+ return MaskedArray(res, m_flat)
607
+ # 标量索引返回 0-d MaskedArray(ma 语义:掩码信息不能丢,
608
+ # 否则后续比较走 ndarray 标量分支抛 Unsupported operand type)
609
+ try:
610
+ mv = bool(self._mask[int(key)]) if int(key) < len(self._mask) \
611
+ else False
612
+ except Exception:
613
+ mv = False
614
+ return MaskedArray(res, [mv])
615
+
616
+ def __setitem__(self, key, value):
617
+ self._data[key] = value
618
+
619
+ def __len__(self):
620
+ return len(self._data)
621
+
622
+ def __iter__(self):
623
+ return iter(self._data)
624
+
625
+ def __repr__(self):
626
+ return "masked_array(data=%s,\n mask=%s)" % (self._data, self._mask)
627
+
628
+ def __str__(self):
629
+ return self.__repr__()
630
+
631
+
632
+ def array(data=None, mask=False, dtype=None, fill_value=None, copy=False, **kwargs):
633
+ """构造一个掩码数组。"""
634
+ return MaskedArray(data, mask=mask, dtype=dtype, fill_value=fill_value,
635
+ copy=copy, **kwargs)
636
+
637
+
638
+ masked_array = MaskedArray
639
+
640
+
641
+ def getdata(a):
642
+ """返回掩码数组的底层数据。"""
643
+ return a._data if _is_ma(a) else a
644
+
645
+
646
+ def getmask(a):
647
+ """ma.getmask 兼容:非掩码数组返回 nomask。"""
648
+ if _is_ma(a):
649
+ return a._mask
650
+ return nomask
651
+
652
+
653
+ def getmaskarray(a):
654
+ """返回掩码数组的布尔掩码。"""
655
+ if _is_ma(a):
656
+ return a.mask
657
+ return np.zeros(getattr(a, 'shape', (0,)), dtype='bool')
658
+
659
+
660
+ def asarray(a, dtype=None):
661
+ if _is_ma(a):
662
+ if dtype is not None and a.dtype != np.dtype(dtype):
663
+ return MaskedArray(a.data.astype(dtype), a.mask, fill_value=a.fill_value)
664
+ return a
665
+ return MaskedArray(np.asarray(a, dtype=dtype))
666
+
667
+
668
+ def isMaskedArray(a):
669
+ return _is_ma(a)
670
+
671
+
672
+ def masked_values(data, value, rtol=1e-5, atol=1e-8, copy=True):
673
+ data = np.array(data, copy=copy)
674
+ mask = np.abs(data - value) <= atol + rtol * np.abs(value)
675
+ return MaskedArray(data, mask=mask, fill_value=value)
676
+
677
+
678
+ def masked_invalid(data, copy=True):
679
+ data = np.array(data, copy=copy)
680
+ return MaskedArray(data, mask=~np.isfinite(data))
681
+
682
+
683
+ class _MaskedConstant:
684
+ """np.ma.masked 单例:按 数组语义表现为 0-d float64 MaskedArray
685
+ (值 0.0、全掩码)。委托给惰性创建的 MaskedArray 实例。"""
686
+
687
+ # 哨兵:np.add 等核心 ufunc 据此短路返回常量自身(避免循环导入)
688
+ _ma_masked_self = True
689
+
690
+ def __repr__(self):
691
+ return 'masked'
692
+
693
+ def __str__(self):
694
+ return 'masked'
695
+
696
+ def __bool__(self):
697
+ return False
698
+
699
+ def _as_ma(self):
700
+ if '_ma' not in self.__dict__:
701
+ self._ma = MaskedArray(np.array(0.0), mask=[True])
702
+ return self._ma
703
+
704
+ def __getattr__(self, name):
705
+ # 常规查找失败后委托给 0-d MaskedArray(dtype/_data/_mask/算术等)
706
+ return getattr(self._as_ma(), name)
707
+
708
+ def __int__(self):
709
+ # 数组语义:int(masked) 对整型目标抛 MaskError(不可静默取值)
710
+ raise MaskError("Cannot convert masked constant to int")
711
+
712
+ def __float__(self):
713
+ return float(self._as_ma()._data)
714
+
715
+ def __index__(self):
716
+ return 0
717
+
718
+ # 数组语义:与 masked 常量的任何二元运算都返回 masked 单例自身
719
+ def _masked_ret(self, *args, **kwargs):
720
+ return self
721
+
722
+ __add__ = _masked_ret
723
+ __radd__ = _masked_ret
724
+ __sub__ = _masked_ret
725
+ __rsub__ = _masked_ret
726
+ __mul__ = _masked_ret
727
+ __rmul__ = _masked_ret
728
+ __truediv__ = _masked_ret
729
+ __rtruediv__ = _masked_ret
730
+ __floordiv__ = _masked_ret
731
+ __rfloordiv__ = _masked_ret
732
+ __mod__ = _masked_ret
733
+ __rmod__ = _masked_ret
734
+ __pow__ = _masked_ret
735
+ __rpow__ = _masked_ret
736
+ __and__ = _masked_ret
737
+ __rand__ = _masked_ret
738
+ __or__ = _masked_ret
739
+ __ror__ = _masked_ret
740
+ __xor__ = _masked_ret
741
+ __rxor__ = _masked_ret
742
+ __eq__ = _masked_ret
743
+ __ne__ = _masked_ret
744
+ __lt__ = _masked_ret
745
+ __le__ = _masked_ret
746
+ __gt__ = _masked_ret
747
+ __ge__ = _masked_ret
748
+
749
+
750
+ masked = _MaskedConstant()
751
+ nomask = False
752
+ MaskType = np.bool_
753
+
754
+
755
+ # ---------------------------------------------------------------------------
756
+ # 掩码构造器(ma.core.masked_* 兼容)
757
+ # ---------------------------------------------------------------------------
758
+
759
+ def masked_equal(a, value, copy=True):
760
+ a = np.array(a, copy=copy) if not hasattr(a, '_array') else a
761
+ return MaskedArray(a, mask=(a == value))
762
+
763
+
764
+ def masked_not_equal(a, value, copy=True):
765
+ a = np.array(a, copy=copy) if not hasattr(a, '_array') else a
766
+ return MaskedArray(a, mask=(a != value))
767
+
768
+
769
+ def masked_greater(a, t, copy=True):
770
+ a = np.array(a, copy=copy) if not hasattr(a, '_array') else a
771
+ return MaskedArray(a, mask=(a > t))
772
+
773
+
774
+ def masked_greater_equal(a, t, copy=True):
775
+ a = np.array(a, copy=copy) if not hasattr(a, '_array') else a
776
+ return MaskedArray(a, mask=(a >= t))
777
+
778
+
779
+ def masked_less(a, t, copy=True):
780
+ a = np.array(a, copy=copy) if not hasattr(a, '_array') else a
781
+ return MaskedArray(a, mask=(a < t))
782
+
783
+
784
+ def masked_less_equal(a, t, copy=True):
785
+ a = np.array(a, copy=copy) if not hasattr(a, '_array') else a
786
+ return MaskedArray(a, mask=(a <= t))
787
+
788
+
789
+ def masked_inside(a, left, right, copy=True):
790
+ a = np.array(a, copy=copy) if not hasattr(a, '_array') else a
791
+ return MaskedArray(a, mask=((a >= left) & (a <= right)))
792
+
793
+
794
+ def masked_outside(a, left, right, copy=True):
795
+ a = np.array(a, copy=copy) if not hasattr(a, '_array') else a
796
+ return MaskedArray(a, mask=((a < left) | (a > right)))
797
+
798
+
799
+ def masked_object(a, copy=True):
800
+ """掩掉 None 与 NaN 元素(ma.masked_object 兼容)。"""
801
+ a = np.array(a, copy=copy) if not hasattr(a, '_array') else a
802
+ vals = a.tolist()
803
+ flat = _flatten(vals)
804
+ mask = [v is None or (isinstance(v, float) and v != v) for v in flat]
805
+ return MaskedArray(a, mask=mask)
806
+
807
+
808
+ def masked_where(condition, a, **kwargs):
809
+ """按条件生成掩码数组(ma.masked_where 兼容)。"""
810
+ cond = np.array(condition, dtype=bool) if not hasattr(condition, '_array') else condition
811
+ return MaskedArray(a, mask=cond)
812
+
813
+
814
+ def mvoid(a):
815
+ """全部掩码的掩码数组(ma.mvoid 兼容)。"""
816
+ return MaskedArray(a, mask=True)
817
+
818
+
819
+ # ---------------------------------------------------------------------------
820
+ # 掩码/填充值辅助
821
+ # ---------------------------------------------------------------------------
822
+
823
+ def common_fill_value(dtype):
824
+ """dtype 的默认填充值(ma.common_fill_value 兼容)。"""
825
+ dt = np.dtype(dtype)
826
+ kind = dt.kind
827
+ if kind in ('U', 'S'):
828
+ return ''
829
+ if kind == 'c':
830
+ return complex(np.inf, np.inf)
831
+ if kind == 'f':
832
+ return np.inf
833
+ if kind == 'b':
834
+ return False
835
+ if kind in ('i', 'u'):
836
+ return 999999
837
+ if kind in ('M', 'm'):
838
+ return 'NaT'
839
+ return 0
840
+
841
+
842
+ def default_fill_value(a):
843
+ if _is_ma(a):
844
+ if a.fill_value is not None:
845
+ return a.fill_value
846
+ return common_fill_value(getattr(a, 'dtype', 'f'))
847
+
848
+
849
+ def maximum_fill_value(dt):
850
+ dt = np.dtype(dt)
851
+ kind = dt.kind
852
+ if kind == 'b':
853
+ return True
854
+ if kind == 'f':
855
+ return np.inf
856
+ if kind in ('i', 'u'):
857
+ return int(np.iinfo(dt).max)
858
+ if kind in ('M', 'm'):
859
+ return np.iinfo(np.dtype('int64')).max
860
+ return 0
861
+
862
+
863
+ def minimum_fill_value(dt):
864
+ dt = np.dtype(dt)
865
+ kind = dt.kind
866
+ if kind == 'b':
867
+ return False
868
+ if kind == 'f':
869
+ return -np.inf
870
+ if kind in ('i', 'u'):
871
+ return int(np.iinfo(dt).min)
872
+ if kind in ('M', 'm'):
873
+ return int(np.iinfo(np.dtype('int64')).min)
874
+ return 0
875
+
876
+
877
+ def make_mask(a, shrink=True, mask=nomask):
878
+ """为 a 构造布尔掩码(ma.make_mask 兼容)。"""
879
+ if mask is nomask:
880
+ if _is_ma(a):
881
+ return a._mask if a._mask.__class__ is list else nomask
882
+ return nomask
883
+ if _is_ma(a) and mask is a._mask:
884
+ return mask
885
+ m = np.asarray(mask, dtype='bool')
886
+ if m.shape != tuple(getattr(a, 'shape', ())) and m.size == 1:
887
+ m = np.broadcast_to(m, tuple(getattr(a, 'shape', ())))
888
+ if shrink:
889
+ if not bool(m.any()):
890
+ return nomask
891
+ return m
892
+
893
+
894
+ def make_mask_descr(dtype):
895
+ """掩码的 dtype 描述(结构化 → 字段描述列表;否则 bool)。"""
896
+ dt = np.dtype(dtype)
897
+ if dt.names:
898
+ return [(n, 'bool') for n in dt.names]
899
+ return 'bool'
900
+
901
+
902
+ def flatten_mask(mask):
903
+ if mask is nomask:
904
+ return nomask
905
+ m = np.asarray(mask, dtype='bool')
906
+ return m.reshape((-1,))
907
+
908
+
909
+ def mask_or(a, b):
910
+ """两个掩码按位或(ma.mask_or 兼容)。"""
911
+ ma_ = getmaskarray(a)
912
+ mb_ = getmaskarray(b)
913
+ if ma_ is nomask:
914
+ return mb_
915
+ if mb_ is nomask:
916
+ return ma_
917
+ return ma_ | mb_
918
+
919
+
920
+ def fix_invalid(a):
921
+ """把 inf/NaN 掩掉(ma.fix_invalid 兼容)。"""
922
+ a = asarray(a)
923
+ data = a.data
924
+ bad = ~np.isfinite(data)
925
+ newmask = list(a._mask)
926
+ for i, b in enumerate(bad.reshape((-1,)).tolist()):
927
+ if i < len(newmask):
928
+ newmask[i] = newmask[i] or bool(b)
929
+ a._mask = newmask[:_leaf_count(data)]
930
+ return a
931
+
932
+
933
+ def count(a, axis=None, **kwargs):
934
+ """未掩码元素计数(ma.count 兼容)。"""
935
+ a = asarray(a) if not _is_ma(a) else a
936
+ m = getmaskarray(a)
937
+ if m is nomask:
938
+ return a.size if axis is None else a.shape[axis]
939
+ unmasked = ~m
940
+ if axis is None:
941
+ return int(unmasked.sum())
942
+ return unmasked.sum(axis=axis)
943
+
944
+
945
+ def filled(a, fill_value=None):
946
+ """掩码位置填值后返回普通数组(ma.filled 兼容)。"""
947
+ if _is_ma(a):
948
+ return a.filled(fill_value)
949
+ return a
950
+
951
+
952
+ def anom(a, tol=1e-05):
953
+ """掩掉 |x| <= tol 的"异常零"值(ma.anom 兼容)。"""
954
+ a = np.asarray(a)
955
+ return MaskedArray(a, mask=(np.abs(a) <= tol))
956
+
957
+
958
+ def minmax(a):
959
+ """返回 (未掩码最小, 未掩码最大)(ma.minmax 兼容)。"""
960
+ a = asarray(a)
961
+ c = a.compressed()
962
+ if c.size == 0:
963
+ raise MAError("No minimal/maximal values")
964
+ return (c.min(), c.max())
965
+
966
+
967
+ def masked_print_option(legacy_print=False):
968
+ import warnings
969
+ warnings.warn("ma.masked_print_option is deprecated and will be "
970
+ "removed; it is a no-op.", DeprecationWarning, stacklevel=2)
971
+
972
+ def f(x):
973
+ return x
974
+ return f
975
+
976
+
977
+ def fromflex(fld, **kwargs):
978
+ raise NotImplementedError(
979
+ "rsarray.ma.fromflex is not implemented (flexible file format)")
980
+
981
+
982
+ def flatten_structured_array(a, out_dtype=None):
983
+ """单字段结构化数组 → 普通数组(ma.flatten_structured_array 兼容)。"""
984
+ dt = np.dtype(getattr(a, 'dtype', a))
985
+ if dt.names and len(dt.names) == 1:
986
+ return a[dt.names[0]]
987
+ return np.asarray(a)
988
+
989
+
990
+ def anomalies(a, axis=None, dtype=None):
991
+ """标准分数(z-score),掩码感知(ma.anomalies 兼容)。
992
+
993
+ 结果 = (a - mean)/std,沿 axis 归一化;std == 0 的位置与输入掩码
994
+ 位置一并掩码。
995
+ """
996
+ a = asarray(a)
997
+ if axis is None:
998
+ mean = a.mean()
999
+ std = a.std()
1000
+ out = (a - mean) / std
1001
+ if bool(std == 0):
1002
+ return MaskedArray(out.data, mask=[True] * a.size,
1003
+ fill_value=a.fill_value)
1004
+ return out
1005
+ mean = a.mean(axis=axis)
1006
+ std = a.std(axis=axis)
1007
+ if a.ndim > 0 and getattr(mean, 'ndim', 0) == a.ndim - 1:
1008
+ shape = [1] * a.ndim
1009
+ shape[axis] = a.shape[axis]
1010
+ mean = mean.reshape(tuple(shape))
1011
+ std = std.reshape(tuple(shape))
1012
+ out = (a - mean) / std
1013
+ bad = (std == 0)
1014
+ bad_data = bad.data if hasattr(bad, 'data') else bad
1015
+ if bool(np.asarray(bad_data).any()):
1016
+ try:
1017
+ bad_b = np.broadcast_to(np.asarray(bad_data), a.shape)
1018
+ except Exception:
1019
+ bad_b = np.asarray(bad_data)
1020
+ m = getmaskarray(out)
1021
+ m_data = m.data if isinstance(m, MaskedArray) else m
1022
+ m_final = bad_b if m is nomask else (m_data | bad_b)
1023
+ flat = list(np.asarray(m_final).reshape((-1,)).tolist())
1024
+ return MaskedArray(out.data, mask=flat, fill_value=a.fill_value)
1025
+ return out
1026
+
1027
+
1028
+ def allequal(a, b):
1029
+ """两数组逐元素相等(只在双方都未掩码的位置比较,ma.allequal 兼容)。"""
1030
+ a = asarray(a)
1031
+ b = asarray(b)
1032
+ if a.shape != b.shape:
1033
+ return False
1034
+ ma_ = getmaskarray(a)
1035
+ mb_ = getmaskarray(b)
1036
+ if ma_ is nomask and mb_ is nomask:
1037
+ return bool((a.data == b.data).all())
1038
+ m = mask_or(ma_, mb_)
1039
+ if m is nomask or not bool(m.any()):
1040
+ return bool((a.data == b.data).all())
1041
+ unmasked = ~m
1042
+ sub_a = a.data[unmasked]
1043
+ sub_b = b.data[unmasked]
1044
+ if sub_a.size == 0:
1045
+ return True
1046
+ return bool((sub_a == sub_b).all())
1047
+
1048
+
1049
+ def alltrue(a, axis=None, **kwargs):
1050
+ """未掩码元素全为真(掩码元素忽略,ma.alltrue 兼容)。"""
1051
+ a = asarray(a)
1052
+ if axis is None:
1053
+ c = a.compressed()
1054
+ return bool((c != 0).all()) if c.size else True
1055
+ m = getmaskarray(a)
1056
+ ok = (a.data != 0)
1057
+ if m is not nomask:
1058
+ ok = ok & ~m
1059
+ return ok.all(axis=axis)
1060
+
1061
+
1062
+ def sometrue(a, axis=None, **kwargs):
1063
+ """任一未掩码元素为真(掩码元素忽略,ma.sometrue 兼容)。"""
1064
+ a = asarray(a)
1065
+ if axis is None:
1066
+ c = a.compressed()
1067
+ return bool((c != 0).any()) if c.size else False
1068
+ m = getmaskarray(a)
1069
+ ok = (a.data != 0)
1070
+ if m is not nomask:
1071
+ ok = ok & ~m
1072
+ return ok.any(axis=axis)
1073
+
1074
+
1075
+ # ---------------------------------------------------------------------------
1076
+ # 构造器与 re-export(ma.core 公共名从 rsarray 顶层取回)
1077
+ # ---------------------------------------------------------------------------
1078
+
1079
+ def zeros(shape, dtype=float, **kwargs):
1080
+ """全零掩码数组(ma.zeros 兼容)。"""
1081
+ return MaskedArray(np.zeros(shape, dtype=dtype))
1082
+
1083
+
1084
+ def ones(shape, dtype=float, **kwargs):
1085
+ """全一掩码数组(ma.ones 兼容)。"""
1086
+ return MaskedArray(np.ones(shape, dtype=dtype))
1087
+
1088
+
1089
+ def empty(shape, dtype=float, **kwargs):
1090
+ """未初始化掩码数组(ma.empty 兼容)。"""
1091
+ return MaskedArray(np.empty(shape, dtype=dtype))
1092
+
1093
+
1094
+ def full(shape, fill_value, dtype=None, **kwargs):
1095
+ """定值掩码数组(ma.full 兼容)。"""
1096
+ return MaskedArray(np.full(shape, fill_value, dtype=dtype))
1097
+
1098
+
1099
+ def ones_like(a, dtype=None):
1100
+ return MaskedArray(np.ones_like(a.data if _is_ma(a) else a, dtype=dtype),
1101
+ mask=list(asarray(a)._mask) if _is_ma(a) else None)
1102
+
1103
+
1104
+ def zeros_like(a, dtype=None):
1105
+ return MaskedArray(np.zeros_like(a.data if _is_ma(a) else a, dtype=dtype),
1106
+ mask=list(asarray(a)._mask) if _is_ma(a) else None)
1107
+
1108
+
1109
+ def empty_like(a, dtype=None):
1110
+ return MaskedArray(np.empty_like(a.data if _is_ma(a) else a, dtype=dtype),
1111
+ mask=list(asarray(a)._mask) if _is_ma(a) else None)
1112
+
1113
+
1114
+ # ma 专属构造器:本地定义返回 MaskedArray(np.ma.zeros 等语义),
1115
+ # 不可被 np 同名普通数组构造器覆盖。
1116
+ _MA_OWN_CONSTRUCTORS = (
1117
+ 'empty', 'empty_like', 'full', 'full_like',
1118
+ 'ones', 'ones_like', 'zeros', 'zeros_like',
1119
+ )
1120
+
1121
+
1122
+ def _copy_names():
1123
+ names = (
1124
+ 'abs', 'absolute', 'add', 'all', 'allclose', 'allequal', 'alltrue',
1125
+ 'angle', 'any', 'arange', 'arccos', 'arccosh', 'arcsin', 'arctan',
1126
+ 'arctan2', 'argsort', 'choose', 'concatenate', 'conjugate', 'cos',
1127
+ 'cosh', 'deg2rad', 'diag', 'divide', 'empty', 'empty_like', 'equal',
1128
+ 'exp', 'expm1', 'fabs', 'fix', 'floor', 'full', 'full_like',
1129
+ 'greater', 'greater_equal', 'hstack', 'identity', 'inner', 'less',
1130
+ 'less_equal', 'log', 'log10', 'log1p', 'log2', 'logaddexp', 'logical_and',
1131
+ 'logical_or', 'logical_xor', 'maximum', 'minimum', 'mod', 'multiply',
1132
+ 'ndim', 'not_equal', 'ones', 'ones_like', 'outer', 'power', 'prod',
1133
+ 'product', 'rad2deg', 'ravel', 'repeat', 'reshape', 'resize',
1134
+ 'rint', 'shape', 'sin', 'sinh', 'sometrue', 'sort', 'sqrt',
1135
+ 'subtract', 'sum', 'tan', 'tanh', 'transpose', 'trunc', 'where',
1136
+ 'vstack', 'zeros', 'zeros_like', 'min', 'max', 'mean', 'std',
1137
+ 'var', 'cumsum', 'cumprod', 'ptp', 'take', 'put', 'putmask',
1138
+ 'swapaxes', 'newaxis', 'nonzero', 'hypot',
1139
+ )
1140
+ d = {}
1141
+ for n in names:
1142
+ if n in _MA_OWN_CONSTRUCTORS:
1143
+ continue
1144
+ if hasattr(np, n):
1145
+ d[n] = getattr(np, n)
1146
+ return d
1147
+
1148
+
1149
+ for _n, _v in _copy_names().items():
1150
+ globals()[_n] = _v
1151
+ del _copy_names, _n, _v
1152
+
1153
+ # 二元 ufunc 对 masked 常量短路(数组语义:add(masked, x) → masked)
1154
+ _MA_BIN_UFUNCS = (
1155
+ 'add', 'subtract', 'divide', 'equal', 'not_equal',
1156
+ 'greater', 'greater_equal', 'less', 'less_equal',
1157
+ 'logical_and', 'logical_or', 'logical_xor',
1158
+ 'arctan2', 'hypot', 'logaddexp', 'maximum', 'minimum',
1159
+ 'mod', 'power', 'outer', 'inner',
1160
+ )
1161
+
1162
+
1163
+ def _ma_ufunc_shortcircuit(f):
1164
+ def _w(*args, **kwargs):
1165
+ for _a in args:
1166
+ if isinstance(a := _a, _MaskedConstant):
1167
+ return a
1168
+ return f(*args, **kwargs)
1169
+ return _w
1170
+
1171
+
1172
+ for _n in _MA_BIN_UFUNCS:
1173
+ if _n in globals():
1174
+ globals()[_n] = _ma_ufunc_shortcircuit(globals()[_n])
1175
+ del _MA_BIN_UFUNCS, _ma_ufunc_shortcircuit, _n
1176
+
1177
+
1178
+ # ---- 掩码感知 argsort / minmax(ma 语义;覆盖上面从 np 拷贝的同名函数)----
1179
+
1180
+ def _ma_argsort_impl(a, axis, kind=None, order=None):
1181
+ # gh-8701:>1-d 的默认 axis(None/展平)未来将变为 -1
1182
+ if axis is _ma_argsort_default:
1183
+ axis = None
1184
+ if a.ndim > 1:
1185
+ warnings.warn(
1186
+ "the default axis of argsort for 2-d arrays is not going to "
1187
+ "be the same as the axis of sort in the future; values will "
1188
+ "be sorted along the last axis instead.",
1189
+ MaskedArrayFutureWarning, stacklevel=3)
1190
+ if axis is not None:
1191
+ ax = axis % a.ndim
1192
+ res = np.argsort(a.data, axis=ax)
1193
+ return MaskedArray(res, mask=False, fill_value=a.fill_value)
1194
+ # axis=None:展平 argsort,masked 元素排末尾
1195
+ flat = a.data.reshape((-1,)).tolist()
1196
+ if not isinstance(flat, list):
1197
+ flat = [flat]
1198
+ mask_flat = ([bool(x) for x in a._mask]
1199
+ if a._mask is not nomask else [False] * len(flat))
1200
+ idx = sorted(range(len(flat)), key=lambda i: (mask_flat[i], flat[i]))
1201
+ return MaskedArray(np.array(idx, dtype='int64'), mask=False,
1202
+ fill_value=a.fill_value)
1203
+
1204
+
1205
+ def argsort(a, axis=_ma_argsort_default, kind=None, order=None):
1206
+ """掩码感知 argsort(ma.argsort 兼容;gh-8701 警告语义)。"""
1207
+ return _ma_argsort_impl(asarray(a), axis, kind, order)
1208
+
1209
+
1210
+ class _ma_minmax:
1211
+ """ma.minimum/maximum:可调二元算子 + .reduce(1.13 axis 警告语义)。"""
1212
+
1213
+ def __init__(self, name, use_min):
1214
+ self.__name__ = name
1215
+ self._use_min = use_min
1216
+ self.__doc__ = "mask-aware %s (ma.%s compatible)" % (name, name)
1217
+
1218
+ def __call__(self, a, b, **kw):
1219
+ return (np.minimum(a, b, **kw) if self._use_min
1220
+ else np.maximum(a, b, **kw))
1221
+
1222
+ def reduce(self, a, axis=_ma_reduce_default, **kw):
1223
+ a = asarray(a)
1224
+ if axis is _ma_reduce_default:
1225
+ axis = None
1226
+ if a.ndim > 1:
1227
+ warnings.warn(
1228
+ "the default axis of reduce for 2-d arrays is not going "
1229
+ "to be the same as the axis of sum in the future.",
1230
+ MaskedArrayFutureWarning, stacklevel=3)
1231
+ op = builtins.min if self._use_min else builtins.max
1232
+ fill = a.fill_value
1233
+
1234
+ def _fill0():
1235
+ return fill if fill is not None else 0
1236
+
1237
+ if a.ndim <= 1 or axis is None:
1238
+ flat = a.data.reshape((-1,)).tolist()
1239
+ if not isinstance(flat, list):
1240
+ flat = [flat]
1241
+ mask_flat = ([bool(x) for x in a._mask]
1242
+ if a._mask is not nomask else [False] * len(flat))
1243
+ vals = [v for v, mm in zip(flat, mask_flat) if not mm]
1244
+ if not vals:
1245
+ return _fill0()
1246
+ return op(vals)
1247
+ # per-axis(2-d 简化:沿行/列取 min/max,masked 元素不参与)
1248
+ ax = axis % a.ndim
1249
+ d = a.data.tolist()
1250
+ rows, cols = len(d), len(d[0])
1251
+ mask_flat = ([bool(x) for x in a._mask]
1252
+ if a._mask is not nomask else [False] * (rows * cols))
1253
+ out = []
1254
+ if ax == 1:
1255
+ for i in range(rows):
1256
+ vals = [d[i][j] for j in range(cols)
1257
+ if not mask_flat[i * cols + j]]
1258
+ out.append(op(vals) if vals else _fill0())
1259
+ else:
1260
+ for j in range(cols):
1261
+ vals = [d[i][j] for i in range(rows)
1262
+ if not mask_flat[i * cols + j]]
1263
+ out.append(op(vals) if vals else _fill0())
1264
+ return np.array(out, dtype=a.data.dtype)
1265
+
1266
+
1267
+ minimum = _ma_minmax('minimum', True)
1268
+ maximum = _ma_minmax('maximum', False)
1269
+
1270
+ # 遗留别名:product = prod。np.product 在顶层于 ma 导入之后才挂载,
1271
+ # _copy_names 时尚不可见,这里显式补齐。
1272
+ product = prod
1273
+
1274
+
1275
+ # ---- 精确签名函数(测试用 inspect.signature 断言;须位于 _copy_names
1276
+ # ---- 循环之后以覆盖从 np 拷贝的同名函数)
1277
+
1278
+ def nonzero(a):
1279
+ """掩码感知 nonzero:返回未掩码非零元素的索引元组(ma.nonzero)。"""
1280
+ a = asarray(a)
1281
+ m = getmaskarray(a)
1282
+ ok = a.data != 0
1283
+ if m is not nomask:
1284
+ m_data = m.data if isinstance(m, MaskedArray) else m
1285
+ ok = ok & ~m_data
1286
+ idx = np.nonzero(ok)
1287
+ return tuple(idx)
1288
+
1289
+
1290
+ def cumsum(a, axis=None, dtype=None, out=None):
1291
+ """掩码感知累计和(ma.cumsum 兼容;掩码保留)。"""
1292
+ a = asarray(a)
1293
+ d = a.data
1294
+ res = d.cumsum() if axis is None else d.cumsum(axis=axis)
1295
+ if dtype is not None:
1296
+ res = res.astype(dtype)
1297
+ mask = list(a._mask) if a._mask is not nomask else False
1298
+ return MaskedArray(res, mask=mask, fill_value=a.fill_value)
1299
+
1300
+
1301
+ def compress(condition, a, axis=None, out=None):
1302
+ """按条件提取元素(ma.compress 兼容;掩码位置不选入)。"""
1303
+ a = asarray(a)
1304
+ cond = np.asarray(condition)
1305
+ if axis is not None:
1306
+ res = np.compress(cond, a.data, axis=axis)
1307
+ return MaskedArray(res, mask=False, fill_value=a.fill_value)
1308
+ cond_flat = [bool(c) for c in list(np.asarray(cond).reshape((-1,)).tolist())]
1309
+ data_flat = list(a.data.reshape((-1,)).tolist())
1310
+ if a._mask is not nomask:
1311
+ mask_flat = list(a._mask)
1312
+ else:
1313
+ mask_flat = [False] * a.size
1314
+ vals = [d for c, d, m in zip(cond_flat, data_flat, mask_flat)
1315
+ if c and not m]
1316
+ return MaskedArray(np.array(vals, dtype=a.data.dtype), mask=False,
1317
+ fill_value=a.fill_value)
1318
+
1319
+
1320
+ def empty(shape, dtype=None, order='C', *, device=None, like=None,
1321
+ fill_value=None, hardmask=False):
1322
+ """掩码空数组(ma.empty 兼容;精确签名)。"""
1323
+ _ = order, device, like, hardmask
1324
+ arr = np.empty(shape, dtype=dtype)
1325
+ fv = common_fill_value(arr.dtype) if fill_value is None else fill_value
1326
+ try:
1327
+ arr.fill(fv)
1328
+ except Exception:
1329
+ pass
1330
+ return MaskedArray(arr, mask=False, fill_value=fv)
1331
+
1332
+
1333
+ def empty_like(prototype, /, dtype=None, order='K', subok=True,
1334
+ shape=None, *, device=None):
1335
+ """同形状掩码空数组(ma.empty_like 兼容;精确签名)。"""
1336
+ _ = order, subok, device
1337
+ proto = prototype.data if isinstance(prototype, MaskedArray) else prototype
1338
+ if shape is not None:
1339
+ arr = np.empty(shape, dtype=dtype if dtype is not None
1340
+ else proto.dtype)
1341
+ else:
1342
+ arr = np.empty_like(proto, dtype=dtype)
1343
+ return MaskedArray(arr, mask=False, fill_value=common_fill_value(arr.dtype))
1344
+
1345
+
1346
+ def squeeze(a, axis=None, *, fill_value=None, hardmask=False):
1347
+ """压缩单元素轴(ma.squeeze 兼容;精确签名)。"""
1348
+ _ = hardmask
1349
+ a = asarray(a)
1350
+ res = a.data.squeeze(axis=axis) if axis is not None else a.data.squeeze()
1351
+ m = getmaskarray(a)
1352
+ mask = False
1353
+ if m is not nomask:
1354
+ m_arr = m.data if isinstance(m, MaskedArray) else m
1355
+ try:
1356
+ ms = (np.asarray(m_arr).squeeze(axis=axis) if axis is not None
1357
+ else np.asarray(m_arr).squeeze())
1358
+ mask = list(ms.reshape((-1,)).tolist())
1359
+ except Exception:
1360
+ mask = False
1361
+ fv = a.fill_value if fill_value is None else fill_value
1362
+ return MaskedArray(res, mask=mask, fill_value=fv)
1363
+
1364
+
1365
+ def identity(n, dtype=None, *, like=None, fill_value=None, hardmask=False):
1366
+ """单位矩阵(ma.identity 兼容;精确签名)。"""
1367
+ _ = like, hardmask
1368
+ arr = np.identity(n, dtype=dtype)
1369
+ fv = common_fill_value(arr.dtype) if fill_value is None else fill_value
1370
+ return MaskedArray(arr, mask=False, fill_value=fv)
1371
+
1372
+
1373
+ __all__ = ['MAError', 'MaskError', 'MaskType', 'MaskedArray',
1374
+ 'MaskedArrayFutureWarning', 'array', 'masked_array', 'masked',
1375
+ 'nomask', 'masked_print_option', 'anom', 'minmax', 'mvoid',
1376
+ 'fromflex', 'flatten_structured_array', 'getdata', 'getmask',
1377
+ 'getmaskarray', 'asarray', 'isMaskedArray', 'masked_values',
1378
+ 'masked_invalid', 'masked_equal', 'masked_not_equal',
1379
+ 'masked_greater', 'masked_greater_equal', 'masked_less',
1380
+ 'masked_less_equal', 'masked_inside', 'masked_outside',
1381
+ 'masked_object', 'masked_where', 'common_fill_value',
1382
+ 'default_fill_value', 'maximum_fill_value', 'minimum_fill_value',
1383
+ 'make_mask', 'make_mask_descr', 'flatten_mask', 'mask_or',
1384
+ 'fix_invalid', 'count', 'filled', 'zeros', 'ones', 'empty',
1385
+ 'full', 'ones_like', 'zeros_like', 'empty_like']