pythonnumpyfunctiontype-conversionnumpy-ufunc

How Can I Convert a String to a Ufunc?


I am trying to write a simple function that converts an input written in LaTeX to a ufunc that can be read by numpy. So far, I'm testing the function by converting \sin(x) to np.sin(x) (ignoring the conversion from {} to (). I'm not that familiar with ufuncs so I keep running into an error when trying to convert the \sin(x) string to the np.sin(x) ufunc for any given x.

import numpy as np

latexEq = input()

def latexMap(latexEq):
    if "\sin" in latexEq:
        sinLatex = latexEq.replace("\sin", "np.sin")
    else:
        pass
    return sinLatex

npOutput = np.ufunc(latexMap(latexEq))
print(f"f(x)={numpyOutput}")

Similar to how an integer may be converted into a string str(2), I tried enclosed both sinLatex, latexEq, "np.sin", and npOutput but the error I always receive is

TypeError: cannot create 'numpy.ufunc' instances

Any explanation would be appreciated.


Solution

  • So if you just have npOutput = "np.sin" (without the (x)) you can do

    # function_name = getattr(module, function_name_string)
    npOutput = getattr(np, npOutput.lstrip("np."))
    

    which gives you the function np.sin. The parentheses have to be gone because otherwise it would be a function call, not a function.