def sweep(self, wireFrameProjection, frame, lines,
              color=[0, 0, 255], sweepThick=5, fullsweepFrame=104):
        # calculate sweep angle
        halfcycle = fullsweepFrame / 2
        position = (frame % fullsweepFrame)
        if position > halfcycle:
            position = fullsweepFrame - position
        sweep = position / halfcycle
        allY = [n * 32 for n in range(int(self.projectedY / 32))]

        # calculate the wireframe positions
        nlanes = len(lines) - 1
        leftPolynomial = np.poly1d(lines[0].currentFit)
        rightPolynomial = np.poly1d(lines[nlanes].currentFit)

        # scanning sweep
        polySweepDiff = np.polysub(
            lines[nlanes].currentFit,
            lines[0].currentFit) * sweep
        sweepPoly = np.polyadd(leftPolynomial, polySweepDiff)
        allX = sweepPoly(allY)
        XYPolyline = np.column_stack((allX, allY)).astype(np.int32)
        cv2.polylines(wireFrameProjection, [XYPolyline], 0, color, sweepThick)
        sweepLane = 0
        for i in range(nlanes):
            leftLine = np.poly1d(lines[i].currentFit)
            rightLine = np.poly1d(lines[i+1].currentFit)
            if (leftLine([self.projectedY])[0] <
                    sweepPoly([self.projectedY])[0] and
                    sweepPoly([self.projectedY])[0] <
                    rightLine([self.projectedY])[0]):
                sweepLane = i
        return sweepLane
Beispiel #2
0
def residue(b,a,tol=1e-3,rtype='avg'):
    """Compute partial-fraction expansion of b(s) / a(s).

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

            b(s)     b[0] s**(M-1) + b[1] s**(M-2) + ... + b[M-1]
    H(s) = ------ = ----------------------------------------------
            a(s)     a[0] s**(N-1) + a[1] s**(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:  invres, poly, polyval, unique_roots
    """

    b,a = map(asarray,(b,a))
    k,b = polydiv(b,a)
    p = roots(a)
    r = p*0.0
    pout, mult = unique_roots(p,tol=tol,rtype=rtype)
    p = []
    for n in range(len(pout)):
        p.extend([pout[n]]*mult[n])
    p = asarray(p)
    # Compute the residue from the general formula
    indx = 0
    for n in range(len(pout)):
        bn = b.copy()
        pn = []
        for l in range(len(pout)):
            if l != n:
                pn.extend([pout[l]]*mult[l])
        an = atleast_1d(poly(pn))
        # bn(s) / an(s) is (s-po[n])**Nn * b(s) / a(s) where Nn is
        # multiplicity of pole at po[n]
        sig = mult[n]
        for m in range(sig,0,-1):
            if sig > m:
                # compute next derivative of bn(s) / an(s)
                term1 = polymul(polyder(bn,1),an)
                term2 = polymul(bn,polyder(an,1))
                bn = polysub(term1,term2)
                an = polymul(an,an)
            r[indx+m-1] = polyval(bn,pout[n]) / polyval(an,pout[n]) \
                          / factorial(sig-m)
        indx += sig
    return r, p, k
Beispiel #3
0
    def createPolyFitRight(self, curImgFtr, leftLane,
                           faint=1.0, resized=False):
        # create new right line polynomial
        polyDiff = np.polysub(leftLane.lines[leftLane.right].currentFit,
                              leftLane.lines[leftLane.left].currentFit)
        self.currentFit = np.polyadd(
            leftLane.lines[leftLane.right].currentFit, polyDiff)
        polynomial = np.poly1d(self.currentFit)
        self.allY = leftLane.lines[leftLane.right].allY
        self.currentX = polynomial(self.allY)
        self.allX = self.currentX

        if len(self.allY) > 75:
            # We need to increase our pixel count by 2 to get to 100%
            # confidence and maintain the current pixel count to keep
            # the line detection
            self.confidence_based = len(self.allY) * 2
            self.confidence = len(self.allY) / self.confidence_based
            self.detected = True

            # create linepoly
            xy1 = np.column_stack(
                (self.currentX + self.maskDelta, self.allY))
            xy1 = xy1.astype(np.int32)
            xy2 = np.column_stack(
                (self.currentX - self.maskDelta, self.allY))
            xy2 = xy2.astype(np.int32)
            self.linePoly = np.concatenate((xy1, xy2[::-1]), axis=0)

            # create mask
            self.linemask = np.zeros_like(self.linemask)
            cv2.fillConvexPoly(self.linemask, self.linePoly, 64)

            # Add the point at the bottom.
            allY = np.append(self.allY, self.projectedY - 1)
            allX = polynomial(allY)
            self.XYPolyline = np.column_stack((allX, allY))
            self.XYPolyline = self.XYPolyline.astype(np.int32)

            # create the accumulator
            self.bestFit = self.currentFit

            # classify the line
            # print("classifying the right line",self.side)
            self.getLineStats(
                curImgFtr.getRoadProjection(), faint=faint, resized=resized)

            # set bottom of line
            x = polynomial([self.projectedY - 1])
            self.pixelBasePos = x[0]
Beispiel #4
0
 def __sub__(self, other):
     """An operator overload for subtracting two terms with ``-``."""
     if isinstance(other, Polynomial) and self.transform == other.transform:
         return Polynomial(coefficients=numpy.polysub(self.coefficients, other.coefficients),
                           transform=self.transform)
     elif isinstance(other, Constant):
         if len(self.coefficients):  # pylint: disable=len-as-condition; coefficients might be a NumPy array, where __nonzero__ is not equivalent to len(.)
             coefficients = list(self.coefficients)
             coefficients[-1] -= other.value
             return Polynomial(coefficients=coefficients, transform=self.transform)
         else:
             return -other
     else:
         return super().__sub__(other)
Beispiel #5
0
    def updatePolyFitRight(self, leftLane):
        # update new right line polynomial
        polyDiff = np.polysub(leftLane.lines[leftLane.right].currentFit,
                              leftLane.lines[leftLane.left].currentFit)
        self.currentFit = np.polyadd(
            leftLane.lines[leftLane.right].currentFit, polyDiff)
        polynomial = np.poly1d(self.currentFit)
        self.allY = leftLane.lines[leftLane.right].allY
        self.currentX = polynomial(self.allY)
        self.allX = self.currentX

        if len(self.allY) > 150:
            # We need to increase our pixel count by 2 to get to 100%
            # confidence and maintain the current pixel count to keep
            # the line detection
            self.confidence = len(self.allY) / self.confidence_based
            if self.confidence > 0.5:
                self.detected = True
                if self.confidence > 1.0:
                    self.confidence = 1.0
            else:
                self.detected = False

            # create linepoly
            xy1 = np.column_stack(
                (self.currentX + self.maskDelta, self.allY)).astype(np.int32)
            xy2 = np.column_stack(
                (self.currentX - self.maskDelta, self.allY)).astype(np.int32)
            self.linePoly = np.concatenate((xy1, xy2[::-1]), axis=0)

            # create mask
            self.linemask = np.zeros_like(self.linemask)
            cv2.fillConvexPoly(self.linemask, self.linePoly, 64)

            # Add the point at the bottom.
            allY = np.append(self.allY, self.projectedY - 1)
            allX = polynomial(allY)
            self.XYPolyline = np.column_stack((allX, allY)).astype(np.int32)

            # create the accumulator
            self.bestFit = self.currentFit
    def wireframe(self, wireFrameProjection, frame, mainLane,
                  color=[255, 255, 255], wireThick=1,
                  sweepThick=5, fullsweepFrame=26):
        # calculate the wireframe positions
        nlanes = len(mainLane.lines) - 1
        leftPolynomial = np.poly1d(mainLane.lines[0].currentFit)
        roadleftPolynomial = np.poly1d(
            mainLane.lines[mainLane.left].currentFit)
        roadrightPolynomial = np.poly1d(
            mainLane.lines[mainLane.right].currentFit)
        rightPolynomial = np.poly1d(mainLane.lines[nlanes].currentFit)
        delta = (frame * 32) % 128
        squares = []

        # horizontal lines
        for i in range(int(self.projectedY / 128)):
            y1 = 128 * i + delta
            x1 = leftPolynomial([y1])
            x2 = roadleftPolynomial([y1])
            x3 = roadrightPolynomial([y1])
            x4 = rightPolynomial([y1])
            cv2.line(wireFrameProjection, (x1, y1),
                     (x4, y1), color, wireThick * 3)
            squares.append(((x2, y1), (x3, y1)))

        # vertical lines
        allY = [n * 32 for n in range(int(self.projectedY / 32))]
        polyDiff = np.polysub(mainLane.lines[nlanes].currentFit,
                              mainLane.lines[0].currentFit) / (nlanes * 2)
        curPoly = leftPolynomial
        for i in range(nlanes * 2):
            allX = curPoly(allY)
            XYPolyline = np.column_stack((allX, allY)).astype(np.int32)
            cv2.polylines(wireFrameProjection, [
                          XYPolyline], 0, color, int(wireThick / 4))
            curPoly = np.polyadd(curPoly, polyDiff)
        return squares
def stability_margins(sysdata, returnall=False, epsw=0.0):
    """Calculate stability margins and associated crossover frequencies.

    Parameters
    ----------
    sysdata: LTI system or (mag, phase, omega) sequence
        sys : LTI system
            Linear SISO system
        mag, phase, omega : sequence of array_like
            Arrays of magnitudes (absolute values, not dB), phases (degrees),
            and corresponding frequencies. Crossover frequencies returned are
            in the same units as those in `omega` (e.g., rad/sec or Hz).
    returnall: bool, optional
        If true, return all margins found. If False (default), return only the
        minimum stability margins. For frequency data or FRD systems, only
        margins in the given frequency region can be found and returned.
    epsw: float, optional
        Frequencies below this value (default 0.0) are considered static gain,
        and not returned as margin.

    Returns
    -------
    gm: float or array_like
        Gain margin
    pm: float or array_loke
        Phase margin
    sm: float or array_like
        Stability margin, the minimum distance from the Nyquist plot to -1
    wg: float or array_like
        Frequency for gain margin (at phase crossover, phase = -180 degrees)
    wp: float or array_like
        Frequency for phase margin (at gain crossover, gain = 1)
    ws: float or array_like
        Frequency for stability margin (complex gain closest to -1)
    """

    try:
        if isinstance(sysdata, frdata.FRD):
            sys = frdata.FRD(sysdata, smooth=True)
        elif isinstance(sysdata, xferfcn.TransferFunction):
            sys = sysdata
        elif getattr(sysdata, '__iter__', False) and len(sysdata) == 3:
            mag, phase, omega = sysdata
            sys = frdata.FRD(mag * np.exp(1j * phase * math.pi / 180),
                             omega,
                             smooth=True)
        else:
            sys = xferfcn._convertToTransferFunction(sysdata)
    except Exception as e:
        print(e)
        raise ValueError("Margin sysdata must be either a linear system or "
                         "a 3-sequence of mag, phase, omega.")

    # calculate gain of system
    if isinstance(sys, xferfcn.TransferFunction):

        # check for siso
        if not issiso(sys):
            raise ValueError("Can only do margins for SISO system")

        # real and imaginary part polynomials in omega:
        rnum, inum = _polyimsplit(sys.num[0][0])
        rden, iden = _polyimsplit(sys.den[0][0])

        # test (imaginary part of tf) == 0, for phase crossover/gain margins
        test_w_180 = np.polyadd(np.polymul(inum, rden),
                                np.polymul(rnum, -iden))
        w_180 = np.roots(test_w_180)

        # first remove imaginary and negative frequencies, epsw removes the
        # "0" frequency for type-2 systems
        w_180 = np.real(w_180[(np.imag(w_180) == 0) * (w_180 >= epsw)])

        # evaluate response at remaining frequencies, to test for phase 180 vs 0
        with np.errstate(all='ignore'):
            resp_w_180 = np.real(
                np.polyval(sys.num[0][0], 1.j * w_180) /
                np.polyval(sys.den[0][0], 1.j * w_180))

        # only keep frequencies where the negative real axis is crossed
        w_180 = w_180[np.real(resp_w_180) <= 0.0]

        # and sort
        w_180.sort()

        # test magnitude is 1 for gain crossover/phase margins
        test_wc = np.polysub(np.polyadd(_polysqr(rnum), _polysqr(inum)),
                             np.polyadd(_polysqr(rden), _polysqr(iden)))
        wc = np.roots(test_wc)
        wc = np.real(wc[(np.imag(wc) == 0) * (wc > epsw)])
        wc.sort()

        # stability margin was a bitch to elaborate, relies on magnitude to
        # point -1, then take the derivative. Second derivative needs to be >0
        # to have a minimum
        test_wstabd = np.polyadd(_polysqr(rden), _polysqr(iden))
        test_wstabn = np.polyadd(_polysqr(np.polyadd(rnum, rden)),
                                 _polysqr(np.polyadd(inum, iden)))
        test_wstab = np.polysub(
            np.polymul(np.polyder(test_wstabn), test_wstabd),
            np.polymul(np.polyder(test_wstabd), test_wstabn))

        # find the solutions, for positive omega, and only real ones
        wstab = np.roots(test_wstab)
        wstab = np.real(wstab[(np.imag(wstab) == 0) * (np.real(wstab) >= 0)])

        # and find the value of the 2nd derivative there, needs to be positive
        wstabplus = np.polyval(np.polyder(test_wstab), wstab)
        wstab = np.real(wstab[(np.imag(wstab) == 0) * (wstab > epsw) *
                              (wstabplus > 0.)])
        wstab.sort()

    else:
        # a bit coarse, have the interpolated frd evaluated again
        def mod(w):
            """to give the function to calculate |G(jw)| = 1"""
            return np.abs(sys._evalfr(w)[0][0]) - 1

        def arg(w):
            """function to calculate the phase angle at -180 deg"""
            return np.angle(-sys._evalfr(w)[0][0])

        def dstab(w):
            """function to calculate the distance from -1 point"""
            return np.abs(sys._evalfr(w)[0][0] + 1.)

        # Find all crossings, note that this depends on omega having
        # a correct range
        widx = np.where(np.diff(np.sign(mod(sys.omega))))[0]
        wc = np.array([
            sp.optimize.brentq(mod, sys.omega[i], sys.omega[i + 1])
            for i in widx if i + 1 < len(sys.omega)
        ])

        # find the phase crossings ang(H(jw) == -180
        widx = np.where(np.diff(np.sign(arg(sys.omega))))[0]
        widx = widx[np.real(sys._evalfr(sys.omega[widx])[0][0]) <= 0]
        w_180 = np.array([
            sp.optimize.brentq(arg, sys.omega[i], sys.omega[i + 1])
            for i in widx if i + 1 < len(sys.omega)
        ])

        # find all stab margins?
        widx = np.where(np.diff(np.sign(np.diff(dstab(sys.omega)))))[0]
        wstab = np.array([
            sp.optimize.minimize_scalar(dstab,
                                        bracket=(sys.omega[i],
                                                 sys.omega[i + 1])).x
            for i in widx if i + 1 < len(sys.omega)
            and np.diff(np.diff(dstab(sys.omega[i - 1:i + 2])))[0] > 0
        ])
        wstab = wstab[(wstab >= sys.omega[0]) * (wstab <= sys.omega[-1])]

    # margins, as iterables, converted frdata and xferfcn calculations to
    # vector for this
    with np.errstate(all='ignore'):
        gain_w_180 = np.abs(sys._evalfr(w_180)[0][0])
        GM = 1.0 / gain_w_180
    SM = np.abs(sys._evalfr(wstab)[0][0] + 1)
    PM = np.remainder(np.angle(sys._evalfr(wc)[0][0], deg=True), 360.0) - 180.0

    if returnall:
        return GM, PM, SM, w_180, wc, wstab
    else:
        if GM.shape[0] and not np.isinf(GM).all():
            with np.errstate(all='ignore'):
                gmidx = np.where(
                    np.abs(np.log(GM)) == np.min(np.abs(np.log(GM))))
        else:
            gmidx = -1
        if PM.shape[0]:
            pmidx = np.where(np.abs(PM) == np.amin(np.abs(PM)))[0]
        return ((not gmidx != -1 and float('inf'))
                or GM[gmidx][0], (not PM.shape[0] and float('inf'))
                or PM[pmidx][0], (not SM.shape[0] and float('inf'))
                or np.amin(SM), (not gmidx != -1 and float('nan'))
                or w_180[gmidx][0], (not wc.shape[0] and float('nan'))
                or wc[pmidx][0], (not wstab.shape[0] and float('nan'))
                or wstab[SM == np.amin(SM)][0])
weights = np.hanning(N)
print("Weights", weights)

bhp = np.loadtxt('BHP.csv', delimiter=',', usecols=(6, ), unpack=True)
bhp_returns = np.diff(bhp) / bhp[:-1]
smooth_bhp = np.convolve(weights / weights.sum(), bhp_returns)[N - 1:-N + 1]

vale = np.loadtxt('VALE.csv', delimiter=',', usecols=(6, ), unpack=True)
vale_returns = np.diff(vale) / vale[:-1]
smooth_vale = np.convolve(weights / weights.sum(), vale_returns)[N - 1:-N + 1]

K = 8
t = np.arange(N - 1, len(bhp_returns))
poly_bhp = np.polyfit(t, smooth_bhp, K)
poly_vale = np.polyfit(t, smooth_vale, K)
poly_sub = np.polysub(poly_bhp, poly_vale)

xpoints = np.roots(poly_sub)
print("Intersection points", xpoints)

reals = np.isreal(xpoints)
print("Real number?", reals)

xpoints = np.select([reals], [xpoints])
xpoints = xpoints.real
print("Real intersection points", xpoints)
print("Sans 0s", np.trim_zeros(xpoints))

plt.plot(t, bhp_returns[N - 1:], lw=1.0, label='BHP returns')
plt.plot(t, smooth_bhp, lw=2.0, label='BHP smoothed')
plt.plot(t, vale_returns[N - 1:], '--', lw=1.0, label='VALE returns')
Beispiel #9
0
def residue(b, a, tol=1e-3, rtype='avg'):
    """
    Compute partial-fraction expansion of b(s) / a(s).

    If ``M = len(b)`` and ``N = len(a)``, then the partial-fraction
    expansion H(s) is defined as::

              b(s)     b[0] s**(M-1) + b[1] s**(M-2) + ... + b[M-1]
      H(s) = ------ = ----------------------------------------------
              a(s)     a[0] s**(N-1) + a[1] s**(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 together than `tol`), then H(s)
    has terms like::

            r[i]      r[i+1]              r[i+n-1]
          -------- + ----------- + ... + -----------
          (s-p[i])  (s-p[i])**2          (s-p[i])**n

    Returns
    -------
    r : ndarray
        Residues.
    p : ndarray
        Poles.
    k : ndarray
        Coefficients of the direct polynomial term.

    See Also
    --------
    invres, numpy.poly, unique_roots

    """

    b, a = map(asarray, (b, a))
    rscale = a[0]
    k, b = polydiv(b, a)
    p = roots(a)
    r = p * 0.0
    pout, mult = unique_roots(p, tol=tol, rtype=rtype)
    p = []
    for n in range(len(pout)):
        p.extend([pout[n]] * mult[n])
    p = asarray(p)
    # Compute the residue from the general formula
    indx = 0
    for n in range(len(pout)):
        bn = b.copy()
        pn = []
        for l in range(len(pout)):
            if l != n:
                pn.extend([pout[l]] * mult[l])
        an = atleast_1d(poly(pn))
        # bn(s) / an(s) is (s-po[n])**Nn * b(s) / a(s) where Nn is
        # multiplicity of pole at po[n]
        sig = mult[n]
        for m in range(sig, 0, -1):
            if sig > m:
                # compute next derivative of bn(s) / an(s)
                term1 = polymul(polyder(bn, 1), an)
                term2 = polymul(bn, polyder(an, 1))
                bn = polysub(term1, term2)
                an = polymul(an, an)
            r[indx + m - 1] = polyval(bn, pout[n]) / polyval(an, pout[n]) \
                          / factorial(sig - m)
        indx += sig
    return r / rscale, p, k
Beispiel #10
0
mp.plot(dates[1:],vale_returns,color='red',label='vale returns',alpha=0.2)

#卷积降噪
kernel=np.hanning(8)
kernel/=kernel.sum()
bhp_convoloed=np.convolve(bhp_returns,kernel,'valid')
vale_convoloed=np.convolve(vale_returns,kernel,'valid')

mp.plot(dates[8:],bhp_convoloed,color='orange',label='bhp_convoloed',alpha=0.1)
mp.plot(dates[8:],vale_convoloed,color='m',label='vale_convoloed',alpha=0.1)

#多项式拟合,获取两项多项式系数
days=dates[8:].astype('M8[D]').astype('i4')
bhp_P=np.polyfit(days,bhp_convoloed,3)
bhp_val=np.polyval(bhp_P,days)                              #把days带入polyval
vale_P=np.polyfit(days,vale_convoloed,3)
vale_val=np.polyval(vale_P,days)
mp.plot(dates[8:],bhp_convoloed,color='gold',label='bhp_convoloed')
mp.plot(dates[8:],vale_convoloed,color='green',label='vale_convoloed')

#求两个多项式的焦点
diff_P=np.polysub(bhp_P,vale_P)
#求根
xs=np.roots(diff_P)
print(xs.astype('M8[D]'))

#添加图例
mp.legend()
mp.gcf().autofmt_xdate()
mp.show()
Beispiel #11
0
#Form X1o for n=even
Ee=np.copy(E)
Eo=np.copy(E)
Fe=np.copy(F)
Fo=np.copy(F)
for i in range(len(Ee)):
    if i%2==0:
        Eo[i]=0
        Fo[i]=0
    else:
        Ee[i]=0
        Fe[i]=0
Eo=Eo[1:]
Fo=Fo[1:]
X1On=np.polysub(Ee,Fe)
X1On = X1On[2:]
X1Od=np.polyadd(Eo,Fo)  

#X1On=np.polysub(Ee,Fe)
#X1Od=np.polysub(Eo,Fo)

#sort and organize transmission zeros for finite poles for synthesis
#According SU p296, finite pole frequencies closest to the bandedge should
#be placed in the middle of the filter to avoid negative components.
bz = np.array([])
for u in range(2,m+1):
    bz = np.append(bz, np.array([bS[2*u-1]]))
#bz = np.append(bz,np.inf)

tz=1/(np.sort(bz))
Beispiel #12
0
def  compute(a1,a2,a3):
	multiAns = np.polymul(a1,a3)
	ans =  np.polysub(a2,multiAns)
	ans = np.poly1d(ans)
	modPolynomial(ans)
	return ans
Beispiel #13
0
print "Weights", weights

bhp = numpy.loadtxt('BHP.csv', delimiter=',', usecols=(6,), unpack=True)
bhp_returns = numpy.diff(bhp) / bhp[ : -1]
smooth_bhp = numpy.convolve(weights/weights.sum(), bhp_returns)[N-1:-N+1]

vale = numpy.loadtxt('VALE.csv', delimiter=',', usecols=(6,), unpack=True)
vale_returns = numpy.diff(vale) / vale[ : -1]
smooth_vale = numpy.convolve(weights/weights.sum(), vale_returns)[N-1:-N+1]

K = int(sys.argv[1])
t = numpy.arange(N - 1, len(bhp_returns))
poly_bhp = numpy.polyfit(t, smooth_bhp, K)
poly_vale = numpy.polyfit(t, smooth_vale, K)

poly_sub = numpy.polysub(poly_bhp, poly_vale)
xpoints = numpy.roots(poly_sub)
print "Intersection points", xpoints

reals = numpy.isreal(xpoints)
print "Real number?", reals

xpoints = numpy.select([reals], [xpoints])
xpoints = xpoints.real
print "Real intersection points", xpoints

print "Sans 0s", numpy.trim_zeros(xpoints)

plot(t, bhp_returns[N-1:], lw=1.0)
plot(t, smooth_bhp, lw=2.0)
Beispiel #14
0
bhp = np.loadtxt('BHP.csv', delimiter=',', usecols=(6, ), unpack=True)
bhp_returns = np.diff(bhp) / bhp[:-1]  #np.diff()计算数组差值
smooth_bhp = np.convolve(
    weights / weights.sum(),
    bhp_returns)[N - 1:-N + 1]  #np.convolve()[n-1:-N+1]计算数组卷积长度为[N-1:]

vale = np.loadtxt('VALE.csv', delimiter=',', usecols=(6, ), unpack=True)
vale_returns = np.diff(vale) / vale[:-1]
smooth_vale = np.convolve(weights / weights.sum(), vale_returns)[N - 1:-N + 1]

K = int(sys.argv[1])  #拟合几次多项式
t = np.arange(N - 1, len(bhp_returns))
poly_bhp = np.polyfit(t, smooth_bhp, K)  #np.plotfit()返回拟合多项式的系数
poly_vale = np.polyfit(t, smooth_vale, K)

poly_sub = np.polysub(poly_bhp, poly_vale)  #np.plotsub()计算两个多项式的差构成的多项式
poly_sub_val = np.polyval(poly_sub, t)
poly_der = np.polyder(poly_bhp)
poly_der_val = np.polyval(poly_der, t)
xpoints = np.roots(poly_sub)  #np.roots()计算多项式的根
print "Intersection points", xpoints

reals = np.isreal(xpoints)  #np.isreal()判断多项式的根是否为实数,并返回布尔值
print "Real number?", reals

xpoints = np.select(
    [reals], [xpoints])  #np.select([reals],[xpoints])将xpoints数组中实数值返回,虚数值返回0
xpoints = xpoints.real  #返回数组中标签为实数的值
print "Real intersection points", xpoints

print "Sans 0s", np.trim_zeros(xpoints)  #np.trim_zeros()去除一维数组中开头和末尾的0元素
Beispiel #15
0
smooth_tencent = np.convolve(weights, tencent_returns)[N-1:-N+1]

t=np.arange(N-1, len(bidu_returns))
plt.clf()
plt.plot(t, bidu_returns[N-1:], lw=1.0, label='bidu_returns')
plt.plot(t, smooth_bidu, lw=2.0, label='bidu_smooth')
plt.plot(t, tencent_returns[N-1:], lw=1.0, label='tencent_returns')
plt.plot(t, smooth_tencent, lw=2.0, label='tencent_smooth')

plt.legend(loc='upper left')
plt.savefig('images/hanning_smooth.png', format='png')

K=3
t=np.arange(N-1, len(tencent_returns))
poly_bidu = np.polyfit(t, smooth_bidu, K)
poly_tencent = np.polyfit(t, smooth_tencent, K)

poly_sub = np.polysub(poly_bidu, poly_tencent)
xpoints = np.roots(poly_sub)
print "Intersection points:", xpoints

reals = np.isreal(xpoints)
print "Real number?", reals

xpoints = np.select([reals], [xpoints])
xpoints = xpoints.real

print "Real intersection points", xpoints

print "Sans 0s", np.trim_zeros(xpoints)
Beispiel #16
0
        E = np.polymul(E, [1, -1 * rt])
E = np.real(E)

#Form X1o for n=odd
Ee = np.copy(E)
Eo = np.copy(E)
Fe = np.copy(F)
Fo = np.copy(F)
for i in range(len(Ee)):
    if i % 2 == 0:
        Ee[i] = 0
        Fe[i] = 0
    else:
        Eo[i] = 0
        Fo[i] = 0
X1On = np.polysub(Ee, Fe)
X1Od = np.polyadd(Eo, Fo)

#sort and organize transmission zeros for finite poles for synthesis
#According SU p296, finite pole frequencies closest to the bandedge should
#be placed in the middle of the filter to avoid negative components.
tz = 1 / (np.sort(a[2:n:2]))
tzo = tz[::2]
tzo = np.append(tzo, np.sort(tz[1::2]))

#pad zeroes into tzo so the indices match SU
tzop = np.array([0])
for z in tzo:
    tzop = np.append(tzop, [0, z])

#test for removal
Beispiel #17
0
bhp = np.convolve(bhp_returns, kernel, 'valid')
vale = np.convolve(vale_returns, kernel, 'valid')

#针对vale与bhp分别做多项式
days = dates[7:].astype('M8[D]').astype('int32')
P_vale = np.polyfit(days, vale, 3)
P_bhp = np.polyfit(days, bhp, 3)

y_vale = np.polyval(P_vale, days)
y_bhp = np.polyval(P_bhp, days)

mp.plot(dates[7:], y_vale, c="orangered", label="vale_convolved")
mp.plot(dates[7:], y_bhp, c="dodgerblue", label="bhp_convolved")

#求多个多项式的交点位置

P = np.polysub(P_vale, P_bhp)
xs = np.roots(P)

dates = np.floor(xs).astype('M8[D]')

print(dates)

mp.legend()
mp.gcf().autofmt_xdate()

mp.show()

mp.legend()
mp.gcf().autofmt_xdate()
mp.show()
Beispiel #18
0
def Extract(n, p, tzop, E, F, wc_p, cauer_type='a'):
    cap_array = np.array([])
    ind_array = np.array([])
    omega_array = np.array([])

    _, _, _, _, X1On, X1Od = X1O(E, F)

    B_num = np.copy(X1Od)
    B_den = np.copy(X1On)

    #element extraction SU p306
    index = 2
    while index < n:
        #shunt removal
        BdivL_num = B_num[:
                          -1]  #equivalent to B divided by lambda when constant term of B is 0
        BdivL_num_eval = np.polyval(BdivL_num, 1j * tzop[index])
        BdivL_den_eval = np.polyval(B_den, 1j * tzop[index])
        c_shnt = BdivL_num_eval / BdivL_den_eval

        #update component and frequency arrays
        cap_array = np.append(cap_array, np.real(c_shnt))
        ind_array = np.append(ind_array, [0])
        omega_array = np.append(omega_array, [0])

        #update polynomila B
        Lc = np.array([np.real(c_shnt), 0])  #lambda*c(extracted)
        B_num = np.polysub(B_num, np.polymul(Lc, B_den))

        #series removal
        temp_n = np.polymul(np.array([1, 0]), B_num)
        temp_n = np.polydiv(temp_n, np.array([1, 0, tzop[index]**2]))[0]

        temp_ne = np.polyval(temp_n, 1j * tzop[index])
        temp_de = np.polyval(B_den, 1j * tzop[index])
        c_srs = temp_ne / temp_de

        #update component and frequency arrays
        cap_array = np.append(cap_array, np.real(c_srs))
        w = tzop[index]
        omega_array = np.append(omega_array, [w])
        l_srs = 1 / (w)**2 / (np.real(c_srs))
        ind_array = np.append(ind_array, [l_srs])

        #update polynomial B
        temp1 = np.polymul(B_den, np.array([1, 0, tzop[index]**2]))
        temp2 = np.polymul(B_num, np.array([1 / np.real(c_srs), 0]))
        B_den = np.polysub(temp1, temp2)
        B_num = np.polymul(B_num, np.array([1, 0, tzop[index]**2]))

        index += 2

    #shunt removal
    BdivL_num = B_num[:-1]  #B divided by lambda when constant term of B is 0
    BdivL_num_eval = BdivL_num[0]
    BdivL_den_eval = B_den[0]
    c_shnt = BdivL_num_eval / BdivL_den_eval

    #update component and frequency arrays
    cap_array = np.append(cap_array, np.real(c_shnt))
    ind_array = np.append(ind_array, [0])
    omega_array = np.append(omega_array, [0])

    #Lc = np.array([np.real(c_shnt), 0])  #lambda*c(extracted)
    #B_num = np.polysub(B_num, np.polymul(Lc, B_den))

    zout = 1

    #For even order filters, extract series L by using X2O
    if n % 2 == 0:
        if cauer_type == 'b':
            zout = (1 - p) / (1 + p)

        #see table 4.4 page 129 in Zverev for X2O
        _, _, _, _, X2On, X2Od = X2O(E, F)
        l_srs = (X2On[0]) / (X2Od[0])

        cap_array = np.append(cap_array, 0)
        ind_array = np.append(ind_array, l_srs * zout)
        omega_array = np.append(omega_array, [0])

    #Denormalize component values and frequencies
    cap_array = cap_array * wc_p
    ind_array = ind_array * wc_p
    omega_array = omega_array / wc_p

    #Pad zeros so indices match those of SU
    cap_array = np.insert(cap_array, 0, 0)
    cap_array = np.append(cap_array, 0)

    ind_array = np.insert(ind_array, 0, 0)
    ind_array = np.append(ind_array, 0)

    omega_array = np.insert(omega_array, 0, 0)
    omega_array = np.append(omega_array, 0)

    terms = np.array([1])
    terms = np.append(terms, np.zeros(n))
    terms = np.append(terms, zout)

    return cap_array, ind_array, omega_array, terms
Beispiel #19
0
print "Weights", weights

bhp = np.loadtxt('BHP.csv', delimiter=',', usecols=(6,), unpack=True)
bhp_returns = np.diff(bhp) / bhp[ : -1]
smooth_bhp = np.convolve(weights/weights.sum(), bhp_returns)[N-1:-N+1]

vale = np.loadtxt('VALE.csv', delimiter=',', usecols=(6,), unpack=True)
vale_returns = np.diff(vale) / vale[ : -1]
smooth_vale = np.convolve(weights/weights.sum(), vale_returns)[N-1:-N+1]

K = int(sys.argv[1])
t = np.arange(N - 1, len(bhp_returns))
poly_bhp = np.polyfit(t, smooth_bhp, K)
poly_vale = np.polyfit(t, smooth_vale, K)

poly_sub = np.polysub(poly_bhp, poly_vale)
xpoints = np.roots(poly_sub)
print "Intersection points", xpoints

reals = np.isreal(xpoints)
print "Real number?", reals

xpoints = np.select([reals], [xpoints])
xpoints = xpoints.real
print "Real intersection points", xpoints

print "Sans 0s", np.trim_zeros(xpoints)

plot(t, bhp_returns[N-1:], lw=1.0)
plot(t, smooth_bhp, lw=2.0)
Beispiel #20
0
 def __sub__(self, other):
     return self.__class__(np.polysub(self.coeff, other.coeff))
Beispiel #21
0
bhp = numpy.loadtxt('BHP.csv', delimiter=',', usecols=(6, ), unpack=True)
bhp_returns = numpy.diff(bhp) / bhp[:-1]
smooth_bhp = numpy.convolve(weights / weights.sum(), bhp_returns)[N - 1:-N + 1]

vale = numpy.loadtxt('VALE.csv', delimiter=',', usecols=(6, ), unpack=True)
vale_returns = numpy.diff(vale) / vale[:-1]
smooth_vale = numpy.convolve(weights / weights.sum(),
                             vale_returns)[N - 1:-N + 1]

K = int(sys.argv[1])
t = numpy.arange(N - 1, len(bhp_returns))
poly_bhp = numpy.polyfit(t, smooth_bhp, K)
poly_vale = numpy.polyfit(t, smooth_vale, K)

poly_sub = numpy.polysub(poly_bhp, poly_vale)
xpoints = numpy.roots(poly_sub)
print "Intersection points", xpoints

reals = numpy.isreal(xpoints)
print "Real number?", reals

xpoints = numpy.select([reals], [xpoints])
xpoints = xpoints.real
print "Real intersection points", xpoints

print "Sans 0s", numpy.trim_zeros(xpoints)

plot(t, bhp_returns[N - 1:], lw=1.0)
plot(t, smooth_bhp, lw=2.0)
Beispiel #22
0
def FilterSub(f1, f2):
    den = polymul(f1.get_den(), f2.get_den())
    n1 = polymul(f1.get_num(), f2.get_den())
    n2 = polymul(f1.get_den(), f2.get_num())
    num = polysub(n1, n2)
    return Filter(num, den)
Beispiel #23
0
 def sub(self, u1, u2):
     return self.adjust(np.polysub(u1, u2)) 
Beispiel #24
0
def stability_margins(sysdata, returnall=False, epsw=1e-8):
    """Calculate stability margins and associated crossover frequencies.

    Parameters
    ----------
    sysdata: LTI system or (mag, phase, omega) sequence
        sys : LTI system
            Linear SISO system
        mag, phase, omega : sequence of array_like
            Arrays of magnitudes (absolute values, not dB), phases (degrees),
            and corresponding frequencies.  Crossover frequencies returned are
            in the same units as those in `omega` (e.g., rad/sec or Hz).
    returnall: bool, optional
        If true, return all margins found. If false (default), return only the
        minimum stability margins.  For frequency data or FRD systems, only one
        margin is found and returned.
    epsw: float, optional
        Frequencies below this value (default 1e-8) are considered static gain,
        and not returned as margin.

    Returns
    -------
    gm: float or array_like
        Gain margin
    pm: float or array_loke
        Phase margin
    sm: float or array_like
        Stability margin, the minimum distance from the Nyquist plot to -1
    wg: float or array_like
        Gain margin crossover frequency (where phase crosses -180 degrees)
    wp: float or array_like
        Phase margin crossover frequency (where gain crosses 0 dB)
    ws: float or array_like
        Stability margin frequency (where Nyquist plot is closest to -1)
    """

    try:
        if isinstance(sysdata, frdata.FRD):
            sys = frdata.FRD(sysdata, smooth=True)
        elif isinstance(sysdata, xferfcn.TransferFunction):
            sys = sysdata
        elif getattr(sysdata, '__iter__', False) and len(sysdata) == 3:
            mag, phase, omega = sysdata
            sys = frdata.FRD(mag * np.exp(1j * phase * np.pi/180), 
                             omega, smooth=True)
        else:
            sys = xferfcn._convertToTransferFunction(sysdata)
    except Exception as e:
        print (e)
        raise ValueError("Margin sysdata must be either a linear system or "
                         "a 3-sequence of mag, phase, omega.")

    # calculate gain of system
    if isinstance(sys, xferfcn.TransferFunction):

        # check for siso
        if not issiso(sys):
            raise ValueError("Can only do margins for SISO system")

        # real and imaginary part polynomials in omega:
        rnum, inum = _polyimsplit(sys.num[0][0])
        rden, iden = _polyimsplit(sys.den[0][0])

        # test (imaginary part of tf) == 0, for phase crossover/gain margins
        test_w_180 = np.polyadd(np.polymul(inum, rden), np.polymul(rnum, -iden))
        w_180 = np.roots(test_w_180)
        #print ('1:w_180', w_180)

        # first remove imaginary and negative frequencies, epsw removes the
        # "0" frequency for type-2 systems
        w_180 = np.real(w_180[(np.imag(w_180) == 0) * (w_180 >= epsw)])
        #print ('2:w_180', w_180)

        # evaluate response at remaining frequencies, to test for phase 180 vs 0
        resp_w_180 = np.real(np.polyval(sys.num[0][0], 1.j*w_180) /
                             np.polyval(sys.den[0][0], 1.j*w_180))
        #print ('resp_w_180', resp_w_180)                     

        # only keep frequencies where the negative real axis is crossed
        w_180 = w_180[np.real(resp_w_180) < 0.0]

        # and sort
        w_180.sort()
        #print ('3:w_180', w_180)

        # test magnitude is 1 for gain crossover/phase margins
        test_wc = np.polysub(np.polyadd(_polysqr(rnum), _polysqr(inum)),
                             np.polyadd(_polysqr(rden), _polysqr(iden)))
        wc = np.roots(test_wc)
        wc = np.real(wc[(np.imag(wc) == 0) * (wc > epsw)])
        wc.sort()

        # stability margin was a bitch to elaborate, relies on magnitude to
        # point -1, then take the derivative. Second derivative needs to be >0
        # to have a minimum
        test_wstabd = np.polyadd(_polysqr(rden), _polysqr(iden))
        test_wstabn = np.polyadd(_polysqr(np.polyadd(rnum,rden)),
                                 _polysqr(np.polyadd(inum,iden)))
        test_wstab = np.polysub(
            np.polymul(np.polyder(test_wstabn),test_wstabd),
            np.polymul(np.polyder(test_wstabd),test_wstabn))

        # find the solutions, for positive omega, and only real ones
        wstab = np.roots(test_wstab)
        #print('wstabr', wstab)
        wstab = np.real(wstab[(np.imag(wstab) == 0) * 
                        (np.real(wstab) >= 0)])
        #print('wstab', wstab)

        # and find the value of the 2nd derivative there, needs to be positive
        wstabplus = np.polyval(np.polyder(test_wstab), wstab)
        #print('wstabplus', wstabplus)
        wstab = np.real(wstab[(np.imag(wstab) == 0) * (wstab > epsw) *
                              (wstabplus > 0.)])
        #print('wstab', wstab)
        wstab.sort()

    else:
        # a bit coarse, have the interpolated frd evaluated again
        def mod(w):
            """to give the function to calculate |G(jw)| = 1"""
            return np.abs(sys.evalfr(w)[0][0]) - 1

        def arg(w):
            """function to calculate the phase angle at -180 deg"""
            return np.angle(-sys.evalfr(w)[0][0])

        def dstab(w):
            """function to calculate the distance from -1 point"""
            return np.abs(sys.evalfr(w)[0][0] + 1.)

        # Find all crossings, note that this depends on omega having
        # a correct range
        widx = np.where(np.diff(np.sign(mod(sys.omega))))[0]
        wc = np.array(
            [ sp.optimize.brentq(mod, sys.omega[i], sys.omega[i+1])
              for i in widx if i+1 < len(sys.omega)])
        
        # find the phase crossings ang(H(jw) == -180
        widx = np.where(np.diff(np.sign(arg(sys.omega))))[0]
        #print('widx (180)', widx, sys.omega[widx])
        #print('x', sys.evalfr(sys.omega[widx])[0][0])
        widx = widx[np.real(sys.evalfr(sys.omega[widx])[0][0]) <= 0]
        #print('widx (180,2)', widx)
        w_180 = np.array(
            [ sp.optimize.brentq(arg, sys.omega[i], sys.omega[i+1])
              for i in widx if i+1 < len(sys.omega) ])
        #print('x', sys.evalfr(w_180)[0][0])
        #print('w_180', w_180)

        # find all stab margins?
        widx = np.where(np.diff(np.sign(np.diff(dstab(sys.omega)))))[0]
        #print('widx', widx)
        #print('wstabx', sys.omega[widx])
        wstab = np.array([ sp.optimize.minimize_scalar(
                  dstab, bracket=(sys.omega[i], sys.omega[i+1])).x
              for i in widx if i+1 < len(sys.omega) and
              np.diff(np.diff(dstab(sys.omega[i-1:i+2])))[0] > 0 ])
        #print('wstabf0', wstab)
        wstab = wstab[(wstab >= sys.omega[0]) * 
                      (wstab <= sys.omega[-1])]
        #print ('wstabf', wstab)
        

    # margins, as iterables, converted frdata and xferfcn calculations to
    # vector for this
    GM = 1/np.abs(sys.evalfr(w_180)[0][0])
    SM = np.abs(sys.evalfr(wstab)[0][0]+1)
    PM = np.angle(sys.evalfr(wc)[0][0], deg=True) + 180
    
    if returnall:
        return GM, PM, SM, w_180, wc, wstab
    else:
        return (
            (GM.shape[0] or None) and np.amin(GM),
            (PM.shape[0] or None) and np.amin(PM),
            (SM.shape[0] or None) and np.amin(SM),
            (w_180.shape[0] or None) and w_180[GM==np.amin(GM)][0],
            (wc.shape[0] or None) and wc[PM==np.amin(PM)][0],
            (wstab.shape[0] or None) and wstab[SM==np.amin(SM)][0])
Beispiel #25
0
def stability_margins(sysdata, deg=True, returnall=False, epsw=1e-10):
    """Calculate gain, phase and stability margins and associated
    crossover frequencies.

    Usage
    -----
    gm, pm, sm, wg, wp, ws = stability_margins(sysdata, deg=True,
                                               returnall=False, epsw=1e-10)

    Parameters
    ----------
    sysdata: linsys or (mag, phase, omega) sequence
        sys : linsys
            Linear SISO system
        mag, phase, omega : sequence of array_like
            Input magnitude, phase, and frequencies (rad/sec) sequence from
            bode frequency response data
    deg=True: boolean
        If true, all input and output phases in degrees, else in radians
    returnall=False: boolean
        If true, return all margins found. Note that for frequency data or
        FRD systems, only one margin is found and returned. 
    epsw=1e-10: float
        frequencies below this value are considered static gain, and not
        returned as margin.

    Returns
    -------
    gm, pm, sm, wg, wp, ws: float or array_like
        Gain margin gm, phase margin pm, stability margin sm, and
        associated crossover
        frequencies wg, wp, and ws of SISO open-loop. If more than
        one crossover frequency is detected, returns the lowest corresponding
        margin.
        When requesting all margins, the return values are array_like,
        and all margins are returns for linear systems not equal to FRD
        """

    try:
        if isinstance(sysdata, frdata.FRD):
            sys = frdata.FRD(sysdata, smooth=True)
        elif isinstance(sysdata, xferfcn.TransferFunction):
            sys = sysdata
        elif getattr(sysdata, '__iter__', False) and len(sysdata) == 3:
            mag, phase, omega = sysdata
            sys = frdata.FRD(mag*np.exp((1j/360.)*phase), omega, smooth=True)
        else:
            sys = xferfcn._convertToTransferFunction(sysdata)
    except Exception as e:
        print (e)
        raise ValueError("Margin sysdata must be either a linear system or "
                         "a 3-sequence of mag, phase, omega.")

    # calculate gain of system
    if isinstance(sys, xferfcn.TransferFunction):

        # check for siso
        if not issiso(sys):
            raise ValueError("Can only do margins for SISO system")

        # real and imaginary part polynomials in omega:
        rnum, inum = _polyimsplit(sys.num[0][0])
        rden, iden = _polyimsplit(sys.den[0][0])

        # test imaginary part of tf == 0, for phase crossover/gain margins
        test_w_180 = np.polyadd(np.polymul(inum, rden), np.polymul(rnum, -iden))
        w_180 = np.roots(test_w_180)

        # first remove imaginary and negative frequencies, epsw removes the
        # "0" frequency for type-2 systems
        w_180 = np.real(w_180[(np.imag(w_180) == 0) * (w_180 >= epsw)])

        # evaluate response at remaining frequencies, to test for phase 180 vs 0
        resp_w_180 = np.real(np.polyval(sys.num[0][0], 1.j*w_180) /
                             np.polyval(sys.den[0][0], 1.j*w_180))

        # only keep frequencies where the negative real axis is crossed
        w_180 = w_180[(resp_w_180 < 0.0)]

        # and sort
        w_180.sort()

        # test magnitude is 1 for gain crossover/phase margins
        test_wc = np.polysub(np.polyadd(_polysqr(rnum), _polysqr(inum)),
                             np.polyadd(_polysqr(rden), _polysqr(iden)))
        wc = np.roots(test_wc)
        wc = np.real(wc[(np.imag(wc) == 0) * (wc > epsw)])
        wc.sort()

        # stability margin was a bitch to elaborate, relies on magnitude to
        # point -1, then take the derivative. Second derivative needs to be >0
        # to have a minimum
        test_wstabn = np.polyadd(_polysqr(rnum), _polysqr(inum))
        test_wstabd = np.polyadd(_polysqr(np.polyadd(rnum,rden)),
                                 _polysqr(np.polyadd(inum,iden)))
        test_wstab = np.polysub(
            np.polymul(np.polyder(test_wstabn),test_wstabd),
            np.polymul(np.polyder(test_wstabd),test_wstabn))

        # find the solutions
        wstab = np.roots(test_wstab)

        # and find the value of the 2nd derivative there, needs to be positive
        wstabplus = np.polyval(np.polyder(test_wstab), wstab)
        wstab = np.real(wstab[(np.imag(wstab) == 0) * (wstab > epsw) *
                              (np.abs(wstabplus) > 0.)])
        wstab.sort()

    else:
        # a bit coarse, have the interpolated frd evaluated again
        def mod(w):
            """to give the function to calculate |G(jw)| = 1"""
            return [np.abs(sys.evalfr(w[0])[0][0]) - 1]

        def arg(w):
            """function to calculate the phase angle at -180 deg"""
            return [np.angle(sys.evalfr(w[0])[0][0]) + np.pi]

        def dstab(w):
            """function to calculate the distance from -1 point"""
            return np.abs(sys.evalfr(w[0])[0][0] + 1.)

        # how to calculate the frequency at which |G(jw)| = 1
        wc = np.array([sp.optimize.fsolve(mod, sys.omega[0])])[0]
        w_180 = np.array([sp.optimize.fsolve(arg, sys.omega[0])])[0]
        wstab = np.real(
            np.array([sp.optimize.fmin(dstab, sys.omega[0], disp=0)])[0])

    # margins, as iterables, converted frdata and xferfcn calculations to
    # vector for this
    PM = np.angle(sys.evalfr(wc)[0][0], deg=True) + 180
    GM = 1/(np.abs(sys.evalfr(w_180)[0][0]))
    SM = np.abs(sys.evalfr(wstab)[0][0]+1)

    if returnall:
        return GM, PM, SM, w_180, wc, wstab
    else:
        return (
            (GM.shape[0] or None) and GM[0],
            (PM.shape[0] or None) and PM[0],
            (SM.shape[0] or None) and SM[0],
            (w_180.shape[0] or None) and w_180[0],
            (wc.shape[0] or None) and wc[0],
            (wstab.shape[0] or None) and wstab[0])
def calc_c_s(r, q, k, p):
    x_to_the_power_of_kp_minus_one = np.append([1], np.zeros(k*(p-1)))
    r_tilde = np.polysub(r, x_to_the_power_of_kp_minus_one)
    c, s = np.polydiv(r_tilde, q)
    np.testing.assert_allclose(r_tilde, np.polyadd(np.polymul(q, c), s))
    return c, s
Beispiel #27
0
qrvo_returns = np.diff(qrvo) / qrvo[:-1]

# smooth
smooth_avgo = np.convolve(weights / weights.sum(), avgo_returns)[N - 1:-N + 1]
smooth_qrvo = np.convolve(weights / weights.sum(), qrvo_returns)[N - 1:-N + 1]

t = np.arange(N - 1, len(avgo_returns))

plot(t, avgo_returns[N - 1:], lw=1.0)
plot(t, smooth_avgo, lw=2.0)
plot(t, qrvo_returns[N - 1:], lw=1.0)
plot(t, smooth_qrvo, lw=2.0)
show()

K = 3
poly_avgo = np.polyfit(t, smooth_avgo, K)
poly_qrvo = np.polyfit(t, smooth_qrvo, K)

poly_sub = np.polysub(poly_avgo, poly_qrvo)

xpoints = np.roots(poly_sub)
print("Intersection points {0}".format(xpoints))

reals = np.isreal(xpoints)
print("Real number? {0}".format(reals))

xpoints = np.select([reals], [xpoints])
xpoints = xpoints.real
print("Real intersection points {0}".format(xpoints))

print("Sans 0s {0}".format(np.trim_zeros(xpoints)))
Beispiel #28
0
mp.plot(dates[7:-1], Yang_Ming_Marine_SMT, linewidth=2, c='coral', label="Yang Ming Smoothing Lines")

# 找出數學多項式擬和公式,繪製擬和線
days = dates[7:-1].astype(int)
# 以多項式擬和三次方擬和
degree = 3
Eva_coefficient = np.polyfit(days, Eva_Marine_SMT,  degree)
Ymg_coefficient = np.polyfit(days, Yang_Ming_Marine_SMT,  degree)
Eva_poly_Fvalues = np.polyval(Eva_coefficient, days)
Ymg_poly_Fvalues = np.polyval(Ymg_coefficient, days)
# 以下為多項式擬和線繪製
mp.plot(dates[7:-1], Eva_poly_Fvalues, linewidth=5, c='green', label="Eva Marine Fitting Lines")
mp.plot(dates[7:-1], Ymg_poly_Fvalues, linewidth=5, c='coral', label="Yang Ming Fitting Lines")

# 找出兩條擬和線之交叉點
truning_points = np.polysub(Eva_poly_Fvalues, Ymg_poly_Fvalues)  # 先求出之差
R_x = np.roots(truning_points)                                   # 再求出交叉之根
R_y = np.polyval(Eva_coefficient, R_x)                           # 以根求出y
R_x = R_x.astype(int).astype('M8[D]')
#mp.scatter(R_x, R_y, marker="x", label="Turning Points")

# 設定格線繪製
ax = mp.gca()
# 設定x軸主要刻度(依據每周周一,不含周末)
ax.xaxis.set_major_locator(md.WeekdayLocator(byweekday=md.MONDAY))
# 設定x軸主要次刻度(依據天數)
ax.xaxis.set_minor_locator(md.DayLocator())
# 設定X軸主刻度顯示方式(日期/月份英文縮寫)
ax.xaxis.set_major_formatter(md.DateFormatter('%d-%b'))
mp.tick_params(labelsize=8)
mp.xticks(rotation=35)
Beispiel #29
0
#for n=even
E = np.array([1])
for root in np.roots(EnE):
    if np.real(root) < 0:
        #print(root)
        E = np.polymul(E, np.array([1, -1*root]))
E = np.real(E)
#print(E)

#zout = (1-p)/(1+p)
zout = (1+p)/(1-p)
t = np.sqrt(1/zout)
pc = 2/(t+1/t)

MnM = np.polysub(EnE,(pc**2)*PnP)
M = np.array([1])
for root in np.roots(MnM):
    if np.real(root) < 0:
        #print(root)
        M = np.polymul(M, np.array([1, -1*root]))
M = np.real(M)

X1On=np.polyadd(E,M)
X1Od=np.polysub(E,M)  

#sort and organize transmission zeros for finite poles for synthesis
#According SU p296, finite pole frequencies closest to the bandedge should
#be placed in the middle of the filter to avoid negative components.

tzop=np.array([0,0,w2,0,w4])
Beispiel #30
0
print(numpy.poly([-1, 1, 1, 10]))
print(numpy.poly([1, 1]))
print(numpy.roots([1, 0, -1]))
print(numpy.polyint([1, 1, 1]))  #find the integration
print(numpy.polyder([1, 1, 1, 1]))  #find the derivative
print(numpy.polyval([1, -2, 0, 2], 4))
print(numpy.polyfit([0, 1, -1, 2, -2], [0, 1, 1, 4, 4],
                    2))  #fit the value with specific order

p1 = numpy.poly1d([1, 2])
p2 = numpy.poly1d([9, 5, 4])
print(p1)
print(p2)
print(numpy.polyadd(p1, p2))
print(numpy.polysub(p1, p2))
print(numpy.polymul(p1, p2))
print(numpy.polydiv(p1, p2))

#https://docs.scipy.org/doc/numpy/reference/routines.linalg.html
print(numpy.linalg.det([[1, 2], [2, 1]]))
vals, vecs = numpy.linalg.eig([[1, 2], [2, 1]])
print(vals)
print(vecs)
print(numpy.linalg.inv([[1, 2], [2, 1]]))

#sort two associated arraies
a = ['f', 'e', 'b', 'd', 'a']
b = list(range(0, len(a)))
aa = a
bb = b
        if not issiso(sys):
            raise ValueError("Can only do margins for SISO system")

        # real and imaginary part polynomials in omega:
        rnum, inum = _polyimsplit(sys.num[0][0])
        rden, iden = _polyimsplit(sys.den[0][0])

        # test imaginary part of tf == 0, for phase crossover/gain margins
        test_w_180 = np.polyadd(np.polymul(inum, rden),
                                np.polymul(rnum, -iden))
        w_180 = np.roots(test_w_180)
        w_180 = np.real(w_180[(np.imag(w_180) == 0) * (w_180 > epsw)])
        w_180.sort()

        # test magnitude is 1 for gain crossover/phase margins
        test_wc = np.polysub(np.polyadd(_polysqr(rnum), _polysqr(inum)),
                             np.polyadd(_polysqr(rden), _polysqr(iden)))
        wc = np.roots(test_wc)
        wc = np.real(wc[(np.imag(wc) == 0) * (wc > epsw)])
        wc.sort()

        # stability margin was a bitch to elaborate, relies on magnitude to
        # point -1, then take the derivative. Second derivative needs to be >0
        # to have a minimum
        test_wstabn = np.polyadd(_polysqr(rnum), _polysqr(inum))
        test_wstabd = np.polyadd(_polysqr(np.polyadd(rnum, rden)),
                                 _polysqr(np.polyadd(inum, iden)))
        test_wstab = np.polysub(
            np.polymul(np.polyder(test_wstabn), test_wstabd),
            np.polymul(np.polyder(test_wstabd), test_wstabn))

        # find the solutions
Beispiel #32
0
Datei: smr.py Projekt: nykh2010/-
bhp_returns = np.diff(bhp_closing_prices) / \
    bhp_closing_prices[:-1]
vale_returns = np.diff(vale_closing_prices) / \
    vale_closing_prices[:-1]
N = 8
weights = np.hanning(N)
weights / weights.sum()
bhp_smooth_returns = np.convolve(bhp_returns, weights, 'valid')
vale_smooth_returns = np.convolve(vale_returns, weights, 'valid')
days = dates[N - 1:-1].astype(int)
degree = 5
bhp_p = np.polyfit(days, bhp_smooth_returns, degree)
bhp_poly_returns = np.polyval(bhp_p, days)
vale_p = np.polyfit(days, vale_smooth_returns, degree)
vale_poly_returns = np.polyval(vale_p, days)
sub_p = np.polysub(bhp_p, vale_p)
roots = np.roots(sub_p)
reals = roots[np.isreal(roots)].real
inters = []
for real in reals:
    if days[0] <= real and real <= days[-1]:
        inters.append([real, np.polyval(bhp_p, real)])
inters = np.array(inters)
mp.figure(num='Smoothing Returns', facecolor='lightgray')
mp.title('Smoothing Returns', fontsize=20)
mp.xlabel('Date', fontsize=14)
mp.ylabel('Returns', fontsize=14)
ax = mp.gca()
ax.xaxis.set_major_locator(md.WeekdayLocator(byweekday=md.MO))
ax.xaxis.set_minor_locator(md.DayLocator())
ax.xaxis.set_major_formatter(md.DateFormatter('%d %b %Y'))
Beispiel #33
0
qrvo_returns = np.diff(qrvo)/qrvo[:-1]

# smooth
smooth_avgo = np.convolve(weights/weights.sum(), avgo_returns)[N-1:-N+1]
smooth_qrvo = np.convolve(weights/weights.sum(), qrvo_returns)[N-1:-N+1]

t = np.arange(N-1, len(avgo_returns))

plot(t, avgo_returns[N-1:], lw = 1.0)
plot(t, smooth_avgo, lw=2.0)
plot(t, qrvo_returns[N-1:], lw = 1.0)
plot(t, smooth_qrvo, lw = 2.0)
show()

K = 3
poly_avgo = np.polyfit(t, smooth_avgo, K)
poly_qrvo = np.polyfit(t, smooth_qrvo, K)

poly_sub = np.polysub(poly_avgo, poly_qrvo)

xpoints = np.roots(poly_sub)
print("Intersection points {0}".format(xpoints))

reals = np.isreal(xpoints)
print("Real number? {0}".format(reals))

xpoints = np.select([reals], [xpoints])
xpoints = xpoints.real
print("Real intersection points {0}".format(xpoints))

print("Sans 0s {0}".format(np.trim_zeros(xpoints)))
Beispiel #34
0
def residuez(b, a, tol=1e-3, rtype='avg'):
    """Compute partial-fraction expansion of b(z) / a(z).

    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
    --------
    invresz, poly, polyval, unique_roots

    """
    b, a = map(asarray, (b, a))
    gain = a[0]
    brev, arev = b[::-1], a[::-1]
    krev, brev = polydiv(brev, arev)
    if krev == []:
        k = []
    else:
        k = krev[::-1]
    b = brev[::-1]
    p = roots(a)
    r = p * 0.0
    pout, mult = unique_roots(p, tol=tol, rtype=rtype)
    p = []
    for n in range(len(pout)):
        p.extend([pout[n]] * mult[n])
    p = asarray(p)
    # Compute the residue from the general formula (for discrete-time)
    #  the polynomial is in z**(-1) and the multiplication is by terms
    #  like this (1-p[i] z**(-1))**mult[i].  After differentiation,
    #  we must divide by (-p[i])**(m-k) as well as (m-k)!
    indx = 0
    for n in range(len(pout)):
        bn = brev.copy()
        pn = []
        for l in range(len(pout)):
            if l != n:
                pn.extend([pout[l]] * mult[l])
        an = atleast_1d(poly(pn))[::-1]
        # bn(z) / an(z) is (1-po[n] z**(-1))**Nn * b(z) / a(z) where Nn is
        # multiplicity of pole at po[n] and b(z) and a(z) are polynomials.
        sig = mult[n]
        for m in range(sig, 0, -1):
            if sig > m:
                # compute next derivative of bn(s) / an(s)
                term1 = polymul(polyder(bn, 1), an)
                term2 = polymul(bn, polyder(an, 1))
                bn = polysub(term1, term2)
                an = polymul(an, an)
            r[indx + m -
              1] = (polyval(bn, 1.0 / pout[n]) / polyval(an, 1.0 / pout[n]) /
                    factorial(sig - m) / (-pout[n])**(sig - m))
        indx += sig
    return r / gain, p, k
#for n=even
E = np.array([1])
for root in np.roots(EnE):
    if np.real(root) < 0:
        #print(root)
        E = np.polymul(E, np.array([1, -1 * root]))
E = np.real(E)
#print(E)

#zout = (1-p)/(1+p)
zout = (1 + p) / (1 - p)
t = np.sqrt(1 / zout)
pc = 2 / (t + 1 / t)

MnM = np.polysub(EnE, (pc**2) * PnP)
M = np.array([1])
for root in np.roots(MnM):
    if np.real(root) < 0:
        #print(root)
        M = np.polymul(M, np.array([1, -1 * root]))
M = np.real(M)

# #Form X1o for n=even
# Ee=np.copy(E)
# Eo=np.copy(E)
# Fe=np.copy(F)
# Fo=np.copy(F)
# for i in range(len(Ee)):
#     if i%2==0:
#         Eo[i]=0
Beispiel #36
0
    def fly(self, point, isDebug):
        global drone
        begin, end = False, False  #是否截止点
        step, total = 0, len(point) - 1  #计算飞行步数,当前步数
        print("预计飞行[%d]次航程" % total)
        #起始向量,飞机头向下
        startDirection = np.polyadd([0, 0], [0, 1])
        if (len(point) > 0):
            lastPoint = point[0]
            for i in range(len(point)):
                step += 1
                p = point[i]
                if p == lastPoint:
                    #第一步 连接ssid,飞机起飞,上升0.5m
                    begin = True
                    if (not isDebug):
                        if drone is None:
                            self.connect()
                        self.takeOff()
                        self.setSpeed()
                    # self.moveUp()
                    startVector = startDirection
                    toVector = np.polysub(point[i + 1], p)
                    rotate = self.cal_rotate(startVector, toVector)
                    distance = self.cal_distance(toVector)
                    cw_or_ccw = self.cal_cw_or_ccw(startVector, toVector)
                elif p == point[len(point) - 1]:
                    #最后一步,降落
                    end = True
                    toVector = startDirection
                    startVector = np.polysub(p, point[i - 1])
                    rotate = self.cal_rotate(startVector, toVector)
                    cw_or_ccw = self.cal_cw_or_ccw(startVector, toVector)
                    distance = 0
                else:
                    startVector = np.polysub(p, lastPoint)
                    toVector = np.polysub(point[i + 1], p)
                    rotate = self.cal_rotate(startVector, toVector)
                    distance = self.cal_distance(toVector)
                    cw_or_ccw = self.cal_cw_or_ccw(startVector, toVector)
                    pass
                lastPoint = p
                self.printRotateAndDistance(cw_or_ccw, distance, rotate, step,
                                            total)
                #实际飞行距离=像素坐标距离*比例尺
                distance = distance * GlobalConfig.ratio()
                print("[warning]actual fly distance:%f" % distance)
                #debug模式不飞行
                if not isDebug:
                    if cw_or_ccw > 0:
                        #顺时针
                        self.rotateCw(rotate)
                    else:
                        #逆时针
                        self.rotateCcw(rotate)
                    #前行
                    self.move_forward(distance)
                    if end:
                        self.land()

        else:
            #没有打点
            print('no point error')
Beispiel #37
0
def _poly_iw_mag1_crossing(num_iw, den_iw, epsw):
    # Return w where |H(iw)| == 1, |num(iw)| - |den(iw)| == 0
    w = np.roots(np.polysub(_poly_iw_sqr(num_iw), _poly_iw_sqr(den_iw)))
    w = np.real(w[np.isreal(w)])
    w = w[w > epsw]
    return w
Beispiel #38
0
def residue(b, a, tol=1e-3, rtype='avg'):
    """
    Compute partial-fraction expansion of b(s) / a(s).

    If ``M = len(b)`` and ``N = len(a)``, then the partial-fraction
    expansion H(s) is defined as::

              b(s)     b[0] s**(M-1) + b[1] s**(M-2) + ... + b[M-1]
      H(s) = ------ = ----------------------------------------------
              a(s)     a[0] s**(N-1) + a[1] s**(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 together than `tol`), then H(s)
    has terms like::

            r[i]      r[i+1]              r[i+n-1]
          -------- + ----------- + ... + -----------
          (s-p[i])  (s-p[i])**2          (s-p[i])**n

    Returns
    -------
    r : ndarray
        Residues.
    p : ndarray
        Poles.
    k : ndarray
        Coefficients of the direct polynomial term.

    See Also
    --------
    invres, numpy.poly, unique_roots

    """

    b, a = map(asarray, (b, a))
    rscale = a[0]
    k, b = polydiv(b, a)
    p = roots(a)
    r = p * 0.0
    pout, mult = unique_roots(p, tol=tol, rtype=rtype)
    p = []
    for n in range(len(pout)):
        p.extend([pout[n]] * mult[n])
    p = asarray(p)
    # Compute the residue from the general formula
    indx = 0
    for n in range(len(pout)):
        bn = b.copy()
        pn = []
        for l in range(len(pout)):
            if l != n:
                pn.extend([pout[l]] * mult[l])
        an = atleast_1d(poly(pn))
        # bn(s) / an(s) is (s-po[n])**Nn * b(s) / a(s) where Nn is
        # multiplicity of pole at po[n]
        sig = mult[n]
        for m in range(sig, 0, -1):
            if sig > m:
                # compute next derivative of bn(s) / an(s)
                term1 = polymul(polyder(bn, 1), an)
                term2 = polymul(bn, polyder(an, 1))
                bn = polysub(term1, term2)
                an = polymul(an, an)
            r[indx + m - 1] = polyval(bn, pout[n]) / polyval(an, pout[n]) \
                          / factorial(sig - m)
        indx += sig
    return r / rscale, p, k
from numpy import polyadd, polysub

coeficientes_pol1 = [3, 2, -1]  # Define o polinomio 3x**2 + 2x - 1\n"
coeficientes_pol2 = [4, -1, 3]  # Define polinômio 4x**2 - x + 3\n"

# Adição de polinômios
resultado = polyadd(coeficientes_pol1, coeficientes_pol2)
print("Coeficientes do resultado da soma entre")
print(f"3x**2x - 2x -1 e 4x**2 - x + 3 é {resultado}")

# Subtração de polinômios
coeficientes_pol1 = [3, -2, -1]  # Define o polinomio 3x**2 - 2x + 1\n",
coeficientes_pol2 = [-2, 0, 4]  # Define polinômio -2x**2 + 4\n",
resultado = polysub(coeficientes_pol1, coeficientes_pol2)
print("Coeficientes do resultado da subtracao entre")
print(f"3x**2 - 2x + 1 e - 2x**2 + 4 é {resultado}")
Beispiel #40
0
def residuez(b,a,tol=1e-3,rtype='avg'):
    """Compute partial-fraction expansion of b(z) / a(z).

    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:  invresz, poly, polyval, unique_roots
    """
    b,a = map(asarray,(b,a))
    gain = a[0]
    brev, arev = b[::-1],a[::-1]
    krev,brev = polydiv(brev,arev)
    if krev == []:
        k = []
    else:
        k = krev[::-1]
    b = brev[::-1]
    p = roots(a)
    r = p*0.0
    pout, mult = unique_roots(p,tol=tol,rtype=rtype)
    p = []
    for n in range(len(pout)):
        p.extend([pout[n]]*mult[n])
    p = asarray(p)
    # Compute the residue from the general formula (for discrete-time)
    #  the polynomial is in z**(-1) and the multiplication is by terms
    #  like this (1-p[i] z**(-1))**mult[i].  After differentiation,
    #  we must divide by (-p[i])**(m-k) as well as (m-k)!
    indx = 0
    for n in range(len(pout)):
        bn = brev.copy()
        pn = []
        for l in range(len(pout)):
            if l != n:
                pn.extend([pout[l]]*mult[l])
        an = atleast_1d(poly(pn))[::-1]
        # bn(z) / an(z) is (1-po[n] z**(-1))**Nn * b(z) / a(z) where Nn is
        # multiplicity of pole at po[n] and b(z) and a(z) are polynomials.
        sig = mult[n]
        for m in range(sig,0,-1):
            if sig > m:
                # compute next derivative of bn(s) / an(s)
                term1 = polymul(polyder(bn,1),an)
                term2 = polymul(bn,polyder(an,1))
                bn = polysub(term1,term2)
                an = polymul(an,an)
            r[indx+m-1] = polyval(bn,1.0/pout[n]) / polyval(an,1.0/pout[n]) \
                          / factorial(sig-m) / (-pout[n])**(sig-m)
        indx += sig
    return r/gain, p, k
Beispiel #41
0
 def __sub__(self, other):
     return Polynomial(np.polysub(self.coefficients[::-1], other.coefficients[::-1])[::-1])