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 in_mm(n=16): # %pylab inline # command in ipython that imports sci modulues import sympy as sym sym.init_printing() for k in range(n+1): n = float(n) print(' %5s in - %.6f in - %.6f mm ' % (sym.Rational(k,n) , k/n, 25.4*k/n ) )
def hst(n=16): # %pylab inline # command in ipython that imports sci modulues import sympy as sym sym.init_printing() for k in range(n+1): n = float(n) print('HST63%02d = %s' % ( k, sym.Rational(k,n*2) ) )
def setup_pprint(): from sympy import pprint_use_unicode, init_printing # force pprint to be in ascii mode in doctests pprint_use_unicode(False) # hook our nice, hash-stable strprinter init_printing(pretty_print=False)
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_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(): if sympy.__version__ != "1.0": sys.exit("The doctests must be run against SymPy 1.0. Please install SymPy 1.0 and run them again.") full_text = "" for file in files: with open(file, 'r') as f: s = f.read() st = s.find(begin) while st != -1: if not (st >= len(skip)) or s[st - len(skip) : st] != skip: full_text += s[st + len(begin) : s.find(end, st)] st = s.find(begin, st+ len(begin)) full_text = full_text.replace(r'\end{verbatim}', '') with open(output_file, "w") as f: f.write("'''\n %s \n'''" % full_text) # force pprint to be in ascii mode in doctests pprint_use_unicode(False) # hook our nice, hash-stable strprinter init_printing(pretty_print=False) import test_full_paper # find the doctest module = pdoctest._normalize_module(test_full_paper) tests = SymPyDocTestFinder().find(module) test = tests[0] runner = SymPyDocTestRunner(optionflags=pdoctest.ELLIPSIS | pdoctest.NORMALIZE_WHITESPACE | pdoctest.IGNORE_EXCEPTION_DETAIL) runner._checker = SymPyOutputChecker() old = sys.stdout new = StringIO() sys.stdout = new future_flags = __future__.division.compiler_flag | __future__.print_function.compiler_flag try: f, t = runner.run(test, compileflags=future_flags, out=new.write, clear_globs=False) except KeyboardInterrupt: raise finally: sys.stdout = old if f > 0: print(new.getvalue()) return 1 else: return 0
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 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 new_MM(self): init_printing() m, n, k, self.tag = self.__choose_problem_type__() self.A = self.random_integer_matrix( m, k ) self.x = self.random_integer_matrix( k, n ) self.answer = self.A * self.x return Math( "$$" + latex( MatMul( self.A, self.x ), mat_str = "matrix" ) + "=" + "?" + "$$" )
def new_problem(self): init_printing() m = self.random_integer( 3, 4 ) n = self.random_integer( 2, 3 ) self.A = self.random_integer_matrix( m, n ) self.x = self.random_integer_matrix( n, 1 ) self.answer = self.A * self.x return Math( "$$" + latex( MatMul( self.A, self.x ), mat_str = "matrix" ) + "=" + "?" + "$$" )
def init_sympy_printing(self, line): from sympy import init_printing init_printing() ip = get_ipython() latex = ip.display_formatter.formatters["text/latex"] for key in latex.type_printers.keys(): if key.__module__ == "__builtin__": del latex.type_printers[key] png = ip.display_formatter.formatters["image/png"] for key in png.type_printers.keys(): if key.__module__ == "__builtin__": del png.type_printers[key]
def print_series(n, x_value): # 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) # evaluate the series at x_value series_value = series.subs({x:x_value}) print('Value of the series at {0}: {1}'.format(x_value, series_value))
def exer_mult_step(expression): import re import sympy as sym from sympy import init_printing; init_printing() from IPython.display import display, Math, Latex a, b, c, x, y, z = sym.symbols("a b c x y z") expression=str(expression) evexpr=sym.expand(eval(expression)) print 'Expand the following expression step by step:' display(Math(str(expression).replace('**','^').replace('*',''))) print 'Multiply ALL the monomials:' factor=re.split('\)\s*\*\s*\(',str(expression)) refactor=[ re.split('\(|\)',factor[i])[1-i] for i in range(len(factor))] terms=[ re.split(':',re.sub('\s*(\+|\-)\s*',r':\1',refactor[i])) for i in range(len(refactor)) ] expandednr='' for i in range(len(terms[0])): #nci='' if terms[0][i]: nci=terms[0][i] terms[0][i]=r'{\color{red}{%s}}' %terms[0][i] for j in range(len(terms[1])): #ncj='' if terms[1][j]: ncj=terms[1][j] terms[1][j]=r'\color{red}{%s}' %terms[1][j] l=jointerms(terms) display(Math(l.replace('**','^').replace('*',''))) terms[1][j]=ncj newterm=raw_input() if re.search('^-',newterm): newterm=newterm else: newterm='+'+newterm expandednr=expandednr+newterm expandednr=re.sub('^\+','',expandednr) terms[0][i]=nci print 'Reduce the expression:' display(Math(expandednr.replace('**','^').replace('*',''))) result=raw_input() if evexpr== eval(result): print "Good job!, final result:" return eval(result) else: print('WRONG!!!\nRight result:') return sym.expand(expression)
def ItosLemma(f, drift, diffusion, finv=None, replaceX=True, pretty_print=False): """ This function applies Ito's lemma given a twice-differentiable, invertible function (f) and drift and diffusion coefficients for a stochastic process (X_t) satisfying SDE dX = drift(X,t) dt + diffusion(X,t) dW This routine then prints out a new the SDE for Y=f(X) dY = drift_new(X,t) dt + diffusion_new(X,t) dW_t If replaceX=True, this will replace instances of X with f^{-1}(Y) NOTE: Inputs f, drift, diffusion _all_ expected to be sympy fcns. Derivatives are taken with respect to sympy symbols/variables X and t in those functions. """ # Define symbols for display later t, Y, dt, dW, dY, dX, Y_t = sp.symbols('t Y dt dW dY dX Y_t') # Define differentiation functions DX, Dt = map(lambda var: (lambda fcn: sp.diff(fcn, var)), [X, t]) # Compute drift_new and diffusion_new according to Ito's Lemma drift_new = Dt(f) + DX(f)*b + 0.5*DX(DX(f))*(s**2) diffusion_new = DX(f)*s # If finv not given, invert Y=f(X) to get Y = f^{-1}(X) if finv == None: finv = invertInteractive(f, X, Y) # Substitute out X with f^{-1}(Y) if replaceX: drift_new, diffusion_new = map(lambda fcn: fcn.subs(X,finv).simplify(), [drift_new, diffusion_new]) # Print the results to screen if pretty_print: sp.init_printing() print "\nOriginal SDE\n------------\n" sp.pprint(sp.Eq(dX, (drift)*dt + (diffusion)*dW)) print "\n\nNew SDE for Y = f(X)\n--------------------\n" sp.pprint(sp.Eq(dY,(drift_new)*dt + (diffusion_new)*dW)) print "\nwhere" sp.pprint(sp.Eq(Y,f)) print("\n\n")
def exer_mult(expression): import sympy as sym from sympy import init_printing; init_printing() from IPython.display import display, Math, Latex a, b, c, x, y, z = sym.symbols("a b c x y z") expression=str(expression) evexpr=sym.expand(eval(expression)) print 'Expand the expression:' display(Math(str(expression).replace('**','^').replace('*',''))) result=raw_input() if evexpr== eval(result): print "Good job! Final result:" return eval(result) else: print('WRONG!!!\nRight result:') return sym.expand(eval(expression))
def init_from_matmodlab_magic(p): if p == BOKEH: from bokeh.plotting import output_notebook output_notebook() environ.plotter = BOKEH i = 2 elif p == MATPLOTLIB: environ.plotter = MATPLOTLIB i = 1 environ.notebook = i environ.verbosity = 0 try: from sympy import init_printing init_printing() except ImportError: pass
def Format(Fmode=True, Dmode=True, dop=1, inverse='full'): """ Set modes for latex printer - Fmode: Suppress function arguments (True) Use sympy latex for functions (False) Dmode: Use compact form of derivatives (True) Use sympy latex for derivatives (False) and redirects printer output so that latex compiler can capture it. """ global Format_cnt GaLatexPrinter.Dmode = Dmode GaLatexPrinter.Fmode = Fmode GaLatexPrinter.inv_trig_style = inverse if Format_cnt == 0: Format_cnt += 1 """ if metric.in_ipynb(): GaLatexPrinter.ipy = True else: GaLatexPrinter.ipy = False GaLatexPrinter.dop = dop GaLatexPrinter.latex_flg = True if not GaLatexPrinter.ipy: GaLatexPrinter.redirect() """ GaLatexPrinter.dop = dop GaLatexPrinter.latex_flg = True GaLatexPrinter.redirect() Basic.__str__ = lambda self: GaLatexPrinter().doprint(self) Matrix.__str__ = lambda self: GaLatexPrinter().doprint(self) Basic.__repr_ = lambda self: GaLatexPrinter().doprint(self) Matrix.__repr__ = lambda self: GaLatexPrinter().doprint(self) if isinteractive(): init_printing(use_latex= 'mathjax') return
def exer_mult_step_old(expression): import re import sympy as sym from sympy import init_printing; init_printing() from IPython.display import display, Math, Latex a, b, c, x, y, z = sym.symbols("a b c x y z") expression=str(expression) evexpr=sym.expand(eval(expression)) print 'Expand the following expression step by step:' display(Math(str(expression).replace('**','^').replace('*',''))) print 'Multiply ALL the monomials:' factor=re.split('\)\s*\*\s*\(',str(expression)) refactor=[ re.split('\(|\)',factor[i])[1-i] for i in range(len(factor))] terms=[ re.split(':',re.sub('\s*(\+|\-)\s*',r':\1',refactor[i])) for i in range(len(refactor)) ] expandednr='' for i in terms[0]: for j in terms[1]: if i and j: #mo empty strings print '(%s)*(%s)' %(i,j) newterm=raw_input() if re.search('^-',newterm): newterm=newterm else: newterm='+'+newterm expandednr=expandednr+newterm expandednr=re.sub('^\+','',expandednr) print 'Reduce the expression:' display(Math(expandednr.replace('**','^').replace('*',''))) result=raw_input() if evexpr== eval(result): print "Good job!, final result:" return eval(result) else: print('WRONG!!!\nRight result:') return sym.expand(expression)
def __init__(self, coordinates, metric): sp.init_printing() if len(coordinates)==metric.rows and len(coordinates)==metric.cols: self.gdd = metric #stands for down-down components of the metric g self.x = coordinates self.dim = len(self.x) self.index = range(self.dim) self.guu = metric.inv() self.connection = [[[0 for i in self.index] for i in self.index] for i in self.index] for i in self.index: for j in self.index: for k in self.index: for m in self.index: self.connection[i][j][k] += self.guu[i,m]*(self.gdd[m,j].diff(self.x[k]) + self.gdd[m,k].diff(self.x[j]) - self.gdd[k,j].diff(self.x[m]))/2 self.Riemanntensor = [[[[0for i in self.index]for i in self.index]for i in self.index]for i in self.index] for i in self.index: for j in self.index: for k in self.index: for m in self.index: self.Riemanntensor[i][j][k][m] += self.connection[i][j][k].diff(self.x[m]) - self.connection[i][j][m].diff(self.x[k]) for n in self.index: self.Riemanntensor[i][j][k][m] += self.connection[n][j][k]*self.connection[i][m][n] - self.connection[n][j][m]*self.connection[i][k][n] self.Riccitensor = [[0 for i in self.index]for i in self.index] for i in self.index: for j in self.index: for k in self.index: self.Riccitensor[i][j] += self.Riemanntensor[k][i][k][j] self.Riemannscalar = 0 for i in self.index: for j in self.index: self.Riemannscalar += self.guu[i,j]*self.Riccitensor[i][j] else: print "Creation failed. Please use an n-tuple of coordinate names with a square, n times n matrix"
import numpy as np import sympy from sympy import Matrix, Symbol, symbols from sympy.printing import lambdarepr from sympy import init_printing from sympy import lambdify from sympy import cos, sin, expand_trig from sympy import trigsimp from sympy import simplify from yams.yams_sympy import colvec, R_x, R_y, R_z, cross from yams.yams_sympy import GroundBody from yams.yams_sympy import BeamBody from yams.yams_sympy import RigidBody init_printing(use_unicode=False, wrap_line=False, no_global=True) #init_printing(wrap_line=False) # init_printing(use_latex='mathjax') display = lambda x: sympy.pprint(x, use_unicode=False, wrap_line=False) disp = lambda x: print(lambdarepr.lambdarepr(x)) sep = lambda: print('--------') # --- L = symbols('L') theta_yaw, theta_tilt = symbols('theta_yaw,theta_tilt') alpha_x, alpha_y, alpha_z = symbols('alpha_x,alpha_y,alpha_z') ux1c, ux2c, ux3c, ux4c = symbols('ux1c,ux2c,ux3c,ux4c') uy1c, uy2c, uy3c, uy4c = symbols('uy1c,uy2c,uy3c,uy4c') uz1c, uz2c, uz3c, uz4c = symbols('uz1c,uz2c,uz3c,uz4c') vx1c, vx2c, vx3c, vx4c = symbols('vx1c,vx2c,vx3c,vx4c') vy1c, vy2c, vy3c, vy4c = symbols('vy1c,vy2c,vy3c,vy4c')
import sympy as sym import numpy as np sym.init_printing() x, y = sym.symbols("x, y") A = sym.Matrix([[3, 0], [5, 1]]) B = A.transpose() sigma_r = sym.Matrix([[x, 1 - x]]) sigma_c = sym.Matrix([y, 1 - y]) # A * sigma_c, sigma_r * B import matplotlib import matplotlib.pyplot as plt graph1 = plt.figure() y_domain = [0, 1] row_payoff = [[(A * sigma_c)[i].subs({y: value}) for value in y_domain] for i in range(2)] plt.plot(y_domain, row_payoff[0], label="$(A\sigma_c^T)_1$") plt.plot(y_domain, row_payoff[1], label="$(A\sigma_c^T)_2$") plt.xlabel("$\sigma_c=(y, 1-y)$") plt.title( "Row player payoffs, when the col. player's strategy is $\sigma_c=(y, 1-y)$" ) plt.legend() graph1.savefig("..\..\images\PD-row-payoff.pdf") graph2 = plt.figure()
# 1. [Properties of Invertible Matrices](#Properties_of_invertible_Matrices) # 1. [The Basis of a Vector Space](#The_Basis_of_a_Vector_Space) # 1. [Change of Basis](#Change_of_Basis) # 1. [Orthogonal and Orthonormal](#Orthogonal_and_Orthonormal) # 1. [Gram-Schmidt](#Gram-Schmidt) # 1. [Inner Products](#Inner_Products) # 1. [Inner Product on Functions](#Inner_Product_on_Functions) # 1. [Assignment Wrap-up](#Assignment_Wrap-up) # In[1]: get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pylab as plt import numpy as np import sympy as sym sym.init_printing(use_unicode=True) # ---- # <a name="Properties_of_invertible_Matrices"></a> # # # 1. Review the Properties of Invertible Matrices # Let $A$ be an $n \times n$ matrix. The following statements are equivalent. # # - The column vectors of $A$ form a basis for $R^n$ # - $|A| \ne 0$ # - $A$ is invertible. # - $A$ is row equivalent to $I_n$ (i.e. it's reduced row echelon form is $I_n$) # - The system of equations $Ax = b$ has a unique solution. # - $rank(A) = n$ #
import sympy as sm sm.init_printing() table = sm.Matrix([[1, 0, -3, 0, 0, 0], [6, 0, 0, 0, 0, -1], [0, 1, 0, -2, 0, 0], [0, 2, 0, 0, -1, 0], [0, 8, -4, -3, -2, -1]]) sm.pprint(table) m = table sm.pprint(m) b = sm.zeros(5).col(0) sm.pprint(b) sm.pprint(m.rref()) from sympy.solvers.solveset import linsolve result = linsolve((m, b)) sm.pprint(result)
5. Code to create supplementaryS4.R, an R implementation of the model (797 - 873) """ from sympy import * import numpy as np import matplotlib.pyplot as pl from datetime import datetime import os as os # Set working directory os.chdir('supplementary-material') # Use LaTeX printing from sympy import init_printing ; init_printing() # Make LaTeX output white. Because I use a dark theme init_printing(forecolor="White") # Load symbols used for symbolic maths t, a, r, x2, x3, x4, x1 = symbols('theta alpha r x_2 x_3 x_4 x_1', positive=True) r1 = {r:1} # useful for lots of checks # Define functions # Calculate the final profile averaged over pi. def calcModel(model): x = pi**-1 * sum( [integrate(m[0], m[1:]) for m in model] ).simplify().trigsimp() return x
import itertools from collections import * from math import * from numpy import array, cos, sin import functools import scipy import sympy from IPython.display import Image from scipy.integrate import quad from sympy import * import numpy as np import scipy as sp import time %aimport models %aimport tools from sympy import init_printing;init_printing() from models import * # <codecell> %aimport models # <codecell> tools.DO_PLOT=True # <codecell> profiles_definiton = load_profiles_lookup_table({}) # <codecell>
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Nov 17 09:42:30 2018 @author: xsxsz """ import sympy as sy sy.init_printing(use_unicode=True, use_latex=True) x, y = sy.symbols('x y') expr = x + y**2 latex = sy.latex(expr) print(latex) print('----------') print(sy.solve(x + 1, x)) print('----------') print(sy.limit(sy.sin(x) / x, x, 0)) print('----------') print(sy.limit(sy.sin(x) / x, x, sy.oo)) print('----------') print(sy.limit(sy.ln(x + 1) / x, x, 0)) print('----------') print(sy.integrate(sy.sin(x), (x, -sy.oo, sy.oo))) print('----------') print(sy.integrate(1 / x, (x, 1, 2))) print('----------') print(sy.Rational(1, 2)) print('----------')
import numpy as np from sympy.utilities.lambdify import lambdify from EZ.data import figure_layout import lmfit import schemdraw as schem import sympy as sym from sympy.parsing.sympy_parser import parse_expr from sympy.printing.mathml import print_mathml from sympy.printing.latex import latex sym.init_printing(use_latex='mathjax') sym_omega = sym.Symbol(r"omega", real=True) schem_unit = 1 style = dict(unit=schem_unit, inches_per_unit=0.3, lw=1, fontsize=10) class Model: def eval_Z(self, pars, omega): self.build_symbols() values = dict() for name in self.symbols: if name != "omega": if isinstance(pars[name], dict): value = pars[name]["value"] else: value = pars[name].value values.update({self.symbols[name]: value}) Z = lambdify(sym_omega, self.Z.subs(values), "numpy")(omega)
#!/usr/bin/env python # coding: utf-8 #---- ch07/import-sympy import sympy as sp sp.init_printing() #---- ch07/define-alph-symbol from sympy.abc import x, y, a, b, c, f #---- ch07/use-alph-symbol x**2 * y / x #---- ch07/solve-quadratic sp.solve(a * x**2 + b * x + c, x) #---- ch07/sympy-diff1 f = x**a * y**b f.diff(x) #---- ch07/sympy-diff2 f.diff(x).simplify() #---- ch07/two-period-symbols c, c_1, c_2, y1, y2 = sp.symbols("c, c_1, c_2, y_1, y_2") r, rho, theta, s0 = sp.symbols("r rho theta s_0") #---- ch07/utility c, theta = sp.symbols("c theta") u = (c**(1 - theta) - 1) / (1 - theta) u
""" import numpy as np from sympy import init_printing import astropy.units as u from tqdm import tqdm from matplotlib import rc from scipy.integrate import trapz from data_filter import get_sources from antiobjects.pion_decay import spectrum from astropy.coordinates import SkyCoord, Distance from astroquery.gaia import Gaia # activate latex text rendering rc('font', **{'family': 'serif', 'serif': ['Computer Modern Roman']}) rc('text', usetex=True) init_printing(use_latex=True, forecolor="White") final_sources, excluded_sources = get_sources(TS_max=9) #%% Constantes def calc_dist(source, mass=1 * u.M_sun): velocity = 100 * (u.km / u.s) gamma_luminosity = 0.5 * (1 / 3) * 1e36 * (mass / u.M_sun)**2 * ( velocity / (10 * u.km / u.s))**(-3) / (u.s) E_span = np.linspace(100, 1000, 10000) I_spectrum = spectrum(E_span) ref_flux = trapz(I_spectrum * E_span, E_span) K_flux = source['Energy_Flux100'] * 624151 / ref_flux * (u.cm**(-2) *
def show_answer(self): init_printing() return Math( "$$" + latex( MatMul( self.A, self.x ), mat_str = "matrix" ) + "=" + latex( self.answer, mat_str = "matrix" ) + "$$")
#import sympy from sympy import sympify from sympy import init_printing from sympy import * from enum import Enum from RandomHandler import RandomHandler init_printing() x, y, z = symbols('x y z') class assignment: #assignment-list: 0 - id, 1 - topic, 2 - description, 3 - pystring, 4 - assignmenttype def __init__(self, assign_input): self.sympy_question = '' #sympify(assign_input[3], evaluate = False) self.latex_question = '' self.question_handling(assign_input) self.sympy_solution = self.to_sympy_solution(self.sympy_question, assign_input) self.latex_solution = self.to_latex_solution(assign_input) #with ':' def question_handling(self, assign_input): #sympy handling rh = RandomHandler() parsed_string = rh.parse(assign_input[3]) sympyq_string = parsed_string.replace(':', '/') sympyq_string = sympify(sympyq_string, evaluate=False) #print('sympy string ', sympyq_string)
import sympy as sy sy.init_printing() x, y = sy.var('x y') ## declaração de função f = sy.Lambda(x, (x**3 - 3 * x + 2) * sy.exp(x / 4) - 1) ## limite da função com f(x), com o x tendendo a 1 ponto = 1 limit = sy.limit(f(x), x, ponto) ## print limit sy.print_rcode(limit) ## limites laterais z = sy.var('z') g = sy.Lambda(z, (abs(z)) / z) limiteDireita = sy.limit(g(z), z, 0, '+') esquerda = sy.limit(g(z), z, 0, '-') sy.print_rcode(limiteDireita) sy.print_rcode(esquerda) ## limites ao infinito ## limit(f(x), x, oo)
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' 一个简单的马尔科夫决策过程求解 ''' import sympy from sympy import symbols sympy.init_printing() v_hungry, v_full = symbols('v_hurgry v_full') q_hungry_eat, q_hungry_none, q_full_eat, q_full_none = symbols( 'q_hungry_eat q_hungry_none q_full_eat q_full_none') alpha, beta, x, y, gama = symbols('alpha beta x y gama') system = sympy.Matrix( ((1, 0, x - 1, -x, 0, 0, 0), (0, 1, 0, 0, -y, y - 1, 0), (-gama, 0, 1, 0, 0, 0, 2), ((alpha - 1) * gama, -alpha * gama, 0, 1, 0, 0, -4 * alpha + 3), (-beta * gama, (beta - 1) * gama, 0, 0, 1, 0, 4 * beta - 2), (0, -gama, 0, 0, 0, 1, -1))) # 求解的结果为字典格式 result = sympy.solve_linear_system(system, v_hungry, v_full, q_hungry_eat, q_hungry_none, q_full_eat, q_full_none) for k, v in result.items(): print(k)
from __future__ import print_function import numpy as np import matplotlib.dates as mdates import matplotlib.pyplot as plt from scipy.stats import norm from sympy import Symbol, symbols, Matrix, sin, cos, sqrt, atan2 from sympy import init_printing init_printing(use_latex=True) import numdifftools as nd import math dataset = [] # read the measurement data, use 0.0 to stand LIDAR data # and 1.0 stand RADAR data with open('data_synthetic.txt', 'rb') as f: lines = f.readlines() for line in lines: line = line.strip('\n') line = line.strip() numbers = line.split() result = [] for i, item in enumerate(numbers): item.strip() if i == 0: if item == 'L': result.append(0.0) else: result.append(1.0) else:
def pprint(obj): init_printing() print(pretty(obj)) return
# %% import sympy import numpy as np np.set_printoptions(precision=3, suppress=True) sympy.init_printing(num_columns=240, use_unicode=False) # %% # Setting up symbols K, v_in, v_out, R1, R2 = sympy.symbols(['K', 'v_in', 'v_out', 'R1', 'R2']) s, t = sympy.symbols(['s', 't']) # Equation # v_out = K * (v_pos - v_neg) expr = sympy.Eq(-R2 / R1 * v_in, v_out) print("expr=\n{}".format(sympy.pretty(expr))) print() # Substitute numerical values expr = expr.subs([(K, 10e3), (R1, 1e3), (R2, 1e3)]) print("v_out=\n{}".format(sympy.pretty(expr))) print()
# -*- coding: utf-8 -*- """ Verificación de las deducciones del artículo: 'Exact theory for a linearly elastic interior beam' de Karttunen & Von Hertzen' Por: Alejandro Hincapié Giraldo """ import sympy as sp import numpy as np from numpy import sqrt x, y, z, t, h, q, I, c1, c2, c3, A, N, M, Q, L = sp.symbols('x y z t h q I c1 ' 'c2 c3 A N M Q L') sp.init_printing() def my_print(var, nombre): print('\n', 80 * '~') if nombre != '': print(f'{nombre} =\n') else: print() sp.pprint(var) # %% Función de tensión de Airy psi = (c1 * y**2 + c2 * y**3 + c3 * x * y * (1 - 4 * y**2 / (3 * h**2)) - q / (240 * I) * (5 * h**3 * x**2 + 15 * h**2 * x**2 * y + 4 * y**3 *
########### Better Flux model ############### import numpy as np import matplotlib.pyplot as plt from matplotlib import animation import sympy import math import traffic_funcs as traffic sympy.init_printing(use_latex=False) ## Conditions on the traffic model ''' As rho -> rho_max, Flux -> 0 When rho = rho', F = F_max, F'(rho') = 0 ''' umax = 2.0 ustar = 1.5 rhomax = 15 rho_light = 5.5 nt = 30 nx = 81 L = 4.0 dx = L/(nx-1) x = np.linspace(0,L,nx) u_max, u_star, rho_max, rho_star, A, B, rhohigh = sympy.symbols('u_max u_star rho_max rho_star A B rhohigh')
import numpy as np import matplotlib.pyplot as plt import sympy as sy from sklearn import linear_model, datasets sy.init_printing() iris = datasets.load_iris() X = iris.data[:, :2] Y = iris.target logreg = linear_model.LogisticRegression() logreg.fit(X, Y) print logreg plt.scatter(X[:, 0], X[:, 1], c=Y) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.show()
# -*- coding: utf-8 -*- """ Created on Tue Feb 16 12:21:35 2016 @author: José Arcos Aneas Ejercicios de vectores con python """ import matplotlib.pyplot as plt import numpy as np import sympy # imprimir con notación matemática. sympy.init_printing(use_latex="mathjax") # graficando vector en R^2 [2, 4] def dibujar_figura(): """Crea la figura de pyplot y los ejes.""" fix, ax = plt.subplots() for spine in ["left", "bottom"]: ax.spines[spine].set_position("zero") return ax def vector_plano(vector, color): """Genera el grafico de los vectores en el plano""" v = vector ax.annotate(" ", xy=v, xytext=[0, 0], color=color, arrowprops=dict(facecolor=color, shrink=0, alpha=0.7, width=0.5)) ax.text(1.1 * v[0], 1.1 * v[1], v)
###Precisão Decimal prec = 2 ## Numero de digitos decimais de precisão mostrados no log de dados ###Configurações do pprint, registradas somente uma vez setattr(pprint,'num_columns',5) setattr(pprint,'use_unicode',True) setattr(pprint,'order','none') #("num_columns = 100,use_unicode = True,order = 'none'") ###Uses the best printing available for pprint init_printing( use_latex=True) def drange(start,stop,step): ## Funcão para criar um vetor de valores decimais, #nativo do python só aceita valores inteirosdef seq(start, stop, step=1): n = int(round((stop - start)/float(step))) if n > 1: return([start + step*i for i in range(n+1)]) else: return([])
# %% cell from IPython.display import display import numpy as np from matplotlib import pyplot as plt import sympy as syp from sympy import init_printing, symbols, sqrt, \ exp, Inverse as inv, pi, log, re, Eq, diff, function from sympy.matrices import Matrix, ones, zeros, eye init_printing(use_unicode=True) # %% C = symbols("C", real="True") sigma_s, sigma_x, sigma_nu = \ symbols(r"\sigma_s \sigma_x \sigma_{\nu}", real=True) s = Matrix(2, 1, symbols('s_p s_s'), real=True) mux = Matrix(2, 1, symbols(r'\mu_{x_i} \mu_{x_e}'), real=True) dmux = Matrix(2, 1, symbols(r'd\mu_{x_i} d\mu_{x_e}'), real=True) munu = Matrix(2, 1, symbols(r'\mu_{\nu_i} \mu_{\nu_e}'), real=True) dmunu = Matrix(2, 1, symbols(r'd\mu_{\nu_i} d\mu_{\nu_e}'), real=True) Sigma_s = eye(2, real=True) * sigma_s Sigma_x = eye(2, real=True) * sigma_x Sigma_nu = eye(2, real=True) * sigma_nu def g(x): W = eye(2, real=True)
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # 2018-04-10T18:05+08:00 import sympy from sympy.abc import x, y import sympy.plotting sympy.init_printing(use_unicode=True) lhs = y * sympy.sin(3*x) rhs = x * sympy.cos(3*y) sympy.plotting.plot_implicit(lhs - rhs, title='ysin3x=xcos3y')
from sympy import init_printing, symbols, pretty, solve, pi, Integral, LC, \ factor, sqrt, pretty_print, exp, simplify, ln, exp, log, sin, cos from numbers import Number from fractions import Fraction ##################################################################### init_printing(use_unicode='true') ##################################################################### ##################################################################### # Area of Square ##################################################################### def _square_(side=Number) -> object: """Area = a^2 :param side: The length of the side """ print('\n') print('Side: {0}'.format(side)) area = (side ** 2) print('Area of Square: {0}'.format(area)) print('\n') return area ##################################################################### # Area of Triangle ##################################################################### def _triangle_(base, height) -> object: """Area = ½ * b * h :param base: The length of the base of the triangle
# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import sympy as sp # enable latex printing in ipython qtconsole qt = 1 if qt: from sympy import init_printing from IPython.display import display init_printing() string_line = "#"*85 + "\n\n" string_line2 = "-"*85 + "\n\n" def print_matrix(name, i, supplement, matrix): if not matrix==None: print name + str(i) + supplement + " [" + str(matrix.shape[0]) + " x " + str(matrix.shape[1]) + "] = " print_nicely(matrix) def print_nicely(formula): if qt: display(formula) else: sp.pprint(formula) print("\n")
def _repr_latex_(self): init_printing(use_latex='mathjax') return latex(Matrix(self._inc), mode='inline')
from matplotlib import animation from clawpack.visclaw.JSAnimation import IPython_display from IPython.display import display import ipywidgets import sympy import numpy as np import matplotlib.pyplot as plt import matplotlib sympy.init_printing(use_latex='mathjax') def riemann_solution(solver,q_l,q_r,aux_l=None,aux_r=None,t=0.2,problem_data=None,verbose=False): r""" Compute the (approximate) solution of the Riemann problem with states (q_l, q_r) based on the (approximate) Riemann solver `solver`. The solver should be a pointwise solver provided as a Python function. **Example**:: # Call solver >>> from clawpack import riemann >>> gamma = 1.4 >>> problem_data = { 'gamma' : gamma, 'gamma1' : gamma - 1 } >>> solver = riemann.euler_1D_py.euler_hll_1D >>> q_l = (3., -0.5, 2.); q_r = (1., 0., 1.) >>> states, speeds, reval = riemann_solution(solver, q_l, q_r, problem_data=problem_data) # Check output >>> q_m = np.array([1.686068, 0.053321, 1.202282])
def main(): sympy.init_printing() t = sympy.symbols('t') # x = sympy.Function('x')(t) defined by ω and ρ y = sympy.Function('y')(t) θ = sympy.Function('θ')(t) ρ = sympy.Function('ρ')(t) φ = sympy.Function('φ')(t) # Masses m_ow, m_ow_rot, m_iw, m_iw_rot, m_m = sympy.symbols( 'm_ow m_owr m_iw m_iwr m_m') # Dimensions l_iw_m, r_1, r_2, r_3 = sympy.symbols('l_iwm r_1 r_2 r_3') l_ow_iw = r_2 - r_1 # Constants g = sympy.symbols('g') # Gear ratio i_gear = r_2 / r_1 # Linking rotation of outer and inner wheel φ_iw = φ φ_ow = (1 / i_gear) * φ_iw ω = φ.diff(t) ω_iw = ω ω_ow = φ_ow.diff(t) # Y positions y_ow = r_3 + y y_iw = y_ow - l_ow_iw * sympy.cos(ρ) y_m = y_iw + l_iw_m * sympy.cos(θ) # Rotation based x movement # TODO: Check to be correct x = r_3 * (φ_ow - ρ) # X positions x_ow = x x_iw = x_ow + l_ow_iw * sympy.sin(ρ) x_m = x_iw + l_iw_m * sympy.sin(θ) #################### # Potential Energy # #################### # Potential Energy V = (m_m * y_m + m_ow * y_ow + m_iw * y_iw) * g ################## # KINETIC ENERGY # ################## # Rotating mass inertia J_ow = (1 / 2) * m_ow_rot * (r_2**2 + r_3**2) J_iw = (1 / 2) * m_iw_rot * r_1**2 # Kinetic energy of rotating cylinder W_owr = (1 / 2) * J_ow * ω_ow**2 W_iwr = (1 / 2) * J_iw * ω_iw**2 # Translational kinetic energy W_ow = (1 / 2) * m_ow * (sympy.diff(x_ow, t)**2 + sympy.diff(y_ow, t)**2) W_iw = (1 / 2) * m_iw * (sympy.diff(x_iw, t)**2 + sympy.diff(y_iw, t)**2) W_m = (1 / 2) * m_m * (sympy.diff(x_m, t)**2 + sympy.diff(y_m, t)**2) # Dampening (e.g. heat dissipation) d_ow, d_iw, d_m, d_owr, d_iwr = sympy.symbols('d_ow d_iw d_m d_owr d_iwr') W_d_ow = sympy.integrate( d_ow * (1 / 2) * (sympy.diff(x_ow, t)**2 + sympy.diff(y_ow, t)**2), t) W_d_iw = sympy.integrate(d_iw * (1 / 2) * sympy.diff(ρ, t)**2, t) W_d_m = sympy.integrate((d_m * (1 / 2) * sympy.diff(θ, t)**2), t) W_d_owr = sympy.integrate(d_owr * (1 / 2) * ω_ow**2, t) W_d_iwr = sympy.integrate(d_iwr * (1 / 2) * ω_iw**2, t) W_heat = W_d_ow + W_d_iw + W_d_m # + W_d_owr + W_d_iwr # W_heat = 0 # Kinetic Energy T = W_ow + W_iw + W_m # + W_owr + W_iwr # + W_heat # TODO: Centrifugal forces seem missing ############### # State Space # ############### states = [θ, θ.diff(t), ρ, ρ.diff(t), φ, φ.diff(t)] ############ # Lagrange # ############ L = T - V f_y = y.diff(t) L_y = sympy.diff(sympy.diff(L, sympy.diff(y, t)), t) - sympy.diff(L, y) f_dy = sympy.solve(L_y, y.diff(t, t))[0] f_θ = θ.diff(t) L_θ = sympy.diff(sympy.diff(L, sympy.diff(θ, t)), t) - sympy.diff(L, θ) f_dθ = sympy.solve(L_θ, θ.diff(t, t))[0] f_ρ = ρ.diff(t) L_ρ = sympy.diff(sympy.diff(L, sympy.diff(ρ, t)), t) - sympy.diff(L, ρ) f_dρ = sympy.solve(L_ρ, ρ.diff(t, t))[0] f_φ = φ.diff(t) L_φ = sympy.diff(sympy.diff(L, sympy.diff(φ, t)), t) - sympy.diff(L, φ) f_dφ = sympy.solve(L_φ, φ.diff(t, t))[0] eqs = [f_θ, f_dθ, f_ρ, f_dρ, f_φ, f_dφ] def createMatrix(eqs: list, states: list) -> sympy.Matrix: if (len(eqs) != len(states)): print("eqs and states must have the same size") A = sympy.zeros(len(eqs), len(eqs)) for i, eq in enumerate(eqs, start=0): for j, state in enumerate(states, start=0): A[i, j] = sympy.diff(eq, state) return A # Create A Matrix A = createMatrix(eqs, states) def lineariceA(A_in, x_lineraice, x_delta): # Linearice linearice = [(sympy.sin(θ), sin(x_lineraice[0])), (sympy.cos(θ), cos(x_lineraice[0])), (sympy.sin(ρ), sin(x_lineraice[2])), (sympy.cos(ρ), cos(x_lineraice[2])), (θ.diff(t, t), x_delta[1]), (θ.diff(t)**2, x_lineraice[1]**2), (θ.diff(t), x_lineraice[1]), (θ, x_lineraice[0]), (ρ.diff(t, t), x_delta[3]), (ρ.diff(t)**2, x_lineraice[3]**2), (ρ.diff(t), x_lineraice[3]), (ρ, x_lineraice[2]), (φ.diff(t, t), x_delta[5]), (φ.diff(t), x_lineraice[5]), (φ, x_lineraice[4]), (y.diff(t, t), 0), (y.diff(t), 0), (y, 0)] return sympy.simplify(A_in.subs(linearice)) A_lin_up = lineariceA(A, [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]) A_lin_down = lineariceA(A, [math.pi, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]) masses = { g: 9.81, m_ow: 1.0, m_ow_rot: 0.5, m_iw: 0.3, m_iw_rot: 0.1, m_m: 15.0 } lengths = {l_iw_m: 2.0, r_1: 0.25, r_2: 1.0, r_3: 1.2} dampening = {d_ow: 1.0, d_iw: 1.0, d_m: 1.0, d_owr: 1.0, d_iwr: 1.0} def applyConstants(A_): return A_.subs(masses).subs(lengths).subs(dampening) # states = [θ, θ.diff(t), ρ, ρ.diff(t), φ, φ.diff(t)] jacobian_up = np.float64(applyConstants(A_lin_up)) jacobian_down = np.float64(applyConstants(A_lin_down)) A_j_up = jacobian_up A_j_down = jacobian_down # TODO: Create proper movement matrix (see page 302) B = np.float64(sympy.Matrix([0, -1, 0, 0, 0, 1])) C = control.ctrb(A_j_up, B) rank = linalg.matrix_rank(C) print("Rank is " + str(rank)) O = control.obsv(A_j_up, C) Q = np.float64(np.diag([1, 1, 1, 1, 1, 1])) R = np.float64(sympy.Matrix([1])) A_j_up.shape B.shape Q.shape R.shape # K, S, E = control.matlab.lqr(A_j, B, Q, R) # print(K) K_save = np.float64([[ -1.35133831e+04, -5.98789910e+03, 8.32433588e-01, 8.19822691e-03, -2.23606797e+00, -8.34913488e-01 ]]) K = K_save print(K) K.shape # Visualization # Initial State x_0 = np.float64([0.1, 0.0, 0.2, 0.0, 0.0, 0.0]) # Target State w_r = np.float64([math.pi, 0.0, 0.0, 0.0, 0.0, 0.0]) dt = 0.01 timeline = np.arange(0., 5., dt) def update_last_y(store_y): last_y = store_y last_y = x_0 update_last_y(x_0) A_constant = applyConstants(A) def applyJ(y, t): # A_local = np.float64(lineariceA(A_constant, y, y - last_y)) A_local = np.float64(lineariceA(A_constant, y, [0, 0, 0, 0, 0, 0])) # if (y[0] > - math.pi / 4 and y[0] < math.pi / 4): # A_local = A_j_up # else: # A_local = A_j_down # A_local = A_j_up # update_last_y(y) return A_j_up.dot(y) - (K * B).dot(y) # return A_local.dot(y) solution = integrate.odeint(applyJ, x_0, timeline) # x_ow, y_ow, x_iw, y_iw, x_m, y_m positions = sympy.zeros(6, len(timeline)) energy = sympy.zeros(3, len(timeline)) for tp in tqdm.tqdm(range(len(timeline))): results = {(θ.diff(t, t), 0), (θ.diff(t), solution[tp, 1]), (θ, solution[tp, 0]), (ρ.diff(t, t), 0), (ρ.diff(t), solution[tp, 3]), (ρ, solution[tp, 2]), (φ.diff(t, t), 0), (φ.diff(t), solution[tp, 5]), (φ, solution[tp, 4]), (y.diff(t, t), 0), (y.diff(t), 0), (y, 0)} positions[0, tp] = x_ow.subs(lengths).subs(results) positions[1, tp] = y_ow.subs(lengths).subs(results) positions[2, tp] = x_iw.subs(lengths).subs(results) positions[3, tp] = y_iw.subs(lengths).subs(results) positions[4, tp] = x_m.subs(lengths).subs(results) positions[5, tp] = y_m.subs(lengths).subs(results) energy[0, tp] = T.subs(lengths).subs(masses).subs(dampening).subs(results) energy[1, tp] = V.subs(lengths).subs(masses).subs(dampening).subs(results) energy[2, tp] = L.subs(lengths).subs(masses).subs(dampening).subs(results) fig, axs = plt.subplots(3) for row, state in enumerate(states): axs[0].plot(timeline, solution[:, row], label=str(state)) axs[1].plot(timeline, positions[0, :].T, label='x_ow') # axs[1].plot(timeline, positions[1, :].T, label='y_ow') axs[1].plot(timeline, positions[2, :].T, label='x_iw') axs[1].plot(timeline, positions[3, :].T, label='y_iw') axs[1].plot(timeline, positions[4, :].T, label='x_m') axs[1].plot(timeline, positions[5, :].T, label='y_m') axs[2].plot(timeline, energy[0, :].T, label='T') axs[2].plot(timeline, energy[1, :].T, label='V') axs[2].plot(timeline, energy[2, :].T, label='L') axs[0].legend() axs[1].legend() axs[2].legend() axs[0].grid() axs[1].grid() axs[2].grid() plt.xlabel('t') # plt.axis([-0.01, 5, -0.75, 1.5]) scene = canvas(align='left', width=1830, height=1120, center=vector(0, 0, 0), background=color.black) floor = box(pos=vector(0, -2.125, 0), length=8, height=0.25, width=4, color=color.gray(0.5)) rod_m = cylinder(pos=vector(0, -1.0, -0.1), axis=vector(0, 0, 0.6), radius=0.4, color=color.green) rod_iw = cylinder(pos=vector(0, -1.0, -0.1), axis=vector(0, 0, 0.6), radius=r_1.subs(lengths), color=color.gray(0.2)) rod_ow = cylinder(pos=vector(0, -1.0, 0), axis=vector(0, 0, 0.4), radius=r_3.subs(lengths), color=color.gray(0.6)) def render_task(): while 1: for i in range(len(timeline)): rate(1 / dt) rod_ow.pos.x = positions[0, i] rod_ow.pos.y = positions[1, i] - 2 rod_iw.pos.x = positions[2, i] rod_iw.pos.y = positions[3, i] - 2 rod_m.pos.x = positions[4, i] rod_m.pos.y = positions[5, i] - 2 render3d = threading.Thread(target=render_task) render3d.start() plt.show()
from IPython.display import display_markdown as markdown import numpy as np import sympy as sp sp.init_printing() _Document_ = {} def md(*args): s = '' for x in args: if (isinstance(x, sp.Basic) or isinstance(x, sp.MutableDenseMatrix) or isinstance(x, tuple)): s = s + sp.latex(x) elif isinstance(x, np.ndarray): s = s + sp.latex(sp.Matrix(x)) elif (isinstance(x, str)): s = s + x elif (isinstance(x, int) or isinstance(x, float)): s = s + str(x) else: print(type(x)) markdown(s, raw=True) def line(name, *args): def conv(x): if (isinstance(x, sp.Basic) or isinstance(x, sp.MutableDenseMatrix) or isinstance(x, tuple)): return sp.latex(x) elif isinstance(x, str): return x else: print(type(x)) line = [ conv(x) for x in args ] try:
# -*- coding: utf-8 -*- """ Written by Daniel M. Aukes Email: danaukes<at>gmail.com Please see LICENSE for full license. """ import sympy sympy.init_printing(pretty_print=False) import pynamics from pynamics.frame import Frame from pynamics.variable_types import Differentiable, Constant, Variable from pynamics.system import System from pynamics.body import Body from pynamics.dyadic import Dyadic from pynamics.output import Output, PointsOutput from pynamics.particle import Particle import pynamics.integration import pynamics.tanh import sympy import numpy import matplotlib.pyplot as plt plt.ion() from math import pi system = System() pynamics.set_system(__name__, system) tol = 1e-4 error_tol = 1e-10