public

Second-order sections for SciPy Python

  • Download Gist
Butterworth_Lowpass_Filter_Example.png
butter_sos_example.py
Python
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
"""
Translation of example from:
https://ccrma.stanford.edu/~jos/fp/Butterworth_Lowpass_Filter_Example.html
to demonstrate that sosfilt and tf2sos function the same as the Octave version
 
"""
 
from __future__ import division
from scipy.signal import butter
from sos import tf2sos, sosfilt
from numpy import shape, zeros, log10
from numpy.fft import fft, fftfreq
from matplotlib.pyplot import plot, figure, axis, grid
 
fc = 1000 # Cut-off frequency (Hz)
fs = 8192 # Sampling rate (Hz)
order = 5 # Filter order
B, A = butter(order, fc / (fs/2)) # [0:pi] maps to [0:1] here
sos, k = tf2sos(B, A)
print sos
print k
 
"""
Actual values differ slightly from Octave's, which are:
 
sos = array([[1.00000, 2.00080, 1.00080, 1.00000, -0.92223, 0.28087],
[1.00000, 1.99791, 0.99791, 1.00000, -1.18573, 0.64684],
[1.00000, 1.00129, -0.00000, 1.00000, -0.42504, 0.00000]])
 
g = 0.0029714
"""
 
## Compute and display the amplitude response
#Bs = sos[:, :3] # Section numerator polynomials
#As = sos[:, 3:] # Section denominator polynomials
#nsec = shape(sos)[0]
 
nsamps = 256 # Number of impulse-response samples
 
# Note use of input scale-factor k here:
x = zeros(nsamps)
x[0] = k # SCALED impulse signal
 
x = sosfilt(sos, x)
 
# Plot impulse response to make sure it has decayed to zero (numerically)
plot(x)
 
# Plot amplitude of frequency response
figure(2)
X = fft(x) # sampled frequency response
f = fftfreq(nsamps, 1/fs)
grid(True)
 
axis([0, fs / 2, -100, 5])
 
plot(f[:nsamps / 2], 20 * log10(X[:nsamps / 2]))
readme.md
Markdown

Dumping this on gist in case I never finish it

SciPy's functions internally convert to tf representation and back again instead of using zpk or ss throughout, making this kind of pointless so far, because high-order filters can't be generated reliably in the first place.

I plan to rewrite this from scratch so it's not GPL and can be included in SciPy? maybe?

sos.py
Python
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 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
# First part:
 
# Copyright (C) 2005 Julius O. Smith III <jos@ccrma.stanford.edu>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, see <http://www.gnu.org/licenses/>.
 
# (This is a direct translation of GPL code and cannot be included in SciPy as-is)
 
# Translated by endolith@gmail.com
# Also translated by Kittipong Piyawanno <project.dictator@ximplesoft.com>
# though that version has some bugs http://projects.scipy.org/scipy/ticket/648
 
 
from __future__ import division
from scipy.signal import tf2zpk, lfilter
from numpy import (asarray, asfarray, array, atleast_2d, trim_zeros, empty,
roots, prod, append, rank, spacing, ones, isrealobj,
atleast_1d, sort, conj, mean, dstack, lexsort,
vstack, abs, polymul)
from numpy.random import rand
 
def tf2sos(b, a):
"""
Convert direct-form filter coefficients to series second-order
sections.
 
Parameters
----------
b, a : array_like
[copy from sos2tf]
 
Returns
-------
sos : array_like
[copy from sos2tf]
b0 must be nonzero for each section (zeros at infinity not supported).
k : float
[copy from sos2tf]
 
Examples
--------
>>> B = array([1, 0, 0, 0, 0, 1])
>>> A = array([1, 0, 0, 0, 0, .9])
>>> sos, k = tf2sos(B, A)
>>> sos
array([[ 1. , 0.618 , 1. , 1. , 0.6051, 0.9587],
[ 1. , -1.618 , 1. , 1. , -1.5843, 0.9587],
[ 1. , 1. , -0. , 1. , 0.9791, -0. ]])
>>> k
1.0
 
See Also
--------
sos2tf, zp2sos, sos2pz, zp2tf, tf2zp
 
"""
b = asarray(b)
a = asarray(a)
 
return zpk2sos(*tf2zpk(b, a))
 
 
def sos2tf(sos, k=1):
"""
Convert series second-order sections to direct form H(z) = B(z)/A(z).
 
Parameters
----------
sos : array_like
array of series second-order sections, one per row:
sos = [[B0, A0], [B1, A1], ... [Bn, An]], where
B1 == [b0, b1, b2] and A1 == [1, a1, a2] for
section 1, etc.
b0 must be nonzero for each section.
See `lfilter` for documentation of the
second-order direct-form filter coefficients bn and an.
 
k : float
overall gain factor that effectively scales the output `B` vector (or
any one of the input Bi vectors).
 
Returns
-------
b : ndarray
Numerator polynomial of the IIR filter H(z).
a : ndarray
Denominator polynomial of the IIR filter H(z).
 
Examples
--------
>>> b, a = sos2tf([[1, 0, 1, 1, 0, -0.81], [1, 0, 0, 1, 0, 0.49]])
>>> b
array([ 1., 0., 1.])
>>> a
array([ 1. , 0. , -0.32 , 0. , -0.3969])
 
See Also
--------
tf2sos, zp2sos, sos2pz, zp2tf, tf2zp
 
"""
sos = atleast_2d(asarray(sos))
N, M = sos.shape
 
if M != 6:
raise ValueError('sos array should be N by 6')
 
a = array([1])
b = array([1])
 
for i in range(N):
b = polymul(b, sos[i, :3])
a = polymul(a, sos[i, 3:])
 
b = trim_zeros(b, 'b')
a = trim_zeros(a, 'b')
 
b *= k
 
return b, a
 
 
def sos2zpk(sos, k=1):
"""
Second-order sections representation to zero-pole-gain representation
 
Return zero, pole, gain (z,p,k) representation from a series second-order
sections ("SOS") representation of a linear filter.
 
(pole residues).
 
Parameters
----------
[copy from sos2tf]
 
Returns
-------
z : ndarray
Zeros of the IIR filter transfer function (roots of B(z)).
p : ndarray
Poles of the IIR filter transfer function (roots of A(z)).
k : float
Overall system gain of the IIR filter transfer function (= B(Inf)). TODO: WTF
 
Examples
--------
>>> z, p, k = sos2zpk([[1, 0, 1, 1, 0, -0.81], [1, 0, 0, 1, 0, 0.49]])
>>> z
array([ 0.+1.j, 0.-1.j, 0.+0.j, 0.+0.j])
>>> p
array([ 0.9+0.j , -0.9+0.j , 0.0+0.7j, 0.0-0.7j])
>>> k
1.0
 
See Also
--------
zp2sos, sos2tf, tf2sos, zp2tf, tf2zp
 
"""
sos = atleast_2d(asfarray(sos)) # TODO else the following lines won't work for 1D array or list, right? chec kfor 3d?
gains = sos[:, 0] # All b0 coefficients
 
k = prod(gains) * k # pole-zero gain
if k == 0:
raise ValueError('One or more section gains is zero')
 
N, M = sos.shape
if M != 6:
raise ValueError('Array sos should be N by 6')
 
sos[:, :3] /= array([gains, gains, gains]).T
 
z = empty(2 * N, dtype=complex)
p = empty(2 * N, dtype=complex)
for i in range(N):
# every 2 rows [0:2], [2:4], ...
zi = roots(sos[i, :3])
z[2*i:2*(i+1)] = zi
pi = roots(sos[i, 3:])
p[2*i:2*(i+1)] = pi
 
return z, p, k
 
 
def zpk2sos(z=None, p=array([]), k=1):
"""
Zero-pole-gain representation to second-order sections representation
 
Return the series second-order section (SOS) representation of a linear
filter from its zero, pole, gain (ZPK) representation.
 
Parameters
----------
[copy from sos2zpk]
 
Returns
-------
[copy from sos2tf]
b0 must be nonzero for each section.@*
See @code{filter()} for documentation of the
second-order direct-form filter coefficients `B`i and
%`A`i, i=1:N.
 
k : float
[copy from others]
overall gain factor that effectively scales
any one of the `B`i vectors.
 
Examples
--------
>>> z,p,k = tf2zpk([1, 0, 0, 0, 0, 1],[1, 0, 0, 0, 0, .9])
>>> sos,k = zpk2sos(z, p, k)
>>> sos
array([[ 1. , 0.618 , 1. , 1. , 0.6051, 0.9587],
[ 1. , -1.618 , 1. , 1. , -1.5843, 0.9587],
[ 1. , 1. , -0. , 1. , 0.9791, -0. ]])
>>> k
1.0
 
See Also
--------
sos2pz, sos2tf, tf2sos, zp2tf, tf2zp
 
"""
zc, zr = cplxreal(asarray(z))
pc, pr = cplxreal(asarray(p))
 
# zc,zr,pc,pr
 
nzc = len(zc)
npc = len(pc)
 
nzr = len(zr)
npr = len(pr)
 
# Pair up real zeros:
if nzr:
if nzr % 2 == 1:
zr = append(zr, 0)
nzr = nzr + 1
nzrsec = nzr / 2.0
# prms, prp, zrms, zrp # TODO: are these always real? cast from complex warning
# if filter is real, then yes, sos output is always real
zrms = -zr[:nzr-1:2] - zr[1:nzr:2]
zrp = zr[:nzr-1:2] * zr[1:nzr:2]
else:
nzrsec = 0
 
# Pair up real poles:
if npr:
if npr % 2 == 1:
pr = append(pr, 0)
npr = npr + 1
nprsec = npr / 2.0
prms = -pr[:npr-1:2] - pr[1:npr:2]
prp = pr[:npr-1:2] * pr[1:npr:2]
else:
nprsec = 0
 
nsecs = int(max(nzc + nzrsec, npc + nprsec))
 
# Convert complex zeros and poles to real 2nd-order section form:
zcm2r = -2 * zc.real
zca2 = abs(zc)**2
pcm2r = -2 * pc.real
pca2 = abs(pc)**2
 
sos = empty((nsecs, 6))
 
# all 2nd-order polynomials are monic
sos[:, 0] = ones(nsecs)
sos[:, 3] = ones(nsecs)
 
nzrl = nzc + nzrsec # index of last real zero section
nprl = npc + nprsec # index of last real pole section
 
 
 
for i in range(nsecs):
if i + 1 <= nzc: # lay down a complex zero pair:
sos[i, 1:3] = append(zcm2r[i], zca2[i])
elif i + 1 <= nzrl: # lay down a pair of real zeros:
sos[i, 1:3] = append(zrms[i - nzc], zrp[i - nzc])
 
if i + 1 <= npc: # lay down a complex pole pair:
sos[i, 4:6] = append(pcm2r[i], pca2[i])
elif i + 1 <= nprl: # lay down a pair of real poles:
sos[i, 4:6] = append(prms[i - npc], prp[i - npc])
 
if rank(sos) == 1:
sos = array([sos])
return sos, k
 
 
 
# Everything above this is GPL, direct translation from Octave
#########################################################################
 
 
 
#########################################################################
# Everything below this written by myself and BSD-licensed for scipy:
 
 
 
 
"""
TODO: Do the float comparisons correctly, using spacing(max(a,b)) or something
Octave: "those with abs (imag (z) / z) < tol)"
 
http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
http://stackoverflow.com/questions/5595425/what-is-the-best-way-to-compare-floats-for-almost-equality-in-python
 
TODO: array almost equal uses decimal=6, so maybe do that? that seems
like a better idea, according to
https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
 
TODO: Should this have an atol and rtol like allclose? ask in pull request
Could be a spacing() multipler, a atol/rtol, a decimal, etc.
 
 
TODO: should have the same parameter name, either tol= or thresh=?
matlab has B = cplxpair(A,tol,dim)
Octave has cplxpair (z, tol, dim)
Octave has cplxreal (z, thresh) in signal package, though tol and thresh do the same thing, so prefer tol?
numpy.allclose(a, b, rtol=1.0000000000000001e-05, atol=1e-08)
numpy.testing.assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True)
 
 
TODO: maybe incorporate this enhanced functionality too?
http://www.mathworks.com/matlabcentral/fileexchange/8037-more-flexible-sorting-and-multiplicity-of-roots-of-a-polynomial/content/cmplx_roots_sort.m
 
 
TODO: N-D arrays, axis= parameter? "By default the complex pairs are
sorted along the first non-singleton dimension of z. If dim is
specified, then the complex pairs are sorted along this dimension."
 
 
TODO: Conceivably, sorting and matching inaccurate pairs could result in a
mismatch? Does it matter? Would result in a "no matching conjugate" error?
"""
 
 
def cplxreal(z, tol=100*spacing(1)):
"""
Split into complex and real outputs, combining conjugate pairs.
 
The 1D input vector z is split up into its complex (`zc`) and real (`zr`)
elements. Every complex element must be part of a complex-conjugate pair,
which are combined into a single number for output.
 
Parameters
----------
z : array_like
Vector of complex numbers to be sorted and split
tol : float
Relative tolerance for testing realness and equality.
Default is 100 * spacing(1)
 
Returns
-------
zc : ndarray
Complex elements of `z`, with each pair represented by a single value
having positive imaginary part, sorted first by real part, and then
by magnitude of imaginary part. The pairs are forced to be exact
complex conjugates by averaging.
zr : ndarray
Real elements of `z` (those having imaginary part less than
spacing*tol), sorted by value.
 
Raises
------
ValueError
If there are any complex numbers in `z` for which a conjugate
cannot be found.
 
See Also
--------
cplxpair
 
Examples
--------
>>> a = [4, 3, 1, 2-2j, 2+2j, 2-1j, 2+1j, 2-1j, 2+1j, 1+1j, 1-1j]
>>> zc, zr = cplxreal(a)
>>> print zc
[ 1.+1.j 2.+1.j 2.+1.j 2.+2.j]
>>> print zr
[ 1. 3. 4.]
 
"""
z = asarray(z)
if z.size == 0:
return array([]), array([])
 
# Sort by real part, magnitude of imaginary part
z = z[lexsort((abs(z.imag), z.real))]
 
# def conjpair(a, b):
# """a and b are approximately a complex conjugate pair"""
# if a == conj(b):
# return True
# elif a * b == 0:
# return abs(a - conj(b)) < tol * spacing(abs(a))
# else:
# return abs(a - conj(b)) / (abs(a) + abs(b)) < tol * spacing(abs(a))
#
# def iscomplex(a):
# """Imaginary part of input is non-negligible"""
# if a.imag == 0:
# return False
# else:
# return abs(a.imag) > tol * spacing(abs(a))
 
# Split reals from conjugate pairs
reals = abs(z.imag) < tol * abs(z) # TODO: use iscomplex here?
zr = z[reals].real
 
if len(zr) == len(z):
return array([]), zr
 
z = z[~reals]
zp = z[z.imag > 0]
zn = z[z.imag < 0]
 
if len(zp) != len(zn):
if len(zp) > len(zn):
bad_match = str(zp[-1])
else:
bad_match = str(zn[-1])
raise ValueError('Array contains complex value with no matching '
'conjugate. \nFirst mismatch is: ' + bad_match)
 
if any(abs(zp - conj(zn)) > tol * abs(zn)):
# Find and report the mismatch
for i in range(min(len(zn), len(zp))):
if abs(zp[i] - conj(zn[i])) > tol * abs(zn[i]):
bad_match = '{0}, {1}'.format(zp[i], zn[i])
match_error = abs(zp[i] - conj(zn[i]))/abs(zn[i])
break
 
raise ValueError('Array contains complex value with no matching '
'conjugate. \nFirst mismatch is: ' + bad_match +
'\nRelative error is ' + str(match_error) +
' vs tol of ' + str(tol))
 
# Average real and imag parts of pairs to try to minimize numerical error
zc = mean(vstack((zp, conj(zn))), 0)
 
return zc, zr
 
 
def cplxpair(z, tol=100*spacing(1)):
"""
Sort `z` into pairs of complex conjugates.
 
Currently this is for 1D arrays only.
 
Complex conjugates are sorted by increasing real part. In each pair, the
number with negative imaginary part appears first.
 
If pairs have identical real parts, they are sorted by increasing
imaginary magnitude.
 
Two complex numbers are considered a conjugate pair if their real and
imaginary parts differ in magnitude by less than `tol`. TODO: tol The conjugate
pairs are forced to be exact complex conjugates by averaging the real and
imaginary parts.
 
Purely real numbers are also sorted, but placed after the complex
conjugate pairs. A number is considered real if its imaginary part is
smaller than `tol`. TODO: tol
 
Parameters
----------
z : array_like
Input array to be sorted
tol : float
Tolerance used for testing equality of conjugate pairs and
negligibility of imaginary part for real numbers
 
Returns
-------
y : ndarray
Complex conjugate pairs followed by real numbers
 
Raises
------
ValueError
If there are any complex numbers in `z` for which a conjugate
cannot be found.
 
See Also
--------
cplxreal: Splits the real and complex pair components of the input
 
"""
z = atleast_1d(z)
if z.size == 0 or isrealobj(z):
return z
zc, zr = cplxreal(z, tol)
 
# Interleave complex values and their conjugates, with negative imaginary
# parts first in each pair
zc = dstack((conj(zc), zc)).flatten()
 
return append(zc, zr)
 
 
# TODO: Does it make sense to support zi parameter?
# TODO: Does it handle ND arrays correctly?
def sosfilt(sos, x, axis=-1):
"""
Filter a signal using cascaded second-order sections
 
Filter a data sequence, `x`, using a digital filter defined by `sos`.
This is implemented simply by performing `lfilter` for each second-order
section. See `lfilter` for details.
 
Parameters
----------
sos : array_like
[copy from sos2tf]
The second order section filter is described by the matrix sos with:
 
[ B1 A1 ]
 
sos = [ ... ],
 
[ BN AN ]
 
where B1=[b0 b1 b2] and A1=[1 a1 a2] for section 1, etc.
b0 must be nonzero for each section.
 
If a[0]
is not 1, then both a and b are normalized by a[0].
x : array_like
An N-dimensional input array.
axis : int
The axis of the input data array along which to apply the
linear filter. The filter is applied to each subarray along
this axis (*Default* = -1)
zi : array_like (optional)
Initial conditions for the filter delays. It is a vector
(or array of vectors for an N-dimensional input) of length TODO: FIX THIS
max(len(a),len(b))-1. If zi=None or is not given, then initial
rest is assumed. SEE signal.lfiltic for more information.
 
Returns
-------
y : array
The output of the digital filter.
zf : array (optional)
If zi is None, this is not returned, otherwise, zf holds the
final filter delay values.
 
"""
sos = atleast_2d(sos)
n, m = sos.shape
 
# if zi is None:
# else:
# x, zi??? = lfilter(sos[i, :3], sos[i, 3:], x, axis, zi)
# return x, zi
 
for i in range(n):
B = sos[i, :3]
A = sos[i, 3:]
x = lfilter(B, A, x, axis)
return x
 
 
 
if __name__ == "__main__":
from numpy.testing import assert_array_almost_equal, assert_raises
from numpy.random import shuffle
from numpy import arange, pi, exp, sin, copy
 
# cplxpair tests
assert (cplxpair([]).size == 0)
assert (cplxpair(1) == 1)
assert_array_almost_equal(cplxpair([1+1j, 1-1j]), [1-1j, 1+1j])
 
a = [1+1j, 1+1j, 1, 1-1j, 1-1j, 2]
b = [1-1j, 1+1j, 1-1j, 1+1j, 1, 2]
assert_array_almost_equal(cplxpair(a), b)
 
assert_array_almost_equal(cplxpair([0, 1, 2]), [0, 1, 2])
 
z = exp(2j*pi*array([4, 3, 5, 2, 6, 1, 0])/7)
z1 = copy(z)
shuffle(z)
assert_array_almost_equal(cplxpair(z), z1)
shuffle(z)
assert_array_almost_equal(cplxpair(z), z1)
shuffle(z)
assert_array_almost_equal(cplxpair(z), z1)
 
# tolerance test
assert_array_almost_equal(cplxpair([1j, -1j, 1+(1j*spacing(1))], 2*spacing(1)),
[-1j, 1j, 1+(1j*spacing(1))])
 
 
# sorting close to 0
assert_array_almost_equal(cplxpair([-spacing(1)+1j, +spacing(1)-1j]),
[0 - 1j, -0 + 1j])
assert_array_almost_equal(cplxpair([+spacing(1)+1j, -spacing(1)-1j]),
[-0 - 1j, 0 + 1j])
assert_array_almost_equal(cplxpair([0+1j, 0-1j]),
[0 - 1j, 0 + 1j])
 
# Should be able to pair up all the conjugates
x = rand(10000) + 1j * rand(10000)
y = conj(x)
z = rand(10000)
x = append(append(x, y), z)
shuffle(x)
#timeit cplxpair(x) # 0.6 seconds, vs 13 seconds for Octave's function
c = cplxpair(x)
 
# Every other element of head should be conjugates:
assert_array_almost_equal(c[0:20000:2], conj(c[1:20000:2]))
# Real parts should be in sorted order:
assert_array_almost_equal(c[0:20000:2].real, sort(c[0:20000:2].real))
# Tail should be sorted real numbers:
assert_array_almost_equal(c[20000:], sort(c[20000:]))
 
# Octave comparison:
"""
x = rand(10000,1) + i*rand(10000,1);
y = conj(x);
z = rand(10000,1);
x = [x;y;z];
ix = randperm(length(x));
xsh = x(ix);
length(xsh)
cplxpair (xsh);
"""
 
assert_raises(ValueError, cplxpair, [1+3j, 1-3j, 1+2j])
 
a1 = cplxpair(exp(2j*pi*arange(5 )/5))
a2 = exp(2j*pi*array([3, 2, 4, 1, 0])/5)
ans = [
-0.80902 - 0.58779j,
-0.80902 + 0.58779j,
0.30902 - 0.95106j,
0.30902 + 0.95106j,
1.00000 + 0.00000j,
]
assert_array_almost_equal(a1, ans, decimal=5)
assert_array_almost_equal(a2, ans, decimal=5)
 
 
 
 
 
 
 
 
# cplxreal tests
zc, zr = cplxreal(roots(array([1, 0, 0, 1])))
assert_array_almost_equal(append(zc, zr), [0.5 + 1j * sin(pi / 3), -1])
 
a = [1, 2, 3, 4, 5, 0+1j, 0-1j, 0+spacing(1)+1j, 0+spacing(1)-1j,
0-spacing(1)+1j, 0-spacing(1)-1j, 1+1j, 1+1j, 1+1j, 1-1j,
1-1j, 1-1j, 1+2j, 1-2j, 2+3j, 2-3j, 2+3j, 2-3j]
shuffle(a)
zc, zr = cplxreal(a)
assert_array_almost_equal(zc, [0+1j, 0+1j, 0+1j, 1+1j, 1+1j, 1+1j, 1+2j, 2+3j, 2+3j])
assert_array_almost_equal(zr, [1, 2, 3, 4, 5])
 
 
# TODO: make a test with poor tolerance and conflated values to test that the pair averaging is working
 
assert_raises(ValueError, cplxreal, [1+3j, 1-3j, 1+2j])
assert_raises(ValueError, cplxreal, [1+3j, 1-3j, 1+2j, 1-3j])
assert_raises(ValueError, cplxreal, [1+3j, 1-3j, 1+3j])
assert_raises(ValueError, cplxreal, [1+3j])
assert_raises(ValueError, cplxreal, [1-3j])
 
# SOS tests
B = [1, 0, 0, 0, 0, 1]
A = [1, 0, 0, 0, 0, .9]
 
z, p, k = tf2zpk(B, A)
sos, k = zpk2sos(z, p, k)
Bh, Ah = sos2tf(sos, k)
assert_array_almost_equal([Bh, Ah], [B, A])
# works
 
sos, k = tf2sos(B, A)
Bh, Ah = sos2tf(sos, k)
assert_array_almost_equal([Bh, Ah], [B, A])
# works
 
sos2 = [[1.00000, 0.61803, 1.0000, 1.00000, 0.60515, 0.95873],
[1.00000, -1.61803, 1.0000, 1.00000, -1.58430, 0.95873],
[1.00000, 1.00000, 0.0000, 1.00000, 0.97915, 0.00000]]
k2 = 1
 
z, p, k = tf2zpk(B, A)
sos, k = zpk2sos(z, p, k)
assert_array_almost_equal(sos, sos2, decimal=5)
assert_array_almost_equal(k, k2)
 
sos, k = tf2sos(B, A)
assert_array_almost_equal(sos, sos2, decimal=5)
assert_array_almost_equal(k, k2)
 
B = array([1, 1])
A = array([1, 0.5])
sos, k = tf2sos(B, A)
Bh, Ah = sos2tf(sos, k)
assert_array_almost_equal([Bh, Ah], [B, A])
# works
 
 
 
 
# Matlab example
sos = [[1, 1, 1, 1, 0, -1], [-2, 3, 1, 1, 10, 1]]
b, a = sos2tf(sos)
b2 = [-2, 1, 2, 4, 1]
a2 = [1, 10, 0, -10, -1]
assert_array_almost_equal(a, a2)
assert_array_almost_equal(b, b2)
# works
 
# ordering wrong:
z, p, k = sos2zpk(sos)
z2 = [-0.5000 + 0.8660j, -0.5000 - 0.8660j, 1.7808, -0.2808]
p2 = [-1.0000, 1.0000, -9.8990, -0.1010]
k2 = -2
assert_array_almost_equal(z, z2, decimal=4)
assert_array_almost_equal(sort(p), sort(p2), decimal=4)
assert_array_almost_equal(k, k2)
# order of poles isn't important
 
 
z, p, k = sos2zpk([[1, 0, 1, 1, 0, -0.81], [1, 0, 0, 1, 0, 0.49]])
z2 = [1j, -1j, 0, 0]
p2 = [0.9, -0.9, 0.7j, -0.7j]
k2 = 1
assert_array_almost_equal(z, z2, decimal=4)
assert_array_almost_equal(p, p2, decimal=4)
assert_array_almost_equal(k, k2)
 
 
 
b1t = array([1, 2, 3])
a1t = array([1, .2, .3])
 
b2t = array([4, 5, 6])
a2t = array([1, .4, .5])
 
sos = array([append(b1t, a1t), append(b2t, a2t)])
 
z = array([-1 - 1.41421356237310j, -1 + 1.41421356237310j,
-0.625 - 1.05326872164704j, -0.625 + 1.05326872164704j])
p = array([-0.2 - 0.678232998312527j, -0.2 + 0.678232998312527j,
-0.1 - 0.538516480713450j, -0.1 + 0.538516480713450j])
k = 4
z2, p2, k2 = sos2zpk(sos, 1)
assert_array_almost_equal(cplxpair(z2), z)
assert_array_almost_equal(cplxpair(p2), p)
assert_array_almost_equal(k2, k)
# doesn't work
 
z = [-1, -1]
p = [0.57149 + 0.29360j, 0.57149 - 0.29360j]
sos, k = zpk2sos(z, p)
sos2 = [[1.00000, 2.00000, 1.00000, 1.00000, -1.14298, 0.41280]]
k2 = 1
assert_array_almost_equal(sos, sos2, decimal=5)
assert_array_almost_equal(k2, k)
 
N = [1, -.5, -.315, -.0185]
D = [1, -.5, .5, -.25]
sos, k = tf2sos(N, D)
sos2 = [[1.0000, 0.3813, 0.0210, 1.0000, 0.0000, 0.5000],
[1.0000, -0.8813, 0.0000, 1.0000, -0.5000, 0.0000],
]
k2 = 1
assert_array_almost_equal(sos, sos2, decimal=4)
assert_array_almost_equal(k2, k)
# sos order doesn't matter either? so reordered sections to match
 
b = [0.5, 0, -0.18]
a = [1, 0.1, -0.72]
z, p, c = tf2zpk(b, a)
z2 = [0.6, -0.6]
p2 = [-0.9, 0.8]
c2 = 0.5
assert_array_almost_equal(z, z2, decimal=6)
assert_array_almost_equal(p, p2, decimal=6)
assert_array_almost_equal(c, c2)
 
 
# num = [2, 16, 44, 56, 32]
# den = [3, 3, -15, 18, -12]
# sos = tf2sos(num, den)
# sos2 = [[0.6667, 4.0000, 5.3333, 1.0000, 2.0000, -4.0000],
# [1.0000, 2.0000, 2.0000, 1.0000, -1.0000, 1.0000]]
# # Matlab doesn't normalize by k if you don't ask for it?
# # different order?
# assert_array_almost_equal(sos, sos2)
# Matches Octave behavior though
 
B = [1, 0, 0, 0, 0, 1]
A = [1, 0, 0, 0, 0, 0.9]
sos, g = tf2sos(B,A)
sos2 = [
[1.00000, 0.61803, 1.00000, 1.00000, 0.60515, 0.95873],
[1.00000, -1.61803, 1.00000, 1.00000, -1.58430, 0.95873],
[1.00000, 1.00000, -0.00000, 1.00000, 0.97915, -0.00000],
]
g2 = 1
assert_array_almost_equal(sos, sos2, decimal=5)
assert_array_almost_equal(g, g2)
 
b = [1, -3, 11, -27, 18]
a = [16, 12, 2, -4, -1]
sos, G = tf2sos(b, a)
G2 = 0.0625
sos2 = [[1.0000, 0.0000, 9.0000, 1.0000, 1.0000, 0.5000],
[1.0000, -3.0000, 2.0000, 1.0000, -.25000, -.12500]]
# matlab different order?
assert_array_almost_equal(sos, sos2)
assert_array_almost_equal(G, G2)
 
 
 
 
 
 
# state-space tests:
 
#b = [2 3 0];
#a = [1 0.4 1];
#[z,p,k] = tf2zp(b,a)
#z =
# 0.0000
# -1.5000
#p =
# -0.2000 + 0.9798i
# -0.2000 - 0.9798i
#k =
# 2
#[A,B,C,D] = tf2ss(b,a);
#[z,p,k] = ss2zp(A,B,C,D,1)
#z =
# 0.0000
# -1.5000
#p =
# -0.2000 + 0.9798i
# -0.2000 - 0.9798i
#k =
# 2
 
 
 
 
#b = [0 2 3; 1 2 1];
#a = [1 0.4 1];
#[A,B,C,D] = tf2ss(b,a)
#A =
# -0.4000 -1.0000
# 1.0000 0
#B =
# 1
# 0
#C =
# 2.0000 3.0000
# 1.6000 0
#D =
# 0
# 1
 
 
 
 
 
#sos = [1 1 1 1 0 -1; -2 3 1 1 10 1];
#[A,B,C,D] = sos2ss(sos)
#A =
# -10 0 10 1
# 1 0 0 0
# 0 1 0 0
# 0 0 1 0
#B =
# 1
# 0
# 0
# 0
#C =
# 21 2 -16 -1
#D =
# -2
# from scipy.signal import bessel, cheby1, cheby2, ellip
#
# z1, p1, k1 = tf2zpk(*cheby1(15, 60, pi, 'high', analog=True))
# z2, p2, k2 = zpklp2lp(*tf2zpk(*cheby1(15, 60, 1, 'high', analog=True)), wo=pi)
#
# assert_array_almost_equal(z1, z2)
# assert_array_almost_equal(p1, p2)
# assert_array_almost_equal(k1, k2)
#
#

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.