2016-09-16 11 views
3

私は、ユーザーからの入力を受け取り、解析し、結果の式に対していくつかの置換を実行したいと考えています。私はsympy.parsing.sympy_parser.parse_exprを使用して、ユーザーからの任意の入力を解析できることを知っています。しかし、関数定義を代入するのに問題があります。このようにして補助金を出すことは可能ですか?もしそうなら、どうすればいいですか?代用関数呼び出しwith sympy

全体的な目標は、ユーザーがxの機能を提供できるようにすることです。この機能は、データの格納に使用されます。 parse_exprは私にその道の95%を与えますが、以下に示すような便利な拡張を提供したいと思います。

import sympy 
from sympy.parsing.sympy_parser import parse_expr 

x,height,mean,sigma = sympy.symbols('x height mean sigma') 
gaus = height*sympy.exp(-((x-mean)/sigma)**2/2) 

expr = parse_expr('gaus(100, 5, 0.2) + 5') 

print expr.subs('gaus',gaus)         # prints 'gaus(100, 5, 0.2) + 5' 
print expr.subs(sympy.Symbol('gaus'),gaus)     # prints 'gaus(100, 5, 0.2) + 5' 
print expr.subs(sympy.Symbol('gaus')(height,mean,sigma),gaus) # prints 'gaus(100, 5, 0.2) + 5' 

# Desired output: '100 * exp(-((x-5)/0.2)**2/2) + 5' 

これは、python 2.7.9、sympy 0.7.5を使用して行われます。

答えて

2

replaceメソッドを使用できます。たとえば、

gaus = Function("gaus") # gaus is parsed as a Function 
expr.replace(gaus, Lambda((height, mean, sigma), height*sympy.exp(-((x-mean)/sigma)**2/2))) 

には、パターンマッチングなどの他のオプションもあります。

0

いくつかの実験の後で、私は組み込みの解決策を見つけられませんでしたが、単純なケースを満たすものを構築することは困難ではありませんでした。私はsympyエキスパートではないので、私が考慮していないエッジケースがあるかもしれません。

import sympy 
from sympy.core.function import AppliedUndef 

def func_sub_single(expr, func_def, func_body): 
    """ 
    Given an expression and a function definition, 
    find/expand an instance of that function. 

    Ex: 
     linear, m, x, b = sympy.symbols('linear m x b') 
     func_sub_single(linear(2, 1), linear(m, b), m*x+b) # returns 2*x+1 
    """ 
    # Find the expression to be replaced, return if not there 
    for unknown_func in expr.atoms(AppliedUndef): 
     if unknown_func.func == func_def.func: 
      replacing_func = unknown_func 
      break 
    else: 
     return expr 

    # Map of argument name to argument passed in 
    arg_sub = {from_arg:to_arg for from_arg,to_arg in 
       zip(func_def.args, replacing_func.args)} 

    # The function body, now with the arguments included 
    func_body_subst = func_body.subs(arg_sub) 

    # Finally, replace the function call in the original expression. 
    return expr.subs(replacing_func, func_body_subst) 


def func_sub(expr, func_def, func_body): 
    """ 
    Given an expression and a function definition, 
    find/expand all instances of that function. 

    Ex: 
     linear, m, x, b = sympy.symbols('linear m x b') 
     func_sub(linear(linear(2,1), linear(3,4)), 
       linear(m, b), m*x+b)    # returns x*(2*x+1) + 3*x + 4 
    """ 
    if any(func_def.func==body_func.func for body_func in func_body.atoms(AppliedUndef)): 
     raise ValueError('Function may not be recursively defined') 

    while True: 
     prev = expr 
     expr = func_sub_single(expr, func_def, func_body) 
     if prev == expr: 
      return expr