_nnls.py 2.2 KB

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