def poly_decimation(p, t): """Decimates polynomial and returns decimated polynomial. :type p: sympy.Poly :type t: int :rtype: sympy.Poly """ from sympy.abc import x from operator import mul n = sympy.degree(p) s = seq_decimation(p, t) while len(s) < 2 * n: s += s cd = sympy.Poly(1, x, modulus=2) l, m, bd = 0, -1, 1 for i in range(2 * n): sub_cd = list(reversed(cd.all_coeffs()))[1:l + 1] sub_s = list(reversed(s[i - l:i])) sub_cd += [0] * (len(sub_s) - len(sub_cd)) disc = s[i] + sum(map(mul, sub_cd, sub_s)) if disc % 2 == 1: td = cd cd += bd * sympy.Poly(x**(i - m), x, modulus=2) if l <= i / 2: l = i + 1 - l m = i bd = td if sympy.degree(cd) == n: cd = sympy.Poly(reversed(cd.all_coeffs()), x, modulus=2) return cd else: return None
def normalize_poly(poly): poly = sp.simplify(poly) num = sp.Poly(sp.expand(sp.numer(poly))) den = sp.Poly(sp.expand(sp.denom(poly))) num /= den.coeffs()[0] den /= den.coeffs()[0] return num / den
def symToTransferFn(Y): Y = sympy.expand(sympy.simplify(Y)) n, d = sympy.fraction(Y) n, d = sympy.Poly(n, s), sympy.Poly(d, s) num, den = n.all_coeffs(), d.all_coeffs() num, den = [float(f) for f in num], [float(f) for f in den] return num, den
def poly_slicer(poly, first_n_terms=None, show_zeros=True, ghost_terms=True, underline=False, x=sym.symbols('x')): """Helper Function for Polynomial long division""" if show_zeros: terms = sym.Poly(poly, x).all_terms() else: terms = sym.Poly(poly, x).terms() first_n_terms = len(terms) if (first_n_terms is None or first_n_terms > len(terms)) else first_n_terms if underline: poly_string = f"\\underline{{ \\left({pmsign(terms[0][1], leading=True)}{sym.latex(x ** terms[0][0][0])}" for term in terms[1:first_n_terms]: poly_string += f"{constant_sign(term[1])}" \ f"{sym.latex(x ** term[0][0]) if term[0][0] != 0 else ''}" poly_string += " \\right)}" else: poly_string = f"{pmsign(terms[0][1], leading=True)}" \ f"{sym.latex(x ** terms[0][0][0]) if terms[0][0][0] != 0 else ''}" for term in terms[1:first_n_terms]: poly_string += f"{constant_sign(term[1])}" \ f"{sym.latex(x ** term[0][0]) if term[0][0] != 0 else ''}" if ghost_terms: poly_string += f"\\phantom{{ { '{{}}' if not underline else ''} " for term in terms[first_n_terms:]: poly_string += f"{constant_sign(term[1])}" \ f"{sym.latex(x ** term[0][0]) if term[0][0] != 0 else ''}" poly_string += " }" return poly_string
def get_big_poly(p, t): n = sympy.degree(p) d = high_decimation(p, t) while len(d) < (2 * n): d += d cd = sympy.Poly(1, sym_x, modulus=2) l, m, bd = 0, -1, 1 for i in range(2 * n): sub_cd = list(reversed(cd.all_coeffs()))[1:l + 1] sub_s = list(reversed(d[i - l:i])) sub_cd += [0] * (len(sub_s) - len(sub_cd)) disc = d[i] + sum(map(mul, sub_cd, sub_s)) if disc % 2 == 1: td = cd cd += bd * sympy.Poly(sym_x**(i - m), sym_x, modulus=2) if l <= i / 2: l = i + 1 - l m = i bd = td if sympy.degree(cd) == n: cd = sympy.Poly(reversed(cd.all_coeffs()), sym_x, modulus=2) return cd else: return None
def e2nd(expression): """ basic helper function that accepts a sympy expression, expands it, attempts to simplify it, and returns a numerator and denomenator pair for the instantiation of a scipy LTI system object. """ expression = expression.expand().cancel() n = sympy.Poly(sympy.numer(expression), s).all_coeffs() d = sympy.Poly(sympy.denom(expression), s).all_coeffs() return ([float(x) for x in n], [float(x) for x in d])
def __Mult_Poli(self): x, y, z, w = sp.symbols('x,y,z,w') print("_________________________________________________") print( " ###### MÓDULO PARA MULTIPLICAR POLINOMIOS ####### \n \n Ejemplo: 2x³+4x²+5y²+y = 2*x**3+4*x**2+5y**2+y" ) print("_________________________________________________") self.Poly1 = (input("Ingrese f(x,y,z,w) = ")) print("-------------------------------------------------") self.Poly2 = (input("Ingrese g(x,y,z,w) = ")) print("\n" * 100) print("_________________________________________________") self.P1 = sp.Poly(self.Poly1) self.P2 = sp.Poly(self.Poly2) self.Mult = self.P1 * self.P2 print("_________________________________________________") print(" ###### MÓDULO PARA MULTIPLICAR POLINOMIOS ####### ") print("-------------------------------------------------") print(" f(x,y,z,w) = ", self.Poly1) print("-------------------------------------------------") print(" g(x,y,z,w) = ", self.Poly2) print("-------------------------------------------------") print(" f x g = ", self.Mult) print("_________________________________________________")
def Matv(v, base, indep_prompt=True): if isinstance(v, (list)): return [Matv(i, base, indep_prompt=True) for i in v] if re.match(r'P.', base[0].space): n = len(base) c = sym.symbols('c0:{}'.format(n)) x = sym.symbols('x') C = np.array(c)[:, np.newaxis] B = np.array(base) Base_Poly = sym.Poly(str(invMatv(C, base)), x) Vec_Poly = sym.Poly(v.vec, x) Eq = (Base_Poly - Vec_Poly).all_coeffs() Coef = sym.linsolve(Eq, c) if len(Coef) < 1 or len(Coef.free_symbols) > 0: if indep_prompt: print('Warning: Improper base! Returning 0') return 0 dtype = 'float' if any(abs(sym.im(c)) > tol for c in Coef.args[0]): dtype = 'complex' res = np.array(Coef.args[0])[:, np.newaxis].astype(dtype) if re.match(r'F.', base[0].space): B = np.array([(b.vec).transpose() for b in base]).transpose() res = np.array(la.pinv(B).dot(v.vec[:, np.newaxis])) chk = B.dot(res) - v.vec[:, np.newaxis] if res.dtype != 'object' and la.norm(chk) > tol: if indep_prompt: print('Warning: Improper base! Returning 0') return 0 return res
def canonical(self): """Convert rational function to canonical form with unity highest power of denominator. See also general, partfrac, mixedfrac, and ZPK""" try: N, D, delay = self.as_ratfun_delay() except ValueError: # TODO: copy? return self.expr var = self.var Dpoly = sym.Poly(D, var) Npoly = sym.Poly(N, var) K = sym.cancel(Npoly.LC() / Dpoly.LC()) if delay != 0: K *= sym.exp(self.var * delay) # Divide by leading coefficient Nm = Npoly.monic() Dm = Dpoly.monic() expr = K * (Nm / Dm) return expr
def keygen(m_val, t_val, files): global x # Random irreducible polynomial of degree m k_vec = get_irreducible(m_val) if args.v: print("k(x) = ", sympy.Poly(k_vec, x, domain='FF(2)')) # Random irreducible polynomial of degree t g_vec = get_irreducible(t_val) if args.v: print("g(x) = ", sympy.Poly(g_vec, x, domain='FF(2)')) # Produce k*n generator matrix G for the code H_matrix = get_H(m_val, t_val, k_vec, g_vec) if args.v: print('\nH ='); sympy.pprint(H_matrix); print(H_matrix.shape) G_matrix = get_G(H_matrix[:,:]) if args.v: print('\nG ='); sympy.pprint(G_matrix); print(G_matrix.shape) k_val = G_matrix.shape[0] # Select a random k*k binary non-singular matrix S S_matrix = get_nonsingular(k_val) if args.v: print('\nS ='); sympy.pprint(S_matrix) # Select a random n*n permutation matrix P n_val = G_matrix.shape[1] permutation = random.sample(range(n_val), n_val) P_matrix = sympy.Matrix(n_val, n_val, lambda i, j: int((permutation[i]-j)==0)) if args.v: print('\nP ='); sympy.pprint(P_matrix) # Compute k*n matrix G_pub = SGP G_pub = (S_matrix * G_matrix * P_matrix).applyfunc(lambda x: mod(x,2)) if args.v: print('\nG_pub ='); sympy.pprint(G_pub); print(G_pub.shape) # Public key is (G_pub, t) # Private key is (S, G, P) # length of the Goppa Code if args.v: print("\nn = ", n_val) if args.v: print("k =", k_val) writeKeys(G_pub, t_val, S_matrix, H_matrix, P_matrix, files)
def Chebyshev_gen(N, poles): """Function to evaluate the numerator and denominator polynomials of the generalized Chebyshev (i.e., with/without poles) filtering function.""" if(len(poles) == 0): Num = sp.polys.orthopolys.chebyshevt_poly(N) Num = sp.Poly(Num).all_coeffs() Den = np.array([[1]]) else: # evaluation of the polynomial P (i.e., the denominator) P = np.poly(poles); Den = np.reshape(P, (len(P), -1)) # denominator # placing all other poles at infinity poles = np.hstack((poles, np.inf * np.ones(N - poles.size))) # R. J. Cameron's recursive algorithm x = sp.Symbol('x') tmp1 = x - 1 / poles[0] tmp2 = sp.sqrt(x ** 2 - 1) * np.sqrt(1 - 1 / poles[0] ** 2) for j in range(1, len(poles)): if(np.isinf(poles[j])): U = x * tmp1 + sp.sqrt(x ** 2 - 1) * tmp2 V = x * tmp2 + sp.sqrt(x ** 2 - 1) * tmp1 tmp1 = sp.simplify(U); tmp2 = sp.simplify(V) else: U = x * tmp1 - tmp1 / poles[j] + sp.sqrt(x ** 2 - 1) * np.sqrt(1 - 1 / poles[j] ** 2) * tmp2 V = x * tmp2 - tmp2 / poles[j] + sp.sqrt(x ** 2 - 1) * np.sqrt(1 - 1 / poles[j] ** 2) * tmp1 tmp1 = sp.simplify(U); tmp2 = sp.simplify(V) U = tmp1; Num = sp.Poly(U, x).all_coeffs() # numerator Num = I_to_i(Num) norm = np.polyval(Num, 1) / np.polyval(Den, 1) Num = np.reshape(Num, (len(Num), -1)) / norm # so that abs(polynomial) value becomes 1 at +1 return Num, Den
def __new__(self, *polynomials, var=None, floater=False): """takes a symbolic polynomial and returns a vector of the leading coefficients args: polynomials: Expression(s) for which you wish to get the coefficients var: Polynomial variable such as s in s**2 + s**1 + s**0 must be specified if polynomial has symbolic coefficients """ results = [] for poly in polynomials: p = sym.simplify(poly) # if the variable is defined if var: p = sym.Poly(p, var) c = p.all_coeffs() results.append(c) # if variable is not defined else: try: p = sym.Poly(p) c = p.all_coeffs() # handles s**0 poly's except sym.polys.GeneratorsNeeded: c = [sym.Float(p)] finally: results.append(c) # try to convert to floats if floater set to true if floater: results = [[float(x) for x in item] for item in results] return results
def s_to_w(poly_ip, coef_norm=False): r""" Arraytool mostly uses polynomials defined in 's' domain, i.e., the Laplace domain. However, sometimes we may need polynomials in 'w' (omega) domain, i.e., lowpass prototype frequency domain. So, this function can be used to convert a given polynomial from 's' to 'w' domain (s=jw). :param poly_ip: Input polynomial :param coef_norm: If `true`, the output polynomial will be normalized such that the coefficient of the highest degree term becomes 1. :rtype: Returns a polynomial of the same order, however defined in `s=jw` domain """ if len(poly_ip) == 1: poly_op = np.array([[1]]) else: s = sp.Symbol('s'); w = sp.Symbol('w') poly_ip = sp.Poly(poly_ip.ravel().tolist(), s) poly_op = sp.simplify(poly_ip.subs(s, 1j * w)) # substitution poly_op = sp.Poly(poly_op, w).all_coeffs() poly_op = I_to_i(poly_op) poly_op = np.reshape(poly_op, (len(poly_op), -1)) if (coef_norm): poly_op = poly_op / poly_op[0] return poly_op
def poly_E(eps, eps_R, F, P): r""" Function to obtain the polynomial E and its roots in the s-domain. :param eps: Constant term associated with S21 :param eps_R: Constant term associated with S11 :param F: Polynomial F, i.e., numerator of S11 (in s-domain) :param P: Polynomial P, i.e., numerator of S21 (in s-domain) For further explanation, see "filter theory notes" by the author. :rtype: [polynomial_E, roots_E] ... where polynomial E is the denominator of S11 and S21 """ N = len(F); nfz = len(P) if (((N + nfz) % 2 == 0) and (abs(eps.real) > 0)): warnings.warn("'eps' value should be pure imaginary when (N+nfz) is an even number") elif (((N + nfz + 1) % 2 == 0) and (abs(eps.imag) > 0)): warnings.warn("'eps' value should be pure real when (N+nfz) is an odd number") s = sp.Symbol('s') poly_P = sp.Poly(P.ravel().tolist(), s) poly_F = sp.Poly(F.ravel().tolist(), s) poly_E = eps_R * poly_P + eps * poly_F roots_E = I_to_i(sp.nroots(poly_E)) roots_E = np.reshape(roots_E, (len(roots_E), -1)) roots_E = -abs(roots_E.real) + 1j * roots_E.imag # all roots to the LHS # create the polynomial from the obtained LHS roots poly_E = np.poly(roots_E.ravel().tolist()) poly_E = np.reshape(poly_E, (len(poly_E), -1)) return poly_E, roots_E
def compileParseMoment(x, objectiveFunction, equalityConstraints, inequalityConstraints, omega=None): # Useful constants n = len(x) xID = [x for x in range(n)] # Find maximum degree of each constraint and objective function equalityConstraintsDegrees = [ sym.Poly(constraint, *x).total_degree() for constraint in equalityConstraints ] inequalityConstraintsDegrees = [ sym.Poly(constraint, *x).total_degree() for constraint in inequalityConstraints ] objectiveFunctionDegree = sym.Poly(objectiveFunction, *x).total_degree() maxDegree = math.ceil( max(max(equalityConstraintsDegrees), max(inequalityConstraintsDegrees), objectiveFunctionDegree) / 2) # Corect omega if required omega = maxDegree if omega is None or omega < maxDegree else omega # Find cliques CD = corrSparsityCliques(x, objectiveFunction, equalityConstraints + inequalityConstraints) # TODO: Continuing from here return (1, 1, 1, 1)
def poly_euclid(a, b): if b.degree() > a.degree(): bigger, smaller = b, a else: bigger, smaller = a, b prev_coeff_bigger = sympy.Poly(1, x, modulus=3) prev_coeff_smaller = sympy.Poly(0, x, modulus=3) coeff_bigger = sympy.Poly(0, x, modulus=3) coeff_smaller = sympy.Poly(1, x, modulus=3) while smaller.degree() >= 0: quotient, remainder = bigger.div(smaller) bigger = smaller smaller = remainder next_coeff_bigger = prev_coeff_bigger - quotient * coeff_bigger next_coeff_smaller = prev_coeff_smaller - quotient * coeff_smaller prev_coeff_bigger = coeff_bigger prev_coeff_smaller = coeff_smaller coeff_bigger = next_coeff_bigger coeff_smaller = next_coeff_smaller leading_coeff = sympy.Poly(bigger.coeffs()[0], x, modulus=3) gcd = leading_coeff * bigger cofactor_bigger = leading_coeff * prev_coeff_bigger cofactor_smaller = leading_coeff * prev_coeff_smaller return gcd, cofactor_bigger, cofactor_smaller
def scale_filter_dbN(n): pol_string, pol_aux = pol_db(n) roots_less_1 = roots_less_one(pol_string, 'z') string = f'(z+1)**({n}/2)*' for root in roots_less_1: string_aux = f'(z-{root})*' string = string + string_aux string = string[:-1] pol1 = sym.sympify(string) pol1 = sym.Poly(pol1, z) coefs1 = pol1.coeffs() string = '0+' for k in range(n): string_aux = f'z**({n}-{k}-1)+' string = string + string_aux string = string[:-1] pol2 = sym.sympify(string) pol2 = sym.Poly(pol2, z) coefs2 = pol2.coeffs() ck = [i/j for i,j in zip(coefs1, coefs2)] ck_real = np.array([sym.re(i) for i in ck]) sum_ck = np.dot(ck_real,ck_real) norm = math.sqrt(sum_ck) ck_norm = [i/norm for i in ck_real] ck_norm = ck_norm[::-1] return np.array(ck_norm)
def extend(self, y: sp.Symbol, n: int, ext_irr: sp.Poly): self.y = y self.ext_irr = ext_irr self.ext_elements = [sp.Poly(0, self.ext_irr.gens[::-1], modulus=self.p)] + \ [sp.Poly(self.y ** i, self.ext_irr.gens[::-1], modulus=self.p) for i in range(n)] for i in range(n, self.dim**n): el = sp.rem(sp.Poly(self.y**i, self.y), self.ext_irr, modulus=self.p, symmetric=False) el = sp.rem(sp.Poly(el, el.gens[::-1]), self.irr, modulus=self.p, symmetric=False) if el not in self.ext_elements: self.ext_elements.append(el) else: if el == 1 and len(self.elements) == self.dim: print( 'Last element is 1. Irreducible polynomial is really primitive.' ) else: raise ValueError( 'Repeated field element detected; please make sure your irreducible polynomial is primitive.' )
def __init__(self, x: sp.Symbol, p: int, n: int, irr: sp.Poly): # Extension parameters self.ext_elements = None self.ext_irr = None self.y = None self.p = p self.n = n self.irr = irr self.x = x self.dim = p**n # Initial elements self.elements = [sp.Poly(0, self.x, modulus=self.p)] + \ [sp.Poly(self.x ** i, self.x, modulus=self.p) for i in range(n)] for i in range(n, self.dim): el = sp.rem(sp.Poly(self.x**i, x), self.irr, modulus=p, symmetric=False) if el not in self.elements: self.elements.append(el) else: if el == 1 and len(self.elements) == self.dim: print( 'Last element is 1. Irreducible polynomial is really primitive.' ) else: raise ValueError( 'Repeated field element detected; please make sure your irreducible polynomial is primitive.' )
def main(): print "Root Locus Extras" print "Methods to add functionality to control.matlab.rlocus" print "requires control.matlab package" print "suggested usage: import homework8.root_locus_extras as rlx" _s = sympy.Symbol("s") _S = 1 / ((_s + 1) * (_s + 2) * (_s + 10)) _numerS = map(float, sympy.Poly(_S.as_numer_denom()[0], _s).all_coeffs()) _denomS = map(float, sympy.Poly(_S.as_numer_denom()[1], _s).all_coeffs()) _tf = matlab.tf(_numerS, _denomS) _gain = 164.5 _damping_ratio = 0.174 _gain = gainFromDampingRatio(_tf, _damping_ratio) _poles = polesFromTransferFunction(_tf) _overshoot = overshootFromDampingRatio(_tf, _damping_ratio) _damping_ratio = dampingRatioFromGain(_tf, _gain) print "example: " print "system = ", _tf print "Damping Ratio provided: ", _damping_ratio print "Calculated values:" print "Gain: ", _gain print "Poles: ", _poles print "Overshoot: ", _overshoot print "Damping Ratio: ", dampingRatioFromGain(_tf, _gain) print "Overshoot: ", overshootFromGain(_tf, _gain) print "Frequency:", frequencyFromGain(_tf, _gain)
def rational_inequality_solve(eqn): lhs = eqn.lhs numerator, denominator = lhs.as_numer_denom() numerator, denominator = sympy.Poly(numerator), sympy.Poly(denominator) relation_operator = eqn.rel_op return sympy.solve_rational_inequalities([[((numerator, denominator), relation_operator)]])
def get_legendre_poly(n, sym, r): a = r[0] b = r[1] c = (a + b) / 2 m = 2 / (b - a) print sym, n if n == 0: const_val = np.sqrt(1.0 / (b - a)) return SampledPolynomial(sympy.Poly(const_val, *base_syms, domain='RR'), None, inputs=inputs) sym_n = (sym - c) * m p = sympy.expand((sym * sym - 1)**n) for i in range(n): p = p.diff() p = p.subs(sym, sym_n) return SampledPolynomial(sympy.Poly( (1 / ((2**n) * scipy.misc.factorial(n))) * np.sqrt(n + 0.5) * p, *base_syms, domain='RR'), None, inputs=inputs)
def symbolic_transfer_function( eq: Union[sp.Expr, int, float]) -> ct.TransferFunction: """ Transform a symbolic equation to a transfer function (sympy -> control) :param eq: your symbolic sympy based equation :return: a control Transfer Function class """ s = sp.var('s') try: if eq.is_real: pass except: if not isinstance(eq, float) and not isinstance(eq, int): used_symbols = [str(sym) for sym in eq.free_symbols] if not len(used_symbols) == 1 or "s" not in used_symbols: raise Exception( "invalid equation, please use correct transfer function equation (e.g. 1/(s**2+3))" ) n, d = sp.fraction(sp.factor(eq)) num = sp.Poly(sp.expand(n), s).all_coeffs() den = sp.Poly(sp.expand(d), s).all_coeffs() num: [float] = [float(v) for v in num] den: [float] = [float(v) for v in den] return ct.TransferFunction(num, den)
def polynomial_gcd(a, b): """Function to find gcd of two poly1d polynomials. Return gcd, s, t, u, v with a s + bt = gcd (Bezout s theorem) a = u gcd b = v gcd Hence s u + t v = 1 These are used in diagimalize procedure """ s = sp.Poly(0, x, domain='QQ').as_expr() old_s = sp.Poly(1, x, domain='QQ').as_expr() t = sp.Poly(1, x, domain='QQ').as_expr() old_t = sp.Poly(0, x, domain='QQ').as_expr() r = b old_r = a while not is_zero_polynomial(r): quotient, remainder = sp.div(old_r, r, x) (old_r, r) = (r, remainder) (old_s, s) = (s, old_s - quotient * s) (old_t, t) = (t, old_t - quotient * t) # output "Bézout coefficients:", (old_s, old_t) # output "greatest common divisor:", old_r # output "quotients by the gcd:", (t, s) u, _ = sp.div(a, old_r, x, domain='QQ') v, _ = sp.div(b, old_r, x, domain='QQ') return old_r.as_expr(), old_s.as_expr(),\ old_t.as_expr(), u.as_expr(), v.as_expr()
def w_to_s(poly_ip, coef_norm=False): r""" Arraytool mostly uses polynomials defined in 's' domain, i.e., Laplace domain. So, this function can be used to convert a given polynomial from 'w' to 's' domain (w=-js). :param poly_ip: Input polynomial :param coef_norm: If `true`, the output polynomial will be normalized such that the coefficient of the highest degree term becomes 1. :rtype: Returns a polynomial of the same order, however defined in `w=-js` domain """ if (len(poly_ip) == 1): poly_op = np.array([[1]]) else: s = sp.Symbol('s'); w = sp.Symbol('w') poly_ip = sp.Poly(poly_ip.ravel().tolist(), w) poly_op = sp.simplify(poly_ip.subs(w, -1j * s)) # substitution poly_op = sp.Poly(poly_op, s).all_coeffs() poly_op = I_to_i(poly_op) poly_op = np.reshape(poly_op, (len(poly_op), -1)) if (coef_norm): poly_op = poly_op / poly_op[0] return poly_op
def _complete_helper(n): if n == 1: return sympy.Poly(1, p) else: s = sympy.Poly(0, p) for j in range(1, n): s += nCr(n-1, j-1)*_complete_helper(j)*sympy.Poly(1-p)**(j*(n-j)) return 1-sympy.simplify(s)
def test_finite_field(self): """ Ensures finite fields work in the finite field case. """ p1 = sympy.Poly([1, 5, 3, 7, 3], sympy.abc.x, domain=sympy.GF(11)) p2 = sympy.Poly([0], sympy.abc.x, domain=sympy.GF(11)) p3 = sympy.Poly([10], sympy.abc.x, domain=sympy.GF(11)) self.assertEqual(symbaudio.utils.poly.max_coeff(p1), 7) self.assertEqual(symbaudio.utils.poly.max_coeff(p2), 0) self.assertEqual(symbaudio.utils.poly.max_coeff(p3), 10)
def test_integer(self): """ Ensures Z works in the integer case. """ p1 = sympy.Poly([1, 5, 3, 7, 3], sympy.abc.x, domain="ZZ") p2 = sympy.Poly([0], sympy.abc.x, domain="ZZ") p3 = sympy.Poly([10], sympy.abc.x, domain="ZZ") self.assertEqual(symbaudio.utils.poly.max_coeff(p1), 7) self.assertEqual(symbaudio.utils.poly.max_coeff(p2), 0) self.assertEqual(symbaudio.utils.poly.max_coeff(p3), 10)
def convert(Vs): Vs = sy.simplify(Vs) num, den = sy.fraction(Vs) num = np.array(sy.Poly(num, s).all_coeffs(), dtype=np.complex64) den = np.array(sy.Poly(den, s).all_coeffs(), dtype=np.complex64) Vo_sig = sp.lti(num, den) print(Vo_sig) return Vo_sig
def findLine(x, y, num): #from second cam to first cam if num == 2: med = np.dot(K2.I, np.transpose([np.array([x, y, 1])])) xs = sp.symbols('xs:4') EQ1 = T2[0][0] * xs[0] + T2[0][1] * xs[1] + T2[0][2] * xs[2] + T2[0][ 3] - xs[3] * med[0] EQ2 = T2[1][0] * xs[0] + T2[1][1] * xs[1] + T2[1][2] * xs[2] + T2[1][ 3] - xs[3] * med[1] EQ3 = T2[2][0] * xs[0] + T2[2][1] * xs[1] + T2[2][2] * xs[2] + T2[2][ 3] - xs[3] * med[2] solution = sp.solve([EQ1, EQ2, EQ3], xs[:-1]) #print(solution) med2 = sp.Matrix( np.dot(K1, np.transpose([np.array([xs[0], xs[1], xs[2]])])) / xs[2]).subs(solution) med2.subs(solution) #print(med2) ab = sp.symbols('ab:2') EQ5 = ab[1] - med2[1] EQ4 = ab[0] - med2[0] solution2 = sp.solve([EQ4, EQ5], {ab[0], xs[3]}) line = solution2[0][ab[0]] ploy = sp.Poly(line, ab[1]) #print (a.coeffs()) return ploy.coeffs() #from third cam to first cam if num == 3: med = np.dot(K3.I, np.transpose([np.array([x, y, 1])])) xs = sp.symbols('xs:4') EQ1 = T3[0][0] * xs[0] + T3[0][1] * xs[1] + T3[0][2] * xs[2] + T3[0][ 3] - xs[3] * med[0] EQ2 = T3[1][0] * xs[0] + T3[1][1] * xs[1] + T3[1][2] * xs[2] + T3[1][ 3] - xs[3] * med[1] EQ3 = T3[2][0] * xs[0] + T3[2][1] * xs[1] + T3[2][2] * xs[2] + T3[2][ 3] - xs[3] * med[2] solution = sp.solve([EQ1, EQ2, EQ3], xs[:-1]) #print(solution) med2 = sp.Matrix( np.dot(K1, np.transpose([np.array([xs[0], xs[1], xs[2]])])) / xs[2]).subs(solution) med2.subs(solution) #print(med2) ab = sp.symbols('ab:2') EQ5 = ab[1] - med2[1] EQ4 = ab[0] - med2[0] solution2 = sp.solve([EQ4, EQ5], {ab[0], xs[3]}) line = solution2[0][ab[0]] ploy = sp.Poly(line, ab[1]) #print (a.coeffs()) return ploy.coeffs()