Skip to content

scipy/solve-in-loop

Rule solve-in-loop
Pack SciPy
Severity warning
Fix none, edit by hand
Library versions every version

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

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

xpd prints this message with the issue. A name that starts with $ stands for code from your file.

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.

Browse the other rules of the SciPy pack.