Пример #1
0
    def plot(self, U, V, ctr):
        X1 = arange(min(U) - 2, max(U) + 2, 0.1)
        x = [1]
        for i in range(len(U)):
            x = P.polymul(x, [-1 * U[i], 1])
        plt.axis([-10, 10, min(V) - 1, max(V) + 1])
        b = [0]
        for i in range(len(U)):
            a = P.polydiv(x, [-1 * U[i], 1])
            b = P.polyadd(
                P.polymul((P.polydiv(a[0], P.polyval(U[i], a[0])))[0], [V[i]]),
                b)
            Y = P.polyval(
                X1,
                P.polymul((P.polydiv(a[0], P.polyval(U[i], a[0])))[0], [V[i]]))
            plt.plot(X1, Y, 'y')
        plt.plot(U, V, 'ro')
        X1 = arange(-5, 5, 0.1)
        Y = P.polyval(X1, b)
        plt.plot(X1, Y, 'b', label='Required Polynomial')
        plt.plot((-8, 8), (0, 0), 'k')

        plt.grid(b=True, which='both', color='0.65', linestyle='-')
        Y = list(Y)
        plt.plot((0, 0), (-max(Y) - 5, max(Y) + 5), 'k')
        plt.xlabel('x-axis')
        plt.ylabel('y-axis')
        plt.legend(loc=1)
        filename = "this_plot" + str(ctr) + ".png"
        path = "C:\\Users\HP\Anaconda3\static"
        fullpath = os.path.join(path, filename)
        plt.savefig(fullpath)
Пример #2
0
def chuck(samplerate, sig, shift_hz=1000):
    rc_imag = [
        allpass(samplerate, rc)
        for rc in [5.49e-06, 4.75e-05, 2.37e-04, 1.27e-03]
    ]
    rc_real = [
        allpass(samplerate, rc)
        for rc in [2.00e-05, 1.07e-04, 5.36e-04, 4.64e-03]
    ]

    sos_imag = [
        signal.tf2sos(
            polynomial.polymul(rc1[0], rc2[0]),
            polynomial.polymul(rc1[1], rc2[1]),
        )[0] for rc1, rc2 in zip(rc_imag[::2], rc_imag[1::2])
    ]

    sos_real = [
        signal.tf2sos(
            polynomial.polymul(rc1[0], rc2[0]),
            polynomial.polymul(rc1[1], rc2[1]),
        )[0] for rc1, rc2 in zip(rc_real[::2], rc_real[1::2])
    ]

    # plot_response(sys._getframe().f_code.co_name, sos_real, sos_imag)

    real = signal.sosfilt(sos_real, sig)
    imag = signal.sosfilt(sos_imag, sig)

    analytic = 0.5 * (real - 1j * imag)
    return pitch_shift(samplerate, analytic, shift_hz)
Пример #3
0
def getEpsrNumDen(Mat_pol, N_true_poles):
    ## create num and den
    list_num, list_den = [], []
    for k in range(2 * N_true_poles):
        list_num.append((Mat_pol[1, k]))
        list_den.append((-Mat_pol[2, k], 1.))
    den = (1)
    for k in range(2 * N_true_poles):
        den = poly.polymul(den, list_den[k])
    inter = []
    pinter = (1)
    for k1 in range(2 * N_true_poles):
        pinter = list_num[k1]
        for k2 in range(2 * N_true_poles):
            if (k1 != k2):
                pinter = poly.polymul(pinter, list_den[k2])
        inter.append(pinter)
    num = inter[0]
    for k in range(1, 2 * N_true_poles):
        num = poly.polyadd(num, inter[k])
    for k in range(len(num)):
        num[k] /= (1j)**k
    for k in range(len(den)):
        den[k] /= (1j)**k
    num, den = num.real, den.real
    # np.savetxt('text_num.out', num, delimiter=',')
    # np.savetxt('text_den.out', den, delimiter=',')
    num = poly.polyadd(num, den)
    w2 = (0., 0., -1.)
    num2 = poly.polymul(w2, num)
    # print_w2_chi(num2,den)
    # dnum2, dden = get_der_rational(num2,den)
    return (num, den, num2)
def get_extended_cycle(p, n, extender):
    newp = p**n - 1
    a = [0, 1]
    curr = [0, 1]

    alphas = {0: [1], 1: a}

    for x in range(2, n):
        curr = pol.polymul(curr, a)
        alphas[x] = list(map(int, curr))

    curr = list(map(lambda x: -x % p, extender[:-1]))
    curr = trim(curr)
    alphas[n] = curr

    for x in range(n + 1, newp):
        curr = pol.polymul(curr, a)
        while (len(curr) > n):
            nam = int(curr[-1] % p)
            curr = list(
                map(
                    lambda x: int(x) % p,
                    pol.polyadd(
                        list(map(lambda x: x * nam, alphas[len(curr) - 1])),
                        curr[:-1])))
        curr = list(map(lambda x: int(x) % p, curr))
        alphas[x] = list(map(int, curr))

    return (alphas)
 def plot(self,U,V,ctr):
     X1=arange(min(U)-2,max(U)+2,0.1)
     x=[1]
     for i in range(len(U)):
         x=P.polymul(x,[-1*U[i],1])
     plt.axis([-10,10,min(V)-1,max(V)+1])
     b=[0]
     for i in range(len(U)):
         a=P.polydiv(x,[-1*U[i],1])
         b=P.polyadd(P.polymul((P.polydiv(a[0],P.polyval(U[i],a[0])))[0],[V[i]]),b)
         Y=P.polyval(X1,P.polymul((P.polydiv(a[0],P.polyval(U[i],a[0])))[0],[V[i]]))
         plt.plot(X1,Y,'y')
     plt.plot(U,V,'ro')
     X1=arange(-5,5,0.1)
     Y=P.polyval(X1,b)
     plt.plot(X1,Y,'b',label='Required Polynomial')
     plt.plot((-8,8),(0,0),'k')
     
     plt.grid(b=True, which='both', color='0.65',linestyle='-')
     Y=list(Y)
     plt.plot((0,0),(-max(Y)-5,max(Y)+5),'k')
     plt.xlabel('x-axis')
     plt.ylabel('y-axis')
     plt.legend(loc=1)
     filename = "this_plot"+str(ctr)+".png"
     path = "C:\\Users\HP\Anaconda3\static"
     fullpath = os.path.join(path, filename)
     plt.savefig(fullpath)
Пример #6
0
def get_der_rational(num, den):
    dnum = poly.polyder(num)
    dden = poly.polyder(den)
    dnum_den = poly.polymul(dnum, den)
    dden_num = poly.polymul(num, dden)
    num_new = poly.polysub(dnum_den, dden_num)
    den_new = poly.polymul(den, den)
    return (num_new, den_new)
Пример #7
0
def gram_schmidt(A):
    n = A.shape[1]  # numero de vectores columna
    for j in range(n):
        for k in range(j):
            #A[:, j] -= np.dot(A[:, k], A[:, j]) * A[:, k]
            A[:, j] -= quad(P.polymul(A[:, k], A[:, j]), -1, 1) * A[:, k]
        A[:, j] = A[:, j] / quad(P.polymul(A[:, j], A[:, j]), -1, 1)
    return A
Пример #8
0
def test_coeff_convert():
    """Test the function convertion from factored coeffs to end coeffs."""
    assert np.allclose(fcoeffs2coeffs(np.array([1.0, 2, 1, 1])),
                       P.polymul([1, 1, 2], [1, 1]))
    assert np.allclose(fcoeffs2coeffs(np.array([1.0, 2, 1.2])),
                       P.polymul([1, 1, 2], 1.2))
    assert np.allclose(fcoeffs2coeffs(np.array([1.0, 2])), P.polymul([1, 1],
                                                                     2))
Пример #9
0
def egcd(a, b, p):
    x,y, u,v = np.array([0]),np.array([1]), np.array([1]),np.array([0])
    while not np.all(a == 0):
        q, r = P.polydiv(b,a)[0]%p, P.polydiv(b, a)[1]%p
        print(q,r)
        m, n = (x-P.polymul(u, q))%p, (y-P.polymul(v,q))%p
        b,a, x,y, u,v = a,r, u,v, m,n
    gcd = b
    return gcd, x, y
Пример #10
0
def test_fcoeffs2coeffs():
    """Test the function expanding factored polynomials"""
    assert np.allclose(
        fcoeffs2coeffs(np.array([1.0, 2, 1, 1])), P.polymul([1, 1, 2], [1, 1])
    )
    assert np.allclose(
        fcoeffs2coeffs(np.array([1.0, 2, 1.2])), P.polymul([1, 1, 2], 1.2)
    )
    assert np.allclose(fcoeffs2coeffs(np.array([1.0, 2])), P.polymul([1, 1], 2))
Пример #11
0
def ButterworthD2(N, w, Ts):
    Nr = int(N / 2)
    a = np.array(myPoli.num(2 * Nr)) * Ts**(2 * Nr) * w**N
    b = np.array(myPoli.polynomialMultiplier(N, Nr))
    if N % 2 == 1:
        n = [w * Ts + 2, w * Ts - 2]
        d = [w * Ts, w * Ts]
        b = poly.polymul(b, n)
        a = poly.polymul(a, d)
    print a, b
Пример #12
0
def d2d(b, a, T):
    nb = len(b)
    na = len(a)
    b_new = _polytustin(b, T)
    a_new = _polytustin(a, T)
    if nb > na:
        a_new = polymul(a_new, polypow([1, (T - 1) / (T + 1)], nb - na))
    elif na > nb:
        b_new = polymul(b_new, polypow([1, (T - 1) / (T + 1)], na - nb))
    return b_new / a_new[0], a_new / a_new[0]
Пример #13
0
def calculate_rst(b_minus,
                  b_plus,
                  a_minus,
                  a_plus,
                  a_m,
                  a0=np.ones(1),
                  d=1,
                  p=0,
                  r_e=0):
    """Calculate the coefficient of the rst"""
    perturbation = P.polypow(zero(1), p)
    s2, r0 = solve_diophantine(P.polymul(perturbation, a_minus),
                               P.polymul(delay(d), b_minus),
                               P.polymul(a_m, a0))
    b_m_plus, _ = solve_diophantine(P.polymul(delay(d), b_minus),
                                    P.polypow(zero(1), r_e + 1), a_m)
    t0 = P.polymul(a0, b_m_plus)
    r = P.polymul(r0, a_plus)
    s = P.polymul(s2, P.polymul(b_plus, perturbation))
    t = P.polymul(t0, a_plus)

    print("R = ", ", ".join(map(str, r)))
    print("S = ", ", ".join(map(str, s)))
    print("T = ", ", ".join(map(str, t)))

    return r, s, t
Пример #14
0
def PolyGCD(a: numpy.array, b: numpy.array):
    """Iterative Greatest Common Divisor  for polynomial"""

    # if len(a) < len(b):
    #     a, b = b, a
    x, xt, y, yt = (1, ), (0, ), (0, ), (1, )
    while any(num != 0.0 for num in b):
        q = polydiv(a, b)[0]
        a, b = b, polydiv(a, b)[1]
        x, xt = xt, polysub(x, polymul(xt, q))
        y, yt = yt, polysub(y, polymul(yt, q))
    return a, x, y
Пример #15
0
def ButterworthC(N, w, Ts):
    Nr = int(N / 2)
    i = 1j
    a = [w**N]
    b = [1]
    # print poly.polymul(a,b)
    for k in range(1, Nr + 1):
        rad = np.pi * (2 * k - 1) / (2 * N)
        n = [1, 2 * w * np.sin(rad), w**2]
        b = poly.polymul(b, n)
    if N % 2 == 1:
        b = poly.polymul(b, [1, w])
    print a, b
    def root_finding_poly(self):
        """
        R = p^2 - (1 - x^2) * q^2

        Returns
        -------
        coef : np.ndarray
            Coefficients of a root-finding polynomial `R(x)`. Every zero of
            the `PseudoPolynomial` is also a zero of `R(x)`.
        """
        return remove_zeros(pol.polysub(pol.polymul(self.p, self.p),
                                        pol.polymul(pol.polymul(self.q, self.q),
                                                    (1, 0, -1))))
Пример #17
0
def plot(points):

    s, X, F = points[:], [], []
    while (s != ''):
        i = s.index('(')
        j = s.index(',', i)
        X.append(float(s[i + 1:j]))
        k = s.index(')', j)
        F.append(float(s[j + 1:k]))
        s = s[k + 2:]

    fig = plt.figure()
    plt.clf()
    sub = fig.add_subplot(111)
    X1 = np.arange(min(X) - 2, max(X) + 2, 0.1)
    num_plots = len(X)
    colormap = plt.cm.gist_ncar
    plt.gca().set_color_cycle(
        [colormap(i) for i in np.linspace(0.2, 0.9, num_plots)])
    x = [1.0]
    for i in range(len(X)):
        x = P.polymul(x, [-1 * X[i], 1])
    b = [0.0]
    for i in range(len(X)):
        a = P.polydiv(x, [-1 * X[i], 1])
        b = P.polyadd(
            P.polymul((P.polydiv(a[0], P.polyval(X[i], a[0])))[0], [F[i]]), b)
        Y = P.polyval(
            X1, P.polymul((P.polydiv(a[0], P.polyval(X[i], a[0])))[0], [F[i]]))
        sub.plot(X1, Y)

    Y = P.polyval(X1, b)
    Y1 = P.polyval(np.arange(min(X), max(X) + 0.1, 0.1), b)
    interpol_obj = sub.plot(X1, Y, 'k', linewidth=2)
    sub.plot(X, F, 'ro', markersize=8)

    plt.grid(True)
    fig.legend(interpol_obj, ['Interpolating Polynomial'],
               fancybox=True,
               shadow=True,
               loc='upper left')
    plt.axis([min(X) - 3, max(X) + 3, min(Y1) - 2, max(Y1) + 2])
    plt.xlabel('x axis')
    plt.ylabel('y axis')
    plt.title('Interpolate')
    canvas = FigureCanvas(fig)
    output = StringIO.StringIO()
    canvas.print_png(output)
    response = make_response(output.getvalue())
    response.mimetype = 'image/png'
    return response
Пример #18
0
 def get_poly(n):
     if n > len(Bessel.polynomials):
         if n == 1:
             Bessel.polynomials.append(Polynomial(coef=[1, 1]))
         elif n == 2:
             Bessel.polynomials.append(Polynomial(coef=[3, 3, 1]))
         else:
             b_n_2 = poly.polymul(Polynomial(coef=[0, 0, 1]),
                                  Bessel.get_poly(n - 2))
             b_n_1 = poly.polymul(Polynomial(coef=[2 * n - 1]),
                                  Bessel.get_poly(n - 1))
             b_n = poly.polyadd(b_n_1, b_n_2)
             Bessel.polynomials.append(b_n[0])
     return Bessel.polynomials[n - 1]
Пример #19
0
def test_pseudopoly_multiplication(A, r, rseed=42):
    # float * polynomial
    poly = random_polynomial(2, 3, r=r, rseed=rseed)
    poly2 = PseudoPolynomial(A * poly.p, A * poly.q, r=r)

    assert A * poly == poly2
    assert poly * A == poly2

    # polynomial * pseudopoly
    A = [1, 3, 2, 4]
    result = PseudoPolynomial(p=pol.polymul(A, poly.p),
                              q=pol.polymul(A, poly.q),
                              r=poly.r)
    assert A * poly == result
    assert poly * A == result
def fast_power_poly(base, power, r, Z_n):
    result = 1
    while power > 0:
        # If power is even
        if power % 2 == 0:
            # Divide the power by 2
            power = power / 2
            # Multiply base to itself
            base = P.polymul(base, base)
            #base = P.polydiv(square, modulus)[1]
            # base = base mod (x^r-1)
            x = np.nonzero(result)[0]
            for i in x[x>=r]:
                if base[i] != 0:
                    base[i % r] += base[i]
                    base[i] = 0
            # Keep the coefficients in Z_n
            base = base % Z_n
        else:
            # Decrement the power by 1 and make it even
            power = power - 1
            # Take care of the extra value that we took out
            # We will store it directly in result
            result = P.polymul(result, base)
            #result = P.polydiv(mult, modulus)[1]
            #print(np.nonzero(result))
            x = np.nonzero(result)[0]
            for i in x[x>=r]:
                #print(i)
                if result[i] != 0:
                    result[i % r] += result[i]
                    result[i] = 0
            # Keep the coefficients in Z_n
            result = result % Z_n

            # Now power is even, so we can follow our previous procedure
            power = power / 2
            base = P.polymul(base, base)
            #base = P.polydiv(square, modulus)[1]
            x = np.nonzero(result)[0]
            for i in x[x>=r]:
                if base[i] != 0:
                    base[i % r] += base[i]
                    base[i] = 0
            # Keep the coefficients in Z_n
            base = base % Z_n

    return result
Пример #21
0
def negPNX(n):
    if n == 1:
        return (1)
    if n < 1:
        return
    if n in negPNXDict:
        return negPNXDict[n]
    first = P.polymul((3, 2 * n - 4), negPNX(n - 1))
    second = P.polymul((0, 4), (1, -1))
    deriv = P.polyder(negPNX(n - 1))
    second = P.polymul(second, deriv)
    third = posPNX(n - 1)
    ret = P.polyadd(first, second)
    ret = P.polyadd(ret, third)
    negPNXDict[n] = ret
    return ret
Пример #22
0
def polynomials_mult(x, y, mod, poly_mod):
    return np.int64(
        np.round(
            poly.polydiv(
                poly.polymul(x, y) % mod,
                poly_mod
            )[1] % mod))
Пример #23
0
def evaluate_keygen_v1(sk, size, modulus, T, poly_mod, std2):
    """Generate a relinearization key using version 1.
        Args:
            sk: secret key.
            size: size of the polynomials.
            modulus: coefficient modulus.
            T: base.
            poly_mod: polynomial modulus.
            std2: standard deviation for the error distribution.
        Returns:
            rlk0, rlk1: relinearization key.
        """
    n = len(poly_mod) - 1
    l = np.int(np.log(modulus) / np.log(T))
    rlk0 = np.zeros((l + 1, n), dtype=np.int64)
    rlk1 = np.zeros((l + 1, n), dtype=np.int64)
    for i in range(l + 1):
        a = gen_uniform_poly(size, modulus)
        e = gen_normal_poly(size, 0, std2)
        secret_part = T**i * poly.polymul(sk, sk)
        b = np.int64(
            polyadd(polymul_wm(-a, sk, poly_mod),
                    polyadd_wm(-e, secret_part, poly_mod), modulus, poly_mod))

        b = np.int64(np.concatenate((b, [0] * (n - len(b)))))  # pad b
        a = np.int64(np.concatenate((a, [0] * (n - len(a)))))  # pad a

        rlk0[i] = b
        rlk1[i] = a
    return rlk0, rlk1
Пример #24
0
def posPNX(n):
    if n == 1:
        return (1)
    if n < 1:
        return
    if n in posPNXDict:
        return posPNXDict[n]
    first = P.polymul((1, 2 * n - 2), posPNX(n - 1))
    second = P.polymul((0, 4), (1, -1))
    deriv = P.polyder(posPNX(n - 1))
    second = P.polymul(second, deriv)
    third = P.polymul((0, 1), (negPNX(n - 1)))
    ret = P.polyadd(first, second)
    ret = P.polyadd(ret, third)
    posPNXDict[n] = ret
    return ret
Пример #25
0
    def Lagrange(L,M):                                                               
        polylist=[]
        n=len(L)                                                           
        w=(-1*L[0],1)                                                      
        for i in range(1,n):
            w=P.polymul(w,(-1*L[i],1))                                    
        result=array([0.0 for i in range(len(w)-1)])                    
        derivative=P.polyder(w)                                             
        for i in range(n):
            polylist.append((P.polydiv(w,(-1*L[i],1))[0]*M[i])/P.polyval(L[i],derivative))
            result+=polylist[-1]   

        polynomial=""                                                  
        for i in range(len(result)-1,0,-1):                                 
            if(result[i]!=0):
                if(result[i]>0 and i!=(len(result)-1)):
                    polynomial+=" + "+str(result[i])+"x^"+str(i)+" "
                elif(result[i]>0 and i==(len(result)-1)):
                    polynomial+=str(result[i])+"x^"+str(i)+" "
                else:
                    polynomial+=" - "+str(-1*result[i])+"x^"+str(i)+" "
        if(result[0]!=0):
            polynomial+=" + "+str(result[0]) if result[0]>0 else " - "+str(-1*result[0])
        plot(L,M,polylist,result)
        return (polynomial)
Пример #26
0
def poly_mul_mod(op1, op2, coeff_mod, poly_mod):
    """Multiply two polynomials and modulo every coefficient with coeff_mod.

    Args:
        op1 (list): First Polynomail (Multiplicand).
        op2 (list): Second Polynomail (Multiplier).

    Returns:
        A list with polynomial coefficients.
    """

    # For non same size polynomials we have to shift the polynomials because numpy consider right
    # side as lower order of polynomial and we consider right side as heigher order.
    if len(op1) != poly_mod:
        op1 += [0] * (poly_mod - len(op1))
    if len(op2) != poly_mod:
        op2 += [0] * (poly_mod - len(op2))

    poly_len = poly_mod
    poly_mod = np.array([1] + [0] * (poly_len - 1) + [1])
    result = (
        poly.polydiv(
            poly.polymul(np.array(op1, dtype="object"), np.array(op2, dtype="object")) % coeff_mod,
            poly_mod,
        )[1]
        % coeff_mod
    ).tolist()

    if len(result) != poly_len:
        result += [0] * (poly_len - len(result))

    return [round(x) for x in result]
Пример #27
0
def plot(points):

    s,X,F=points[:],[],[]
    while(s!=''):
        i=s.index('(')
        j=s.index(',',i)
        X.append(float(s[i+1:j]))
        k=s.index(')',j)
        F.append(float(s[j+1:k]))
        s=s[k+2:]

    fig=plt.figure()
    plt.clf()
    sub=fig.add_subplot(111)
    X1=np.arange(min(X)-2,max(X)+2,0.1)
    num_plots=len(X)
    colormap = plt.cm.gist_ncar
    plt.gca().set_color_cycle([colormap(i) for i in np.linspace(0.2, 0.9, num_plots)])
    x=[1.0]
    for i in range(len(X)):
        x=P.polymul(x,[-1*X[i],1])
    b=[0.0]
    for i in range(len(X)):
        a=P.polydiv(x,[-1*X[i],1])
        b=P.polyadd(P.polymul((P.polydiv(a[0],P.polyval(X[i],a[0])))[0],[F[i]]),b)
        Y=P.polyval(X1,P.polymul((P.polydiv(a[0],P.polyval(X[i],a[0])))[0],[F[i]]))
        sub.plot(X1,Y)

    Y=P.polyval(X1,b)
    Y1=P.polyval(np.arange(min(X)-0.1,max(X)+0.1,0.1),b)
    interpol_obj=sub.plot(X1,Y,'k',linewidth=2)
    sub.plot(X,F,'ro',markersize=8)

    plt.grid(True)
    fig.legend(interpol_obj,['Interpolating Polynomial'],fancybox=True,shadow=True,loc='upper left')
    plt.axis([min(X)-3,max(X)+3,min(Y1)-2,max(Y1)+2])
    plt.xlabel('x axis')
    plt.ylabel('y axis')
    plt.title('Interpolate')
    #plt.show()

    canvas = FigureCanvas(fig)
    output = StringIO.StringIO()
    canvas.print_png(output)
    response = make_response(output.getvalue())
    response.mimetype = 'image/png'
    return response
Пример #28
0
def extended_euclid_poly(a, b, p):
    """ Повертає d=НСД(x,y) і x, y такі, що ax + by = d """
    if np.all(b == 0):
        print ("b=0", a, b)
        return a, np.array([1]), np.array([0])
    d, x, y = extended_euclid_poly(b, P.polydiv(a, b)[1] % p, p)
    print (d, x, y)
    return d, y, (x - P.polymul(P.polydiv(a,b)[0], y)) % p
Пример #29
0
 def test_polymul(self):
     for i in range(5):
         for j in range(5):
             msg = "At i=%d, j=%d" % (i, j)
             tgt = np.zeros(i + j + 1)
             tgt[i + j] += 1
             res = poly.polymul([0] * i + [1], [0] * j + [1])
             assert_equal(trim(res), trim(tgt), err_msg=msg)
Пример #30
0
def n_k(order, coef_func):
    if order < 0:
        raise ValueError()
    if order == 0:
        return Polynomial([0, 1])
    elif order > 0:
        return pl.polymul(n_k(order - 1, coef_func),
                          Polynomial([coef_func(order), 1]))[0] / (order + 1)
def mult(a, b, type=1):
    kex_start = timeit.default_timer()
    if type == 1:
        c = p.polymul(a, b)
    else:
        c = np.fft.irfft(np.fft.rfft(a, 2 * n) * np.fft.rfft(b, 2 * n), 2 * n)
    kex_end = timeit.default_timer()
    return c, kex_end - kex_start
Пример #32
0
def polymul(a, b):
    """
    Multiply polynomial a by polynomial b.
    a and b are lists from highest order term to lowest.
    """
    val = polynomial.polymul(a[::-1], b[::-1])
    val = val[::-1]
    return val
Пример #33
0
 def test_polymul(self) :
     for i in range(5) :
         for j in range(5) :
             msg = "At i=%d, j=%d" % (i,j)
             tgt = np.zeros(i + j + 1)
             tgt[i + j] += 1
             res = poly.polymul([0]*i + [1], [0]*j + [1])
             assert_equal(trim(res), trim(tgt), err_msg=msg)
Пример #34
0
 def generalized_hankel_matrices(self, phis, pols):
     G  = np.zeros((len(phis), len(phis)), dtype=complex)
     G1 = np.zeros((len(phis), len(phis)), dtype=complex)
     prow = [monicPolynomial(npol.polymul(pols[1].coef, pols[j].coef), coef_type='normal').f_polynomial() for j in range(len(phis))]
     for i,j in itertools.product(range(len(phis)), range(len(phis))):
         G [i,j] = self.inner_prod(phis[i], phis[j])
         G1[i,j] = self.inner_prod(phis[i], prow[j])
     return G, G1
Пример #35
0
def interpolate(pointList):
    size = len(pointList)
    if len(pointList) == 1:
        return (fr(pointList[0][1]),)
    result = [fr(0)]
    for index_i in range(0, size):
        x_i = fr(pointList[index_i][0])
        y_i = fr(pointList[index_i][1])
        member = [y_i]
        for index_j in range(0, size):
            if index_i == index_j:
                continue
            x_j = fr(pointList[index_j][0])
            member = polymul(member, [-x_j, fr(1)])
            multiplier = [fr(1, x_i - x_j)]
            member = polymul(member, multiplier)
        result = polyadd(result, member)
    return result
Пример #36
0
def polymul_wm(x, y, poly_mod):
    """Multiply two polynomials
    Args:
        x, y: two polynomials to be multiplied.
        poly_mod: polynomial modulus.
    Returns:
        A polynomial in Z[X]/(poly_mod).
    """
    return poly.polydiv(poly.polymul(x, y), poly_mod)[1]
Пример #37
0
def mul(a, b, prime, exp, min0):
    a.reverse()
    b.reverse()
    min0.reverse()
    ans = []
    mul0 = poly.polymul(a, b)
    ans = poly.polydiv(mul0, min0)[1]
    ans = list(map(int, ans))
    ans.reverse()
    return ans
Пример #38
0
 def polycomp(c1, c2):
     """
     Compose two polynomials : c1 o c2 = c1(c2(x))
     The arguments are sequences of coefficients, from lowest order term to highest, e.g., [1,2,3] represents the polynomial 1 + 2*x + 3*x**2.
     """
     # TODO: Polynomial(Polynomial()) seems to do just that?
     # using Horner's method to compute the result of a polynomial
     cr = [c1[-1]]
     for a in reversed(c1[:-1]):
         # cr = cr * c2 + a 
         cr = polynomial.polyadd(polynomial.polymul(cr, c2), [a])
     
     return cr
Пример #39
0
    def evaluate(self, nodes, interval=None):
        """Computes weights for stored polynomial and given nodes.

        The weights are calculated with help of the Lagrange polynomials

        .. math::

            \\alpha_i = \\int_a^b\\omega (x) \\prod_{j=1,j \\neq i}^{n} \\frac{x-x_j}{x_i-x_j} \\mathrm{d}x

        See Also
        --------
        :py:meth:`.IWeightFunction.evaluate` : overridden method
        """
        super(PolynomialWeightFunction, self).evaluate(nodes, interval)

        a = self._interval[0]
        b = self._interval[1]

        n_nodes = nodes.size
        alpha = np.zeros(n_nodes)

        for j in range(n_nodes):
            selection = list(range(j))
            selection.extend(list(range(j + 1, n_nodes)))
            poly = [1.0]

            for ais in nodes[selection]:
                # builds Lagrange polynomial p_i
                poly = pol.polymul(poly, [ais / (ais - nodes[j]), 1 / (nodes[j] - ais)])

            # computes \int w(x)p_i dx
            poly = pol.polyint(pol.polymul(poly, self._coefficients))
            alpha[j] = pol.polyval(b, poly) - pol.polyval(a, poly)

        #LOG.debug("Computed polynomial weights for nodes {:s} in {:s}."
        #          .format(nodes, self._interval))
        del self._interval
        self._weights = alpha
        def Lagrange(self,A,B):

            from numpy import array
            from numpy.polynomial import polynomial as P
            n=len(A)
            w=(-1*A[0],1)
            for i in range(1,n):
                w=P.polymul(w,(-1*A[i],1))
            result=array([0.0 for i in range(len(w)-1)])
            derivative=P.polyder(w)
            for i in range(n):
                result+=(P.polydiv(w,(-1*A[i],1))[0]*B[i])/P.polyval(A[i],derivative)
            s=self.plot(list(result),A,B)
            return s
Пример #41
0
    def test_polydiv(self) :
        # check zero division
        assert_raises(ZeroDivisionError, poly.polydiv, [1], [0])

        # check scalar division
        quo, rem = poly.polydiv([2],[2])
        assert_equal((quo, rem), (1, 0))
        quo, rem = poly.polydiv([2,2],[2])
        assert_equal((quo, rem), ((1,1), 0))

        # check rest.
        for i in range(5) :
            for j in range(5) :
                msg = "At i=%d, j=%d" % (i,j)
                ci = [0]*i + [1,2]
                cj = [0]*j + [1,2]
                tgt = poly.polyadd(ci, cj)
                quo, rem = poly.polydiv(tgt, ci)
                res = poly.polyadd(poly.polymul(quo, ci), rem)
                assert_equal(res, tgt, err_msg=msg)
        def Newton(self,A,B):

            from numpy import array
            from numpy.polynomial import polynomial as P
            n=len(A)
            mat=[[0.0 for i in range(n)] for j in range(n)]
            for i in range(n):
                mat[i][0]=B[i]
            for i in range(1,n):
                for j in range(n-i):
                    mat[j][i]=(mat[j+1][i-1]-mat[j][i-1])/(A[j+i]-A[j])
            res=array((mat[0][0],))
            for i in range(1,n):
                prod=(-1*A[0],1)

                for j in range(1,i):
                    prod=P.polymul(prod,(-1*A[j],1))
                res=P.polyadd(res,array(prod)*mat[0][i])
            s=self.plot(list(res),A,B)
            return s
    def Lagrange(self,U,V):                                                
       
        
       
        n=len(U)                                                           
        w=(-1*U[0],1)                                                      
        for i in range(1,n):
            w=P.polymul(w,(-1*U[i],1))                                    
        result=array([0.0 for i in range(len(w)-1)])                    
        derivative=P.polyder(w)                                             
        for i in range(n):
            result+=(P.polydiv(w,(-1*U[i],1))[0]*V[i])/P.polyval(U[i],derivative)


        temp=list(result);
        cofficient=temp
        l=len(cofficient);
        temp=[];
        for i in range(l-1):
            temp.append(str(cofficient[l-(i+1)])+'x^'+str(l-(i+1))+str('+'))
        temp.append(str(cofficient[0])+'x^'+str(0));
        str1=''.join(temp)
        return(str1)   
Пример #44
0
def p389(dice):
    
    t=time.clock()
    
    probs={n:1/dice[0] for n in range (1,dice[0]+1)}
    ks=[n for n in range(1,dice[0]+1)]
    for n in dice[1:]:
        newWays={}
        p0=np.array([0.]+[1. for i in range(n)])/n
        pks=np.copy(p0)
        for k in ks: 
            if k>1:
                pks=P.polymul(p0,pks)
            for s in range(k,len(pks)):
                newWays[s]=newWays.get(s,0)+probs[k]*pks[s]
        probs.update(newWays)
        ks=sorted([k for k,v in probs.items()])
    
    EX=sum([k*prob for k,prob in probs.items()])
    EX2=sum([k**2*prob for k,prob in probs.items()])
    var=EX2-EX**2
    
    print(EX,var)
    print(time.clock()-t)
Пример #45
0
 def __mul__(self, other):
     if isinstance(other, Polynomial):
         result = polynomial.polymul(self._poly, other._poly)
     else:
         result = [0] * other + self._poly
     return Polynomial(poly=result)
Пример #46
0
def longitudinal(velocity, density, S_gross_w, mac, Cm_q, Cz_alpha, mass, Cm_alpha, Iy, Cm_alpha_dot, Cz_u, Cz_alpha_dot, Cz_q, Cw, Theta, Cx_u, Cx_alpha):
    """ output = SUAVE.Methods.Flight_Dynamics.Dynamic_Stablity.Full_Linearized_Equations.longitudinal(velocity, density, S_gross_w, mac, Cm_q, Cz_alpha, mass, Cm_alpha, Iy, Cm_alpha_dot, Cz_u, Cz_alpha_dot, Cz_q, Cw, Theta, Cx_u, Cx_alpha)
        Calculate the natural frequency and damping ratio for the full linearized short period and phugoid modes        
        
        Inputs:
            velocity - flight velocity at the condition being considered [meters/seconds]
            density - flight density at condition being considered [kg/meters**3]
            S_gross_w - area of the wing [meters**2]
            mac - mean aerodynamic chord of the wing [meters]
            Cm_q - coefficient for the change in pitching moment due to pitch rate [dimensionless] (2 * K * dC_m/di * lt/c where K is approximately 1.1)
            Cz_alpha - coefficient for the change in Z force due to the angle of attack [dimensionless] (-C_D - dC_L/dalpha)
            mass - mass of the aircraft [kilograms]
            Cm_alpha - coefficient for the change in pitching moment due to angle of attack [dimensionless] (dC_m/dC_L * dCL/dalpha)
            Iy - moment of interia about the body y axis [kg * meters**2]
            Cm_alpha_dot - coefficient for the change in pitching moment due to rate of change of angle of attack [dimensionless] (2 * dC_m/di * depsilon/dalpha * lt/mac)
            Cz_u - coefficient for the change in force in the Z direction due to change in forward velocity [dimensionless] (usually -2 C_L or -2C_L - U dC_L/du)
            Cz_alpha_dot - coefficient for the change of angle of attack caused by w_dot on the Z force [dimensionless] (2 * dC_m/di * depsilon/dalpha)
            Cz_q - coefficient for the change in Z force due to pitching velocity [dimensionless] (2 * K * dC_m/di where K is approximately 1.1)
            Cw - coefficient to account for gravity [dimensionless] (-C_L)
            Theta - angle between the horizontal axis and the body axis measured in the vertical plane [radians]
            Cx_u - coefficient for the change in force in the X direction due to change in the forward velocity [dimensionless] (-2C_D)
            Cx_alpha - coefficient for the change in force in the X direction due to the change in angle of attack caused by w [dimensionless] (C_L-dC_L/dalpha)
        
        Outputs:
            output - a data dictionary with fields:
                short_w_n - natural frequency of the short period mode [radian/second]
                short_zeta - damping ratio of the short period mode [dimensionless]
                phugoid_w_n - natural frequency of the short period mode [radian/second]
                phugoid_zeta - damping ratio of the short period mode [dimensionless]
            
        Assumptions:
            X-Z axis is plane of symmetry
            Constant mass of aircraft
            Origin of axis system at c.g. of aircraft
            Aircraft is a rigid body
            Earth is inertial reference frame
            Perturbations from equilibrium are small
            Flow is Quasisteady
            Zero initial conditions
            Cm_a = CF_z_a = CF_x_a = 0
            Neglect Cx_alpha_dot, Cx_q and Cm_u
            
        Source:
            J.H. Blakelock, "Automatic Control of Aircraft and Missiles" Wiley & Sons, Inc. New York, 1991, p 26-41.
    """ 
    
    #process
    
    # constructing matrix of coefficients
    A = (- Cx_u, mass * velocity / S_gross_w / (0.5*density*velocity**2.))  # X force U term
    B = (-Cx_alpha) # X force alpha term
    C = (-Cw * np.cos(Theta)) # X force theta term
    D = (-Cz_u) # Z force U term
    E = (-Cz_alpha, (mass*velocity/S_gross_w/(0.5*density*velocity**2.)-mac*0.5/velocity*Cz_alpha_dot)) # Z force alpha term
    F = (- Cw * np.sin(Theta), (-mass*velocity/S_gross_w/(0.5*density*velocity**2.)-mac*0.5/velocity*Cz_q))# Z force theta term
    G = (0.) # M moment U term
    H = (-Cm_alpha, -mac*0.5/velocity*Cm_alpha_dot) # M moment alpha term
    I = (0., - mac*0.5/velocity*Cm_q, Iy/S_gross_w/(0.5*density*velocity**2)/mac) # M moment theta term
    
    # Taking the determinant of the matrix ([A, B, C],[D, E, F],[G, H, I])
    EI = P.polymul(E,I)
    FH = P.polymul(F,H)
    part1 = P.polymul(A,P.polysub(EI,FH))
    DI = P.polymul(D,I)
    FG = P.polymul(F,G)
    part2 = P.polymul(B,P.polysub(FG,DI))    
    DH = P.polymul(D,H)
    GE = P.polymul(G,E)
    part3 = P.polymul(C,P.polysub(DH,GE))
    total = P.polyadd(part1,P.polyadd(part2,part3))
    
    # Use Synthetic division to split polynomial into two quadratic factors
    poly = total / total[4]
    poly1 = poly * 1. 
    poly2 = poly * 1. 
    poly3 = poly * 1.
    poly4 = poly * 1.
    
    poly1[4] = poly[4] - poly[2]/poly[2]
    poly1[3] = poly[3] - poly[1]/poly[2]
    poly1[2] = poly[2] - poly[0]/poly[2]
    poly2[4] = 0
    poly2[3] = poly1[3] - poly[2]*poly1[3]/poly[2]
    poly2[2] = poly1[2] - poly[1]*poly1[3]/poly[2]
    poly2[1] = poly1[1] - poly[0]*poly1[3]/poly[2]
    
    poly3[4] = poly[4] - poly2[2]/poly2[2]
    poly3[3] = poly[3] - poly2[1]/poly2[2]
    poly3[2] = poly[2] - poly2[0]/poly2[2]
    poly4[3] = poly3[3] - poly2[2]*poly3[3]/poly2[2]
    poly4[2] = poly3[2] - poly2[1]*poly3[3]/poly2[2]
    poly4[1] = poly3[1] - poly2[0]*poly3[3]/poly2[2]
     
    # Generate natural frequency and damping for Short Period and Phugoid modes
    short_w_n = (poly4[2])**0.5
    short_zeta = poly3[3]*0.5/short_w_n
    phugoid_w_n = (poly2[0]/poly2[2])**0.5
    phugoid_zeta = poly2[1]/poly2[2]*0.5/phugoid_w_n
    
    output = Data()
    output.short_natural_frequency = short_w_n
    output.short_damping_ratio = short_zeta
    output.phugoid_natural_frequency = phugoid_w_n
    output.phugoid_damping_ratio = phugoid_zeta    
    
    return output
def lateral_directional(velocity, Cn_Beta, S_gross_w, density, span, I_z, Cn_r, I_x, Cl_p, J_xz, Cl_r, Cl_Beta, Cn_p, Cy_phi, Cy_psi, Cy_Beta, mass):
    """ output = SUAVE.Methods.Flight_Dynamics.Dynamic_Stablity.Full_Linearized_Equations.lateral_directional(velocity, Cn_Beta, S_gross_w, density, span, I_z, Cn_r, I_x, Cl_p, J_xz, Cl_r, Cl_Beta, Cn_p, Cy_phi, Cy_psi, Cy_Beta)
        Calculate the natural frequency and damping ratio for the full linearized dutch roll mode along with the time constants for the roll and spiral modes        
        Inputs:
            velocity - flight velocity at the condition being considered [meters/seconds]
            Cn_Beta - coefficient for change in yawing moment due to sideslip [dimensionless] (no simple relation)
            S_gross_w - area of the wing [meters**2]
            density - flight density at condition being considered [kg/meters**3]
            span - wing span of the aircraft [meters]
            I_z - moment of interia about the body z axis [kg * meters**2]
            Cn_r - coefficient for change in yawing moment due to yawing velocity [dimensionless] ( - C_D(wing)/4 - 2 * Sv/S * (l_v/b)**2 * (dC_L/dalpha)(vert) * eta(vert))
            I_x - moment of interia about the body x axis [kg * meters**2]
            Cl_p - change in rolling moment due to the rolling velocity [dimensionless] (no simple relation for calculation)
            J_xz - products of inertia in the x-z direction [kg * meters**2] (if X and Z lie in a plane of symmetry then equal to zero)
            Cl_r - coefficient for change in rolling moment due to yawing velocity [dimensionless] (Usually equals C_L(wing)/4)
            Cl_Beta - coefficient for change in rolling moment due to sideslip [dimensionless] 
            Cn_p - coefficient for the change in yawing moment due to rolling velocity [dimensionless] (-C_L(wing)/8*(1 - depsilon/dalpha)) (depsilon/dalpha = 2/pi/e/AspectRatio dC_L(wing)/dalpha)
            Cy_phi  - coefficient for change in sideforce due to aircraft roll [dimensionless] (Usually equals C_L)
            Cy_psi - coefficient to account for gravity [dimensionless] (C_L * tan(Theta))
            Cy_Beta - coefficient for change in Y force due to sideslip [dimensionless] (no simple relation)
            mass - mass of the aircraft [kilograms]
        
        Outputs:
            output - a data dictionary with fields:
                dutch_w_n - natural frequency of the dutch roll mode [radian/second]
                dutch_zeta - damping ratio of the dutch roll mode [dimensionless]
                roll_tau - approximation of the time constant of the roll mode of an aircraft [seconds] (positive values are bad)
                spiral_tau - time constant for the spiral mode [seconds] (positive values are bad)
            
        Assumptions:
            X-Z axis is plane of symmetry
            Constant mass of aircraft
            Origin of axis system at c.g. of aircraft
            Aircraft is a rigid body
            Earth is inertial reference frame
            Perturbations from equilibrium are small
            Flow is Quasisteady
            Zero initial conditions
            Neglect Cy_p and Cy_r
            
        Source:
            J.H. Blakelock, "Automatic Control of Aircraft and Missiles" Wiley & Sons, Inc. New York, 1991, p 118-124.
    """ 
    
    #process
    
    # constructing matrix of coefficients
    A = (0, -span * 0.5 / velocity * Cl_p, I_x/S_gross_w/(0.5*density*velocity**2)/span )  # L moment phi term
    B = (0, -span * 0.5 / velocity * Cl_r, -J_xz / S_gross_w / (0.5 * density * velocity ** 2.) / span) # L moment psi term
    C = (-Cl_Beta) # L moment Beta term
    D = (0, - span * 0.5 / velocity * Cn_p, -J_xz / S_gross_w / (0.5 * density * velocity ** 2.) / span ) # N moment phi term 
    E = (0, - span * 0.5 / velocity * Cn_r, I_z / S_gross_w / (0.5 * density * velocity ** 2.) / span ) # N moment psi term
    F = (-Cn_Beta) # N moment Beta term
    G = (-Cy_phi) # Y force phi term
    H = (-Cy_psi, mass * velocity / S_gross_w / (0.5 * density * velocity ** 2.))    
    I = (-Cy_Beta, mass * velocity / S_gross_w / (0.5 * density * velocity ** 2.))
    
    # Taking the determinant of the matrix ([A, B, C],[D, E, F],[G, H, I])
    EI = P.polymul(E,I)
    FH = P.polymul(F,H)
    part1 = P.polymul(A,P.polysub(EI,FH))
    DI = P.polymul(D,I)
    FG = P.polymul(F,G)
    part2 = P.polymul(B,P.polysub(FG,DI))    
    DH = P.polymul(D,H)
    GE = P.polymul(G,E)
    part3 = P.polymul(C,P.polysub(DH,GE))
    total = P.polyadd(part1,P.polyadd(part2,part3))
    poly = total / total[5]
    
    # Generate the time constant for the spiral and roll modes along with the damping and natural frequency for the dutch roll mode
    root = np.roots(poly)
    root = sorted(root,reverse=True)
    spiral_tau = 1 * root[0].real
    w_n = (root[1].imag**2 + root[1].real**2)**(-0.5)
    zeta = -2*root[1].real/w_n
    roll_tau = 1 * root [3].real
    
    output = Data()
    output.dutch_natural_frequency = w_n
    output.dutch_damping_ratio = zeta
    output.spiral_tau = spiral_tau
    output.roll_tau = roll_tau    
    
    return output
Пример #48
0
     p2 = obj.insertPol(gr1,p2)
     print "La suma es:"+str(npy.polyadd(p1,p2))
 elif op == 3:
     print "Resta"
     gr1 = input("Grado del polinomio 1")
     p1 = obj.insertPol(gr1,p1)
     gr1 = input("Grado del polinomio 2")
     p2 = obj.insertPol(gr1,p2)
     print "La resta es:"+str(npy.polysub(p1,p2))
 elif op == 4:
     print "Multiplicacion"
     gr1 = input("Grado del polinomio 1")
     p1 = obj.insertPol(gr1,p1)
     gr1 = input("Grado del polinomio 2")
     p2 = obj.insertPol(gr1,p2)
     print "La multiplicacion es:"+str(npy.polymul(p1,p2))
 elif op == 5:
     print "Igualdad"
     gr1 = input("Grado del polinomio 1")
     p1 = obj.insertPol(gr1,p1)
     gr1 = input("Grado del polinomio 2")
     p2 = obj.insertPol(gr1,p2)
 elif op == 6:
     print "Polinomio Opuesto"
     gr1 = input("Ingresa el grado del polinomio")
     p1 = obj.insertPol(gr1,p1)
     for i in range (0,len(p1)):
         p1[i]=-p1[i]
     print p1
 else:
     print "No es una opcion valida"
Пример #49
0
def polymul(c1, c2):
    from numpy.polynomial.polynomial import polymul
    return polymul(c1, c2)
Пример #50
0
		print "a",a
		print "b",b
		break

        # TESTING SUBTRACTION FUNCTION
	a=P.polysub(c1,c2).tolist()
	b=q.subPoly(c1,c2)
	if(a!=b):
		print "Failed on Case:"
		print "a subtract b"
		print "a",a
		print "b",b
		break

	# TESTING MULTIPLICATION FUNCTION	
	a=P.polymul(c1,c2).tolist()
	b=q.multPoly(c1,c2)
	if(a!=b):
		print "Failed on Case:"
		print "a * b"
		print "a",a
		print "b",b
		break
	
	# TESINGING DIVISION FUNCTION
	if q.trim(c2)==[0]:
		continue
	try:
		[a1,a2]=P.polydiv(c1,c2)
		a1=q.trim(a1.tolist())
		a2=q.trim(a2.tolist())