def main(): A = sympy.Matrix([[3, 11], [22, 6]]) b = sympy.Matrix([0, 0]) print("Исходная матрица A:") sympy.pprint(A) x = gauss.gauss(A, b) if x: print("\nРезультат:", x)
def main(): A = sympy.Matrix([[1, -3, -1], [2, -2, 1], [3, -1, 2]]) b = sympy.Matrix([-11, -7, -4]) print("Исходная матрица A:") sympy.pprint(A) print("\nВектор b:") sympy.pprint(b) x = gauss.gauss(A, b) if x: print("\nРезультат:", x)
def case1(): a, x1, x2 = symbols('a x1 x2') # Define symbols b = 3 * (a - 1) # Relation between a and b y = a * x1 + b * x2 + 5 # Given function y # Error of x1 and x2 Sigx1 = 0.8 Sigx2 = 1.5 print "In the case that x1 and x2 are dependent:\n" Sigx1x2 = Sigx1 * Sigx2 # Correlation coefficient equals to 1 SigmaXX = np.matrix([[Sigx1**2, Sigx1x2], # Define covariance [Sigx1x2, Sigx2**2]]) # matrix of x1 and x2 print "SigmaXX =\n" pprint(Matrix(SigmaXX)) print # Jacobian matrix of y function with respect to x1 and x2 Jyx = np.matrix([diff(y, x1), diff(y, x2)]) SigmaYY = Jyx * SigmaXX * Jyx.T # Compute covariance matrix of y function # Compute solution in witch the SigmaYY is minimum a = round(solve(diff(expand(SigmaYY[0, 0]), a))[0], 8) b = round(b.evalf(subs={'a': a}), 8) # Compute sigma y SigmaY = sqrt(SigmaYY[0, 0].evalf(subs={'a': a, 'b': b})) print "a = %.4f\nb = %.4f" % (a, b) print "SigmaY = %.4f" % float(SigmaY)
def invertInteractive(f, X, Y): """ Given function Y = f(X) return inverse f^{-1}(X). Note: - f could be fcn of multiple variables. This inverts in variable X - f must be a sympy function of sympy symbol/variable X - Returns function of Y and anything else f depends upon, removing dependence upon X - Accounts for non-unique inverse by prompting user to select from possible inverses """ # Try to construct inverse finv = sp.solve(Y-f, X) # If inverse unique, return it. If not, prompt user to select one if len(finv) == 1: finv = finv[0] else: print "Please choose expression for the inverse X = f^{-1}(Y)\n" for opt, expr in enumerate(finv): print "\nOption %d:\n----------\n" % opt sp.pprint(expr) choice = int(raw_input("Your Choice: ")) finv = finv[choice] os.system('clear') return finv
def quick_equation(eq = None, latex = None): """ first print the given equation. optionally, in markdown mode, generate an image from an equation and write a link to it. """ if eq is not None: sympy.pprint(eq) else: print latex # print an empty line print if not markdown: return global plt if latex is None: latex = sympy.latex(eq) img_filename = hashlib.sha1(latex).hexdigest()[: 10] # create the figure and hide the border. set the height and width to # something far smaller than the resulting image - bbox_inches will # expand this later fig = plt.figure(figsize = (0.1, 0.1), frameon = False) ax = fig.add_axes([0, 0, 1, 1]) ax.axis("off") fig = plt.gca() fig.axes.get_xaxis().set_visible(False) fig.axes.get_yaxis().set_visible(False) plt.text(0, 0, r"$%s$" % latex, fontsize = 25) plt.savefig("img/%s.png" % img_filename, bbox_inches = "tight") # don't use the entire latex string for the alt text as it could be long quick_write("![%s](img/%s.png)" % (latex[: 20], img_filename))
def test1(): """ Wiedemann's Formel hat einen Fehler! """ print("\n\n...................", """Wiedemann's Formel hat einen Fehler!""") fs,ld = S.symbols('fs ld') QF = S.Matrix([[1,0],[-1/fs,1]]) DR = S.Matrix([[1,ld],[0,1]]) QD = S.Matrix([[1,0],[1/fs,1]]) FODO1 = QD*DR*QF FODO2 = FODO1.subs(fs, -fs) FODO = FODO1*FODO2 FODO = S.expand(FODO) print('... this is the correct one:') S.pprint(FODO) T = 25. # kin. energy [MeV] T=T*1.e-3 # [GeV] kin.energy betakin=M.sqrt(1.-(1+T/E0)**-2) # beta kinetic E=E0+T # [GeV] energy k=0.2998*Bg/(betakin*E) # [1/m^2] L=0.596 # distance between quads [m] Ql=0.04 # full quad length [m] f = 1./(k*Ql) fodo1 = FODO.subs(fs,2*f).subs(ld,L/2.) fodo1 = np.array(fodo1) fodo2 = Mfodo(2*f,L/2.) # Wiedemann (the book is wrong!!) my_debug('matrix probe: fodo1-fodo2 must be zero matrix') zero = fodo1-fodo2 my_debug(f'{abs(zero[0][0])} {abs(zero[0][1])}') my_debug(f'{abs(zero[1][0])} {abs(zero[1][1])}') return
def getRelError(variables,func,showFunc = False): """getError generates a function to calculate the error of a function. I.E. a function that gives you the error in its result given the error in its input. Output function is numpy ready. Output function will take twice as many args as variables, one for the var and one for the error in that var. arguments variables : a list of sympy symbols in func errorVariables : list of sympy ymbols representing the error in each value of variables. must be the same length as variables func : a function containing your variables that you want the error of""" ErrorFunc = 0 # need to set function to start value erVars = {} for i in range(len(variables)): #run through all variables in the function v = variables[i] dv = Symbol('d'+str(v), positive = True) erVars['d'+str(v)] = dv D = (diff(func,v)*dv)**2 ErrorFunc += D ErrorFunc = sqrt(ErrorFunc)/func if showFunc: pprint(ErrorFunc) variables.extend(erVars.values()) #create a list of all sympy symbols involved func = lambdify(tuple(variables), ErrorFunc ,"numpy") #convert ErrorFunc to a numpy rteady python lambda return(func)
def p1_5(part=None): """ Complete solution to problem 1.5 Parameters ---------- part: str, optional(default=None) The part number you would like evaluated. If this is left blank the default value of None is used and the entire problem will be solved. Returns ------- i-dont-know-yet """ f, fp, fp2, fp3, fp4, h, fplus, fminus = symbols('f, fp, fp2, fp3, fp4, \ h, fplus, fminus') eqns = (Eq(fplus, f + fp * h + fp2 * h ** 2 / 2 + \ fp3 * h ** 3 / 6 + fp4 * h ** 4 / 24), Eq(fminus, f - fp * h + fp2 * h ** 2 / 2 - \ fp3 * h ** 3 / 6 + fp4 * h ** 4 / 24)) soln = solve(eqns, fp, fp2) pprint(soln) pass # return nothing
def showCookToomFilter(a,n,r,fractionsIn=FractionsInG): AT,G,BT,f = cookToomFilter(a,n,r,fractionsIn) print "AT = " pprint(AT) print "" print "G = " pprint(G) print "" print "BT = " pprint(BT) print "" if fractionsIn != FractionsInF: print "AT*((G*g)(BT*d)) =" pprint(filterVerify(n,r,AT,G,BT)) print "" if fractionsIn == FractionsInF: print "fractions = " pprint(f) print ""
def display(self,opt='repr'): """ Procedure Name: display Purpose: Displays the random variable in an interactive environment Arugments: 1. self: the random variable Output: 1. A print statement for each piece of the distribution indicating the function and the relevant support """ if self.ftype[0] in ['continuous','Discrete']: print ('%s %s'%(self.ftype[0],self.ftype[1])) for i in range(len(self.func)): cons_list=['0<'+str(cons) for cons in self.constraints[i]] cons_string=', '.join(cons_list) print('for x,y enclosed in the region:') print(cons_string) print('---------------------------') pprint(self.func[i]) print('---------------------------') if i<len(self.func)-1: print(' ');print(' ') if self.ftype[0]=='discrete': print '%s %s where {x->f(x)}:'%(self.ftype[0], self.ftype[1]) for i in range(len(self.support)): if i!=(len(self.support)-1): print '{%s -> %s}, '%(self.support[i], self.func[i]), else: print '{%s -> %s}'%(self.support[i], self.func[i])
def print_formulas(G): for node in G.nodes(): print("Node {}:".format(node)) pprint(G.formula_conj(node)) #pprint(simplify(G.formula_conj(node))) #pprint(to_cnf(G.formula_conj(node), simplify=True)) print("\n")
def tests(): x, y, z = symbols('x,y,z') #print(x + x + 1) expr = x**2 - y**2 factors = factor(expr) print(factors, " | ", expand(factors)) pprint(expand(factors))
def showCookToomConvolution(a,n,r,fractionsIn=FractionsInG): AT,G,BT,f = cookToomFilter(a,n,r,fractionsIn) B = BT.transpose() A = AT.transpose() print "A = " pprint(A) print "" print "G = " pprint(G) print "" print "B = " pprint(B) print "" if fractionsIn != FractionsInF: print "Linear Convolution: B*((G*g)(A*d)) =" pprint(convolutionVerify(n,r,B,G,A)) print "" if fractionsIn == FractionsInF: print "fractions = " pprint(f) print ""
def main(): print 'Initial metric:' pprint(gdd) print '-'*40 print 'Christoffel symbols:' for i in [0,1,2,3]: for k in [0,1,2,3]: for l in [0,1,2,3]: if Gamma.udd(i,k,l) != 0 : pprint_Gamma_udd(i,k,l) print'-'*40 print'Ricci tensor:' for i in [0,1,2,3]: for j in [0,1,2,3]: if Rmn.dd(i,j) !=0: pprint_Rmn_dd(i,j) print '-'*40 #Solving EFE for A and B s = ( Rmn.dd(1,1)/ A(r) ) + ( Rmn.dd(0,0)/ B(r) ) pprint (s) t = dsolve(s, A(r)) pprint(t) metric = gdd.subs(A(r), t) print "metric:" pprint(metric) r22 = Rmn.dd(3,3).subs( A(r), 1/B(r)) h = dsolve( r22, B(r) ) pprint(h)
def pprint(self, **settings): """ Print the PHS structure :math:`\\mathbf{b} = \\mathbf{M} \\cdot \\mathbf{a}` using sympy's pretty printings. Parameters ---------- settings : dic Parameters for sympy.pprint function. See Also -------- sympy.pprint """ sympy.init_printing() b = types.matrix_types[0](self.dtx() + self.w + self.y + self.cy) a = types.matrix_types[0](self.dxH() + self.z + self.u + self.cu) sympy.pprint([b, self.M, a], **settings)
def setup_loss(loss_type, native_lang = "C", verbose=False): """ set up symbolic derivations """ print "setting up autowrapped loss", loss_type x = x = sympy.Symbol("x") y = y = sympy.Symbol("y") z = z = sympy.Symbol("z") cx = cx = sympy.Symbol("cx") cy = cy = sympy.Symbol("cy") wx = wx = sympy.Symbol("wx") wy = wy = sympy.Symbol("wy") rx = rx = sympy.Symbol("rx") ry = ry = sympy.Symbol("ry") if loss_type == "algebraic_squared": fun = ((x-(cx + z*wx))**2/(rx*rx) + (y-(cy + z*wy))**2/(ry*ry) - 1)**2 if loss_type == "algebraic_abs": fun = sympy.sqrt(((x-(cx + z*wx))**2/(rx*rx) + (y-(cy + z*wy))**2/(ry*ry) - 1)**2 + 0.01) #TODO replace x**2 with x*x fun = fun.expand(deep=True) if verbose: sympy.pprint(fun) d_cx = fun.diff(cx).expand(deep=True) d_cy = fun.diff(cy).expand(deep=True) d_wx = fun.diff(wx).expand(deep=True) d_wy = fun.diff(wy).expand(deep=True) d_rx = fun.diff(rx).expand(deep=True) d_ry = fun.diff(ry).expand(deep=True) if native_lang == "fortran": c_fun = autowrap(fun, language="F95", backend="f2py") c_d_cx = autowrap(d_cx) c_d_cy = autowrap(d_cy) w_d_wx = autowrap(d_wx) w_d_wy = autowrap(d_wy) c_d_rx = autowrap(d_rx) c_d_ry = autowrap(d_ry) else: c_fun = autowrap(fun, language="C", backend="Cython", tempdir=".") c_d_cx = autowrap(d_cx, language="C", backend="Cython", tempdir=".") c_d_cy = autowrap(d_cy, language="C", backend="Cython", tempdir=".") c_d_wx = autowrap(d_wx, language="C", backend="Cython", tempdir=".") c_d_wy = autowrap(d_wy, language="C", backend="Cython", tempdir=".") c_d_rx = autowrap(d_rx, language="C", backend="Cython", tempdir=".") c_d_ry = autowrap(d_ry, language="C", backend="Cython", tempdir=".") grads = {"cx": d_cx, "cy": d_cy, "wx": d_wx, "wy": d_wy, "rx": d_rx, "ry": d_ry} c_grads = {"cx": c_d_cx, "cy": c_d_cy, "wx": c_d_wx, "wy": c_d_wy, "rx": c_d_rx, "ry": c_d_ry} print "done setting up autowrapped loss" return c_fun, c_grads
def triangle_length(l): sympy.init_printing() for n in range(1, 17): print("Triangle: ", n) print (l) sympy.pprint (l * sympy.sqrt(n), use_unicode=True) sympy.pprint (l * sympy.sqrt(n+1), use_unicode=True) print ("-------------------------")
def print_formulas(G, label=None): if label: print("{}".format(label)) print("----------------------") for node in G.nodes(): print("Node {}:".format(node)) pprint(G.formula_conj(node)) print("\n")
def main(): A = sympy.Matrix([[3, -1], [-6, 2]]) b = sympy.Matrix([0, 0]) print("\nInitial matrix:") sympy.pprint(A) x = gauss.sym_gauss(A, b) sympy.pprint(x)
def main(): a = Symbol('a') b = Symbol('b') c = Symbol('c') e = ( a*b*b + 2*b*a*b )**c print('') pprint(e) print('')
def non_homo_linear(rhs, *cds): char_func, eq, rs = homo_linear(*cds) print('\nnon-homogeneous ODE:') pprint(Eq(eq, rhs)) eq -= rhs print('\nsolving non-homogeneous linear equation...\nresult:') rs = dsolve(eq) pprint(rs) return char_func, eq, rs
def main(): a = Symbol("a") b = Symbol("b") c = Symbol("c") e = (a * b * b + 2 * b * a * b) ** c print("") pprint(e) print("")
def print_series(n): # initialize printing system with # reverse order init_printing(order='rev-lex') x = Symbol('x') series = x for i in range(2, n+1): series = series + (x**i)/i pprint(series)
def main(): a = sympy.Symbol('a') b = sympy.Symbol('b') c = sympy.Symbol('c') e = ( a*b*b + 2*b*a*b )**c print pprint(e) print
def grad_test_times_grad_field(degree): """Calculate \int \nabla \phi _i \cdot \nabla \phi _j.""" # Setup variables. r, s = sympy.symbols('r s') r_gll = sympy.symbols('r_0:%d' % (degree + 1)) s_gll = sympy.symbols('s_0:%d' % (degree + 1)) total_integration_points = (degree + 1) * (degree + 1) # Get N + 1 lagrange polynomials in each direction. generator_r = generating_polynomial_lagrange(degree, 'r', r_gll) generator_s = generating_polynomial_lagrange(degree, 's', s_gll) # Evalute bases basis = sympy.physics.quantum.TensorProduct(generator_r, generator_s) gll_coordinates, gll_weights = gauss_lobatto_legendre_quadruature_points_weights(degree + 1) basis = basis.subs([(v, c) for v, c in zip(r_gll, gll_coordinates)]) basis = basis.subs([(v, c) for v, c in zip(s_gll, gll_coordinates)]) # Get gradient of basis functions. basis_gradient_r = [sympy.diff(i, r) for i in basis] basis_gradient_s = [sympy.diff(i, s) for i in basis] # Get interpolating field. field = poly_2D(degree) # Take gradient of this field. grad_field = sympy.Matrix([[sympy.diff(field, r).subs({r: i, s: j}) for j in gll_coordinates for i in gll_coordinates], [sympy.diff(field, s).subs({r: i, s: j}) for j in gll_coordinates for i in gll_coordinates]]) # Take gradient of the tensor basis. grad_test = sympy.Matrix([basis_gradient_r, basis_gradient_s]) # Compute \nabla \phi _i \cdot \nabla \phi _j grad_test_grad_field = [grad_test.col(i).dot(grad_field.col(j)) for i in range(total_integration_points) for j in range(total_integration_points)] # Sum over \phi _i final_grad = [sum(grad_test_grad_field[i:i + total_integration_points]) for i in range(0, len(grad_test_grad_field), total_integration_points)] # Integrate over 2D domain. integrated = [sympy.integrate(f, (r, -1, 1)) for f in final_grad] integrated = [sympy.integrate(f, (s, -1, 1)) for f in integrated] print("NABLA PHI_i \cdot NABLA PHI_j") sympy.pprint(integrated) print(sum(integrated))
def test_pprint(): import StringIO, sys fd = StringIO.StringIO() sso = sys.stdout sys.stdout = fd try: pprint(pi, use_unicode=False) finally: sys.stdout = sso assert fd.getvalue() == 'pi\n'
def print_series(n, x_value): init_printing(order = 'rev-lex') x = Symbol('x') series = x for i in range(2, n+1): series = series + (x**i)/i pprint(series) series_value = series.subs({x:x_value}) print('Value of the series at {0}: {1}'.format(x_value, series_value))
def main(): a = sympy.Symbol("a") b = sympy.Symbol("b") e = (a + b) ** 5 print pprint(e) print "\n" pprint(e.expand()) print
def main(): a = sympy.Symbol('a') b = sympy.Symbol('b') e = (a + b)**5 print("\nExpression:") pprint(e) print('\nExpansion of the above expression:') pprint(e.expand()) print()
def printSeries(n, val): init_printing(order='rev-lex') x = Symbol('x') expr = x for i in range(2, n + 1): expr += (x**i / i) pprint(expr) res = expr.subs({x: val}) print(res)
def Subcriticalb(): r, x = sy.symbols('r x', real=True) equation = r * x + 4 * x**3 - 9 * x**5 system = [sy.Eq(equation, 0), sy.Eq(sy.diff(equation, x), 0)] sy.pprint(sy.solve(system)) equation.subs((r, -4 / 9))
def eq3(): r = Symbol("r") e = Rmn.dd(2,2) e = e.subs(nu(r), -lam(r)) pprint(dsolve(e, lam(r)))
def pmatrix(Anp, s): import sympy msym = sympy.Matrix(Anp) print(s) sympy.pprint(msym)
import sympy from sympy.abc import pi sympy.pprint(pi) sympy.pprint("I am" + pi)
# In[3]: import sympy as sym a = sym.sqrt(11) a # Podemos mejorar la apariencia de una expresión si en vez de usar print utilizamos: # ~~~python # sym.pprint(a) # ~~~ # o si simplemente poniendo la expresión. # In[4]: sym.pprint(a) # Podemos obtener el valor numérico con evalf(). Obtenga el valor numérico de $\sqrt{11}$ # In[5]: a.evalf() # Las variables comunes de álgebra son símbolos. Si quiero definir x: # In[6]: x = sym.symbols("x") # Imprimimos x para verificar.
# -*- coding: utf-8 -*- # Usage: python math/composition-shift.py import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), "..")) from CALPHAD_energies import * from sympy import Eq, init_printing, Matrix, pprint, solve_linear_system, symbols init_printing() P_delta = 2 * s_delta / r_delta P_laves = 2 * s_laves / r_laves pprint(Eq(symbols("x_alpha_Cr"), xe_gam_Cr + DXAB(P_delta, P_laves))) pprint(Eq(symbols("x_alpha_Nb"), xe_gam_Nb + DXAC(P_delta, P_laves))) pprint(Eq(symbols("x_beta_Cr"), xe_del_Cr + DXBB(P_delta, P_laves))) pprint(Eq(symbols("x_beta_Nb"), xe_del_Nb + DXBC(P_delta, P_laves))) pprint(Eq(symbols("x_gamma_Cr"), xe_lav_Cr + DXGB(P_delta, P_laves))) pprint(Eq(symbols("x_gamma_Nb"), xe_lav_Nb + DXGC(P_delta, P_laves))) pprint(Eq(symbols("x_Cr"), levers[y])) pprint(Eq(symbols("x_Nb"), levers[x]))
def main(): e = sympy.Rational(2)**50/sympy.Rational(10)**50 pprint(e)
#!/usr/bin/env python from sympy import pi, Symbol, symbols, log, pprint print(pi.evalf(50), '\n') # <1> x = Symbol('x') # <2> f = x**(1 - log(log(log(log(1 / x))))) # <3> pprint(f) pprint(f.subs(x, pi).evalf()) # <4> pprint(f.subs(x, 10).evalf()) pprint(f.subs(x, 3).evalf()) print() a, b, c = symbols('a b c') # <5> exp = (a + b) * 40 - (c - a) / 0.5 # <6> pprint(exp) pprint(exp.evalf(6, subs={a: 6, b: 5, c: 2})) # <7>
p = x * (x + x) print(p) p = (x + 2) * (x + 3) print(p) expr = x**2 - y**2 factors = factor(expr) print(factor(expr)) print(expand(factors)) expr = x**3 + 3 * x**2 * y + 3 * x * y**2 + y**3 factors = factor(expr) print(factors) pprint(factors) n = 5 series = x for i in range(2, n + 1): series = series + (x**i) / i pprint(series) expr = x * x + x * y + x * y + y * y res = expr.subs({x: 1, y: 2}) print(res) print(expr.subs({x: 1 - y})) x = Symbol('x') series = x
print(expression_3) print() # 符号矩阵 print('符号矩阵:') a, b = sympy.symbols('a b') matrix = sympy.Matrix([[1, a], [0, b]]) # 使用sympy.Matrix() print(matrix) print() sympy.init_printing(use_unicode=True) # 符号矩阵的特征值和特征向量 print('符号矩阵的特征值和特征向量:') eigenvalue = matrix.eigenvals() # 使用.eigenvals()方法 print('特征值\n', eigenvalue, '\n') sympy.pprint(eigenvalue) # 使用sympy.pprint()输出 print('\n', sympy.pretty(eigenvalue)) # 使用sympy.pretty()美化后输出 print() eigenvector = matrix.eigenvects() # 使用.eigenvects()方法 print('特征向量\n', eigenvector, '\n') sympy.pprint(eigenvector) print('\n', sympy.pretty(eigenvector)) print() P, D = matrix.diagonalize() # 使用.diagonalize()方法 print('特征值\n', D, '\n') print(sympy.pretty(D), '\n') print('特征向量\n', P, '\n') print(sympy.pretty(P), '\n') print()
def main(): print(__doc__) # arrays are represented with IndexedBase, indices with Idx m = Symbol('m', integer=True) i = Idx('i', m) A = IndexedBase('A') B = IndexedBase('B') x = Symbol('x') print("Compiling ufuncs for radial harmonic oscillator solutions") # setup a basis of ho-solutions (for l=0) basis_ho = {} for n in range(basis_dimension): # Setup the radial ho solution for this n expr = R_nl(n, orbital_momentum_l, omega2, x) # Reduce the number of operations in the expression by eval to float expr = expr.evalf(15) print("The h.o. wave function with l = %i and n = %i is" % (orbital_momentum_l, n)) pprint(expr) # implement, compile and wrap it as a ufunc basis_ho[n] = ufuncify(x, expr) # now let's see if we can express a hydrogen radial wave in terms of # the ho basis. Here's the solution we will approximate: H_ufunc = ufuncify(x, hydro_nl(hydrogen_n, orbital_momentum_l, 1, x)) # The transformation to a different basis can be written like this, # # psi(r) = sum_i c(i) phi_i(r) # # where psi(r) is the hydrogen solution, phi_i(r) are the H.O. solutions # and c(i) are scalar coefficients. # # So in order to express a hydrogen solution in terms of the H.O. basis, we # need to determine the coefficients c(i). In position space, it means # that we need to evaluate an integral: # # psi(r) = sum_i Integral(R**2*conj(phi(R))*psi(R), (R, 0, oo)) phi_i(r) # # To calculate the integral with autowrap, we notice that it contains an # element-wise sum over all vectors. Using the Indexed class, it is # possible to generate autowrapped functions that perform summations in # the low-level code. (In fact, summations are very easy to create, and as # we will see it is often necessary to take extra steps in order to avoid # them.) # we need one integration ufunc for each wave function in the h.o. basis binary_integrator = {} for n in range(basis_dimension): # # setup basis wave functions # # To get inline expressions in the low level code, we attach the # wave function expressions to a regular SymPy function using the # implemented_function utility. This is an extra step needed to avoid # erroneous summations in the wave function expressions. # # Such function objects carry around the expression they represent, # but the expression is not exposed unless explicit measures are taken. # The benefit is that the routines that searches for repeated indices # in order to make contractions will not search through the wave # function expression. psi_ho = implemented_function( 'psi_ho', Lambda(x, R_nl(n, orbital_momentum_l, omega2, x))) # We represent the hydrogen function by an array which will be an input # argument to the binary routine. This will let the integrators find # h.o. basis coefficients for any wave function we throw at them. psi = IndexedBase('psi') # # setup expression for the integration # step = Symbol('step') # use symbolic stepsize for flexibility # let i represent an index of the grid array, and let A represent the # grid array. Then we can approximate the integral by a sum over the # following expression (simplified rectangular rule, ignoring end point # corrections): expr = A[i]**2 * psi_ho(A[i]) * psi[i] * step if n == 0: print("Setting up binary integrators for the integral:") pprint(Integral(x**2 * psi_ho(x) * Function('psi')(x), (x, 0, oo))) # Autowrap it. For functions that take more than one argument, it is # a good idea to use the 'args' keyword so that you know the signature # of the wrapped function. (The dimension m will be an optional # argument, but it must be present in the args list.) binary_integrator[n] = autowrap(expr, args=[A.label, psi.label, step, m]) # Lets see how it converges with the grid dimension print("Checking convergence of integrator for n = %i" % n) for g in range(3, 8): grid, step = np.linspace(0, rmax, 2**g, retstep=True) print("grid dimension %5i, integral = %e" % (2**g, binary_integrator[n](grid, H_ufunc(grid), step))) print("A binary integrator has been set up for each basis state") print("We will now use them to reconstruct a hydrogen solution.") # Note: We didn't need to specify grid or use gridsize before now grid, stepsize = np.linspace(0, rmax, gridsize, retstep=True) print("Calculating coefficients with gridsize = %i and stepsize %f" % (len(grid), stepsize)) coeffs = {} for n in range(basis_dimension): coeffs[n] = binary_integrator[n](grid, H_ufunc(grid), stepsize) print("c(%i) = %e" % (n, coeffs[n])) print("Constructing the approximate hydrogen wave") hydro_approx = 0 all_steps = {} for n in range(basis_dimension): hydro_approx += basis_ho[n](grid) * coeffs[n] all_steps[n] = hydro_approx.copy() if pylab: line = pylab.plot(grid, all_steps[n], ':', label='max n = %i' % n) # check error numerically diff = np.max(np.abs(hydro_approx - H_ufunc(grid))) print("Error estimate: the element with largest deviation misses by %f" % diff) if diff > 0.01: print("This is much, try to increase the basis size or adjust omega") else: print("Ah, that's a pretty good approximation!") # Check visually if pylab: print("Here's a plot showing the contribution for each n") line[0].set_linestyle('-') pylab.plot(grid, H_ufunc(grid), 'r-', label='exact') pylab.legend() pylab.show() print("""Note: These binary integrators were specialized to find coefficients for a harmonic oscillator basis, but they can process any wave function as long as it is available as a vector and defined on a grid with equidistant points. That is, on any grid you get from numpy.linspace. To make the integrators even more flexible, you can setup the harmonic oscillator solutions with symbolic parameters omega and l. Then the autowrapped binary routine will take these scalar variables as arguments, so that the integrators can find coefficients for *any* isotropic harmonic oscillator basis. """)
from sympy import init_printing, pprint init_printing(use_unicode=True) # about `Points` from sympy.vector import CoordSys3D N = CoordSys3D("N") pprint(N.origin) print(type(N.origin)) # we can instantiate new points in space using locate_new method of `Point` from sympy.abc import a, b, c P = N.origin.locate_new("P", a*N.i + b*N.j + c*N.k) Q = P.locate_new("Q", -b*N.j) pprint(P) pprint(Q) # position vector # v = P - Q v = P.position_wrt(Q) pprint(v) v = Q.position_wrt(N.origin) pprint(v) v = P.position_wrt(N.origin) pprint(v)
def a(): t = sym.symbols('t') xt = 4 * sym.sin(7*t)+ 25* sym.cos(15*t) #sym.plot(xt) sym.pprint(xt)
import sympy as sy import matplotlib.pyplot as plt import numpy as np plt.close() sy.init_printing() #From Johansson, R Numerical Python p.209 onward. #Create symbols for the ODE r,k,N0, t = sy.symbols('r k N_0 t' ) N = sy.symbols('N', function=True) ode = N(t).diff(t) - (r*N(t)*(1-N(t)/k))# - N(t)**2/(1+N(t)**2)) sy.pprint(sy.Eq(ode)) #solve the ODE ode_sol = sy.dsolve(ode, N(t)) ics = {N(0):N0} print('+'*30) print('Iniital conditions:') sy.pprint(ics) #Find the value of the integration constants C_eq = sy.Eq(ode_sol.lhs.subs(t,0).subs(ics),ode_sol.rhs.subs(t,0)) print('+'*30) print('Create equations at N(0))') sy.pprint(C_eq) print() #Solve for C_eq C_sol = sy.solve(C_eq,sy.Symbol('C1')) soln = ode_sol.subs(sy.Symbol('C1'),C_sol[0]) sy.pprint(C_sol) sy.pprint(soln) print('+'*30) ode_func = sy.lambdify(t, soln.rhs.subs({N0:100,r:.2,k:1000}) )
def getExpression(mode, submode): '''一阶电路示例''' if (mode == 1): if (submode == 1): Vc = symbols('Vc', cls=sp.Function) t = symbols('t') if (S.mode == 0): eq = Eq(diff(Vc(t), t, 1), -Vc(t) / (S.R * S.C) + S.Vs / (S.R * S.C)) sp.pprint(dsolve(eq, Vc(t), ics={Vc(0): S.V0})) elif (S.mode == 1): eq = Eq( diff(Vc(t), t, 1), -Vc(t) / (S.R * S.C) + S.Vs * sp.sin(2 * sp.pi * t / S.T0) / (S.R * S.C)) sp.pprint(dsolve(eq, Vc(t), ics={Vc(0): S.V0})) elif (submode == 2): iL = symbols('iL', cls=sp.Function) t = symbols('t') if (S.mode == 0): eq = Eq(diff(iL(t), t, 1), -iL(t) * S.R / S.L + S.iS * S.R / S.L) sp.pprint(dsolve(eq, iL(t), ics={iL(0): S.I0})) elif (S.mode == 1): eq = Eq( diff(iL(t), t, 1), -iL(t) * S.R / S.L + S.iS * sp.sin(2 * sp.pi * t / S.T0) * S.R / S.L) sp.pprint(dsolve(eq, iL(t), ics={iL(0): S.I0})) '''二阶电路示例''' elif (mode == 2): if (submode == 1): Vc, iL = symbols('Vc,iL', cls=sp.Function) t = symbols('t') if (S.mode == 0): eq1 = Eq( diff(Vc(t), t, 2) + S.R * diff(Vc(t), t, 1) / S.L + Vc(t) / (S.L * S.C), S.Vs / (S.L * S.C)) sp.pprint( dsolve(eq1, Vc(t), ics={ Vc(0): S.V0, diff(Vc(t), t).subs(t, 0): S.I0 / S.C })) elif (S.mode == 1): eq1 = Eq( diff(Vc(t), t, 2) + S.R * diff(Vc(t), t, 1) / S.L + Vc(t) / (S.L * S.C), S.Vs * sp.sin(2 * sp.pi * t / S.T0) / (S.L * S.C)) sp.pprint( dsolve(eq1, Vc(t), ics={ Vc(0): S.V0, diff(Vc(t), t).subs(t, 0): S.I0 / S.C }))
def _dev_iters_until_threshold(): """ INTERACTIVE DEVELOPMENT FUNCTION How many iterations of ewma until you hit the poisson / biniomal threshold This establishes a principled way to choose the threshold for the refresh criterion in my thesis. There are paramters --- moving parts --- that we need to work with: `a` the patience, `s` the span, and `mu` our ewma. `s` is a span paramter indicating how far we look back. `mu` is the average number of label-changing reviews in roughly the last `s` manual decisions. These numbers are used to estimate the probability that any of the next `a` manual decisions will be label-chanigng. When that probability falls below a threshold we terminate. The goal is to choose `a`, `s`, and the threshold `t`, such that the probability will fall below the threshold after a maximum of `a` consecutive non-label-chaning reviews. IE we want to tie the patience paramter (how far we look ahead) to how far we actually are willing to go. """ import numpy as np import utool as ut import sympy as sym i = sym.symbols('i', integer=True, nonnegative=True, finite=True) # mu_i = sym.symbols('mu_i', integer=True, nonnegative=True, finite=True) s = sym.symbols('s', integer=True, nonnegative=True, finite=True) # NOQA thresh = sym.symbols('tau', real=True, nonnegative=True, finite=True) # NOQA alpha = sym.symbols('alpha', real=True, nonnegative=True, finite=True) # NOQA c_alpha = sym.symbols('c_alpha', real=True, nonnegative=True, finite=True) # patience a = sym.symbols('a', real=True, nonnegative=True, finite=True) available_subs = { a: 20, s: a, alpha: 2 / (s + 1), c_alpha: (1 - alpha), } def subs(expr, d=available_subs): """ recursive expression substitution """ expr1 = expr.subs(d) if expr == expr1: return expr1 else: return subs(expr1, d=d) # mu is either the support for the poisson distribution # or is is the p in the binomial distribution # It is updated at timestep i based on ewma, assuming each incoming responce is 0 mu_0 = 1.0 mu_i = c_alpha ** i # Estimate probability that any event will happen in the next `a` reviews # at time `i`. poisson_i = 1 - sym.exp(-mu_i * a) binom_i = 1 - (1 - mu_i) ** a # Expand probabilities to be a function of i, s, and a part = ut.delete_dict_keys(available_subs.copy(), [a, s]) mu_i = subs(mu_i, d=part) poisson_i = subs(poisson_i, d=part) binom_i = subs(binom_i, d=part) if True: # ewma of mu at time i if review is always not label-changing (meaningful) mu_1 = c_alpha * mu_0 # NOQA mu_2 = c_alpha * mu_1 # NOQA if True: i_vals = np.arange(0, 100) mu_vals = np.array([subs(mu_i).subs({i: i_}).evalf() for i_ in i_vals]) # NOQA binom_vals = np.array([subs(binom_i).subs({i: i_}).evalf() for i_ in i_vals]) # NOQA poisson_vals = np.array([subs(poisson_i).subs({i: i_}).evalf() for i_ in i_vals]) # NOQA # Find how many iters it actually takes my expt to terminate thesis_draft_thresh = np.exp(-2) np.where(mu_vals < thesis_draft_thresh)[0] np.where(binom_vals < thesis_draft_thresh)[0] np.where(poisson_vals < thesis_draft_thresh)[0] sym.pprint(sym.simplify(mu_i)) sym.pprint(sym.simplify(binom_i)) sym.pprint(sym.simplify(poisson_i)) # Find the thresholds that force termination after `a` reviews have passed # do this by setting i=a poisson_thresh = poisson_i.subs({i: a}) binom_thresh = binom_i.subs({i: a}) print('Poisson thresh') print(sym.latex(sym.Eq(thresh, poisson_thresh))) print(sym.latex(sym.Eq(thresh, sym.simplify(poisson_thresh)))) poisson_thresh.subs({a: 115, s: 30}).evalf() sym.pprint(sym.Eq(thresh, poisson_thresh)) sym.pprint(sym.Eq(thresh, sym.simplify(poisson_thresh))) print('Binomial thresh') sym.pprint(sym.simplify(binom_thresh)) sym.pprint(sym.simplify(poisson_thresh.subs({s: a}))) def taud(coeff): return coeff * 360 if 'poisson_cache' not in vars(): poisson_cache = {} binom_cache = {} S, A = np.meshgrid(np.arange(1, 150, 1), np.arange(0, 150, 1)) import plottool as pt SA_coords = list(zip(S.ravel(), A.ravel())) for sval, aval in ut.ProgIter(SA_coords): if (sval, aval) not in poisson_cache: poisson_cache[(sval, aval)] = float(poisson_thresh.subs({a: aval, s: sval}).evalf()) poisson_zdata = np.array( [poisson_cache[(sval, aval)] for sval, aval in SA_coords]).reshape(A.shape) fig = pt.figure(fnum=1, doclf=True) pt.gca().set_axis_off() pt.plot_surface3d(S, A, poisson_zdata, xlabel='s', ylabel='a', rstride=3, cstride=3, zlabel='poisson', mode='wire', contour=True, title='poisson3d') pt.gca().set_zlim(0, 1) pt.gca().view_init(elev=taud(1 / 16), azim=taud(5 / 8)) fig.set_size_inches(10, 6) fig.savefig('a-s-t-poisson3d.png', dpi=300, bbox_inches=pt.extract_axes_extents(fig, combine=True)) for sval, aval in ut.ProgIter(SA_coords): if (sval, aval) not in binom_cache: binom_cache[(sval, aval)] = float(binom_thresh.subs({a: aval, s: sval}).evalf()) binom_zdata = np.array( [binom_cache[(sval, aval)] for sval, aval in SA_coords]).reshape(A.shape) fig = pt.figure(fnum=2, doclf=True) pt.gca().set_axis_off() pt.plot_surface3d(S, A, binom_zdata, xlabel='s', ylabel='a', rstride=3, cstride=3, zlabel='binom', mode='wire', contour=True, title='binom3d') pt.gca().set_zlim(0, 1) pt.gca().view_init(elev=taud(1 / 16), azim=taud(5 / 8)) fig.set_size_inches(10, 6) fig.savefig('a-s-t-binom3d.png', dpi=300, bbox_inches=pt.extract_axes_extents(fig, combine=True)) # Find point on the surface that achieves a reasonable threshold # Sympy can't solve this # sym.solve(sym.Eq(binom_thresh.subs({s: 50}), .05)) # sym.solve(sym.Eq(poisson_thresh.subs({s: 50}), .05)) # Find a numerical solution def solve_numeric(expr, target, want, fixed, method=None, bounds=None): """ Args: expr (Expr): symbolic expression target (float): numberic value fixed (dict): fixed values of the symbol expr = poisson_thresh expr.free_symbols fixed = {s: 10} solve_numeric(poisson_thresh, .05, {s: 30}, method=None) solve_numeric(poisson_thresh, .05, {s: 30}, method='Nelder-Mead') solve_numeric(poisson_thresh, .05, {s: 30}, method='BFGS') """ import scipy.optimize # Find the symbol you want to solve for want_symbols = expr.free_symbols - set(fixed.keys()) # TODO: can probably extend this to multiple params assert len(want_symbols) == 1, 'specify all but one var' assert want == list(want_symbols)[0] fixed_expr = expr.subs(fixed) def func(a1): expr_value = float(fixed_expr.subs({want: a1}).evalf()) return (expr_value - target) ** 2 # if method is None: # method = 'Nelder-Mead' # method = 'Newton-CG' # method = 'BFGS' # Use one of the other params the startin gpoing a1 = list(fixed.values())[0] result = scipy.optimize.minimize(func, x0=a1, method=method, bounds=bounds) if not result.success: print('\n') print(result) print('\n') return result # Numeric measurments of thie line thresh_vals = [.001, .01, .05, .1, .135] svals = np.arange(1, 100) target_poisson_plots = {} for target in ut.ProgIter(thresh_vals, bs=False, freq=1): poisson_avals = [] for sval in ut.ProgIter(svals, 'poisson', freq=1): expr = poisson_thresh fixed = {s: sval} want = a aval = solve_numeric(expr, target, want, fixed, method='Nelder-Mead').x[0] poisson_avals.append(aval) target_poisson_plots[target] = (svals, poisson_avals) fig = pt.figure(fnum=3) for target, dat in target_poisson_plots.items(): pt.plt.plot(*dat, label='prob={}'.format(target)) pt.gca().set_xlabel('s') pt.gca().set_ylabel('a') pt.legend() pt.gca().set_title('poisson') fig.set_size_inches(5, 3) fig.savefig('a-vs-s-poisson.png', dpi=300, bbox_inches=pt.extract_axes_extents(fig, combine=True)) target_binom_plots = {} for target in ut.ProgIter(thresh_vals, bs=False, freq=1): binom_avals = [] for sval in ut.ProgIter(svals, 'binom', freq=1): aval = solve_numeric(binom_thresh, target, a, {s: sval}, method='Nelder-Mead').x[0] binom_avals.append(aval) target_binom_plots[target] = (svals, binom_avals) fig = pt.figure(fnum=4) for target, dat in target_binom_plots.items(): pt.plt.plot(*dat, label='prob={}'.format(target)) pt.gca().set_xlabel('s') pt.gca().set_ylabel('a') pt.legend() pt.gca().set_title('binom') fig.set_size_inches(5, 3) fig.savefig('a-vs-s-binom.png', dpi=300, bbox_inches=pt.extract_axes_extents(fig, combine=True)) # ---- if True: fig = pt.figure(fnum=5, doclf=True) s_vals = [1, 2, 3, 10, 20, 30, 40, 50] for sval in s_vals: pp = poisson_thresh.subs({s: sval}) a_vals = np.arange(0, 200) pp_vals = np.array([float(pp.subs({a: aval}).evalf()) for aval in a_vals]) # NOQA pt.plot(a_vals, pp_vals, label='s=%r' % (sval,)) pt.legend() pt.gca().set_xlabel('a') pt.gca().set_ylabel('poisson prob after a reviews') fig.set_size_inches(5, 3) fig.savefig('a-vs-thresh-poisson.png', dpi=300, bbox_inches=pt.extract_axes_extents(fig, combine=True)) fig = pt.figure(fnum=6, doclf=True) s_vals = [1, 2, 3, 10, 20, 30, 40, 50] for sval in s_vals: pp = binom_thresh.subs({s: sval}) a_vals = np.arange(0, 200) pp_vals = np.array([float(pp.subs({a: aval}).evalf()) for aval in a_vals]) # NOQA pt.plot(a_vals, pp_vals, label='s=%r' % (sval,)) pt.legend() pt.gca().set_xlabel('a') pt.gca().set_ylabel('binom prob after a reviews') fig.set_size_inches(5, 3) fig.savefig('a-vs-thresh-binom.png', dpi=300, bbox_inches=pt.extract_axes_extents(fig, combine=True)) # ------- fig = pt.figure(fnum=5, doclf=True) a_vals = [1, 2, 3, 10, 20, 30, 40, 50] for aval in a_vals: pp = poisson_thresh.subs({a: aval}) s_vals = np.arange(1, 200) pp_vals = np.array([float(pp.subs({s: sval}).evalf()) for sval in s_vals]) # NOQA pt.plot(s_vals, pp_vals, label='a=%r' % (aval,)) pt.legend() pt.gca().set_xlabel('s') pt.gca().set_ylabel('poisson prob') fig.set_size_inches(5, 3) fig.savefig('s-vs-thresh-poisson.png', dpi=300, bbox_inches=pt.extract_axes_extents(fig, combine=True)) fig = pt.figure(fnum=5, doclf=True) a_vals = [1, 2, 3, 10, 20, 30, 40, 50] for aval in a_vals: pp = binom_thresh.subs({a: aval}) s_vals = np.arange(1, 200) pp_vals = np.array([float(pp.subs({s: sval}).evalf()) for sval in s_vals]) # NOQA pt.plot(s_vals, pp_vals, label='a=%r' % (aval,)) pt.legend() pt.gca().set_xlabel('s') pt.gca().set_ylabel('binom prob') fig.set_size_inches(5, 3) fig.savefig('s-vs-thresh-binom.png', dpi=300, bbox_inches=pt.extract_axes_extents(fig, combine=True)) #--------------------- # Plot out a table mu_i.subs({s: 75, a: 75}).evalf() poisson_thresh.subs({s: 75, a: 75}).evalf() sval = 50 for target, dat in target_poisson_plots.items(): slope = np.median(np.diff(dat[1])) aval = int(np.ceil(sval * slope)) thresh = float(poisson_thresh.subs({s: sval, a: aval}).evalf()) print('aval={}, sval={}, thresh={}, target={}'.format(aval, sval, thresh, target)) for target, dat in target_binom_plots.items(): slope = np.median(np.diff(dat[1])) aval = int(np.ceil(sval * slope))
from sympy import Symbol, Limit from sympy import Symbol, exp, sqrt, pi, Integral from sympy import pprint # video1 t = Symbol('t') St = 5 * t**2 + 2 * t + 8 t1 = Symbol('t1') delta_t = Symbol('delta_t') St1 = St.subs({t: t1}) St1_delta = St.subs({t: t1 + delta_t}) Limit((St1_delta - St1) / delta_t, delta_t, 0).doit() # video2 x = Symbol('x') p = exp(-(x - 10)**2 / 2) / sqrt(2 * pi) pprint(Integral(p, (x, 11, 12)).doit().evalf())
def derivative(f, var): var = Symbol(var) d = Derivative(f, var).doit( ) # Define a function(f) and a variable(var) to differentiate pprint(d)
return f.diff(x, 2) + f.diff(y, 2) r = sqrt(x**2 + y**2) r_w = sqrt((x - x_w)**2 + (y - y_w)**2) r_p_squared = (x - x_p)**2 + (y - y_p)**2 theta = atan(y / x) u = r**(pi / omega) * sin(theta * pi / omega) + atan( alpha_w * (r_w - r0)) + exp(-alpha_p * r_p_squared) + exp(-(1 + y) / epsilon) params = { omega: 3 * pi / 2, x_w: 0, y_w: -S(3) / 4, r0: S(3) / 4, alpha_p: 1000, alpha_w: 200, x_p: sqrt(5) / 4, y_p: -S(1) / 4, epsilon: S(1) / 100, } u = u.subs(params) lhs = laplace(u) print "lhs, as a formula:" pprint(lhs) print print "-" * 60 print "lhs, as C code:" print ccode(lhs)
#!/usr/bin/env python # Prerequisites: have sympy installed (or use Anaconda) import sympy # from math import tan from sympy.solvers.solveset import nonlinsolve from sympy.core.symbol import symbols from sympy import tan, pprint x1, y1, doa_1, theta_1 = symbols('x1, y1, doa1, theta1', real=True) x2, y2, doa_2, theta_2 = symbols('x2, y2, doa2, theta2', real=True) x3, y3, doa_3, theta_3 = symbols('x3, y3, doa3, theta3', real=True) xr, yr, theta_r = symbols('xr, yr, theta_r', real=True) # eq1 = doa_1 + theta_r - theta_1 # theta 1 = theta_r + doa_1 # eq2 = doa_2 + theta_r - theta_2 # theta 2 = theta_r + doa_2 # eq3 = doa_3 + theta_r - theta_3 # theta 3 = theta_r + doa_3 # eq4 = (y1 - yr) / (x1 - xr) - tan(theta_1) # eq5 = (y2 - yr) / (x2 - xr) - tan(theta_2) # eq6 = (y3 - yr) / (x3 - xr) - tan(theta_3) eq1 = (y1 - yr) / (x1 - xr) - tan(doa_1 + theta_r) eq2 = (y2 - yr) / (x2 - xr) - tan(doa_2 + theta_r) eq3 = (y3 - yr) / (x3 - xr) - tan(doa_3 + theta_r) result = nonlinsolve([eq1, eq2, eq3], [xr, yr, theta_r]) pprint(result, use_unicode=True)
[ C1, C2, C3, C4 ]) # %% Se reemplaza aquí el valor de las constantes de integración V = V.subs(sol) M = M.subs(sol) t = t.subs(sol) v = v.subs(sol) # %% Se simplifica lo calculado por sympy V = sp.piecewise_fold(V.rewrite(sp.Piecewise)).nsimplify() M = sp.piecewise_fold(M.rewrite(sp.Piecewise)).nsimplify() t = sp.piecewise_fold(t.rewrite(sp.Piecewise)) v = sp.piecewise_fold(v.rewrite(sp.Piecewise)) # %% Se imprimen los resultados print("\n\nV(x) = "); sp.pprint(V) print("\n\nM(x) = "); sp.pprint(M) print("\n\nt(x) = "); sp.pprint(t) print("\n\nv(x) = "); sp.pprint(v) # %% Se grafican los resultados x_xmin_xmax = (x, 0+0.001, 6-0.001) sp.plot(V, x_xmin_xmax, xlabel='x', ylabel='V(x)') sp.plot(M, x_xmin_xmax, xlabel='x', ylabel='M(x)') sp.plot(t, x_xmin_xmax, xlabel='x', ylabel='t(x)') sp.plot(v, x_xmin_xmax, xlabel='x', ylabel='v(x)') # %% Se calculan las reacciones en la viga print(f"Fy(x=0) = {float(+V.subs(sol).subs(x, 0))}") # Ry en x=0 print(f"Fy(x=6) = {float(-V.subs(sol).subs(x, 6))}") # Ry en x=6
from sympy import symbols, solve, diff, pprint, integrate # After a long study, tree scientists conclude that a eucalyptus tree will grow at the rate of t = symbols('t') R = 0.5 + 4 / (t + 1)**3 # feet per year, where t is the time (in years). pprint(R) # Find the number of feet that the tree will grow in the second year. a, b = 1, 2 round(integrate(R, (t, a, b)), 3) # Round to three decimal places as needed. # Find the number of feet that the tree will grow in the second year. a, b = 2, 3 round(integrate(R, (t, a, b)), 3) # Round to three decimal places as needed.
X3_s_step_G_theta = G_theta * F_s_step x3_t_step_G_theta = sym.inverse_laplace_transform(X3_s_step_G_theta, s, t) X3_s_frequency_G_theta = G_theta * F_s_frequency x3_t_frequency_G_theta = sym.inverse_laplace_transform(X3_s_frequency_G_theta, s, t, w) X1_s_impulse_G_x = G_x * F_s_impulse x1_t_impulse_G_x = sym.inverse_laplace_transform(X1_s_impulse_G_x, s, t) X1_s_step_G_x = G_x * F_s_step x1_t_step_G_x = sym.inverse_laplace_transform(X1_s_step_G_x, s, t) X1_s_frequency_G_x = G_x * F_s_frequency x1_t_frequency_G_x = sym.inverse_laplace_transform(X1_s_frequency_G_x, s, t, w) # Print the symbolic expressions #sym.pprint(x3_t_impulse_G_theta.simplify()) #sym.pprint(x3_t_step_G_theta.simplify()) sym.pprint(x3_t_frequency_G_theta.simplify()) #sym.pprint(x1_t_impulse_G_x.simplify()) #sym.pprint(x1_t_step_G_x.simplify()) #sym.pprint(x1_t_frequency_G_x.simplify()) # Print the symbolic expressions for LaTex #print(sym.latex(x3_t_impulse_G_theta.simplify())) #print(sym.latex(x3_t_step_G_theta.simplify())) #print(sym.latex(x3_t_frequency_G_theta.simplify())) #print(sym.latex(x1_t_impulse_G_x.simplify())) #print(sym.latex(x1_t_step_G_x.simplify())) #print(sym.latex(x1_t_frequency_G_x.simplify()))
def SARIMAEquation(trendparams:tuple=(0,0,0), seasonalparams:tuple=(0,0,0,1), trendAR=None, trendMA=None, seasonAR=None, seasonMA=None): p, d, q = trendparams P, D, Q, m = seasonalparams print(f'SARIMA({p},{d},{q})({P},{D},{Q},{m})') assert type(p) is int, 'Input parameter "p" is not an integer type.' assert type(d) is int, 'Input parameter "d" is not an integer type.' assert type(q) is int, 'Input parameter "q" is not an integer type.' assert type(P) is int, 'Input parameter "P" is not an integer type.' assert type(D) is int, 'Input parameter "D" is not an integer type.' assert type(Q) is int, 'Input parameter "Q" is not an integer type.' assert type(m) is int, 'Input parameter "m" is not an integer type.' if trendAR : assert len(trendAR) == p, f'The len(trendAR) must be {p}. Reset the parameters.' else : trendAR = [0]*p if trendMA : assert len(trendMA) == q, f'The len(trendMA) must be {q}. Reset the parameters.' else : trendMA = [0]*q if seasonAR : assert len(seasonAR) == P, f'The len(seasonAR) must be {P}. Reset the parameters.' else : seasonAR = [0]*P if seasonMA : assert len(seasonMA) == Q, f'The len(seasonMA) must be {Q}. Reset the parameters.' else : seasonMA = [0]*Q Y_order = p + P*m + d + D*m e_order = q + Q*m # define Y, e Y, e = sympy.symbols('Y_t, e_t') I, J = sympy.symbols('i, j') Y_ = {}; e_ = {} Y_['t'] = Y; Y__ = [ [Y_['t']] ] e_['t'] = e; e__ = [ [e_['t']] ] for i in range(1, Y_order+1): Y_[f't-{i}'] = sympy.symbols(f'Y_t-{i}') Y__.append( [Y_[f't-{i}']*(I**i)] ) # Y__ = [ [Y_['t']], [Y_['t-1']], ..., [Y_['t-(p+P*m+q+Q*m)']] ] for i in range(1, e_order+1): e_[f't-{i}'] = sympy.symbols(f'e_t-{i}') e__.append( [e_[f't-{i}']*(J**i)] ) # e__ = [ [e_['t']], [e_['t-1']], ..., [e_['t-(q+Q*m)']] ] # define L L = sympy.symbols('L') S_Lag = L**m T_Lag = L S_Lag_Diff = (1-L**m)**D T_Lag_Diff = (1-L)**d # define coefficients : phis(T), Phis(S), thetas(T), Thetas(S) T_phi = {}; T_phis = []; L_byT_phi = [] S_phi = {}; S_phis = []; L_byS_phi = [] T_theta = {}; T_thetas = []; L_byT_theta = [] S_theta = {}; S_thetas = []; L_byS_theta = [] for p_ in range(0, p+1): T_phi[p_] = sympy.symbols(f'phi_{p_}') T_phis.append(-T_phi[p_]) # T_phis = [T_phi[0], T_phi[1], ..., T_phi[p]] L_byT_phi.append([T_Lag**p_]) # L_byT_phi = [[L**0], [L**1], ..., [L**p]] for P_ in range(0, P+1): S_phi[P_] = sympy.symbols(f'Phi_{P_}') S_phis.append(-S_phi[P_]) # S_phis = [S_phi[0], S_phi[1], ..., S_phi[P]] L_byS_phi.append([S_Lag**P_]) # L_byS_phi = [[(L**m)**0], [(L**m)**1], ..., [(L**m)**P]] for q_ in range(0, q+1): T_theta[q_] = sympy.symbols(f'theta_{q_}') T_thetas.append(T_theta[q_]) # T_thetas = [T_theta[0], T_theta[1], ..., T_theta[q]] L_byT_theta.append([T_Lag**q_]) # L_byT_theta = [[L**0], [L**1], ..., [L**q]] for Q_ in range(0, Q+1): S_theta[Q_] = sympy.symbols(f'Theta_{Q_}') S_thetas.append(S_theta[Q_]) # S_thetas = [T_theta[0], T_theta[1], ..., T_theta[Q]] L_byS_theta.append([S_Lag**Q_]) # L_byS_theta = [[(L**m)**0], [(L**m)**1], ..., [(L**m)**Q]] T_phi_Lag = sympy.Matrix([T_phis]) * sympy.Matrix(L_byT_phi) S_phi_Lag = sympy.Matrix([S_phis]) * sympy.Matrix(L_byS_phi) T_theta_Lag = sympy.Matrix([T_thetas]) * sympy.Matrix(L_byT_theta) S_theta_Lag = sympy.Matrix([S_thetas]) * sympy.Matrix(L_byS_theta) Y_operator = (T_phi_Lag * S_phi_Lag * T_Lag_Diff * S_Lag_Diff).subs(T_phi[0], -1).subs(S_phi[0], -1)[0] e_operator = (T_theta_Lag * S_theta_Lag).subs(T_theta[0], 1).subs(S_theta[0], 1)[0] Y_operation = sympy.collect(Y_operator.expand(), L) e_operation = sympy.collect(e_operator.expand(), L) Y_coeff = sympy.Poly(Y_operation, L).all_coeffs()[::-1] e_coeff = sympy.Poly(e_operation, L).all_coeffs()[::-1] Y_term = sympy.Matrix([Y_coeff]) * sympy.Matrix(Y__) # left-side e_term = sympy.Matrix([e_coeff]) * sympy.Matrix(e__) # right-side Time_Series = {} Time_Series['Y_t(i,j)'] = sympy.Poly(Y - Y_term[0] + e_term[0], (I,J)) Time_Series['Y_t'] = Time_Series['Y_t(i,j)'].subs(I, 1).subs(J, 1) for i in range(1, int(p+P*m+d+D*m)+1): Time_Series['Y_t'] = sympy.collect(Time_Series['Y_t'], Y_[f't-{i}']).simplify() for i in range(1, int(q+Q*m)+1): Time_Series['Y_t'] = sympy.collect(Time_Series['Y_t'], e_[f't-{i}']).simplify() print('* Time Series Equation(Analytic Form)') sympy.pprint(Time_Series['Y_t']); print() Time_Series['Analytic_Coeff_of_Y'] = Time_Series['Y_t(i,j)'].subs(J, 0).all_coeffs()[::-1] Time_Series['Analytic_Coeff_of_e'] = Time_Series['Y_t(i,j)'].subs(I, 0).all_coeffs()[::-1] Time_Series['Numeric_Coeff_of_Y'] = Time_Series['Y_t(i,j)'].subs(J, 0) - e_['t'] Time_Series['Numeric_Coeff_of_e'] = Time_Series['Y_t(i,j)'].subs(I, 0) for i, (phi, Np) in enumerate(zip(list(T_phi.values())[1:], trendAR)): Time_Series['Numeric_Coeff_of_Y'] = Time_Series['Numeric_Coeff_of_Y'].subs(phi, Np) for i, (Phi, NP) in enumerate(zip(list(S_phi.values())[1:], seasonAR)): Time_Series['Numeric_Coeff_of_Y'] = Time_Series['Numeric_Coeff_of_Y'].subs(Phi, NP) for i, (theta, Nt) in enumerate(zip(list(T_theta.values())[1:], trendMA)): Time_Series['Numeric_Coeff_of_e'] = Time_Series['Numeric_Coeff_of_e'].subs(theta, Nt) for i, (Theta, NT) in enumerate(zip(list(S_theta.values())[1:], seasonMA)): Time_Series['Numeric_Coeff_of_e'] = Time_Series['Numeric_Coeff_of_e'].subs(Theta, NT) print('* Time Series Equation(Numeric Form)') sympy.pprint((Time_Series['Numeric_Coeff_of_Y'] + Time_Series['Numeric_Coeff_of_e']).subs(I, 1).subs(J, 1)) Time_Series['Numeric_Coeff_of_Y'] = sympy.Poly(Time_Series['Numeric_Coeff_of_Y'], I).all_coeffs()[::-1] Time_Series['Numeric_Coeff_of_e'] = sympy.Poly(Time_Series['Numeric_Coeff_of_e'], J).all_coeffs()[::-1] final_coeffs = [[], []] print('\n* Y params') print(f'- TAR({trendparams[0]}) phi : {trendAR}') print(f'- TMA({trendparams[2]}) theta : {trendMA}') for i, (A_coeff_Y, N_coeff_Y) in enumerate(zip(Time_Series['Analytic_Coeff_of_Y'], Time_Series['Numeric_Coeff_of_Y'])): if i == 0: pass elif i != 0: A_coeff_Y = A_coeff_Y.subs(Y_[f"t-{i}"], 1) N_coeff_Y = N_coeff_Y.subs(Y_[f"t-{i}"], 1) print(f't-{i} : {A_coeff_Y} > {round(N_coeff_Y, 5)}') final_coeffs[0].append(N_coeff_Y) print('\n* e params') print(f'- SAR({seasonalparams[0]}) Phi : {seasonAR}') print(f'- SMA({seasonalparams[2]}) Theta : {seasonMA}') for i, (A_coeff_e, N_coeff_e) in enumerate(zip(Time_Series['Analytic_Coeff_of_e'], Time_Series['Numeric_Coeff_of_e'])): if i == 0: A_coeff_e = A_coeff_e.subs(e_[f"t"], 1) N_coeff_e = N_coeff_e.subs(e_[f"t"], 1) print(f't-{i} : {A_coeff_e} > {1}') elif i != 0: A_coeff_e = A_coeff_e.subs(e_[f"t-{i}"], 1) N_coeff_e = N_coeff_e.subs(e_[f"t-{i}"], 1) print(f't-{i} : {A_coeff_e} > {round(N_coeff_e, 5)}') final_coeffs[1].append(N_coeff_e) print('\n* Convergence Factor') try: print('Y :', sympy.tensorcontraction(sympy.Array(final_coeffs[0]).applyfunc(lambda x: x**2), (0,))) print('e :', sympy.tensorcontraction(sympy.Array(final_coeffs[1]).applyfunc(lambda x: x**2), (0,))) except: pass #Time_Series['Y_t'] """ Y_t = (~)*Y_t-1 + ... + 1*e_t + (~)*e_t-1 + ... final_coeffs[0] : coeff[Y_t-1, Y_t-2, ...] final_coeffs[1] : coeff[e_t-1, e_t-2, ...] """ return final_coeffs
# The equilibrium points F0 = 0 x30 = 0 x40 = 0 # Substitute symbols with equilibrium points phi_deriv_F_at_equlibrium = phi_deriv_F.subs([(F, F0), (x3, x30), (x4, x40)]) phi_deriv_x3_at_equlibrium = phi_deriv_x3.subs([(F, F0), (x3, x30), (x4, x40)]) phi_deriv_x4_at_equlibrium = phi_deriv_x4.subs([(F, F0), (x3, x30), (x4, x40)]) psi_deriv_F_at_equlibrium = psi_deriv_F.subs([(F, F0), (x3, x30), (x4, x40)]) psi_deriv_x3_at_equlibrium = psi_deriv_x3.subs([(F, F0), (x3, x30), (x4, x40)]) psi_deriv_x4_at_equlibrium = psi_deriv_x4.subs([(F, F0), (x3, x30), (x4, x40)]) # Print the partial derivatives sym.pprint(phi_deriv_F_at_equlibrium) sym.pprint(phi_deriv_x3_at_equlibrium) sym.pprint(phi_deriv_x4_at_equlibrium) sym.pprint(psi_deriv_F_at_equlibrium) sym.pprint(psi_deriv_x3_at_equlibrium) sym.pprint(psi_deriv_x4_at_equlibrium) # Print the equations for LaTex print(sym.latex(phi)) print(sym.latex(psi)) print(sym.latex(phi_deriv_F_at_equlibrium)) print(sym.latex(phi_deriv_x3_at_equlibrium)) print(sym.latex(phi_deriv_x4_at_equlibrium)) print(sym.latex(psi_deriv_F_at_equlibrium)) print(sym.latex(psi_deriv_x3_at_equlibrium)) print(sym.latex(psi_deriv_x4_at_equlibrium))
import sympy as sym from sympy import Symbol from sympy import pprint # %matplotlib inline --> *for pycharm, use plt.show* import matplotlib as mpl import sympy.plotting as syp sigma = Symbol('sigma') mu = Symbol('mu') x = Symbol('x') part1 = 1 / (sym.sqrt(2 * sym.pi * sigma**2)) part2 = sym.exp(-1 * ((x - mu)**2) / (2 * sigma**2)) my_gaussfunction = part1 * part2 pprint(my_gaussfunction) syp.plot(my_gaussfunction.subs({ mu: 10, sigma: 30 }), (x, -100, 100), title='gauss distribution') x_values = [] y_values = [] for value in range(-5, 5): y = my_gaussfunction.subs({mu: 10, sigma: 30, x: value}).evalf() y_values.append(y) x_values.append(value) print(value, y) import matplotlib.pyplot as plt
def eq4(): r = Symbol("r") e = Rmn.dd(3,3) e = e.subs(nu(r), -lam(r)) pprint(dsolve(e, lam(r))) pprint(dsolve(e, lam(r), 'best'))
import nife import sympy as sp sp.init_printing() triangle = nife.Polygon([sp.Point(0, 0), sp.Point(0, 1), sp.Point(1, 0)]) fn = nife.Function(sp.sympify("a*x + b*y + c"), sp.sympify("x, y")) # V rozich exprs = [fn.eval_point(p) for p in triangle.points] sp.pprint(nife.make_shape_functions(fn, exprs)) # Integral pres hranu exprs = [fn.line_itegrate(nife.segment_to_curve(e)) for e in triangle.edges] sp.pprint(nife.make_shape_functions(fn, exprs)) # RT phi = nife.Function(sp.Matrix(sp.sympify("a*x + b, a*y + c")), sp.sympify("x, y")) exprs = [sp.line_integrate(phi.expression.dot(nife.unit_normal(e)), nife.segment_to_curve(e), phi.vars) for e in triangle.edges] sp.pprint(nife.make_shape_functions(phi, exprs))
import sympy from sympy import Symbol from sympy import pprint import sympy as sym import sympy.plotting as syp import sympy as sy import matplotlib.pyplot as plt sigma = Symbol('sigma') mu = Symbol('mu') x = Symbol('x') part_1 = 1/(sym.sqrt(2*sym.pi*sigma*sigma)) part_2 = sym.exp(-1*((x-mu)**2)/(2*sigma**2)) my_gauss_function = part_1*part_2 print(pprint(my_gauss_function)) print(syp.plot(my_gauss_function.subs({mu:1,sigma:3}), (x, -10, 10), title='gauss')) x_values = [] y_values = [] for value in range(-50,50): y = my_gauss_function.subs({mu:0,sigma:10,x:value}).evalf() y_values.append(y) x_values.append(value) print(value,y) plt.plot(x_values,y_values)
import sympy as sym from sympy import Symbol from sympy import pprint p = Symbol('p') x = Symbol('x') n = Symbol('n') my_f_3_part_0 = sym.factorial(n) / sym.factorial(x) * sym.factorial(n - x) pprint(my_f_3_part_0) my_f_3_part_1 = p**x pprint(my_f_3_part_1) my_f_3_part_2 = (1 - p)**(n - x) pprint(my_f_3_part_2) my_f_3 = my_f_3_part_0 * my_f_3_part_1 * my_f_3_part_2 pprint(my_f_3) sym.plot(my_f_3.sub({ p: 0.5, n: 50 }), (x, 0, 50), title='binomin distribution for n= 50')