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
|
@@ -0,0 +1,1082 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""polynomial.polynomial 兼容模块(新 API:升序系数,低次在前)。
|
|
3
|
+
|
|
4
|
+
数值内核复用 Rust _core(polyadd/polysub/polymul/polydiv/polyroots,
|
|
5
|
+
均为降序系数约定,边界处反转);求值/积分/导数/拟合走 rsarray 数组
|
|
6
|
+
运算或 lstsq(保持 dtype 与 object 语义);校验、lbnd/k/scl、axis、
|
|
7
|
+
deg 幂列表、__array_function__ 派发按 2.x 语义实现。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import builtins
|
|
11
|
+
import itertools as _itertools
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
'polyzero', 'polyone', 'polyx', 'polydomain',
|
|
15
|
+
'polyval', 'polyvalfromroots', 'polyval2d', 'polyval3d', 'polyvalnd',
|
|
16
|
+
'polygrid2d', 'polygrid3d',
|
|
17
|
+
'polyder', 'polyint',
|
|
18
|
+
'polyroots', 'polyfromroots', 'polyfit',
|
|
19
|
+
'polyadd', 'polysub', 'polymul', 'polymulx', 'polydiv', 'polypow',
|
|
20
|
+
'polytrim', 'polycompanion', 'polyline',
|
|
21
|
+
'polyvander', 'polyvander2d', 'polyvander3d',
|
|
22
|
+
'Polynomial',
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _NX():
|
|
27
|
+
import rsarray
|
|
28
|
+
return rsarray
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _core():
|
|
32
|
+
import rsarray.num_core as _c
|
|
33
|
+
return _c
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _nd():
|
|
37
|
+
from rsarray import ndarray
|
|
38
|
+
return ndarray
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _wrap(raw):
|
|
42
|
+
return _nd()(raw)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _raw(a):
|
|
46
|
+
if hasattr(a, '_array'):
|
|
47
|
+
return a._array
|
|
48
|
+
return _core().ndarray(a)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _frac_type():
|
|
52
|
+
from fractions import Fraction
|
|
53
|
+
return Fraction
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _isfrac(x):
|
|
57
|
+
return isinstance(x, _frac_type())
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _is_py_scalar(x):
|
|
61
|
+
return isinstance(x, (int, float, complex)) or _isfrac(x)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _pyval(c, x):
|
|
65
|
+
"""Horner 求值(升序系数 c)。object dtype(Fraction)标量精确。"""
|
|
66
|
+
y = 0
|
|
67
|
+
for pv in reversed(c):
|
|
68
|
+
y = y * x + pv
|
|
69
|
+
return y
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _flat_shape(shape):
|
|
73
|
+
n = 1
|
|
74
|
+
for s in shape:
|
|
75
|
+
n *= int(s)
|
|
76
|
+
return n
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _unflat(vals, shape):
|
|
80
|
+
"""1-D 列表 → 嵌套列表(C 序);shape=() 返回标量。"""
|
|
81
|
+
shape = tuple(shape)
|
|
82
|
+
if not shape:
|
|
83
|
+
return vals[0]
|
|
84
|
+
sz = _flat_shape(shape[1:])
|
|
85
|
+
if sz == 0:
|
|
86
|
+
return [_unflat([], shape[1:]) for _ in range(shape[0])]
|
|
87
|
+
return [_unflat(vals[i * sz:(i + 1) * sz], shape[1:])
|
|
88
|
+
for i in range(shape[0])]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _flat_list(data):
|
|
92
|
+
"""嵌套列表 → 1-D 列表(C 序)。"""
|
|
93
|
+
if not isinstance(data, (list, tuple)):
|
|
94
|
+
return [data]
|
|
95
|
+
out = []
|
|
96
|
+
for v in data:
|
|
97
|
+
out.extend(_flat_list(v))
|
|
98
|
+
return out
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _idx_unflat(gi, shape):
|
|
102
|
+
"""flat C 序索引 → 多下标元组。"""
|
|
103
|
+
idx = []
|
|
104
|
+
for s in reversed(shape):
|
|
105
|
+
idx.append(int(gi % s))
|
|
106
|
+
gi //= s
|
|
107
|
+
return tuple(reversed(idx))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _multiget(nested, idx):
|
|
111
|
+
v = nested
|
|
112
|
+
for i in idx:
|
|
113
|
+
v = v[i]
|
|
114
|
+
return v
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _mk_array(vals):
|
|
118
|
+
"""构造 ndarray;含 Fraction 时走 object dtype(保精确值)。"""
|
|
119
|
+
NX = _NX()
|
|
120
|
+
if isinstance(vals, (list, tuple)):
|
|
121
|
+
flat = _flat_list(list(vals))
|
|
122
|
+
else:
|
|
123
|
+
flat = [vals]
|
|
124
|
+
if any(_isfrac(v) for v in flat):
|
|
125
|
+
seq = list(vals) if isinstance(vals, (list, tuple)) else [vals]
|
|
126
|
+
return NX.array(seq, dtype='object')
|
|
127
|
+
return NX.array(vals)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _dispatch(args, func, kwargs=None):
|
|
131
|
+
"""__array_function__ 派发(2.x:第一个实现该协议的参数类型,
|
|
132
|
+
在实例上调用 type(a).__array_function__(a, func, (t,), args, kwargs))。"""
|
|
133
|
+
if kwargs is None:
|
|
134
|
+
kwargs = {}
|
|
135
|
+
for a in args:
|
|
136
|
+
t = builtins.type(a)
|
|
137
|
+
af = getattr(t, '__array_function__', None)
|
|
138
|
+
if af is not None:
|
|
139
|
+
return af(a, func, (t,), args, kwargs)
|
|
140
|
+
return None
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def __getattr__(name):
|
|
144
|
+
"""常量惰性构造:包在 rsarray 部分初始化期被 import 时(rsarray/__init__
|
|
145
|
+
早期 from .polynomial import ...)ndarray 尚不可用,推迟到运行时。"""
|
|
146
|
+
if name == 'polyzero':
|
|
147
|
+
return _nd()([0.])
|
|
148
|
+
if name == 'polyone':
|
|
149
|
+
return _nd()([1.])
|
|
150
|
+
if name == 'polyx':
|
|
151
|
+
return _nd()([0., 1.])
|
|
152
|
+
if name == 'polydomain':
|
|
153
|
+
return _nd()([-1., 1.])
|
|
154
|
+
raise AttributeError("module 'rsarray.polynomial.polynomial' has no "
|
|
155
|
+
"attribute %r" % (name,))
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _py_mul(a, b):
|
|
159
|
+
"""升序系数相乘(纯 Python,object dtype 安全)。"""
|
|
160
|
+
n, m = len(a), len(b)
|
|
161
|
+
out = [0] * (n + m - 1)
|
|
162
|
+
for i in range(n):
|
|
163
|
+
for j in range(m):
|
|
164
|
+
out[i + j] = out[i + j] + a[i] * b[j]
|
|
165
|
+
return out
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _py_add(a, b):
|
|
169
|
+
"""升序系数相加(纯 Python,object dtype 安全)。"""
|
|
170
|
+
n = builtins.max(len(a), len(b))
|
|
171
|
+
return [(a[i] if i < len(a) else 0) + (b[i] if i < len(b) else 0)
|
|
172
|
+
for i in range(n)]
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
# ========== 求值 ==========
|
|
176
|
+
|
|
177
|
+
def polyval(x, c, tensor=True):
|
|
178
|
+
"""按升序系数在 x 处求值。c 多维时末轴为批量维:
|
|
179
|
+
tensor=True 输出形状 c.shape[1:] + x.shape,否则 x.shape + c.shape[1:]。"""
|
|
180
|
+
r = _dispatch((x, c), polyval, {'tensor': tensor})
|
|
181
|
+
if r is not None:
|
|
182
|
+
return r
|
|
183
|
+
NX = _NX()
|
|
184
|
+
c = NX.asarray(c)
|
|
185
|
+
cshape = tuple(c.shape)
|
|
186
|
+
cvals = c.tolist()
|
|
187
|
+
if c.ndim == 1:
|
|
188
|
+
if not cvals:
|
|
189
|
+
return NX.array([])
|
|
190
|
+
if _is_py_scalar(x):
|
|
191
|
+
return _pyval(cvals, x)
|
|
192
|
+
xarr = NX.asanyarray(x)
|
|
193
|
+
y = NX.zeros_like(xarr)
|
|
194
|
+
for pv in reversed(cvals):
|
|
195
|
+
y = y * xarr + pv
|
|
196
|
+
return y
|
|
197
|
+
# c 多维:首轴系数轴,其余批量轴
|
|
198
|
+
xarr = NX.asanyarray(x)
|
|
199
|
+
xshape = tuple(xarr.shape)
|
|
200
|
+
xflat = _flat_list(xarr.tolist())
|
|
201
|
+
npts = _flat_shape(xshape) if xshape else 1
|
|
202
|
+
nb = _flat_shape(cshape[1:])
|
|
203
|
+
res = [0.0] * (nb * npts)
|
|
204
|
+
for g in range(nb):
|
|
205
|
+
gidx = _idx_unflat(g, cshape[1:])
|
|
206
|
+
ccol = [_multiget(cvals, (i,) + gidx) for i in range(cshape[0])]
|
|
207
|
+
for k in range(npts):
|
|
208
|
+
v = _pyval(ccol, xflat[k])
|
|
209
|
+
if tensor:
|
|
210
|
+
res[g * npts + k] = v
|
|
211
|
+
else:
|
|
212
|
+
res[k * nb + g] = v
|
|
213
|
+
out_shape = cshape[1:] + xshape if tensor else xshape + cshape[1:]
|
|
214
|
+
return NX.array(_unflat(res, out_shape))
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def polyvalfromroots(x, roots, tensor=True):
|
|
218
|
+
"""Πᵢ (x - roots[i]);roots 多维时末轴组分别求值。
|
|
219
|
+
tensor=True:输出形状 roots.shape[1:] + x.shape;
|
|
220
|
+
tensor=False:x 与根组逐组配对(第 i 个 x 点配第 i 组根),
|
|
221
|
+
输出形状 roots.shape[1:](roots 须 ≥2 维)。"""
|
|
222
|
+
NX = _NX()
|
|
223
|
+
x = NX.asanyarray(x)
|
|
224
|
+
roots = NX.asarray(roots)
|
|
225
|
+
if roots.ndim == 0:
|
|
226
|
+
# 0 维根 = 单根(数组语义)
|
|
227
|
+
rshape = (1,)
|
|
228
|
+
rval = [roots.tolist()]
|
|
229
|
+
else:
|
|
230
|
+
rshape = tuple(roots.shape)
|
|
231
|
+
rval = roots.tolist()
|
|
232
|
+
xshape = tuple(x.shape)
|
|
233
|
+
if len(rshape) > 1:
|
|
234
|
+
out_shape = rshape[1:] + xshape if tensor else rshape[1:]
|
|
235
|
+
elif tensor:
|
|
236
|
+
out_shape = xshape
|
|
237
|
+
else:
|
|
238
|
+
raise ValueError("too few dimensions in `roots`")
|
|
239
|
+
xval = x.tolist()
|
|
240
|
+
ndx = x.ndim
|
|
241
|
+
if ndx == 0:
|
|
242
|
+
xflat = [xval]
|
|
243
|
+
xshape = (1,)
|
|
244
|
+
else:
|
|
245
|
+
xflat = _flat_list(xval)
|
|
246
|
+
npts = _flat_shape(xshape)
|
|
247
|
+
if len(rshape) > 1:
|
|
248
|
+
gshape = rshape[1:]
|
|
249
|
+
ng = _flat_shape(gshape)
|
|
250
|
+
if tensor:
|
|
251
|
+
res = [0.0] * (ng * npts)
|
|
252
|
+
for gi in range(ng):
|
|
253
|
+
gidx = _idx_unflat(gi, gshape)
|
|
254
|
+
for k in range(npts):
|
|
255
|
+
v = 1.0
|
|
256
|
+
for i in range(rshape[0]):
|
|
257
|
+
v *= (xflat[k] - _multiget(rval, (i,) + gidx))
|
|
258
|
+
res[gi * npts + k] = v
|
|
259
|
+
else:
|
|
260
|
+
# 逐组配对:x[i] 与第 i 组根
|
|
261
|
+
if npts < ng:
|
|
262
|
+
raise ValueError("x must have at least as many points "
|
|
263
|
+
"as root groups for tensor=False")
|
|
264
|
+
res = [0.0] * ng
|
|
265
|
+
for gi in range(ng):
|
|
266
|
+
gidx = _idx_unflat(gi, gshape)
|
|
267
|
+
v = 1.0
|
|
268
|
+
for i in range(rshape[0]):
|
|
269
|
+
v *= (xflat[gi] - _multiget(rval, (i,) + gidx))
|
|
270
|
+
res[gi] = v
|
|
271
|
+
return NX.array(_unflat(res, out_shape))
|
|
272
|
+
# 1 维 roots:单组
|
|
273
|
+
res = []
|
|
274
|
+
for xv in xflat:
|
|
275
|
+
v = 1.0
|
|
276
|
+
for rr in rval:
|
|
277
|
+
v *= (xv - rr)
|
|
278
|
+
res.append(v)
|
|
279
|
+
return NX.array(_unflat(res, out_shape))
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
# ========== 导数 / 积分 ==========
|
|
283
|
+
|
|
284
|
+
def _apply_along_axis(c, fn, axis):
|
|
285
|
+
"""对 ndarray c 沿系数轴 axis 逐段应用 fn(list)->list(transpose 实现,
|
|
286
|
+
任意维:先转置把系数轴放最后,折叠前置维后逐行应用)。"""
|
|
287
|
+
NX = _NX()
|
|
288
|
+
shape = tuple(c.shape)
|
|
289
|
+
nd = builtins.len(shape)
|
|
290
|
+
if nd <= 1:
|
|
291
|
+
return NX.array(fn(c.tolist()))
|
|
292
|
+
ax = axis if axis >= 0 else axis + nd
|
|
293
|
+
perm = [a for a in range(nd) if a != ax]
|
|
294
|
+
perm.append(ax)
|
|
295
|
+
t = c.transpose(tuple(perm))
|
|
296
|
+
tshape = tuple(shape[p] for p in perm)
|
|
297
|
+
lead = _flat_shape(tshape[:-1])
|
|
298
|
+
t2 = t.reshape((lead, tshape[-1]))
|
|
299
|
+
fn_out = [fn(row) for row in t2.tolist()]
|
|
300
|
+
new_len = builtins.len(fn_out[0])
|
|
301
|
+
o = NX.array(fn_out).reshape(tshape[:-1] + (new_len,))
|
|
302
|
+
inv = [0] * nd
|
|
303
|
+
for i, p in enumerate(perm):
|
|
304
|
+
inv[p] = i
|
|
305
|
+
return o.transpose(tuple(inv))
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _der1d(cvals, m, scl):
|
|
309
|
+
cur = list(cvals)
|
|
310
|
+
for _ in range(m): # m 为 float 时自然 TypeError
|
|
311
|
+
if len(cur) <= 1:
|
|
312
|
+
cur = [0.0]
|
|
313
|
+
else:
|
|
314
|
+
cur = [(j + 1) * scl * cur[j + 1] for j in range(len(cur) - 1)]
|
|
315
|
+
return cur
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _int1d(cvals, m, k, lbnd, scl):
|
|
319
|
+
cur = list(cvals)
|
|
320
|
+
for i in range(m):
|
|
321
|
+
cur = [v * scl for v in cur] # scl 每次积分都乘(数组语义)
|
|
322
|
+
if builtins.len(cur) == 1 and cur[0] == 0:
|
|
323
|
+
# 长度为 1 的零多项式:保持长度,只累加积分常数(数组语义)
|
|
324
|
+
cur = [cur[0] + k[i]]
|
|
325
|
+
else:
|
|
326
|
+
nxt = [0] + [cur[j] / (j + 1) for j in range(len(cur))]
|
|
327
|
+
# lbnd 语义:第 i+1 次积分后的多项式在 lbnd 处取值恰为 k[i]
|
|
328
|
+
if lbnd is not None:
|
|
329
|
+
nxt[0] = nxt[0] + k[i] - _pyval(nxt, lbnd)
|
|
330
|
+
else:
|
|
331
|
+
nxt[0] = nxt[0] + k[i]
|
|
332
|
+
cur = nxt
|
|
333
|
+
return cur
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _check_axis(axis):
|
|
337
|
+
if axis is not None and (isinstance(axis, bool) or not isinstance(axis, int)):
|
|
338
|
+
raise TypeError("axis must be an integer")
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def polyder(c, m=1, scl=1, axis=0):
|
|
342
|
+
"""m 阶导数(每阶乘 scl)。axis 指定系数轴(默认 0)。"""
|
|
343
|
+
_check_axis(axis)
|
|
344
|
+
NX = _NX()
|
|
345
|
+
if m < 0:
|
|
346
|
+
raise ValueError("m must be non-negative")
|
|
347
|
+
c = NX.asarray(c)
|
|
348
|
+
if c.ndim == 1:
|
|
349
|
+
return NX.array(_der1d(c.tolist(), m, scl))
|
|
350
|
+
ax = 0 if axis is None else axis
|
|
351
|
+
fn = lambda v: _der1d(v, m, scl)
|
|
352
|
+
return _apply_along_axis(c, fn, ax)
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def polyint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
|
|
356
|
+
"""m 次积分(默认 k=[]、lbnd=0、scl=1、axis=0)。
|
|
357
|
+
k 为各次积分常数(标量或长 m 序列,空序列=全零);
|
|
358
|
+
lbnd 标量:使第 i+1 次积分后多项式在 lbnd 处取 k[i];scl 整体缩放。"""
|
|
359
|
+
_check_axis(axis)
|
|
360
|
+
NX = _NX()
|
|
361
|
+
if m < 0:
|
|
362
|
+
raise ValueError("m must be non-negative")
|
|
363
|
+
if isinstance(k, (list, tuple)):
|
|
364
|
+
if len(k) > m:
|
|
365
|
+
raise ValueError("Too many integration constants")
|
|
366
|
+
# 短序列零填充(数组语义)
|
|
367
|
+
klist = list(k) + [0] * (m - builtins.len(k))
|
|
368
|
+
else:
|
|
369
|
+
klist = [k] * m
|
|
370
|
+
if isinstance(lbnd, (list, tuple)):
|
|
371
|
+
raise ValueError("lbnd must be a scalar")
|
|
372
|
+
if isinstance(scl, (list, tuple)):
|
|
373
|
+
raise ValueError("scl must be a scalar")
|
|
374
|
+
c = NX.asarray(c)
|
|
375
|
+
if c.ndim == 1:
|
|
376
|
+
return NX.array(_int1d(c.tolist(), m, klist, lbnd, scl))
|
|
377
|
+
ax = 0 if axis is None else axis
|
|
378
|
+
fn = lambda v: _int1d(v, m, klist, lbnd, scl)
|
|
379
|
+
return _apply_along_axis(c, fn, ax)
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
# ========== 根 / 由根构造 / 拟合 ==========
|
|
383
|
+
|
|
384
|
+
def polyroots(c):
|
|
385
|
+
"""多项式根(Rust QR 伴矩阵特征值内核,降序约定)。
|
|
386
|
+
结果按 (实部, 虚部) 排序——实根升序,与 实根情形一致。"""
|
|
387
|
+
NX = _NX()
|
|
388
|
+
c = NX.asarray(c)
|
|
389
|
+
cvals = c.tolist()
|
|
390
|
+
if len(cvals) <= 1:
|
|
391
|
+
return NX.array([])
|
|
392
|
+
desc = list(reversed(cvals))
|
|
393
|
+
raw = _wrap(_core().polyroots_rs(_raw(desc)))
|
|
394
|
+
vals = raw.tolist()
|
|
395
|
+
cv = [complex(v) for v in vals]
|
|
396
|
+
cv.sort(key=lambda z: (z.real, z.imag))
|
|
397
|
+
if all(z.imag == 0 for z in cv):
|
|
398
|
+
return NX.array([z.real for z in cv])
|
|
399
|
+
return NX.array([z for z in cv])
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def polyfromroots(roots):
|
|
403
|
+
"""由根序列返回升序系数。"""
|
|
404
|
+
NX = _NX()
|
|
405
|
+
r = NX.asarray(roots)
|
|
406
|
+
if r.size == 0:
|
|
407
|
+
return NX.array([1.0])
|
|
408
|
+
vals = r.tolist()
|
|
409
|
+
out = [1.0]
|
|
410
|
+
for rt in vals:
|
|
411
|
+
# 标准构造:c * (x - rt):new[i] -= c[i]*rt; new[i+1] += c[i](升序)
|
|
412
|
+
new = [0.0] * (builtins.len(out) + 1)
|
|
413
|
+
for i, cv in enumerate(out):
|
|
414
|
+
new[i] = new[i] - cv * rt
|
|
415
|
+
new[i + 1] = new[i + 1] + cv
|
|
416
|
+
out = new
|
|
417
|
+
return NX.array(out)
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def _is_complex_data(vals):
|
|
421
|
+
"""嵌套列表数据是否含 complex 元素。"""
|
|
422
|
+
if isinstance(vals, (list, tuple)):
|
|
423
|
+
flat = vals if all(not isinstance(v, (list, tuple))
|
|
424
|
+
for v in vals) else _flat_list(vals)
|
|
425
|
+
else:
|
|
426
|
+
flat = [vals]
|
|
427
|
+
return any(isinstance(v, complex) for v in flat)
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def _gauss_complex(A, bvec):
|
|
431
|
+
"""复数高斯消元(列主元)。"""
|
|
432
|
+
k = builtins.len(bvec)
|
|
433
|
+
M = [list(A[i]) + [bvec[i]] for i in range(k)]
|
|
434
|
+
for i in range(k):
|
|
435
|
+
p = i
|
|
436
|
+
best = builtins.abs(M[i][i])
|
|
437
|
+
for r in range(i + 1, k):
|
|
438
|
+
if builtins.abs(M[r][i]) > best:
|
|
439
|
+
best = builtins.abs(M[r][i])
|
|
440
|
+
p = r
|
|
441
|
+
M[i], M[p] = M[p], M[i]
|
|
442
|
+
piv = M[i][i]
|
|
443
|
+
if piv == 0:
|
|
444
|
+
continue
|
|
445
|
+
for r in range(i + 1, k):
|
|
446
|
+
f = M[r][i] / piv
|
|
447
|
+
if f != 0:
|
|
448
|
+
for c in range(i, k + 1):
|
|
449
|
+
M[r][c] = M[r][c] - f * M[i][c]
|
|
450
|
+
x = [0j] * k
|
|
451
|
+
for i in range(k - 1, -1, -1):
|
|
452
|
+
s = M[i][k]
|
|
453
|
+
for c in range(i + 1, k):
|
|
454
|
+
s = s - M[i][c] * x[c]
|
|
455
|
+
x[i] = s / M[i][i] if M[i][i] != 0 else 0j
|
|
456
|
+
return x
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _lstsq_normal(V, ycol):
|
|
460
|
+
"""正规方程 (V^H V) c = V^H y 最小二乘(复数路径用;
|
|
461
|
+
rsarray 复数 lstsq 内核损坏,见 linalg 后续任务)。"""
|
|
462
|
+
n = builtins.len(V)
|
|
463
|
+
k = builtins.len(V[0])
|
|
464
|
+
A = [[0j] * k for _ in range(k)]
|
|
465
|
+
for i in range(n):
|
|
466
|
+
row = V[i]
|
|
467
|
+
for a in range(k):
|
|
468
|
+
ca = row[a].conjugate()
|
|
469
|
+
for b in range(k):
|
|
470
|
+
A[a][b] = A[a][b] + ca * row[b]
|
|
471
|
+
bvec = [sum(V[i][a].conjugate() * ycol[i] for i in range(n))
|
|
472
|
+
for a in range(k)]
|
|
473
|
+
return _gauss_complex(A, bvec)
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):
|
|
477
|
+
"""最小二乘拟合。deg 可为 int 或严格递增非负幂列表;
|
|
478
|
+
结果长度 max(deg)+1(缺失幂次补零);支持复数 x、2-D y(逐列)、权重 w。"""
|
|
479
|
+
NX = _NX()
|
|
480
|
+
x = NX.asarray(x)
|
|
481
|
+
y = NX.asarray(y)
|
|
482
|
+
if x.ndim != 1:
|
|
483
|
+
raise TypeError("x must be 1 dimensional")
|
|
484
|
+
if y.ndim > 2:
|
|
485
|
+
raise TypeError("y must be 1 or 2 dimensional")
|
|
486
|
+
if x.size == 0:
|
|
487
|
+
raise TypeError("x must be non-empty")
|
|
488
|
+
if y.shape[0] != x.size:
|
|
489
|
+
raise TypeError("x and y must have same first dimension")
|
|
490
|
+
if w is not None:
|
|
491
|
+
w = NX.asarray(w)
|
|
492
|
+
if w.ndim != 1 or w.size != x.size:
|
|
493
|
+
raise TypeError("w must be 1 dimensional and same length as x")
|
|
494
|
+
if isinstance(deg, (list, tuple)):
|
|
495
|
+
if len(deg) == 0:
|
|
496
|
+
raise TypeError("deg must be a non-empty sequence or integer")
|
|
497
|
+
for d in deg:
|
|
498
|
+
if isinstance(d, bool) or not isinstance(d, int):
|
|
499
|
+
raise TypeError("deg values must be integers")
|
|
500
|
+
if d < 0:
|
|
501
|
+
raise ValueError("deg must be non-negative")
|
|
502
|
+
if any(deg[i] >= deg[i + 1] for i in range(len(deg) - 1)):
|
|
503
|
+
raise ValueError("deg sequence must be strictly increasing")
|
|
504
|
+
order = builtins.max(deg)
|
|
505
|
+
else:
|
|
506
|
+
if isinstance(deg, bool) or not isinstance(deg, int):
|
|
507
|
+
raise TypeError("deg must be an integer or sequence")
|
|
508
|
+
if deg < 0:
|
|
509
|
+
raise ValueError("deg must be non-negative")
|
|
510
|
+
order = deg
|
|
511
|
+
xvals = x.tolist()
|
|
512
|
+
yvals = y.tolist()
|
|
513
|
+
wvals = w.tolist() if w is not None else None
|
|
514
|
+
rows = []
|
|
515
|
+
for i, xv in enumerate(xvals):
|
|
516
|
+
s = (wvals[i] ** 0.5) if wvals is not None else 1.0
|
|
517
|
+
rows.append([(xv ** d) * s for d in range(order + 1)])
|
|
518
|
+
if _is_complex_data(rows) or _is_complex_data(yvals):
|
|
519
|
+
# 复数路径:正规方程纯 Python 求解(复数 lstsq 内核损坏)
|
|
520
|
+
if y.ndim == 2:
|
|
521
|
+
ncol = builtins.len(yvals[0])
|
|
522
|
+
cols = [[row[i] for row in yvals] for i in range(ncol)]
|
|
523
|
+
else:
|
|
524
|
+
cols = [yvals]
|
|
525
|
+
sols = [_lstsq_normal(rows, col) for col in cols]
|
|
526
|
+
if y.ndim == 1:
|
|
527
|
+
sol = NX.array(sols[0])
|
|
528
|
+
else:
|
|
529
|
+
sol = NX.array([list(row) for row in sols])
|
|
530
|
+
if full:
|
|
531
|
+
return sol, NX.array([]), NX.array([order + 1]), NX.array([])
|
|
532
|
+
return sol
|
|
533
|
+
# 1 维 y → 1 维解(数组语义);2 维 y 逐列
|
|
534
|
+
Y = NX.array(yvals) if y.ndim == 1 else \
|
|
535
|
+
NX.array([list(row) for row in yvals])
|
|
536
|
+
sol, resids, rank, sv = NX.linalg.lstsq(NX.array(rows), Y, rcond=rcond)
|
|
537
|
+
if y.ndim == 1 and sol.ndim == 2:
|
|
538
|
+
# lstsq 对 1-D b 可能返回 (n,1) → 压平为 (n,)
|
|
539
|
+
sol = NX.array([v[0] for v in sol.tolist()])
|
|
540
|
+
if full:
|
|
541
|
+
return sol, resids, rank, sv
|
|
542
|
+
return sol
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
# ========== 算术族(Rust 内核,降序约定边界反转) ==========
|
|
546
|
+
|
|
547
|
+
def _binop(name, a, b):
|
|
548
|
+
NX = _NX()
|
|
549
|
+
a = NX.asarray(a)
|
|
550
|
+
b = NX.asarray(b)
|
|
551
|
+
ra = list(reversed(a.tolist()))
|
|
552
|
+
rb = list(reversed(b.tolist()))
|
|
553
|
+
res = getattr(_core(), name)(_raw(ra), _raw(rb))
|
|
554
|
+
return NX.array(list(reversed(res.tolist())))
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
def polyadd(a1, a2):
|
|
558
|
+
return _binop('polyadd', a1, a2)
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def polysub(a1, a2):
|
|
562
|
+
return _binop('polysub', a1, a2)
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def polymul(a1, a2):
|
|
566
|
+
return _binop('polymul', a1, a2)
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def polymulx(c):
|
|
570
|
+
"""乘以 x(升序:前置补零后裁剪尾零)。"""
|
|
571
|
+
NX = _NX()
|
|
572
|
+
c = NX.asarray(c)
|
|
573
|
+
vals = c.tolist()
|
|
574
|
+
out = [0.0] + list(vals)
|
|
575
|
+
i = len(out) - 1
|
|
576
|
+
while i >= 0 and builtins.abs(out[i]) <= 0:
|
|
577
|
+
i -= 1
|
|
578
|
+
if i < 0:
|
|
579
|
+
return NX.array([0.0])
|
|
580
|
+
return NX.array(out[:i + 1])
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def polydiv(u, v):
|
|
584
|
+
"""多项式除法 → (商, 余数);v 为零多项式抛 ZeroDivisionError。"""
|
|
585
|
+
NX = _NX()
|
|
586
|
+
u = NX.asarray(u)
|
|
587
|
+
v = NX.asarray(v)
|
|
588
|
+
vv = list(reversed(v.tolist()))
|
|
589
|
+
if not any(builtins.abs(xv) > 0 for xv in vv):
|
|
590
|
+
raise ZeroDivisionError("polynomial division")
|
|
591
|
+
qd, rd = _core().polydiv(_raw(list(reversed(u.tolist()))), _raw(vv))
|
|
592
|
+
return (NX.array(list(reversed(qd.tolist()))),
|
|
593
|
+
NX.array(list(reversed(rd.tolist()))))
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def polypow(c, pow, maxpower=None):
|
|
597
|
+
"""c 的 pow 次幂(pow=0 → [1])。maxpower 为 预留参数。"""
|
|
598
|
+
if isinstance(pow, bool) or not isinstance(pow, int):
|
|
599
|
+
raise TypeError("pow must be an integer")
|
|
600
|
+
if pow < 0:
|
|
601
|
+
raise ValueError("pow must be non-negative")
|
|
602
|
+
NX = _NX()
|
|
603
|
+
c = NX.asarray(c)
|
|
604
|
+
cvals = c.tolist()
|
|
605
|
+
if pow == 0:
|
|
606
|
+
return NX.array([1.0])
|
|
607
|
+
out = [1.0]
|
|
608
|
+
for _ in range(pow):
|
|
609
|
+
out = _py_mul(out, cvals)
|
|
610
|
+
return NX.array(out)
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
def polytrim(coef, tol=0):
|
|
614
|
+
"""自高次端裁剪 |c| <= tol 的系数;全裁完返回 [0]。"""
|
|
615
|
+
if tol < 0:
|
|
616
|
+
raise ValueError("tol must be non-negative")
|
|
617
|
+
NX = _NX()
|
|
618
|
+
c = NX.asarray(coef)
|
|
619
|
+
vals = c.tolist()
|
|
620
|
+
i = len(vals) - 1
|
|
621
|
+
while i >= 0 and builtins.abs(vals[i]) <= tol:
|
|
622
|
+
i -= 1
|
|
623
|
+
if i < 0:
|
|
624
|
+
return NX.array([0.0])
|
|
625
|
+
return NX.array(vals[:i + 1])
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def polycompanion(c):
|
|
629
|
+
"""伴随矩阵(升序系数;首行为 -c[:n]/c[n],次对角线为单位)。"""
|
|
630
|
+
NX = _NX()
|
|
631
|
+
c = NX.asarray(c)
|
|
632
|
+
vals = c.tolist()
|
|
633
|
+
if c.ndim != 1 or len(vals) < 2:
|
|
634
|
+
raise ValueError("c must be a 1d array with at least 2 elements")
|
|
635
|
+
lead = vals[-1]
|
|
636
|
+
cv = [v / lead for v in vals]
|
|
637
|
+
n = len(vals) - 1
|
|
638
|
+
comp = [[0.0] * n for _ in range(n)]
|
|
639
|
+
for i in range(1, n):
|
|
640
|
+
comp[i][i - 1] = 1.0
|
|
641
|
+
comp[0] = [-cv[i] for i in range(n)]
|
|
642
|
+
return NX.array(comp)
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
def polyline(off, scl):
|
|
646
|
+
"""线性多项式 off + scl*x 的系数表示(scl=0 时裁剪)。"""
|
|
647
|
+
NX = _NX()
|
|
648
|
+
if scl != 0:
|
|
649
|
+
return NX.array([off, scl])
|
|
650
|
+
return NX.array([off])
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
# ========== Vandermonde 矩阵族 ==========
|
|
654
|
+
|
|
655
|
+
def polyvander(x, deg):
|
|
656
|
+
"""x**i 沿末轴堆叠;输出形状 x.shape + (deg+1,)。"""
|
|
657
|
+
if deg < 0:
|
|
658
|
+
raise ValueError("deg must be non-negative")
|
|
659
|
+
NX = _NX()
|
|
660
|
+
x = NX.asarray(x)
|
|
661
|
+
xv = x.tolist()
|
|
662
|
+
|
|
663
|
+
def rec(v):
|
|
664
|
+
if isinstance(v, (list, tuple)):
|
|
665
|
+
return [rec(u) for u in v]
|
|
666
|
+
return [v ** i for i in range(deg + 1)]
|
|
667
|
+
|
|
668
|
+
return NX.array(rec(xv))
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
def _vander_nd(pts, deg):
|
|
672
|
+
"""通用 nd Vandermonde:输出形状 pts[0].shape + tuple(d+1 for d in deg)。"""
|
|
673
|
+
NX = _NX()
|
|
674
|
+
pts = [NX.asarray(p) for p in pts]
|
|
675
|
+
shape = tuple(pts[0].shape)
|
|
676
|
+
for p in pts[1:]:
|
|
677
|
+
if tuple(p.shape) != shape:
|
|
678
|
+
raise ValueError("incompatible point dimensions in polyvandern")
|
|
679
|
+
flats = [p.ravel().tolist() for p in pts]
|
|
680
|
+
n = len(flats[0])
|
|
681
|
+
grid_shape = tuple(d + 1 for d in deg)
|
|
682
|
+
ng = _flat_shape(grid_shape)
|
|
683
|
+
# res[g][k] = Π_a flats[a][k] ** idx_a(g)
|
|
684
|
+
res = [[0.0] * n for _ in range(ng)]
|
|
685
|
+
for g in range(ng):
|
|
686
|
+
gidx = _idx_unflat(g, grid_shape)
|
|
687
|
+
for k in range(n):
|
|
688
|
+
v = 1.0
|
|
689
|
+
for a in range(len(pts)):
|
|
690
|
+
if gidx[a]:
|
|
691
|
+
v *= flats[a][k] ** gidx[a]
|
|
692
|
+
res[g][k] = v
|
|
693
|
+
# 转置:每点 k 的 ng 个值构成 grid_shape 嵌套
|
|
694
|
+
per_point = [_unflat([res[g][k] for g in range(ng)], grid_shape)
|
|
695
|
+
for k in range(n)]
|
|
696
|
+
return NX.array(_unflat(per_point, shape))
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def _broadcast_flat(arr, bshape):
|
|
700
|
+
"""把 arr 按广播规则铺到 bshape 后展平为 1-D 列表。"""
|
|
701
|
+
shape = tuple(arr.shape)
|
|
702
|
+
if shape == bshape:
|
|
703
|
+
return _flat_list(arr.tolist())
|
|
704
|
+
nd = builtins.len(bshape)
|
|
705
|
+
pad = [1] * (nd - builtins.len(shape)) + list(shape)
|
|
706
|
+
vals = _flat_list(arr.tolist())
|
|
707
|
+
npts = _flat_shape(bshape)
|
|
708
|
+
out = []
|
|
709
|
+
for k in range(npts):
|
|
710
|
+
q = _idx_unflat(k, bshape)
|
|
711
|
+
sidx = 0
|
|
712
|
+
for a in range(nd - builtins.len(shape), nd):
|
|
713
|
+
s = int(q[a] % pad[a])
|
|
714
|
+
sidx = sidx * builtins.int(pad[a]) + s
|
|
715
|
+
out.append(vals[builtins.int(sidx)])
|
|
716
|
+
return out
|
|
717
|
+
|
|
718
|
+
|
|
719
|
+
def polyvander2d(x, y, deg):
|
|
720
|
+
"""2 点 Vandermonde:输出形状 broadcast(x, y).shape + (扁平网格,),
|
|
721
|
+
网格按 (deg0, deg1) C 序展开。"""
|
|
722
|
+
if builtins.len(deg) != 2:
|
|
723
|
+
raise ValueError("deg must be a length-2 sequence")
|
|
724
|
+
NX = _NX()
|
|
725
|
+
x = NX.asarray(x)
|
|
726
|
+
y = NX.asarray(y)
|
|
727
|
+
xs, ys = tuple(x.shape), tuple(y.shape)
|
|
728
|
+
if not _can_broadcast((xs, ys)):
|
|
729
|
+
raise ValueError("incompatible point dimensions in polyvander2d")
|
|
730
|
+
bshape = _broadcast_shape((xs, ys))
|
|
731
|
+
npts = _flat_shape(bshape)
|
|
732
|
+
gridlen = (deg[0] + 1) * (deg[1] + 1)
|
|
733
|
+
xv = _broadcast_flat(x, bshape)
|
|
734
|
+
yv = _broadcast_flat(y, bshape)
|
|
735
|
+
data = []
|
|
736
|
+
for k in range(npts):
|
|
737
|
+
for i in range(deg[0] + 1):
|
|
738
|
+
for j in range(deg[1] + 1):
|
|
739
|
+
data.append(xv[k] ** i * yv[k] ** j)
|
|
740
|
+
return NX.array(_unflat(data, bshape + (gridlen,)))
|
|
741
|
+
|
|
742
|
+
|
|
743
|
+
def polyvander3d(x, y, z, deg):
|
|
744
|
+
"""3 点 Vandermonde:输出形状 broadcast(x, y, z).shape + (扁平网格,),
|
|
745
|
+
网格按 (deg0, deg1, deg2) C 序展开。"""
|
|
746
|
+
if builtins.len(deg) != 3:
|
|
747
|
+
raise ValueError("deg must be a length-3 sequence")
|
|
748
|
+
NX = _NX()
|
|
749
|
+
x = NX.asarray(x)
|
|
750
|
+
y = NX.asarray(y)
|
|
751
|
+
z = NX.asarray(z)
|
|
752
|
+
shapes = (tuple(x.shape), tuple(y.shape), tuple(z.shape))
|
|
753
|
+
if not _can_broadcast(shapes):
|
|
754
|
+
raise ValueError("incompatible point dimensions in polyvander3d")
|
|
755
|
+
bshape = _broadcast_shape(shapes)
|
|
756
|
+
npts = _flat_shape(bshape)
|
|
757
|
+
gridlen = (deg[0] + 1) * (deg[1] + 1) * (deg[2] + 1)
|
|
758
|
+
xv = _broadcast_flat(x, bshape)
|
|
759
|
+
yv = _broadcast_flat(y, bshape)
|
|
760
|
+
zv = _broadcast_flat(z, bshape)
|
|
761
|
+
data = []
|
|
762
|
+
for k in range(npts):
|
|
763
|
+
for i in range(deg[0] + 1):
|
|
764
|
+
for j in range(deg[1] + 1):
|
|
765
|
+
for t in range(deg[2] + 1):
|
|
766
|
+
data.append(xv[k] ** i * yv[k] ** j * zv[k] ** t)
|
|
767
|
+
return NX.array(_unflat(data, bshape + (gridlen,)))
|
|
768
|
+
|
|
769
|
+
|
|
770
|
+
# ========== 多维求值 / 网格 ==========
|
|
771
|
+
|
|
772
|
+
def _can_broadcast(shapes):
|
|
773
|
+
m = builtins.max(builtins.len(s) for s in shapes)
|
|
774
|
+
padded = [list(reversed(s)) + [1] * (m - builtins.len(s))
|
|
775
|
+
for s in shapes]
|
|
776
|
+
for d in range(m):
|
|
777
|
+
sizes = builtins.set(p[d] for p in padded)
|
|
778
|
+
sizes.discard(1)
|
|
779
|
+
if builtins.len(sizes) > 1:
|
|
780
|
+
return False
|
|
781
|
+
return True
|
|
782
|
+
|
|
783
|
+
|
|
784
|
+
def _broadcast_shape(shapes):
|
|
785
|
+
m = builtins.max(builtins.len(s) for s in shapes)
|
|
786
|
+
b = [1] * m
|
|
787
|
+
for s in shapes:
|
|
788
|
+
for d, sz in enumerate(reversed(s)):
|
|
789
|
+
b[m - 1 - d] = builtins.max(b[m - 1 - d], sz)
|
|
790
|
+
return tuple(b)
|
|
791
|
+
|
|
792
|
+
|
|
793
|
+
def _polyvalnd(pts, c):
|
|
794
|
+
"""Σ c[idx] Π p_a**idx[a](点数组按 广播规则)。"""
|
|
795
|
+
NX = _NX()
|
|
796
|
+
pts = [NX.asarray(p) for p in pts]
|
|
797
|
+
if not pts:
|
|
798
|
+
raise ValueError("pts must be non-empty")
|
|
799
|
+
c = NX.asarray(c)
|
|
800
|
+
if c.ndim != builtins.len(pts):
|
|
801
|
+
raise ValueError("coef array must have the same ndim as "
|
|
802
|
+
"number of points")
|
|
803
|
+
shapes = [tuple(p.shape) for p in pts]
|
|
804
|
+
if not _can_broadcast(shapes):
|
|
805
|
+
raise ValueError("incompatible point dimensions in polyvalnd: "
|
|
806
|
+
+ " ".join(repr(s) for s in shapes))
|
|
807
|
+
bshape = _broadcast_shape(shapes)
|
|
808
|
+
cvals = c.tolist()
|
|
809
|
+
res = NX.zeros(bshape)
|
|
810
|
+
for idx in _itertools.product(*[range(d) for d in c.shape]):
|
|
811
|
+
cv = _multiget(cvals, idx)
|
|
812
|
+
if cv == 0:
|
|
813
|
+
continue
|
|
814
|
+
term = NX.array(cv)
|
|
815
|
+
for a, p in enumerate(pts):
|
|
816
|
+
if idx[a]:
|
|
817
|
+
term = term * (p ** idx[a])
|
|
818
|
+
res = res + term
|
|
819
|
+
return res
|
|
820
|
+
|
|
821
|
+
|
|
822
|
+
def polyval2d(x, y, c):
|
|
823
|
+
"""Σ c[i,j] x**i y**j。"""
|
|
824
|
+
r = _dispatch((x, y, c), polyval2d)
|
|
825
|
+
if r is not None:
|
|
826
|
+
return r
|
|
827
|
+
return _polyvalnd((x, y), c)
|
|
828
|
+
|
|
829
|
+
|
|
830
|
+
def polyval3d(x, y, z, c):
|
|
831
|
+
"""Σ c[i,j,k] x**i y**j z**k。"""
|
|
832
|
+
r = _dispatch((x, y, z, c), polyval3d)
|
|
833
|
+
if r is not None:
|
|
834
|
+
return r
|
|
835
|
+
return _polyvalnd((x, y, z), c)
|
|
836
|
+
|
|
837
|
+
|
|
838
|
+
def polyvalnd(pts, c):
|
|
839
|
+
"""Σ c[idx] Π p_a**idx[a](pts 为点数组序列)。"""
|
|
840
|
+
r = _dispatch(tuple(pts) + (c,), polyvalnd)
|
|
841
|
+
if r is not None:
|
|
842
|
+
return r
|
|
843
|
+
return _polyvalnd(tuple(pts), c)
|
|
844
|
+
|
|
845
|
+
|
|
846
|
+
def polygrid2d(x1, x2, c):
|
|
847
|
+
"""配对网格求值(xy 索引:输出形状 (len(x2), len(x1)))。"""
|
|
848
|
+
r = _dispatch((x1, x2, c), polygrid2d)
|
|
849
|
+
if r is not None:
|
|
850
|
+
return r
|
|
851
|
+
NX = _NX()
|
|
852
|
+
a1 = NX.asarray(x1)
|
|
853
|
+
a2 = NX.asarray(x2)
|
|
854
|
+
# 输出 res[i, j] = f(x1[i], x2[j])(保留输入形状,测试规格 einsum 'i,j->ij')
|
|
855
|
+
p1 = a1.reshape(a1.shape + (1,) * builtins.len(a2.shape))
|
|
856
|
+
p2 = a2.reshape((1,) * builtins.len(a1.shape) + a2.shape)
|
|
857
|
+
return _polyvalnd((p1, p2), c)
|
|
858
|
+
|
|
859
|
+
|
|
860
|
+
def polygrid3d(x1, x2, x3, c):
|
|
861
|
+
"""三维配对网格求值(输出形状 (len(x3), len(x2), len(x1)))。"""
|
|
862
|
+
NX = _NX()
|
|
863
|
+
a1 = NX.asarray(x1)
|
|
864
|
+
a2 = NX.asarray(x2)
|
|
865
|
+
a3 = NX.asarray(x3)
|
|
866
|
+
# 输出形状 = s1 + s2 + s3:各输入占据互不重叠的轴块(其余轴 pad 1)
|
|
867
|
+
s1, s2, s3 = a1.shape, a2.shape, a3.shape
|
|
868
|
+
R = builtins.len(s1) + builtins.len(s2) + builtins.len(s3)
|
|
869
|
+
p1 = a1.reshape(s1 + (1,) * (R - builtins.len(s1)))
|
|
870
|
+
p2 = a2.reshape((1,) * builtins.len(s1) + s2
|
|
871
|
+
+ (1,) * (R - builtins.len(s1) - builtins.len(s2)))
|
|
872
|
+
p3 = a3.reshape((1,) * (builtins.len(s1) + builtins.len(s2)) + s3)
|
|
873
|
+
return _polyvalnd((p1, p2, p3), c)
|
|
874
|
+
|
|
875
|
+
|
|
876
|
+
# ========== Polynomial 类 ==========
|
|
877
|
+
|
|
878
|
+
def _py_der(cvals, m):
|
|
879
|
+
cur = list(cvals)
|
|
880
|
+
for _ in range(m):
|
|
881
|
+
if len(cur) <= 1:
|
|
882
|
+
cur = [0]
|
|
883
|
+
else:
|
|
884
|
+
cur = [(j + 1) * cur[j + 1] for j in range(len(cur) - 1)]
|
|
885
|
+
return cur
|
|
886
|
+
|
|
887
|
+
|
|
888
|
+
class Polynomial:
|
|
889
|
+
"""polynomial.Polynomial 兼容类(升序系数;默认 domain/window
|
|
890
|
+
[-1, 1];求值先把 x 从 domain 线性映射到 window)。"""
|
|
891
|
+
|
|
892
|
+
def __init__(self, c, domain=None, window=None, symbol='x'):
|
|
893
|
+
NX = _NX()
|
|
894
|
+
c = _mk_array(c) if isinstance(c, (list, tuple)) else NX.asarray(c)
|
|
895
|
+
if c.ndim > 1:
|
|
896
|
+
c = c.ravel()
|
|
897
|
+
elif c.ndim == 0:
|
|
898
|
+
c = NX.array([c.tolist()])
|
|
899
|
+
self._coef = c
|
|
900
|
+
if domain is None:
|
|
901
|
+
domain = NX.array([-1., 1.])
|
|
902
|
+
if window is None:
|
|
903
|
+
window = NX.array([-1., 1.])
|
|
904
|
+
self._domain = _mk_array(domain) if isinstance(domain, (list, tuple)) \
|
|
905
|
+
else NX.asarray(domain)
|
|
906
|
+
self._window = _mk_array(window) if isinstance(window, (list, tuple)) \
|
|
907
|
+
else NX.asarray(window)
|
|
908
|
+
self._symbol = symbol
|
|
909
|
+
|
|
910
|
+
# ---- 属性 ----
|
|
911
|
+
@property
|
|
912
|
+
def coef(self):
|
|
913
|
+
return self._coef
|
|
914
|
+
|
|
915
|
+
@property
|
|
916
|
+
def domain(self):
|
|
917
|
+
return self._domain
|
|
918
|
+
|
|
919
|
+
@property
|
|
920
|
+
def window(self):
|
|
921
|
+
return self._window
|
|
922
|
+
|
|
923
|
+
@property
|
|
924
|
+
def symbol(self):
|
|
925
|
+
return self._symbol
|
|
926
|
+
|
|
927
|
+
@property
|
|
928
|
+
def degree(self):
|
|
929
|
+
return builtins.max(len(self._coef.tolist()) - 1, 0)
|
|
930
|
+
|
|
931
|
+
# ---- domain → window 映射参数:mapped = x * sc + ofst ----
|
|
932
|
+
def _mapparms(self):
|
|
933
|
+
# 用数组元素访问保 dtype(f4 domain → f4 参数,弱标量语义);
|
|
934
|
+
# object(Fraction)元素访问返回 Python 对象,走精确算术
|
|
935
|
+
d, w = self._domain, self._window
|
|
936
|
+
sc = (w[1] - w[0]) / (d[1] - d[0])
|
|
937
|
+
ofst = (w[0] * d[1] - w[1] * d[0]) / (d[1] - d[0])
|
|
938
|
+
return ofst, sc
|
|
939
|
+
|
|
940
|
+
def __call__(self, x):
|
|
941
|
+
ofst, sc = self._mapparms()
|
|
942
|
+
if _isfrac(x):
|
|
943
|
+
# Fraction 路径:全程 Python 精确算术
|
|
944
|
+
return _pyval(self._coef.tolist(), x * sc + ofst)
|
|
945
|
+
NX = _NX()
|
|
946
|
+
# x 为 Python 标量时保持弱标量语义(dtype 跟随 domain/coef)
|
|
947
|
+
mapped = (x * sc + ofst) if _is_py_scalar(x) else \
|
|
948
|
+
NX.asarray(x) * sc + ofst
|
|
949
|
+
mapped = NX.asarray(mapped)
|
|
950
|
+
y = NX.zeros_like(mapped)
|
|
951
|
+
for pv in reversed(self._coef.tolist()):
|
|
952
|
+
y = y * mapped + pv
|
|
953
|
+
return y
|
|
954
|
+
|
|
955
|
+
# ---- 算术(object dtype 安全,纯 Python 系数运算) ----
|
|
956
|
+
def _same_basiss(self, other):
|
|
957
|
+
return (self._domain.tolist() == other._domain.tolist()
|
|
958
|
+
and self._window.tolist() == other._window.tolist())
|
|
959
|
+
|
|
960
|
+
def __add__(self, other):
|
|
961
|
+
if not isinstance(other, Polynomial):
|
|
962
|
+
return NotImplemented
|
|
963
|
+
if not self._same_basiss(other):
|
|
964
|
+
raise ValueError("domains or windows must be the same")
|
|
965
|
+
c = _py_add(self._coef.tolist(), other._coef.tolist())
|
|
966
|
+
return Polynomial(_mk_array(c), domain=self._domain,
|
|
967
|
+
window=self._window, symbol=self._symbol)
|
|
968
|
+
|
|
969
|
+
__radd__ = __add__
|
|
970
|
+
|
|
971
|
+
def __sub__(self, other):
|
|
972
|
+
if not isinstance(other, Polynomial):
|
|
973
|
+
return NotImplemented
|
|
974
|
+
if not self._same_basiss(other):
|
|
975
|
+
raise ValueError("domains or windows must be the same")
|
|
976
|
+
a = self._coef.tolist()
|
|
977
|
+
b = other._coef.tolist()
|
|
978
|
+
n = builtins.max(len(a), len(b))
|
|
979
|
+
c = [(a[i] if i < builtins.len(a) else 0)
|
|
980
|
+
- (b[i] if i < builtins.len(b) else 0)
|
|
981
|
+
for i in range(n)]
|
|
982
|
+
return Polynomial(_mk_array(c), domain=self._domain,
|
|
983
|
+
window=self._window, symbol=self._symbol)
|
|
984
|
+
|
|
985
|
+
def __neg__(self):
|
|
986
|
+
return Polynomial(_mk_array([-v for v in self._coef.tolist()]),
|
|
987
|
+
domain=self._domain, window=self._window,
|
|
988
|
+
symbol=self._symbol)
|
|
989
|
+
|
|
990
|
+
def _scaled(self, s):
|
|
991
|
+
NX = _NX()
|
|
992
|
+
vals = self._coef.tolist()
|
|
993
|
+
if any(_isfrac(v) for v in vals):
|
|
994
|
+
c = NX.array([s * v for v in vals], dtype='object')
|
|
995
|
+
else:
|
|
996
|
+
c = self._coef * s
|
|
997
|
+
return Polynomial(c, domain=self._domain, window=self._window,
|
|
998
|
+
symbol=self._symbol)
|
|
999
|
+
|
|
1000
|
+
def __mul__(self, other):
|
|
1001
|
+
if isinstance(other, Polynomial):
|
|
1002
|
+
c = _py_mul(self._coef.tolist(), other._coef.tolist())
|
|
1003
|
+
return Polynomial(_mk_array(c), domain=self._domain,
|
|
1004
|
+
window=self._window, symbol=self._symbol)
|
|
1005
|
+
if _is_py_scalar(other):
|
|
1006
|
+
return self._scaled(other)
|
|
1007
|
+
return NotImplemented
|
|
1008
|
+
|
|
1009
|
+
__rmul__ = __mul__
|
|
1010
|
+
|
|
1011
|
+
def __pow__(self, n):
|
|
1012
|
+
if isinstance(n, bool) or not isinstance(n, int):
|
|
1013
|
+
raise TypeError("pow must be an integer")
|
|
1014
|
+
if n < 0:
|
|
1015
|
+
raise ValueError("pow must be non-negative")
|
|
1016
|
+
if n == 0:
|
|
1017
|
+
c = [1]
|
|
1018
|
+
else:
|
|
1019
|
+
c = [1]
|
|
1020
|
+
for _ in range(n):
|
|
1021
|
+
c = _py_mul(c, self._coef.tolist())
|
|
1022
|
+
return Polynomial(_mk_array(c), domain=self._domain,
|
|
1023
|
+
window=self._window, symbol=self._symbol)
|
|
1024
|
+
|
|
1025
|
+
# ---- 导数 / 根 ----
|
|
1026
|
+
def deriv(self, m=1):
|
|
1027
|
+
c = _py_der(self._coef.tolist(), m)
|
|
1028
|
+
return Polynomial(_mk_array(c), domain=self._domain,
|
|
1029
|
+
window=self._window, symbol=self._symbol)
|
|
1030
|
+
|
|
1031
|
+
def roots(self):
|
|
1032
|
+
return polyroots(self._coef)
|
|
1033
|
+
|
|
1034
|
+
# ---- 比较(Polynomial 无 __eq__;此处提供以便测试比较) ----
|
|
1035
|
+
def __eq__(self, other):
|
|
1036
|
+
if not isinstance(other, Polynomial):
|
|
1037
|
+
return NotImplemented
|
|
1038
|
+
return (self._coef.tolist() == other._coef.tolist()
|
|
1039
|
+
and self._same_basiss(other))
|
|
1040
|
+
|
|
1041
|
+
def __ne__(self, other):
|
|
1042
|
+
r = self.__eq__(other)
|
|
1043
|
+
if r is NotImplemented:
|
|
1044
|
+
return r
|
|
1045
|
+
return not r
|
|
1046
|
+
|
|
1047
|
+
__hash__ = None
|
|
1048
|
+
|
|
1049
|
+
def __repr__(self):
|
|
1050
|
+
return ('Polynomial(' + repr(self._coef.tolist()) + ', domain='
|
|
1051
|
+
+ repr(self._domain.tolist()) + ', window='
|
|
1052
|
+
+ repr(self._window.tolist()) + ')')
|
|
1053
|
+
|
|
1054
|
+
__str__ = __repr__
|
|
1055
|
+
|
|
1056
|
+
# ---- 拟合 ----
|
|
1057
|
+
@builtins.classmethod
|
|
1058
|
+
def fit(cls, x, y, deg=1, rcond=None, w=None, full=False,
|
|
1059
|
+
domain=None, window=None, symbol='x'):
|
|
1060
|
+
"""最小二乘拟合(x 先从 domain 映射到 window);秩亏时 RankWarning。"""
|
|
1061
|
+
NX = _NX()
|
|
1062
|
+
if domain is None:
|
|
1063
|
+
domain = NX.array([-1., 1.])
|
|
1064
|
+
if window is None:
|
|
1065
|
+
window = NX.array([-1., 1.])
|
|
1066
|
+
domain = NX.asarray(domain)
|
|
1067
|
+
window = NX.asarray(window)
|
|
1068
|
+
d = domain.tolist()
|
|
1069
|
+
wv = window.tolist()
|
|
1070
|
+
sc = (wv[1] - wv[0]) / (d[1] - d[0])
|
|
1071
|
+
ofst = (wv[0] * d[1] - wv[1] * d[0]) / (d[1] - d[0])
|
|
1072
|
+
xarr = NX.asarray(x)
|
|
1073
|
+
xm = xarr * sc + ofst
|
|
1074
|
+
sol, _resids, rank, _sv = polyfit(xm, y, deg, rcond=rcond,
|
|
1075
|
+
full=True, w=w)
|
|
1076
|
+
# 秩亏阈值 = Vandermonde 列数 = 次数 + 1(deg 列表时取 max+1)
|
|
1077
|
+
ncoef = (deg + 1) if isinstance(deg, int) else (builtins.max(deg) + 1)
|
|
1078
|
+
if rank < ncoef:
|
|
1079
|
+
import warnings
|
|
1080
|
+
warnings.warn("Polyfit may be poorly conditioned",
|
|
1081
|
+
NX.exceptions.RankWarning, stacklevel=2)
|
|
1082
|
+
return cls(sol, domain=domain, window=window, symbol=symbol)
|