_spectral.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. """
  2. Spectral Algorithm for Nonlinear Equations
  3. """
  4. from __future__ import division, absolute_import, print_function
  5. import collections
  6. import numpy as np
  7. from scipy.optimize import OptimizeResult
  8. from scipy.optimize.optimize import _check_unknown_options
  9. from .linesearch import _nonmonotone_line_search_cruz, _nonmonotone_line_search_cheng
  10. class _NoConvergence(Exception):
  11. pass
  12. def _root_df_sane(func, x0, args=(), ftol=1e-8, fatol=1e-300, maxfev=1000,
  13. fnorm=None, callback=None, disp=False, M=10, eta_strategy=None,
  14. sigma_eps=1e-10, sigma_0=1.0, line_search='cruz', **unknown_options):
  15. r"""
  16. Solve nonlinear equation with the DF-SANE method
  17. Options
  18. -------
  19. ftol : float, optional
  20. Relative norm tolerance.
  21. fatol : float, optional
  22. Absolute norm tolerance.
  23. Algorithm terminates when ``||func(x)|| < fatol + ftol ||func(x_0)||``.
  24. fnorm : callable, optional
  25. Norm to use in the convergence check. If None, 2-norm is used.
  26. maxfev : int, optional
  27. Maximum number of function evaluations.
  28. disp : bool, optional
  29. Whether to print convergence process to stdout.
  30. eta_strategy : callable, optional
  31. Choice of the ``eta_k`` parameter, which gives slack for growth
  32. of ``||F||**2``. Called as ``eta_k = eta_strategy(k, x, F)`` with
  33. `k` the iteration number, `x` the current iterate and `F` the current
  34. residual. Should satisfy ``eta_k > 0`` and ``sum(eta, k=0..inf) < inf``.
  35. Default: ``||F||**2 / (1 + k)**2``.
  36. sigma_eps : float, optional
  37. The spectral coefficient is constrained to ``sigma_eps < sigma < 1/sigma_eps``.
  38. Default: 1e-10
  39. sigma_0 : float, optional
  40. Initial spectral coefficient.
  41. Default: 1.0
  42. M : int, optional
  43. Number of iterates to include in the nonmonotonic line search.
  44. Default: 10
  45. line_search : {'cruz', 'cheng'}
  46. Type of line search to employ. 'cruz' is the original one defined in
  47. [Martinez & Raydan. Math. Comp. 75, 1429 (2006)], 'cheng' is
  48. a modified search defined in [Cheng & Li. IMA J. Numer. Anal. 29, 814 (2009)].
  49. Default: 'cruz'
  50. References
  51. ----------
  52. .. [1] "Spectral residual method without gradient information for solving
  53. large-scale nonlinear systems of equations." W. La Cruz,
  54. J.M. Martinez, M. Raydan. Math. Comp. **75**, 1429 (2006).
  55. .. [2] W. La Cruz, Opt. Meth. Software, 29, 24 (2014).
  56. .. [3] W. Cheng, D.-H. Li. IMA J. Numer. Anal. **29**, 814 (2009).
  57. """
  58. _check_unknown_options(unknown_options)
  59. if line_search not in ('cheng', 'cruz'):
  60. raise ValueError("Invalid value %r for 'line_search'" % (line_search,))
  61. nexp = 2
  62. if eta_strategy is None:
  63. # Different choice from [1], as their eta is not invariant
  64. # vs. scaling of F.
  65. def eta_strategy(k, x, F):
  66. # Obtain squared 2-norm of the initial residual from the outer scope
  67. return f_0 / (1 + k)**2
  68. if fnorm is None:
  69. def fnorm(F):
  70. # Obtain squared 2-norm of the current residual from the outer scope
  71. return f_k**(1.0/nexp)
  72. def fmerit(F):
  73. return np.linalg.norm(F)**nexp
  74. nfev = [0]
  75. f, x_k, x_shape, f_k, F_k, is_complex = _wrap_func(func, x0, fmerit, nfev, maxfev, args)
  76. k = 0
  77. f_0 = f_k
  78. sigma_k = sigma_0
  79. F_0_norm = fnorm(F_k)
  80. # For the 'cruz' line search
  81. prev_fs = collections.deque([f_k], M)
  82. # For the 'cheng' line search
  83. Q = 1.0
  84. C = f_0
  85. converged = False
  86. message = "too many function evaluations required"
  87. while True:
  88. F_k_norm = fnorm(F_k)
  89. if disp:
  90. print("iter %d: ||F|| = %g, sigma = %g" % (k, F_k_norm, sigma_k))
  91. if callback is not None:
  92. callback(x_k, F_k)
  93. if F_k_norm < ftol * F_0_norm + fatol:
  94. # Converged!
  95. message = "successful convergence"
  96. converged = True
  97. break
  98. # Control spectral parameter, from [2]
  99. if abs(sigma_k) > 1/sigma_eps:
  100. sigma_k = 1/sigma_eps * np.sign(sigma_k)
  101. elif abs(sigma_k) < sigma_eps:
  102. sigma_k = sigma_eps
  103. # Line search direction
  104. d = -sigma_k * F_k
  105. # Nonmonotone line search
  106. eta = eta_strategy(k, x_k, F_k)
  107. try:
  108. if line_search == 'cruz':
  109. alpha, xp, fp, Fp = _nonmonotone_line_search_cruz(f, x_k, d, prev_fs, eta=eta)
  110. elif line_search == 'cheng':
  111. alpha, xp, fp, Fp, C, Q = _nonmonotone_line_search_cheng(f, x_k, d, f_k, C, Q, eta=eta)
  112. except _NoConvergence:
  113. break
  114. # Update spectral parameter
  115. s_k = xp - x_k
  116. y_k = Fp - F_k
  117. sigma_k = np.vdot(s_k, s_k) / np.vdot(s_k, y_k)
  118. # Take step
  119. x_k = xp
  120. F_k = Fp
  121. f_k = fp
  122. # Store function value
  123. if line_search == 'cruz':
  124. prev_fs.append(fp)
  125. k += 1
  126. x = _wrap_result(x_k, is_complex, shape=x_shape)
  127. F = _wrap_result(F_k, is_complex)
  128. result = OptimizeResult(x=x, success=converged,
  129. message=message,
  130. fun=F, nfev=nfev[0], nit=k)
  131. return result
  132. def _wrap_func(func, x0, fmerit, nfev_list, maxfev, args=()):
  133. """
  134. Wrap a function and an initial value so that (i) complex values
  135. are wrapped to reals, and (ii) value for a merit function
  136. fmerit(x, f) is computed at the same time, (iii) iteration count
  137. is maintained and an exception is raised if it is exceeded.
  138. Parameters
  139. ----------
  140. func : callable
  141. Function to wrap
  142. x0 : ndarray
  143. Initial value
  144. fmerit : callable
  145. Merit function fmerit(f) for computing merit value from residual.
  146. nfev_list : list
  147. List to store number of evaluations in. Should be [0] in the beginning.
  148. maxfev : int
  149. Maximum number of evaluations before _NoConvergence is raised.
  150. args : tuple
  151. Extra arguments to func
  152. Returns
  153. -------
  154. wrap_func : callable
  155. Wrapped function, to be called as
  156. ``F, fp = wrap_func(x0)``
  157. x0_wrap : ndarray of float
  158. Wrapped initial value; raveled to 1D and complex
  159. values mapped to reals.
  160. x0_shape : tuple
  161. Shape of the initial value array
  162. f : float
  163. Merit function at F
  164. F : ndarray of float
  165. Residual at x0_wrap
  166. is_complex : bool
  167. Whether complex values were mapped to reals
  168. """
  169. x0 = np.asarray(x0)
  170. x0_shape = x0.shape
  171. F = np.asarray(func(x0, *args)).ravel()
  172. is_complex = np.iscomplexobj(x0) or np.iscomplexobj(F)
  173. x0 = x0.ravel()
  174. nfev_list[0] = 1
  175. if is_complex:
  176. def wrap_func(x):
  177. if nfev_list[0] >= maxfev:
  178. raise _NoConvergence()
  179. nfev_list[0] += 1
  180. z = _real2complex(x).reshape(x0_shape)
  181. v = np.asarray(func(z, *args)).ravel()
  182. F = _complex2real(v)
  183. f = fmerit(F)
  184. return f, F
  185. x0 = _complex2real(x0)
  186. F = _complex2real(F)
  187. else:
  188. def wrap_func(x):
  189. if nfev_list[0] >= maxfev:
  190. raise _NoConvergence()
  191. nfev_list[0] += 1
  192. x = x.reshape(x0_shape)
  193. F = np.asarray(func(x, *args)).ravel()
  194. f = fmerit(F)
  195. return f, F
  196. return wrap_func, x0, x0_shape, fmerit(F), F, is_complex
  197. def _wrap_result(result, is_complex, shape=None):
  198. """
  199. Convert from real to complex and reshape result arrays.
  200. """
  201. if is_complex:
  202. z = _real2complex(result)
  203. else:
  204. z = result
  205. if shape is not None:
  206. z = z.reshape(shape)
  207. return z
  208. def _real2complex(x):
  209. return np.ascontiguousarray(x, dtype=float).view(np.complex128)
  210. def _complex2real(z):
  211. return np.ascontiguousarray(z, dtype=complex).view(np.float64)