Пример #1
0
Файл: main.py Проект: mrow4a/UNI
 def myzpk2tf(self, z, p, k):
         z = np.atleast_1d(z)
         k = np.atleast_1d(k)
         if len(z.shape) > 1:
                 temp = np.poly(z[0])
                 b = np.zeros((z.shape[0], z.shape[1] + 1), temp.dtype.char)
                 if len(k) == 1:
                         k = [k[0]] * z.shape[0]
                 for i in range(z.shape[0]):
                         b[i] = k[i] * poly(z[i])
         else:
                 b = k * np.poly(z)
         a = np.atleast_1d(np.poly(p))
         # Use real output if possible. Copied from numpy.poly, since
         # we can't depend on a specific version of numpy.
         if issubclass(b.dtype.type, np.complexfloating):
                 # if complex roots are all complex conjugates, the roots are real.
                 roots = np.asarray(z, complex)
                 pos_roots = np.compress(roots.imag > 0, roots)
                 neg_roots = np.conjugate(np.compress(roots.imag < 0, roots))
                 if len(pos_roots) == len(neg_roots):
                         if np.all(np.sort_complex(neg_roots) == np.sort_complex(pos_roots)):
                                 b = b.real.copy()
         if issubclass(a.dtype.type, np.complexfloating):
                 # if complex roots are all complex conjugates, the roots are real.
                 roots = np.asarray(p, complex)
                 pos_roots = np.compress(roots.imag > 0, roots)
                 neg_roots = np.conjugate(np.compress(roots.imag < 0, roots))
                 if len(pos_roots) == len(neg_roots):
                         if np.all(np.sort_complex(neg_roots) == np.sort_complex(pos_roots)):
                                 a = a.real.copy()
         return b, a
Пример #2
0
def zpk2tf(z, p, k):
    """Return polynomial transfer function representation from zeros
    and poles

    Parameters
    ----------
    z : ndarray
        Zeros of the transfer function.
    p : ndarray
        Poles of the transfer function.
    k : float
        System gain.

    Returns
    -------
    b : ndarray
        Numerator polynomial.
    a : ndarray
        Denominator polynomial.

    """
    z = atleast_1d(z)
    k = atleast_1d(k)
    if len(z.shape) > 1:
        temp = poly(z[0])
        b = zeros((z.shape[0], z.shape[1] + 1), temp.dtype.char)
        if len(k) == 1:
            k = [k[0]] * z.shape[0]
        for i in range(z.shape[0]):
            b[i] = k[i] * poly(z[i])
    else:
        b = k * poly(z)
    a = atleast_1d(poly(p))
    return b, a
Пример #3
0
def lsf2poly(lsf):
    """Convert line spectral frequencies to prediction filter coefficients

    returns a vector a containing the prediction filter coefficients from a vector lsf of line spectral frequencies.

    .. doctest::

        >>> from spectrum import lsf2poly
        >>> lsf = [0.7842 ,   1.5605  ,  1.8776 ,   1.8984,    2.3593]
        >>> a = lsf2poly(lsf)

    # array([  1.00000000e+00,   6.14837835e-01,   9.89884967e-01,
    # 9.31594056e-05,   3.13713832e-03,  -8.12002261e-03 ])

    .. seealso:: poly2lsf, rc2poly, ac2poly, rc2is
    """
    #   Reference: A.M. Kondoz, "Digital Speech: Coding for Low Bit Rate Communications
    #   Systems" John Wiley & Sons 1994 ,Chapter 4

    # Line spectral frequencies must be real.

    lsf = numpy.array(lsf)

    if max(lsf) > numpy.pi or min(lsf) < 0:
        raise ValueError('Line spectral frequencies must be between 0 and pi.')

    p = len(lsf) # model order

    # Form zeros using the LSFs and unit amplitudes
    z  = numpy.exp(1.j * lsf)

    # Separate the zeros to those belonging to P and Q
    rQ = z[0::2]
    rP = z[1::2]

    # Include the conjugates as well
    rQ = numpy.concatenate((rQ, rQ.conjugate()))
    rP = numpy.concatenate((rP, rP.conjugate()))

    # Form the polynomials P and Q, note that these should be real
    Q  = numpy.poly(rQ);
    P  = numpy.poly(rP);

    # Form the sum and difference filters by including known roots at z = 1 and
    # z = -1

    if p%2:
        # Odd order: z = +1 and z = -1 are roots of the difference filter, P1(z)
        P1 = numpy.convolve(P, [1, 0, -1])
        Q1 = Q
    else:
        # Even order: z = -1 is a root of the sum filter, Q1(z) and z = 1 is a
        # root of the difference filter, P1(z)
        P1 = numpy.convolve(P, [1, -1])
        Q1 = numpy.convolve(Q, [1,  1])

    # Prediction polynomial is formed by averaging P1 and Q1

    a = .5 * (P1+Q1)
    return a[0:-1:1] # do not return last element
Пример #4
0
def find_coeff(poles, mode="f"):
    """
    Find LP coefficients from a set of LP roots (poles).

    Parameters
    ----------
    poles : ndarray
        Array of LP roots (poles)
    mode : {'f', 'b'}
        Mode in which LP coefficients should be returned.  'f' for coefficients
        ordered m, m - 1,..., 1. 'b' for coefficients ordered 1, 2, ...., m.

    Returns
    -------
    c : ndarray
        LP coefficients ordered according to `mode`.

    """
    # STABILITY
    # the algorithm used here is numpy poly function which convolves
    # the roots to find the coefficients, the accuracy of this method
    # depends on the dtype of the poles parameter.
    if mode not in ['f', 'b']:
        raise ValueError("mode must be 'f'or 'b'")

    if mode == 'f':  # reverse resulting coefficients
        return np.squeeze(-np.poly(poles)[:0:-1])
    else:   # keep coefficients as is
        return np.squeeze(-np.poly(poles)[1:])
Пример #5
0
	def compute_filter(self):
		theta = 2 * np.pi * self.frequency / self.nyquist * 2
		zero = np.exp(np.array([1j, -1j]) * theta)
		pole = self.module_pole * zero

		self._filter_b = np.poly(zero)
		self._filter_a = np.poly(pole)
Пример #6
0
def lsf_to_lpc(all_lsf):
    if len(all_lsf.shape) < 2:
        all_lsf = all_lsf[None]
    order = all_lsf.shape[1]
    all_lpc = np.zeros((len(all_lsf), order + 1))
    for i in range(len(all_lsf)):
        lsf = all_lsf[i]
        zeros = np.exp(1j * lsf)
        sum_zeros = zeros[::2]
        diff_zeros = zeros[1::2]
        sum_zeros = np.hstack((sum_zeros, np.conj(sum_zeros)))
        diff_zeros = np.hstack((diff_zeros, np.conj(diff_zeros)))
        sum_filt = np.poly(sum_zeros)
        diff_filt = np.poly(diff_zeros)

        if order % 2 != 0:
            deconv_diff = sg.convolve(diff_filt, [1, 0, -1])
            deconv_sum = sum_filt
        else:
            deconv_diff = sg.convolve(diff_filt, [1, -1])
            deconv_sum = sg.convolve(sum_filt, [1, 1])

        lpc = .5 * (deconv_sum + deconv_diff)
        # Last coefficient is 0 and not returned
        all_lpc[i] = lpc[:-1]
    return np.squeeze(all_lpc)
Пример #7
0
def do_plot(ax, z):
    
    tt=np.linspace(0,1,100)
    yy = z[0]*(1-tt)+z[1]*(tt)
    z1=z[:5]
    z2=z[5:]
    
    P = np.poly(z1) 
    Q = np.poly(z2)
    Z0 = np.roots((P-Q)[1:])
    
    def Z(t):
        F=P*(1-t)+Q*t
        return np.roots(F)
        
    N = 100
    
    ZZ = np.zeros([5, N], np.complex)
    for i in range(N):
        ZZ[:,i]=Z(i/50.0-0.5).transpose()

    rval = []
    rval.extend( ax.plot(Z0.real, Z0.imag, "gx") )
    rval.extend( ax.plot(ZZ.real.transpose(), ZZ.imag.transpose(), "r.") )
    return rval
Пример #8
0
    def apply_to(self, array, samplerate):
        # Nyquist frequency
        nyquist = samplerate / 2.

        # ratio of notch freq. to Nyquist freq.
        freq_ratio = self.frequency / nyquist

        # width of the notch
        notchWidth = 0.01

        # Compute zeros
        zeros = np.array([np.exp(1j * np.pi * freq_ratio),
                         np.exp(-1j * np.pi * freq_ratio)])

        # Compute poles
        poles = (1 - notchWidth) * zeros

        b = np.poly(zeros)    # Get moving average filter coefficients
        a = np.poly(poles)    # Get autoregressive filter coefficients

        try:
            if array.ndim == 1:
                filtered = scipy.signal.filtfilt(b, a, array, padtype="even")
            else:
                filtered = np.empty(array.shape)
                for i in range(array.shape[1]):
                    filtered[:, i] = scipy.signal.filtfilt(
                        b, a, array[:, i], padtype="even")

            return filtered * self.gain + array * (1 - self.gain)
        except ValueError:
            print "Could not apply filter"
            return array
Пример #9
0
def test_infnorm():
	"""Test function for infnorm()"""
	# FIXME M/P test needed
	num, den = np.poly([3, 0.3, 1]), np.poly([2, 0.5, .25])
	H = (num, den)
	Hinf, fmax = infnorm(H)
	assert np.allclose((Hinf, fmax), (np.array([ 1.84888889]), np.array([ 0.50000001])), 
	                   atol=1e-8, rtol=1e-5)
Пример #10
0
 def test_impL1_num_den(self):
     """Test function for impL1() 2/4"""
     sys1 = (np.array([-.4]), np.array([0, 0]), 1) 
     num = np.poly(sys1[0])
     den = np.poly(sys1[1])
     num[0] *= sys1[2]
     tf = (num, den)
     r3 = ds.impL1(tf, n=10)
     self.assertTrue(np.allclose(self.r2, r3, atol=1e-8, rtol=1e-4))
    def impz(self, zeros, poles, L):
        from scipy.signal import lfilter

        a = np.poly(poles)
        b = np.poly(zeros)
        d = np.zeros(L)
        d[0] = 1
        h = lfilter(b, a, d)
        return h
Пример #12
0
def getTheta(ar_roots, ma_roots, sigma):
	'''Return theta for Libcarma'''
	ma_poly = sigma*np.poly(ma_roots) #TODO Change * to /
	ar_poly = np.poly(ar_roots)
	theta = np.concatenate((ar_poly[1:], ma_poly))
	p = len(ar_roots)
	q = len(ma_roots)
		
	return theta, p, q
Пример #13
0
def ss2tf(A, B, C, D, input=0):
    """State-space to transfer function.

    Parameters
    ----------
    A, B, C, D : ndarray
        State-space representation of linear system.
    input : int, optional
        For multiple-input systems, the input to use.

    Returns
    -------
    num : 2-D ndarray
        Numerator(s) of the resulting transfer function(s).  `num` has one row
        for each of the system's outputs. Each row is a sequence representation
        of the numerator polynomial.
    den : 1-D ndarray
        Denominator of the resulting transfer function(s).  `den` is a sequence
        representation of the denominator polynomial.

    """
    # transfer function is C (sI - A)**(-1) B + D
    A, B, C, D = map(asarray, (A, B, C, D))
    # Check consistency and make them all rank-2 arrays
    A, B, C, D = abcd_normalize(A, B, C, D)

    nout, nin = D.shape
    if input >= nin:
        raise ValueError("System does not have the input specified.")

    # make MOSI from possibly MOMI system.
    if B.shape[-1] != 0:
        B = B[:, input]
    B.shape = (B.shape[0], 1)
    if D.shape[-1] != 0:
        D = D[:, input]

    try:
        den = poly(A)
    except ValueError:
        den = 1

    if (product(B.shape, axis=0) == 0) and (product(C.shape, axis=0) == 0):
        num = numpy.ravel(D)
        if (product(D.shape, axis=0) == 0) and (product(A.shape, axis=0) == 0):
            den = []
        return num, den

    num_states = A.shape[0]
    type_test = A[:, 0] + B[:, 0] + C[0, :] + D
    num = numpy.zeros((nout, num_states + 1), type_test.dtype)
    for k in range(nout):
        Ck = atleast_2d(C[k, :])
        num[k] = poly(A - dot(B, Ck)) + (D[k] - 1) * den

    return num, den
Пример #14
0
def dual_band(F, P, E, eps, eps_R=1, x1=0.5, map_type=1):
    r"""
    Function to give modified F, P, and E polynomials after lowpass 
    prototype dual band transformation.
    
    :param F:       Polynomial F, i.e., numerator of S11 (in s-domain)
    :param P:       Polynomial P, i.e., numerator of S21 (in s-domain)
    :param E:       polynomial E is the denominator of S11 and S21 (in s-domain)
    :param eps:     Constant term associated with S21
    :param eps_R:   Constant term associated with S11
    :param x1:
    :param map_type:
                  
    :rtype:    
    """

    if (map_type == 1) or (map_type == 2):

        s = sp.Symbol("s")
        if map_type == 1:
            a = -2j / (1 - x1 ** 2)
            b = -1j * (1 + x1 ** 2) / (1 - x1 ** 2)
        elif map_type == 2:
            a = 2j / (1 - x1 ** 2)
            b = 1j * (1 + x1 ** 2) / (1 - x1 ** 2)
        s1 = a * s ** 2 + b

        F = sp.Poly(F.ravel().tolist(), s)
        F1 = sp.simplify(F.subs(s, s1))
        F1 = sp.Poly(F1, s).all_coeffs()
        F1 = I_to_i(F1)

        E = sp.Poly(E.ravel().tolist(), s)
        E1 = sp.simplify(E.subs(s, s1))
        E1 = sp.Poly(E1, s).all_coeffs()
        E1 = I_to_i(E1)

        P = sp.Poly(P.ravel().tolist(), s)
        P1 = sp.simplify(P.subs(s, s1))
        P1 = sp.Poly(P1, s).all_coeffs()
        P1 = I_to_i(P1)

    elif map_type == 3:

        F_roots = np.roots(F.ravel().tolist())
        P_roots = np.roots(P.ravel().tolist())
        F1_roots = Lee_roots_map(F_roots, x1)
        P1_roots = Lee_roots_map(P_roots, x1)
        P1_roots = np.concatenate((P1_roots, np.array([0, 0])))
        F1 = np.poly(F1_roots)
        P1 = np.poly(P1_roots)
        F1 = np.reshape(F1, (len(F1), -1))
        P1 = np.reshape(P1, (len(P1), -1))
        E1 = poly_E(eps, eps_R, F1, P1)[0]

    return F1, P1, E1
Пример #15
0
 def solve(self):
     if len(self.pole) == 0:
         self.a = np.ones((1))
     else:
         self.a = np.poly(self.pole)
     if len(self.zero) == 0:
         self.b = np.ones((1))
     else:
         self.b = np.poly(self.zero)
     self.solved = True
Пример #16
0
    def init(self, freq=50.0, mod=0.9):
        theta = 2 * np.pi * 50 / self.input.sample_rate
        zero = np.exp(np.array([1j, -1j]) * theta)
        pole = mod * zero

        a, b = np.poly(pole), np.poly(zero)
        #notch_ab = numpy.poly(zero), numpy.poly(pole)
        #notch_ab = scipy.signal.iirfilter(32, [30.0 / 125], btype='low')

        self.gr_block = filter.iir_filter_ffd(b, a, oldstyle=False)
Пример #17
0
def z_coeff(Poles,Zeros,fs,g,fg,fo = 'none'):
    if fg == np.inf:
        fg = fs/2
    if fo == 'none':
        beta = 1.0
    else:
        beta = f_warp(fo,fs)/fo
    a = np.poly(z_from_f(beta*np.array(Poles),fs))
    b = np.poly(z_from_f(beta*np.array(Zeros),fs))
    gain = 10.**(g/20.)/abs(Fz_at_f(beta*np.array(Poles),beta*np.array(Zeros),fg,fs))
    
    return (a,b*gain)
Пример #18
0
def invresz(r, p, k, tol=1e-3, rtype='avg'):
    """Compute b(z) and a(z) from partial fraction expansion: r,p,k

    If M = len(b) and N = len(a)

            b(z)     b[0] + b[1] z**(-1) + ... + b[M-1] z**(-M+1)
    H(z) = ------ = ----------------------------------------------
            a(z)     a[0] + a[1] z**(-1) + ... + a[N-1] z**(-N+1)

                 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

    See also
    --------
    residuez, poly, polyval, unique_roots

    """
    extra = asarray(k)
    p, indx = cmplx_sort(p)
    r = take(r, indx, 0)
    pout, mult = unique_roots(p, tol=tol, rtype=rtype)
    p = []
    for k in range(len(pout)):
        p.extend([pout[k]] * mult[k])
    a = atleast_1d(poly(p))
    if len(extra) > 0:
        b = polymul(extra, a)
    else:
        b = [0]
    indx = 0
    brev = asarray(b)[::-1]
    for k in range(len(pout)):
        temp = []
        # Construct polynomial which does not include any of this root
        for l in range(len(pout)):
            if l != k:
                temp.extend([pout[l]] * mult[l])
        for m in range(mult[k]):
            t2 = temp[:]
            t2.extend([pout[k]] * (mult[k] - m - 1))
            brev = polyadd(brev, (r[indx] * poly(t2))[::-1])
            indx += 1
    b = real_if_close(brev[::-1])
    return b, a
Пример #19
0
def invres(r,p,k,tol=1e-3,rtype='avg'):
    """Compute b(s) and a(s) from partial fraction expansion: r,p,k

    If M = len(b) and N = len(a)

            b(s)     b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1]
    H(s) = ------ = ----------------------------------------------
            a(s)     a[0] x**(N-1) + a[1] x**(N-2) + ... + a[N-1]

             r[0]       r[1]             r[-1]
         = -------- + -------- + ... + --------- + k(s)
           (s-p[0])   (s-p[1])         (s-p[-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]
          -------- + ----------- + ... + -----------
          (s-p[i])  (s-p[i])**2          (s-p[i])**n

    See Also
    --------
    residue, poly, polyval, unique_roots

    """
    extra = k
    p, indx = cmplx_sort(p)
    r = take(r,indx,0)
    pout, mult = unique_roots(p,tol=tol,rtype=rtype)
    p = []
    for k in range(len(pout)):
        p.extend([pout[k]]*mult[k])
    a = atleast_1d(poly(p))
    if len(extra) > 0:
        b = polymul(extra,a)
    else:
        b = [0]
    indx = 0
    for k in range(len(pout)):
        temp = []
        for l in range(len(pout)):
            if l != k:
                temp.extend([pout[l]]*mult[l])
        for m in range(mult[k]):
            t2 = temp[:]
            t2.extend([pout[k]]*(mult[k]-m-1))
            b = polyadd(b,r[indx]*poly(t2))
            indx += 1
    b = real_if_close(b)
    while allclose(b[0], 0, rtol=1e-14) and (b.shape[-1] > 1):
        b = b[1:]
    return b, a
Пример #20
0
def zp_expr(s,Z,P):
    pZ = np.poly(Z)
    pP = np.poly(P)

    a = np.polyval(pZ, s)
    b = np.polyval(pP, s)

    print "zp_expr"

    print "  a",a
    print "  b",b

    return a / b
 def test_objects(self):
     from decimal import Decimal
     p = np.poly1d([Decimal('4.0'), Decimal('3.0'), Decimal('2.0')])
     p2 = p * Decimal('1.333333333333333')
     assert_(p2[1] == Decimal("3.9999999999999990"))
     p2 = p.deriv()
     assert_(p2[1] == Decimal('8.0'))
     p2 = p.integ()
     assert_(p2[3] == Decimal("1.333333333333333333333333333"))
     assert_(p2[2] == Decimal('1.5'))
     assert_(np.issubdtype(p2.coeffs.dtype, np.object_))
     p = np.poly([Decimal(1), Decimal(2)])
     assert_equal(np.poly([Decimal(1), Decimal(2)]),
                  [1, Decimal(-3), Decimal(2)])
Пример #22
0
    def zero(self):
        """Compute the zeros of a state space system."""

        if self.inputs > 1 or self.outputs > 1:
            raise NotImplementedError("StateSpace.zeros is currently \
implemented only for SISO systems.")

        den = poly1d(poly(self.A))
        # Compute the numerator based on zeros
        #! TODO: This is currently limited to SISO systems
        num = poly1d(poly(self.A - dot(self.B, self.C)) + ((self.D[0, 0] - 1) *
            den))

        return roots(num)
Пример #23
0
def build_TF(poles=[], zeros=[]):
    """Build a TF whose poles and zeros are given.  Complex poles or zeros
    are created by passing (wn,z) as a tuple in the pole or zero list."""
    if np.isscalar(poles):
        poles = [poles]
    if np.isscalar(zeros):
        zeros = [zeros]
        
    all_poles = _unpack_complex(poles)
    all_zeros = _unpack_complex(zeros)
    num = np.poly(all_zeros)
    den = np.poly(all_poles)
    G = TF(num,den)
    return G
Пример #24
0
 def test_sacpaz_from_resp(self):
     # The following two files were both extracted from a dataless
     # seed file using rdseed
     respfile = os.path.join(os.path.dirname(__file__),
                             'data', 'RESP.NZ.CRLZ.10.HHZ')
     sacpzfile = os.path.join(os.path.dirname(__file__),
                              'data', 'SAC_PZs_NZ_CRLZ_HHZ')
     # This is a rather lengthy test, in which the
     # poles, zeros and the gain of each instrument response file
     # are converted into the corresponding velocity frequency response
     # function which have to be sufficiently close. Possibly due to
     # different truncations in the RESP-formatted and SAC-formatted
     # response files the frequency response functions are not identical.
     tr1 = Trace()
     tr2 = Trace()
     attach_resp(tr1, respfile, torad=True, todisp=False)
     attach_paz(tr2, sacpzfile, torad=False, tovel=True)
     p1 = tr1.stats.paz.poles
     z1 = tr1.stats.paz.zeros
     g1 = tr1.stats.paz.gain
     t_samp = 0.01
     n = 32768
     fy = 1 / (t_samp * 2.0)
     # start at zero to get zero for offset/ DC of fft
     f = np.arange(0, fy + fy / n, fy / n)  # arange should includes fy
     w = f * 2 * np.pi
     s = 1j * w
     a1 = np.poly(p1)
     b1 = g1 * np.poly(z1)
     h1 = np.polyval(b1, s) / np.polyval(a1, s)
     h1 = np.conj(h1)
     h1[-1] = h1[-1].real + 0.0j
     p2 = tr2.stats.paz.poles
     z2 = tr2.stats.paz.zeros
     g2 = tr2.stats.paz.gain
     a2 = np.poly(p2)
     b2 = g2 * np.poly(z2)
     h2 = np.polyval(b2, s) / np.polyval(a2, s)
     h2 = np.conj(h2)
     h2[-1] = h2[-1].real + 0.0j
     amp1 = abs(h1)
     amp2 = abs(h2)
     phase1 = np.unwrap(np.arctan2(-h1.imag, h1.real))
     phase2 = np.unwrap(np.arctan2(-h2.imag, h2.real))
     np.testing.assert_almost_equal(phase1, phase2, decimal=4)
     rms = np.sqrt(np.sum((amp1 - amp2) ** 2) /
                   np.sum(amp2 ** 2))
     self.assertTrue(rms < 2.02e-06)
     self.assertTrue(tr1.stats.paz.t_shift, 0.4022344)
Пример #25
0
def lsf2poly(L):
    order = len(L)
    Q = L[::2]
    P = L[1::2]
    poles_P = np.r_[np.exp(1j * P), np.exp(-1j * P)]
    poles_Q = np.r_[np.exp(1j * Q), np.exp(-1j * Q)]

    P = np.poly(poles_P)
    Q = np.poly(poles_Q)

    P = convolve(P, np.array([1.0, -1.0]))
    Q = convolve(Q, np.array([1.0, 1.0]))

    a = 0.5 * (P + Q)
    return a[:-1]
Пример #26
0
    def test_simple(self):
        z_r = np.array([0.5, -0.5])
        p_r = np.array([1.j / np.sqrt(2), -1.j / np.sqrt(2)])
        # Sort the zeros/poles so that we don't fail the test if the order
        # changes
        z_r.sort()
        p_r.sort()
        b = np.poly(z_r)
        a = np.poly(p_r)

        z, p, k = tf2zpk(b, a)
        z.sort()
        p.sort()
        assert_array_almost_equal(z, z_r)
        assert_array_almost_equal(p, p_r)
    def setup_main_screen(self):

        import matplotlib.gridspec as gridspec

        # Poles & zeros
        self.fig = plt.figure()
        gs = gridspec.GridSpec(3, 12)
        # self.ax = self.fig.add_axes([0.1, 0.1, 0.77, 0.77], polar=True, axisbg='#d5de9c')
        # self.ax=self.fig.add_subplot(221,polar=True, axisbg='#d5de9c')
        self.ax = plt.subplot(gs[0:, 0:6], polar=True, axisbg="#d5de9c")
        # self.ax = self.fig.add_subplot(111, polar=True)
        self.fig.suptitle(
            "Poles & zeros adjustment", fontsize=18, color="blue", x=0.1, y=0.98, horizontalalignment="left"
        )
        # self.ax.set_title('Poles & zeros adjustment',fontsize=16, color='blue')
        self.ax.set_ylim([0, self.ymax])
        self.poles_line, = self.ax.plot(self.poles_th, self.poles_r, "ob", ms=9, picker=5, label="Poles")
        self.zeros_line, = self.ax.plot(self.zeros_th, self.zeros_r, "Dr", ms=9, picker=5, label="Zeros")
        self.ax.plot(np.linspace(-np.pi, np.pi, 500), np.ones(500), "--b", lw=1)
        self.ax.legend(loc=1)

        # Transfer function
        # self.figTF, self.axTF = plt.subplots(2, sharex=True)
        # self.axTF0=self.fig.add_subplot(222,axisbg='LightYellow')
        self.axTF0 = plt.subplot(gs[0, 6:11], axisbg="LightYellow")
        # self.axTF[0].set_axis_bgcolor('LightYellow')
        self.axTF0.set_title("Transfer function (modulus)")
        # self.axTF1=self.fig.add_subplot(224,axisbg='LightYellow')
        self.axTF1 = plt.subplot(gs[1, 6:11], axisbg="LightYellow")
        self.axTF1.set_title("Transfer function (phase)")
        self.axTF1.set_xlabel("Frequency")
        f = np.linspace(0, 1, self.N)
        self.TF = np.fft.fft(np.poly(self.zeros), self.N) / np.fft.fft(np.poly(self.poles), self.N)
        self.TF_m_line, = self.axTF0.plot(f, np.abs(self.TF))
        self.TF_p_line, = self.axTF1.plot(f, 180 / np.pi * np.angle(self.TF))
        # self.figTF.canvas.draw()

        # Impulse response
        # self.figIR = plt.figure()
        # self.axIR = self.fig.add_subplot(223,axisbg='Lavender')
        self.axIR = plt.subplot(gs[2, 6:11], axisbg="Lavender")
        self.IR = self.impz(self.zeros, self.poles, self.Nir)  # np.real(np.fft.ifft(self.TF))
        self.axIR.set_title("Impulse response")
        self.axIR.set_xlabel("Time")
        self.IR_m_line, = self.axIR.plot(self.IR)
        # self.figIR.canvas.draw()
        self.fig.canvas.draw()
        self.fig.tight_layout()
def design_allpole(pole_mags, pole_freqs, fs):
    poles = []
    for n in range(len(pole_mags)):
        w_p = pole_freqs[n] / fs * (2 * np.pi)
        poles.append(pole_mags[n] * np.exp(1j * w_p))
    a = np.poly(np.asarray(poles))
    return np.array([1]), a
Пример #29
0
def reachable_form(xsys):
    # Check to make sure we have a SISO system
    if not issiso(xsys):
        raise ControlNotImplemented(
            "Canonical forms for MIMO systems not yet supported")

    # Create a new system, starting with a copy of the old one
    zsys = StateSpace(xsys)

    # Generate the system matrices for the desired canonical form
    zsys.B = zeros(shape(xsys.B))
    zsys.B[0, 0] = 1
    zsys.A = zeros(shape(xsys.A))
    Apoly = poly(xsys.A)  # characteristic polynomial
    for i in range(0, xsys.states):
        zsys.A[0, i] = -Apoly[i + 1] / Apoly[0]
        if (i + 1 < xsys.states):
            zsys.A[i + 1, i] = 1

    # Compute the reachability matrices for each set of states
    Wrx = ctrb(xsys.A, xsys.B)
    Wrz = ctrb(zsys.A, zsys.B)

    # Transformation from one form to another
    Tzx = Wrz * inv(Wrx)

    # Finally, compute the output matrix
    zsys.C = xsys.C * inv(Tzx)

    return zsys, Tzx
Пример #30
0
def function_transfere(aircraft, point_trim):

    alt, Ma, sm, km = point_trim
    aircraft.set_mass_and_static_margin(km, sm)
    va = dyn.va_of_mach(Ma, alt)
    xtrim, utrim = dyn.trim(aircraft, {'va': va, 'gamm': 0, 'h': alt})
    A, B = utils.num_jacobian(xtrim, utrim, aircraft, dyn.dyn)
    A_4, B_4 = A[2:,2:], B[2:,:2][:,0].reshape((4,1))
    C_4 = np.zeros((1,4))
    C_4[0][2] = 1
    Acc_4 = np.zeros((4, 4))
    Bcc_4 = np.zeros((4, 1))
    Bcc_4[3,0] = 1
    valeursp, M = np.linalg.eig(A_4)
    coeff = np.poly(valeursp)
    for i in range(3):
        Acc_4[i,i+1] = 1
        Acc_4[3,3-i] = -coeff[i+1]
    Acc_4[3,0] = -coeff[4]
    Qccc = np.zeros((4, 4))
    Q = np.zeros((4, 4))
    for i in range(4):
        Qccc[:,i:i+1] = np.dot(np.linalg.matrix_power(Acc_4, i), Bcc_4)
        Q[:,i:i+1] = np.dot(np.linalg.matrix_power(A_4, i), B_4)
    Mcc = np.dot(Q, np.linalg.inv(Qccc))
    Ccc_4 = np.dot(C_4, Mcc)
    num = list(Ccc_4)
    num.reverse()
    den = list(-Acc_4[3, :])
    den.append(1.)
    den.reverse()
    return num, den, valeursp
Пример #31
0
    def sample_data(self, rate, AR = 1):
        '''
        Generate simulated data with default class params. Feel free to change if needed. Can be AR1 or AR2
        '''

        if np.shape(rate)[-1] != self.Tps:
            raise ValueError("rate should be the same length as T in the calcium class, got {0}".format(np.shape(data)[-1]))


        spikes = onp.random.poisson(rate)


        roots = onp.exp(-self.dt/np.array(self.AR_params)) ### here self.AR_params is an n-length vector where n is the AR process order
        coeffs = onp.poly(roots) #find coefficients with of a polynomial with roots of params
        z = lfilter([self.alpha],coeffs,spikes) #generate AR-n process with inputs spk_counts, where self.alpha is the CA increase due to a spike


        # q = [exp(-self.dt/tau_samp),exp(-self.dt/tau_samp_b)]
        # a_true = onp.poly(q)
        # z = filter(1,a_true,spcounts);
        # ##### To Do: AR2 PROCESS HERE!

        trace = z + onp.sqrt(self.Gauss_sigma)*onp.random.randn(onp.size(z))#add noise

        return trace, spikes
Пример #32
0
 def principal_invariants(self):
     """
     Returns a list of principal invariants for the tensor,
     which are the values of the coefficients of the characteristic
     polynomial for the matrix
     """
     return np.poly(self)[1:] * np.array([-1, 1, -1])
Пример #33
0
def reachable_form(xsys):
    # Check to make sure we have a SISO system
    if not control.issiso(xsys): 
        raise control.ControlNotImplemented(
            "Canonical forms for MIMO systems not yet supported")

    # Create a new system, starting with a copy of the old one
    zsys = control.StateSpace(xsys)

    # Generate the system matrices for the desired canonical form
    zsys.B = zeros(shape(xsys.B)); zsys.B[0, 0] = 1;
    zsys.A = zeros(shape(xsys.A))
    Apoly = poly(xsys.A)                # characteristic polynomial
    for i in range(0, xsys.states):
        zsys.A[0, i] = -Apoly[i+1] / Apoly[0]
        if (i+1 < xsys.states): zsys.A[i+1, i] = 1
    
    # Compute the reachability matrices for each set of states
    Wrx = control.ctrb(xsys.A, xsys.B)
    Wrz = control.ctrb(zsys.A, zsys.B)

    # Transformation from one form to another
    Tzx = Wrz * inv(Wrx)

    # Finally, compute the output matrix
    zsys.C = xsys.C * inv(Tzx)

    return zsys, Tzx
Пример #34
0
 def principal_invariants(self):
     """
     Returns a list of principal invariants for the tensor,
     which are the values of the coefficients of the characteristic
     polynomial for the matrix
     """
     return np.poly(self)[1:] * np.array([-1, 1, -1])
Пример #35
0
def Filter(N, fc, fs):
    N = float(N)
    #Nth order butterworth filter
    fc = float(fc)
    #cutoff frequency
    fs = float(fs)
    #sampling frequency
    wc = float(2 * math.pi * fc / fs)
    T = 1 / fs
    omega_c = (2 / T) * math.tan(wc / 2)
    omega_c = 2 * math.pi * fc
    s_k = [
        omega_c *
        cmath.exp(cmath.sqrt(-1) * math.pi * (N + 2 * k - 1) / (2 * N))
        for k in range(1,
                       int(N) + 1)
    ]
    s_k_poly = np.poly(s_k)
    [a_k, p, s] = scipy.signal.residue(math.pow(omega_c, N), s_k_poly)
    return [
        sum([
            T * a_k[k] /
            (1 - cmath.exp(p[k] * T) * cmath.exp(-1 * cmath.sqrt(-1) * W[w]))
            for k in range(0, int(N))
        ]) for w in range(0, len(W))
    ]
Пример #36
0
Файл: ar.py Проект: idiap/ssp
def ARHarmonicPoly(f0, rate, mag=0.99):
    """
    Generates coefficients of an AR polynomial corresponding to a
    harmonic excitation at frequency f0
    """
    omega = float(f0)/rate * 2.0 * np.pi
    n = int(np.pi / omega)
    roots = np.ndarray((n*2), dtype='complex')
    for i in range(n):
        a = omega * (i+1)
        c = mag*np.cos(a)
        s = mag*np.sin(a)
        roots[i*2] = complex(c, s)
        roots[i*2+1] = complex(c, -s)

    if True:
        poly = np.poly(roots)[1:]
    else:
        # polyfromroots() returns the trailing coeff = 1, so just
        # knock off that one and reverse the rest as we have negative
        # powers.
        poly = pn.polyfromroots(roots).real[-2::-1]
    if np.max(np.abs(poly)) >= 1.0:
        print(roots, np.prod(roots), poly)
        raise OverflowError('Poly too big')
    return -poly
Пример #37
0
 def transfunc(self, polos, **kwargs):
     wp = kwargs.get('wp', 0)
     w0 = kwargs.get('w0', 0)
     Bw = kwargs.get('bw', self.Bp)
     ordem = kwargs.get('ord', self.ordem())
     resp = kwargs.get('response', self.tipo)
     G_db = kwargs.get('G', self.G_bp)
     fcn = 0
     if resp == 'lp':
         self.den_norm = np.real(np.poly(polos))
         denm = np.zeros(len(self.den_norm))
         for i in range(0, len(polos) + 1):
             denm[i] = self.den_norm[i] * np.power(wp, i)
         if (ordem % 2 == 0):
             num = denm[-1] * (1 / np.sqrt(1 + np.power(self.eps, 2)))
         else:
             num = denm[-1]
         fcn = signal.TransferFunction(pow(10, -G_db / 20.0) * num, denm)
     if resp == 'hp':
         self.den_norm = np.real(np.poly(polos))
         denm = np.zeros(len(polos) + 1)
         for i in range(0, len(polos) + 1):
             denm[i] = self.den_norm[len(polos) - i] * np.power(wp, i)
         num = np.zeros(len(polos) + 1)
         if (self.ordem() % 2 == 0):
             num[0] = denm[0] * (1 / np.sqrt(1 + np.power(self.eps, 2)))
         else:
             num[0] = denm[0]
         fcn = signal.TransferFunction(pow(10, -G_db / 20.0) * num, denm)
     if (resp == 'bp'):
         self.den_norm = np.real(np.poly(polos))
         [num, den] = signal.lp2bp(self.den_norm[-1], self.den_norm, w0, Bw)
         if (self.ordem() % 2 == 0):
             num[0] = num[0] * (1 / np.sqrt(1 + np.power(self.eps, 2)))
         else:
             num[0] = num[0]
         fcn = signal.TransferFunction(num, den)
     if (resp == 'bs'):
         self.den_norm = np.real(np.poly(polos))
         [num, den] = signal.lp2bs(self.den_norm[-1], self.den_norm, w0, Bw)
         if (self.ordem() % 2 == 0):
             num = num[::] * (1 / np.sqrt(1 + np.power(self.eps, 2)))
         else:
             num[-1] = num[-1]
         fcn = signal.TransferFunction(num, den)
     self.fcn = fcn
     return fcn
Пример #38
0
def ss2tf(A, B, C, D, input=0):
    """State-space to transfer function.

    Inputs:

      A, B, C, D -- state-space representation of linear system.
      input -- For multiple-input systems, the input to use.

    Outputs:

      num, den -- Numerator and denominator polynomials (as sequences)
                  respectively.
    """
    # transfer function is C (sI - A)**(-1) B + D
    A, B, C, D = map(asarray, (A, B, C, D))
    # Check consistency and
    #     make them all rank-2 arrays
    A, B, C, D = abcd_normalize(A, B, C, D)

    nout, nin = D.shape
    if input >= nin:
        raise ValueError, "System does not have the input specified."

    # make MOSI from possibly MOMI system.
    if B.shape[-1] != 0:
        B = B[:,input]
    B.shape = (B.shape[0],1)
    if D.shape[-1] != 0:
        D = D[:,input]

    den = poly(A)

    if (product(B.shape,axis=0) == 0) and (product(C.shape,axis=0) == 0):
        num = numpy.ravel(D)
        if (product(D.shape,axis=0) == 0) and (product(A.shape,axis=0) == 0):
            den = []
        end
        return num, den

    num_states = A.shape[0]
    type_test = A[:,0] + B[:,0] + C[0,:] + D
    num = numpy.zeros((nout, num_states+1), type_test.dtype)
    for k in range(nout):
        Ck = atleast_2d(C[k,:])
        num[k] = poly(A - dot(B,Ck)) + (D[k]-1)*den

    return num, den
def estimate_time_constant(y, p=2, sn=None, lags=10, fudge_factor=1., nonlinear_fit=False):
    """
    Estimate AR model parameters through the autocovariance function

    Parameters
    ----------
    y : array, shape (T,)
        One dimensional array containing the fluorescence intensities with
        one entry per time-bin.
    p : positive integer
        order of AR system
    sn : float
        sn standard deviation, estimated if not provided.
    lags : positive integer
        number of additional lags where he autocovariance is computed
    fudge_factor : float (0< fudge_factor <= 1)
        shrinkage factor to reduce bias

    Returns
    -------
    g : estimated coefficients of the AR process
    """

    if sn is None:
        sn = GetSn(y)

    lags += p
    # xc = axcov(y, lags)[lags:]
    y = y - y.mean()
    xc = np.array([y[i:].dot(y[:-i if i else None]) for i in range(1 + lags)]) / len(y)

    if nonlinear_fit and p <= 2:
        xc[0] -= sn**2
        g1 = xc[:-1].dot(xc[1:]) / xc[:-1].dot(xc[:-1])
        if p == 1:
            def func(x, a, g):
                return a * g**x
            popt, pcov = curve_fit(func, list(range(len(xc))), xc, (xc[0], g1)) #, bounds=(0, [3 * xc[0], 1]))
            return popt[1:2] * fudge_factor
        elif p == 2:
            def func(x, a, d, r):
                return a * (d**(x + 1) - r**(x + 1) / (1 - r**2) * (1 - d**2))
            popt, pcov = curve_fit(func, list(range(len(xc))), xc, (xc[0], g1, .1))
            d, r = popt[1:]
            d *= fudge_factor
            return np.array([d + r, -d * r])

    xc = xc[:, np.newaxis]
    A = scipy.linalg.toeplitz(xc[np.arange(lags)],
                              xc[np.arange(p)]) - sn**2 * np.eye(lags, p)
    g = np.linalg.lstsq(A, xc[1:], rcond=None)[0]
    gr = np.roots(np.concatenate([np.array([1]), -g.flatten()]))
    gr = (gr + gr.conjugate()) / 2.
    gr[gr > 1] = 0.95 + np.random.normal(0, 0.01, np.sum(gr > 1))
    gr[gr < 0] = 0.15 + np.random.normal(0, 0.01, np.sum(gr < 0))
    g = np.poly(fudge_factor * gr)
    g = -g[1:]

    return g.flatten()
Пример #40
0
def test_minimal_realization_Transfer():
    G = Transfer(
        [1., -8., 28., -58., 67., -30.],
        poly([1, 2, 3., 2, 3., 4, 1 + (2 + 1e-6) * 1j, 1 - (2 + 1e-6) * 1j]))
    H_f = minimal_realization(G)
    assert_almost_equal(H_f.num, array([[1]]))
    H_nf = minimal_realization(G, tol=1e-7)
    assert_almost_equal(H_nf.num, array([[1., -7., 21., -37., 30.]]))
Пример #41
0
def main():
    plotdistinct = []
    plotest = []
    for i in range (12,30):
        Nsamples = 2**i
        polys = []
        for count in range (1, Nsamples):
            Clinks = np.zeros( (4*n, 4*n) )
            for i in range(0,n):
                jlist = []
                for k in range(0, n):
                    o = random.randrange(n + 1, 3*n, 1)
                    jlist.append(o)
                for j in range(1,len(jlist)):
                    Clinks[i][jlist[j]] = 1

            for i in range(3*n, 4*n):
                klist = []
                for k in range(0, n):
                    o = random.randrange(n + 1, 3*n, 1)
                    klist.append(o)
                for j in range(1,len(jlist)):
                    Clinks[klist[j]][i] = 1

            Csparse = Clinks
            for i in range(0,n):
                for j in range(3*n + 1, 4*n):
                    Npaths = 0
                    for k in range (n+1, 3*n):
                        Npaths = Npaths + Csparse[i][k]*Csparse[k][j]
                    if(Npaths > 0):
                        Clinks[i][j] = 1

            Csparse = Clinks
            SAC = Csparse + np.transpose(Csparse)
            ASAC = Csparse - np.transpose(Csparse)
            comm = np.subtract(np.matmul(SAC, ASAC).shape, np.matmul(ASAC, SAC).shape)
            a = np.matmul(SAC, ASAC).shape
            b = np.matmul(ASAC, SAC).shape
            comm = np.subtract(a,b)
            polys.append(np.concatenate(((np.poly(SAC)), (np.poly(ASAC)), (np.poly(comm))), axis=None))


        counter = tally(polys)
        distinct = len(counter) + 1
        print(Nsamples, " ", distinct)
def my_K(omega, xi=0.8):
    omega_d = omega * math.sqrt(1 - xi ** 2)
    p1 = complex(-omega * xi, omega_d)
    p2 = complex(-omega * xi, -omega_d)
    p3 = -1.5 * omega
    poles = [p1, p2, p3]
    coefs = -np.poly(poles)[::-1]
    return np.real(coefs[:-1])
Пример #43
0
def polybyrow(R):
    """ Calculate the polynomial coefficients for rows of roots in R
    """
    nr, nc = np.shape(R)
    A = np.zeros((nr, nc+1))
    for i in range(nr):
        A[i,] = np.real(np.poly(R[i,]))
    return A
Пример #44
0
def nu(z1, z0, b, beta, s):
    nu0 = ((b - z0) ** (1 - beta) - (b - z1) ** (1 - beta)) / (1 - beta)
    nu = [nu0]
    for i in range(1, s + 1):
        c = (-1) ** i * np.poly([b] * i )[::-1]
        nu_i = - sum([c[j] * ((b - z1) ** (j + 1 - beta) - (b - z0) ** (j + 1 - beta)) / (j + 1 - beta) for j in range(0, i + 1)])
        nu.append(nu_i)
    return nu
Пример #45
0
def mu(z1, z0, a, alpha, s):
    mu0 = ((z1 - a) ** (1 - alpha) - (z0 - a) ** (1 - alpha)) / (1 - alpha)
    mu = [mu0]
    for i in range(1, s + 1):
        c = np.poly([-a] * i)[::-1]
        mu_i = sum([c[j] * ((z1 - a) ** (j + 1 - alpha) - (z0 - a) ** (j + 1 - alpha)) / (j + 1 - alpha) for j in range(0, i + 1)])
        mu.append(mu_i)
    return mu
Пример #46
0
def lagrange(nodes):
    result = Polynomial([0])
    w = Polynomial(np.poly(nodes)[::-1])
    deriv = w.deriv(1)
    for i in range(len(nodes)):
        result = pl.polyadd(result,
                            make_l_k(i, nodes, w, deriv) * f(nodes[i]))[0]
    return result
Пример #47
0
 def test_polystab(self):
     # test case
     x = [1, -2, -3]
     v = np.roots(x)
     vs = 0.5 * (np.sign(np.abs(v) - 1) + 1)
     v = (1 - vs) * v + vs / np.conj(v)
     b = x[0] * np.poly(v)
     self.assertTrue(np.all(IIRDesign.polystab(self.a) == b))
Пример #48
0
def mls_polynomial_coefficients(rho, degree):
    """Determine the coefficients for a MLS polynomial smoother

    Parameters
    ----------
    rho : {float}
        Spectral radius of the matrix in question
    degree : {int}
        Degree of polynomial coefficients to generate

    Returns
    -------
    Tuple of arrays (coeffs,roots) containing the
    coefficients for the (symmetric) polynomial smoother and
    the roots of polynomial prolongation smoother.

    The coefficients of the polynomial are in descending order

    References
    ----------
    .. [1] Parallel multigrid smoothing: polynomial versus Gauss--Seidel
       M. F. Adams, M. Brezina, J. J. Hu, and R. S. Tuminaro
       J. Comp. Phys., 188 (2003), pp. 593--610

    Examples
    --------
    >>> from pyamg.relaxation.chebyshev import mls_polynomial_coefficients
    >>> mls = mls_polynomial_coefficients(2.0, 2)
    >>> print mls[0] # coefficients
    [   6.4  -48.   144.  -220.   180.   -75.8   14.5]
    >>> print mls[1] # roots
    [ 1.4472136  0.5527864]
    """

    # std_roots = np.cos(np.pi * (np.arange(degree) + 0.5)/ degree)
    # print std_roots

    roots = rho / 2.0 * (1.0 -
                         np.cos(2 * np.pi *
                                (np.arange(degree, dtype='float64') + 1) /
                                (2.0 * degree + 1.0)))
    # print roots
    roots = 1.0 / roots

    # S_coeffs = list(-np.poly(roots)[1:][::-1])

    S = np.poly(roots)[::-1]  # monomial coefficients of S error propagator

    SSA_max = rho / (
        (2.0 * degree + 1.0)**2)  # upper bound spectral radius of S^2A
    S_hat = np.polymul(S, S)  # monomial coefficients of \hat{S} propagator
    S_hat = np.hstack(((-1.0 / SSA_max) * S_hat, [1]))

    # coeff for combined error propagator \hat{S}S
    coeffs = np.polymul(S_hat, S)
    coeffs = -coeffs[:-1]  # coeff for smoother

    return (coeffs, roots)
Пример #49
0
def ratspec_to_ss(A, B, controllable=True):
    q = A(0) / B(0)

    LA = A.c / (np.power(1j, np.arange(len(A.c) - 1, -1, -1)))
    LB = B.c / (np.power(1j, np.arange(len(B.c) - 1, -1, -1)))

    #only take real coefficient from denumerator
    LA = np.poly1d(LA.real)
    LB = np.poly1d(LB.real)

    #strangely np.roots seems flipped between real and imag
    ra = LA.roots[LA.roots < 0]
    rb = LB.roots[LB.roots < 0]

    GA = np.poly(ra)
    GB = np.poly(rb)

    GA = np.poly1d(GA.real)
    GB = np.poly1d(GB.real)

    GA.c /= GA.c[-1]
    GB.c /= GB.c[-1]

    GA.c /= GB.c[0]
    GB.c /= GB.c[0]

    F = np.zeros((len(GB.c) - 1, len(GB.c) - 1), dtype=np.float64)
    L = np.zeros((len(GB.c) - 1, 1), dtype=np.float64)
    H = np.zeros((1, len(GB.c) - 1), dtype=np.float64)
    if controllable:

        F[-1, :] = -GB.c[-1:0:-1]
        F[:-1, 1:] = np.eye(len(GB.c) - 2)
        L[-1, 0] = 1
        H[0, :len(GA.c)] = GA.c[-1::-1]

    else:

        F[:, -1] = -GB.c[-1:0:-1]
        F[1:, :-1] = np.eye(len(GB.c) - 2)
        L[:len(GA.c), 0] = GA.c[-1::-1]
        H[0, -1] = 1

    Pinf = sla.solve_lyapunov(F, -q * L @ L.T)
    return F, L, q, H, Pinf
Пример #50
0
def _matched(sys_: TransferFunction,
             sample_time: numbers.Real) -> Tuple[np.ndarray, ...]:
    poles = sys_.pole()
    zeros = sys_.zero()
    num = np.poly(np.exp(zeros * sample_time))
    den = np.poly(np.exp(poles * sample_time))
    num = np.atleast_1d(num)
    den = np.atleast_1d(den)
    root_number_delta = np.roots(den).shape[0] - np.roots(num).shape[0]
    while root_number_delta > 0:
        num = np.polymul(num, np.array([1, 1]))
        root_number_delta -= 1
    nump = np.poly1d(num)
    denp = np.poly1d(den)
    ds = np.polyval(sys_.num, 0) / np.polyval(sys_.den, 0)
    d1z = nump(1) / denp(1)
    dz_gain = ds / d1z
    return num * dz_gain, den
Пример #51
0
def lagrange(x):
    n = len(x)
    L = np.zeros((n, n))
    for i in range(n):
        y = np.delete(x, i)
        polinomio = np.poly(y)
        denominador = np.polyval(polinomio, x[i])
        L[i] = polinomio / denominador
    return L
Пример #52
0
def polyscale(a):
    # we need to ensure that the roots of our filter have unit norm before computing z       
    # this ensures that the ratio of the input and output spectrum is a constant function
    for i in range(a.shape[1]):
        a[:, i] = np.flipud(a[:, i])
        roots = np.roots(a[:, i])
        a[:, i] = np.poly(np.divide(roots, np.abs(roots)))
        a[:, i] = np.flipud(a[:, i])
    return a
Пример #53
0
    def fix_poles(self, a):
        poles = np.roots(a)
        THR = 0.98
        if not np.any(np.abs(poles) > THR):
            return a
        idxs = np.abs(poles) > THR
        poles[idxs] = THR * poles[idxs] / np.abs(poles[idxs])

        return np.poly(poles)
Пример #54
0
def randomPureReal(N=4, M=3):

    #Generate a random transfer function of degree N

    num = np.poly(2 * np.random.rand(N) - 1)
    den = np.poly(2 * np.random.rand(M) - 1)
    G = ctrl.tf(num, den, 1)
    realFreq = pureReal(G)
    sizes = [abs(ctrl.evalfr(G, z)) for z in realFreq]
    realFreq = realFreq[np.argsort(sizes)]
    sizes = 10 * (np.arange(len(realFreq)) + 1)

    #Plot the unit circle and all the values where it is pure real
    x = np.linspace(0, 2 * np.pi)
    plt.plot(np.cos(x), np.sin(x))
    plt.scatter(realFreq.real, realFreq.imag, s=sizes, c='r')
    plt.axis('scaled')
    plt.show()
Пример #55
0
def daubcqf(n, dtype='min'):
    """
Function computes the Daubechies' scaling and wavelet filters
(normalized to sqrt(2)).

Input: 
   n     : Length of filter (must be even)
   dtype : Optional parameter that distinguishes the minimum phase,
           maximum phase and mid-phase solutions ('min', 'max', or
           'mid'). If no argument is specified, the minimum phase
           solution is used.

Output: 
   h_0 : Minimal phase Daubechies' scaling filter 
   h_1 : Minimal phase Daubechies' wavelet filter 

Example:
   n = 4
   dtype = 'min'
   h_0, h_1 = daubcqf(n, dtype)

Example Result:
   h_0 = array([0.4830, 0.8365, 0.2241, -0.1294])
   h_1 = array([0.1294, 0.2241, -0.8365, 0.4830])

Reference: \"Orthonormal Bases of Compactly Supported Wavelets\",
            CPAM, Oct.89 
  """
    if (n % 2 != 0):
        raise Exception("No Daubechies filter exists for ODD length")
    k = n // 2
    a = p = q = 1
    h_0 = np.array([1, 1])
    for j in range(1, k):
        a = -a * 0.25 * (j + k - 1) / j
        h_0 = np.hstack((0, h_0)) + np.hstack((h_0, 0))
        p = np.hstack((0, -p)) + np.hstack((p, 0))
        p = np.hstack((0, -p)) + np.hstack((p, 0))
        q = np.hstack((0, q, 0)) + a * p
    q = np.sort(np.roots(q))
    qt = q[0:k - 1]
    if (dtype == 'mid'):
        if (k % 2 == 1):
            qt = np.hstack((q[0:n - 2:4], q[1:n - 2:4]))
        else:
            qt = np.hstack((q[0], q[3:k - 1:4], q[4:k - 1:4], q[n - 4:k:-4],
                            q[n - 5:k:-4]))
    h_0 = np.convolve(h_0, np.real(np.poly(qt)))
    h_0 = np.sqrt(2) * h_0 / sum(h_0)
    if (dtype == 'max'):
        h_0 = np.flipud(h_0)
    if (np.abs(sum(np.power(h_0, 2))) - 1 > 1e-4):
        raise Exception("Numerically unstable for this value of n")
    h_1 = np.copy(np.flipud(h_0))
    h_1[0:n - 1:2] = -h_1[0:n - 1:2]
    return h_0, h_1
Пример #56
0
def chebpoly(n, x=None, kind=1):
    """
    Return Chebyshev polynomial of the first or second kind.

    These polynomials are orthogonal on the interval [-1,1], with
    respect to the weight function w(x) = (1-x^2)^(-1/2+kind-1).

    chebpoly(n) returns the coefficients of the Chebychev polynomial of degree N.
    chebpoly(n,x) returns the Chebychev polynomial of degree N evaluated in X.

    Parameters
    ----------
    n : integer, scalar
        degree of Chebychev polynomial.
    x : array-like, optional
        evaluation points
    kind: 1 or 2, optional
        kind of Chebychev polynomial (default 1)

    Returns
    -------
    p : ndarray
        polynomial coefficients if x is None.
        Chebyshev polynomial evaluated at x otherwise

    Examples
    --------
    >>> import numpy as np
    >>> x = chebroot(3)
    >>> np.abs(chebpoly(3,x))<1e-15
    array([ True,  True,  True], dtype=bool)
    >>> chebpoly(3)
    array([ 4.,  0., -3.,  0.])
    >>> x2 = chebroot(4,kind=2)
    >>> np.abs(chebpoly(4,x2,kind=2))<1e-15
    array([ True,  True,  True,  True], dtype=bool)
    >>> chebpoly(4,kind=2)
    array([ 16.,   0., -12.,   0.,   1.])


    Reference
    ---------
    http://en.wikipedia.org/wiki/Chebyshev_polynomials
    """
    if x is None:  # Calculate coefficients.
        if n == 0:
            p = np.ones(1)
        else:
            p = np.round(
                pow(2, n - 2 + kind) * np.poly(chebroot(n, kind=kind)))
            p[1::2] = 0
        return p
    else:  #   Evaluate polynomial in chebychev form
        ck = np.zeros(n + 1)
        ck[n] = 1.
        return _chebval(np.atleast_1d(x), ck, kind=kind)
Пример #57
0
def botheigs(num, eigs, init):
    charpoly = np.poly(eigs)
    temp = []
    for i in range(len(charpoly) - 1):
        temp.append(-charpoly[i + 1])
    print('\nThe coefficients are:\n')
    print(temp)
    a = bothways(num, init, temp)

    return a
Пример #58
0
    def power_spectrum(self, fs, p):
        p = self.to_params(p)

        ar_roots = self.ar_roots(p)
        ma_roots = self.ma_roots(p)

        ar_coefs = np.real(np.poly(ar_roots))

        ma_coefs = np.real(np.poly(ma_roots))
        ma_coefs /= ma_coefs[-1]
        ma_coefs = ma_coefs[::-1]

        s = par.bounded_values(p['logit_sigma'],
                               low=self.sigma_min,
                               high=self.sigma_max)

        sigma = s / np.sqrt(cm.carma_variance(1.0, ar_roots, ma_coefs))

        return cm.power_spectrum(fs, sigma, ar_coefs, ma_coefs)
Пример #59
0
def root_error(roots):
    """Make a scatter plot of the real and imaginary parts of
    the real and imaginary parts of roots and of the real and
    imaginary parts of the computed roots of the polynomial with
    coefficients calculated so that it should have roots at
    the same points as the original set of roots. """
    computed_roots = np.poly1d(np.poly(roots)).roots
    plt.scatter(roots.real, roots.imag, color='b')
    plt.scatter(computed_roots.real, computed_roots.imag, color='r')
    plt.show()
Пример #60
0
 def setUp(self):
     num = np.poly([3, 0.3, 1])
     den = np.poly([2, 0.5, .25])
     H = (num, den)
     tstr1 = empty()
     (tstr1.form, tstr1.num, tstr1.den) = ('coeff', num, den)
     tstr2 = empty()
     tstr2.form = 'zp'
     (tstr2.zeros, tstr2.poles, tstr2.gain) = tf2zpk(num, den)
     z = np.exp(1j * np.linspace(0, 2*np.pi, num=129, endpoint=True))
     self.h1 = ds.evalTF(tstr1, z)
     self.h2 = ds.evalTF(tstr2, z)
     self.h3 = ds.evalTF(H, z)
     self.h4 = ds.evalTF(lti(tstr2.zeros, tstr2.poles, tstr2.gain), z)
     h5tf = lti(tstr2.zeros, tstr2.poles, tstr2.gain).to_ss()
     self.h5 = ds.evalTF((h5tf.A, h5tf.B, h5tf.C, h5tf.D), z)
     h6tf = np.vstack((np.hstack((h5tf.A, h5tf.B)),
                       np.hstack((h5tf.C, np.atleast_2d(h5tf.D)))))
     self.h6 = ds.evalTF(h6tf, z)