Python/Numpy/Scipy - Converting string to mathematical function
Asked Answered
P

1

6

I am in the somewhat unfortunate position to try to convert a program from the depths of CERN ROOT to python. In ROOT code (CINT in itself is an abomination imo), one can store mathematical functions as a "string" and pass these along to ROOT for fitting, plotting, etc. because of how ROOT defines these as "strings."

At the moment, the mathematical functions are stored in simple text files as a line, i.e.

(1+[1])^(1+[1])/TMath::Gamma(1+[1]) * x^[1]/[0]^(1+[1]) * exp(-(1+[1])*x/[0])

and are then extracted as strings by C++ when reading in the file. Is there something similar in python? I know of numexpr, but I cant seem to get it to work with the equivalent of the above, i.e.

(1+p[1])**(1+p[1])/scipy.special.Gamma(1+p[1]) * x**p[1]/p[0]**(1+p[1]) * numpy.exp(-(1+p[1])*x/p[0])

Thanks a bunch in advance.

Penutian answered 26/12, 2011 at 23:27 Comment(1)
you can call ROOT function from python, so you can create a ROOT.TF1 in python, as in C++Foust
I
10

Since, presumably, you can trust the strings to be non-malicious, you could build a string which defines a function which evaluates the expression and use exec to execute that string as a statement. For example,

import numpy as np
import scipy.special as special

expr='(1+p[1])**(1+p[1])/special.gamma(1+p[1]) * x**p[1]/p[0]**(1+p[1]) * np.exp(-(1+p[1])*x/p[0])'

def make_func(expr):
    funcstr='''\
def f(x,p):
    return {e}
    '''.format(e=expr)
    exec(funcstr)
    return f

f=make_func(expr)
print(f(1,[2,3]))

returns

0.360894088631
Ingate answered 26/12, 2011 at 23:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.