[Scipy-svn] r6892 - in trunk/scipy: signal sparse sparse/linalg/dsolve sparse/linalg/eigen/arpack

scipy-svn@scip... scipy-svn@scip...
Sun Nov 14 04:01:37 CST 2010


Author: rgommers
Date: 2010-11-14 04:01:37 -0600 (Sun, 14 Nov 2010)
New Revision: 6892

Modified:
   trunk/scipy/signal/ltisys.py
   trunk/scipy/sparse/__init__.py
   trunk/scipy/sparse/linalg/dsolve/__init__.py
   trunk/scipy/sparse/linalg/eigen/arpack/arpack.py
Log:
DOC: merge wiki edits for sparse module and signal/ltisys.py

Modified: trunk/scipy/signal/ltisys.py
===================================================================
--- trunk/scipy/signal/ltisys.py	2010-11-14 10:01:15 UTC (rev 6891)
+++ trunk/scipy/signal/ltisys.py	2010-11-14 10:01:37 UTC (rev 6892)
@@ -315,17 +315,17 @@
         * 3: (zeros, poles, gain)
         * 4: (A, B, C, D)
 
-    U : ndarray or array-like (1D or 2D), optional
+    U : array_like (1D or 2D), optional
         An input array describing the input at each time T.  Linear
         interpolation is used between given times.  If there are
         multiple inputs, then each column of the rank-2 array
         represents an input.  If U is not given, the input is assumed
         to be zero.
-    T : ndarray or array-like (1D or 2D), optional
+    T : array_like (1D or 2D), optional
         The time steps at which the input is defined and at which the
         output is desired.  The default is 101 evenly spaced points on
         the interval [0,10.0].
-    X0 : ndarray or array-like (1D), optional
+    X0 : array_like (1D), optional
         The initial condition of the state vector.  If `X0` is not
         given, the initial conditions are assumed to be 0.
     kwargs : dict
@@ -583,50 +583,62 @@
 
 
 def impulse2(system, X0=None, T=None, N=None, **kwargs):
-    """Impulse response of a single-input continuous-time linear system.
+    """
+    Impulse response of a single-input, continuous-time linear system.
 
-    The solution is generated by calling `scipy.signal.lsim2`, which uses
-    the differential equation solver `scipy.integrate.odeint`.
 
     Parameters
     ----------
     system : an instance of the LTI class or a tuple describing the system.
         The following gives the number of elements in the tuple and
-        the interpretation.
+        the interpretation:
             2 (num, den)
             3 (zeros, poles, gain)
             4 (A, B, C, D)
-    T : 1D ndarray or array-like, optional
+    T : 1-D array_like, optional
         The time steps at which the input is defined and at which the
         output is desired.  If `T` is not given, the function will
         generate a set of time samples automatically.
-    X0 : 1D ndarray or array-like, optional
-        The initial condition of the state vector.  If X0 is None, the
-        initial conditions are assumed to be 0.
+    X0 : 1-D array_like, optional
+        The initial condition of the state vector.  Default: 0 (the
+        zero vector).
     N : int, optional
-        Number of time points to compute.  If `N` is not given, 100
-        points are used.
-    **kwargs :
-        Additional keyword arguments are passed on the function
+        Number of time points to compute.  Default: 100.
+    kwargs : various types
+        Additional keyword arguments are passed on to the function
         `scipy.signal.lsim2`, which in turn passes them on to
-        :func:`scipy.integrate.odeint`.  See the documentation for
-        :func:`scipy.integrate.odeint` for information about these
-        arguments.
+        `scipy.integrate.odeint`; see the latter's documentation for
+        information about these arguments.
 
     Returns
     -------
-    T : 1D ndarray
+    T : ndarray
         The time values for the output.
     yout : ndarray
         The output response of the system.
 
     See Also
     --------
-    scipy.signal.impulse
+    impulse, lsim2, integrate.odeint
 
     Notes
     -----
+    The solution is generated by calling `scipy.signal.lsim2`, which uses
+    the differential equation solver `scipy.integrate.odeint`.
+
     .. versionadded:: 0.8.0
+
+
+    Examples
+    --------
+
+    Second order system with a repeated root: x''(t) + 2*x(t) + x(t) = u(t)
+
+    >>> system = ([1.0], [1.0, 2.0, 1.0])
+    >>> t, y = impulse2(system)
+    >>> import matplotlib.pyplot as plt
+    >>> plt.plot(t, y)
+
     """
     if isinstance(system, lti):
         sys = system

Modified: trunk/scipy/sparse/__init__.py
===================================================================
--- trunk/scipy/sparse/__init__.py	2010-11-14 10:01:15 UTC (rev 6891)
+++ trunk/scipy/sparse/__init__.py	2010-11-14 10:01:37 UTC (rev 6892)
@@ -1,5 +1,174 @@
-"Sparse Matrix Support"
+"""
+Sparse Matrices
+===============
 
+SciPy 2-D sparse matrix package.
+
+Original code by Travis Oliphant.
+Modified and extended by Ed Schofield, Robert Cimrman, and Nathan Bell.
+
+There are seven available sparse matrix types:
+    1. csc_matrix: Compressed Sparse Column format
+    2. csr_matrix: Compressed Sparse Row format
+    3. bsr_matrix: Block Sparse Row format
+    4. lil_matrix: List of Lists format
+    5. dok_matrix: Dictionary of Keys format
+    6. coo_matrix: COOrdinate format (aka IJV, triplet format)
+    7. dia_matrix: DIAgonal format
+
+To construct a matrix efficiently, use either lil_matrix (recommended) or
+dok_matrix. The lil_matrix class supports basic slicing and fancy
+indexing with a similar syntax to NumPy arrays.  As illustrated below,
+the COO format may also be used to efficiently construct matrices.
+
+To perform manipulations such as multiplication or inversion, first
+convert the matrix to either CSC or CSR format. The lil_matrix format is
+row-based, so conversion to CSR is efficient, whereas conversion to CSC
+is less so.
+
+All conversions among the CSR, CSC, and COO formats are efficient,
+linear-time operations.
+
+Example 1
+---------
+Construct a 1000x1000 lil_matrix and add some values to it:
+
+>>> from scipy.sparse import lil_matrix
+>>> from scipy.sparse.linalg import spsolve
+>>> from numpy.linalg import solve, norm
+>>> from numpy.random import rand
+
+>>> A = lil_matrix((1000, 1000))
+>>> A[0, :100] = rand(100)
+>>> A[1, 100:200] = A[0, :100]
+>>> A.setdiag(rand(1000))
+
+Now convert it to CSR format and solve A x = b for x:
+
+>>> A = A.tocsr()
+>>> b = rand(1000)
+>>> x = spsolve(A, b)
+
+Convert it to a dense matrix and solve, and check that the result
+is the same:
+
+>>> x_ = solve(A.todense(), b)
+
+Now we can compute norm of the error with:
+
+>>> err = norm(x-x_)
+>>> err < 1e-10
+True
+
+It should be small :)
+
+
+Example 2
+---------
+
+Construct a matrix in COO format:
+
+>>> from scipy import sparse
+>>> from numpy import array
+>>> I = array([0,3,1,0])
+>>> J = array([0,3,1,2])
+>>> V = array([4,5,7,9])
+>>> A = sparse.coo_matrix((V,(I,J)),shape=(4,4))
+
+Notice that the indices do not need to be sorted.
+
+Duplicate (i,j) entries are summed when converting to CSR or CSC.
+
+>>> I = array([0,0,1,3,1,0,0])
+>>> J = array([0,2,1,3,1,0,0])
+>>> V = array([1,1,1,1,1,1,1])
+>>> B = sparse.coo_matrix((V,(I,J)),shape=(4,4)).tocsr()
+
+This is useful for constructing finite-element stiffness and mass matrices.
+
+Further Details
+---------------
+
+CSR column indices are not necessarily sorted.  Likewise for CSC row
+indices.  Use the .sorted_indices() and .sort_indices() methods when
+sorted indices are required (e.g. when passing data to other libraries).
+
+Package Contents
+================
+
+Modules
+-------
+
+.. autosummary::
+   :toctree: generated/
+
+   base - Base class for sparse matrices
+   bsr - Compressed Block Sparse Row matrix format
+   compressed - Sparse matrix base class using compressed storage
+   construct - Functions to construct sparse matrices
+   coo - A sparse matrix in COOrdinate or 'triplet' format
+   csc - Compressed Sparse Column matrix format
+   csgraph - Compressed Sparse graph algorithms
+   csr - Compressed Sparse Row matrix format
+   data - Base class for sparse matrice with a .data attribute
+   dia - Sparse DIAgonal format
+   dok - Dictionary Of Keys based matrix
+   extract - Functions to extract parts of sparse matrices
+   lil - LInked List sparse matrix class
+   linalg -
+   sparsetools - A collection of routines for sparse matrix operations
+   spfuncs - Functions that operate on sparse matrices
+   sputils - Utility functions for sparse matrix module
+
+Classes
+-------
+
+.. autosummary::
+   :toctree: generated/
+
+   SparseEfficiencyWarning -
+   SparseWarning -
+   bsr_matrix - Block Sparse Row matrix
+   coo_matrix - A sparse matrix in COOrdinate format
+   csc_matrix - Compressed Sparse Column matrix
+   csr_matrix - Compressed Sparse Row matrix
+   dia_matrix - Sparse matrix with DIAgonal storage
+   dok_matrix - Dictionary Of Keys based sparse matrix
+   lil_matrix - Row-based linked list sparse matrix
+
+Functions
+---------
+
+.. autosummary::
+   :toctree: generated/
+
+   bmat - Build a sparse matrix from sparse sub-blocks
+   cs_graph_components -
+   eye - Sparse MxN matrix whose k-th diagonal is all ones
+   find -
+   hstack - Stack sparse matrices horizontally (column wise)
+   identity - Identity matrix in sparse format
+   issparse -
+   isspmatrix -
+   isspmatrix_bsr -
+   isspmatrix_coo -
+   isspmatrix_csc -
+   isspmatrix_csr -
+   isspmatrix_dia -
+   isspmatrix_dok -
+   isspmatrix_lil -
+   kron - kronecker product of two sparse matrices
+   kronsum - kronecker sum of sparse matrices
+   lil_diags - Generate a lil_matrix with the given diagonals
+   lil_eye - RxC lil_matrix whose k-th diagonal set to one
+   rand - Random values in a given shape
+   spdiags - Return a sparse matrix from diagonals
+   tril - Lower triangular portion of a matrix in sparse format
+   triu - Upper triangular portion of a matrix in sparse format
+   vstack - Stack sparse matrices vertically (row wise)
+
+"""
+
 from info import __doc__
 
 from base import *

Modified: trunk/scipy/sparse/linalg/dsolve/__init__.py
===================================================================
--- trunk/scipy/sparse/linalg/dsolve/__init__.py	2010-11-14 10:01:15 UTC (rev 6891)
+++ trunk/scipy/sparse/linalg/dsolve/__init__.py	2010-11-14 10:01:37 UTC (rev 6892)
@@ -1,5 +1,56 @@
-"Direct Solvers for Sparse Linear Systems"
+"""
+Linear Solvers
+==============
 
+The default solver is SuperLU (included in the scipy distribution),
+which can solve real or complex linear systems in both single and
+double precisions.  It is automatically replaced by UMFPACK, if
+available.  Note that UMFPACK works in double precision only, so
+switch it off by
+
+>>> use_solver( useUmfpack = False )
+
+to solve in the single precision. See also use_solver documentation.
+
+Example session:
+
+>>> from scipy.sparse import csc_matrix, spdiags
+>>> from numpy import array
+>>> from scipy.sparse.linalg import spsolve, use_solver
+>>>
+>>> print "Inverting a sparse linear system:"
+>>> print "The sparse matrix (constructed from diagonals):"
+>>> a = spdiags([[1, 2, 3, 4, 5], [6, 5, 8, 9, 10]], [0, 1], 5, 5)
+>>> b = array([1, 2, 3, 4, 5])
+>>> print "Solve: single precision complex:"
+>>> use_solver( useUmfpack = False )
+>>> a = a.astype('F')
+>>> x = spsolve(a, b)
+>>> print x
+>>> print "Error: ", a*x-b
+>>>
+>>> print "Solve: double precision complex:"
+>>> use_solver( useUmfpack = True )
+>>> a = a.astype('D')
+>>> x = spsolve(a, b)
+>>> print x
+>>> print "Error: ", a*x-b
+>>>
+>>> print "Solve: double precision:"
+>>> a = a.astype('d')
+>>> x = spsolve(a, b)
+>>> print x
+>>> print "Error: ", a*x-b
+>>>
+>>> print "Solve: single precision:"
+>>> use_solver( useUmfpack = False )
+>>> a = a.astype('f')
+>>> x = spsolve(a, b.astype('f'))
+>>> print x
+>>> print "Error: ", a*x-b
+
+"""
+
 from info import __doc__
 
 #import umfpack

Modified: trunk/scipy/sparse/linalg/eigen/arpack/arpack.py
===================================================================
--- trunk/scipy/sparse/linalg/eigen/arpack/arpack.py	2010-11-14 10:01:15 UTC (rev 6891)
+++ trunk/scipy/sparse/linalg/eigen/arpack/arpack.py	2010-11-14 10:01:37 UTC (rev 6892)
@@ -312,52 +312,46 @@
 def eigen(A, k=6, M=None, sigma=None, which='LM', v0=None,
           ncv=None, maxiter=None, tol=0,
           return_eigenvectors=True):
-    """Find k eigenvalues and eigenvectors of the square matrix A.
+    """
+    Find k eigenvalues and eigenvectors of the square matrix A.
 
-    Solves A * x[i] = w[i] * x[i], the standard eigenvalue problem for
-    w[i] eigenvalues with corresponding eigenvectors x[i].
+    Solves ``A * x[i] = w[i] * x[i]``, the standard eigenvalue problem
+    for w[i] eigenvalues with corresponding eigenvectors x[i].
 
-
     Parameters
     ----------
     A : matrix, array, or object with matvec(x) method
         An N x N matrix, array, or an object with matvec(x) method to perform
         the matrix vector product A * x.  The sparse matrix formats
         in scipy.sparse are appropriate for A.
-
     k : integer
         The number of eigenvalues and eigenvectors desired
 
     Returns
     -------
     w : array
-        Array of k eigenvalues
-
+        Array of k eigenvalues.
     v : array
-        An array of k eigenvectors
-        The v[i] is the eigenvector corresponding to the eigenvector w[i]
+        An array of `k` eigenvectors.
+        ``v[:, i]`` is the eigenvector corresponding to the eigenvalue w[i].
 
     Other Parameters
     ----------------
-
     M : matrix or array
         (Not implemented)
         A symmetric positive-definite matrix for the generalized
-        eigenvalue problem A * x = w * M * x
-
+        eigenvalue problem ``A * x = w * M * x``.
     sigma : real or complex
         (Not implemented)
         Find eigenvalues near sigma.  Shift spectrum by sigma.
-
     v0 : array
         Starting vector for iteration.
-
     ncv : integer
         The number of Lanczos vectors generated
-        ncv must be greater than k; it is recommended that ncv > 2*k
-
+        `ncv` must be greater than `k`; it is recommended that ``ncv > 2*k``.
     which : string
-        Which k eigenvectors and eigenvalues to find:
+        Which `k` eigenvectors and eigenvalues to find:
+
          - 'LM' : largest magnitude
          - 'SM' : smallest magnitude
          - 'LR' : largest real part
@@ -367,10 +361,8 @@
 
     maxiter : integer
         Maximum number of Arnoldi update iterations allowed
-
     tol : float
         Relative accuracy for eigenvalues (stopping criterion)
-
     return_eigenvectors : boolean
         Return eigenvectors (True) in addition to eigenvalues
 
@@ -378,12 +370,17 @@
     --------
     eigen_symmetric : eigenvalues and eigenvectors for symmetric matrix A
 
-    Notes
-    -----
-
     Examples
     --------
+    Find 6 eigenvectors of the identity matrix:
 
+    >>> id = np.identity(13)
+    >>> vals, vecs = sp.sparse.linalg.eigen(id, k=6)
+    >>> vals
+    array([ 1.+0.j,  1.+0.j,  1.+0.j,  1.+0.j,  1.+0.j,  1.+0.j])
+    >>> vecs.shape
+    (13, 6)
+
     """
     A = aslinearoperator(A)
     if A.shape[0] != A.shape[1]:



More information about the Scipy-svn mailing list