def goto_state(n, send=1): """ For equal superpositions of non-0 states in a n-dimensional system, this function will create an operator that sends all the amplitude to state |send> Note: currently not set up to send to 0 """ m = n - 1 p = n - 2 base = (p * sp.sqrt(m))**-1 y = sp.together(sp.Rational(1, p) - base) x = sp.together(-sp.Rational(p - 1, p) - base) # y = sp.Rational(1,p) - base # x = -sp.Rational(p-1,p) - base mat = ones([m, m], object) * y fill_diagonal(mat, x) mat[:, send - 1] = 1 / sp.sqrt(m) mat[send - 1, :] = 1 / sp.sqrt(m) result = identity(n, object) result[1:, 1:] = mat tt = mat2tt(result) name = 'Size ' + str(n) + ', ' + arrow + str(send) + ' Goto-state gate' return diff_gate(tt, name)
def test_together2(): x, y, z = symbols("xyz") assert together(1/(x*y) + 1/y**2) == 1/x*y**(-2)*(x + y) assert together(1/(1 + 1/x)) == x/(1 + x) x = symbols("x", nonnegative=True) y = symbols("y", real=True) assert together(1/x**y + 1/x**(y-1)) == x**(-y)*(1 + x)
def showAnswer(p): n = Symbol('n') sp = together(sumFibPower(n, p, viaPowers=True).expand().simplify()) sn = together(sumFibPower(n, p, viaPowers=False).expand().simplify()) print ("Sum F(i)^%d = "%(p)) print ("=",sp,"=") print ("=",sn)
def singular_term(F,X,Y,L,I,version): """ Computes a single set of singular terms of the Puiseux expansions. For `I=1`, the function computes the first term of each finite `\mathbb{K}` expansion. For `I=2`, it computes the other terms of the expansion. """ T = [] # if the curve is singular then compute the singular tuples # otherwise, use the standard newton polygon method if is_singular(F,X,Y): for (q,m,l,Phi) in desingularize(F,X,Y): for eta in Phi.all_roots(radicals=True): tau = (q,1,m,1,sympy.together(eta)) T.append((tau,0,1)) else: # each side of the newton polygon corresponds to a K-term. for (q,m,l,Phi) in polygon(F,X,Y,I): # the rational method if version == 'rational': u,v = _bezout(q,m) # each newton polygon side has a characteristic # polynomial. For each square-free factor, each root # corresponds to a K-term for (Psi,r) in _square_free(Phi,_Z): Psi = sympy.Poly(Psi,_Z) # compute the roots of Psi. Use the RootOf construct if # possible. In the case when Psi is over EX (i.e. when # RootOf doesn't work) then compute symbolic roots. try: roots = Psi.all_roots(radicals=True) except NotImplementedError: roots = sympy.roots(Psi,_Z).keys() for xi in roots: # the classical version returns the "raw" roots if version == 'classical': P = sympy.Poly(_U**q-xi,_U) beta = RootOf(P,0,radicals=True) tau = (q,1,m,beta,1) T.append((tau,l,r)) # the rational version rescales parameters so as # to include ony rational terms in the Puiseux # expansions. if version == 'rational': mu = xi**(-v) beta = sympy.together(xi**u) tau = (q,mu,m,beta,1) T.append((tau,l,r)) return T
def __mul__(self, other): if isinstance(other, RayTransferMatrix): return RayTransferMatrix(Matrix.__mul__(self, other)) elif isinstance(other, GeometricRay): return GeometricRay(Matrix.__mul__(self, other)) elif isinstance(other, BeamParameter): temp = self*Matrix(((other.q,), (1,))) q = (temp[0]/temp[1]).expand(complex=True) return BeamParameter(other.wavelen, together(re(q)), z_r=together(im(q))) else: return Matrix.__mul__(self, other)
def __mul__(self, other): if isinstance(other, RayTransferMatrix): return RayTransferMatrix(Matrix.__mul__(self, other)) elif isinstance(other, GeometricRay): return GeometricRay(Matrix.__mul__(self, other)) elif isinstance(other, BeamParameter): temp = self * Matrix(((other.q, ), (1, ))) q = (temp[0] / temp[1]).expand(complex=True) return BeamParameter(other.wavelen, together(re(q)), z_r=together(im(q))) else: return Matrix.__mul__(self, other)
def FaireCorrection(self): if self.type == "D\\'eveloppement": self.corr = self.expr.expand() if self.type == "In\\'equation": self.corr = solveset(self.res >= 0, domain=S.Reals) if self.type == "Equation": self.corr = solveset(self.expr, domain=S.Reals) if self.type == "Tableaux de Variation": self.der = sp.together( sp.expand(sp.together(sp.diff(self.expr, x)))) self.Df = solveset(self.CheckDomaine >= 0, domain=S.Reals) [a, b] = fraction(self.der) self.res = solveset(a >= 0, domain=self.Df)
def calcular(request): # print dir(request) datos = request.GET print datos.get('lx') print datos.get('ly') res = "<!DOCTYPE html><html><head><title>Lagrange</title><script type='text/javascript' src='/static/MathJax.js?config=TeX-AMS_HTML'></script></head><body><div ><hr>" xl = (datos.get('lx')).split(",") yl = (datos.get('ly')).split(",") for i in range(len(xl)): xl[i] = int(xl[i]) yl[i] = int(yl[i]) lagrange = 0 x = symbols('x') for j in range(len(yl)): lx = 1 for i in range(len(xl)): if j != i: lx = lx * ((x - xl[i]) / (xl[j] - xl[i])) #lx=together(apart(lx,x),x) #res=res+latex(lx, mode='equation')+"<br>" #res=res+"<hr>" res = res + " multiplicando por " + str(yl[j]) + "<br>" lx = lx * yl[j] lx = together(apart(lx, x), x) res = res + latex(lx, mode='equation') + "<br>" res = res + "<hr>" res = res + "<br>" lagrange = lagrange + lx res = res + "La funcion resultado es:<br>" lagrange = together(apart(lagrange, x), x) lista = [] for i in range(1, 21): lista.append(lagrange.subs(x, i)) res = res + latex(lagrange, mode='equation') + "<br>" res = res + "<div><canvas id='lineChart' height='140'></canvas></div></div><script src='/static/jquery-2.1.1.js'></script><script src='/static/chartJs/Chart.min.js'></script>" res = res + """ <script>$(function () {var lineData = { labels: ["1", "2", "3", "4", "5", "6", "7","8","9","10","11","12","13","14","15","16","17","18","19","20"], datasets: [{ label: "funcion",backgroundColor: 'rgba(26,179,148,0.5)', borderColor: "rgba(26,179,148,0.7)",pointBackgroundColor: "rgba(26,179,148,1)", pointBorderColor: "#fff",data: """ + lista.__str__( ) + """ }]}; var lineOptions = {responsive: true};var ctx = document.getElementById("lineChart").getContext("2d");new Chart(ctx, {type: 'line', data: lineData, options:lineOptions}); });</script> """ res = res + "</body></html>" #return HttpResponseRedirect("/") return HttpResponse(res)
def findSymbolicExpressionL1(df,target,result_object,scaler,task="regression",logged_target=False,find_acceptable=True,features_type='best_features',max_length=-1): columns=df.columns.values X=result_object[features_type] individuals=result_object['best_individuals_equations'] final=[] eqs=convertIndividualsToEqs(individuals,columns) eqs2=[] if max_length>0: for eq in eqs: if len(eq)<max_length: eqs2.append(eq) eqs=eqs2 x=np.column_stack(X) if task=='regression': models=findSymbolicExpressionL1_regression_helper(x,target) elif task=='classification': models=findSymbolicExpressionL1_classification_helper(x,target) for model,score,coefs in models: if(len(model.coef_.shape)==1): eq="" #category represents a class. In logistic regression with scikit learn for j in range(0,len(eqs)): eq=eq+"+("+str(coefs[j])+"*("+str(sympify(eqs[j]))+"))" final.append((together(sympify(eq)),np.around(score,3))) else: dummy=[] for category_coefs in model.coef_: eq="" #category represents a class. In logistic regression with scikit learn for j in range(0,len(eqs)): eq=eq+"+("+str(category_coefs[j])+"*("+str(sympify(eqs[j]))+"))" dummy.append(together(sympify(eq))) final.append((dummy,np.around(score,3))) if find_acceptable: final=findAcceptableL1(final) return final
def c(lambdas): lambdas_tup = tuple(sorted(lambdas.items())) if lambdas_tup in known_correlators: return known_correlators[lambdas_tup] denom = t / Q * q**2 * (1 - q) * f_1(min(lambdas)) correlator = (first_term(lambdas) + second_term(lambdas) +\ third_term(lambdas) + fourth_term(lambdas) +\ fifth_term(lambdas)) correlator = sm.together(correlator, deep=True) correlator /= denom known_correlators[lambdas_tup] = sm.factor(sm.together(sm.expand( correlator, deep=True), deep=True), deep=True) return correlator
def antal_h_coefficient(index, game_matrix): """ Returns the H_index coefficient, according to Antal et al. (2009), as given by equation 2. H_k = \frac{1}{n^2} \sum_{i=1}^{n} \sum_{j=1}^{n} (a_{kj}-a_{jj}) Parameters ---------- index: int game_matrix: sympy.Matrix Returns ------- out: sympy.Expr Examples: -------- >>>a = Symbol('a') >>>antal_h_coefficient(0, Matrix([[a,2,3],[4,5,6],[7,8,9]])) Out[1]: (2*a - 29)/9 >>>antal_h_coefficient(0, Matrix([[1,2,3],[4,5,6],[7,8,9]])) Out[1]: -3 """ size = game_matrix.shape[0] suma = 0 for i in range(0, size): for j in range(0, size): suma = suma + (game_matrix[index, i] - game_matrix[i, j]) return sympy.together(sympy.simplify(suma / (size ** 2)), size)
def init_params(self): self.mi = [] self.gi = [] self.beta = [] assert self.n_pole > 0 if self.bw_l is None: decay = self.decay[0] self.bw_l = min(decay.get_l_list()) self.symbol = sym.together( KMatrix_single(self.n_pole, self.m1, self.m2, self.bw_l, self.d)) self.function = opt_lambdify( self.symbol.free_symbols, (sym.re(self.symbol), sym.im(self.symbol)), modules="tensorflow", ) for i in range(self.n_pole): self.mi.append( self.add_var(f"mass{i+1}", value=self.mass_list[i], fix=True)) self.gi.append( self.add_var(f"width{i+1}", value=self.width_list[i], fix=True)) self.beta.append(self.add_var(f"beta{i+1}", is_complex=True)) self.beta[0].fixed(1.0)
def _simplify(expr): u"""Simplifie une expression. Alias de simplify (sympy 0.6.4). Mais simplify n'est pas garanti d'être stable dans le temps. (Cf. simplify.__doc__).""" return together(expand(Poly.cancel(powsimp(expr))))
def test_apart_extension(): f = 2 / (x**2 + 1) g = I / (x + I) - I / (x - I) assert apart(f, extension=I) == g assert apart(f, gaussian=True) == g f = x / ((x - 2) * (x + I)) assert factor(together(apart(f)).expand()) == f # https://github.com/sympy/sympy/issues/18531 from sympy.core import Mul def mul2(expr): # 2-arg mul hack... return Mul(2, expr, evaluate=False) f = ((x**2 + 1)**3 / ((x - 1)**2 * (x + 1)**2 * (-x**2 + 2 * x + 1) * (x**2 + 2 * x - 1))) g = (1 / mul2(x - sqrt(2) + 1) - 1 / mul2(x - sqrt(2) - 1) + 1 / mul2(x + 1 + sqrt(2)) - 1 / mul2(x - 1 + sqrt(2)) + 1 / mul2( (x + 1)**2) + 1 / mul2((x - 1)**2)) assert apart(f, x, extension={sqrt(2)}) == g
def antal_l_coefficient(index, game_matrix): """ Returns the L_index coefficient, according to Antal et al. (2009), as given by equation 1. L_k = \frac{1}{n} \sum_{i=1}^{n} (a_{kk}+a_{ki}-a_{ik}-a_{ii}) Parameters ---------- index: int game_matrix: sympy.Matrix Returns ------- out: sympy.Expr Examples: -------- >>>a = Symbol('a') >>>antal_l_coefficient(0, Matrix([[a,2,3],[4,5,6],[7,8,9]])) Out[1]: 2*(a - 10)/3 >>>antal_l_coefficient(0, Matrix([[1,2,3],[4,5,6],[7,8,9]])) Out[1]: -6 """ size = game_matrix.shape[0] suma = 0 for i in range(0, size): suma = suma + (game_matrix[index, index] + game_matrix[index, i] - game_matrix[i, index] - game_matrix[i, i]) return sympy.together(sympy.simplify(suma / size), size)
def calculate_gains(sol, xin, optimize=True): """Calculate low-frequency gain and roots of a transfer function. **Parameters:** sol : dict the circuit solution xin : Sympy symbol the input variable optimize : boolean, optional If ``optimize`` is set to ``False``, no algebraic simplification will be attempted on the results. The default (``optimize=True``) results in ``sympy.together`` being called on each expression. **Returns:** gs : dict A dictionary with as keys the strings <key>/<xin> and as values dictionaries with keys ``'gain'``, ``'gain0'``, ``'poles'``, ``'zeros'``. """ gains = {} for key, value in sol.items(): tf = {} gain = sympy.together(value.diff(xin)) if optimize else value.diff(xin) (ps, zs) = get_roots(gain) tf.update({'gain': gain}) tf.update({'gain0': gain.subs(s, 0)}) tf.update({'poles': ps}) tf.update({'zeros': zs}) gains.update({"%s/%s" % (str(key), str(xin)): tf}) return gains
def thetas_alphas_to_expr_real(thetas, alphas, alpha0): theta, alpha = symbols('theta, alpha') re_form = together(expand_complex(re(alpha/(t - theta)))) return alpha0 + Add(*[re_form.subs({alpha: al, theta: th}) for th, al in zip(thetas, alphas)])
def antal_h_coefficient(index, game_matrix): """ Returns the H_index coefficient, according to Antal et al. (2009), as given by equation 2. H_k = \frac{1}{n^2} \sum_{i=1}^{n} \sum_{j=1}^{n} (a_{kj}-a_{jj}) Parameters ---------- index: int game_matrix: sympy.Matrix Returns ------- out: sympy.Expr Examples: -------- >>>a = Symbol('a') >>>antal_h_coefficient(0, Matrix([[a,2,3],[4,5,6],[7,8,9]])) Out[1]: (2*a - 29)/9 >>>antal_h_coefficient(0, Matrix([[1,2,3],[4,5,6],[7,8,9]])) Out[1]: -3 """ size = game_matrix.shape[0] suma = 0 for i in range(0, size): for j in range(0, size): suma = suma + (game_matrix[index, i] - game_matrix[i, j]) return sympy.together(sympy.simplify(suma / (size**2)), size)
def test_re_form(): theta, alpha = symbols('theta, alpha') # Check that this doesn't change re_form = together(expand_complex(re(alpha / (t - theta)))) assert re_form == (t * re(alpha) - re(alpha) * re(theta) - im(alpha) * im(theta)) / ( (t - re(theta))**2 + im(theta)**2)
def apply(self, expr, evaluation): 'Together[expr_]' expr_sympy = expr.to_sympy() result = sympy.together(expr_sympy) result = from_sympy(result) result = cancel(result) return result
def parse_coefficient(line, dimension_symbol, args): '''Decomposes the coefficent into numerator and denominator and \ calculates the order of epsilon of the coefficient.''' d = sp.symbols(dimension_symbol) eps = sp.symbols("eps") coeff_n, coeff_d = sp.fraction(sp.cancel(sp.together(sp.sympify(line).subs(d,4-2*eps)))) coefficient = Coefficient([str(coeff_n)],[str(coeff_d)],args['mandelstam_symbols']+args['mass_symbols']) return coefficient
def regular(S,X,Y,nterms,degree_bound): """ INPUT: -- ``S``: a finite set of pairs `\{(\pi_k,F_k)\}_{1 \leq k \leq B}` where `\pi_k` is a finite `\mathbb{K}`-expansion, `F_k \in \bar{\mathbb{K}}[X,Y]` with `F_k(0,0) = 0`, `\partial_Y F_k(0,0) \neq 0`, and `F_k(X,0) \neq 0`. -- ``H``: a positive integer OUTPUT: -- ``(list)``: a set `\{ \pi_k' \}_{1 \leq k \leq B}` of finite `\mathbb{K}` expansions such that `\pi_k'` begins with `\pi_k` and contains at least `H` `\mathbb{K}`-terms. """ R = [] for (pi,F) in S: # grow each expansion to the number of desired terms Npi = len(pi) # if a degree bound is specified, get the degree of the # singular part of the Puiseux series. We also want to compute # enough terms to distinguish the puiseux series. q,mu,m,beta,eta = pi[-1] e = reduce( lambda q1,q2: q1*q1, (tau[0] for tau in pi) ) ydeg = sum( tau[0]*tau[2] for tau in pi ) need_more_terms = True while ((Npi < nterms) and (ydeg < e*degree_bound)) or need_more_terms: # if the set of all (0,j), j!=0 is empty, then we've # encountered a finite puiseux expansion a = dict(F.terms()) ms = [j for (j,i) in a.keys() if i==0 and j!=0] if ms == []: break else: m = min(ms) # if a degree bound is specified, break pi-series # construction once we break the bound. ydeg += m Npi += 1 beta = sympy.together(-a[(m,0)]/a[(0,1)]) tau = (1,1,m,beta,1) pi.append(tau) F = _new_polynomial(F,X,Y,tau,m) # if the degree in the y-series isn't divisible by the # ramification index then we have enough terms to # distinguish the puiseux series. if sympy.gcd(ydeg,e) == 1: need_more_terms = False R.append(tuple(pi)) return tuple(R)
def _get_Ylm(self, l, m): """ Compute an expression for spherical harmonic of order (l,m) in terms of Cartesian unit vectors, :math:`\hat{z}` and :math:`\hat{x} + i \hat{y}` Parameters ---------- l : int the degree of the harmonic m : int the order of the harmonic; |m| < l Returns ------- expr : a sympy expression that corresponds to the requested Ylm References ---------- https://en.wikipedia.org/wiki/Spherical_harmonics """ import sympy as sp # the relevant cartesian and spherical symbols x, y, z, r = sp.symbols('x y z r', real=True, positive=True) xhat, yhat, zhat = sp.symbols('xhat yhat zhat', real=True, positive=True) xpyhat = sp.Symbol('xpyhat', complex=True) phi, theta = sp.symbols('phi theta') defs = [(sp.sin(phi), y / sp.sqrt(x**2 + y**2)), (sp.cos(phi), x / sp.sqrt(x**2 + y**2)), (sp.cos(theta), z / sp.sqrt(x**2 + y**2 + z**2))] # the cos(theta) dependence encoded by the associated Legendre poly expr = sp.assoc_legendre(l, m, sp.cos(theta)) # the exp(i*m*phi) dependence expr *= sp.expand_trig(sp.cos( m * phi)) + sp.I * sp.expand_trig(sp.sin(m * phi)) # simplifying optimizations expr = sp.together(expr.subs(defs)).subs(x**2 + y**2 + z**2, r**2) expr = expr.expand().subs([(x / r, xhat), (y / r, yhat), (z / r, zhat)]) expr = expr.factor().factor(extension=[sp.I]).subs( xhat + sp.I * yhat, xpyhat) expr = expr.subs(xhat**2 + yhat**2, 1 - zhat**2).factor() # and finally add the normalization amp = sp.sqrt((2 * l + 1) / (4 * numpy.pi) * sp.factorial(l - m) / sp.factorial(l + m)) expr *= amp return expr
def apply_list(self, expr, vars, evaluation): "FactorTermsList[expr_, vars_List]" if expr == Integer(0): return Expression("List", Integer(1), Integer(0)) elif isinstance(expr, Number): return Expression("List", expr, Integer(1)) for x in vars.leaves: if not (isinstance(x, Atom)): return evaluation.message("CoefficientList", "ivar", x) sympy_expr = expr.to_sympy() if sympy_expr is None: return Expression("List", Integer(1), expr) sympy_expr = sympy.together(sympy_expr) sympy_vars = [ x.to_sympy() for x in vars.leaves if isinstance(x, Symbol) and sympy_expr.is_polynomial(x.to_sympy()) ] result = [] numer, denom = sympy_expr.as_numer_denom() try: if denom == 1: # Get numerical part num_coeff, num_polys = sympy.factor_list(sympy.Poly(numer)) result.append(num_coeff) # Get factors are independent of sub list of variables if (sympy_vars and isinstance(expr, Expression) and any( x.free_symbols.issubset(sympy_expr.free_symbols) for x in sympy_vars)): for i in reversed(range(len(sympy_vars))): numer = sympy.factor(numer) / sympy.factor(num_coeff) num_coeff, num_polys = sympy.factor_list( sympy.Poly(numer), *[x for x in sympy_vars[:(i + 1)]]) result.append(sympy.expand(num_coeff)) # Last factor numer = sympy.factor(numer) / sympy.factor(num_coeff) result.append(sympy.expand(numer)) else: num_coeff, num_polys = sympy.factor_list(sympy.Poly(numer)) den_coeff, den_polys = sympy.factor_list(sympy.Poly(denom)) result = [ num_coeff / den_coeff, sympy.expand( sympy.factor(numer) / num_coeff / (sympy.factor(denom) / den_coeff)), ] except sympy.PolynomialError: # MMA does not raise error for non poly result.append(sympy.expand(numer)) # evaluation.message(self.get_name(), 'poly', expr) return Expression("List", *[from_sympy(i) for i in result])
def AnalyseLogA(expr): S1 = StrFexpr(expr) deriv = sp.diff(expr, x) sgn = together(deriv) [a, b] = fraction(sgn) a = a.expand() sgn = a / b deriv = sgn resultat = solveset(sgn > 0, domain=S.Reals) return [S1, deriv, resultat]
def apply(self, expr, evaluation): "Together[expr_]" expr_sympy = expr.to_sympy() if expr_sympy is None: return None result = sympy.together(expr_sympy) result = from_sympy(result) result = cancel(result) return result
def test_apart_extension(): f = 2/(x**2 + 1) g = I/(x + I) - I/(x - I) assert apart(f, extension=I) == g assert apart(f, gaussian=True) == g f = x/((x - 2)*(x + I)) assert factor(together(apart(f))) == f
def test_apart_extension(): f = 2 / (x**2 + 1) g = I / (x + I) - I / (x - I) assert apart(f, extension=I) == g assert apart(f, gaussian=True) == g f = x / ((x - 2) * (x + I)) assert factor(together(apart(f)).expand()) == f
def exercise_6_43(): z = sp.Symbol('z') b_of_z = 1/(1 - z) sp.pprint('\n' + 'b_of_z:') sp.pprint(b_of_z) e_b_prime_of_z = z**2/(1 - z)**2 sp.pprint('\n' +'e_b_prime_of_z:') sp.pprint(e_b_prime_of_z) e_b_prime_of_n = sp.series(e_b_prime_of_z, z, 0, 10) sp.pprint('\n' +'e_b_prime_of_n:') sp.pprint(e_b_prime_of_n) e_b_of_z = sp.integrate(e_b_prime_of_z, z) constant = e_b_of_z.subs(z, 0) e_b_of_z = e_b_of_z - constant sp.pprint('\n' +'e_b_of_z:') sp.pprint(e_b_of_z) e_b_of_n = sp.series(e_b_of_z, z, 0, 10) sp.pprint('\n' +'e_b_of_n:') sp.pprint(e_b_of_n) e_b_prime_of_z = sp.diff(e_b_of_z, z) sp.pprint('\n' +'e_b_prime_of_z:') sp.pprint(e_b_prime_of_z) f_of_z = sp.together((1 - z)**2*e_b_prime_of_z) sp.pprint('\n' +'f_of_z:') sp.pprint(f_of_z) F_of_z = sp.integrate(f_of_z, z) sp.pprint('\n' +'F_of_z:') sp.pprint(F_of_z) c_b_of_z = (e_b_of_z.subs(z, 0) + F_of_z)/(1 - z)**2 sp.pprint('\n' +'c_b_of_z:') sp.pprint(c_b_of_z) c_b_of_n = sp.series(c_b_of_z, z, 0, 10) sp.pprint('\n' +'c_b_of_n:') sp.pprint(c_b_of_n)
def findSymbolicExpression(df,target,result_object,scaler,task="regression",logged_target=False,acceptable_only=True): columns=df.columns.values X=result_object['best_features'] individuals=result_object['best_individuals_object'] final=[] eqs=convertIndividualsToEqs(individuals,columns) for i in range(1,len(X)): x=np.column_stack(X[0:i]) if task=='regression': model=linear_model.LinearRegression() scoring='r2' elif task=='classification': model=linear_model.LogisticRegression() scoring='f1_weighted' scores=cross_validation.cross_val_score(estimator=model, X=x, y=target, cv=10,scoring=scoring) model.fit(x,target) m=np.mean(scores) sd=np.std(scores) if(acceptable_only and m>sd) or (not acceptable_only): if(len(model.coef_.shape)==1): eq="" #category represents a class. In logistic regression with scikit learn for j in range(0,i): eq=eq+"+("+str(model.coef_[j])+"*("+str(sympify(eqs[j]))+"))" final.append((together(sympify(eq)),m,sd)) else: dummy=[] for category_coefs in model.coef_: eq="" #category represents a class. In logistic regression with scikit learn for j in range(0,i): eq=eq+"+("+str(category_coefs[j])+"*("+str(sympify(eqs[j]))+"))" dummy.append(together(sympify(eq))) final.append((dummy,m,sd)) return final
def extract_coefficients(func, t): tx = (diff(func[0], t)) ty = (diff(func[1], t)) eq = together(tx * tx + ty * ty) n, _ = fraction(eq) poly = Poly(n, t) coeffs = poly.all_coeffs() coeffs.reverse() return poly, coeffs
def apply(self, expr, evaluation): 'Simplify[expr_]' expr_sympy = expr.to_sympy() result = expr_sympy result = sympy.simplify(result) result = sympy.trigsimp(result) result = sympy.together(result) result = sympy.cancel(result) result = from_sympy(result) return result
def sympy_factor(expr_sympy): try: result = sympy.together(expr_sympy) numer, denom = result.as_numer_denom() if denom == 1: result = sympy.factor(expr_sympy) else: result = sympy.factor(numer) / sympy.factor(denom) except sympy.PolynomialError: return expr_sympy return result
def test(): a, b, c, d, e = sy.symbols("a, b, c, d, e") one = sy.S("1") correct = a * b * (one + c * (one + d)) computed = recursive_collect("a*b + a*b*c + a*b*c*d", ["a", "b", "c", "d"]) assert computed == correct correct = a * b * (one + c * (d + e)) / e computed = recursive_collect(sy.together("a*b/e + a*b*c + a*b*c*d/e"), ["a", "b", "c", "d", "e"]) print(computed) assert computed == correct
def calculate_gains(sol, xin, optimize=True): gains = {} for key, value in sol.iteritems(): tf = {} gain = sympy.together(value.diff(xin)) if optimize else value.diff(xin) (ps, zs) = get_roots(gain) tf.update({'gain': gain}) tf.update({'gain0': gain.subs(s, 0)}) tf.update({'poles': ps}) tf.update({'zeros': zs}) gains.update({"%s/%s" % (str(key), str(xin)): tf}) return gains
def continued_fraction_dc(x): int_part = floor(x) if x == int_part: next_x = None else: next_x = 1 / (x - int_part) next_x = together(next_x) N, D = fraction(next_x) assert D > 0 assert N > D #assert not D > N # here fire!!! return int_part, next_x
def calculate_gains(sol, xin, optimize=True): gains = {} for key, value in sol.iteritems(): tf = {} gain = sympy.together(value.diff(xin)) if optimize else value.diff(xin) (ps, zs) = get_roots(gain) tf.update({'gain': gain}) tf.update({'gain0': gain.subs(sympy.Symbol('s', complex=True), 0)}) tf.update({'poles': ps}) tf.update({'zeros': zs}) gains.update({"%s/%s" % (str(key), str(xin)): tf}) return gains
def StrExoFractionMoyen(classe): a = rd.randint(1, 50) b = rd.randint(1, 50) c = rd.randint(1, 50) d = rd.randint(1, 50) e = rd.randint(1, 50) f = rd.randint(1, 50) u = rd.randint(0, 5) v = rd.randint(0, 1) u = 1 if u == 0: if v == 0: S1 = "\\frac{" + "{0}".format(a) + "}" + "{" + "{0}".format( b) + "}" + " + " + "\\frac{" + "{0}".format( c) + "}" + "{" + "{0}".format(d) + "}" res = Rational(a, b) + Rational(c, d) if v == 1: S1 = "\\frac{" + "{0}".format(a) + "}" + "{" + "{0}".format( b) + "}" + " - " + "\\frac{" + "{0}".format( c) + "}" + "-" + "{" + "{0}".format(d) + "}" res = Rational(a, b) - Rational(c, d) if u > 0: A = AxPb() B = AxPb() C = AxPb() D = AxPb() AA = sp.latex(A) BB = sp.latex(B) CC = sp.latex(C) DD = sp.latex(D) if v == 0: S1 = "\\frac{" + AA + "}" + "{" + BB + "}" + " + " + "\\frac{" + CC + "}" + "{" + DD + "}" res = sp.together(A / B + C / D) if v == 1: S1 = "\\frac{" + AA + "}" + "{" + BB + "}" + " - " + "\\frac{" + CC + "}" + "{" + DD + "}" res = sp.together(A / B - C / D) [a, b] = fraction(res) a = sp.expand(a) res = a / b return [S1, sp.latex(res)]
def _get_Ylm(self, l, m): """ Compute an expression for spherical harmonic of order (l,m) in terms of Cartesian unit vectors, :math:`\hat{z}` and :math:`\hat{x} + i \hat{y}` Parameters ---------- l : int the degree of the harmonic m : int the order of the harmonic; |m| < l Returns ------- expr : a sympy expression that corresponds to the requested Ylm References ---------- https://en.wikipedia.org/wiki/Spherical_harmonics """ import sympy as sp # the relevant cartesian and spherical symbols x, y, z, r = sp.symbols('x y z r', real=True, positive=True) xhat, yhat, zhat = sp.symbols('xhat yhat zhat', real=True, positive=True) xpyhat = sp.Symbol('xpyhat', complex=True) phi, theta = sp.symbols('phi theta') defs = [(sp.sin(phi), y/sp.sqrt(x**2+y**2)), (sp.cos(phi), x/sp.sqrt(x**2+y**2)), (sp.cos(theta), z/sp.sqrt(x**2 + y**2 + z**2)) ] # the cos(theta) dependence encoded by the associated Legendre poly expr = sp.assoc_legendre(l, m, sp.cos(theta)) # the exp(i*m*phi) dependence expr *= sp.expand_trig(sp.cos(m*phi)) + sp.I*sp.expand_trig(sp.sin(m*phi)) # simplifying optimizations expr = sp.together(expr.subs(defs)).subs(x**2 + y**2 + z**2, r**2) expr = expr.expand().subs([(x/r, xhat), (y/r, yhat), (z/r, zhat)]) expr = expr.factor().factor(extension=[sp.I]).subs(xhat+sp.I*yhat, xpyhat) expr = expr.subs(xhat**2 + yhat**2, 1-zhat**2).factor() # and finally add the normalization amp = sp.sqrt((2*l+1) / (4*numpy.pi) * sp.factorial(l-m) / sp.factorial(l+m)) expr *= amp return expr
def handle_together(message): try: message.text = rstr(message) if (len(message.text) != 0): s = sympy.together(message.text) lat = sympy.latex(s) plt.text(0, 0.6, r"$%s$" % lat, fontsize=50) plt.axis('off') plt.savefig('plot.png') photo = open('plot.png', 'rb') bot.send_photo(message.chat.id, photo, s) plt.close() except BaseException: bot.send_message(message.chat.id, 'Ошибка при вводе дробей!')
def apply(self, expr, evaluation): 'Factor[expr_]' expr_sympy = expr.to_sympy() try: result = sympy.together(expr_sympy) numer, denom = result.as_numer_denom() if denom == 1: result = sympy.factor(expr_sympy) else: result = sympy.factor(numer) / sympy.factor(denom) except sympy.PolynomialError: return expr return from_sympy(result)
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 apply(self, expr, evaluation): 'Simplify[expr_]' expr_sympy = expr.to_sympy() result = expr_sympy try: result = sympy.simplify(result) except TypeError: #XXX What's going on here? pass result = sympy.trigsimp(result) result = sympy.together(result) result = sympy.cancel(result) result = from_sympy(result) return result
def apply_list(self, expr, vars, evaluation): 'FactorTermsList[expr_, vars_List]' if expr == Integer(0): return Expression('List', Integer(1), Integer(0)) elif isinstance(expr, Number): return Expression('List', expr, Integer(1)) for x in vars.leaves: if not(isinstance(x, Atom)): return evaluation.message('CoefficientList', 'ivar', x) sympy_expr = expr.to_sympy() if sympy_expr is None: return Expression('List', Integer(1), expr) sympy_expr = sympy.together(sympy_expr) sympy_vars = [x.to_sympy() for x in vars.leaves if isinstance(x, Symbol) and sympy_expr.is_polynomial(x.to_sympy())] result = [] numer, denom = sympy_expr.as_numer_denom() try: from sympy import factor, factor_list, Poly if denom == 1: # Get numerical part num_coeff, num_polys = factor_list(Poly(numer)) result.append(num_coeff) # Get factors are independent of sub list of variables if (sympy_vars and isinstance(expr, Expression) and any(x.free_symbols.issubset(sympy_expr.free_symbols) for x in sympy_vars)): for i in reversed(range(len(sympy_vars))): numer = factor(numer) / factor(num_coeff) num_coeff, num_polys = factor_list(Poly(numer), *[x for x in sympy_vars[:(i+1)]]) result.append(sympy.expand(num_coeff)) # Last factor numer = factor(numer) / factor(num_coeff) result.append(sympy.expand(numer)) else: num_coeff, num_polys = factor_list(Poly(numer)) den_coeff, den_polys = factor_list(Poly(denom)) result = [num_coeff / den_coeff, sympy.expand(factor(numer)/num_coeff / (factor(denom)/den_coeff))] except sympy.PolynomialError: # MMA does not raise error for non poly result.append(sympy.expand(numer)) # evaluation.message(self.get_name(), 'poly', expr) return Expression('List', *[from_sympy(i) for i in result])
def regular(S,X,Y,nterms,degree_bound): """ INPUT: -- ``S``: a finite set of pairs `\{(\pi_k,F_k)\}_{1 \leq k \leq B}` where `\pi_k` is a finite `\mathbb{K}`-expansion, `F_k \in \bar{\mathbb{K}}[X,Y]` with `F_k(0,0) = 0`, `\partial_Y F_k(0,0) \neq 0`, and `F_k(X,0) \neq 0`. -- ``H``: a positive integer OUTPUT: -- ``(list)``: a set `\{ \pi_k' \}_{1 \leq k \leq B}` of finite `\mathbb{K}` expansions such that `\pi_k'` begins with `\pi_k` and contains at least `H` `\mathbb{K}`-terms. """ R = [] for (pi,F) in S: # grow each expansion to the number of desired terms # if a degree bound is specified, get the degree of the # singular part of the Puiseux series q,mu,m,beta,eta = pi[-1] deg = sympy.Rational(m,q) while (len(pi) < nterms) and (deg < degree_bound): # if the set of all (0,j), j!=0 is empty, then we've # encountered a finite puiseux expansion a = dict(F.terms()) ms = [j for (j,i) in a.keys() if i==0 and j!=0] if ms == []: break else: m = min(ms) # if a degree bound is specified, break pi-series # construction once we break the bound. deg += m beta = sympy.together(-a[(m,0)]/a[(0,1)]) tau = (1,1,m,beta,1) pi.append(tau) F = _new_polynomial(F,X,Y,tau,m) R.append(pi) return R
def apply_iter(self, expr, i, imin, imax, di, evaluation): '%(name)s[expr_, {i_Symbol, imin_, imax_, di_}]' if isinstance(self, SympyFunction) and di.get_int_value() == 1: whole_expr = Expression(self.get_name(), expr, Expression('List', i, imin, imax)) sympy_expr = whole_expr.to_sympy() # apply Together to produce results similar to Mathematica result = sympy.together(sympy_expr) result = from_sympy(result) result = cancel(result) if not result.same(whole_expr): return result index = imin.evaluate(evaluation) imax = imax.evaluate(evaluation) di = di.evaluate(evaluation) result = [] while True: cont = Expression('LessEqual', index, imax).evaluate(evaluation) if cont == Symbol('False'): break if cont != Symbol('True'): if self.throw_iterb: evaluation.message(self.get_name(), 'iterb') return evaluation.check_stopped() try: item = dynamic_scoping(expr.evaluate, {i.name: index}, evaluation) result.append(item) except ContinueInterrupt: if self.allow_loopcontrol: pass else: raise except BreakInterrupt: if self.allow_loopcontrol: break else: raise index = Expression('Plus', index, di).evaluate(evaluation) return self.get_result(result)
def apply_iter(self, expr, i, imin, imax, di, evaluation): '%(name)s[expr_, {i_Symbol, imin_, imax_, di_}]' if di.get_int_value() == 1 and isinstance(self, SageFunction): whole_expr = Expression(self.get_name(), expr, Expression('List', i, imin, imax)) sympy_expr = whole_expr.to_sympy() # apply Together to produce results similar to Mathematica result = sympy.together(sympy_expr) result = from_sympy(result) result = cancel(result) if not result.same(whole_expr): return result index = imin.evaluate(evaluation).get_real_value() imax = imax.evaluate(evaluation).get_real_value() di = di.evaluate(evaluation).get_real_value() if index is None or imax is None or di is None: if self.throw_iterb: evaluation.message(self.get_name(), 'iterb') return result = [] while index <= imax: evaluation.check_stopped() try: item = dynamic_scoping(expr.evaluate, {i.name: Number.from_mp(index)}, evaluation) result.append(item) except ContinueInterrupt: if self.allow_loopcontrol: pass else: raise except BreakInterrupt: if self.allow_loopcontrol: break else: raise index = add(index, di) return self.get_result(result)
def derive_conic_to_aligned_ellipse(): """ derive the respective routine using sympy """ import sympy cx = sympy.Symbol("cx") cy = sympy.Symbol("cy") rx = sympy.Symbol("rx") ry = sympy.Symbol("ry") x = sympy.Symbol("x") y = sympy.Symbol("y") fun = ((x-cx)**2 / (rx**2) + (y-cy)**2 / (ry**2) - 1)**2 print "initial function" sympy.pprint(fun) f1 = fun.expand(deep=True) f2 = sympy.together(f1) f3 = f2*(rx**2*ry**2) print "=======================" print "expanded function" sympy.pprint(f3) print "=======================" print "derive gradient" print f3.diff(cx) print f3.diff(cy) print f3.diff(rx) print f3.diff(ry) return f3
def symmetryDetection(allVariables, diffEquations, observables, obsFunctions, initFunctions, predictions, predFunctions, ansatz = 'uni', pMax = 2, inputs = [], fixed = [], parallel = 1, allTrafos = False, timeTrans = False, pretty = True, suffix=''): n = len(allVariables) m = len(diffEquations) h = len(observables) ########################################################################################### ############################# prepare equations #################################### ########################################################################################### sys.stdout.write('Preparing equations...') sys.stdout.flush() # make infinitesimal ansatz infis, diffInfis, rs = makeAnsatz(ansatz, allVariables, m, len(inputs), pMax, fixed) # get infinitesimals of time transformation if timeTrans: rs.append(spy.var('r_T_1')) diffInfiT = rs[-1] allVariables += [T] else: diffInfiT = None # and convert to polynomial infis, diffInfis = transformInfisToPoly(infis, diffInfis, allVariables, rs, parallel, ansatz) diffInfiT = Apoly(diffInfiT, allVariables, rs) ### extract numerator and denominator of equations #differential equations numerators = [0]*m denominators = [0]*m for k in range(m): rational = spy.together(diffEquations[k]) numerators[k] = Apoly(spy.numer(rational), allVariables, None) denominators[k] = Apoly(spy.denom(rational), allVariables, None) #observation functions obsNumerators = [0]*h obsDenominatros = [0]*h for k in range(h): rational = spy.together(obsFunctions[k]) obsNumerators[k] = Apoly(spy.numer(rational), allVariables, None) obsDenominatros[k] = Apoly(spy.denom(rational), allVariables, None) #initial functions if len(initFunctions) != 0: initNumerators = [0]*m initDenominatros = [0]*m for k in range(m): rational = spy.together(initFunctions[k]) initNumerators[k] = Apoly(spy.numer(rational), allVariables, None) initDenominatros[k] = Apoly(spy.denom(rational), allVariables, None) else: initNumerators = [] initDenominatros = [] ### calculate numerator of derivatives of equations #differential equatioins derivativesNum = [0]*m for i in range(m): derivativesNum[i] = [0]*n for k in range(m): for l in range(n): derivativesNum[k][l] = Apoly(None, allVariables, None) derivativesNum[k][l].add(numerators[k].diff(l).mul(denominators[k])) derivativesNum[k][l].sub(numerators[k].mul(denominators[k].diff(l))) #observation functions obsDerivativesNum = [0]*h for i in range(h): obsDerivativesNum[i] = [0]*n for k in range(h): for l in range(n): obsDerivativesNum[k][l] = Apoly(None, allVariables, None) obsDerivativesNum[k][l].add(obsNumerators[k].diff(l).mul(obsDenominatros[k])) obsDerivativesNum[k][l].sub(obsNumerators[k].mul(obsDenominatros[k].diff(l))) #initial functions if len(initFunctions) != 0: initDerivativesNum = [0]*len(initFunctions) for i in range(m): initDerivativesNum[i] = [0]*n for k in range(m): for l in range(n): initDerivativesNum[k][l] = Apoly(None, allVariables, None) initDerivativesNum[k][l].add(initNumerators[k].diff(l).mul(initDenominatros[k])) initDerivativesNum[k][l].sub(initNumerators[k].mul(initDenominatros[k].diff(l))) else: initDerivativesNum = [] sys.stdout.write('\rPreparing equations...done\n') sys.stdout.flush() ########################################################################################### ############################ build linear system ################################### ########################################################################################### sys.stdout.write('\nBuilding system...') sys.stdout.flush() rSystem = buildSystem(numerators, denominators, derivativesNum, obsDerivativesNum, initDenominatros, initDerivativesNum, initFunctions, infis, diffInfis, diffInfiT, allVariables, rs, parallel, ansatz) sys.stdout.write('done\n') sys.stdout.flush() ########################################################################################### ############################## solve system ######################################## ########################################################################################### sys.stdout.write('\nSolving system of size ' + str(rSystem.shape[0]) + 'x' +\ str(rSystem.shape[1]) + '...') sys.stdout.flush() #get LU decomposition from scipy rSystem = scipy.linalg.lu(rSystem, permute_l=True)[1] #calculate reduced row echelon form rSystem, pivots = getrref(rSystem) sys.stdout.write('done\n') sys.stdout.flush() ########################################################################################### ############################# process results ###################################### ########################################################################################### sys.stdout.write('\nProcessing results...') sys.stdout.flush() # calculate solution space sys.stdout.write('\n calculating solution space') sys.stdout.flush() baseMatrix = nullSpace(rSystem, pivots) #substitute solutions into infinitesimals #(and remove the ones with common parameter factors) sys.stdout.write('\n substituting solutions') sys.stdout.flush() infisAll = [] for l in range(baseMatrix.shape[1]): infisTmp = [0]*n for i in range(len(infis)): infisTmp[i] = infis[i].getCopy() infisTmp[i].rs = baseMatrix[:,l] infisTmp[i] = infisTmp[i].as_expr() if timeTrans: infisTmp.append(baseMatrix[-1,l] * T) if allTrafos: infisAll.append(infisTmp) else: if not checkForCommonFactor(infisTmp, allVariables, m): infisAll.append(infisTmp) print('') sys.stdout.write('done\n') sys.stdout.flush() # print transformations print('\n\n') if len(infisAll) != 0: printTransformations(infisAll, allVariables, pretty,suffix) ########################################################################################### ############################ check predictions ##################################### ########################################################################################### if predictions != False: checkPredictions(predictions, predFunctions, infisAll, allVariables) print(time.strftime('\nTotal time: %Hh:%Mm:%Ss', time.gmtime(time.time()-t0)))
def sol_to_dict(sol, x, optimize=True): ret = {} for index in range(x.shape[0]): sol_current = sympy.together(sol[index]) if optimize else sol[index] ret.update({str(x[index]): sol_current}) return ret
def apply(self, eqs, vars, evaluation): 'Solve[eqs_, vars_]' vars_original = vars head_name = vars.get_head_name() if head_name == 'System`List': vars = vars.leaves else: vars = [vars] for var in vars: if ((var.is_atom() and not var.is_symbol()) or # noqa head_name in ('System`Plus', 'System`Times', 'System`Power') or 'System`Constant' in var.get_attributes(evaluation.definitions)): evaluation.message('Solve', 'ivar', vars_original) return eqs_original = eqs if eqs.get_head_name() in ('System`List', 'System`And'): eqs = eqs.leaves else: eqs = [eqs] sympy_eqs = [] sympy_denoms = [] for eq in eqs: symbol_name = eq.get_name() if symbol_name == 'System`True': pass elif symbol_name == 'System`False': return Expression('List') elif not eq.has_form('Equal', 2): return evaluation.message('Solve', 'eqf', eqs_original) else: left, right = eq.leaves left = left.to_sympy() right = right.to_sympy() if left is None or right is None: return eq = left - right eq = sympy.together(eq) eq = sympy.cancel(eq) sympy_eqs.append(eq) numer, denom = eq.as_numer_denom() sympy_denoms.append(denom) vars_sympy = [var.to_sympy() for var in vars] if None in vars_sympy: return # delete unused variables to avoid SymPy's # PolynomialError: Not a zero-dimensional system # in e.g. Solve[x^2==1&&z^2==-1,{x,y,z}] all_vars = vars[:] all_vars_sympy = vars_sympy[:] vars = [] vars_sympy = [] for var, var_sympy in zip(all_vars, all_vars_sympy): pattern = Pattern.create(var) if not eqs_original.is_free(pattern, evaluation): vars.append(var) vars_sympy.append(var_sympy) def transform_dict(sols): if not sols: yield sols for var, sol in six.iteritems(sols): rest = sols.copy() del rest[var] rest = transform_dict(rest) if not isinstance(sol, (tuple, list)): sol = [sol] if not sol: for r in rest: yield r else: for r in rest: for item in sol: new_sols = r.copy() new_sols[var] = item yield new_sols break def transform_solution(sol): if not isinstance(sol, dict): if not isinstance(sol, (list, tuple)): sol = [sol] sol = dict(list(zip(vars_sympy, sol))) return transform_dict(sol) if not sympy_eqs: sympy_eqs = True elif len(sympy_eqs) == 1: sympy_eqs = sympy_eqs[0] try: if isinstance(sympy_eqs, bool): result = sympy_eqs else: result = sympy.solve(sympy_eqs, vars_sympy) if not isinstance(result, list): result = [result] if (isinstance(result, list) and len(result) == 1 and result[0] is True): return Expression('List', Expression('List')) if result == [None]: return Expression('List') results = [] for sol in result: results.extend(transform_solution(sol)) result = results if any(sol and any(var not in sol for var in all_vars_sympy) for sol in result): evaluation.message('Solve', 'svars') # Filter out results for which denominator is 0 # (SymPy should actually do that itself, but it doesn't!) result = [sol for sol in result if all( sympy.simplify(denom.subs(sol)) != 0 for denom in sympy_denoms)] return Expression('List', *(Expression( 'List', *(Expression('Rule', var, from_sympy(sol[var_sympy])) for var, var_sympy in zip(vars, vars_sympy) if var_sympy in sol) ) for sol in result)) except sympy.PolynomialError: # raised for e.g. Solve[x^2==1&&z^2==-1,{x,y,z}] when not deleting # unused variables beforehand pass except NotImplementedError: pass except TypeError as exc: if str(exc).startswith("expected Symbol, Function or Derivative"): evaluation.message('Solve', 'ivar', vars_original)
#s = s.replace( " - ", "-" ) return s def inputlines(): lines = [] while True: l = input() if not l: break lines.append(l) return "".join(lines) USAGE = """Convert formula, written in Python notation, into LaTeX form. Replaces occurences of F(<arg>)**n with f_{<arg>}^n. Enter formula, followed by an empty line: """ if __name__=="__main__": print (USAGE) formula = inputlines() formula = formula.replace("//","/") F = Symbol("F") n = Symbol("n") f = eval( formula, {"F": lambda x: F(x), "n": n } ) f = together(f) #print (f) print (cleanlatex(latex(f)))