Skip to content

scipy/solve-in-loop

Pack Severity Fix Versions
SciPy warning none, edit by hand All versions

spsolve or solve inside a loop factors the same matrix again on every pass. Factor it once before the loop with splu, then call lu.solve in the loop.

xs = [spsolve(A, b) for b in sides]
lu = splu(A.tocsc())
xs = [lu.solve(b) for b in sides]

The rule reports scipy.sparse.linalg.spsolve(A, b) and scipy.linalg.solve(A, b) inside a comprehension or a loop that doesn't assign A or take it as its loop name. Each call factors A again, and factoring once was faster:

Matrix Right sides Factoring once was faster by
sparse, 10,000 rows 100 17 to 20 times
dense, 1,000 by 1,000 20 18 to 23 times

The matrix argument must be a name. An expression such as A + s * I can change with each pass and is left alone.

xpd has no automatic fix, so make the change by hand.

For a sparse matrix, convert to CSC once, call splu before the loop and reuse its solve method. For a dense matrix, call lu_factor before the loop and reuse the factorization with lu_solve.

spsolve factors $A again on every pass of this loop. Factor it once before the loop with lu = splu($A.tocsc()) from scipy.sparse.linalg, then call lu.solve(b) in the loop, which ran 17 to 20 times faster for 100 right sides.

See all rules in the SciPy pack.