我正在研究SymPy对我的某些项目的适用性,并且遇到了lambdify和IndexedBase之间的交互问题。

简而言之,我的应用程序大量使用了采用两倍加总数组结构的函数。我需要能够针对数组元素计算函数以及函数的一阶到三阶导数。

因此,我的问题是:


如何让diff进行lambdify工作?
如何制作lambdify函数,在该函数中可以指定要派生的索引?
如何将以上内容扩展到具有不同索引的二阶导数(即相对于索引i和j的二阶)?


简化示例:

from sympy import IndexedBase, Idx, lambdify, Sum, diff
from numpy import array


i = Idx("i", range=(0,1))
j = Idx("j", range=(0,1))
n = IndexedBase("n")
coefficients = IndexedBase("C")

double_sum = Sum(Sum(n[i]*n[j]*coefficients[i,j],(i,i.lower,i.upper)),(j,j.lower,j.upper))
first_derivative = diff(double_sum, n[i])
second_derivative = diff(first_derivative, n[j])

test_function_1 = lambdify((n,coefficients),double_sum)
test_function_2 = lambdify((n,coefficients,i),first_derivative)
test_function_3 = lambdify((n,coefficients,i,j),second_derivative)

test_vector = array([1, 2])
test_coefficients = array([[1,1],[2,3]])

test_value_1 = test_function_1(test_vector,test_coefficients)
print(test_value_1)

test_value_2 = test_function_2(test_vector,test_coefficients,1)
print(test_value_2)

test_value_3 = test_function_3(test_vector,test_coefficients)
print(test_value_3)


执行此代码将产生错误:

File "<lambdifygenerated-2>", line 9, in _lambdifygenerated
File "<lambdifygenerated-2>", line 9, in <genexpr>
NameError: name 'KroneckerDelta' is not defined

最佳答案

索引表达式很有用,但是它们的派生有时比应有的要复杂,并且它们在lambdify上往往会出现问题。这是不使用索引的大致等效代码。不同之处在于,数组的大小是预先声明的,这使得可以使用symarray创建普通(非索引)符号的显式数组,对其进行处理以及对表达式进行lambdify。我以某种方式对它们进行了羔羊化处理,以使一阶导数以1列矩阵形式返回,而二阶导数以方矩阵形式返回(下面是另一种返回类型)。

from sympy import symarray, Add, lambdify, Matrix
from numpy import array

i_upper = 2
j_upper = 2
n = symarray("n", i_upper)
coefficients = symarray("C", (i_upper, j_upper))

double_sum = Add(*[n[i]*n[j]*coefficients[i, j] for i in range(i_upper) for j in range(j_upper)])
first_derivative = Matrix(i_upper, 1, lambda i, j: double_sum.diff(n[i]))
second_derivative = Matrix(i_upper, j_upper, lambda i, j: double_sum.diff(n[i], n[j]))

params = list(n) + list(coefficients.ravel())
test_function_1 = lambdify(params, double_sum)
test_function_2 = lambdify(params, first_derivative)
test_function_3 = lambdify(params, second_derivative)

test_vector = array([1, 2])
test_coefficients = array([[1, 1], [2, 3]])
test_params = list(test_vector) + list(test_coefficients.ravel())
test_value_1 = test_function_1(*test_params)
test_value_2 = test_function_2(*test_params)
test_value_3 = test_function_3(*test_params)


测试值分别为19[[8], [15]][[2, 3], [3, 6]]

另外,这些函数可以返回嵌套列表:

first_derivative = [double_sum.diff(n[i]) for i in range(i_upper)]
second_derivative = [[double_sum.diff(n[i], n[j]) for j in range(i_upper)] for i in range(i_upper)]


或NumPy数组:

first_derivative = array([double_sum.diff(n[i]) for i in range(i_upper)])
second_derivative = array([[double_sum.diff(n[i], n[j]) for j in range(i_upper)] for i in range(i_upper)])


这种方法的局限性:(a)在形成表达式时必须知道符号的数量; (b)不能接受索引ij作为lambdified函数的参数。

09-25 19:58