简体   繁体   English

加快sympy矩阵运算

[英]speeding up sympy matrix operations

I have written a code, which uses sympy to set up a matrix and a vector. 我已经编写了一个代码,该代码使用sympy来设置矩阵和向量。 The elements of these two are sympy symbols. 这两个的元素是sympy符号。 Then I invert the matrix and multiply the inverted matrix and the vector. 然后,我将矩阵求逆,并将求逆的矩阵与向量相乘。 This should be a generic solver for linear equation systems with n variables. 这应该是具有n个变量的线性方程组的通用求解器。 I am interested in the symbolic solution of these linear equations. 我对这些线性方程的符号解感兴趣。 The problem is that my code is too slow. 问题是我的代码太慢了。 For instance, for n=4 it takes roughly 30 sec but for n=7 I haven't been able to solve it so far, the code ran all night (8h) and hasn't finished in the morning. 例如,对于n = 4,大约需要30秒,但是对于n = 7,我到目前为止还无法解决,代码运行了一整夜(8h),并且没有在早上完成。 This is my code. 这是我的代码。

from sympy import * 
import pprint 

MM = Matrix(niso,1, lambda i,j:var('MM_%s' % (i+1) ))
MA = Matrix (niso,1, lambda i,j:var('m_%s%s' % ('A', chr(66+i)) ) )
MX = Matrix (niso,1, lambda i,j:var('m_%s%s'% (chr(66+i), 'A')))
RB = Matrix(niso,1, lambda i,j:var('R_%s%s' % ('A'+chr(66+i),i+2)))
R = Matrix (niso, niso-1, lambda i,j: var('R_%s%d' % (chr(65+i) , j+2 )))
K= Matrix(niso-1,1, lambda i,j:var('K_%d' % (i+2) ) )
C= Matrix(niso-1,1, lambda i,j:var('A_%d' % i))

A = Matrix(niso-1,niso-1, lambda i,j:var('A_%d' % i))
b = Matrix(niso-1,1, lambda i,j:var('A_%d' % i))

for i in range(0,niso-1):
        for j in range(0,niso-1):
            A[i,j]=MM[j+1,0]*(Add(Mul(R[0,j],1/MA[i,0]/(RB[i,0]-R[0,i])))+R[i+1,j]/MX[i,0]/(-RB[i,0]+R[0,i]))

for i in range(0,niso-1):
    b[i,0]=MM[0,0]*(Add(Mul(1,1/MA[i,0]/(RB[i,0]-R[0,i])))+1/MX[i,0]/(-RB[i,0]+R[0,i]))


A_in = Inverse(A)
if niso <= 4:
    X =simplify(A_in*b)
if niso > 4:
    X = A_in*b
pprint(X)

Is there a way to speed it up? 有没有办法加快速度?

Don't invert! 不要反转! With n=4 n=4

%timeit soln = A.LUsolve(b)
697 µs ± 12.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

With n=10 n=10

%timeit soln = A.LUsolve(b)
431 ms ± 13 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM