klu_solve

sksparse.klu.klu_solve(A, b, *, control=None, transpose=False, rhs_batch_size=100, **kwargs)[source]

Solve a linear system using KLU.

This function solves a linear system for \(x\) given the right-hand side \(b\) as either a vector or a matrix with multiple right-hand sides.

If transpose=False, solve

\[A x = b\]

or, if transpose=True, solve

\[x A = b \Longleftrightarrow A^{\top} x^{\top} = b^{\top}.\]

This is a convenience function that creates a KLUFactor object, computes the numeric factorization, and solves the linear system with KLUFactor.solve().

Parameters:
  • A ((N, N) numpy.ndarray or sparse array) – The input matrix to factorize.

  • b ((N,) or (N, K) numpy.ndarray) – The right-hand side vector or matrix.

  • control (KLUControl, optional) – An optional KLUControl object to set the factorization parameters. If not provided, default parameters are used.

  • transpose (bool, optional) – If True, solve \(x A = b\), otherwise, solve \(A x = b\).

  • rhs_batch_size (int, optional) – If b is a 2D sparse array, this parameter controls the number of columns to be solved simultaneously. A larger number will increase memory consumption by converting more columns at a time to dense arrays, but may improve runtime.

  • **kwargs – Additional keyword arguments passed to the KLUControl constructor.

Returns:

x ((N,) or (N, K) numpy.ndarray or sparse array) – The solution vector or matrix of the same type and shape as the input right-hand side b.

See also

KLUFactor, klu_solve

Added in version 0.5.0.

Examples

See: Davis, Timothy A. (2006). Direct Methods for Sparse Linear Systems, p 74 (Figure 5.1)

>>> import numpy as np
>>> from scipy import sparse
>>> from sksparse.klu import klu_solve
>>> N = 8
>>> rows = np.array(
...    [0, 1, 2, 3, 4, 5, 6, 3, 6, 1, 6, 0, 2, 5, 7, 4, 7, 0, 1, 3, 7, 5, 6],
...    dtype=np.int32,
...)
>>> cols = np.array(
...    [0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7],
...    dtype=np.int32,
...)
>>> vals = np.ones(len(rows), dtype=np.float64)
>>> vals[:7] = np.arange(1, 8, dtype=np.float64)  # make diagonal entries non-unit
>>> A = sparse.csc_array((vals, (rows, cols)), shape=(N, N))
>>> A
<Compressed Sparse Column sparse array of dtype 'float64'
        with 23 stored elements and shape (8, 8)>
>>> # Solve a linear system
>>> expect_x = np.arange(N, dtype=np.float64)
>>> b = A @ expect_x
>>> x = klu_solve(A, b)
>>> np.allclose(x, expect_x)
True