我使用lambdify来编译一个表达式,该表达式是某些参数的函数。每个参数都有N点。因此,我需要评估表达式N次。下面显示了有关此操作的简化示例。

import numpy as np
from sympy.parsing.sympy_parser import parse_expr
from sympy.utilities.lambdify import lambdify, implemented_function
from sympy import S, Symbol
from sympy.utilities.autowrap import ufuncify


def CreateMagneticFieldsList(dataToSave,equationString,DSList):

    expression  = S(equationString)
    numOfElements = len(dataToSave["MagneticFields"])

    #initialize the magnetic field output array
    magFieldsArray    = np.empty(numOfElements)
    magFieldsArray[:] = np.NaN

    lam_f = lambdify(tuple(DSList),expression,modules='numpy')
    try:
        for i in range(numOfElements):
            replacementList = np.zeros(len(DSList))


            for j in range(len(DSList)):
                replacementList[j] = dataToSave[DSList[j]][i]

            try:
                val = np.double(lam_f(*replacementList))

            except:
                val = np.nan
            magFieldsArray[i] = val
    except:
        print("Error while evaluating the magnetic field expression")
    return magFieldsArray


list={"MagneticFields":list(range(10000)), "Chx":list(range(10000))}

out=CreateMagneticFieldsList(list,"MagneticFields*5+Chx",["MagneticFields","Chx"])

print(out)


有没有办法进一步优化此通话?具体来说,我的意思是有一种方法可以使lambdify包括我正在计算的点列表,以便可以优化循环评估?

最佳答案

感谢@asmeurer,他给出了如何做的想法。

由于lambdify是使用numpy编译的,因此可以简单地将列表作为参数传递!以下是一个工作示例

#!/usr/bin/python3

import numpy as np
from sympy.parsing.sympy_parser import parse_expr
from sympy.utilities.lambdify import lambdify, implemented_function
from sympy import S, Symbol
from sympy.utilities.autowrap import ufuncify


def CreateMagneticFieldsListOpt(dataToSave,equationString,DSList):

    expression  = S(equationString)
    numOfElements = len(dataToSave["MagneticFields"])

    #initialize the magnetic field output array
    magFieldsArray    = np.empty(numOfElements)
    magFieldsArray[:] = np.NaN

    lam_f = lambdify(tuple(DSList),expression,modules='numpy')
    replacementList = [None]*len(DSList)

    for j in range(len(DSList)):
        replacementList[j] = np.array(dataToSave[DSList[j]])
    print(replacementList)

    magFieldsArray = np.double(lam_f(*replacementList))


    return magFieldsArray

list={"MagneticFields":[1,2,3,4,5],"ChX":[2,4,6,8,10]}

out=CreateMagneticFieldsListOpt(list,"MagneticFields*5+ChX",["MagneticFields","ChX"])

print(out)

08-19 01:28