def stepSizeSteepestDescent(f,x0,g0): """ Description : Calculates the minimized step size for the steepest descent algorithm using Newton's 1D method Parameters: 1. f : symbolic symbolic representation of the function f 2. x0 : list of independant variables for the function 3. g0 : gradient value at point x0 as a numpy matrix Output: gradient vector as numpy matrix """ phi,alpha = symbols('phi alpha') Q = hessian(f,X) if (poly(f).is_quadratic): return float(g0*g0.transpose()/matrix2numpy(g0*Q*g0.transpose())) else: xStar = x0 - squeeze(asarray(alpha*g0)) def alphaValue(phi,a0): return phi.subs([(alpha,a0)]) a0 = 0. phi = fValue(f,xStar) while (True): a = a0 a0 = a0 - alphaValue(diff(phi,alpha),a0)/alphaValue(diff(diff(phi,alpha),alpha),a0) if (abs(a-a0)<epsilon): return a0
def calcpv(pvrange,pvinx1, pvinx2, sipx, sipy, tpvx, tpvy): """Calculate the PV coefficient expression as a function of CD matrix parameters and SIP coefficients Parameters: ----------- pvrange (list) : indices to the PV keywords pvinx1 (int): first index, 1 or 2 pvinx2 (int): second index tpvx (Sympy expr) : equation for x-distortion in TPV convention tpvy (Sympy expr) : equation for y-distortion in TPV convention sipx (Sympy expr) : equation for x-distortion in SIP convention sipy (Sympy expr) : equation for y-distortion in SIP convention Returns: -------- Expression of CD matrix elements and SIP polynomial coefficients """ x, y = symbols("x y") if (pvinx1 == 1): expr1 = tpvx expr2 = sipx elif (pvinx1 == 2): expr1 = tpvy expr2 = sipy else: raise Valuerror, 'incorrect first index to PV keywords' if (pvinx2 not in pvrange): raise ValueError, 'incorrect second index to PV keywords' exec("pvar = 'pv%d_%d'"%(pvinx1, pvinx2)) xord = yord = 0 if expr1.coeff(pvar).has(x): xord = poly(expr1.coeff(pvar)).degree(x) if expr1.coeff(pvar).has(y): yord = poly(expr1.coeff(pvar)).degree(y) return(expr2.coeff(x,xord).coeff(y,yord))
def expectation(self, expr, var, evaluate=True, **kwargs): """ Expectation of expression over distribution """ # TODO: support discrete sets with non integer stepsizes if evaluate: try: p = poly(expr, var) t = Dummy('t', real=True) mgf = self.moment_generating_function(t) deg = p.degree() taylor = poly(series(mgf, t, 0, deg + 1).removeO(), t) result = 0 for k in range(deg+1): result += p.coeff_monomial(var ** k) * taylor.coeff_monomial(t ** k) * factorial(k) return result except PolynomialError: return summation(expr * self.pdf(var), (var, self.set.inf, self.set.sup), **kwargs) else: return Sum(expr * self.pdf(var), (var, self.set.inf, self.set.sup), **kwargs)
def generate_poly(hyper, params): """ Create a symbolic polynomial for the moments. """ k, d = hyper['k'], hyper['d'] #atoms = { # (h,) : symbols('h_%d'%h) # for h in xrange(1, k+1) # } #atoms[(k,)] = 1. - sum( symbols('h_%d'%h) for h in xrange(1, k) ) atoms = {} for h in xrange(1,k+1): atoms.update({ (h,x1) : symbols('x_%d%d'%(h,x1)) for x1 in xrange(1,d+1) }) #atoms[(h,d)] = 1. - sum(symbols('x_%d%d'%(h,x1)) for x1 in xrange(1,d)) m = {} for x1 in xrange(1,d+1): m[(x1,)] = poly( sum( atoms[(h,x1)] for h in xrange(1,k+1) ) ) for x2 in xrange(1,d+1): m[(x1,x2)] = poly( sum( atoms[(h,x1)] * atoms[(h,x2)] for h in xrange(1,k+1) ) ) for x3 in xrange(1,d+1): m[(x1,x2,x3)] = poly( sum( atoms[(h,x1)] * atoms[(h,x2)] * atoms[(h,x3)] for h in xrange(1,k+1) ) ) return m
def cs3_0(expr): if as_cs: out0 = '\n[整理] ' + str(normal0(expr)) expr0 = str(numer(cancel(sigma(expr)))) expr2 = numer(cancel(sigma(expr))) else: out0 = '\n[整理] ' + str(normal1(expr)) expr0 = str(numer(cancel(expr))) expr2 = numer(cancel(expr)) s_bc, s_ca, s_ab = (b - c) ** 2, (c - a) ** 2, (a - b) ** 2 deg0 = judge1(expr0) fnum = dict1(deg0).__len__() varlistf = sympy.symbols('v:{}:a'.format(fnum)) s_a, s_b, s_c = 0, 0, 0 for i in range(0, fnum): s_a += varlistf[i] * dict1(deg0)[i] s_b += varlistf[i] * sympy.simplify(ex_0('{0}'.format(dict1(deg0)[i]))) s_c += varlistf[i] * sympy.simplify(ex_1('{0}'.format(dict1(deg0)[i]))) ineq = s_a * s_bc + s_b * s_ca + s_c * s_ab ineq0 = expand(s_a * s_bc + s_b * s_ca + s_c * s_ab) func0 = sympy.poly(ineq0 - expr2, a, b, c) equlist0 = [] for i in range(0, dict0(deg0).__len__()): equlist0.append(func0.coeff_monomial(dict0(deg0)[i])) ans = solve(equlist0, varlistf) result0 = ineq.subs(ans) result2_a, result2_b, result2_c = s_a.subs(ans), s_b.subs(ans), s_c.subs(ans) result0 = str(result0) varlistf0 = [str(varlistf[i]) for i in range(0, fnum)] varlistf1, i = [], 0 result2 = s_a.subs(ans) for j in range(0, fnum): if varlistf0[j] in result0: varlistf1.append(varlistf0[j]) fnum0 = varlistf1.__len__() if fnum0 == 0: out0 += '\n[结果] ' + 'Σ (' + str(result2) + ') * (b - c) ** 2' else: out0 += '\n[通式] ' + 'Σ (' + str(result2) + ') * (b - c) ** 2' varlistf2 = [[] for _ in range(0, fnum0)] for k in range(0, fnum0): varlistf2[k] = sympy.symbols(varlistf1[k]) varlistf3 = [varlistf2[i] for i in range(0, fnum0)] out0 += '\n[参数] ' + str(varlistf2) if judge1(expr0) == 4: add_a = sympy.poly(result2_a, a, b, c) equlist_4_1 = [add_a.coeff_monomial(c ** 2) - add_a.coeff_monomial(a ** 2)] equlist_4_2 = [add_a.coeff_monomial(a ** 2) - add_a.coeff_monomial(b ** 2)] add0_4 = solve(equlist_4_1 + equlist_4_2, varlistf3) result2 = numer(factor(add_a.subs(add0_4))) out0 += '\n[默认] ' + 'Σ (' + str(result2) + ') * (b - c) ** 2' if judge1(expr0) >= 5: add_a = sympy.poly(result2_a, a, b, c) add0_5 = {varlistf2[i]: 0 for i in range(0, fnum0)} result2 = numer(factor(add_a.subs(add0_5))) out0 += '\n[默认] ' + 'Σ (' + str(result2) + ') * (b - c) ** 2' return [out0, str(result2)]
def LP_from_stdin(stdin, do_prompt=True): """ :returns: (constraints_matrix, objective_func) """ if do_prompt and stdin.istty(): prompt = stdout.write else: # Do not write prompts for non-interactive sessions. prompt = lambda text: None prompt("Enter objective function (e.g. x + y - 3z): ") objective = sympy.poly( parse_expr_and_transform(stdin.readline()) ) prompt("Enter constraints, one per line, terminate with empty line\n") prompt( "Constraints are of the form 'x + y - 3z <= 100', only " "less than constraints are allowed" ) prompt("NOTE: all variables are assumed to be non-negative\n") constraints = [] while True: constraint_raw = stdin.readline() if not constraint_raw: break constraint = parse_expr_and_transform(constraint_raw) assert isinstance( constraint, LessThan), "Only LessThan constraints are allowed" constraint_poly = sympy.poly( (constraint.args[0] - constraint.args[1]).simplify() ) assert constraint_poly.is_linear, \ "Only linear constraints are allowed" constraints.append(constraint_poly) # Convert constraints and objective func to the matrix form. used_vars = sorted( set(sum([c.gens for c in constraints], ()) + objective.gens) ) # NOTE: constants do not affect the value of the objective function. objective_row = [ get_coeff_from_poly(objective, var) for var in used_vars ] constraints_matrix = [ [ get_coeff_from_poly(c, var) for var in used_vars ] + [-get_constant_from_poly(c)] for c in constraints ] return (np.array(constraints_matrix), np.array(objective_row), map(str, used_vars))
def plot_residuals(ts, p_poly, q_poly, d_poly, p_ARIMA_coeffs, q_ARIMA_coeffs, pacf_max=100, ): fig, (ax1, ax2, ax3) = plt.subplots(3, 1) ts = ts.astype(float) if p_poly is not None: est_p_poly: poly = poly(p_poly.subs(dict(zip(p_symbols, p_ARIMA_coeffs))), B) else: est_p_poly = None if q_poly is not None: est_q_poly: poly = poly(q_poly.subs(dict(zip(q_symbols, q_ARIMA_coeffs))), B) else: est_q_poly = None print("est_p_poly:", est_p_poly) print("est_q_poly:", est_q_poly) # remember: use non-differenced series model_err = spp.calculateSeasonalARIMA_error(ts, est_p_poly, d_poly, est_q_poly) # step: differencing error, to test if if the noise term is describable by a MA(1) process model_err_sec = model_err[:-1] - model_err[1:] ax1.plot(model_err_sec, label='consec. differenced residuals') rks3 = compute_rks3(model_err_sec) res_95 = compute_safe_conf_95(rks3) ax2.plot(rks3, label='corellogram') ax2.vlines(np.arange(0, len(rks3)), 0, rks3, color="tab:red") ax2.plot(res_95, label='est. upper 95% conf. interval, ') ax2.plot(-res_95, label='est. lower 95% conf. interval,') # remember: pacf calculation can be unstable. Lag_max is a function of convergence: the faster it converges, # the smaller the pacf_max possible. ts_pacf = stt.pacf(rks3, nlags=pacf_max) ts_pacf_95 = np.sqrt(1 / len(rks3)) ax3.plot(ts_pacf, label='pacf') ax3.plot([ts_pacf_95] * pacf_max, label='est. upper 95% conf. interval') ax3.plot([-ts_pacf_95] * pacf_max, label='est. lower 95% conf. interval') ax3.vlines(np.arange(0, len(ts_pacf)), 0, ts_pacf, color="tab:red") ax1.set_ylabel('Error') ax1.set_xlabel('t') ax1.legend() ax2.set_ylabel('Estimated corr. coeff.') ax2.set_xlabel('t') ax2.legend() ax3.set_ylabel('pacf.') ax3.set_xlabel('t') ax3.legend() return fig, (ax1, ax2, ax3)
def SyHa(P, Q, j, v): P = poly(P) Q = poly(Q) p = P.degree(v) q = Q.degree(v) # assert P.gens == Q.gens coef = partial(coefs, p + q - j, v) return Matrix([coef(P * v**k) for k in range(q - j - 1, -1, -1)] + [coef(Q * v**k) for k in range(0, p - j, 1)])
def iter_proj(proj_set, x): p_out = [] for aux in proj1(proj_set, x): p_out.append(poly(aux)) for aux in proj2(proj_set, x): p_out.append(poly(aux)) print('p_out: ', p_out) return p_out
def useLC(remainders, quotients, count, gcd, lc, dom, m): return EEA(remainders, quotients, count, gcd, dom, m, lcPoly=poly(lc, x, domain=dom), oneP=poly(1, x, domain=dom))
def poly_from_sympy(xpr, symbol='s'): """ Convert Sympy transfer function polynomial to Scipy LTI """ s = sy.Symbol(symbol) num, den = sy.simplify(xpr).as_numer_denom() # expressions p_num_den = sy.poly(num, s), sy.poly(den, s) # polynomials c_num_den = [sy.expand(p).all_coeffs() for p in p_num_den] # coefficients # convert to floats l_num, l_den = [sy.lambdify((), c)() for c in c_num_den] return l_num, l_den
def EuclidsAlgorithm(a, b, m, dom): #the following statements set the polynomials in their domain and prepares them for further use a = poly(a) b = poly(b) a = a.as_poly(domain=dom) b = b.as_poly(domain=dom) ab = largesmall(a, b) a = ab[0] b = ab[1] #divide to obtain quotient q and remainder r q, r = div(a, b, domain=dom) #create empty arrays to accumulate quotients and remainders remainders = [ab[0], ab[1]] quotients = [[0], [0]] remainders.append(r) quotients.append(q) #loop collects remainders and quotients untill divide by 0 error, count used to determinne gcd x = True count = 2 while x: try: count += 1 q, r = div(remainders[count - 2], remainders[count - 1], domain=dom) remainders.append(r) quotients.append(q) except: x = False #the last value in remainders will always be 0, thus the gcd is the penultimate element in the list temp = remainders[count - 2] gcd = temp #obtain leading coefficient->lc for use in obtaining monic equation Aa+Bb=gcd, made into its own sympy polynomial for div # to make the gcd a monic polynomial we divide it by its leading coefficient, luckily sympy has a function for that # we then take gcd as a polynomial argument to use for printing later lc = gcd.all_coeffs()[0] lc = sympify(float(lc)) gcd = monic(gcd) gcd = Polynomial(gcd.all_coeffs()[::-1]) #printData prints Recursive division, GCD, and rearanngement of equations so the user can see how the inverse euclid #algorithm s obtained printData(remainders, quotients, count, gcd) #use lc is used to circumvent sympy bug which doesnt allow for polynomials of degree 0 unless in function arguments useLC(remainders, quotients, count, gcd, lc, dom, m)
def simplify_n_monic(tt): num, den = sp.fraction(sp.simplify(tt)) num = sp.poly(num, s) den = sp.poly(den, s) lcnum = sp.LC(num) lcden = sp.LC(den) return (sp.simplify(lcnum / lcden) * (sp.monic(num) / sp.monic(den)))
def generatePoly (n): symbols = [] for i in range(n+1): symbols.append(sp.symbols(f"a_{i}", positive = True, real = True)) s = sp.symbols('s') result = sp.poly(0, s) for x in range(n+1): result = result.add(sp.poly(symbols[x]*s**x,s)) return result, symbols
def test_simple_basis(): """ Test the creation of a quotient basis """ x,y = sp.symbols('x,y') f1 = sp.poly( x**2 + y - 1, domain = 'C' ) f2 = sp.poly( 2*x**2 + x*y + 2*y**2 + 1, domain = 'C' ) I = [f1,f2] syms = [x,y] g_basis = sp.polys.groebner(I, *syms, order='grlex') q_basis = get_quotient_basis(I, *syms) assert len(q_basis) == 4
def test_Cox_refine(self): """ Use 1-homogeneous partition and refine computation. """ import sympy as sym # Define tols tol = 1e-4 tracktol = 1e-8 finaltol = 1e-8 singtol = 0. tracktolr = 1e-14 finaltolr = 1e-14 singtol = 0. x, y, z = sym.symbols('x, y, z') pol = pypolsys.utils.fromSympy([ sym.poly(x**2 + y + z - 1, (x, y, z)), sym.poly(x + y**2 + z - 1, (x, y, z)), sym.poly(x + y + z**2 - 1, (x, y, z)) ]) # Pass it to POLSYS_PLP pypolsys.polsys.init_poly(*pol) # Create homogeneous partition part = pypolsys.utils.make_h_part(3) # Pass it to POLSYS_PLP pypolsys.polsys.init_partition(*part) # Solve with loose tolerances bplp = pypolsys.polsys.solve(tracktol, finaltol, finaltol) # Get the roots, array of size (N+1) x bplp r0 = pypolsys.polsys.myroots # Get status of the solving process pypolsys.polsys.report() # Create References solution. ref = np.zeros((3, 5)) sol = [(1., 0., 0.), (0., 1., 0.), (0., 0, 1.), (-1. + np.sqrt(2.), -1. + np.sqrt(2.), -1. + np.sqrt(2.)), (-1. - np.sqrt(2.), -1. - np.sqrt(2.), -1. - np.sqrt(2.))] for i, s in enumerate(sol): ref[:, i] = s # Compute error with loose bounds err0 = sort_ref_found(ref, r0) # Refine one-half of the solutions path1 = np.array([1, 3, 5, 8]) pypolsys.polsys.refine(path1, tracktolr, finaltolr, finaltol) path2 = np.array([2, 4, 6, 7]) pypolsys.polsys.refine(path2, tracktolr, finaltolr, finaltol) # Get refine solution rr = pypolsys.polsys.myroots # Compute error with tight bounds errr = sort_ref_found(ref, rr) # Check error is lower than before self.assertTrue(errr * 100 < err0)
def test_normality(n=4): x = sympy.Symbol("x") p = sympy.poly(x) iterator = orthopy.c1.chebyshev2.Eval(p, "normal") for k, val in enumerate(itertools.islice(iterator, n)): if k == 0: val = sympy.poly(val, x) # sympy integration isn't only slow, but also wrong, # <https://github.com/sympy/sympy/issues/19427> # assert _integrate(val ** 2, x) == 1 assert _integrate_poly(val**2) == 1
def test_simple_basis(): """ Test the creation of a quotient basis """ x, y = sp.symbols('x,y') f1 = sp.poly(x**2 + y - 1, domain='C') f2 = sp.poly(2 * x**2 + x * y + 2 * y**2 + 1, domain='C') I = [f1, f2] syms = [x, y] g_basis = sp.polys.groebner(I, *syms, order='grlex') q_basis = get_quotient_basis(I, *syms) assert len(q_basis) == 4
def test_normality(d, standardization, n=4): X = [sympy.symbols(f"x{k}") for k in range(d)] p = [sympy.poly(x, X) for x in X] evaluator = orthopy.enr2.Eval(p, standardization) vals = next(evaluator) val = sympy.poly(vals[0], X) assert _integrate_poly(val**2, standardization) == 1 for k in range(n + 1): vals = next(evaluator) for val in vals: assert _integrate_poly(val**2, standardization) == 1
def test_horner_dense(self): """ Test horner, dense and standard approach on a simple test case, without solution at infnity. """ import sympy as sym tol = 1e-4 # due to reference solution tracktol = 1e-8 finaltol = 1e-14 singtol = 0. # Example from https://nextjournal.com/saschatimme/homotopy-continuation-crash-course x, y = sym.symbols('x, y') monoms = pypolsys.utils.fromSympy( [sym.poly(x**2 + 2 * y, (x, y)), sym.poly(y**2 - 2, (x, y))]) # 1-Homogeneous pypolsys.polsys.init_poly(*monoms) part = pypolsys.utils.make_h_part(2) pypolsys.polsys.init_partition(*part) # Solve and Store results b1 = pypolsys.polsys.solve(tracktol, finaltol, singtol) r1 = pypolsys.polsys.myroots.copy() # Use dense dmonoms = pypolsys.utils.toDense(*monoms) pypolsys.polsys.init_poly(*dmonoms) pypolsys.polsys.init_partition(*part) # Solve and Store results b1dense = pypolsys.polsys.solve(tracktol, finaltol, singtol, False) r1dense = pypolsys.polsys.myroots.copy() # Use dense AND Horner # Need to associate pypolsys.polsys.init_poly(*dmonoms) pypolsys.polsys.init_partition(*part) # Solve and Store results b1denseH = pypolsys.polsys.solve(tracktol, finaltol, singtol, True) r1denseH = pypolsys.polsys.myroots.copy() # Ref solution ref = np.array([[-2.51712e-32 - 1.68179j, 1.41421 - 3.69779e-32j], [1.68179 + 1.54074e-33j, -1.41421 - 1.54074e-33j], [2.51712e-32 + 1.68179j, 1.41421 - 3.69779e-32j], [-1.68179 - 1.54074e-33j, -1.41421 - 1.54074e-33j]]).T # Need to sort both solutions in the same way err0 = sort_ref_found(ref, r1) # standard err1 = sort_ref_found(ref, r1dense) # dense err2 = sort_ref_found(ref, r1denseH) # dense + horner self.assertTrue(err0 < tol) self.assertTrue(err1 < tol) self.assertTrue(err2 < tol)
def test_basis(self): x, y = sp.symbols('x y') b = Basis.from_degree(2, 3, hom=True) # Should not return error b.check_can_represent(sp.poly(x**2 * y**4)) with self.assertRaises(ValueError): # Degree too high b.check_can_represent(sp.poly(x**7)) with self.assertRaises(ValueError): # Not homogeneous b.check_can_represent(sp.poly(x**2 * y**3))
def _find_Psi(self, AR, MA, p, q, m): # generate column-vector Psi from AR and MA polynomials phi = -np.flip(sym.poly(AR, B).all_coeffs()) the = -np.flip(sym.poly(MA, B).all_coeffs()) phi = np.concatenate((phi, np.zeros(m - p))) the = np.concatenate((the, np.zeros(m - q))) psi = [] for j in range(m + 1): psi_j = (the[j] - phi[1:j + 1] @ np.flip(psi[:j])) / phi[0] psi.append(psi_j) return np.array([psi]).T
def sc1_5(expr): print('[整理] ', normal0(expr)) expr0 = str(numer(cancel(sigma(expr)))) expr2 = numer(cancel(sigma(expr))) s_bc, s_ca, s_ab = (a - b) * (a - c), (b - c) * (b - a), (c - a) * (c - b) fnum = dict1(expr0).__len__() varlistf = sympy.symbols('v:{}:a'.format(fnum)) s_a, s_b, s_c = 0, 0, 0 for i in range(0, fnum): s_a += varlistf[i] * dict1(expr0)[i] s_b += varlistf[i] * sympy.simplify(ex_0('{0}'.format( dict1(expr0)[i]))) s_c += varlistf[i] * sympy.simplify(ex_1('{0}'.format( dict1(expr0)[i]))) ineq = s_a * s_bc + s_b * s_ca + s_c * s_ab ineq0 = expand(s_a * s_bc + s_b * s_ca + s_c * s_ab) func0 = sympy.poly(ineq0 - expr2, a, b, c) equlist0 = [] for i in range(0, dict0(expr0).__len__()): equlist0.append(func0.coeff_monomial(dict0(expr0)[i])) ans = solve(equlist0, varlistf) result0 = ineq.subs(ans) result2_a, result2_b, result2_c = s_a.subs(ans), s_b.subs(ans), s_c.subs( ans) result0 = str(result0) varlistf0 = [str(varlistf[i]) for i in range(0, fnum)] varlistf1, i = [], 0 result2 = s_a.subs(ans) print('[通式] ', 'Σ (', result2, ') * ( a - b ) * ( a - c )') for j in range(0, fnum): if varlistf0[j] in result0: varlistf1.append(varlistf0[j]) fnum0 = varlistf1.__len__() varlistf2 = [[] for i in range(0, fnum0)] for k in range(0, fnum0): varlistf2[k] = sympy.symbols(varlistf1[k]) varlistf3 = [varlistf2[i] for i in range(0, fnum0)] print('[参数] ', varlistf2) if judge1(expr0) == 4: add_a = sympy.poly(result2_a, a, b, c) equlist_4_1 = [add_a.coeff_monomial(c**2) - add_a.coeff_monomial(a**2)] equlist_4_2 = [add_a.coeff_monomial(a**2) - add_a.coeff_monomial(b**2)] add0_4 = solve(equlist_4_1 + equlist_4_2, varlistf3) result2 = numer(factor(add_a.subs(add0_4))) print('[默认] ', 'Σ (', result2, ') * ( a - b ) * ( a - c )') if judge1(expr0) >= 5: add_a = sympy.poly(result2_a, a, b, c) add0_5 = {varlistf2[i]: 1 for i in range(0, fnum0)} result2 = numer(factor(add_a.subs(add0_5))) print('[默认] ', 'Σ (', result2, ') * ( a - b ) * ( a - c )')
def fsagrowthtopolystrings(filename): f = open(filename, "r") lines = f.readlines() assert ('as previous' in lines[-1] and 'as previous' in lines[-2]) liness = lines[3:-2] line = '' for l in liness: line = line + (l.rstrip('\n')) numbegin = line.index('(') numend = line.index(')') denombegin = 1 + numend + (line[1 + numend:]).index('(') denomend = 1 + numend + (line[1 + numend:]).index(')') return sympy.poly(line[1 + numbegin:numend]).all_coeffs(), sympy.poly( line[1 + denombegin:denomend]).all_coeffs()
def pqr2_6_1(expr): if as_pqr: ineq0 = numer(cancel(sigma(expr))) else: ineq0 = numer(cancel(expr)) a, b, c = sympy.symbols('a, b, c') p, q, r = sympy.symbols('p, q, r') list1, list2, equlist0 = [], dict0(judge1(expr)), [] list0 = dict2(judge1(expr))[-1] fnum0, fnum1, result0, resultpqr = list0.__len__(), list2.__len__(), 0, 0 varlistf = sympy.symbols('c:{}:a'.format(fnum0)) for i in range(0, fnum0): list1.append(list0[i].subs({ p: (a + b + c), q: a * b + b * c + c * a, r: a * b * c })) result0 += list1[i] * varlistf[i] resultpqr += list0[i] * varlistf[i] result1 = sympy.poly(sympy.simplify(result0) - ineq0, a, b, c) for i in range(0, fnum1): equlist0.append(result1.coeff_monomial(list2[i])) ans = solve(equlist0, varlistf) result2 = factor(resultpqr.subs(ans)) return result2
def pqr2_6_2(expr): if as_pqr: ineq0 = numer(cancel(sigma(expr))) else: ineq0 = numer(cancel(expr)) a, b, c = sympy.symbols('a, b, c') p, q, r = sympy.symbols('p, q, r') deg0 = judge1(expr) poly0 = sympy.poly(ineq0, a, b, c) polydict0 = poly0.as_dict() all0 = list(zip(list(polydict0.keys()), list(polydict0.values()))) length0 = all0.__len__() listcy = [[] for _ in range(0, deg0 + 1)] listcy0 = [0 * a for _ in range(0, deg0 + 1)] for cy in range(1, deg0 + 1): for len in range(0, length0): if sum(all0[len][0]) == cy: listcy[cy].append((a**all0[len][0][0] * b**all0[len][0][1] * c**all0[len][0][2]) * all0[len][1]) count0 = listcy[cy].__len__() for i in range(0, count0): listcy0[cy] += listcy[cy][i] listcy0[cy] = sympy.simplify(listcy0[cy]) for len in range(0, length0): if sum(all0[len][0]) == 0: listcy0[0] = all0[len][1] result3 = listcy0[0] for i in range(1, deg0 + 1): if as_pqr: result3 += pqr2_6_1(str(listcy0[i])) / 3 else: result3 += pqr2_6_1(str(listcy0[i])) return result3
def sympy_polynomial_to_function(expr, symbs, func_name='sympy_polynomial', return_string=False): poly = sp.poly(sp.collect(sp.expand(expr), symbs), *symbs) input_names = map(attrgetter('name'), poly.gens) num_names = len(input_names) def term_string((powers, coeff)): indices = filter(lambda i: powers[i] != 0, range(num_names)) if indices: terms = map(lambda i: '(%s ** %s)' % (input_names[i], powers[i]), indices) return '%s * %s' % (float(coeff), ' * '.join(terms)) else: return '%s' % float(coeff) poly_str = ' + '.join(map(term_string, poly.terms())) function_str = 'def %s(%s):\n return %s' % ( func_name, ', '.join(input_names), poly_str) if return_string: return function_str exec_env = {} exec function_str in exec_env return exec_env[func_name]
def test_cubic2(): import sympy as sym x, t, c, L, dx = sym.symbols('x t c L dx') T = lambda t: 1 + sym.Rational(1, 2) * t # Temporal term # Set u as a 3rd-degree polynomial in space X = lambda x: sum(a[i] * x**i for i in range(4)) a = sym.symbols('a_0 a_1 a_2 a_3') u = lambda x, t: X(x) * T(t) # Force discrete boundary condition to be zero by adding # a correction term the analytical suggestion x*(L-x)*T # u_x = x*(L-x)*T(t) - 1/6*u_xxx*dx**2 R = sym.diff(u(x, t), x) - ( x * (L - x) - sym.Rational(1, 6) * sym.diff(u(x, t), x, x, x) * dx**2) # R is a polynomial: force all coefficients to vanish. # Turn R to Poly to extract coefficients: R = sym.poly(R, x) coeff = R.all_coeffs() s = sym.solve(coeff, a[1:]) # a[0] is not present in R # s is dictionary with a[i] as keys # Fix a[0] as 1 s[a[0]] = 1 X = lambda x: sym.simplify(sum(s[a[i]] * x**i for i in range(4))) u = lambda x, t: X(x) * T(t) print 'u:', u(x, t) # Find source term f = sym.diff(u(x, t), t, t) - c**2 * sym.diff(u(x, t), x, x) f = sym.simplify(f) print 'f:', f u_exact = sym.lambdify([x, t, L, dx], u(x, t), 'numpy') V_exact = sym.lambdify([x, t, L, dx], sym.diff(u(x, t), t), 'numpy') f_exact = sym.lambdify([x, t, L, dx, c], f) # Replace symbolic variables by numeric ones L = 2.0 Nx = 3 C = 0.75 c = 0.5 dt = C * (L / Nx) / c dx = dt * c / C I = lambda x: u_exact(x, 0, L, dx) V = lambda x: V_exact(x, 0, L, dx) f = lambda x, t: f_exact(x, t, L, dx, c) # user_action function asserts correct solution def assert_no_error(u, x, t, n): u_e = u_exact(x, t[n], L, dx) diff = abs(u - u_e).max() nt.assert_almost_equal(diff, 0, places=13) u, x, t, cpu = solver(I=I, V=V, f=f, c=c, L=L, dt=dt, C=C, T=4 * dt, user_action=assert_no_error)
def luhn_verify(number_to_verify): # Verifies that the card number of the account the user wishes to transfer money to passes the # Luhn algorithm. # number_to_verify: receiving account number, passed from outer function do_transfer() digit_list = [] control_number = 0 for digit in number_to_verify: digit_list.append(int(digit)) for index in range(len(digit_list)): if (index + 1) % 2 != 0 and index < 15: digit_list[index] *= 2 if digit_list[index] > 9 and index < 15: digit_list[index] -= 9 for index in range(len(digit_list)): if index < 15: control_number += digit_list[index] x = sympy.symbols("x") checksum = sympy.solve(sympy.poly(control_number + x, modulus=10))[0] if checksum < 0: checksum += 10 if digit_list[-1] == checksum: return True # Returns True if the Luhn algorithm was passed. else: return False # Returns False if the Luhn algorithm was not passed.
def test_get_sos_le_van_barel_1(self): polynomial = poly( '2*w**2 - 2*z*w + 8*z**2 - 2*y*z + y**2 - 2*y**2*w + y**4 - 4*x*y*z - 4*x**2*z + x**2*y**2 + 2*x**4' ) status, sos = get_sos(polynomial) self.assertEqual(status, 'Exact SOS decomposition found.') self.assertEqual(expand(sos.as_expr()), expand(polynomial).as_expr())
def gorner(self, f, x_value): x = Symbol('x') coof = poly(f).coeffs() ans = 0 for k in coof: ans = k + ans * x_value return ans
def sample_points(f, range_x=(-1.,1.), resolution=100): f = sp.poly(f.as_expr()) pts = [] for x in np.linspace(*(range_x + (resolution,))): for y in sp.polys.real_roots(f(x)): pts.append((float(x), float(y))) return np.array(pts)
def _is_linear(self, expr): try: # Check to see whether expression represents linear dynamics return sympy.poly(expr.rhs, *self.input_and_states).is_linear except PolynomialError: # Return false if not a polynomial return False
def integrate_h_profile( self, n_pts: int = 301, x_max: float = None, do_truncate: bool = True, do_use_newton: bool = False, ) -> None: """ Generate topographic profile by numerically integrating gradient. Uses simple quadrature. Args: n_pts: optional sample rate along each curve x_max: optional x-axis limit do_truncate: optionally omit that last couple of points? do_use_newton: optionally use Newton-Raphson method to find gradient values (default is to find these values algebraically) """ logging.info("gme.core.time_invariant.integrate_h_profile") x_max_: float = (float(Lc.subs(self.parameters)) if x_max is None else x_max) self.h_x_array: np.ndarray = np.linspace(0, x_max_, n_pts) px0_poly_eqn: Poly = poly( self.gmeq.poly_px_xiv0_eqn.subs(self.parameters), px) if do_truncate: h_x_array = self.h_x_array[:-2] gradient_array: np.ndarray = np.array([ gradient_value( x_, pz_=self.pz0, px_poly_eqn=px0_poly_eqn, do_use_newton=do_use_newton, ) for x_ in h_x_array ]) h_z_array: np.ndarray = cumtrapz(gradient_array, h_x_array, initial=0) h_z_interp: Callable = InterpolatedUnivariateSpline(h_x_array, h_z_array, k=2, ext=0) self.h_z_array: np.ndarray = h_z_interp(self.h_x_array) else: h_x_array = self.h_x_array # for x_ in h_x_array: # print(x_,self.gradient_value(x_,parameters=self.parameters)) gradient_array = np.array([ gradient_value( x_, pz_=self.pz0, px_poly_eqn=px0_poly_eqn, do_use_newton=do_use_newton, ) for x_ in h_x_array ]) self.h_z_array = cumtrapz(gradient_array, h_x_array, initial=0)
def _findRoots(self, convertToEne, fun, **args): if self.resultFileHandler: self.resultFileHandler.startLogAction("_findRoots") if self.hasCoeffs: allRoots = [] for eKey in self.alphas: alphas = self.alphas[eKey] betas = self.betas[eKey] k = sy.symbols('k') matLst = [] for m in range(self.numChannels): matLst.append([]) for n in range(self.numChannels): lm = self.kCal.l(m) ln = self.kCal.l(n) val = 0.0 for ci in range(self.numCoeffs): A = alphas[ci][m,n] B = betas[ci][m,n] val += (1.0/2.0)*(1.0/self.kCal.massMult)**(ci) * (QSToSympy(A)*k**(ln-lm+2*ci) - sy.I*QSToSympy(B)*k**(ln+lm+1+2*ci) ) matLst[len(matLst)-1].append(poly(val)) #matLst[len(matLst)-1].append(val) #v1 mat = sy_matrix(matLst) roots = fun(mat, k, **args) if convertToEne: mappedRoots = map(lambda val: self.kCal.e(val,True), roots) else: mappedRoots = map(lambda val: complex(val), roots) allRoots.extend(mappedRoots) if self.resultFileHandler: self.resultFileHandler.startLogAction("_findRoots") return allRoots
def ast3_0(expr): if as_ast: exprast = str(normal0(str(expr))) else: exprast = str(normal1(str(expr))) expr0, expr1 = [i for i in exprast], '' for i in range(0, expr0.__len__()): if expr0[i] == 'b': expr0[i] = '(a+s)' continue if expr0[i] == 'c': if ast: expr0[i] = '(a+t)' continue else: expr0[i] = '(a+s+t)' for i in range(0, expr0.__len__()): expr1 += expr0[i] expr1 = sympy.poly(sympy.simplify(expand(expr1)), a) deg0 = expr1.total_degree() expr2, expr3 = '', [] for n in range(0, deg0): expr_temp = factor(expr1.coeff_monomial(a**(deg0 - n))) expr2 += str(expr_temp * a**(deg0 - n)) + ' + ' expr3.append(expr_temp) constant0 = str(factor(expr1.coeff_monomial(a**0))) expr2 += constant0 expr3.append(constant0) return [expr2, expr3]
def test_orthogonality(d, n): X = [sympy.Symbol(f"x{k}") for k in range(d)] p = [sympy.poly(x, X) for x in X] evaluator = orthopy.cn.Eval(p) tree = numpy.concatenate([next(evaluator) for _ in range(n + 1)]) for f0, f1 in itertools.combinations(tree, 2): assert _integrate_poly(f0 * f1) == 0
def _get_data(dim, n, point_fun, symbolic): # points idxs = numpy.array(get_all_exponents(dim + 1, n)[-1]) points = point_fun(idxs) # weights weights = numpy.empty(len(points)) kk = 0 for idx in idxs: # Define the polynomial which to integrate over the simplex. t = sympy.DeferredVector("t") g = prod( sympy.poly((t[i] - point_fun(k)) / (point_fun(m) - point_fun(k))) for i, m in enumerate(idx) for k in range(m)) if isinstance(g, int): exp = [0] * (dim + 1) coeffs = g else: # make sure the exponents are all of the correct length exp = [list(m) + [0] * (dim - len(m) + 1) for m in g.monoms()] coeffs = g.coeffs() weights[kk] = sum(c * integrate_bary(m, symbolic) for c, m in zip(coeffs, exp)) kk += 1 return weights, points
def special_chromatic_polynomial(adj, N, tutte_polynomial, **kwargs): ''' This is the chromatic polynomial, derived from the Tutte polynomial The chromatic polynomial for a connected graphs evaluates T(x,y) at C(k) = T(x=1-k,y=0)*(-1)**N*(1-k)*N ''' tutte_adjust = [(coeff, xd - 1) for xd, yd, coeff in tutte_polynomial if yd == 1] from sympy.abc import x p = 0 for (coeff, power) in tutte_adjust: p += coeff * x ** power C = (-1) ** (N - 1) * x * p.subs(x, 1 - x) C = sympy.poly(C) coeff_list = [] for degree in range(0, N + 1): coeff = C.nth(degree) if coeff: key = (degree, int(coeff)) coeff_list.append(key) return tuple(coeff_list)
def mildorf_titu_andreescu(self): polynomial = poly( 'a**4*c**2 + b**4*a**2 + c**4*b**2 - a**3*b**2*c - b**3*c**2*a - c**3*a**2*b' ) status, sos = get_sos(polynomial) self.assertEqual(status, 'Exact SOS decomposition found.') self.assertEqual(expand(sos.as_expr()), expand(polynomial).as_expr())
def test_orthogonality(d, n, standardization): X = [sympy.symbols(f"x{k}") for k in range(d)] p = [sympy.poly(x, X) for x in X] evaluator = orthopy.enr2.Eval(p, standardization) vals = numpy.concatenate([next(evaluator) for _ in range(n + 1)]) for f0, f1 in itertools.combinations(vals, 2): assert _integrate_poly(f0 * f1, standardization) == 0
def homogenize(f,x,y,z): """ Returns the polynomial in homogenous coordinates. """ p = sympy.poly(f,[x,y]) d = max(map(sum,p.monoms())) F = sympy.expand( z**d * f.subs([(x,x/z),(y,y/z)]) ) return F, d
def constraints_tx_iter(): para = list(zip(txs, [0.0] * order)) c_global = constraints_global while len(para) > 1: tx = txs[-len(para)] para.pop(0) c_global.pop(0) yield tx, [poly(c.subs(para), tx).all_coeffs() for c in c_global]
def expectation(self, expr, var, evaluate=True, **kwargs): """ Expectation of expression over distribution """ if evaluate: try: p = poly(expr, var) t = Dummy('t', real=True) mgf = self._moment_generating_function(t) if mgf is None: return integrate(expr * self.pdf(var), (var, self.set), **kwargs) deg = p.degree() taylor = poly(series(mgf, t, 0, deg + 1).removeO(), t) result = 0 for k in range(deg+1): result += p.coeff_monomial(var ** k) * taylor.coeff_monomial(t ** k) * factorial(k) return result except PolynomialError: return integrate(expr * self.pdf(var), (var, self.set), **kwargs) else: return Integral(expr * self.pdf(var), (var, self.set), **kwargs)
def test_cubic2(): import sympy as sym x, t, c, L, dx = sym.symbols('x t c L dx') T = lambda t: 1 + sym.Rational(1,2)*t # Temporal term # Set u as a 3rd-degree polynomial in space X = lambda x: sum(a[i]*x**i for i in range(4)) a = sym.symbols('a_0 a_1 a_2 a_3') u = lambda x, t: X(x)*T(t) # Force discrete boundary condition to be zero by adding # a correction term the analytical suggestion x*(L-x)*T # u_x = x*(L-x)*T(t) - 1/6*u_xxx*dx**2 R = sym.diff(u(x,t), x) - ( x*(L-x) - sym.Rational(1,6)*sym.diff(u(x,t), x, x, x)*dx**2) # R is a polynomial: force all coefficients to vanish. # Turn R to Poly to extract coefficients: R = sym.poly(R, x) coeff = R.all_coeffs() s = sym.solve(coeff, a[1:]) # a[0] is not present in R # s is dictionary with a[i] as keys # Fix a[0] as 1 s[a[0]] = 1 X = lambda x: sym.simplify(sum(s[a[i]]*x**i for i in range(4))) u = lambda x, t: X(x)*T(t) print 'u:', u(x,t) # Find source term f = sym.diff(u(x,t), t, t) - c**2*sym.diff(u(x,t), x, x) f = sym.simplify(f) print 'f:', f u_exact = sym.lambdify([x,t,L,dx], u(x,t), 'numpy') V_exact = sym.lambdify([x,t,L,dx], sym.diff(u(x,t), t), 'numpy') f_exact = sym.lambdify([x,t,L,dx,c], f) # Replace symbolic variables by numeric ones L = 2.0 Nx = 3 C = 0.75 c = 0.5 dt = C*(L/Nx)/c dx = dt*c/C I = lambda x: u_exact(x, 0, L, dx) V = lambda x: V_exact(x, 0, L, dx) f = lambda x, t: f_exact(x, t, L, dx, c) # user_action function asserts correct solution def assert_no_error(u, x, t, n): u_e = u_exact(x, t[n], L, dx) diff = abs(u - u_e).max() nt.assert_almost_equal(diff, 0, places=13) u, x, t, cpu = solver( I=I, V=V, f=f, c=c, L=L, dt=dt, C=C, T=4*dt, user_action=assert_no_error)
def compute_plane_gradient(p1, p2, p3): # Equation of type: a x + b y + c z + d = 0. # Return gradient as 2D point: (-a / c, -b / c) # p1, p2, p3 are Point3D objects. plane_equation = Plane(p1, p2, p3).equation() plane_equation_poly = poly(str(plane_equation), gens=sp.symbols(['x', 'y', 'z'])) a = plane_equation_poly.diff('x') b = plane_equation_poly.diff('y') c = plane_equation_poly.diff('z') return (- a / c, - b / c)
def _get_coeffs(self): self.coeffs = [] x = sympy.symbols('x') for i in range(len(self.xy) - 1): polynomial = self.m[i] * (self.xy[i + 1][0] - x) ** 3 / (6 * self.dx[i]) polynomial += self.m[i + 1] * (x - self.xy[i][0]) ** 3 / (6 * self.dx[i]) polynomial += (self.xy[i][1] - self.m[i] * self.dx[i] ** 2 / 6) * (self.xy[i + 1][0] - x) / self.dx[i] polynomial += (self.xy[i + 1][1] - self.m[i + 1] * self.dx[i] ** 2 / 6) * (x - self.xy[i][0]) / self.dx[i] if polynomial == 0: self.coeffs.append([0, 0, 0, 0]) else: self.coeffs.append(sympy.poly(polynomial).all_coeffs())
def solve(p, l, r, plus): q = get_q(l, plus) f = p.subs(b, q) v = poly(f - r).intervals() s = [] if v: s = [i[0][0] for i in v if i[0][0] > 0 and i[0][0] == i[0][1]] return s
def by_evaluation(*pols, **args): r""" Creates a polynomial by evaluating each of pols with the arguments in **kwargs @param *pols polynomial list - list of polynomials to evaluate @param **kwargs symbol map - map of variable to value @return polynomial - is \sum (pol_i - pol_i(x))^2 """ ret = 0. for pol in pols: ret += (pol - pol.evalf(subs=args))**2 return sp.poly(ret)
def generate_poly(hyper, syms): """ Create a symbolic polynomial for the moments. """ k, d = hyper['k'], hyper['d'] atoms = {} for h in xrange(1,k+1): atoms.update({ (h,x1) : symbols(sym(h,x1)) for x1 in xrange(1,d+1) }) m = {} for x1 in xrange(1,d+1): m[(x1,)] = poly( sum( atoms[(h,x1)] for h in xrange(1,k+1) ), *syms, domain='RR') for x2 in xrange(x1,d+1): m[(x1,x2)] = poly( sum( atoms[(h,x1)] * atoms[(h,x2)] for h in xrange(1,k+1) ), *syms, domain='RR') # for x3 in xrange(x2,d+1): # m[(x1,x2,x3)] = poly( sum( atoms[(h,x1)] * atoms[(h,x2)] * atoms[(h,x3)] for h in xrange(1,k+1) ), *syms, domain='RR') return m
def test_cubic(): """ Test the simple quadratic (x-a)^2. """ a = 2. x = symbols('x') pol = poly( (x - a)**6 ) x_opt = a sol = polyopt.optimize_polynomial(pol) x_sol = sol[x] assert np.allclose( x_opt, x_sol, 1e-1 )
def get_reaction_orders(hazards, species): reaction_orders = [] # parse each hazard equation to determine the order of the reaction for reaction_id, hazard in enumerate(hazards): # we need to 'pythonify' the power sign in the hazard string py_hazard = string.replace(hazard, '^', '**') # expand the equation to it's canonical form py_hazard = str(sympy.expand(py_hazard)) # is degree of poly == reaction order? temp_poly = sympy.poly(py_hazard, sympy.symbols(species.keys())) poly_degree = sympy.polys.polytools.Poly.total_degree(temp_poly) reaction_orders.append(poly_degree) return reaction_orders
def make_transition_matrix(scaling, order): """Given the scaling function and the order this function generates the transition matrix Ps<-basis, where s is the standard basis. """ x = sp.symbols('x') transition_matrix = np.zeros([order, order], dtype=np.float64) for j in range(order): try: pol = sp.poly(scaling(order, j, x)) tmp = np.zeros(order, dtype=np.float64) pol_arr = np.flip(np.array(pol.all_coeffs(), dtype=np.float64), 0) for i in range(pol_arr.size): tmp[i] = pol_arr[i] transition_matrix[:, j] = tmp except: transition_matrix[0, 0] = 1.0 return transition_matrix
def _poly_factorable_over_field(p, domain): # Factor the char poly over the integers pz = sympy.factor(p, domain=domain) # Change expression like (a+b)**n -> (a+b) def reduce_power(fp): try: return fp.base except: return fp # Loop over the factors for term in pz.as_ordered_factors(): term_poly = sympy.poly(reduce_power(term)) # Check if the base factors are not linear # indicates can't be factored over choosen domain if term_poly.degree() > 1: return False return True
def parabolic_curvature(x, y, D): """ Another model of capillarian bend is described here """ # Those are generic lens describing parameters # and may be used to describe the curve y0 = y['y0'] y1 = y['y1'] ym = y['ym'] y2 = y['y2'] yf = y['yf'] h1 = abs(x) Din = D['Din'] Dout = D['Dout'] Dmax = D['Dmax'] h2 = h1 * Dout/Din hm = h1 * (0.5 * Dmax) / (0.5 * Din) # TODO lambdas might look better? # Define a specific parabola with y(40) = 1 def funn(pos): return 1. - (pos/85.5 - 1.) **2 # Normalize to the type 'A' lens entrance # and account for amplitude :: x/Din def fuxx(pos): return (1. * h1 / Din) * funn(pos) / funn(40) # Make it sympy.poly(x) if h1 <> 0: parapoly = poly(fuxx(XX)) coeffs = parapoly.all_coeffs() else: coeffs = [0., 0., 0.] # Reverse coefficients so they start with the lowest power coeffs.reverse() out = coeffs + [0., 0., 0.] # Convert to floats out = [float(val) for val in out] return out
def sizeControl(xac,canard,main,tail,configuration="both",ratio=0): """Returns area of either canard, tail, or coefficients of the equation ret= both, c, t Input: Canard, Wing, Tail location and aerodynamic properties Ouput: Canard, Tail surface Area""" ScA=sympy.Symbol("ScA") StA=sympy.Symbol("StA") Sxcg=sympy.Symbol("Sxcg") eq = (xac - Sxcg)/main.chord - main.cm/main.cl \ + canard.cl/main.cl*ScA*canard.dist_np/(main.surface*main.chord)*(canard.VelFrac)**2 \ + tail.cl/main.cl*StA* tail.dist_np/(main.surface*main.chord)*( tail.VelFrac)**2 if configuration=="both": eqP = sympy.poly(eq) return eq,eqP.coeffs() elif configuration=="c": return sympy.solve(eq.subs(ScA,ratio*StA)) elif configuration=="t": return sympy.solve(eq.subs(StA,ratio*ScA)) else: raise ValueError("Configuration Unknown")
def numeric_instance(self, ys, maxdeg = None): """ assign the matrix_monos ys and return an np matrix @params - ys: a list of numbers corresponding to self.matrix_monos @params - maxdeg: cutoff the matrix at this degree """ assert len(ys)==len(self.matrix_monos), 'the lengths of the moment sequence is wrong' G = self.get_LMI_coefficients() num_inst = np.zeros(len(self.row_monos)**2) for i,val in enumerate(ys): num_inst += -val*np.array(matrix(G[i])).flatten() num_row_monos = len(self.row_monos) mat = num_inst.reshape(num_row_monos,num_row_monos) if maxdeg is not None: deglist = [sp.poly(rm, self.vars).total_degree() for rm in self.row_monos] cutoffind = sum([int(d<=maxdeg) for d in deglist]) mat = mat[0:cutoffind, 0:cutoffind] return mat
def sizeStab(xac,canard,main,tail,stabMargin=0.1,configuration="both",ratio=0): """Returns area of either canard, tail, or coefficients of the equation ret= both, c, t Input: Canard, Wing, Tail location and aerodynamic properties Ouput: Canard, Tail surface Area""" ScA=sympy.Symbol("ScA") StA=sympy.Symbol("StA") Sxcg=sympy.Symbol("Sxcg") eq = xac/main.chord - stabMargin - Sxcg/main.chord \ + ScA*canard.dist_np/(main.surface*main.chord)*(canard.VelFrac)**2 *canard.clalpha/main.clalpha*(1+canard.wash)\ + StA*tail.dist_np /(main.surface*main.chord)*(tail.VelFrac)**2 *tail.clalpha /main.clalpha*(1+tail.wash) if configuration=="both": eqP = sympy.poly(eq) return eq,eqP.coeffs() elif configuration=="c": return sympy.solve(eq.subs({StA:ratio*ScA})) elif configuration=="t": return sympy.solve(eq.subs({ScA:ratio*StA})) else: raise ValueError("Configuration Unknown")
def build_random_polynomial(self): # Construct list of random coefficients and exponents. coef_exps_list = [] for index in range(POLY_TERMS): coef = np.random.randint(POLY_MIN_COEF, POLY_MAX_COEF, 1).tolist() exps = np.random.randint(0, POLY_MAX_DEGREE, self.n).tolist() coef_exps_list.append(tuple(coef + exps)) # Construct polynomial variables as x_1, x_2, ..., x_n. poly_vars = sp.symbols(['x_' + str(i + 1) for i in range(self.n)]) # Construct the terms of the polynomial. poly_terms = [] for coef_exps in coef_exps_list: coef = coef_exps[0] poly_term = [] for index, exponent in enumerate(coef_exps[1:]): poly_term.append(str(poly_vars[index]) + '**' + str(exponent)) poly_terms.append(str(coef) + ' * ' + ' * '.join(poly_term)) return poly(' + '.join(poly_terms), gens=poly_vars)
def polygon(F,X,Y,I): """ Computes a set of parameters and polynomials in one-to-one correspondence with the segments fo the Newton polygon of F. If ``I=2`` the correspondence is only with the segments with negative slope. The segment `\Delta` corresponding to the list `(q,m,l,\Phi)` is on the line `qj+mi=l` in the `(i,j)`-plane and .. math: \Phi = \sum_{(i,j) \in \Delta} a_{ij}Z^{(i-i_0)/q} where `i_0` is the smallest value of `i` such that there is a point `(i,j) \in \Delta`. Note that `\Phi \in \mathbb{L}[Z]`. INPUTS: -- ``F``: a polynomial in `\mathbb{L}[X,Y]` -- ``X,Y``: the variable defining ``F`` -- ``I``: a parameter OUTPUTS: -- ``(list)``: a list of tuples `(q,m,l,\Phi)` where `q,m,l` are integers with `(q,m) = 1`, `q>0`, and `\Phi \in \mathbb{L}[Z]`. """ # compute the coefficients and support of F P = sympy.poly(F,X,Y) a = _coefficient(P) support = a.keys() # compute the lower convex hull of F. # # since sympy.convex_hull doesn't include points on edges, we need # to compare back to the support. the convex hull will contain all # points. Those on the boundary are considered "outside" by sympy. hull = sympy.convex_hull(*support) if type(hull) == sympy.Segment: hull_with_bdry = support # colinear support is a newton polygon else: hull_with_bdry = [p for p in support if not hull.encloses(sympy.Point(p))] newton = [] # find the start and end points (0,J) and (I,0). Include points # along the i-axis if I==1. Otherwise, only include points with # negative slope if I==2 JJ = min([j for (i,j) in hull if i == 0]) if I == 2: II = min([i for (i,j) in hull if j == 0]) else: II = max([i for (i,j) in hull if j == 0]) testslope = -float(JJ)/II # determine largest slope with (0,JJ). If this is greater than the # test slope then there exist points above the line connecting # (0,JJ) with (II,0) this fact is used to deal with certain # borderline cases include_borderline_colinear = (type(hull) == sympy.Segment) for (i,j) in hull_with_bdry: # when the point is on the j-axis, the onle one we want is the # point (0,JJ) if i == 0: if j == JJ: slope = -sympy.oo else: slope = sympy.oo else: slope = float(j-JJ)/i if slope > testslope: include_borderline_colinear = True break # loop through all points on the boundary and determine if it's in the # newton polygon using a testslope method for (i,j) in hull_with_bdry: # when the point is on the j-axis, the onle one we want is the # point (0,JJ) if i == 0: if j == JJ: slope = -sympy.oo else: slope = sympy.oo else: slope = float(j-JJ)/i # if the slope is less than the test slope or if we're in the # case where we include points along the j=0 line then add the # point to the newton polygon if (slope < testslope) or (I==1 and j==0): newton.append((i,j)) elif (slope == testslope) and include_borderline_colinear: # borderline case is when there is only one segment from # (0,JJ) to (II,0). When this is the case, include all # points whose slope matches testslope newton.append((i,j)) newton.sort(key=itemgetter(1),reverse=True) # sort second in j-th coord newton.sort(key=itemgetter(0)) # sort first in i-th coord # # now that we have the newton polygon we compute the parameters # (q,m,l,Phi) for each side Delta on the polygon. # params = [] eps = 1e-14 N = len(newton) n = 0 while n < N-1: # determine slope of current line side = [newton[n],newton[n+1]] sideslope = sympy.Rational(side[1][1]-side[0][1],side[1][0]-side[0][0]) # check against all following points for colinearity by # comparing slopes. append all colinear points to side k = 1 for pt in newton[n+2:]: slope = float(pt[1]-side[0][1]) / (pt[0]-side[0][0]) if abs(slope - sideslope) < eps: side.append(pt) k += 1 else: # when we reach the end of the newton polygon we need # to shift the value of k a little bit so that the # last side is correctly captured if k == N-n-1: k -= # 1 break n += k # compute q,m,l such that qj + mi = l and Phi q = sideslope.q m = -sideslope.p l = q*side[0][1] + m*side[0][0] i0 = min(side, key=itemgetter(0))[0] Phi = sum(a[(i,j)]*_Z**sympy.Rational(i-i0,q) for (i,j) in side) Phi = sympy.Poly(Phi,_Z) params.append((q,m,l,Phi)) return params