/
_polyutils.py
577 lines (452 loc) · 18.7 KB
/
_polyutils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
"""
Routines for manipulating partial fraction expansions.
"""
import cupy
def roots(arr):
"""np.roots replacement. XXX: calls into NumPy, then converts back.
"""
import numpy as np
arr = cupy.asarray(arr).get()
return cupy.asarray(np.roots(arr))
def poly(A):
"""np.poly replacement for 2D A. Otherwise, use cupy.poly."""
sh = A.shape
if not (len(sh) == 2 and sh[0] == sh[1] and sh[0] != 0):
raise ValueError("input must be a non-empty square 2d array.")
import numpy as np
seq_of_zeros = np.linalg.eigvals(A.get())
dt = seq_of_zeros.dtype
a = np.ones((1,), dtype=dt)
for zero in seq_of_zeros:
a = np.convolve(a, np.r_[1, -zero], mode='full')
if issubclass(a.dtype.type, cupy.complexfloating):
# if complex roots are all complex conjugates, the roots are real.
roots = np.asarray(seq_of_zeros, dtype=complex)
if np.all(np.sort(roots) == np.sort(roots.conjugate())):
a = a.real.copy()
return cupy.asarray(a)
def _cmplx_sort(p):
"""Sort roots based on magnitude.
"""
indx = cupy.argsort(cupy.abs(p))
return cupy.take(p, indx, 0), indx
# np.polydiv clone
def _polydiv(u, v):
u = cupy.atleast_1d(u) + 0.0
v = cupy.atleast_1d(v) + 0.0
# w has the common type
w = u[0] + v[0]
m = len(u) - 1
n = len(v) - 1
scale = 1. / v[0]
q = cupy.zeros((max(m - n + 1, 1),), w.dtype)
r = u.astype(w.dtype)
for k in range(0, m-n+1):
d = scale * r[k]
q[k] = d
r[k:k + n + 1] -= d * v
while cupy.allclose(r[0], 0, rtol=1e-14) and (r.shape[-1] > 1):
r = r[1:]
return q, r
def unique_roots(p, tol=1e-3, rtype='min'):
"""Determine unique roots and their multiplicities from a list of roots.
Parameters
----------
p : array_like
The list of roots.
tol : float, optional
The tolerance for two roots to be considered equal in terms of
the distance between them. Default is 1e-3. Refer to Notes about
the details on roots grouping.
rtype : {'max', 'maximum', 'min', 'minimum', 'avg', 'mean'}, optional
How to determine the returned root if multiple roots are within
`tol` of each other.
- 'max', 'maximum': pick the maximum of those roots
- 'min', 'minimum': pick the minimum of those roots
- 'avg', 'mean': take the average of those roots
When finding minimum or maximum among complex roots they are compared
first by the real part and then by the imaginary part.
Returns
-------
unique : ndarray
The list of unique roots.
multiplicity : ndarray
The multiplicity of each root.
See Also
--------
scipy.signal.unique_roots
Notes
-----
If we have 3 roots ``a``, ``b`` and ``c``, such that ``a`` is close to
``b`` and ``b`` is close to ``c`` (distance is less than `tol`), then it
doesn't necessarily mean that ``a`` is close to ``c``. It means that roots
grouping is not unique. In this function we use "greedy" grouping going
through the roots in the order they are given in the input `p`.
This utility function is not specific to roots but can be used for any
sequence of values for which uniqueness and multiplicity has to be
determined. For a more general routine, see `numpy.unique`.
"""
if rtype in ['max', 'maximum']:
reduce = cupy.max
elif rtype in ['min', 'minimum']:
reduce = cupy.min
elif rtype in ['avg', 'mean']:
reduce = cupy.mean
else:
raise ValueError("`rtype` must be one of "
"{'max', 'maximum', 'min', 'minimum', 'avg', 'mean'}")
points = cupy.empty((p.shape[0], 2))
points[:, 0] = cupy.real(p)
points[:, 1] = cupy.imag(p)
# Replacement for dist = cdist(points, points) to avoid needing `pylibraft`
dist = cupy.linalg.norm(points[:, None, :] - points[None, :, :], axis=-1)
p_unique = []
p_multiplicity = []
used = cupy.zeros(p.shape[0], dtype=bool)
for i, ds in enumerate(dist):
if used[i]:
continue
mask = (ds < tol) & ~used
group = ds[mask]
if group.size > 0:
# print(j, ' : ', group, p[mask])
p_unique.append(reduce(p[mask]))
p_multiplicity.append(group.shape[0])
used[mask] = True
return cupy.asarray(p_unique), cupy.asarray(p_multiplicity)
def _compute_factors(roots, multiplicity, include_powers=False):
"""Compute the total polynomial divided by factors for each root."""
current = cupy.array([1])
suffixes = [current]
for pole, mult in zip(roots[-1:0:-1], multiplicity[-1:0:-1]):
monomial = cupy.r_[1, -pole]
for _ in range(int(mult)):
current = cupy.polymul(current, monomial)
suffixes.append(current)
suffixes = suffixes[::-1]
factors = []
current = cupy.array([1])
for pole, mult, suffix in zip(roots, multiplicity, suffixes):
monomial = cupy.r_[1, -pole]
block = []
for i in range(int(mult)):
if i == 0 or include_powers:
block.append(cupy.polymul(current, suffix))
current = cupy.polymul(current, monomial)
factors.extend(reversed(block))
return factors, current
def _compute_residues(poles, multiplicity, numerator):
denominator_factors, _ = _compute_factors(poles, multiplicity)
numerator = numerator.astype(poles.dtype)
residues = []
for pole, mult, factor in zip(poles, multiplicity,
denominator_factors):
if mult == 1:
residues.append(cupy.polyval(numerator, pole) /
cupy.polyval(factor, pole))
else:
numer = numerator.copy()
monomial = cupy.r_[1, -pole]
factor, d = _polydiv(factor, monomial)
block = []
for _ in range(int(mult)):
numer, n = _polydiv(numer, monomial)
r = n[0] / d[0]
numer = cupy.polysub(numer, r * factor)
block.append(r)
residues.extend(reversed(block))
return cupy.asarray(residues)
def invres(r, p, k, tol=1e-3, rtype='avg'):
"""Compute b(s) and a(s) from partial fraction expansion.
If `M` is the degree of numerator `b` and `N` the degree of denominator
`a`::
b(s) b[0] s**(M) + b[1] s**(M-1) + ... + b[M]
H(s) = ------ = ------------------------------------------
a(s) a[0] s**(N) + a[1] s**(N-1) + ... + a[N]
then the partial-fraction expansion H(s) is defined as::
r[0] r[1] r[-1]
= -------- + -------- + ... + --------- + k(s)
(s-p[0]) (s-p[1]) (s-p[-1])
If there are any repeated roots (closer together than `tol`), then H(s)
has terms like::
r[i] r[i+1] r[i+n-1]
-------- + ----------- + ... + -----------
(s-p[i]) (s-p[i])**2 (s-p[i])**n
This function is used for polynomials in positive powers of s or z,
such as analog filters or digital filters in controls engineering. For
negative powers of z (typical for digital filters in DSP), use `invresz`.
Parameters
----------
r : array_like
Residues corresponding to the poles. For repeated poles, the residues
must be ordered to correspond to ascending by power fractions.
p : array_like
Poles. Equal poles must be adjacent.
k : array_like
Coefficients of the direct polynomial term.
tol : float, optional
The tolerance for two roots to be considered equal in terms of
the distance between them. Default is 1e-3. See `unique_roots`
for further details.
rtype : {'avg', 'min', 'max'}, optional
Method for computing a root to represent a group of identical roots.
Default is 'avg'. See `unique_roots` for further details.
Returns
-------
b : ndarray
Numerator polynomial coefficients.
a : ndarray
Denominator polynomial coefficients.
See Also
--------
scipy.signal.invres
residue, invresz, unique_roots
"""
r = cupy.atleast_1d(r)
p = cupy.atleast_1d(p)
k = cupy.trim_zeros(cupy.atleast_1d(k), 'f')
unique_poles, multiplicity = unique_roots(p, tol, rtype)
factors, denominator = _compute_factors(unique_poles, multiplicity,
include_powers=True)
if len(k) == 0:
numerator = 0
else:
numerator = cupy.polymul(k, denominator)
for residue, factor in zip(r, factors):
numerator = cupy.polyadd(numerator, residue * factor)
return numerator, denominator
def invresz(r, p, k, tol=1e-3, rtype='avg'):
"""Compute b(z) and a(z) from partial fraction expansion.
If `M` is the degree of numerator `b` and `N` the degree of denominator
`a`::
b(z) b[0] + b[1] z**(-1) + ... + b[M] z**(-M)
H(z) = ------ = ------------------------------------------
a(z) a[0] + a[1] z**(-1) + ... + a[N] z**(-N)
then the partial-fraction expansion H(z) is defined as::
r[0] r[-1]
= --------------- + ... + ---------------- + k[0] + k[1]z**(-1) ...
(1-p[0]z**(-1)) (1-p[-1]z**(-1))
If there are any repeated roots (closer than `tol`), then the partial
fraction expansion has terms like::
r[i] r[i+1] r[i+n-1]
-------------- + ------------------ + ... + ------------------
(1-p[i]z**(-1)) (1-p[i]z**(-1))**2 (1-p[i]z**(-1))**n
This function is used for polynomials in negative powers of z,
such as digital filters in DSP. For positive powers, use `invres`.
Parameters
----------
r : array_like
Residues corresponding to the poles. For repeated poles, the residues
must be ordered to correspond to ascending by power fractions.
p : array_like
Poles. Equal poles must be adjacent.
k : array_like
Coefficients of the direct polynomial term.
tol : float, optional
The tolerance for two roots to be considered equal in terms of
the distance between them. Default is 1e-3. See `unique_roots`
for further details.
rtype : {'avg', 'min', 'max'}, optional
Method for computing a root to represent a group of identical roots.
Default is 'avg'. See `unique_roots` for further details.
Returns
-------
b : ndarray
Numerator polynomial coefficients.
a : ndarray
Denominator polynomial coefficients.
See Also
--------
scipy.signal.invresz
residuez, unique_roots, invres
"""
r = cupy.atleast_1d(r)
p = cupy.atleast_1d(p)
k = cupy.trim_zeros(cupy.atleast_1d(k), 'b')
unique_poles, multiplicity = unique_roots(p, tol, rtype)
factors, denominator = _compute_factors(unique_poles, multiplicity,
include_powers=True)
if len(k) == 0:
numerator = 0
else:
numerator = cupy.polymul(k[::-1], denominator[::-1])
for residue, factor in zip(r, factors):
numerator = cupy.polyadd(numerator, residue * factor[::-1])
return numerator[::-1], denominator
def residue(b, a, tol=1e-3, rtype='avg'):
"""Compute partial-fraction expansion of b(s) / a(s).
If `M` is the degree of numerator `b` and `N` the degree of denominator
`a`::
b(s) b[0] s**(M) + b[1] s**(M-1) + ... + b[M]
H(s) = ------ = ------------------------------------------
a(s) a[0] s**(N) + a[1] s**(N-1) + ... + a[N]
then the partial-fraction expansion H(s) is defined as::
r[0] r[1] r[-1]
= -------- + -------- + ... + --------- + k(s)
(s-p[0]) (s-p[1]) (s-p[-1])
If there are any repeated roots (closer together than `tol`), then H(s)
has terms like::
r[i] r[i+1] r[i+n-1]
-------- + ----------- + ... + -----------
(s-p[i]) (s-p[i])**2 (s-p[i])**n
This function is used for polynomials in positive powers of s or z,
such as analog filters or digital filters in controls engineering. For
negative powers of z (typical for digital filters in DSP), use `residuez`.
See Notes for details about the algorithm.
Parameters
----------
b : array_like
Numerator polynomial coefficients.
a : array_like
Denominator polynomial coefficients.
tol : float, optional
The tolerance for two roots to be considered equal in terms of
the distance between them. Default is 1e-3. See `unique_roots`
for further details.
rtype : {'avg', 'min', 'max'}, optional
Method for computing a root to represent a group of identical roots.
Default is 'avg'. See `unique_roots` for further details.
Returns
-------
r : ndarray
Residues corresponding to the poles. For repeated poles, the residues
are ordered to correspond to ascending by power fractions.
p : ndarray
Poles ordered by magnitude in ascending order.
k : ndarray
Coefficients of the direct polynomial term.
Warning
-------
This function may synchronize the device.
See Also
--------
scipy.signal.residue
invres, residuez, numpy.poly, unique_roots
Notes
-----
The "deflation through subtraction" algorithm is used for
computations --- method 6 in [1]_.
The form of partial fraction expansion depends on poles multiplicity in
the exact mathematical sense. However there is no way to exactly
determine multiplicity of roots of a polynomial in numerical computing.
Thus you should think of the result of `residue` with given `tol` as
partial fraction expansion computed for the denominator composed of the
computed poles with empirically determined multiplicity. The choice of
`tol` can drastically change the result if there are close poles.
References
----------
.. [1] J. F. Mahoney, B. D. Sivazlian, "Partial fractions expansion: a
review of computational methodology and efficiency", Journal of
Computational and Applied Mathematics, Vol. 9, 1983.
"""
if (cupy.issubdtype(b.dtype, cupy.complexfloating)
or cupy.issubdtype(a.dtype, cupy.complexfloating)):
b = b.astype(complex)
a = a.astype(complex)
else:
b = b.astype(float)
a = a.astype(float)
b = cupy.trim_zeros(cupy.atleast_1d(b), 'f')
a = cupy.trim_zeros(cupy.atleast_1d(a), 'f')
if a.size == 0:
raise ValueError("Denominator `a` is zero.")
poles = roots(a)
if b.size == 0:
return cupy.zeros(poles.shape), _cmplx_sort(poles)[0], cupy.array([])
if len(b) < len(a):
k = cupy.empty(0)
else:
k, b = _polydiv(b, a)
unique_poles, multiplicity = unique_roots(poles, tol=tol, rtype=rtype)
unique_poles, order = _cmplx_sort(unique_poles)
multiplicity = multiplicity[order]
residues = _compute_residues(unique_poles, multiplicity, b)
index = 0
for pole, mult in zip(unique_poles, multiplicity):
poles[index:index + mult] = pole
index += mult
return residues / a[0], poles, k
def residuez(b, a, tol=1e-3, rtype='avg'):
"""Compute partial-fraction expansion of b(z) / a(z).
If `M` is the degree of numerator `b` and `N` the degree of denominator
`a`::
b(z) b[0] + b[1] z**(-1) + ... + b[M] z**(-M)
H(z) = ------ = ------------------------------------------
a(z) a[0] + a[1] z**(-1) + ... + a[N] z**(-N)
then the partial-fraction expansion H(z) is defined as::
r[0] r[-1]
= --------------- + ... + ---------------- + k[0] + k[1]z**(-1) ...
(1-p[0]z**(-1)) (1-p[-1]z**(-1))
If there are any repeated roots (closer than `tol`), then the partial
fraction expansion has terms like::
r[i] r[i+1] r[i+n-1]
-------------- + ------------------ + ... + ------------------
(1-p[i]z**(-1)) (1-p[i]z**(-1))**2 (1-p[i]z**(-1))**n
This function is used for polynomials in negative powers of z,
such as digital filters in DSP. For positive powers, use `residue`.
See Notes of `residue` for details about the algorithm.
Parameters
----------
b : array_like
Numerator polynomial coefficients.
a : array_like
Denominator polynomial coefficients.
tol : float, optional
The tolerance for two roots to be considered equal in terms of
the distance between them. Default is 1e-3. See `unique_roots`
for further details.
rtype : {'avg', 'min', 'max'}, optional
Method for computing a root to represent a group of identical roots.
Default is 'avg'. See `unique_roots` for further details.
Returns
-------
r : ndarray
Residues corresponding to the poles. For repeated poles, the residues
are ordered to correspond to ascending by power fractions.
p : ndarray
Poles ordered by magnitude in ascending order.
k : ndarray
Coefficients of the direct polynomial term.
Warning
-------
This function may synchronize the device.
See Also
--------
scipy.signal.residuez
invresz, residue, unique_roots
"""
if (cupy.issubdtype(b.dtype, cupy.complexfloating)
or cupy.issubdtype(a.dtype, cupy.complexfloating)):
b = b.astype(complex)
a = a.astype(complex)
else:
b = b.astype(float)
a = a.astype(float)
b = cupy.trim_zeros(cupy.atleast_1d(b), 'b')
a = cupy.trim_zeros(cupy.atleast_1d(a), 'b')
if a.size == 0:
raise ValueError("Denominator `a` is zero.")
elif a[0] == 0:
raise ValueError("First coefficient of determinant `a` must be "
"non-zero.")
poles = roots(a)
if b.size == 0:
return cupy.zeros(poles.shape), _cmplx_sort(poles)[0], cupy.array([])
b_rev = b[::-1]
a_rev = a[::-1]
if len(b_rev) < len(a_rev):
k_rev = cupy.empty(0)
else:
k_rev, b_rev = _polydiv(b_rev, a_rev)
unique_poles, multiplicity = unique_roots(poles, tol=tol, rtype=rtype)
unique_poles, order = _cmplx_sort(unique_poles)
multiplicity = multiplicity[order]
residues = _compute_residues(1 / unique_poles, multiplicity, b_rev)
index = 0
powers = cupy.empty(len(residues), dtype=int)
for pole, mult in zip(unique_poles, multiplicity):
poles[index:index + mult] = pole
powers[index:index + mult] = 1 + cupy.arange(int(mult))
index += mult
residues *= (-poles) ** powers / a_rev[0]
return residues, poles, k_rev[::-1]