_spectral.py 7.7 KB

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