def solve_ixl(): while True: try: user_input = input() if user_input == "e": print("exiting a2.b1...\n") break # split input into two sides to generate a new equation that can be set to 0 split_input = user_input.split("=") left_side = parse_expr(split_input[0]) right_side = parse_expr(split_input[1]) # check if there is more than one variable in the expression if (len((left_side - right_side).free_symbols) > 1): raise Exception("too many variables") new_equation = left_side - right_side answer = str(solve(new_equation)[0]) print(answer + "\n") copy(answer) except Exception as e: print(str(e) + "\n")
def solve_ixl(): while True: try: user_input = input() if user_input == "e": print("exiting a2.b6...\n") break # split input into two sides to generate a new equation that can be set to 0 split_input = user_input.split("=") left_side = parse_expr(split_input[0]) right_side = parse_expr(split_input[1]) new_equation = left_side - right_side # ask the user for the variable to solve for variable = Symbol(input("solve for: ")) if variable not in new_equation.free_symbols: raise Exception("invalid variable") # choose the last element. when outputting solutions with a sqrt(), IXL only accepts the positive square root answer = str(solve(new_equation, variable)[-1]) answer = format_exponents(answer) print(answer + "\n") copy(answer) except Exception as e: print(str(e) + "\n")
def show_cross_section( self, show: Optional[bool] = False, rectangle_subarea_id: Optional[int] = None, circle_subarea_id: Optional[int] = None, figure: Optional[Figure] = None, ): """ you can pass a subarea ID if you want it to be highlighted in red. IDs must match the ones in the subarea dict """ fgen = fig_generator( self.calc.subareas_rectangle, self.calc.subareas_circle, parse_expr(self.calc.total_cg_x), parse_expr(self.calc.total_cg_y), ) fig = fgen.plot(rectangle_subarea_id, circle_subarea_id, figure) if show: fig.show() else: return fig
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
def to_graphviz_sym( # noqa dfa: SimpleDFA, title: Optional[str] = None, states2colors: Optional[Dict[Any, str]] = None, ) -> Digraph: """To graphviz, symbolic.""" symbols = max(dfa.alphabet, key=lambda x: len(x.true_propositions)) states2colors = states2colors or {} g = graphviz.Digraph(format="svg") g.node("fake", style="invisible") for state in dfa.states: if state == dfa.initial_state: if state in dfa.accepting_states: g.node(str(state), root="true", shape="doublecircle") else: g.node(str(state), root="true") elif state in dfa.accepting_states: g.node(str(state), shape="doublecircle") else: g.node(str(state)) if state in states2colors: g.node(str(state), fillcolor="lightsalmon", style="filled") g.edge("fake", str(dfa.initial_state), style="bold") for start in dfa.transition_function: symbolic_transitions: Dict[Tuple[Any, Any], Boolean] = {} for symbol, end in dfa.transition_function[start].items(): tr = (start, end) if tr not in symbolic_transitions: symbolic_transitions[tr] = BooleanFalse() old = symbolic_transitions[tr] if len(symbol.true_propositions) > 0: formula = sympy.parse_expr(" & ".join( list(symbol.true_propositions))) else: formula = sympy.parse_expr(" & ".join( map(lambda s: "~" + s, symbols))) symbolic_transitions[tr] = old | formula for (start, end), formula in symbolic_transitions.items(): formula = formula.simplify() g.edge(str(start), str(end), label=str(formula)) if title: g.attr(label=title) g.attr(fontsize="20") return g
def solve_inequality(user_input): inequality_sign = get_inequality_sign(user_input, False) split_input = user_input.split(inequality_sign) left_side = parse_expr(split_input[0]) right_side = parse_expr(split_input[1]) inequality = Relational(left_side, right_side, inequality_sign) variable = get_variable(str(inequality)) answer = remove_infinities( str(reduce_inequalities(inequality, symbols=variable))) if answer == "True" or answer == "False": raise Exception("no parallel functions allowed") return answer
def define_ode(self, ode): """ Define the ode as a string, which will be translated to sympy format using its parser. Notice that the sympify method is avoided in order not to use the eval() method. To define expressions, use x to define the independent parameter and y to declare the solution, that is y(x). To define derivatives, several options can be used, according to Sympy documentation. However, the simplest one is to write y.diff(x, n), being n the order of the derivative (must be an integer). This may be subjected to change in the future into a more intuitive definition. The rest of the expressions must be defined according to sympy elementary functions: https://docs.sympy.org/latest/modules/functions/elementary.html Args: ode: string. The equation to be parsed. """ if not isinstance(ode, str): raise TypeError( f'The expression must be an integer, not a {type(ode)}') self.ode = sp.parse_expr(ode, local_dict={'x': self.x, 'y': self.y}) # Identify the symbols of the ODE. self.free_symbols = self.ode.free_symbols # Identify the ODE order. self.ode_order = BVPInterface.get_ode_order(self.ode, self.y) # Properly initialize the boundary conditions arrays (ya, yb). self.ya = np.zeros((1, self.ode_order))[0] self.yb = np.zeros((1, self.ode_order))[0]
def set_bcs(self): """ Set the boundary conditions after loading them using the load_bcs method. Returns: Array containing the loaded boundary conditions with the required format for the scipy solver. """ # Structure of the boundary conditions be like (when user's input is an ODE): # bcs = {'a':{'y': bc_val}, 'b':{'y': bc_val}} # bcs = {'a':{'y.diff(x, 1)': bc_val}, 'b':{'y': bc_val}} # Structure of the boundary conditions be like (when user's input is a system): # bcs = {'a': {'n': bc_val}, 'b': {'n': bc_val}}, where n is the unknown number. bc_arr = np.array([]) assign_dict = {'a': self.ya, 'b': self.yb} # Get the bcs from the dictionary. for key, value in self.bcs.items(): for key_, value_ in value.items(): if key_ == 'y': bc_ix = 0 elif key_.isdigit( ): # If it is a digit, the user's input was a system of 1st order ODES. bc_ix = int(key_) - 1 else: temp_der = sp.parse_expr(key_, local_dict={ 'x': self.x, 'y': self.y }) bc_ix = temp_der.derivative_count bc_arr = np.append(bc_arr, assign_dict[key][bc_ix] - value_) return bc_arr
def symparse_items(arr, idx=0): i = idx while i < len(arr): item = arr[i] item = sympy.parse_expr(item) arr[i] = item i += 1
def solve_ixl(): while True: try: user_input = input() if user_input == "e": print("exiting a2.a1...\n") break expression = parse_expr(user_input) variables = expression.free_symbols variable_value_pairs = [ ] # create a list of 2-tuples: item 1 is the variable, item 2 is its value for variable in variables: # ask the user what each variable's value is; cast to int since this ixl only deals with integers substitution = int(input(str(variable) + " = ")) variable_value_pairs.append((variable, substitution)) answer = str(int(expression.subs(variable_value_pairs))) print(answer + "\n") copy(answer) except Exception as e: print(str(e) + "\n")
def __init__(self, objective, constraints, need_parse): # Create the objective/constraint function and obtain its variables if need_parse: self.f0: sp.Function = sp.parse_expr(objective) self.fi = [sp.parse_expr(func) for func in constraints] else: self.f0 = objective self.fi = constraints self.variables = set(self.f0.free_symbols) for cons in self.fi: self.variables.update(cons.free_symbols) self.variables = sorted(list(self.variables), key=lambda var: var.name) self.num_variables = len(self.variables) self.m = len(constraints)
def solve_eq(equation): equation = format_eq(equation) solved = [] try: with time_limit(1): sol = solve(Eq(parse_expr(equation), 0), dict=True) for solution in sol: for k in solution.keys(): if "I" not in str(solution[k]): solution[k] = round( eval( str(solution[k]), { "sqrt": sqrt, "sin": sin, "cos": cos, "tan": tan, "log": log, }, ), 3, ) solved.append(f"{k} = {solution[k]}") except Exception as e: if isinstance(e, TimeoutError): return "Timed Out! Calculation exceeded 1 second!" return "Invalid Input" return solved
def run_test(self, test): evaluation = self.get_kernel().get_kext('eval') test.assertEqual(evaluation.evaluate_code('Integrate[x, x]'), parse_expr('x**2/2')) test.assertEqual(evaluation.evaluate_code('Integrate[x, {x, 0, 1}]'), 1 / 2) test.assertEqual( evaluation.evaluate_code('Integrate[x * y, {x, 0, 1}, {y, 0, 1}]'), 1 / 4) test.assertEqual( evaluation.evaluate_code('Integrate[1/(x^3 + 1), {x, 0, 1}]'), parse_expr('log(2)/3 + sqrt(3)*pi/9'))
def make_expression(expr: str) -> sympy: """Turns a string into a nice sympy expression""" transformations = standard_transformations + ( implicit_multiplication_application, convert_xor, ) return sympy.parse_expr(expr, transformations=transformations)
def run_test(self, test): evaluation = self.get_kernel().get_kext('eval') test.assertEqual(evaluation.evaluate_code('Simplify[x^2-1]'), sp.parse_expr('(x - 1)*(x + 1)')) test.assertEqual( evaluation.evaluate_code('Simplify[Sin[x]^2+Cos[x]^2]'), 1)
def parse(self, expression, check_num): try: expr = parse_expr(expression, transformations=standard_transformations) if self.is_digit(expr.subs(x, check_num)): return expr return False except Exception: return False
def function_cleaner(func: str, dbg: bool = False) -> sp.Function: try: if "^" in func: raise SyntaxError else: return sp.parse_expr(func) except SyntaxError or TypeError: pass func_dict = {'^': '**', 'e': 'E'} trans_table = func.maketrans(func_dict) translated = func.translate(trans_table) if translated[0] != "+" and translated[0] != "-": translated = "+" + translated monomialsToBeConverted = re.findall(r"[+|\-][0-9]+[a-z]", translated) if dbg: print(monomialsToBeConverted) def multiply_var(mono: list) -> list: joined = list() for x in mono: variables = re.search(r"[a-z]", x) if not variables: joined.append(x) else: joined.append(x[:variables.start()] + "*" + x[variables.start():]) return joined replacementTerms = multiply_var(monomialsToBeConverted) if dbg: print(replacementTerms) for monomial in range(len(monomialsToBeConverted)): translated = translated.replace(monomialsToBeConverted[monomial], replacementTerms[monomial]) if dbg: print(translated) return sp.parse_expr(translated)
def get_contraction(bb, ioh): while True: print("Input expression for contraction") action = input(L_PROMPT) try: f = sp.parse_expr(action) except Exception as e: print(f"Error: {e} is not a valid logical expression.") return f, None
def showResults(self): console.highlight("7. Finalmente, podemos decir:") print("x = {}".format(self.x_value[0])) self.equation_y = sp.parse_expr(str(self.y_value_in_x[0])) self.y_value = self.equation_y.subs(self.x, int(self.x_value[0])) print("y = {} => {}".format(str(self.y_value_in_x[0]), self.y_value)) if int(self.x_value[0]) == int(self.y_value): print("La figura es un cuadrado por tener los mismos valores para X y Y") print("\nEl valor de la funcion A(x,y) = x.y") print("A(x,y) = {}".format(self.equation_area.subs( {self.x: int(self.x_value[0]), self.y: int(self.y_value)})))
def __init__(self, problem_strs: ProblemStrs, grid_params: GridParams): self.equation = sympy.parse_expr(problem_strs.equation) self.L_boundary_conditions = [ sympy.parse_expr(bound_condition) for bound_condition in problem_strs.L_boundary_conditions ] self.R_boundary_conditions = [ sympy.parse_expr(bound_condition) for bound_condition in problem_strs.R_boundary_conditions ] if problem_strs.initial_condition: self.initial_condition = sympy.parse_expr( problem_strs.initial_condition) if problem_strs.analytical_solution: self.analytical_solution = sympy.parse_expr( problem_strs.analytical_solution) self.coordinate_system = problem_strs.coordinate_system self.grid_params = grid_params
def calc(expr_str: str, *, vars: Optional[dict[str, any]] = None) -> Any: if vars is None: vars = {} # evaluate=Trueだとeval()を使ってしまうっぽい # ただし、 When evaluate=False, some automatic simplifications will not occur: # # 追記: 嘘。どちらにしろ呼ばれる。 https://github.com/sympy/sympy/blob/fb2d299937fbfd608b61d368466e4b914f96c861/sympy/parsing/sympy_parser.py#L1017 # evaluateのTrue/Falseに関わらずevalが呼ばれてしまう。evaluate=Falseの時にはcompileして実行 expr = parse_expr(expr_str, local_dict={"π": pi, "e": E}, evaluate=False) syms = {Symbol(name): val for name, val in vars.items()} return expr.evalf(subs=syms)
def _loads_symbolic_expr(expr_bytes): from sympy import parse_expr if expr_bytes == b"": return None expr_txt = zlib.decompress(expr_bytes).decode(common.ENCODE) expr = parse_expr(expr_txt) if _optional.HAS_SYMENGINE: from symengine import sympify return sympify(expr) return expr
def bisection_method(): func = request.form['function'] rang = float(request.form['min_value']), float(request.form['max_value']) exp = sym.parse_expr(func) root, err, i = nm.bisection_method(sym.lambdify(x, exp), *rang) return { 'input_function': sym.latex(exp), 'range': rang, 'root': root, 'err': err, 'iterations': i }
def run_test(self, test): evaluation = self.get_kernel().get_kext('eval') test.assertEqual(evaluation.evaluate_code( 'Sqrt[-1]'), evaluation.evaluate_code('I')) test.assertEqual(evaluation.evaluate_code( 'Sqrt[2]'), sp.parse_expr('sqrt(2)')) test.assertEqual(evaluation.evaluate_code( 'Sqrt[25]'), 5) test.assertEqual(evaluation.evaluate_code( 'Sqrt[2.0]'), 1.4142135623730951)
def high_node_cse(expr_g, reuse_thresh, rename_prefix="DENDRO_", dep_thresh=0): G = expr_g._G_ expr_dict = dict(expr_g._sympy_expr) n_list=list() for n in G.nodes(): if(G.in_degree(n)>=reuse_thresh and G.out_degree(n) >dep_thresh ): n_list.append((G.in_degree(n),n)) n_list.sort(key=lambda x : x[0],reverse=True) cse_list=list() for node in n_list: expr = sympy.parse_expr(str(node[1])) cse_list.append(expr) # original list of expressions that we will eliminate cse_renamed_list = list(cse_list) # tuple list containing replacement (j,i) expression_i is a subset in expression_j replace_idx=list() for i,expr_i in enumerate(cse_list): for j,expr_j in enumerate(cse_list): if (i < j and is_sub_expr(expr_j,expr_i)): replace_idx.append((j,i)) # elimination of the CSE in the selected sub expressions. for (expr_i,sub_i) in replace_idx: cse_renamed_list[expr_i] = expr_term_rewrite(cse_renamed_list[expr_i],cse_renamed_list[sub_i],sympy.Symbol(rename_prefix + str(sub_i))) # now replace sub expressions in the actual main expressions. for (k,expr) in expr_dict.items(): print("expr renaming for ", k) for i,sub_expr in enumerate(cse_list): if is_sub_expr(expr,sub_expr): expr=expr_term_rewrite(expr,sub_expr,sympy.Symbol(rename_prefix + str(i))) expr_dict[k]=expr #for (k,expr) in expr_dict.items(): # print("expr name : %s expression %s " %(k,expr)) cse_dict=dict() for i,expr in enumerate(cse_renamed_list): cse_dict[rename_prefix+str(i)]=expr return [cse_dict,expr_dict]
def getAreaFunction(self): console.highlight("2. Obtenemos el valor de y a partir del perimetro") print("2x + 2y = {}".format(perimeter)) self.y_value_in_x = sp.solve( sp.Eq(self.equation_perimeter, self.perimeter), self.y) print("y = {}".format(str(self.y_value_in_x[0]))) console.highlight("3. Reemplazamos el valor de y en la funcion A(x,y)") str_equation_area = 'x*({})'.format(str(self.y_value_in_x[0])) self.equation_area_x = sp.parse_expr(str_equation_area) print("A(x,y) = {}".format(self.equation_area_x)) print("\nPodemos decir: ") print("A(x) = {}".format(self.equation_area_x)) console.printHyphen()
def fixed_point_iteration(): func = request.form['function'] rang = float(request.form['min_value']), float(request.form['max_value']) max_iterations = int(request.form['max_iterations']) exp = sym.parse_expr(func) root, i, err = nm.fixed_point_iteration(sym.lambdify(x, exp), *rang, max_iterations=max_iterations) return { 'input_function': sym.latex(exp), 'range': rang, 'root': root, 'iterations': i, 'error_percentage': 1 - err }
def add_transition(self, from_node: str, to_node: str, transition_rate: str, label: str = None, update=False) -> None: """Adds an edge describing the transition rate between `from_node` and `to_node`. :param from_node: The state that the transition rate is incident from :param to_node: The state that the transition rate is incident to :param transition rate: A string identifying this transition with a rate from self.rates. :param update: If false and exception will be thrown if an edge between from_node and to_node already exists """ if from_node not in self.graph.nodes or to_node not in self.graph.nodes: raise Exception( "A node wasn't present in the graph ({} or {})".format( from_node, to_node)) if not isinstance(transition_rate, str): transition_rate = str(transition_rate) # First check that all of the symbols in sp.expr are defined (if it exists) if transition_rate is not None: for expr in sp.parse_expr(transition_rate).free_symbols: if str(expr) not in self.rates: self.add_rate(str(expr)) if transition_rate not in self.rates: self.rates.add(transition_rate) if label is None: label = transition_rate if (from_node, to_node) in self.graph.edges(): if update: self.graph.add_edge(from_node, to_node, rate=transition_rate, label=label) else: raise Exception( f"An edge already exists between {from_node} and {to_node}. \ Edges are {self.graph.edges()}") else: self.graph.add_edge(from_node, to_node, rate=transition_rate, label=label)
def solve_ixl(): while True: try: user_input = input() if user_input == "e": print("exiting a2.a3...\n") break expression = parse_expr(user_input) answer = str(simplify(expression)) print(answer + "\n") copy(answer) except Exception as e: print(str(e) + "\n")
def __init__(self, obj_function: str): # Create the objective function and obtain its variables f: sp.Function = sp.parse_expr(obj_function) self.variables = sorted(f.free_symbols, key=lambda var: var.name) self.num_variables = len(self.variables) # Create partial derivatives (gradients) based on the function self.orig_gradient = [f.diff(var) for var in self.variables] self.gradient = [ sp.lambdify(var, f.diff(var), modules='numpy') for var in self.variables ] # Create lambda-fied version of f so it can be used as an function self.f = sp.lambdify(self.variables, f, modules='numpy') self.orig_f = f