def test_basic(self):
        c = companion([1, 2, 3])
        expected = array([[-2.0, -3.0], [1.0, 0.0]])
        assert_array_equal(c, expected)

        c = companion([2.0, 5.0, -10.0])
        expected = array([[-2.5, 5.0], [1.0, 0.0]])
        assert_array_equal(c, expected)
Exemple #2
0
    def test_basic(self):
        c = companion([1, 2, 3])
        expected = array([[-2.0, -3.0], [1.0, 0.0]])
        assert_array_equal(c, expected)

        c = companion([2.0, 5.0, -10.0])
        expected = array([[-2.5, 5.0], [1.0, 0.0]])
        assert_array_equal(c, expected)
Exemple #3
0
def test_fiedler_companion():
    fc = fiedler_companion([])
    assert_equal(fc.size, 0)
    fc = fiedler_companion([1.])
    assert_equal(fc.size, 0)
    fc = fiedler_companion([1., 2.])
    assert_array_equal(fc, np.array([[-2.]]))
    fc = fiedler_companion([1e-12, 2., 3.])
    assert_array_almost_equal(fc, companion([1e-12, 2., 3.]))
    with assert_raises(ValueError):
        fiedler_companion([0, 1, 2])
    fc = fiedler_companion([1., -16., 86., -176., 105.])
    assert_array_almost_equal(eigvals(fc), np.array([7., 5., 3., 1.]))
def test_fiedler_companion():
    fc = fiedler_companion([])
    assert_equal(fc.size, 0)
    fc = fiedler_companion([1.])
    assert_equal(fc.size, 0)
    fc = fiedler_companion([1., 2.])
    assert_array_equal(fc, np.array([[-2.]]))
    fc = fiedler_companion([1e-12, 2., 3.])
    assert_array_almost_equal(fc, companion([1e-12, 2., 3.]))
    with assert_raises(ValueError):
        fiedler_companion([0, 1, 2])
    fc = fiedler_companion([1., -16., 86., -176., 105.])
    assert_array_almost_equal(eigvals(fc),
                              np.array([7., 5., 3., 1.]))
Exemple #5
0
 def test_from_state_space(self):
     # Ensure that freqresp works with a system that was created from the
     # state space representation matrices A, B, C, D.  In this case,
     # system.num will be a 2-D array with shape (1, n+1), where (n,n) is
     # the shape of A.
     # A Butterworth lowpass filter is used, so we know the exact
     # frequency response.
     a = np.array([1.0, 2.0, 2.0, 1.0])
     A = linalg.companion(a).T
     B = np.array([[0.0],[0.0],[1.0]])
     C = np.array([[1.0, 0.0, 0.0]])
     D = np.array([[0.0]])
     with warnings.catch_warnings():
         warnings.simplefilter("ignore", BadCoefficients)
         system = lti(A, B, C, D)
         w, H = freqresp(system, n=100)
     expected_magnitude = np.sqrt(1.0 / (1.0 + w**6))
     assert_almost_equal(np.abs(H), expected_magnitude)
Exemple #6
0
 def test_from_state_space(self):
     # Ensure that freqresp works with a system that was created from the
     # state space representation matrices A, B, C, D.  In this case,
     # system.num will be a 2-D array with shape (1, n+1), where (n,n) is
     # the shape of A.
     # A Butterworth lowpass filter is used, so we know the exact
     # frequency response.
     a = np.array([1.0, 2.0, 2.0, 1.0])
     A = linalg.companion(a).T
     B = np.array([[0.0], [0.0], [1.0]])
     C = np.array([[1.0, 0.0, 0.0]])
     D = np.array([[0.0]])
     with warnings.catch_warnings():
         warnings.simplefilter("ignore", BadCoefficients)
         system = lti(A, B, C, D)
     w, H = freqresp(system, n=100)
     expected_magnitude = np.sqrt(1.0 / (1.0 + w**6))
     assert_almost_equal(np.abs(H), expected_magnitude)
Exemple #7
0
    def test_from_state_space(self):
        # Ensure that bode works with a system that was created from the
        # state space representation matrices A, B, C, D.  In this case,
        # system.num will be a 2-D array with shape (1, n+1), where (n,n)
        # is the shape of A.
        # A Butterworth lowpass filter is used, so we know the exact
        # frequency response.
        a = np.array([1.0, 2.0, 2.0, 1.0])
        A = linalg.companion(a).T
        B = np.array([[0.0], [0.0], [1.0]])
        C = np.array([[1.0, 0.0, 0.0]])
        D = np.array([[0.0]])
        with suppress_warnings() as sup:
            sup.filter(BadCoefficients)
            system = lti(A, B, C, D)
            w, mag, phase = bode(system, n=100)

        expected_magnitude = 20 * np.log10(np.sqrt(1.0 / (1.0 + w**6)))
        assert_almost_equal(mag, expected_magnitude)
Exemple #8
0
    def test_from_state_space(self):
        # Ensure that bode works with a system that was created from the
        # state space representation matrices A, B, C, D.  In this case,
        # system.num will be a 2-D array with shape (1, n+1), where (n,n)
        # is the shape of A.
        # A Butterworth lowpass filter is used, so we know the exact
        # frequency response.
        a = np.array([1.0, 2.0, 2.0, 1.0])
        A = linalg.companion(a).T
        B = np.array([[0.0], [0.0], [1.0]])
        C = np.array([[1.0, 0.0, 0.0]])
        D = np.array([[0.0]])
        with suppress_warnings() as sup:
            sup.filter(BadCoefficients)
            system = lti(A, B, C, D)
            w, mag, phase = bode(system, n=100)

        expected_magnitude = 20 * np.log10(np.sqrt(1.0 / (1.0 + w**6)))
        assert_almost_equal(mag, expected_magnitude)
Exemple #9
0
 def test_from_state_space(self):
     # Ensure that freqresp works with a system that was created from the
     # state space representation matrices A, B, C, D.  In this case,
     # system.num will be a 2-D array with shape (1, n+1), where (n,n) is
     # the shape of A.
     # A Butterworth lowpass filter is used, so we know the exact
     # frequency response.
     a = np.array([1.0, 2.0, 2.0, 1.0])
     A = linalg.companion(a).T
     B = np.array([[0.0], [0.0], [1.0]])
     C = np.array([[1.0, 0.0, 0.0]])
     D = np.array([[0.0]])
     with suppress_warnings() as sup:
         sup.filter(BadCoefficients)
         system = lti(A, B, C, D)
         w, H = freqresp(system, n=100)
     s = w * 1j
     expected = (1.0 / (1.0 + 2 * s + 2 * s**2 + s**3))
     assert_almost_equal(H.real, expected.real)
     assert_almost_equal(H.imag, expected.imag)
Exemple #10
0
 def test_from_state_space(self):
     # Ensure that freqresp works with a system that was created from the
     # state space representation matrices A, B, C, D.  In this case,
     # system.num will be a 2-D array with shape (1, n+1), where (n,n) is
     # the shape of A.
     # A Butterworth lowpass filter is used, so we know the exact
     # frequency response.
     a = np.array([1.0, 2.0, 2.0, 1.0])
     A = linalg.companion(a).T
     B = np.array([[0.0],[0.0],[1.0]])
     C = np.array([[1.0, 0.0, 0.0]])
     D = np.array([[0.0]])
     with suppress_warnings() as sup:
         sup.filter(BadCoefficients)
         system = lti(A, B, C, D)
         w, H = freqresp(system, n=100)
     s = w * 1j
     expected = (1.0 / (1.0 + 2*s + 2*s**2 + s**3))
     assert_almost_equal(H.real, expected.real)
     assert_almost_equal(H.imag, expected.imag)
Exemple #11
0
from scipy import linalg as la
import numpy as np
x = np.roots([10,5,-5,1])
print x
a = la.companion([10,5,-5,1])
print a
b=la.eig(a)
print b
Exemple #12
0
    def get_poles(self, method='lscf', show_progress=True):
        """Compute poles based on polynomial approximation of FRF.

        Source: https://github.com/openmodal/OpenModal/blob/master/OpenModal/analysis/lscf.py

        The LSCF method is an frequency-domain Linear Least Squares
        estimator optimized  for modal parameter estimation. The choice of
        the most important algorithm characteristics is based on the
        results in [1] (Section 5.3.3.) and can be summarized as:

            - Formulation: the normal equations [1]
            (Eq. 5.26: [sum(Tk - Sk.H * Rk^-1 * Sk)]*ThetaA=D*ThetaA = 0)
            are constructed for the common denominator discrete-time
            model in the Z-domain. Consequently, by looping over the
            outputs and inputs, the submatrices Rk, Sk, and Tk are
            formulated through the use of the FFT algorithm as Toeplitz
            structured (n+1) square matrices. Using complex coefficients,
            the FRF data within the frequency band of interest (FRF-zoom)
            is projected in the Z-domain in the interval of [0, 2*pi] in
            order to improve numerical conditioning. (In the case that
            real coefficients are used, the data is projected in the
            interval of [0, pi].) The projecting on an interval that does
            not completely describe the unity circle, say [0, alpha*2*pi]
            where alpha is typically 0.9-0.95. Deliberately over-modeling
            is best applied to cope with discontinuities. This is
            justified by the use of a discrete time model in the Z-domain,
            which is much more robust for a high order of the transfer
            function polynomials.

            - Solver: the normal equations can be solved for the
            denominator coefficients ThetaA by computing the Least-Squares
            (LS) or mixed Total-Least-Squares (TLS) solution. The inverse
            of the square matrix D for the LS solution is computed by
            means of a pseudo inverse operation for reasons of numerical
            stability, while the mixed LS-TLS solution is computed using
            an SVD (Singular Value Decomposition).

        Literature:
            [1] Verboven, P., Frequency-domain System Identification for
                Modal Analysis, Ph. D. thesis, Mechanical Engineering Dept.
                (WERK), Vrije Universiteit Brussel, Brussel, (Belgium),
                May 2002, (http://mech.vub.ac.be/avrg/PhD/thesis_PV_web.pdf)
            [2] Verboven, P., Guillaume, P., Cauberghe, B., Parloo, E. and
                Vanlanduit S., Stabilization Charts and Uncertainty Bounds
                For Frequency-Domain Linear Least Squares Estimators, Vrije
                Universiteit Brussel(VUB), Mechanical Engineering Dept.
                (WERK), Acoustic and Vibration Research Group (AVRG),
                Pleinlaan 2, B-1050 Brussels, Belgium,
                e-mail: [email protected], url:
                (http://sem-proceedings.com/21i/sem.org-IMAC-XXI-Conf-s02p01
                -Stabilization-Charts-Uncertainty-Bounds-Frequency-Domain-
                Linear-Least.pdf)
            [3] P. Guillaume, P. Verboven, S. Vanlanduit, H. Van der
                Auweraer, B. Peeters, A Poly-Reference Implementation of the
                Least-Squares Complex Frequency-Domain Estimator, Vrije
                Universiteit Brussel, LMS International

        :param method: The method of poles calculation.
        :param show_progress: Show progress bar
        """
        if method != 'lscf':
            raise Exception(
                f'no method "{method}". Currently only "lscf" method is implemented.'
            )

        if show_progress:

            def tqdm_range(x):
                return tqdm(x, ncols=100)
        else:

            def tqdm_range(x):
                return x

        self.all_poles = []
        self.pole_freq = []
        self.pole_xi = []
        self.partfactors = []

        lower_ind = np.argmin(np.abs(self.freq - self.lower))
        n = self.pol_order_high * 2
        nf = 2 * (self.frf.shape[1] - 1)
        nr = self.frf.shape[0]

        indices_s = np.arange(-n, n + 1)
        indices_t = np.arange(n + 1)

        sk = -_irfft_adjusted_lower_limit(self.frf, lower_ind, indices_s)
        t = _irfft_adjusted_lower_limit(self.frf.real**2 + self.frf.imag**2,
                                        lower_ind, indices_t)
        r = -(np.fft.irfft(np.ones(lower_ind), n=nf))[indices_t] * nf
        r[0] += nf

        s = []
        for i in range(nr):
            s.append(toeplitz(sk[i, n:], sk[i, :n + 1][::-1]))
        t = toeplitz(np.sum(t[:, :n + 1], axis=0))
        r = toeplitz(r)

        # Ascending polinomial order pole computation
        for j in tqdm_range(range(2, n + 1, 2)):
            d = 0
            rinv = np.linalg.inv(r[:j + 1, :j + 1])
            for i in range(nr):
                snew = s[i][:j + 1, :j + 1]
                d -= np.dot(np.dot(snew[:j + 1, :j + 1].T, rinv),
                            snew[:j + 1, :j + 1])  # sum
            d += t[:j + 1, :j + 1]

            a0an1 = np.linalg.solve(-d[0:j, 0:j], d[0:j, j])
            # the numerator coefficients
            sr = np.roots(np.append(a0an1, 1)[::-1])

            # Z-domain (for discrete-time domain model)
            poles = -np.log(sr) / self.sampling_time

            if self.get_participation_factors:
                _t = companion(np.append(a0an1, 1)[::-1])
                _v, _w = np.linalg.eig(_t)
                self.partfactors.append(_w[-1, :])

            f_pole, ceta = tools.complex_freq_to_freq_and_damp(poles)

            self.all_poles.append(poles)
            self.pole_freq.append(f_pole)
            self.pole_xi.append(ceta)
Exemple #13
0
print('cond(H, 1) = ', np.linalg.cond(h_mat, 1))
print('||H||_1 * ||H^(-1)||_1 = ',
      np.linalg.norm(h_mat, 1) * np.linalg.norm(inv_h_mat, 1))
print('cond(H, np.inf) = ', np.linalg.cond(h_mat, 1))
print('||H||_inf * ||H^(-1)||_inf = ',
      np.linalg.norm(h_mat, np.inf) * np.linalg.norm(inv_h_mat, np.inf))

# det(A)
p_mat = sclinalg.pascal(3)
print('Pascal matrix = \n', p_mat)
print('det(P) = |P| = ', sclinalg.det(p_mat))

# Companion行列と固有値
# p(x) = x^3 + x^2 + x + 1 = 0
poly_coef = [1, 1, 1, 1]
mat_c = sclinalg.companion(poly_coef)
print('Companion matrix = \n', mat_c)
eigval, ev = sclinalg.eig(mat_c)
ev = ev.T
print('Eigenvalues = ', eigval)
print('Eigenvectors = ', ev)
# C * v = lambda * v ?
for i in range(0, eigval.size):
    print('|| C * v - lambda[', i, '] * v||_2 = ',
          sclinalg.norm(mat_c @ ev[i].T - eigval[i] * ev[i]))

# p(lambda) = 0?
eigpoly = np.poly1d(poly_coef)
for i in range(eigval.size):
    print('p(lambda[', i, ']) = ', eigpoly(eigval[i]))
Exemple #14
0
 def time_companion(self, size):
     sl.companion(self.x)
def lfilter_zi(b, a):
    """
    Compute an initial state `zi` for the lfilter function that corresponds
    to the steady state of the step response.

    A typical use of this function is to set the initial state so that the
    output of the filter starts at the same value as the first element of
    the signal to be filtered.

    Parameters
    ----------
    b, a : array_like (1-D)
        The IIR filter coefficients. See `scipy.signal.lfilter` for more
        information.

    Returns
    -------
    zi : 1-D ndarray
        The initial state for the filter.

    Notes
    -----
    A linear filter with order m has a state space representation (A, B, C, D),
    for which the output y of the filter can be expressed as::

        z(n+1) = A*z(n) + B*x(n)
        y(n)   = C*z(n) + D*x(n)

    where z(n) is a vector of length m, A has shape (m, m), B has shape
    (m, 1), C has shape (1, m) and D has shape (1, 1) (assuming x(n) is
    a scalar).  lfilter_zi solves::

        zi = A*zi + B

    In other words, it finds the initial condition for which the response
    to an input of all ones is a constant.

    Given the filter coefficients `a` and `b`, the state space matrices
    for the transposed direct form II implementation of the linear filter,
    which is the implementation used by scipy.signal.lfilter, are::

        A = scipy.linalg.companion(a).T
        B = b[1:] - a[1:]*b[0]

    assuming `a[0]` is 1.0; if `a[0]` is not 1, `a` and `b` are first
    divided by a[0].

    Examples
    --------
    The following code creates a lowpass Butterworth filter. Then it
    applies that filter to an array whose values are all 1.0; the
    output is also all 1.0, as expected for a lowpass filter.  If the
    `zi` argument of `lfilter` had not been given, the output would have
    shown the transient signal.

    >>> from numpy import array, ones
    >>> from scipy.signal import lfilter, lfilter_zi, butter
    >>> b, a = butter(5, 0.25)
    >>> zi = lfilter_zi(b, a)
    >>> y, zo = lfilter(b, a, ones(10), zi=zi)
    >>> y
    array([1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])

    Another example:

    >>> x = array([0.5, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0])
    >>> y, zf = lfilter(b, a, x, zi=zi*x[0])
    >>> y
    array([ 0.5       ,  0.5       ,  0.5       ,  0.49836039,  0.48610528,
        0.44399389,  0.35505241])

    Note that the `zi` argument to `lfilter` was computed using
    `lfilter_zi` and scaled by `x[0]`.  Then the output `y` has no
    transient until the input drops from 0.5 to 0.0.

    """

    # FIXME: Can this function be replaced with an appropriate
    # use of lfiltic?  For example, when b,a = butter(N,Wn),
    #    lfiltic(b, a, y=numpy.ones_like(a), x=numpy.ones_like(b)).
    #

    # We could use scipy.signal.normalize, but it uses warnings in
    # cases where a ValueError is more appropriate, and it allows
    # b to be 2D.
    b = np.atleast_1d(b)
    if b.ndim != 1:
        raise ValueError("Numerator b must be rank 1.")
    a = np.atleast_1d(a)
    if a.ndim != 1:
        raise ValueError("Denominator a must be rank 1.")

    while len(a) > 1 and a[0] == 0.0:
        a = a[1:]
    if a.size < 1:
        raise ValueError("There must be at least one nonzero `a` coefficient.")

    if a[0] != 1.0:
        # Normalize the coefficients so a[0] == 1.
        a = a / a[0]
        b = b / a[0]

    n = max(len(a), len(b))

    # Pad a or b with zeros so they are the same length.
    if len(a) < n:
        a = np.r_[a, np.zeros(n - len(a))]
    elif len(b) < n:
        b = np.r_[b, np.zeros(n - len(b))]

    IminusA = np.eye(n - 1) - linalg.companion(a).T
    B = b[1:] - a[1:] * b[0]
    # Solve zi = A*zi + B
    zi = np.linalg.solve(IminusA, B)

    # For future reference: we could also use the following
    # explicit formulas to solve the linear system:
    #
    # zi = np.zeros(n - 1)
    # zi[0] = B.sum() / IminusA[:,0].sum()
    # asum = 1.0
    # csum = 0.0
    # for k in range(1,n-1):
    #     asum += a[k]
    #     csum += b[k] - a[k]*b[0]
    #     zi[k] = asum*zi[0] - csum

    return zi
Exemple #16
0
import numpy as np
import scipy.linalg as la;
import matplotlib.pyplot as plt

P = [4,5,8,1]

c = la.companion(P)
eigenval,eigenvec=np.linalg.eig(c)

r = eigenval

print(eigenval)

x = []
y = []
for r1 in r:
	x.append(r1.real)
	y.append(r1.imag)	


plt.plot(x,y,'r.')
plt.axis("equal")
plt.show()

Exemple #17
0
def lfilter_zi(b, a):
    """
    Compute an initial state `zi` for the lfilter function that corresponds
    to the steady state of the step response.

    A typical use of this function is to set the initial state so that the
    output of the filter starts at the same value as the first element of
    the signal to be filtered.

    Parameters
    ----------
    b, a : array_like (1-D)
        The IIR filter coefficients. See `scipy.signal.lfilter` for more
        information.

    Returns
    -------
    zi : 1-D ndarray
        The initial state for the filter.

    Notes
    -----
    A linear filter with order m has a state space representation (A, B, C, D),
    for which the output y of the filter can be expressed as::

        z(n+1) = A*z(n) + B*x(n)
        y(n)   = C*z(n) + D*x(n)

    where z(n) is a vector of length m, A has shape (m, m), B has shape
    (m, 1), C has shape (1, m) and D has shape (1, 1) (assuming x(n) is
    a scalar).  lfilter_zi solves::

        zi = A*zi + B

    In other words, it finds the initial condition for which the response
    to an input of all ones is a constant.

    Given the filter coefficients `a` and `b`, the state space matrices
    for the transposed direct form II implementation of the linear filter,
    which is the implementation used by scipy.signal.lfilter, are::

        A = scipy.linalg.companion(a).T
        B = b[1:] - a[1:]*b[0]

    assuming `a[0]` is 1.0; if `a[0]` is not 1, `a` and `b` are first
    divided by a[0].

    Examples
    --------
    The following code creates a lowpass Butterworth filter. Then it
    applies that filter to an array whose values are all 1.0; the
    output is also all 1.0, as expected for a lowpass filter.  If the
    `zi` argument of `lfilter` had not been given, the output would have
    shown the transient signal.

    >>> from numpy import array, ones
    >>> from scipy.signal import lfilter, lfilter_zi, butter
    >>> b, a = butter(5, 0.25)
    >>> zi = lfilter_zi(b, a)
    >>> y, zo = lfilter(b, a, ones(10), zi=zi)
    >>> y
    array([1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])

    Another example:

    >>> x = array([0.5, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0])
    >>> y, zf = lfilter(b, a, x, zi=zi*x[0])
    >>> y
    array([ 0.5       ,  0.5       ,  0.5       ,  0.49836039,  0.48610528,
        0.44399389,  0.35505241])

    Note that the `zi` argument to `lfilter` was computed using
    `lfilter_zi` and scaled by `x[0]`.  Then the output `y` has no
    transient until the input drops from 0.5 to 0.0.

    """

    # FIXME: Can this function be replaced with an appropriate
    # use of lfiltic?  For example, when b,a = butter(N,Wn),
    #    lfiltic(b, a, y=numpy.ones_like(a), x=numpy.ones_like(b)).
    #

    # We could use scipy.signal.normalize, but it uses warnings in
    # cases where a ValueError is more appropriate, and it allows
    # b to be 2D.
    b = np.atleast_1d(b)
    if b.ndim != 1:
        raise ValueError("Numerator b must be rank 1.")
    a = np.atleast_1d(a)
    if a.ndim != 1:
        raise ValueError("Denominator a must be rank 1.")

    while len(a) > 1 and a[0] == 0.0:
        a = a[1:]
    if a.size < 1:
        raise ValueError("There must be at least one nonzero `a` coefficient.")

    if a[0] != 1.0:
        # Normalize the coefficients so a[0] == 1.
        a = a / a[0]
        b = b / a[0]

    n = max(len(a), len(b))

    # Pad a or b with zeros so they are the same length.
    if len(a) < n:
        a = np.r_[a, np.zeros(n - len(a))]
    elif len(b) < n:
        b = np.r_[b, np.zeros(n - len(b))]

    IminusA = np.eye(n - 1) - linalg.companion(a).T
    B = b[1:] - a[1:] * b[0]
    # Solve zi = A*zi + B
    zi = np.linalg.solve(IminusA, B)

    # For future reference: we could also use the following
    # explicit formulas to solve the linear system:
    #
    # zi = np.zeros(n - 1)
    # zi[0] = B.sum() / IminusA[:,0].sum()
    # asum = 1.0
    # csum = 0.0
    # for k in range(1,n-1):
    #     asum += a[k]
    #     csum += b[k] - a[k]*b[0]
    #     zi[k] = asum*zi[0] - csum

    return zi
Exemple #18
0
 def time_companion(self, size):
     sl.companion(self.x)