Python / Numpy / Scipy - Convert string to math function

In some unsuccessful situation, I am trying to convert a program from the depths of CERN ROOT to python. In the ROOT code (CINT itself is an abomination of imo), you can store mathematical functions as a "string" and pass them along with ROOT for fitting, building, etc. Because of how ROOT defines them as "strings".

Currently, mathematical functions are stored in simple text files as a string, i.e.

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

and then retrieved as C ++ strings when read in a file. Is there something similar in python? I know about numexpr, but I cannot get it to work with the equivalent 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 for the bunch in advance.

+6
source share
1 answer

Since, presumably, you can trust strings to be harmless, you could build a string that defines a function that evaluates the expression and uses exec to execute that string as an instruction. For instance,

 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 
+8
source

Source: https://habr.com/ru/post/904509/


All Articles