15.12.2012 Views

scipy tutorial - Baustatik-Info-Server

scipy tutorial - Baustatik-Info-Server

scipy tutorial - Baustatik-Info-Server

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

SciPy Reference Guide, Release 0.8.dev<br />

3.14 Sparse matrices (<strong>scipy</strong>.sparse)<br />

3.14.1 Sparse Matrices<br />

Scipy 2D sparse matrix module.<br />

Original code by Travis Oliphant. Modified and extended by Ed Schofield, Robert Cimrman, and Nathan Bell.<br />

There are seven available sparse matrix types:<br />

1. csc_matrix: Compressed Sparse Column format<br />

2. csr_matrix: Compressed Sparse Row format<br />

3. bsr_matrix: Block Sparse Row format<br />

4. lil_matrix: List of Lists format<br />

5. dok_matrix: Dictionary of Keys format<br />

6. coo_matrix: COOrdinate format (aka IJV, triplet format)<br />

7. dia_matrix: DIAgonal format<br />

To construct a matrix efficiently, use either lil_matrix (recommended) or dok_matrix. The lil_matrix class supports<br />

basic slicing and fancy indexing with a similar syntax to NumPy arrays. As illustrated below, the COO format may<br />

also be used to efficiently construct matrices.<br />

To perform manipulations such as multiplication or inversion, first convert the matrix to either CSC or CSR format.<br />

The lil_matrix format is row-based, so conversion to CSR is efficient, whereas conversion to CSC is less so.<br />

All conversions among the CSR, CSC, and COO formats are efficient, linear-time operations.<br />

3.14.2 Example 1<br />

Construct a 1000x1000 lil_matrix and add some values to it:<br />

>>> from <strong>scipy</strong> import sparse, linsolve<br />

>>> from numpy import linalg<br />

>>> from numpy.random import rand<br />

>>> A = sparse.lil_matrix((1000, 1000))<br />

>>> A[0, :100] = rand(100)<br />

>>> A[1, 100:200] = A[0, :100]<br />

>>> A.setdiag(rand(1000))<br />

Now convert it to CSR format and solve A x = b for x:<br />

>>> A = A.tocsr()<br />

>>> b = rand(1000)<br />

>>> x = linsolve.spsolve(A, b)<br />

Convert it to a dense matrix and solve, and check that the result is the same:<br />

>>> x_ = linalg.solve(A.todense(), b)<br />

Now we can compute norm of the error with:<br />

348 Chapter 3. Reference

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!