Scipy.sparse and problems
There are seven available sparse matrix types in scipy.sparse
:
csc_matrix
: Compressed Sparse Column formatcsr_matrix
: Compressed Sparse Row formatbsr_matrix
: Block Sparse Row formatlil_matrix
: List of Lists formatdok_matrix
: Dictionary of Keys formatcoo_matrix
: COOrdinate format (aka IJV, triplet format)dia_matrix
: DIAgonal format
As indicated by the excellent
documentation, the
dok_matrix
or lil_matrix
formats are preferable to construct matrices as they
support basic slicing and indexing similar to a standard NumPy array.
You will notice that the FD matrix we have constructed for the Poisson problem is
composed entirely of diagonal elements, as is often the case. If you were constructing a
similar matrix in MATLAB, you would use the
spdiags
function, and
scipy.sparse
has its own
equivalent.
However, all the scipy.sparse
formats also have special methods
setdiag
which provide a more object-orientated method of doing the same thing.
Scipy has a few different direct solvers for sparse matrics, given below:
spsolve
:
This solves where is converted into CSC or CSR form
spsolve_triangular
:
Solves , where is assumed to be triangular.
factorized
:
This computes the decomposition of the input matrix , returning a Python
function that can be called to solve
splu
:
This computes the decomposition of the input matrix using the popular SuperLU
library. It returns a Python object of class
SuperLU
,
that has a solve
method you can use to solve
Note, scipy.sparse.linalg
also has many iterative solvers, which we will investigate
further in the next chapter.
Problems
Your goal for this problem is to construct the FD matrix given above, using
scipy.sparse
, and:
Visualise Poisson Matrix
Visualise the matrix using the Matplotlib spy
plot
Solve Poisson problem
Solve the Poisson problem using:
, with boundary conditions and . The analytical solution is .
, with boundary conditions and . The analytical solution is
Sparse versus dense: matrix multiplication
Vary the number of discretisation points and calculate using both sparse and
dense matrices. For each calculate the time to calculate the matix
multiplicatiion using Python's
time.perf_counter
,
and plot execution time versus for dense and sparse matrix multiplication.
Comment on how the time varies with .
Sparse versus dense: solving Poisson problem
Vary the number of discretisation points and solve the Poisson problem with varying , and with using both the sparse and direct solvers. For each record the time taken for both the dense and sparse solvers, and record the numerical error . Generate plots of both error and time versus , and comment on how they vary with