nnls.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. from __future__ import division, print_function, absolute_import
  2. from . import _nnls
  3. from numpy import asarray_chkfinite, zeros, double
  4. __all__ = ['nnls']
  5. def nnls(A, b, maxiter=None):
  6. """
  7. Solve ``argmin_x || Ax - b ||_2`` for ``x>=0``. This is a wrapper
  8. for a FORTRAN non-negative least squares solver.
  9. Parameters
  10. ----------
  11. A : ndarray
  12. Matrix ``A`` as shown above.
  13. b : ndarray
  14. Right-hand side vector.
  15. maxiter: int, optional
  16. Maximum number of iterations, optional.
  17. Default is ``3 * A.shape[1]``.
  18. Returns
  19. -------
  20. x : ndarray
  21. Solution vector.
  22. rnorm : float
  23. The residual, ``|| Ax-b ||_2``.
  24. Notes
  25. -----
  26. The FORTRAN code was published in the book below. The algorithm
  27. is an active set method. It solves the KKT (Karush-Kuhn-Tucker)
  28. conditions for the non-negative least squares problem.
  29. References
  30. ----------
  31. Lawson C., Hanson R.J., (1987) Solving Least Squares Problems, SIAM
  32. """
  33. A, b = map(asarray_chkfinite, (A, b))
  34. if len(A.shape) != 2:
  35. raise ValueError("expected matrix")
  36. if len(b.shape) != 1:
  37. raise ValueError("expected vector")
  38. m, n = A.shape
  39. if m != b.shape[0]:
  40. raise ValueError("incompatible dimensions")
  41. maxiter = -1 if maxiter is None else int(maxiter)
  42. w = zeros((n,), dtype=double)
  43. zz = zeros((m,), dtype=double)
  44. index = zeros((n,), dtype=int)
  45. x, rnorm, mode = _nnls.nnls(A, m, n, b, w, zz, index, maxiter)
  46. if mode != 1:
  47. raise RuntimeError("too many iterations")
  48. return x, rnorm