def _theorem_2_(a, b, func, d_) -> object: """Net Change Theorem 1: states that the new value of a changing quantity equals the initial value plus the integral of the rate of change: - 1: Solve for the antiderivative of the integral function - 2: Use substitution with your lower and upper bounds to solve the for the net change of the given problem statement. - ∫ [a , b] F′(x) dx = F(b) − F(a) - F(b) = F(a) + ∫ [a , b] F′(x) dx - F(a) = F(b) - ∫ [a , b] F′(x) dx :param a: Lower bounds :param b: Upper bounds :param func: F'(x) : the integral function :param d_: the variable of integration :return: the solution or raw answer """ print("\n") print("Net Change Theorem 2") _integral_ = Integral(func, (d_, a, b)) _antiderivative_ = integrate(func, d_) ans = _antiderivative_.subs({d_: b}) - _antiderivative_.subs({d_: a}) print("\nF'(x) = \n\n{0}".format(pretty(_integral_))) print("\nF(x) = \n\n{0}".format(pretty(_antiderivative_))) print("\nF(x) = \n\n{0} - {1} = {2}".format( pretty(_antiderivative_.subs({d_: b})), pretty(_antiderivative_.subs({d_: a})), ans)) return ans
def ShowPrettyAction(self): if self.FormulasState == FormulasState.Pretty: return self._UpdateStrsProblemModel() try: sympy_model = problem.ProblemSympy(self.strs_problem_model) except Exception as err: mbox = QtWidgets.QMessageBox(self) mbox.setIcon(mbox.Warning) mbox.setText(str(err)) mbox.show() return self.Equation = sympy.pretty(sympy_model.equation) self.InitialCondition = sympy.pretty(sympy_model.initial_condition) self.LBoundaryConditions = [ sympy.pretty(cond) for cond in sympy_model.L_boundary_conditions ] self.RBoundaryConditions = [ sympy.pretty(cond) for cond in sympy_model.R_boundary_conditions ] self.AnalyticalSolution = sympy.pretty(sympy_model.analytical_solution) self.FormulasState = FormulasState.Pretty
def __str__(self): from ..utils import header_string from ..jinja_env import env template = env.get_template('equivalent_equation.tpl') t, x, y, z, U, Fx, Fy, Fz, Delta = sp.symbols('t, x, y, z, U, Fx, Fy, Fz, Delta_t') Bxx, Bxy, Bxz = sp.symbols('Bxx, Bxy, Bxz') Byx, Byy, Byz = sp.symbols('Byx, Byy, Byz') Bzx, Bzy, Bzz = sp.symbols('Bzx, Bzy, Bzz') phys_equation = sp.Derivative(U, t) + sp.Derivative(Fx, x) if self.dim > 1: phys_equation += sp.Derivative(Fy, y) if self.dim == 3: phys_equation += sp.Derivative(Fz, z) order2 = [] space = [x, y, z] B = [[Bxx, Bxy, Bxz], [Byx, Byy, Byz], [Bzx, Bzy, Bzz], ] phys_equation_rhs = 0 for i in range(self.dim): for j in range(self.dim): order2.append(sp.pretty(sp.Eq(B[i][j], -Delta*self.coeff_order2[i][j], evaluate=False))) phys_equation_rhs += sp.Derivative(B[i][j]*sp.Derivative(U, space[j]), space[i]) return template.render(header=header_string('Equivalent Equations'), dim=self.dim, phys_equation=sp.pretty(sp.Eq(phys_equation, phys_equation_rhs)), conserved_moments=sp.pretty(sp.Eq(U, self.consm, evaluate=False)), order1=[sp.pretty(sp.Eq(F, coeff, evaluate=False)) for F, coeff in zip([Fx, Fy, Fz][:self.dim], self.coeff_order1)], order2=order2 )
def __str__(self): from .utils import header_string from .jinja_env import env template = env.get_template('equivalent_equation.tpl') t, x, y, z, U, Fx, Fy, Fz, Delta = sp.symbols('t, x, y, z, U, Fx, Fy, Fz, Delta_t') Bxx, Bxy, Bxz = sp.symbols('Bxx, Bxy, Bxz') Byx, Byy, Byz = sp.symbols('Byx, Byy, Byz') Bzx, Bzy, Bzz = sp.symbols('Bzx, Bzy, Bzz') phys_equation = sp.Derivative(U, t) + sp.Derivative(Fx, x) if self.dim > 1: phys_equation += sp.Derivative(Fy, y) if self.dim == 3: phys_equation += sp.Derivative(Fz, z) order2 = [] space = [x, y, z] B = [[Bxx, Bxy, Bxz], [Byx, Byy, Byz], [Bzx, Bzy, Bzz], ] phys_equation_rhs = 0 for i in range(self.dim): for j in range(self.dim): order2.append(sp.pretty(sp.Eq(B[i][j], -Delta*self.coeff_order2[i][j], evaluate=False))) phys_equation_rhs += sp.Derivative(B[i][j]*sp.Derivative(U, space[j]), space[i]) return template.render(header=header_string('Equivalent Equations'), dim=self.dim, phys_equation=sp.pretty(sp.Eq(phys_equation, phys_equation_rhs)), conserved_moments=sp.pretty(sp.Eq(U, self.consm, evaluate=False)), order1=[sp.pretty(sp.Eq(F, coeff, evaluate=False)) for F, coeff in zip([Fx, Fy, Fz][:self.dim], self.coeff_order1)], order2=order2 )
def makeOutput(epsilonValues, system): vector = '' for i in range(0, len(epsilonValues)): if (i > 0): vector = vector[:-3] vector += ', ' if (not epsilonValues[i].any()): vector = vector[:-2] vector += ' + ' else: for j in range(0, len(epsilonValues[0])): fraction = str( Fraction(int(epsilonValues[i][j]), int(system.detB))) if (j > 0 and Fraction(fraction) == 1): fraction = '' if (epsilonValues[i][0] != 0): if (j == 1): vector = vector[:-5] + ' + ' if (epsilonValues[i][j] != 0): if (np.sign(int(epsilonValues[i][j]) / int(system.detB)) == -1): vector = vector[:-3] + ' - ' vector += fraction[1:] + sympy.pretty(epsilon) + str( j) + ' + ' else: vector += fraction + sympy.pretty(epsilon) + str( j) + ' + ' return vector[:-3]
def __init__(self, solver): super().__init__(solver) self.short_name = 'GH+C' if solver.model._constraint else 'GH' self.name = 'Gauss-Helmert-Model with Constraints' if solver.model._constraint else 'Gauss-Helmert-Model' if self.auto_diff: self.B = { 'unicode': pretty(solver.model._sym_B), 'latex': latex(solver.model._sym_B) } # constraints definition self.constraint = True if solver.model._constraint else False self.constraint_auto_diff = True if solver.model._sym_gamma else False if self.constraint_auto_diff: self.gamma = { 'unicode': pretty(solver.model._sym_gamma), 'latex': latex(solver.model._sym_gamma) } self.C = { 'unicode': pretty(solver.model._sym_C), 'latex': latex(solver.model._sym_C) } # several numbers self.num_equations = solver._r self.num_constraints = solver.model._c
def __str__(self): out = '' out = out + '---------------------\n' out = out + 'Model "{}":\n'.format(self.name) out = out + 'parameters:\n' for param in self.parameters: out = out + sympy.pretty(param) + '\n' out = out + 'solution_variables:\n' for symbol in self.solution_variables: out = out + sympy.pretty(symbol) + '\n' out = out + 'bounds:\n' out = out + sympy.pretty(self.bounds) + '\n' out = out + 'equations:\n' for eq in self.eqs: out = out + sympy.pretty(eq) + '\n' out = out + 'includes:\n' for i in self.includes: out = out + str(i) + '\n' out = out + '---------------------\n' return out
def divide42by(divideBy): try: return 42 / divideBy except ZeroDivisionError: print( '\n\n\n\nSee the division by zero is not a problem if you are not really looking for a solution.\n Since, division by zero leads to the formation of a non-terminating number which tends to infinity\n So you see it\'s really a hopeless endeavour but since you\'re so hellbent on finding it, My choice of answer for you is \n %s' % sympy.pretty(pi)) sympy.pretty(pi)
def __str__(self): a = [] for ode in self.odes: ode_str = sympy.pretty(ode) a += ode_str.split('\n') for key, value in self.ics.items(): ics_str = sympy.pretty(sympy.Eq(key, value)) a += ics_str.split('\n') return _bracket(a)
def pretty(self): a = sp.pretty(self.represent[0], use_unicode=PP_USE_UNICODE) b = sp.pretty(self.represent[1], use_unicode=PP_USE_UNICODE) c = sp.pretty(self.represent[2], use_unicode=PP_USE_UNICODE) d = sp.pretty(self.represent[3], use_unicode=PP_USE_UNICODE) return "A=\n\n{0}\n\nB=\n\n{1}\n\nC=\n\n{2}\n\nD=\n\n{3}\n\n".format( a, b, c, d)
def my_pretty(frac): """ Write a symbolic rational function as a pretty string that can be printed. :param frac: A rational function. :type frac: A symbolic rational function. :return: A pretty version of the input. :rtype: A string. """ num, denom = sympy.fraction(sympy.factor(frac)) return sympy.pretty(num) + "\n" + "/\n" + sympy.pretty(denom) + "\n\n\n\n\n"
def display_minmax_equations(self): if not self._has_equations: raise Exception('Equation has not been saved!') data = [['Equation', 'Min equation', 'Max Equation'], [ pretty(self.equation), pretty(self.min_equation), pretty(self.max_equation) ]] print(FancyTable(data).table)
def calculus(): int_diff = input("Do you want to integrate or differentiate? ") if int_diff == "differentiate": global diffd_equ choice = int(input("\nInsert the level of differentiation: ")) #This will tell the differentiation attribute how many times the equation has to be differentiated. x = sp.Symbol("x") #This states that "x" is a symbol rather than a string. print("Insert equation: ") equation = input() diffd_equ = sp.diff(equation, x, choice) #The "sp.pretty" is used to output the answer in a more appealing form. print("\nYour answer is:") sp.pprint(diffd_equ) history(diffd_equ) substitution = input("Do you want to substitute a value into x? ") if substitution == "yes": substitute(diffd_equ) elif int_diff == "integrate": global integ choice = input( "\nDo you want to integrate a definite or indefinite integral? ") x = sp.Symbol("x") print("\nInsert Equation: ") equation = input() if choice == "definite": upper = int(input("\nWrite the upper limit here please: ")) lower = int(input("\nWrite the lower limit here please: ")) integ = sp.integrate(equation, (x, lower, upper)) print("\nYour answer is:", sp.pretty(integ)) elif choice == "indefinite": integ = sp.pretty(sp.integrate(equation, x)) integ0 = sp.integrate(equation, x) print("\nYour answer is:\n" + str(integ)) substitution = input("Do you want to substitute a value into x? ") if substitution == "yes": substitute(integ0) history(integ)
def sym_comp_int(): x = sy.Symbol('x') a, b = sy.symbols('a b') print(sy.pretty(sy.Integral(sy.sin(x) + 0.5 * x, (x, a, b)))) int_func = sy.integrate(sy.sin(x) + 0.5 * x, x) print(sy.pretty(int_func)) Fb = int_func.subs(x, 9.5).evalf() Fa = int_func.subs(x, 0.5).evalf() print(Fb - Fa) # exact value of integral int_func_limits = sy.integrate(sy.sin(x) + 0.5 * x, (x, a, b)) print(sy.pretty(int_func_limits)) print(int_func_limits.subs({a : 0.5, b : 9.5}).evalf()) print(sy.integrate(sy.sin(x) + 0.5 * x, (x, 0.5, 9.5)))
def __str__(self): out = 'bounds:\n' out = out + sympy.pretty(self.bounds) + '\n' out = out + 'with additional equations:\n' for eq in self.eqs: out = out + sympy.pretty(eq) + '\n' out = out + 'mapping:\n' for f, t in self.mapping.items(): out = out + '{} = {}\n'.format(f, t) out = out + str(self.submodel) return out
def sym_comp_basics(): x = sy.Symbol('x') y = sy.Symbol('y') print(type(x)) print(sy.sqrt(x)) print(3 + sy.sqrt(x) - 4 ** 2) f = x ** 2 + 3 + 0.5 * x ** 2 + 3 / 2 print(sy.simplify(f)) sy.init_printing(pretty_print=False, use_unicode=False) print(sy.pretty(f)) print(sy.pretty(sy.sqrt(x) + 0.5)) pi_str = str(sy.N(sy.pi, 400000)) print(pi_str[:40]) print(pi_str[-40:]) print(pi_str.find('111272'))
def print(self, expr): """ Print the expression with Sympy pretty Parameters ---------- expr : Sympy Expression Expression to print """ def recursive_subs(obj): if isinstance(obj, dict): for o in obj: obj[o] = recursive_subs(obj[o]) return obj elif isinstance(obj, Iterable): obj = list(obj) for i, o in enumerate(obj): obj[i] = recursive_subs(o) return obj else: obj = simplify(obj.subs(parse_expr("tau"), parse_expr("2*pi"))) obj = obj.subs(parse_expr("pi"), parse_expr("tau/2")) return obj if self.options["tau_kills_pi"]: expr = recursive_subs(expr) result = pretty(expr) if len(result.split('\n')) > 1: print('') print(result) else: print(result)
def main(file, noise): """Pretty prints and plots all benchmark expressions.""" from matplotlib import pyplot as plt data_path = resource_filename("dsr", "data/") benchmark_path = os.path.join(data_path, file) df = pd.read_csv(benchmark_path, encoding="ISO-8859-1") names = df["name"].to_list() expressions = [parse_expr(expression) for expression in df["sympy"]] for expression, name in zip(expressions, names): print("{}:\n\n{}\n\n".format(name, indent(pretty(expression), '\t'))) if "Nguyen" not in name: continue d = Dataset(file, name, noise=noise) if d.X_train.shape[1] == 1: # Draw ground truth expression bounds = list(list(d.train_spec.values())[0].values())[0][:2] x = np.linspace(bounds[0], bounds[1], endpoint=True, num=100) y = d.numpy_expr(x[:, None]) plt.plot(x, y) # Draw the actual points plt.scatter(d.X_train, d.y_train) plt.show()
def prettyAns(f): return sympy.pretty( f, use_unicode=True, num_columns=2147483647, mat_symbol_style="bold", ).replace("zoo", "ℂ∞").replace("nan", "NaN").replace("⋅", "∙")
def pretty(diagram): agraph = pgv.AGraph( directed=True, rankdir='TB', splines='polyline', ) agraph.add_nodes_from(diagram.nodes, label='', xlabel=r'\N', shape='circle', color='black', style='filled', width=0.1, fixedsize=True) for u, v, w, block in diagram.edges(data='block', keys=True): n = f'{v} += f({u}) ({w})' agraph.add_node(n, label=sympy.pretty(block, num_columns=sys.maxsize), fontname='courier', shape='box', style='solid') agraph.add_edge(u, n, style='solid', arrowsize=0.5) agraph.add_edge(n, v, style='solid', arrowsize=0.5) agraph.layout(prog='dot') return agraph
def echo_expression_without_unicode(expr, echo=print): '''sympy.pretty_print ''' result = pretty(expr, use_unicode=False, use_unicode_sqrt_char=False) echo(result)
def format_atom(val): if is_number(val): mag = abs(val) if type(val) is complex: re, im = format_float(val.real), format_float(val.imag) return f"{re} {'-' if im<0 else '+'} {abs(im)}ⅈ" elif mag == inf: return '∞' elif isinstance(val, Rational) and not opts['sci']: if type(val) is Fraction: val.limit_denominator(10**config.precision) if opts['bin']: return bin(val) elif opts['hex']: return hex(val) else: return str(val) elif mag <= 0.001 or mag >= 10000: return format_scinum(val) else: return str(format_float(val)) elif is_function(val): return str(val) if depth == 1 else repr(val) elif is_env(val): if hasattr(val, 'val'): return calc_format(val.val) else: return str(val) if depth == 1 else repr(val) elif isinstance(val, Range): return str(val) else: return pretty(val, use_unicode=True)
def __str__(self, only_target_estimand=False): s = "Estimand type: {0}\n".format(self.estimand_type) i = 1 has_valid_backdoor = sum("backdoor" in key for key in self.estimands.keys()) for k, v in self.estimands.items(): # Do not show backdoor key unless it is the only backdoor set. if k == "backdoor" and has_valid_backdoor > 1: continue if only_target_estimand and k != self.identifier_method: continue s += "\n### Estimand : {0}\n".format(i) s += "Estimand name: {0}".format(k) if k == self.default_backdoor_id: s += " (Default)" s += "\n" if v is None: s += "No such variable found!\n" else: sp_expr_str = sp.pretty(v["estimand"], use_unicode=True) s += "Estimand expression:\n{0}\n".format(sp_expr_str) j = 1 for ass_name, ass_str in v["assumptions"].items(): s += "Estimand assumption {0}, {1}: {2}\n".format( j, ass_name, ass_str) j += 1 i += 1 return s
def __init__(self, expr=None, unit=None): # Use init when expr is string math expression (ie sympify-able) self.unit = unit if expr is not None: sympyexpr = uparser.parse_math(expr, raiseonerr=False) if sympyexpr: self.sympyexpr = sympyexpr self.latexexpr = sympy.latex(self.sympyexpr).encode( 'ascii', 'latex').decode() self.prettytextexpr = sympy.pretty( self.sympyexpr ) # May use multiple lines for fractions, etc. self.simpletextexpr = str( self.sympyexpr) # Typically the same as expr string else: self.sympyexpr = None self.latexexpr = expr self.prettytextexpr = expr self.simpletextexpr = expr if unit is not None: self.latexexpr = self.latexexpr + r'\,' + Unit(unit).latex( escape=False) self.prettytextexpr += Unit(unit).prettytext() self.simpletextexpr += Unit(unit).plaintext() else: self.sympyexpr = None self.latexexpr = None self.prettytextexpr = None self.simpletextexpr = None
def raw_calculate(calculation, return_str=False, return_approx=False): ret = sympify(calculation, evaluate=False) if return_approx: approximation = ret.evalf() else: try: # si Rationnel enlever la multiplication approximation = ret.evalf() if (simplify(ret) == ret or ret.evalf() != ret) else None except AttributeError: approximation = None ret = simplify(ret) if latex_need(ret) and not return_str: latex_str = latex(ret) if approximation is None else latex(ret) + r"\approx" + str(approximation) with open(result_file, "wb") as file: file.write(requests.get( r"https://latex.codecogs.com/png.download?\dpi{110}%20\fn_phv%20\huge%20{\color{White}" + latex_str + "}").content) return True return pretty(ret) if approximation is None else pretty(ret) + " ≈ " + str(approximation)
def show_error(self, type_dict, unicode=True): """ Show the formula for the error. :param type_dict: Dict[type] = Dictionary containing the types of each parameter/variable :param unicode: bool = Specifies if unicode should be used :return: str = pretty version of the formula for the error """ error_f = self.__create_error_f(type_dict) formula = self.__create_formula(type_dict) string = "" string += "Formel:\n" string += pretty(formula, use_unicode=unicode) string += "\nFehlerformel nach Gauss:\n" string += pretty(error_f, use_unicode=unicode) return string
def print_basic_unicode(o, p, cycle): """A function to pretty print sympy Basic objects.""" if cycle: return p.text("Basic(...)") out = pretty(o, use_unicode=True) if "\n" in out: p.text(u"\n") p.text(out)
def latex_need(c): if c == zoo: return True try: sympify(pretty(c)) return False except SympifyError: return True
def display_fn(self, notebook=True): """Display function fn(x, r) which is essentially dx/dt with a single parameter r """ # display(Eq(self.dx, self.fn)) if notebook: display(Eq(self.dx, self.fn)) else: print(pretty(Eq(self.dx, self.fn)))
def __str__(self): out = '' for m in (self.origin, self.to): out = out + 'model "{}":\n{}'.format(m[0].name, sympy.pretty( m[1])) + '\n' return out
def print_basic_unicode(o, p, cycle): """A function to pretty print sympy Basic objects.""" if cycle: return p.text('Basic(...)') out = pretty(o, use_unicode=True) if '\n' in out: p.text(u'\n') p.text(out)
def __str__(self): from .utils import header_string from .jinja_env import env template = env.get_template('scheme.tpl') P = [] EQ = [] s = [] header_scheme = [] for k in range(self.nschemes): myslice = slice(self.stencil.nv_ptr[k], self.stencil.nv_ptr[k+1]) header_scheme.append(header_string("Scheme %d"%k)) P.append(sp.pretty(sp.Matrix(self.P[myslice]))) EQ.append(sp.pretty(sp.Matrix(self.EQ_no_swap[myslice]))) s.append(sp.pretty(sp.Matrix(self.s_no_swap[myslice]))) if self.rel_vel: addons = {'rel_vel': self.rel_vel, 'Tu': sp.pretty(self.Tu_no_swap) } else: addons = {} return template.render(header=header_string("Scheme information"), scheme=self, consm=sp.pretty(list(self.consm.keys())), header_scheme=header_scheme, P=P, EQ=EQ, s=s, M=sp.pretty(self.M_no_swap), invM=sp.pretty(self.invM_no_swap), **addons )
def __str__(self): from .utils import header_string from .jinja_env import env template = env.get_template('scheme.tpl') P = [] EQ = [] s = [] header_scheme = [] for k in range(self.nschemes): myslice = slice(self.stencil.nv_ptr[k], self.stencil.nv_ptr[k + 1]) header_scheme.append(header_string("Scheme %d" % k)) P.append(sp.pretty(sp.Matrix(self.P[myslice]))) EQ.append(sp.pretty(sp.Matrix(self.EQ_no_swap[myslice]))) s.append(sp.pretty(sp.Matrix(self.s_no_swap[myslice]))) if self.rel_vel: addons = { 'rel_vel': self.rel_vel, 'Tu': sp.pretty(self.Tu_no_swap) } else: addons = {} return template.render(header=header_string("Scheme information"), scheme=self, consm=sp.pretty(list(self.consm.keys())), header_scheme=header_scheme, P=P, EQ=EQ, s=s, M=sp.pretty(self.M_no_swap), invM=sp.pretty(self.invM_no_swap), **addons)
def _derivate(self, n): if n not in self.data_cache: m = max((d for d in self.data_cache if d < n)) sym_func = self.data_cache[m]['obj'] derivate = symlib.diff_func(sym_func, n - m) repr_str = sympy.pretty(derivate) func = numlib.generate_func(derivate) values = func(self.x, None) self._fill_cache(n, derivate, values, repr_str)
def print_to_file(guy, append=False, software=r"C:\Program Files (x86)\Notepad++\notepad++.exe"): flag = 'w' if append: flag = 'a' outfile = open(r'print.txt', flag) outfile.write('\n') outfile.write(sympy.pretty(guy, wrap_line=False)) outfile.write('\n') outfile.close() subprocess.Popen(software + ' print.txt')
def test_logic_printing(): from sympy import symbols, pretty from sympy.printing import latex syms = symbols('a:f') expr = And(*syms) assert latex(expr) == 'a \\wedge b \\wedge c \\wedge d \\wedge e \\wedge f' assert pretty(expr) == 'And(a, b, c, d, e, f)' assert str(expr) == 'And(a, b, c, d, e, f)'
def main(): print sympy.pretty(sympy.collect(bdf_method(2, 0).expand(), ys).simplify()) print "code for ibdf2 step:" print my_bdf_code_gen(2, 0, True) # print "\n\n code for eBDF3 step:" # print my_bdf_code_gen(3, 1, False) # print "\n\n code for iBDF3 dydt approximation:" # print my_bdf_code_gen(3, 0, True) print "\n\n code for iBDF3 step:" print my_bdf_code_gen(3, 0, True) # print "\n\n code for iBDF4 dydt approximation:" # print my_bdf_code_gen(4, 0, True) print "\n\n code for eBDF3 step w/ derivative at n-1:" print my_bdf_code_gen(3, 2, True)
def pretty(self, view='question'): '''Return a pretty print representation of example. By default, it pretty prints the question. ``view`` can be any of "question", "answer", "responses", "full" or an integer that refers to a specific response. ''' if view == 'question': return sp.pretty(self.question) elif view == 'answer': return sp.pretty(self.answer) elif view == 'responses': raise NotImplementedError elif view == 'full': out = ['Question', '--------', self.pretty('question')] out.extend(['Responses', '---------', self.pretty('responses')]) return '\n'.join(out) elif isinstance(view, int): return sp.pretty(self.alternatives[view]) else: raise ValueError('unrecognized value: view=%r' % view)
def __init__(self, x, y, model, **params): Fitter.__init__(self, x, y) self.model = model self.params = dict(self.model.default_params) self.params.update(params) numlib.modelfit(self.model, self.params, x, y) sym_func = symlib.generate_sym_func(self.model.funcstring, self.params) repr_str = sympy.pretty(sym_func) values = self.model(self.x, self.params) self._fill_cache(0, sym_func, values, repr_str)
def __str__(self): str_format = ( "T matrix of frame %d wrt frame %d:\n" "----------------------------------\n" "gamma=%s, b=%s, alpha=%s, d=%s, theta=%s, r=%s\n" "%s\n" "**********************************\n" ) % ( self._frame_j, self._frame_i, str(self._gamma), str(self._b), str(self._alpha), str(self._d), str(self._theta), str(self._r), sympy.pretty(self._tmat) ) return str_format
def assert_sym_eq(a, b): """Compare symbolic expressions. Note that the simplification algorithm is not completely robust: might give false negatives (but never false positives). Try adding extra simplifications if needed, e.g. add .trigsimplify() to the end of my_simp. """ def my_simp(expr): # Can't .expand() ints, so catch the zero case separately. try: return expr.expand().simplify() except AttributeError: return expr print print sympy.pretty(my_simp(a)) print "equals" print sympy.pretty(my_simp(b)) print # Try to simplify the difference to zero assert (my_simp(a - b) == 0)
def main(): """Construct implicit or explicit bdf methods. \nCode notation: dtn = size of nth time step yn = value of y at nth step Dyn = derivative at nth step (i.e. f(t_n, y_n)) nm1 = n-1, np1 = n+1, etc. ** is the power operator """ # Parse arguments parser = argparse.ArgumentParser(description=main.__doc__, # Don't mess up my formating in the help message formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--order', action = "store", type=int, help="order of the method to generate", required=True) parser.add_argument('--explicit', action = "store", type=bool, help="Generate explicit bdf method? (true/false)", required=True) args = parser.parse_args() print("I'm computing the", "explicit" if args.explicit else "implicit", "BDF methd of order", args.order, ".\n\n") our_bdf_method = derive_full_method(args.order, 1 if args.explicit else 0) print("The symbolic representation is [may require a unicode-enabled terminal]:\n") print(sympy.pretty(our_bdf_method)) print("\n\nThe code is:") print(code_gen(our_bdf_method))
def main(): print "Hydrogen radial wavefunctions:" var("r a") print "R_{21}:" pprint(R_nl(2, 1, a, r)) print "R_{60}:" pprint(R_nl(6, 0, a, r)) print "Normalization:" i = Integral(R_nl(1, 0, 1, r)**2 * r**2, (r, 0, oo)) print pretty(i), " = ", i.doit() i = Integral(R_nl(2, 0, 1, r)**2 * r**2, (r, 0, oo)) print pretty(i), " = ", i.doit() i = Integral(R_nl(2, 1, 1, r)**2 * r**2, (r, 0, oo)) print pretty(i), " = ", i.doit()
def print_basic_unicode(obj, printer, cycle): out = pretty(obj, use_unicode=True) printer.text(out)
def visualize(self, dico=None, viewer_app=viewer.matplotlib_viewer): """ visualize the stability """ if dico is None: dico = {} consm0 = [0.] * len(self.consm) dicolin = dico.get('linearization', None) if dicolin is not None: for k, moment in enumerate(self.consm): consm0[k] = dicolin.get(moment, 0.) n_wv = dico.get('number_of_wave_vectors', 1024) v_xi, eigs = self.eigenvalues(consm0, n_wv) nx = v_xi.shape[1] fig = viewer_app.Fig(1, 2, figsize=(12.8, 6.4)) # , figsize=(12, 6)) if self.dim == 1: color = 'orange' elif self.dim == 2: color = .5 + .5/np.pi*np.arctan2(v_xi[0, :], v_xi[1, :]) color = np.repeat( color[np.newaxis, :], self.nvtot, axis=0 ).flatten() # real and imaginary part view0 = fig[0] view0.title = "Stability: {}".format(self.is_stable_l2) view0.axis(-1.1, 1.1, -1.1, 1.1, aspect='equal') view0.grid(visible=False) view0.set_label('real part', 'imaginary part') view0.ax.set_xticks([-1, 0, 1]) view0.ax.set_xticklabels([r"$-1$", r"$0$", r"$1$"]) view0.ax.set_yticks([-1, 0, 1]) view0.ax.set_yticklabels([r"$-1$", r"$0$", r"$1$"]) theta = np.linspace(0, 2*np.pi, 1000) view0.plot( np.cos(theta), np.sin(theta), alpha=0.5, color='navy', width=0.5, ) pos0 = np.empty((nx*self.nvtot, 2)) for k in range(self.nvtot): pos0[nx*k:nx*(k+1), 0] = np.real(eigs[:, k]) pos0[nx*k:nx*(k+1), 1] = np.imag(eigs[:, k]) markers0 = view0.markers(pos0, 5, color=color, alpha=0.5) # modulus view1 = fig[1] view1.title = "Stability: {}".format(self.is_stable_l2) view1.axis(0, 2*np.pi, -.1, 1.1) view1.grid(visible=True) view1.set_label('wave vector modulus', 'modulus') view1.ax.set_xticks([k*np.pi/4 for k in range(0, 9)]) view1.ax.set_xticklabels( [ r"$0$", r"$\frac{\pi}{4}$", r"$\frac{\pi}{2}$", r"$\frac{3\pi}{4}$", r"$\pi$", r"$\frac{5\pi}{4}$", r"$\frac{3\pi}{2}$", r"$\frac{7\pi}{4}$", r"$2\pi$" ] ) view1.plot( [0, 2*np.pi], [1., 1.], alpha=0.5, color='navy', width=0.5, ) pos1 = np.empty((nx*self.nvtot, 2)) for k in range(self.nvtot): # pos1[nx*k:nx*(k+1), 0] = np.sqrt(np.sum(v_xi**2, axis=0)) pos1[nx*k:nx*(k+1), 0] = np.max(v_xi, axis=0) pos1[nx*k:nx*(k+1), 1] = np.abs(eigs[:, k]) markers1 = view1.markers(pos1, 5, color=color, alpha=0.5) dicosliders = dico.get('parameters', None) if dicosliders is not None: import matplotlib.pyplot as plt from matplotlib.widgets import Slider axcolor = 'lightgoldenrodyellow' viewer_app.Fig(figsize=(6, 2)) sliders = {} item = 0 length = 0.8/len(dicosliders) for k, v in dicosliders.items(): axe = plt.axes( [0.2, 0.1+item*length, 0.65, 0.8*length], facecolor=axcolor, ) sliders[k] = Slider( axe, v.get('name', sp.pretty(k)), *v['range'], valinit=v['init'], valstep=v['step'] ) item += 1 def update(val): # pylint: disable=unused-argument for k, v in sliders.items(): if k in self.param.keys(): self.param[k] = v.val for i_m, moment in enumerate(self.consm): if moment == k: consm0[i_m] = v.val v_xi, eigs = self.eigenvalues(consm0, n_wv) for k in range(self.nvtot): pos0[nx*k:nx*(k+1), 0] = np.real(eigs[:, k]) pos0[nx*k:nx*(k+1), 1] = np.imag(eigs[:, k]) markers0.set_offsets(pos0) view0.title = "Stability: {}".format(self.is_stable_l2) for k in range(self.nvtot): # pos1[nx*k:nx*(k+1), 0] = np.sqrt(np.sum(v_xi**2, axis=0)) pos1[nx*k:nx*(k+1), 0] = np.max(v_xi, axis=0) pos1[nx*k:nx*(k+1), 1] = np.abs(eigs[:, k]) markers1.set_offsets(pos1) view1.title = "Stability: {}".format(self.is_stable_l2) fig.fig.canvas.draw_idle() for k in sliders.keys(): sliders[k].on_changed(update) fig.show()
def pretty(expr): if hasattr(expr, 'pretty'): return expr.pretty() else: return sym.pretty(expr)
def pretty(self): """Make pretty string""" return sym.pretty(self.expr)
def pretty(self): argsrepr = ', '.join([sym.pretty(arg) for arg in self._tweak_args()]) return '%s(%s)' % (self.__class__.__name__, argsrepr)
sy.sqrt(x) #sqrt(x) #Sympy will automatically simplify math functions 3+sy.sqrt(x)-4**2 #sqrt(x) - 13 #Define arbiraty functions using symbols f=x**2+3+0.5*x**2+3/2 sy.simplify(f) #1.5*x**2 + 4 sy.init_printing(pretty_print=False, use_unicode=False) print sy.pretty(f) # 2 #1.5*x + 4 print sy.pretty(sy.sqrt(x)+0.5) # ___ #\/ x + 0.5 #Solving equations #Example solve x^2-1=0 sy.solve(x**2-1) #[1,1] sy.solve(x**2-1-3) #[2,2]
def prettyans(self, name): """Make pretty string with LHS name""" return sym.pretty(sym.Eq(sympify(name), self.expr))
print("\nLaplace and Z Transforms are related by:") pprint(Eq(z, exp(s / rate))) print("\nBilinear transform approximation (no prewarping):") z_num = exp( s / (2 * rate)) z_den = exp(-s / (2 * rate)) assert z_num / z_den == exp(s / rate) z_bilinear = together(taylor(z_num, x=s, x0=0) / taylor(z_den, x=s, x0=0)) pprint(Eq(z, z_bilinear)) print("\nWhich also means:") s_bilinear = solve(Eq(z, z_bilinear), s)[0] pprint(Eq(s, radsimp(s_bilinear.subs(z, 1 / zinv)))) print("\nPrewarping H(z) = H(s) at a frequency " + pretty(w) + " (rad/sample) to " + pretty(f) + " (rad/s):") pprint(Eq(z, exp(I * w))) pprint(Eq(s, I * f)) f_prewarped = (s_bilinear / I).subs(z, exp(I * w)).rewrite(sin) \ .rewrite(tan).cancel() pprint(Eq(f, f_prewarped)) # Lowpass/highpass filters with prewarped bilinear transform equation T = tan(w / 2) for name, afilt_str in [("high", "s / (s - p)"), ("low", "-p / (s - p)")]: print() print_header("Laplace {0}pass filter (matches {0}pass.z)".format(name)) print("\nFilter equations:")
def test_printing(): psi = Ket('psi') assert pretty(psi, use_unicode=True) == u'\u2758\u03c8\u27e9' assert pretty(Dagger(psi), use_unicode=True) == u'\u27e8\u03c8\u2758' assert latex(psi) == r"{\left|\psi\right\rangle }" assert latex(Dagger(psi)) == r"{\left\langle \psi\right|}"
def solve(statements): # Find all the symbols mentioned in the statements. symbols = set() for statement in statements: symbols = symbols.union(statement.atoms(Symbol)) known_symbols = set() results = {} # Initial pass over the statements to see which ones are # "simple knowns": lhs is a symbol and rhs is non-symbolic. equations = set() for statement in statements: known_symbol = as_known(statement) if known_symbol is not None: if known_symbol.lhs in results: raise Exception( 'Conflicting values of ' + str(known_symbol.lhs) ) results[known_symbol.lhs] = simplify(known_symbol.rhs) known_symbols.add(known_symbol.lhs) continue equations.add(statement) # Substitute all of the "simple knowns" into the equations # to take care of the simple cases. if len(known_symbols) > 0: for equation in equations: for symbol, value in results.iteritems(): equation = equation.subs(symbol, value) remaining_symbols = equation.atoms(Symbol) if len(remaining_symbols) == 0: continue else: known_symbol = as_known(equation) if known_symbol is not None: results[known_symbol.lhs] = simplify(known_symbol.rhs) known_symbols.add(known_symbol.lhs) # Re-substitute all of the original equations with what we now know. # In the process, we might eliminate all of the symbols from # some of the equations. If any of them reduce to False then there # is an inconsistency in the statements which the user must fix. if len(known_symbols) > 0: reduced_equations = set() for equation in equations: subst_equation = equation for symbol, value in results.iteritems(): subst_equation = subst_equation.subs(symbol, value) if subst_equation == false: raise Exception('Inconsistency evaluating ' + pretty(equation)) elif subst_equation != true: reduced_equations.add(subst_equation) equations = reduced_equations unresolved = set() if len(symbols - known_symbols) > 0: try: solutions = solve_system(equations, set=True) except NotImplementedError: raise Exception('No solution found') if type(solutions) is tuple: if len(solutions[1]) == 0: raise Exception('No solution found') for i, lhs in enumerate(solutions[0]): sol_equs = (Eq(lhs, solution[i]) for solution in solutions[1]) for sol_equ in sol_equs: known_symbol = as_known(sol_equ) if known_symbol is not None: results[known_symbol.lhs] = known_symbol.rhs known_symbols.add(known_symbol.lhs) else: unresolved.add(sol_equ) else: if type(solutions) is list: for solution in solutions: sol_equs = ( Eq(lhs, rhs) for lhs, rhs in solution.iteritems() ) for sol_equ in sol_equs: known_symbol = as_known(sol_equ) if known_symbol is not None: results[known_symbol.lhs] = known_symbol.rhs known_symbols.add(known_symbol.lhs) else: unresolved.add(sol_equ) else: raise Exception('No finite solution found') # Any unresolved equations become dependency declarations. unknowns = {} for equation in unresolved: equ_symbols = equation.atoms(Symbol) for symbol in equ_symbols: if symbol in known_symbols: continue if symbol not in unknowns: unknowns[symbol] = set() unknowns[symbol].add(Dependency(symbol, equation)) # In case there's anything we haven't taken care of yet, put # an empty dependency set in the unknowns. for symbol in symbols: if symbol not in results and symbol not in unknowns: unknowns[symbol] = set() return results, unknowns
def autogen_functions(L, where): for d in L: f = d['name']; fname = '%s/@sym/%s.m' % (where,f) print fname fd = open(fname, "w") fd.write(copyright_block) fd.write('\n%% -*- texinfo -*-\n') fd.write("%% @documentencoding UTF-8\n") fd.write("%%%% @deftypefn {Function File} {@var{y} =} %s (@var{x})\n" % f) fd.write("%%%% Symbolic %s function.\n" % f) # Build and out example block for doctest xstr = d['docexpr'] x = sp.S(xstr) y = eval("sp.%s(x)" % d['spname']) ystr = sp.pretty(y, use_unicode=True) lines = ystr.splitlines() if len(lines) > 1: # indent multiline output lines = [("%% " + a).strip() for a in lines] ystr = "\n" + "\n".join(lines) else: ystr = " " + ystr yutf8 = ystr.encode('utf-8') fd.write("%%\n%% Example:\n%% @example\n%% @group\n") fd.write("%% syms x\n") fd.write("%%%% y = %s(%s)\n" % (f, xstr)) fd.write("%%%% @result{} y = (sym)%s\n" % yutf8) fd.write("%% @end group\n%% @end example\n") fd.write( \ """%% %% Note: this file is autogenerated: if you want to edit it, you might %% want to make changes to 'generate_functions.py' instead. %% %% @end deftypefn %% Author: Colin B. Macdonald %% Keywords: symbolic """) fd.write("function y = %s(x)\n" % f) #fd.write('\n') if len(d['extra_code']) > 0: fd.write("\n %s\n\n" % d['extra_code']) fd.write(" y = uniop_helper (x, '%s');\n" % d['spname']) fd.write("end\n") # tests fd.write("\n\n%!shared x, d\n") fd.write("%%! d = %s;\n" % d['test_in_val']) fd.write("%%! x = sym('%s');\n\n" % d['test_in_val']) fd.write("%!test\n") fd.write("%%! f1 = %s(x);\n" % f) if d['out_val_from_oct']: fd.write("%%! f2 = %s(d);\n" % f) else: fd.write("%%! f2 = %s;\n" % d['test_out_val']) fd.write("%! assert( abs(double(f1) - f2) < 1e-15 )\n\n") fd.write("%!test\n") fd.write("%! D = [d d; d d];\n") fd.write("%! A = [x x; x x];\n") fd.write("%%! f1 = %s(A);\n" % f) if d['out_val_from_oct']: fd.write("%%! f2 = %s(D);\n" % f) else: fd.write("%%! f2 = %s;\n" % d['test_out_val']) fd.write("%! f2 = [f2 f2; f2 f2];\n") fd.write("%! assert( all(all( abs(double(f1) - f2) < 1e-15 )))\n") fd.close()
def test_printing(): psi = Ket('psi') ip = Dagger(psi)*psi assert pretty(ip, use_unicode=True) == u'\u27e8\u03c8\u2758\u03c8\u27e9' assert latex(ip) == r"\left\langle \psi \right. {\left|\psi\right\rangle }"
poly *= sym-root return sympy.Poly(poly.expand()) def getSols(poly, sym, orderDiff): df = poly polyDiffs = [] diffRoots = [] for i in range(1+orderDiff): polyDiffs += [df] roots = sympy.roots(df) diffRoots += [roots] df = df.diff() return polyDiffs, diffRoots def getRealPoly(order, orderDiff, sym=sympy.symbols('x')): poly = getPoly(order, sym) polyDiffs, diffRoots = getSols(poly, sym, orderDiff) # Keep making polynomials until we get one with all real roots for roots in diffRoots: for root in roots: if not sympy.ask(sympy.Q.real(root)): return getRealPoly(order, orderDiff, sym) return polyDiffs, diffRoots if __name__ == '__main__': polyDiffs, diffRoots = getRealPoly(4, 3) for i in range(len(polyDiffs)): print(u'{i}° derivative:\n{poly}\n\nroots:'.format(i=i,poly=sympy.pretty(polyDiffs[i].as_expr()))) for root in diffRoots[i]: print(sympy.pretty(root)) print()
def autogen_functions(L, where): for d in L: f = d['name'] fname = '%s/@sym/%s.m' % (where,f) print fname fd = open(fname, "w") fd.write(make_copyright_line(d['firstyear'])) fd.write("%%\n") fd.write(license_boilerplate) # Build and out example block for doctest xstr = d['docexpr'] x = sp.S(xstr) y = eval("sp.%s(x)" % d['spname']) ystr = sp.pretty(y, use_unicode=True) lines = ystr.splitlines() if len(lines) > 1: # indent multiline output lines = [("%% " + a).strip() for a in lines] ystr = "\n" + "\n".join(lines) else: ystr = " " + ystr yutf8 = ystr.encode('utf-8') body = \ """ %% -*- texinfo -*- %% @documentencoding UTF-8 %% @defmethod @@sym {NAME} (@var{{x}}) %% Symbolic {NAME} function. %% %% Example: %% @example %% @group %% syms x %% y = {NAME} ({XSTR}) %% @result{{}} y = (sym){YUTF8} %% @end group %% @end example %% %% Note: this file is autogenerated: if you want to edit it, you might %% want to make changes to 'generate_functions.py' instead. %% %% @end defmethod function y = {NAME}(x) if (nargin ~= 1) print_usage (); end y = elementwise_op ('{SPNAME}', x); end %!error <Invalid> {NAME} (sym(1), 2) %!assert (isequaln ({NAME} (sym(nan)), sym(nan))) """.format(NAME=f, SPNAME=d['spname'], XSTR=xstr, YUTF8=yutf8) fd.write(body) # tests fd.write("%!shared x, d\n") fd.write("%%! d = %s;\n" % d['test_in_val']) fd.write("%%! x = sym('%s');\n\n" % d['test_in_val']) fd.write("%!test\n") fd.write("%%! f1 = %s(x);\n" % f) if d['out_val_from_oct']: fd.write("%%! f2 = %s(d);\n" % f) else: fd.write("%%! f2 = %s;\n" % d['test_out_val']) fd.write("%! assert( abs(double(f1) - f2) < 1e-15 )\n\n") fd.write("%!test\n") fd.write("%! D = [d d; d d];\n") fd.write("%! A = [x x; x x];\n") fd.write("%%! f1 = %s(A);\n" % f) if d['out_val_from_oct']: fd.write("%%! f2 = %s(D);\n" % f) else: fd.write("%%! f2 = %s;\n" % d['test_out_val']) fd.write("%! f2 = [f2 f2; f2 f2];\n") fd.write("%! assert( all(all( abs(double(f1) - f2) < 1e-15 )))\n") fd.write( \ """ %!test %! % round trip %! y = sym('y'); %! A = {NAME} (d); %! f = {NAME} (y); %! h = function_handle (f); %! B = h (d); %! assert (A, B, -eps) """.format(NAME=f)) fd.close()
from StringIO import StringIO from google.appengine.api import users from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp import template sys.path.insert(0, os.path.join(os.getcwd(), 'sympy')) from sympy import srepr, sstr, pretty, latex PRINTERS = { 'repr': srepr, 'str': sstr, 'ascii': lambda arg: pretty(arg, use_unicode=False), 'unicode': lambda arg: pretty(arg, use_unicode=True), 'latex': lambda arg: latex(arg, mode="equation*"), } def gdb(): """Enter pdb in Google App Engine. """ pdb.Pdb(stdin=getattr(sys, '__stdin__'), stdout=getattr(sys, '__stderr__')).set_trace(sys._getframe().f_back) # Set to True if stack traces should be shown in the browser, etc. _DEBUG = True # The entity kind for shell sessions. Feel free to rename to suit your app. _SESSION_KIND = '_Shell_Session'
print_header("Bilinear transformation method") print("\nLaplace and Z Transforms are related by:") pprint(Eq(z, exp(s / rate))) print("\nBilinear transform approximation (no prewarping):") z_num = exp(s / (2 * rate)) z_den = exp(-s / (2 * rate)) assert z_num / z_den == exp(s / rate) z_bilinear = together(taylor(z_num, x=s, x0=0) / taylor(z_den, x=s, x0=0)) pprint(Eq(z, z_bilinear)) print("\nWhich also means:") s_bilinear = solve(Eq(z, z_bilinear), s)[0] pprint(Eq(s, radsimp(s_bilinear.subs(z, 1 / zinv)))) print("\nPrewarping H(z) = H(s) at a frequency " + pretty(w) + " (rad/sample) to " + pretty(f) + " (rad/s):") pprint(Eq(z, exp(I * w))) pprint(Eq(s, I * f)) f_prewarped = (s_bilinear / I).subs(z, exp(I * w)).rewrite(sin).rewrite(tan).cancel() pprint(Eq(f, f_prewarped)) # Lowpass/highpass filters with prewarped bilinear transform equation T = tan(w / 2) for name, afilt_str in [("high", "s / (s - p)"), ("low", "-p / (s - p)")]: print() print_header("Laplace {0}pass filter (matches {0}pass.z)".format(name)) print("\nFilter equations:") print("H(s) = " + afilt_str) afilt = sympify(afilt_str, dict(p=-f, s=s)) pprint(Eq(p, -f)) # Proof is given in lowpass_highpass_matched_z.py