def expression_complexity(expr): ''' Returns the complexity of the expression defined as the sum of the number of leaves and nodes of the tree. TODO: better definition? ''' if isinstance(expr, str): expr = parse_to_sympy(expr) if len(expr.args)==0: return 1 else: return 1+sum(map(expression_complexity, expr.args))
def replace_func(x, t, expr, temp_vars): ''' TODO ''' s_expr = parse_to_sympy(expr, local_dict=self.symbols) for var in eqs.eq_names: temp_vars_specific = dict([('_' + temp_var + '_' + var, Symbol('_' + temp_var + '_' + var)) for temp_var in temp_vars]) self.symbols.update(temp_vars_specific) temp_var_replacements = dict([(temp_var, temp_vars_specific['_' + temp_var + '_' + var]) for temp_var in temp_vars]) one_replacement = x.subs(SYMBOLS['x'], variables[var]) one_replacement = one_replacement.subs(temp_var_replacements) s_expr = s_expr.subs(variables[var], one_replacement) # replace time (important for time-dependent equations) s_expr.subs(SYMBOLS['t'], t) return s_expr
def __init__(self, description): try: parsed = DESCRIPTION.parseString(description, parseAll=True) except ParseException as p_exc: raise SyntaxError('Parsing failed: \n' + str(p_exc.line) + '\n' + ' '*(p_exc.column - 1) + '^\n' + str(p_exc)) self.statements = [] self.symbols = SYMBOLS.copy() for element in parsed: # Make sure to always re-use symbol objects for known symbols, # otherwise the replacements go wrong expression = parse_to_sympy(element.expression, local_dict=self.symbols) symbols = list(expression.atoms(Symbol)) self.symbols.update(dict([(symbol.name, symbol) for symbol in symbols])) if element.getName() == 'statement': self.statements.append((element.identifier, expression)) elif element.getName() == 'output': self.output = expression else: raise AssertionError('Unknown element name: %s' % element.getName())
def __init__(self, code, namespace=None, exhaustive=True, level=0): super(Expression, self).__init__(code, namespace, exhaustive, level + 1) self._sympy_expr = parse_to_sympy(self.code)
def translate_expression(self, expr): expr = parse_to_sympy(expr) return CCodePrinter().doprint(expr)