def test_sympy_interaction(): pytest.importorskip("sympy") import sympy as sp x, y = sp.symbols("x y") f = sp.symbols("f") s1_expr = 1/f(x/sp.sqrt(x**2+y**2)).diff(x, 5) from pymbolic.sympy_interface import ( SympyToPymbolicMapper, PymbolicToSympyMapper) s2p = SympyToPymbolicMapper() p2s = PymbolicToSympyMapper() p1_expr = s2p(s1_expr) s2_expr = p2s(p1_expr) assert sp.ratsimp(s1_expr - s2_expr) == 0 p2_expr = s2p(s2_expr) s3_expr = p2s(p2_expr) assert sp.ratsimp(s1_expr - s3_expr) == 0
def test_sympy_interaction(): pytest.importorskip("sympy") import sympy as sp x, y = sp.symbols("x y") f = sp.Function("f") s1_expr = 1/f(x/sp.sqrt(x**2+y**2)).diff(x, 5) # pylint:disable=not-callable from pymbolic.interop.sympy import ( SympyToPymbolicMapper, PymbolicToSympyMapper) s2p = SympyToPymbolicMapper() p2s = PymbolicToSympyMapper() p1_expr = s2p(s1_expr) s2_expr = p2s(p1_expr) assert sp.ratsimp(s1_expr - s2_expr) == 0 p2_expr = s2p(s2_expr) s3_expr = p2s(p2_expr) assert sp.ratsimp(s1_expr - s3_expr) == 0
def test_ratsimp(): x = Symbol("x") y = Symbol("y") e = 1/x+1/y assert e != (x+y)/(x*y) assert ratsimp(e) == (x+y)/(x*y) e = 1/(1+1/x) assert ratsimp(e) == x/(x+1) assert ratsimp(exp(e)) == exp(x/(x+1))
def print_Div(self, rule): with self.new_step(): f, g = rule.numerator, rule.denominator fp, gp = f.diff(rule.symbol), g.diff(rule.symbol) x = rule.symbol ff = sympy.Function("f")(x) gg = sympy.Function("g")(x) qrule_left = sympy.Derivative(ff / gg, rule.symbol) qrule_right = sympy.ratsimp( sympy.diff(sympy.Function("f")(x) / sympy.Function("g")(x))) qrule = sympy.Eq(qrule_left, qrule_right) self.append("Aplicando la regla del cociente que es:") self.append(self.format_math_display(qrule)) self.append("{} y {}.".format(self.format_math(sympy.Eq(ff, f)), self.format_math(sympy.Eq(gg, g)))) self.append("Para hallar {}:".format( self.format_math(ff.diff(rule.symbol)))) with self.new_level(): self.print_rule(rule.numerstep) self.append("Para hallar {}:".format( self.format_math(gg.diff(rule.symbol)))) with self.new_level(): self.print_rule(rule.denomstep) self.append("Sutituyendo en la regla del cociente:") self.append(self.format_math(diff(rule)))
def print_Div(self, rule): with self.new_step(): f, g = rule.numerator, rule.denominator x = rule.symbol ff = sympy.Function("f")(x) gg = sympy.Function("g")(x) qrule_left = sympy.Derivative(ff / gg, rule.symbol) qrule_right = sympy.ratsimp( sympy.diff(sympy.Function("f")(x) / sympy.Function("g")(x))) qrule = sympy.Eq(qrule_left, qrule_right) self.append("Apply the quotient rule, which is:") self.append(self.format_math_display(qrule)) self.append("{} and {}.".format(self.format_math(sympy.Eq(ff, f)), self.format_math(sympy.Eq(gg, g)))) self.append("Find {}:".format( self.format_math(ff.diff(rule.symbol)))) with self.new_level(): self.print_rule(rule.numerstep) self.append("Find {}:".format( self.format_math(gg.diff(rule.symbol)))) with self.new_level(): self.print_rule(rule.denomstep) self.append( '<div class="collapsible"><h2>open answer</h2><ol class="content">Now plug in to the quotient rule to get:' ) self.append(self.format_math(diff(rule)) + '</ol></div>')
def _solsimp(e, t): no_t, has_t = powsimp(expand_mul(e)).as_independent(t) no_t = ratsimp(no_t) has_t = has_t.replace(exp, lambda a: exp(factor_terms(a))) return no_t + has_t
def print_Div(self, rule): with self.new_step(): f, g = rule.numerator, rule.denominator fp, gp = f.diff(rule.symbol), g.diff(rule.symbol) x = rule.symbol ff = sympy.Function("f")(x) gg = sympy.Function("g")(x) qrule_left = sympy.Derivative(ff / gg, rule.symbol) qrule_right = sympy.ratsimp( sympy.diff(sympy.Function("f")(x) / sympy.Function("g")(x))) qrule = sympy.Eq(qrule_left, qrule_right) self.append("Apply the quotient rule, which is:") self.append(self.format_math_display(qrule)) self.append("{} and {}.".format(self.format_math(sympy.Eq(ff, f)), self.format_math(sympy.Eq(gg, g)))) self.append("To find {}:".format( self.format_math(ff.diff(rule.symbol)))) with self.new_level(): self.print_rule(rule.numerstep) self.append("To find {}:".format( self.format_math(gg.diff(rule.symbol)))) with self.new_level(): self.print_rule(rule.denomstep) self.append("Now plug in to the quotient rule:") self.append(self.format_math(diff(rule)))
def test_pmint_logexp(): f = (1 + x + x*exp(x))*(x + log(x) + exp(x) - 1)/(x + log(x) + exp(x))**2/x g = log(x**2 + 2*x*exp(x) + 2*x*log(x) + exp(2*x) + 2*exp(x)*log(x) + log(x)**2)/2 + 1/(x + exp(x) + log(x)) # TODO: Optimal solution is g = 1/(x + log(x) + exp(x)) + log(x + log(x) + exp(x)), # but SymPy requires a lot of guidance to properly simplify heurisch() output. assert ratsimp(heurisch(f, x)) == g
def test_pmint_logexp(): if ON_TRAVIS: # See https://github.com/sympy/sympy/pull/12795 skip("Too slow for travis.") f = (1 + x + x*exp(x))*(x + log(x) + exp(x) - 1)/(x + log(x) + exp(x))**2/x g = log(x + exp(x) + log(x)) + 1/(x + exp(x) + log(x)) assert ratsimp(heurisch(f, x)) == g
def test_pmint_erf(): f = exp(-(x ** 2)) * erf(x) / (erf(x) ** 3 - erf(x) ** 2 - erf(x) + 1) g = ( sqrt(pi) * log(erf(x) - 1) / 8 - sqrt(pi) * log(erf(x) + 1) / 8 - sqrt(pi) / (4 * erf(x) - 4) ) assert ratsimp(heurisch(f, x)) == g
def test_pmint_logexp(): f = (1 + x + x * exp(x)) * (x + log(x) + exp(x) - 1) / (x + log(x) + exp(x))**2 / x g = log(x**2 + 2 * x * exp(x) + 2 * x * log(x) + exp(2 * x) + 2 * exp(x) * log(x) + log(x)**2) / 2 + 1 / (x + exp(x) + log(x)) # TODO: Optimal solution is g = 1/(x + log(x) + exp(x)) + log(x + log(x) + exp(x)), # but SymPy requires a lot of guidance to properly simplify heurisch() output. assert ratsimp(heurisch(f, x)) == g
def capacitance_matrix_variables(self, symbolic=False): """ Calculates the capacitance matrix for the energy term of the qubit Lagrangian in the variable respresentation. """ if symbolic: C = self.linear_coordinate_transform.T*self.capacitance_matrix(symbolic)*self.linear_coordinate_transform C = sympy.Matrix([sympy.nsimplify(sympy.ratsimp(x)) for x in C]).reshape(*(C.shape)) else: C = np.einsum('ji,jk,kl->il', self.linear_coordinate_transform,self.capacitance_matrix(symbolic),self.linear_coordinate_transform) return C
def lagrange(): polynom = 0 # Polynomial for i in range(n): element = Ys[i] # Element of one sum for k in range(n): if i != k: element *= (x - Xs[k]) / (Xs[i] - Xs[k]) polynom += element polynom = ratsimp(polynom) # Simplify the function print(polynom) return polynom
def find_riccati_ode(ratfunc, x, yf): y = ratfunc yp = y.diff(x) q1 = rand_rational_function(x, 1, 3) q2 = rand_rational_function(x, 1, 3) while q2 == 0: q2 = rand_rational_function(x, 1, 3) q0 = ratsimp(yp - q1 * y - q2 * y**2) eq = Eq(yf.diff(), q0 + q1 * yf + q2 * yf**2) sol = Eq(yf, y) assert checkodesol(eq, sol) == (True, 0) return eq, q0, q1, q2
def _simpsol(soleq): lhs = soleq.lhs sol = soleq.rhs sol = powsimp(sol) gens = list(sol.atoms(exp)) p = Poly(sol, *gens, expand=False) gens = [factor_terms(g) for g in gens] if not gens: gens = p.gens syms = [Symbol('C1'), Symbol('C2')] terms = [] for coeff, monom in zip(p.coeffs(), p.monoms()): coeff = piecewise_fold(coeff) if type(coeff) is Piecewise: coeff = Piecewise(*((ratsimp(coef).collect(syms), cond) for coef, cond in coeff.args)) else: coeff = ratsimp(coeff).collect(syms) monom = Mul(*(g**i for g, i in zip(gens, monom))) terms.append(coeff * monom) return Eq(lhs, Add(*terms))
def test_trigsimp1(): x, y = symbols('x,y') assert trigsimp(1 - sin(x)**2) == cos(x)**2 assert trigsimp(1 - cos(x)**2) == sin(x)**2 assert trigsimp(sin(x)**2 + cos(x)**2) == 1 assert trigsimp(1 + tan(x)**2) == 1/cos(x)**2 assert trigsimp(1/cos(x)**2 - 1) == tan(x)**2 assert trigsimp(1/cos(x)**2 - tan(x)**2) == 1 assert trigsimp(1 + cot(x)**2) == 1/sin(x)**2 assert trigsimp(1/sin(x)**2 - 1) == cot(x)**2 assert trigsimp(1/sin(x)**2 - cot(x)**2) == 1 assert trigsimp(5*cos(x)**2 + 5*sin(x)**2) == 5 assert trigsimp(5*cos(x/2)**2 + 2*sin(x/2)**2) in \ [2 + 3*cos(x/2)**2, 5 - 3*sin(x/2)**2] assert trigsimp(sin(x)/cos(x)) == tan(x) assert trigsimp(2*tan(x)*cos(x)) == 2*sin(x) assert trigsimp(cot(x)**3*sin(x)**3) == cos(x)**3 assert trigsimp(y*tan(x)**2/sin(x)**2) == y/cos(x)**2 assert trigsimp(cot(x)/cos(x)) == 1/sin(x) assert trigsimp(sin(x + y) + sin(x - y)) == 2*sin(x)*cos(y) assert trigsimp(sin(x + y) - sin(x - y)) == 2*sin(y)*cos(x) assert trigsimp(cos(x + y) + cos(x - y)) == 2*cos(x)*cos(y) assert trigsimp(cos(x + y) - cos(x - y)) == -2*sin(x)*sin(y) assert ratsimp(trigsimp(tan(x + y) - tan(x)/(1 - tan(x)*tan(y)))) == \ -tan(y)/(tan(x)*tan(y) -1) assert trigsimp(sinh(x + y) + sinh(x - y)) == 2*sinh(x)*cosh(y) assert trigsimp(sinh(x + y) - sinh(x - y)) == 2*sinh(y)*cosh(x) assert trigsimp(cosh(x + y) + cosh(x - y)) == 2*cosh(x)*cosh(y) assert trigsimp(cosh(x + y) - cosh(x - y)) == 2*sinh(x)*sinh(y) assert ratsimp(trigsimp(tanh(x + y) - tanh(x)/(1 + tanh(x)*tanh(y)))) == \ tanh(y)/(tanh(x)*tanh(y) + 1) assert trigsimp(cos(0.12345)**2 + sin(0.12345)**2) == 1 e = 2*sin(x)**2 + 2*cos(x)**2 assert trigsimp(log(e), deep=True) == log(2)
def test_ratsimp(): f, g = 1/x + 1/y, (x + y)/(x*y) assert f != g and ratsimp(f) == g f, g = 1/(1 + 1/x), 1 - 1/(x + 1) assert f != g and ratsimp(f) == g f, g = x/(x + y) + y/(x + y), 1 assert f != g and ratsimp(f) == g f, g = -x - y - y**2/(x + y) + x**2/(x + y), -2*y assert f != g and ratsimp(f) == g f = (a*c*x*y + a*c*z - b*d*x*y - b*d*z - b*t*x*y - b*t*x - b*t*z + e*x)/(x*y + z) G = [a*c - b*d - b*t + (-b*t*x + e*x)/(x*y + z), a*c - b*d - b*t - ( b*t*x - e*x)/(x*y + z)] assert f != g and ratsimp(f) in G A = sqrt(pi) B = log(erf(x) - 1) C = log(erf(x) + 1) D = 8 - 8*erf(x) f = A*B/D - A*C/D + A*C*erf(x)/D - A*B*erf(x)/D + 2*A/D assert ratsimp(f) == A*B/8 - A*C/8 - A/(4*erf(x) - 4)
def test_pmint_rat(): # TODO: heurisch() is off by a constant: -3/4. Possibly different permutation # would give the optimal result? def drop_const(expr, x): if expr.is_Add: return Add(*[ arg for arg in expr.args if arg.has(x) ]) else: return expr f = (x**7 - 24*x**4 - 4*x**2 + 8*x - 8)/(x**8 + 6*x**6 + 12*x**4 + 8*x**2) g = (4 + 8*x**2 + 6*x + 3*x**3)/(x**5 + 4*x**3 + 4*x) + log(x) assert drop_const(ratsimp(heurisch(f, x)), x) == g
def spline(): # Define Xs and Ys as numpy array and assign 'n' a local value xn = np.asarray(Xs) yn = np.asarray(Ys) n = len(xn) - 1 # Define h hn = np.array([xn[i + 1] - xn[i] for i in range(n)]) # Create matrix (A) and a vector (b) to solve the system A = np.zeros((n, n)) b = np.zeros(n) # Calculate the matrix A[0, 0] = 2 * (hn[0] + hn[n - 1]) A[0, 1] = hn[0] A[0, -1] = hn[n - 1] b[0] = 6 * ((yn[1] - yn[0]) / hn[0] - (yn[n] - yn[n - 1]) / hn[n - 1]) for i in range(1, n): A[i, i] = 2 * (hn[i - 1] + hn[i]) A[i, i - 1] = hn[i - 1] if i < n - 1: A[i, i + 1] = hn[i] b[i] = 6 * ((yn[i + 1] - yn[i]) / hn[i] - (yn[i] - yn[i - 1]) / hn[i - 1]) A[-1, 0] = hn[n - 1] # Solve the system that we got (it's not the original that we've got as final result) solv = np.linalg.solve(A, b) solv = np.append(solv, solv[0]) # Calculate a, b, c, d a = yn b = np.array([ (yn[i + 1] - yn[i]) / hn[i] - (2. * solv[i] + solv[i + 1]) * hn[i] / 6 for i in range(len(hn)) ]) c = solv * 0.5 d = np.array([(solv[i + 1] - solv[i]) / hn[i] / 6 for i in range(len(hn))]) print(' Polynomials: ') sx = [] for i in range(n): # Create a polynomial and print it sx.append( ratsimp(a[i] + b[i] * (x - xn[i]) + c[i] * (x - xn[i])**2 + d[i] * (x - xn[i])**3)) print('[{}, {}]: {}'.format(Xs[i], Xs[i + 1], sx[i])) # Show a plot of all calculations plot(sx)
def capacitance_matrix_variables(self, symbolic=False): """ Calculates the capacitance matrix for the energy term of the qubit Lagrangian in the variable representation. """ if symbolic: C = self.linear_coordinate_transform.T * self.capacitance_matrix( symbolic) * self.linear_coordinate_transform C = sympy.Matrix([sympy.nsimplify(sympy.ratsimp(x)) for x in C]).reshape(*(C.shape)) else: C = np.einsum('ji,jk,kl->il', self.linear_coordinate_transform, self.capacitance_matrix(symbolic), self.linear_coordinate_transform) return C
def test_action_verbs(): assert nsimplify((1/(exp(3*pi*x/5)+1))) == (1/(exp(3*pi*x/5)+1)).nsimplify() assert ratsimp(1/x + 1/y) == (1/x + 1/y).ratsimp() assert trigsimp(log(x), deep=True) == (log(x)).trigsimp(deep = True) assert radsimp(1/(2+sqrt(2))) == (1/(2+sqrt(2))).radsimp() assert powsimp(x**y*x**z*y**z, combine='all') == (x**y*x**z*y**z).powsimp(combine='all') assert simplify(x**y*x**z*y**z) == (x**y*x**z*y**z).simplify() assert together(1/x + 1/y) == (1/x + 1/y).together() assert separate((x*(y*z)**3)**2) == ((x*(y*z)**3)**2).separate() assert collect(a*x**2 + b*x**2 + a*x - b*x + c, x) == (a*x**2 + b*x**2 + a*x - b*x + c).collect(x) assert apart(y/(y+2)/(y+1), y) == (y/(y+2)/(y+1)).apart(y) assert combsimp(y/(x+2)/(x+1)) == (y/(x+2)/(x+1)).combsimp() assert factor(x**2+5*x+6) == (x**2+5*x+6).factor() assert refine(sqrt(x**2)) == sqrt(x**2).refine() assert cancel((x**2+5*x+6)/(x+2)) == ((x**2+5*x+6)/(x+2)).cancel()
def newton(): polynom = 0 # Polynomial for i in range(n): if i == 0: element = f.subs( x, Xs[0] ) # If it's the first element, which can't be multiplied like others else: asd = [Xs[j] for j in range(i + 1)] element = findmult(asd) for k in range(i): element *= (x - Xs[k]) polynom += element polynom = ratsimp(polynom) # Simplify the function print(polynom) return polynom
def print_Div(self, rule): with self.new_step(): f, g = rule.numerator, rule.denominator fp, gp = f.diff(rule.symbol), g.diff(rule.symbol) x = rule.symbol ff = sympy.Function("f")(x) gg = sympy.Function("g")(x) qrule_left = sympy.Derivative(ff / gg, rule.symbol) qrule_right = sympy.ratsimp(sympy.diff(sympy.Function("f")(x) / sympy.Function("g")(x))) qrule = sympy.Eq(qrule_left, qrule_right) self.append("Apply the quotient rule, which is:") self.append(self.format_math_display(qrule)) self.append("{} and {}.".format(self.format_math(sympy.Eq(ff, f)), self.format_math(sympy.Eq(gg, g)))) self.append("To find {}:".format(self.format_math(ff.diff(rule.symbol)))) with self.new_level(): self.print_rule(rule.numerstep) self.append("To find {}:".format(self.format_math(gg.diff(rule.symbol)))) with self.new_level(): self.print_rule(rule.denomstep) self.append("Now plug in to the quotient rule:") self.append(self.format_math(diff(rule)))
def test_pmint_logexp(): f = (1 + x + x*exp(x))*(x + log(x) + exp(x) - 1)/(x + log(x) + exp(x))**2/x g = log(x + exp(x) + log(x)) + 1/(x + exp(x) + log(x)) assert ratsimp(heurisch(f, x)) == g
formula = recursion(m,n,base) formula = (formula.subs([(alpha,1/a),(beta,1/b)])) functions.append(("%s_%d_%d"%(name,m,n), formula)) # Analytical expressions are singular for alpha=beta. # When alpha \approx beta, we therefore compute the expression # by writing beta=alpha+epsilon and writing a Taylor expansion # in epsilon. if m==0 and n==0: # The Taylor expansion in epsilon is computed only for the # base integral... form = base.subs(beta,alpha+epsilon) series_exp = 1 for itaylor in xrange(1,4*mmax+2): series_exp += (-epsilon*R)**itaylor/factorial(itaylor) form = form.subs(exp(-R*(alpha+epsilon)),exp(-R*alpha)*series_exp) form = ratsimp(form) taylor_expansion = simplify(form.subs(epsilon,0)) for itaylor in xrange(4*mmax+1): form = ratsimp(diff(form,epsilon)) taylor_expansion += simplify(form.subs(epsilon, 0)*epsilon**(itaylor+1)/factorial(itaylor+1)) #print taylor_expansion # ...other Taylor expansions are derived using a modified recursion scheme. formula_taylor = simplify(recursiontaylor(m,n,taylor_expansion)) functions.append(("%s_taylor_%d_%d"%(name,m,n), formula_taylor.subs([(alpha,1/a),(epsilon,b)]))) # Write routines in Fortran source code print "Writing source code..." codegen(functions, "F95", "../src/libslater",to_files=True, argument_sequence=(a,b,R), project='libslater') # Write python wrapper with open('../src/libslater.py','w') as f: f.write('''#!/usr/bin/env python\n\n''')
n=500 x0,x1,y0,y1=sp.symbols('x0 x1 y0 y1',real=True) sx=[x0,x1] sy=[y0,y1] #Kx=1 #Py=1 Kx=x1**2 Py=x1**2 #Phi1NL=-0.25/sp.pi*sp.log((x0-y0)**2+(x1-y1)**2) Phi1NL = sp.log(((x0-y0)**2+(x1+y1)**2)/((x0-y0)**2+(x1-y1)**2)) / (sp.pi*2*x1*y1) omgNL=[ Py*sp.diff(Phi1NL,sy[j]) for j in range(2) ] #Phi2NL=-0.5/sp.pi*sp.atan((x1-y1)/(x0-y0)) Phi2NL = sp.log(((x0-y0)**2+(x1+y1)**2)/((x0-y0)**2+(x1-y1)**2)) * (x0-y0)/(2*sp.pi*x1) + (sp.atan((x1-y1)/(x0-y0)) - sp.atan((x1+y1)/(x0-y0))) / (2*sp.pi) V2NL=[sp.ratsimp(Kx*sp.diff(Phi2NL,sx[j])) for j in range(2)] VSNL=[sp.ratsimp(Kx*sp.diff(Phi1NL,sx[j])) for j in range(2)] def Normal(x): n=x[0].shape[0]-1 return np.array([-x[1,1:]+x[1,:n],x[0,1:]-x[0,:n]]) def normal(x): nr=Normal(x) return nr/np.sqrt(nr[0]**2+nr[1]**2) def withoutZero(sFunct): def wrapped(sExpress,M,minDist=myeps): gd=np.sum([(M[i,1]-M[i,0])**2 for i in range(2)],axis=0)>minDist**2 AA=M[0,0].copy() AA[np.logical_not(gd)]+=1
def integral_basis(f,x,y): """ Compute the integral basis {b1, ..., bg} of the algebraic function field C[x,y] / (f). """ # If the curve is not monic then map y |-> y/lc(x) where lc(x) # is the leading coefficient of f T = sympy.Dummy('T') d = sympy.degree(f,y) lc = sympy.LC(f,y) if x in lc: f = sympy.ratsimp( f.subs(y,y/lc)*lc**(d-1) ) else: f = f/lc lc = 1 # # Compute df # p = sympy.Poly(f,[x,y]) n = p.degree(y) res = sympy.resultant(p,p.diff(y),y) factors = sympy.factor_list(res)[1] df = [k for k,deg in factors if (deg > 1) and (sympy.LC(k) == 1)] # # Compute series truncations at appropriate x points # alpha = [] r = [] for l in range(len(df)): k = df[l] alphak = sympy.roots(k).keys()[0] rk = compute_series_truncations(f,x,y,alphak,T) alpha.append(alphak) r.append(rk) # # Main Loop # a = [sympy.Dummy('a%d'%k) for k in xrange(n)] b = [1] for d in range(1,n): bd = y*b[-1] for l in range(len(df)): k = df[l] alphak = alpha[l] rk = r[l] found_something = True while found_something: # construct system of equations consisting of the coefficients # of negative powers of (x-alphak) in the substitutions # A(r_{k,1}),...,A(r_{k,n}) A = (sum(ak*bk for ak,bk in zip(a,b)) + bd) / (x - alphak) coeffs = [] for rki in rk: # substitute and extract coefficients A_rki = A.subs(y,rki) coeffs.extend(_negative_power_coeffs(A_rki, x, alphak)) # solve the coefficient equations for a0,...,a_{d-1} coeffs = [coeff.as_numer_denom()[0] for coeff in coeffs] sols = sympy.solve_poly_system(coeffs, a[:d]) if sols is None or sols == []: found_something = False else: sol = sols[0] bdm1 = sum( sol[i]*bk for i,bk in zip(range(d),b) ) bd = (bdm1 + bd) / k # bd found. Append to list of basis elements b.append( bd ) # finally, convert back to singularized curve if necessary for i in xrange(1,len(b)): b[i] = b[i].subs(y,y*lc).ratsimp() return b
def test_ratsimp2(): x = Symbol("x") e = 1/(1+1/x) assert (x+1)*ratsimp(e)/x == 1
def test_ratsimp_X1(): e = -x-y-(x+y)**(-1)*y**2+(x+y)**(-1)*x**2 assert e != -2*y assert ratsimp(e) == -2*y
def test_pmint_erf(): f = exp(-x**2)*erf(x)/(erf(x)**3 - erf(x)**2 - erf(x) + 1) g = sqrt(pi)*log(erf(x) - 1)/8 - sqrt(pi)*log(erf(x) + 1)/8 - sqrt(pi)/(4*erf(x) - 4) assert ratsimp(heurisch(f, x)) == g
def getCumulants(model, chords, param=[], simp=[], unsimp=[]): doSimplify=not(simp==[] and unsimp == []) start_time = time.time() if( not isConsistent(model,chords) ): print(" ERROR: Model and chords are not correct or inconsistent. ") return( False ) ### number of states N = len(getStateSpace(model)) ### The first Betti number (cyclomatic number) of the model, equals the number of chords B = len(chords) ### Generate transition matrix W from model W = zeros(N) for edge in model: W[edge] = (model[edge]) for j in range(N): W[j,j] = -sum(W[j,i] for i in range(N)) #display(W) ### Generate tilted matrix, from copy of W Wq = W[:,:] q=zeros(B,1) for i in range(B): name = 'q_{{{0}}}'.format(i) q[i] = symbols(name) Wq[chords[i]] = W[chords[i]]*exp(q[i]) Wq[chords[i][::-1]] = W[chords[i][::-1]]*exp(-q[i]) #display(Wq) ### Find coefficients of characteristic polynomial print("--- %s seconds ---" % (time.time() - start_time)) print("Start calculating characteristic polynomial") a = simplify(Wq.berkowitz()[-1][::-1]) # symbolic simplification is *crucial* here! ### Initialize current vector and covariance matrix c = zeros(B,1) C = zeros(B,B) ### Calculate current vector print("--- %s seconds ---" % (time.time() - start_time)) print("Start calculating current vector") for i in range(B): c[i] = -(diff(a[0],q[i])/a[1]).ratsimp() ## populate current vector for i in range(B): c=c.subs(q[i],0) ## subsitute q=0 if(doSimplify): c = c.subs(param) print("--- %s seconds ---" % (time.time() - start_time)) print("Start simplifying current vector") c = simplify(c.subs(simp)) #simplify cancel ### Calculate co-variance matrix print("--- %s seconds ---" % (time.time() - start_time)) print("Start calculating covariance matrix") ### Do in-place parametrization, before simplification, if latter is demanded if(doSimplify): for i in range(B): for j in range(i+1): t1 = ratsimp( diff(a[0],q[i],q[j]).subs(param).subs(simp) ) t2 = ratsimp( (diff(a[1],q[i])*c[j]).subs(param).subs(simp) ) t3 = ratsimp( (diff(a[1],q[j])*c[i]).subs(param).subs(simp) ) t4 = ratsimp( (2*a[2]*c[i]*c[j]).subs(param).subs(simp) ) t5 = ratsimp( a[1].subs(param).subs(simp) ) C[i,j] = -(t1 + t2 + t3 + t4)/t5 else: for i in range(B): for j in range(i+1): t1 = ( diff(a[0],q[i],q[j]) )#.ratsimp() t2 = ( (diff(a[1],q[i])*c[j]) )#.ratsimp() t3 = ( (diff(a[1],q[j])*c[i]) )#.ratsimp() t4 = ( (2*a[2]*c[i]*c[j]) )#.ratsimp() t5 = ( a[1] )#.ratsimp() C[i,j] = -(t1 + t2 + t3 + t4)/t5 ### Populate Covariance Matrix ## If no simplification, perform parametrization now if(not doSimplify): c = c.subs(param) ### simplification of the expectation should be safe to do, in any case c = simplify(c) ### simplification of covariance is possibly very time consuming C = C.subs(param) if(doSimplify): print("--- %s seconds ---" % (time.time() - start_time)) print("Start simplifying covariance matrix") C = simplify(C) ### subsitute q=0 into covariance for i in range(B): C = C.subs(q[i],0) print("--- %s seconds ---" % (time.time() - start_time)) print("All Done") ### Symmetrize covariance matrix: for i in range(B): for j in range(i): C[j,i] = C[i,j] ### return unsimplified expecation and covariance return( [c.subs(unsimp),C.subs(unsimp)])
def test_ratsimp_X2(): e = x/(x+y)+y/(x+y) assert e != 1 assert ratsimp(e) == 1
def getCumulants(model, chords, param=[], simp=[], unsimp=[]): doSimplify = not (simp == [] and unsimp == []) start_time = time.time() if (not isConsistent(model, chords)): print(" ERROR: Model and chords are not correct or inconsistent. ") return (False) ### number of states N = len(getStateSpace(model)) ### The first Betti number (cyclomatic number) of the model, equals the number of chords B = len(chords) ### Generate transition matrix W from model W = zeros(N) for edge in model: W[edge] = (model[edge]) for j in range(N): W[j, j] = -sum(W[j, i] for i in range(N)) #display(W) ### Generate tilted matrix, from copy of W Wq = W[:, :] q = zeros(B, 1) for i in range(B): name = 'q_{{{0}}}'.format(i) q[i] = symbols(name) Wq[chords[i]] = W[chords[i]] * exp(q[i]) Wq[chords[i][::-1]] = W[chords[i][::-1]] * exp(-q[i]) #display(Wq) ### Find coefficients of characteristic polynomial print("--- %s seconds ---" % (time.time() - start_time)) print("Start calculating characteristic polynomial") a = simplify( Wq.berkowitz()[-1][::-1]) # symbolic simplification is *crucial* here! ### Initialize current vector and covariance matrix c = zeros(B, 1) C = zeros(B, B) ### Calculate current vector print("--- %s seconds ---" % (time.time() - start_time)) print("Start calculating current vector") for i in range(B): c[i] = -(diff(a[0], q[i]) / a[1]).ratsimp() ## populate current vector for i in range(B): c = c.subs(q[i], 0) ## subsitute q=0 if (doSimplify): c = c.subs(param) print("--- %s seconds ---" % (time.time() - start_time)) print("Start simplifying current vector") c = simplify(c.subs(simp)) #simplify cancel ### Calculate co-variance matrix print("--- %s seconds ---" % (time.time() - start_time)) print("Start calculating covariance matrix") ### Do in-place parametrization, before simplification, if latter is demanded if (doSimplify): for i in range(B): for j in range(i + 1): t1 = ratsimp(diff(a[0], q[i], q[j]).subs(param).subs(simp)) t2 = ratsimp((diff(a[1], q[i]) * c[j]).subs(param).subs(simp)) t3 = ratsimp((diff(a[1], q[j]) * c[i]).subs(param).subs(simp)) t4 = ratsimp((2 * a[2] * c[i] * c[j]).subs(param).subs(simp)) t5 = ratsimp(a[1].subs(param).subs(simp)) C[i, j] = -(t1 + t2 + t3 + t4) / t5 else: for i in range(B): for j in range(i + 1): t1 = (diff(a[0], q[i], q[j])) #.ratsimp() t2 = ((diff(a[1], q[i]) * c[j])) #.ratsimp() t3 = ((diff(a[1], q[j]) * c[i])) #.ratsimp() t4 = ((2 * a[2] * c[i] * c[j])) #.ratsimp() t5 = (a[1]) #.ratsimp() C[i, j] = -(t1 + t2 + t3 + t4) / t5 ### Populate Covariance Matrix ## If no simplification, perform parametrization now if (not doSimplify): c = c.subs(param) ### simplification of the expectation should be safe to do, in any case c = simplify(c) ### simplification of covariance is possibly very time consuming C = C.subs(param) if (doSimplify): print("--- %s seconds ---" % (time.time() - start_time)) print("Start simplifying covariance matrix") C = simplify(C) ### subsitute q=0 into covariance for i in range(B): C = C.subs(q[i], 0) print("--- %s seconds ---" % (time.time() - start_time)) print("All Done") ### Symmetrize covariance matrix: for i in range(B): for j in range(i): C[j, i] = C[i, j] ### return unsimplified expecation and covariance return ([c.subs(unsimp), C.subs(unsimp)])
def emit(name, func): for x in sorted(exparg): test(name, x, sp.ratsimp(sp.radsimp(func(x).rewrite(sp.exp))), no_trigh=True)
def test_pmint_logexp(): f = (1 + x + x * exp(x)) * (x + log(x) + exp(x) - 1) / (x + log(x) + exp(x))**2 / x g = log(x + exp(x) + log(x)) + 1 / (x + exp(x) + log(x)) assert ratsimp(heurisch(f, x)) == g
from sympy import Symbol, simplify, ratsimp, sympify, factor, limit from numpy import array, zeros from copy import copy from pycircuit.circuit.symbolicapprox import * ## Create regulated cascode circuit c = SubCircuit() nin, nout, n1 = c.add_nodes('in', 'out', 'n1') gm1, gm2, gds1, gds2, Cgs1, Cgs2= [Symbol(symname, real=True) for symname in 'gm1,gm2,gds1,gds2,Cgs1,Cgs2'.split(',')] c['M2'] = MOS(nin, n1, gnd, gnd, gm = gm2, gds = gds2, Cgs=0*Cgs1) c['M1'] = MOS(n1, nout, nin, nin, gm = gm1, gds = gds1, Cgs=0*Cgs2) #c['r'] = R(nin, gnd, r = Symbol('Rs', real=True)) ## Perform twoport analysis with noise twoportana = TwoPortAnalysis(c, nin, gnd, nout, gnd, noise=True, noise_outquantity='i', toolkit=symbolic) res2port = twoportana.solve(Symbol('s'), complexfreq=True) y11 = res2port['twoport'].Y[0,0] print 'Input impedance:', 1/y11 #print 'Approx. input impedance', approx(1/y11, ['gds'], n = 1) print 'Input referred current noise PSD, Sin:', ratsimp(res2port['Sin']) print 'Approx. input referred current noise PSD, Sin:', approx(res2port['Sin'], ['gds'], n=1) print 'Input referred voltage noise PSD, Svn:', ratsimp(res2port['Svn'])
def test_ratsimp(): assert ratsimp(A*B - B*A) == A*B - B*A
print(S.simplify((x**3 + x**2 - x - 1) / (x**2 + 2 * x + 1))) #分解--表达式进行部分分式分解,它将一个有理函数变为数个分子及分母次数较小的有理函数 print("分解") print(S.apart(1 / ((x + 2) * (x + 1)), x)) #三角函数 print(S.sin(x + y).expand(trig=True)) #化简-去括号 f = (a - b + c) * (a + b - c) print(S.expand(f)) #因式分解 print(S.factor(a**2 - b**2 + 2 * b * c - c**2)) #通分运算 ratsimp()对表达式中的分母进行通分运算,即将表达式转换为分子除分母的形式 print(S.ratsimp(x / (x + y) + y / (x - y))) print(S.ratsimp(x / a + x / b)) #分母有理化 #radsimp()对表达式的分母进行有理化,结果中的分母部分不含无理数. print(S.ratsimp(1 / (S.sqrt(5)))) #fraction()返回包含表达式的分子与分母的元组, 用它可以获得ratsimp()通分之后的分子或分母 print(S.fraction(S.ratsimp(1 / x + 1 / y))) #化简三角函数 #trigsimp()化简表达式中的三角函数,通过method参数可以选择化简算法. print(S.trigsimp(S.sin(x)**2 + S.cos(x)**2 + 2 * S.cos(x)))
def matratsimp(mat): return sympy.matrices.Matrix(mat.rows, mat.cols, lambda i, j: sympy.ratsimp(mat[i, j]))
Symbol(symname, real=True) for symname in 'gm1,gm2,gds1,gds2,Cgs1,Cgs2'.split(',') ] c['M2'] = MOS(nin, n1, gnd, gnd, gm=gm2, gds=gds2, Cgs=0 * Cgs1) c['M1'] = MOS(n1, nout, nin, nin, gm=gm1, gds=gds1, Cgs=0 * Cgs2) #c['r'] = R(nin, gnd, r = Symbol('Rs', real=True)) ## Perform twoport analysis with noise twoportana = TwoPortAnalysis(c, nin, gnd, nout, gnd, noise=True, noise_outquantity='i', toolkit=symbolic) res2port = twoportana.solve(Symbol('s'), complexfreq=True) y11 = res2port['twoport'].Y[0, 0] print 'Input impedance:', 1 / y11 #print 'Approx. input impedance', approx(1/y11, ['gds'], n = 1) print 'Input referred current noise PSD, Sin:', ratsimp(res2port['Sin']) print 'Approx. input referred current noise PSD, Sin:', approx(res2port['Sin'], ['gds'], n=1) print 'Input referred voltage noise PSD, Svn:', ratsimp(res2port['Svn'])
#!/usr/bin/python import numpy as np import sympy as sp myeps=0.000001 x0,x1,y0,y1=sp.symbols('x0 x1 y0 y1',real=True) sx=[x0,x1] sy=[y0,y1] _Kx_=1 _Py_=1 _Phi1_=-0.25/sp.pi*sp.log((x0-y0)**2+(x1-y1)**2) _sOmega_=[_Py_*sp.diff(_Phi1_,sy[j]) for j in range(2)] _Phi2_=-0.5/sp.pi*sp.atan((x1-y1)/(x0-y0)) _sV2_=[sp.ratsimp(_Kx_*sp.diff(_Phi2_,sx[j])) for j in range(2)] _sVS_=[_Kx_*sp.diff(_Phi1_,sx[j]) for j in range(2)] def Normal(x): n=x[0].shape[0]-1 return np.array([-x[1,1:]+x[1,:n],x[0,1:]-x[0,:n]]) def normal(x): nr=Normal(x) return nr/np.sqrt(nr[0]**2+nr[1]**2) def withoutZero(sFunct): def wrapped(sExpress,M,minDist=myeps): gd=np.sum([(M[i,1]-M[i,0])**2 for i in range(2)],axis=0)>minDist**2 AA=M[0,0].copy() AA[np.logical_not(gd)]+=1 result=np.zeros_like(M[0,0]) result[gd]=sFunct(sExpress,np.array([[AA,M[0,1]],[M[1,0],M[1,1]]]),minDist)[gd]