Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/scipy/optimize/_nnls.py: 20%
20 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-12 06:31 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-12 06:31 +0000
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 >>> import numpy as np
46 >>> from scipy.optimize import nnls
47 ...
48 >>> A = np.array([[1, 0], [1, 0], [0, 1]])
49 >>> b = np.array([2, 1, 1])
50 >>> nnls(A, b)
51 (array([1.5, 1. ]), 0.7071067811865475)
53 >>> b = np.array([-1, -1, -1])
54 >>> nnls(A, b)
55 (array([0., 0.]), 1.7320508075688772)
57 """
59 A, b = map(asarray_chkfinite, (A, b))
61 if len(A.shape) != 2:
62 raise ValueError("Expected a two-dimensional array (matrix)" +
63 ", but the shape of A is %s" % (A.shape, ))
64 if len(b.shape) != 1:
65 raise ValueError("Expected a one-dimensional array (vector)" +
66 ", but the shape of b is %s" % (b.shape, ))
68 m, n = A.shape
70 if m != b.shape[0]:
71 raise ValueError(
72 "Incompatible dimensions. The first dimension of " +
73 "A is %s, while the shape of b is %s" % (m, (b.shape[0], )))
75 maxiter = -1 if maxiter is None else int(maxiter)
77 w = zeros((n,), dtype=double)
78 zz = zeros((m,), dtype=double)
79 index = zeros((n,), dtype=int)
81 x, rnorm, mode = __nnls.nnls(A, m, n, b, w, zz, index, maxiter)
82 if mode != 1:
83 raise RuntimeError("too many iterations")
85 return x, rnorm