Substitute Function call with sympy
<p>I want to receive input from a user, parse it, then perform some substitutions on the resulting expression.  I know that I can use <code>sympy.parsing.sympy_parser.parse_expr</code> to parse arbitrary input from the user.  However, I am having trouble substituting in function definitions.  Is it possible to make subsitutions in this manner, and if so, how would I do so?</p>

<p>The overall goal is to allow a user to provide a function of <code>x</code>, which is then used to fit data.  <code>parse_expr</code> gets me 95% of the way there, but I would like to provide some convenient expansions, such as shown below.</p>

<pre><code>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'
</code></pre>

<p>This is done using python 2.7.9, sympy 0.7.5.</p>

<p>You can use the <code>replace</code> method. For instance</p>

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

<p><code>replace</code> also has other options, such as pattern matching. </p>

python sympy