Esempio n. 1
0
    def gen_poly(self, n):
        self.order = n

        # zeroth polynomial
        self.poly = [nppoly.polyone]
        alpha = [self.get_alpha(self.poly[0])]
        beta = [1.]

        # first polynomial
        self.poly.append(nppoly.polymulx(self.poly[0]))
        self.poly[1] = nppoly.polyadd(self.poly[1], -alpha[0] * self.poly[0])
        alpha.append(self.get_alpha(self.poly[1]))
        beta.append(self.get_beta(self.poly[1], self.poly[0]))

        # reccurence relation for other polynomials
        for i in range(2, n + 1):
            p_i = nppoly.polymulx(self.poly[i - 1])
            p_i = nppoly.polyadd(p_i, -alpha[i - 1] * self.poly[i - 1])
            p_i = nppoly.polyadd(p_i, -beta[i - 1] * self.poly[i - 2])

            self.poly.append(p_i)

            alpha.append(self.get_alpha(self.poly[i]))
            beta.append(self.get_beta(self.poly[i], self.poly[i - 1]))

        # normalise polynomials
        for i in range(len(self.poly)):
            self.poly[i] = self.poly[i] / np.prod(beta[:i])

        # create Jacobi matrix
        self.jacobi = (np.diag(np.sqrt(beta[1:]), -1) + np.diag(alpha, 0) +
                       np.diag(np.sqrt(beta[1:]), 1))
Esempio n. 2
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)
Esempio n. 3
0
def poly_lagrange(px, py):
    tab_q = base_lagrange(px)
    rt = len(px)
    res = nppol.polyzero
    for h in range(rt):
        res = nppol.polyadd(res, py[h] * tab_q[h])
    return res
Esempio n. 4
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)
Esempio n. 5
0
def hermit_interpol_polynomial(nodes, f):
    def divided_difference(row, col):
        # row = j, col = i
        # Если знаменатель не ноль
        if nodes[row + col] != nodes[row]:
            return (dif_matrix[row + 1, col - 1] -
                    dif_matrix[row, col - 1]) / (nodes[row + col] - nodes[row])
        # Если знаменатель ноль
        else:
            deriv = derivative(f, col)
            return deriv(nodes[row]) / factorial(col)

    n = len(nodes)
    dif_matrix = np.zeros((n, n))

    for i in range(n):
        dif_matrix[i, 0] = f(nodes[i])

    for i in range(1, n):
        for j in range(0, n - i):
            dif_matrix[j, i] = divided_difference(j, i)

    result = Polynomial(dif_matrix[0, 0])

    for i in range(n - 1):
        result = pl.polyadd(
            result,
            Polynomial(np.poly(nodes[0:i + 1])[::-1]) *
            dif_matrix[0, i + 1])[0]

    return result, dif_matrix
Esempio n. 6
0
def newton_interpol_polynomial(nodes, f):
    n = len(nodes)
    dif_matrix = np.zeros((n, n))

    for i in range(n):
        dif_matrix[i, 0] = f(nodes[i])

    # Считаем разделённые разности. Храним их в верхнетреугольной матрице
    for i in range(1, n):
        for j in range(0, n - i):
            dif_matrix[j,
                       i] = (dif_matrix[j + 1, i - 1] -
                             dif_matrix[j, i - 1]) / (nodes[j + i] - nodes[j])

    # Строим интерпол. полином Ньютона, испоьзуя полученные разности
    result = Polynomial(dif_matrix[0, 0])

    for i in range(n - 1):
        result = pl.polyadd(
            result,
            Polynomial(np.poly(nodes[0:i + 1])[::-1]) *
            dif_matrix[0, i + 1])[0]

    # Помимо полинома возвращаем ещё и матрицу разностей, т.к. её, вообще говоря, можно использовать,
    # если мы захотим добавить ещё узлов интерполяции
    return result, dif_matrix
Esempio n. 7
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
Esempio n. 8
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
 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)
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 reshare(PORT, n, t, secret, polynom):
    HOST = ''
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((HOST, PORT))

    s.listen(n)

    i = 1
    prime = 7103

    coeffs = []
    for j in range(t):
        coeffs.append(random.randint(1, prime))
    coeffs.append(0)

    newpolynom = numpy.poly1d(polynomial.polyadd(polynom.c, coeffs))

    print "Old polynomial is: {0}x + {1}".format(int(polynom.c[0]),
                                                 int(polynom.c[1]))
    print "New polynomial is: {0}x + {1}".format(
        int(polynom.c[0]) + coeffs[0],
        int(polynom.c[1]) + coeffs[1])

    while i <= n:
        conn, addr = s.accept()
        conn.sendall(str(i))
        time.sleep(0.1)
        conn.sendall(str(int(newpolynom(i))))
        time.sleep(0.1)
        conn.close()
        i = i + 1

    s.close()
Esempio n. 12
0
def polyadd(a, b):
    """
    Add polynomial a by polynomial b.
    a and b are lists from highest order term to lowest.
    """
    val = polynomial.polyadd(a[::-1], b[::-1])
    val = val[::-1]
    return val
Esempio n. 13
0
def lagrange(nodes):
    result = Polynomial([0])
    w = Polynomial(np.poly(nodes)[::-1])
    deriv = w.deriv(1)
    for i in range(len(nodes)):
        result = pl.polyadd(result,
                            make_l_k(i, nodes, w, deriv) * f(nodes[i]))[0]
    return result
Esempio n. 14
0
def polynomials_sum(x, y, mod, poly_mod):
    return np.int64(
        np.round(
            poly.polydiv(
                poly.polyadd(x, y) % mod,
                poly_mod
            )[1] % mod
        )
    )
Esempio n. 15
0
 def test_polyadd(self) :
     for i in range(5) :
         for j in range(5) :
             msg = "At i=%d, j=%d" % (i,j)
             tgt = np.zeros(max(i,j) + 1)
             tgt[i] += 1
             tgt[j] += 1
             res = poly.polyadd([0]*i + [1], [0]*j + [1])
             assert_equal(trim(res), trim(tgt), err_msg=msg)
Esempio n. 16
0
def polyadd_wm(x, y, poly_mod):
    """Add two polynomials
        Args:
            x, y: two polynomials to be added.
            poly_mod: polynomial modulus.
        Returns:
            A polynomial in Z[X]/(poly_mod).
        """
    return poly.polydiv(poly.polyadd(x, y), poly_mod)[1]
Esempio n. 17
0
 def test_polyadd(self):
     for i in range(5):
         for j in range(5):
             msg = "At i=%d, j=%d" % (i, j)
             tgt = np.zeros(max(i, j) + 1)
             tgt[i] += 1
             tgt[j] += 1
             res = poly.polyadd([0] * i + [1], [0] * j + [1])
             assert_equal(trim(res), trim(tgt), err_msg=msg)
Esempio n. 18
0
def interpolation_polynomial(xi, eta, e, field):
    coeflist = 0
    for i in range(e):
        xi_j_list = [xi[j] for j in range(e) if j != i]
        xi_i = xi[i]
        xi_minus_xi_j = construct_polynomial(xi_j_list, field)
        lambnda_i = eta[i] * inv(evaluation(xi_minus_xi_j, xi_i, field), field)
        a = P.polymul(lambnda_i, xi_minus_xi_j)
        coeflist = P.polyadd(coeflist, a) % field
    return [int(i) for i in coeflist]
Esempio n. 19
0
def add_poly_matrices(matrix_one, matrix_two):
    size = len(matrix_one)
    output_matrix = []
    for i in range(size):
        row = []
        for j in range(size):
            sum = P.polyadd(matrix_one[i][j], matrix_two[i][j])
            row.append(sum)
        output_matrix.append(row)
    return output_matrix
Esempio n. 20
0
def lagrange(nodes):
    result = Polynomial([0])
    # np.poly строит полином по набору корней. Но порядок коэффициетов противоположный тому, который
    # принимает конструктор класса Polynomial
    w = Polynomial(np.poly(nodes)[::-1])
    deriv = w.deriv(1)
    for i in range(len(nodes)):
        result = pl.polyadd(result,
                            make_l_k(i, nodes, w, deriv) * f(nodes[i]))[0]
        # возвращается не только сумма
    return result
Esempio n. 21
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)
Esempio n. 22
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)
Esempio n. 23
0
def _polytustin(a, T):
    n = len(a)
    if sum(a[1:]) == 0:
        return a
    a_new = 0
    num = [(T - 1) / (T + 1), 1]
    den = [1, (T - 1) / (T + 1)]
    for i in range(n):
        pnum = polypow(num, i)
        pden = polypow(den, n - 1 - i)
        a_new = polyadd(a_new, a[i] * polymul(pnum, pden))
    return a_new
def polyadd(x, y, modulus, poly_mod):
    """Multiply two polynoms
    Args:
        x, y: two polynoms to be multiplied.
        modulus: coefficient modulus.
        poly_mod: polynomial modulus.
    Returns:
        A polynomial in Z_modulus[X]/(poly_mod).
    """
    return np.int64(
        np.round(
            poly.polydiv(poly.polyadd(x, y) % modulus, poly_mod)[1] % modulus))
Esempio n. 25
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
Esempio n. 26
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
Esempio n. 27
0
def get_B(z, a):
    N = z.shape[0]
    left = np.array([1])
    middle = np.array([1])

    for i in range(1, N):
        c1 = np.array([-a[i] * z[i - 1], a[i]])
        cc = P.polymul(c1, left)
        right = P.polyadd(middle, cc)
        left = middle
        middle = right

    return right
Esempio n. 28
0
    def Newton(self, L, M):  # Newton function takes two lists as arguments

        # L contains the list of x values
        # M contains the list of f(x) values
        # e.g.-
        #L=[1,2,3] , M=[0,-1,0]
        # i.e., f(1)=0, f(2)=-1, f(3)=0

        self.x_values = L
        self.fx_values = M
        n = len(self.x_values)  # n=length of L, i.e., the number of points
        mat = [[0.0 for i in range(n)]
               for j in range(n)]  # initialising an n*n matrix
        for i in range(n):  # filling 1st column of matrix with f(x) values
            mat[i][0] = self.fx_values[i]
        for i in range(1, n):  # calculating entries of matrix
            for j in range(n - i):
                mat[j][i] = (mat[j + 1][i - 1] - mat[j][i - 1]) / (
                    self.x_values[j + i] - self.x_values[j])
        # The matrix is of the form (for 4 points - x,y,z,w)
        #    f(x)    f(x,y)    f(x,y,z)    f(x,y,z,w)
        #    f(y)    f(y,z)    f(y,z,w)    0
        #    f(z)    f(z,w)    0           0
        #    f(w)    0         0           0

        result = array((mat[0][0], ))  # initialising result array
        for i in range(1, n):
            prod = (-1 * self.x_values[0], 1
                    )  # initialising prod polynomial which is to be multiplied
            # with corresponding element of matrix mat
            for j in range(1, i):
                prod = P.polymul(
                    prod, (-1 * self.x_values[j], 1))  # calculating prod
            result = P.polyadd(result,
                               array(prod) * mat[0][i])  # calculating result
        result = list(result)  # list of co-efficients
        self.polynomial = ""  # string to store final polynomial
        for i in range(len(result) - 1, 0, -1):  # building up the string
            if (result[i] != 0):
                if (result[i] > 0 and i != (len(result) - 1)):
                    self.polynomial += " + " + str(
                        result[i]) + "x^" + str(i) + " "
                elif (result[i] > 0 and i == (len(result) - 1)):
                    self.polynomial += str(result[i]) + "x^" + str(i) + " "
                else:
                    self.polynomial += " - " + str(
                        -1 * result[i]) + "x^" + str(i) + " "
        if (result[0] != 0):
            self.polynomial += " + " + str(
                result[0]) if result[0] > 0 else " - " + str(-1 * result[0])
        return (self.polynomial)  # return result
Esempio n. 29
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
Esempio n. 30
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]
Esempio n. 31
0
def add_poly(x, y, mod_coeff, mod_poly):
    """
    Takes:
        x, y: the two polynoms to be multiplied.
        mod_coeff: coefficient modulus.
        mod_poly: polynomial modulus.
    Returns:
        A polynomial in Z_modulus[X]/(poly_mod).
        
    Adds the two polynoms x and y.
    """
    return np.int64(
        np.round(poly.polydiv(poly.polyadd(x, y) % mod_coeff, mod_poly)[1] % mod_coeff)
    )
Esempio n. 32
0
def funcionNewton( f, a ):
     Ai = 0
     polyDef = []
     for i in range( len(a) ):
         Ai = AiNewt( f, i, a, Ai)
         b = []
         for j in range( len(a) ):
              b.append(a[i]) if j!=i
         lista = np.poly(b)
         pol = [ Ai*x for x in lista]

         polyDef = P.polyadd(poly, polyDef);

     return polyDef
Esempio n. 33
0
 def poly_coeff(n):
     if 0 <= n < len(polys_start_coeff):
         return polys_start_coeff[n]
     elif n >= len(polys_start_coeff):
         coeff = np.array([0.])
         for i, func in recursive_poly_functions:
             if i < 0 or i >= n:
                 raise ValueError(
                     "Can't apply on not yet calculated polynomial! i={}, n={}"
                     .format(i, n))
             coeff = npoly.polyadd(coeff, func(n, poly_coeff(n - i - 1)))
         return coeff
     else:
         raise ValueError(
             "Illegal degree n={} for polynomial coefficients.".format(n))
Esempio n. 34
0
    def __init__(self, pol1, pol2):
        """
        Composes two polynomials (i.e., `pol1'(`pol2')) with distinct covariance
        matrices.

        Considering we have polynomials

            f(x) = \\sum_i a_i x^i,
            g(x) = \\sum_j b_j x^j,

        with variances \\sigma_f and \\sigma_g when evaluated (see
        coll_dyn_activem.maths.Polynomial), we compute

            \\sigma_fg(x) = \\sigma_f(g(x))
                + \\sigma_g(x) \\times [ \\sum_i i a_i g(x)^{i-1} ]^2,

        as the variance of the composed polynomial f(g) evaluated at x. We
        stress that this considers no correlations between the coefficients of
        the polynomials.

        (see https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Non-linear_combinations)

        Parameters
        ----------
        pol1 : coll_dyn_activem.maths.Polynomial
            First polynomial.
        pol2 : coll_dyn_activem.maths.Polynomial
            Second polynomial.

        Returns
        -------
        pol : coll_dyn_activem.maths.Polynomial
            Composed polynomial.
        """

        self._pol1, self._pol2 = pol1, pol2
        self.deg = self._pol1.deg * self._pol2.deg  # degree of composed polynomial

        # WARNING: numpy.polynomial.polynomial.polyadd and polypow considers
        #          arrays as polynomials with lowest coefficient first,
        #          contrarily to polyval and polyfit.
        _pol1, _pol2 = self._pol1.pol[::-1], self._pol2.pol[::-1]

        self.pol = np.zeros((1, ))  # composed polynomial
        for i in range(pol1.deg + 1):
            self.pol = polyadd(self.pol, _pol1[i] * polypow(_pol2, i))

        self.pol = self.pol[::-1]
Esempio n. 35
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
Esempio n. 36
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
        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
Esempio n. 38
0
    ax2.set_ylabel('volume (ml)')

    ax2.grid(True)

    MAX = 300
    data = data[numpy.all(data<MAX,axis=1)]
    length = data.shape[0]
    volumes = volumes[-length:]
    order = 3

    sum = None
    for column_index in range(0,data.shape[1]):
        coefficients = polyfit(data[:,column_index],volumes,order)
        if sum is None:
            sum = coefficients
        else:
            sum = polyadd(sum,coefficients)
    average = sum/data.shape[1]

    round_digits = 8
    average = [round(i,round_digits) for i in average]

    poly = Polynomial(average)
    ys = poly(data[:,-1])
    ax2.plot(data[:,-1],ys,'r',linewidth=3)

    ax2.text(5,7.5,r'$v = c_0 + c_1s + c_2s^2 + c_3s^3$',fontsize=20)
    ax2.text(5,6.5,str(average),fontsize=18,color='r')

    plot.show()
Esempio n. 39
0
     flow = False
 else:
     op = int(entrada)
     if op == 1:
         print "Valor en un punto:\n"
         n = input("Grado del polinomio: ")
         p1 = obj.insertPol(n,p1)
         pto = input("Digite el punto a evaluar: ")
         print "El resultado es: "+str(obj.evalPto(p1,pto))
     elif op == 2:
         print "Suma"
         gr1 = input("Grado del polinomio 1")
         p1 = obj.insertPol(gr1,p1)
         gr1 = input("Grado del polinomio 2")
         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:
Esempio n. 40
0
    #     marker = markers[column_index]
    #     ax2.plot(data_oa[:,column_index],volumes_oa,marker=marker,linestyle='--',color=color)
    ax2.set_xlabel('volume (ml)')
    ax2.set_ylabel('offset mean signals (ADC units)')

    ax2.grid(True)

    order = 3

    sum_va = None
    for column_index in range(0,data_va.shape[1]):
        coefficients_va = polyfit(volumes_va,data_va[:,column_index],order)
        if sum_va is None:
            sum_va = coefficients_va
        else:
            sum_va = polyadd(sum_va,coefficients_va)
    average_va = sum_va/data_va.shape[1]

    round_digits = 8
    average_va = [round(i,round_digits) for i in average_va]
    with open('volume_to_adc_va.yaml', 'w') as f:
        yaml.dump(average_va, f, default_flow_style=False)

    poly_va = Polynomial(average_va)
    ys_va = poly_va(volumes_va)
    ax2.plot(volumes_va,ys_va,'r',linewidth=3)

    ax2.text(0.5,110,r'$s = c_0 + c_1v + c_2v^2 + c_3v^3$',fontsize=20)
    ax2.text(0.5,100,str(average_va),fontsize=18,color='r')

    plot.show()
Esempio n. 41
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
Esempio n. 42
0
                adc_data_points.append(adc_data_point)
            print(adc_data_points)
            volume_array = numpy.array(volume_data_points,dtype='float64')
            adc_array = numpy.array(adc_data_points,dtype='int')
            adc_array = adc_array[volume_array<=6]
            volume_array = volume_array[volume_array<=6]
            ax2.plot(volume_array,
                     adc_array,
                     linestyle='--',
                     linewidth=1,
                     color=color)
            coefficients = polyfit(volume_array,adc_array,order)
            if coefficients_sum is None:
                coefficients_sum = coefficients
            else:
                coefficients_sum = polyadd(coefficients_sum,coefficients)
        coefficients_average = coefficients_sum/run_count
        poly_fit = Polynomial(coefficients_average)
        adc_fit = poly_fit(volume_array)
        ax2.plot(volume_array,
                 adc_fit,
                 linestyle='-',
                 linewidth=2,
                 label=cylinder,
                 color=color)
        coefficients_list = [float(coefficient) for coefficient in coefficients_average]
        output_data[cylinder]['volume_to_adc_low'] = coefficients_list
    ax2.set_xlabel('volume (ml)')
    ax2.set_ylabel('adc low value (adc units)')
    ax2.legend(loc='best')
Esempio n. 43
0
 def __add__(self, other):
     result = polynomial.polyadd(self._poly, other._poly)
     result = self._normalizePoly(result, len(self._poly))
     return Polynomial(poly=result)
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
Esempio n. 45
0

rand.seed(2)
print "TESING 10000 CASES..."
for k in range(10000):
	order1=rand.randint(0,10)
	order2=rand.randint(0,10)
	c1=[0]*(order1+1)
	c2=[0]*(order2+1)
	for i in range(len(c1)):
		c1[i]=rand.randint(-5,5)
	for i in range(len(c2)):
		c2[i]=rand.randint(-5,5)

	# TESTING ADDITION FUNCTION
	a= P.polyadd(c1,c2).tolist()	
	b= q.addPoly(c1,c2)
	if(a!=b):
		print "Failed on Case:"
		print "a add b"
		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
Esempio n. 46
0
def polyadd(c1, c2):
    from numpy.polynomial.polynomial import polyadd
    return polyadd(c1, c2)