Ejemplo n.º 1
0
def sympy_to_str(sympy_expr):
    '''
    sympy_to_str(sympy_expr)

    Converts a sympy expression into a string. This could be as easy as 
    ``str(sympy_exp)`` but it is possible that the sympy expression contains
    functions like ``Abs`` (for example, if an expression such as
    ``sqrt(x**2)`` appeared somewhere). We do want to re-translate ``Abs`` into
    ``abs`` in this case.
    
    Parameters
    ----------
    sympy_expr : sympy.core.expr.Expr
        The expression that should be converted to a string.
        
    Returns
    str_expr : str
        A string representing the sympy expression.
    '''
    orig_sympy_expr = sympy_expr

    # replace the standard functions by our names if necessary
    replacements = dict(
        (f.sympy_func, sympy.Function(name))
        for name, f in DEFAULT_FUNCTIONS.items()
        if f.sympy_func is not None and isinstance(
            f.sympy_func, sympy.FunctionClass) and str(f.sympy_func) != name)
    # replace constants with our names as well
    replacements.update(
        dict((c.sympy_obj, sympy.Symbol(name))
             for name, c in DEFAULT_CONSTANTS.items()
             if str(c.sympy_obj) != name))

    # Replace the placeholder argument by an empty symbol
    replacements[sympy.Symbol('_placeholder_arg')] = sympy.Symbol('')
    atoms = (sympy_expr.atoms()
             | {f.func
                for f in sympy_expr.atoms(sympy.Function)})
    for old, new in replacements.items():
        if old in atoms:
            sympy_expr = sympy_expr.subs(old, new)
    expr = PRINTER.doprint(sympy_expr)

    return expr
Ejemplo n.º 2
0
from brian2.core.functions import DEFAULT_FUNCTIONS, DEFAULT_CONSTANTS
from brian2.core.variables import AuxiliaryVariable
from brian2.parsing.bast import (brian_ast, BrianASTRenderer, dtype_hierarchy,
                                 brian_dtype_from_dtype,
                                 brian_dtype_from_value)
from brian2.parsing.rendering import NodeRenderer
from brian2.utils.stringtools import get_identifiers, word_substitute
from brian2.units.fundamentalunits import DIMENSIONLESS
from brian2.core.preferences import prefs

from .statements import Statement

# Default namespace has all the standard functions and constants in it
defaults_ns = dict((k, v.pyfunc) for k, v in DEFAULT_FUNCTIONS.items())
defaults_ns.update(dict((k, v.value) for k, v in DEFAULT_CONSTANTS.items()))

__all__ = ['optimise_statements', 'ArithmeticSimplifier', 'Simplifier']


def evaluate_expr(expr, ns):
    '''
    Try to evaluate the expression in the given namespace

    Returns either (value, True) if successful, or (expr, False) otherwise.
    '''
    try:
        val = eval(expr, ns)
        return val, True
    except NameError:
        return expr, False