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
def dbl(x, n, q): dist = [-1, 0, 1] prob = [0.25, 0.5, 0.25] e = np.random.choice(dist, n, p=prob) dbl_x = (2 * x) % (2 * q) dbl_x = p.polysub(dbl_x, e) % (2 * q) return dbl_x
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)
def test_polysub(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.polysub([0]*i + [1], [0]*j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg)
def compute_polynomials(self, U): p_unit = (0, 1) p = [] p.append((1)) p_k_1_1 = P.polymul(p_unit, p[0]) p_k_1_2 = P.polymul(U[0, 0], p[0]) p_new = (1 / U[0, 1]) * P.polysub(p_k_1_1, p_k_1_2) p.append(p_new) for k in range(2,self.dim): #print(k) p_k_1_1 = P.polymul(p_unit, p[k-1]) p_k_1_2 = P.polymul(U[k-1,k-1], p[k-1]) p_k_2 = P.polymul(U[k-1,k-2], p[k-2]) p_new = (1/U[k-1,k])*P.polysub( P.polysub(p_k_1_1, p_k_1_2), p_k_2 ) p.append(p_new) self.p = p self.p_n = P.polyadd(P.polymul(-U[self.dim-2,self.dim-1], p[self.dim-2]), P.polymul(P.polysub(p_unit, U[self.dim-1,self.dim-1]), p[self.dim-1])) return p
def test_polysub(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.polysub([0] * i + [1], [0] * j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg)
def berlekampTest(prime, poly): m = len(poly) - 1 u = [0, 1] for i in range(0, m // 2): u = P.polydiv(P.polypow(u, prime), poly)[1] % prime d = gcd(P.polysub(u, [0, 1]) % prime, poly, prime) #print(P.polysub(u, [0, 1]) % prime, poly, d) if not np.array_equal(np.array([1.]), d): return False return True
def PolyGCD_rec(a: numpy.array, b: numpy.array): """Recursive Greatest Common Divisor for polynomial""" if all(num == 0.0 for num in a): return b, 0, 1 t = polydiv(b, a) d, x1, y1 = PolyGCD_rec(t[1], a) x = polysub(y1, polymul(t[0], x1)) y = x1 return d, x, y
def deriv(self): """ compute first derivative Returns ------- dPP : PseudoPolynomial d(PP)/dx represented as a PseudoPolynomial """ dp = pol.polyder(self.p) dq = pol.polyder(self.q) p = pol.polysub(pol.polymul((1, 0, -1), dp), pol.polymul((0, 2 * self.r), self.p)) q = pol.polysub(pol.polymul((1, 0, -1), dq), pol.polymul((0, 2 * self.r + 1), self.q)) r = self.r - 1 return PseudoPolynomial(p=remove_zeros(p), q=remove_zeros(q), r=r)
def impinvar_causal(*args, **kwargs): """causal version of impinvar, h[0] == 0""" # polynomial.polysub is ordered from lowest to highest from numpy.polynomial.polynomial import polysub bz, az = impinvar(*args, **kwargs) h0 = bz[0] / az[0] bz = polysub(bz, h0 * az) return bz, az
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))))
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 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
def polysub(c1, c2): from numpy.polynomial.polynomial import polysub return polysub(c1, c2)
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
print(np.dot(x, y)) #Dot Product #_______________________________________________________________________________ #Find the roots of the given polynomials print("Roots of the first polynomial:") print(np.roots([1, 1.5, 2])) #getting roots of polynomial print("Roots of the second polynomial:") print(np.roots([1, -5.09])) #getting roots of polynomial #_______________________________________________________________________________ # Add, subtract, multiply and divide polynomials from numpy.polynomial import polynomial as P x = (10, 20, 30) #declaring polynomials y = (30, 40, 50) print("Add one polynomial to another:") print(P.polyadd(x, y)) #Adding polynomial print("Subtract one polynomial from another:") print(P.polysub(x, y)) #Subtracting polynomial print("Multiply one polynomial by another:") print(P.polymul(x, y)) #Multiplying polynomial print("Divide one polynomial by another:") print(P.polydiv(x, y)) #Dividing polynomial #_______________________________________________________________________________ #Compute sine, cosine and tangent array of angles given in degrees print("sine: array of angles given in degrees") print(np.sin(np.array( (0., 30., 45., 60., 90.)) * np.pi / 180.)) #Computing sin of angles print("cosine: array of angles given in degrees") print(np.cos(np.array( (0., 30., 45., 60., 90.)) * np.pi / 180.)) #Computing cos of angles print("tangent: array of angles given in degrees") print(np.tan(np.array( (0., 30., 45., 60., 90.)) * np.pi / 180.)) #Computing tan of angles
def polynomialRichardson(f1, f2, degree): power = 2**(degree + 1) from numpy.polynomial import polynomial as P tmp = P.polysub(P.polymul(f2, [power]), f1) return P.polymul(tmp, [1 / (power - 1)])
def inverse_rational_matrix(my_tf_object): """ Takes the inverse of a transfer function matrix and returns it. Parameters: numArray_pres: a 2D array of the coefficients of the polynomials in the numerator of each entry of the original matrix denArray: a 2D array of the coefficients of the polynomials in the denominator of each entry of the original matrix :return: out: a transfer function object that represents the inverted matrix """ # We turn our transfer function into a polynomial coefficient type object for making the algebraic inversion numArray_reverse = my_tf_object.num denArray_reverse = my_tf_object.den # Now we take the coefficients of the polynomial and put them into 2 arrays # one for numerators and one for denominators numArray_list = list(numArray_reverse) denArray_list = list(denArray_reverse) n = np.shape(denArray_list)[0] for i in np.arange(n): for j in np.arange(n): numArray_list[i][j] = np.flipud(numArray_list[i][j]) denArray_list[i][j] = np.flipud(denArray_list[i][j]) numArray_pres = (numArray_list) denArray = (denArray_list) numArray_fut = deepcopy(numArray_pres) our_ks = np.arange(n - 1, -1, -1) # We now go through the process of computing the adjoint of the numerator for k in our_ks: # One iteration of the pivoting, after pivoting the future become the present and the present becomes the past # Now we update our past and present and future numerator arrays for the next pivot numArray_past = deepcopy(numArray_pres) numArray_pres = deepcopy(numArray_fut) for i in np.arange(n): for j in np.arange(n): # Below are the following cases for the numerator of the adjoint, # each is based off of the index of the location of the matrix entry: # Based off of the paper by T. Downs called: On the inversion of a matrix of rational functions (1971) # Case 1: i,j<k if i < k and j < k: if k == n-1: numArray_fut[i][j] = tuple(poly.polysub(poly.polymul(poly.polymul(numArray_pres[i][j], numArray_pres[k][k]), poly.polymul(denArray[i][k], denArray[k][j])), poly.polymul(poly.polymul(numArray_pres[i][k], numArray_pres[k][j]), poly.polymul(denArray[i][j], denArray[k][k])))) else: numArray_fut[i][j] = tuple(poly.polydiv(poly.polysub(poly.polymul(poly.polymul(numArray_pres[i][j], numArray_pres[k][k]), poly.polymul(denArray[i][k], denArray[k][j])), poly.polymul(poly.polymul(numArray_pres[i][k], numArray_pres[k][j]), poly.polymul(denArray[i][j], denArray[k][k]))), numArray_past[k+1][k+1])[0]) # Case 2: i>k>j elif i > k and k > j: numArray_fut[i][j] = tuple(poly.polydiv(poly.polysub(poly.polymul(poly.polymul(numArray_pres[i][j], numArray_pres[k][k]), denArray[k][j]), poly.polymul(poly.polymul(numArray_pres[i][k], numArray_pres[k][j]), denArray[k][k])), poly.polymul(denArray[k][i], numArray_past[k+1][k+1]))[0]) # Case 2.5: j>k>i elif j > k and k > i: numArray_fut[i][j] = tuple(poly.polydiv(poly.polysub(poly.polymul(poly.polymul(numArray_pres[i][j], numArray_pres[k][k]), denArray[i][k]), poly.polymul(poly.polymul(numArray_pres[i][k], numArray_pres[k][j]), denArray[k][k])), poly.polymul(denArray[j][k], numArray_past[k+1][k+1]))[0]) # Case 4 from the paper: i=j>k elif i == j and j > k: numArray_fut[i][j] = tuple(poly.polydiv(poly.polysub(poly.polymul(numArray_pres[i][i], numArray_pres[k][k]), poly.polymul(poly.polymul(numArray_pres[i][k], numArray_pres[k][i]), poly.polymul(denArray[k][k], denArray[i][i]))), poly.polymul(poly.polymul(denArray[k][i], denArray[i][k]), numArray_past[k+1][k+1]))[0]) # Case 3 from the paper: i,j>k elif i > k and j > k: numArray_fut[i][j] = tuple(poly.polydiv(poly.polysub(poly.polymul(numArray_pres[i][j], numArray_pres[k][k]), poly.polymul(poly.polymul(numArray_pres[i][k], numArray_pres[k][j]), denArray[k][k])), poly.polymul(poly.polymul(denArray[k][i], denArray[j][k]), numArray_past[k+1][k+1]))[0]) # Case 5: i=k!=j elif i == k and k != j: numArray_fut[k][j] = tuple(poly.polymul((-1,), numArray_pres[k][j])) # Case 6: j=k!=i elif j == k and k != i: numArray_fut[i][j] = tuple(numArray_pres[i][j]) # Case 7: i=j=k elif i == j == k: if k == n-1: numArray_fut[k][k] = (1,) else: numArray_fut[k][k] = tuple(numArray_past[k+1][k+1]) denArray_fut = deepcopy(denArray) # Below we do the denominator: for i in np.arange(n): for j in np.arange(n): # Each entry of the denominator is the product of all the original denominators except for the ith column # and the jth row of the original denominator matrix # First we normalize the initial entry denArray_fut[i][j] = tuple(poly.polydiv(denArray_fut[i][j], denArray_fut[i][j])[0]) for ii in np.arange(n): for jj in np.arange(n): if j != ii and i != jj: denArray_fut[i][j] = tuple(poly.polymul(denArray_fut[i][j], denArray[ii][jj])) # Now we collect our results and we return our final inverted matrix my_adjoint_num = deepcopy(numArray_fut) my_adjoint_den = deepcopy(denArray_fut) # We multiply the adjoint by the inverse of the determinant of the matrix, the inverse of the determinant is # decided to be the past numerator array (or that before preforming the final pivot) inverse_determinant_den = deepcopy(numArray_pres[0][0]) inverse_determinant_num = (1) for i in np.arange(n): for j in np.arange(n): inverse_determinant_num = tuple(poly.polymul(denArray[i][j], inverse_determinant_num)) newMatrix_num = [] newMatrix_den = [] for i in np.arange(n): newMatrix_num.append([]) for j in np.arange(n): newMatrix_num[i].append(tuple(poly.polymul(my_adjoint_num[i][j], inverse_determinant_num))) # Now we do the denominators for i in np.arange(n): newMatrix_den.append([]) for j in np.arange(n): x = np.shape(my_adjoint_den) newMatrix_den[i].append(tuple(poly.polymul(my_adjoint_den[i][j], inverse_determinant_den))) # Ok, we finally have our inverse! numerators = newMatrix_num denominators = newMatrix_den try: # A polynomial solver for smaller degree polynomials to do cancellations and reduce the polynomials for i in np.arange(n): for j in np.arange(n): numerators[i][j] = np.flipud(numerators[i][j]) denominators[i][j] = np.flipud(denominators[i][j]) k = 0 for val in numerators[i][j]: numerators[i][j][k] = round(val, 4) k += 1 num_roots = (np.roots(numerators[i][j])) den_roots = (np.roots(denominators[i][j])) for r in np.arange(len(num_roots)): num_roots[r] = round(num_roots[r], 4)*10000. for dr in np.arange(len(den_roots)): den_roots[dr] = round(den_roots[dr], 4)*10000. num_roots = Counter(num_roots) den_roots = Counter(den_roots) all_roots_num = num_roots - den_roots all_roots_den = den_roots - num_roots if np.any(numerators[i][j]) != 0: # If zero then we want to keep them as they are. numerators[i][j] = numerators[i][j][0]/denominators[i][j][0] for k in all_roots_num: for number in np.arange(all_roots_num[k]): numerators[i][j] = list(poly.polymul(numerators[i][j], (-k/10000., 1))) denominators[i][j] = 1 for k in all_roots_den: for number in np.arange(all_roots_den[k]): denominators[i][j] = list(poly.polymul(denominators[i][j], (-k/10000., 1))) # Now we return the values in the form of transfer functions by casting them with control.tf for i in np.arange(n): for j in np.arange(n): if type(numerators[i][j]) == 'npumpy.ndarray' or type(numerators[i][j]) == list: numerators[i][j] = np.flipud(numerators[i][j]) else: numerators[i][j] = np.array([float(np.real(numerators[i][j]))]) if type(denominators[i][j]) != int: denominators[i][j] = np.flipud(denominators[i][j]) else: denominators[i][j] = np.array([float(denominators[i][j])]) except: b = "c" num_list = [] den_list = [] for i in np.arange(n): num_list.append(list((numerators[i]))) den_list.append(list((denominators[i]))) out = tf.tf(num_list, den_list) return out
def extrema(self, line, poly): """ Calculates upper extrema. """ return polyroots(polysub(np.array([line.start.cost]), poly))
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 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
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
def subpoly(f, g, m): return to_ring(poly.polysub(f, g), m)
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: 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"
def extrema(self, line, poly): """ Calculates upper extrema. """ return np.concatenate((polyroots(polysub(np.array([line.start.cost, np.inner(self.inexact["c_u"]*line.start.grad, line.dire)]), poly)), polyroots(polysub(np.array([line.start.cost, np.inner(self.inexact["c_l"]*line.start.grad, line.dire)]), poly))))
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. """ velocity = np.mean(velocity) density = np.mean(density) S_gross_w = np.mean(S_gross_w) mac = np.mean(mac) Cm_q = np.mean(Cm_q) Cz_alpha = np.mean(Cz_alpha) mass = np.mean(mass) Cm_alpha = np.mean(Cm_alpha) Iy = np.mean(Iy) Cm_alpha_dot = np.mean(Cm_alpha_dot) Cz_u = np.mean(Cz_u) Cz_alpha_dot = np.mean(Cz_alpha_dot) Cz_q = np.mean(Cz_q) Cw = np.mean(Cw) Theta = np.mean(Theta) Cx_u = np.mean(Cx_u) Cx_alpha = np.mean(Cx_alpha) # 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 __sub__(self, other): if isinstance(other, MyPolynomial): return MyPolynomial( polynomial.polysub(self.polynomial, other.polynomial)[0]) else: return MyPolynomial(self.polynomial - other)