Coverage for /home/martinb/.local/share/virtualenvs/camcops/lib/python3.6/site-packages/scipy/optimize/_nnls.py : 20%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from . import __nnls
2from numpy import asarray_chkfinite, zeros, double
4__all__ = ['nnls']
7def nnls(A, b, maxiter=None):
8 """
9 Solve ``argmin_x || Ax - b ||_2`` for ``x>=0``. This is a wrapper
10 for a FORTRAN non-negative least squares solver.
12 Parameters
13 ----------
14 A : ndarray
15 Matrix ``A`` as shown above.
16 b : ndarray
17 Right-hand side vector.
18 maxiter: int, optional
19 Maximum number of iterations, optional.
20 Default is ``3 * A.shape[1]``.
22 Returns
23 -------
24 x : ndarray
25 Solution vector.
26 rnorm : float
27 The residual, ``|| Ax-b ||_2``.
29 See Also
30 --------
31 lsq_linear : Linear least squares with bounds on the variables
33 Notes
34 -----
35 The FORTRAN code was published in the book below. The algorithm
36 is an active set method. It solves the KKT (Karush-Kuhn-Tucker)
37 conditions for the non-negative least squares problem.
39 References
40 ----------
41 Lawson C., Hanson R.J., (1987) Solving Least Squares Problems, SIAM
43 Examples
44 --------
45 >>> from scipy.optimize import nnls
46 ...
47 >>> A = np.array([[1, 0], [1, 0], [0, 1]])
48 >>> b = np.array([2, 1, 1])
49 >>> nnls(A, b)
50 (array([1.5, 1. ]), 0.7071067811865475)
52 >>> b = np.array([-1, -1, -1])
53 >>> nnls(A, b)
54 (array([0., 0.]), 1.7320508075688772)
56 """
58 A, b = map(asarray_chkfinite, (A, b))
60 if len(A.shape) != 2:
61 raise ValueError("Expected a two-dimensional array (matrix)" +
62 ", but the shape of A is %s" % (A.shape, ))
63 if len(b.shape) != 1:
64 raise ValueError("Expected a one-dimensional array (vector" +
65 ", but the shape of b is %s" % (b.shape, ))
67 m, n = A.shape
69 if m != b.shape[0]:
70 raise ValueError(
71 "Incompatible dimensions. The first dimension of " +
72 "A is %s, while the shape of b is %s" % (m, (b.shape[0], )))
74 maxiter = -1 if maxiter is None else int(maxiter)
76 w = zeros((n,), dtype=double)
77 zz = zeros((m,), dtype=double)
78 index = zeros((n,), dtype=int)
80 x, rnorm, mode = __nnls.nnls(A, m, n, b, w, zz, index, maxiter)
81 if mode != 1:
82 raise RuntimeError("too many iterations")
84 return x, rnorm