2016-09-16 53 views
3

我想接收來自用戶的輸入,解析它,然後對結果表達式執行一些替換。我知道我可以使用sympy.parsing.sympy_parser.parse_expr解析來自用戶的任意輸入。但是,我在替換函數定義時遇到了問題。是否有可能以這種方式進行替代,如果是這樣,我該怎麼做?替補函數調用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))) 

replace也有其它選擇,如模式匹配。

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