_differentiate.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  1. # mypy: disable-error-code="attr-defined"
  2. import warnings
  3. import numpy as np
  4. import scipy._lib._elementwise_iterative_method as eim
  5. from scipy._lib._util import _RichResult
  6. from scipy._lib._array_api import array_namespace, xp_copy, xp_promote, xp_capabilities
  7. import scipy._lib.array_api_extra as xpx
  8. _EERRORINCREASE = -1 # used in derivative
  9. def _derivative_iv(f, x, args, tolerances, maxiter, order, initial_step,
  10. step_factor, step_direction, preserve_shape, callback):
  11. # Input validation for `derivative`
  12. xp = array_namespace(x)
  13. if not callable(f):
  14. raise ValueError('`f` must be callable.')
  15. if not np.iterable(args):
  16. args = (args,)
  17. tolerances = {} if tolerances is None else tolerances
  18. atol = tolerances.get('atol', None)
  19. rtol = tolerances.get('rtol', None)
  20. # tolerances are floats, not arrays; OK to use NumPy
  21. message = 'Tolerances and step parameters must be non-negative scalars.'
  22. tols = np.asarray([atol if atol is not None else 1,
  23. rtol if rtol is not None else 1,
  24. step_factor])
  25. if (not np.issubdtype(tols.dtype, np.number) or np.any(tols < 0)
  26. or np.any(np.isnan(tols)) or tols.shape != (3,)):
  27. raise ValueError(message)
  28. step_factor = float(tols[2])
  29. maxiter_int = int(maxiter)
  30. if maxiter != maxiter_int or maxiter <= 0:
  31. raise ValueError('`maxiter` must be a positive integer.')
  32. order_int = int(order)
  33. if order_int != order or order <= 0:
  34. raise ValueError('`order` must be a positive integer.')
  35. step_direction = xp.asarray(step_direction)
  36. initial_step = xp.asarray(initial_step)
  37. temp = xp.broadcast_arrays(x, step_direction, initial_step)
  38. x, step_direction, initial_step = temp
  39. message = '`preserve_shape` must be True or False.'
  40. if preserve_shape not in {True, False}:
  41. raise ValueError(message)
  42. if callback is not None and not callable(callback):
  43. raise ValueError('`callback` must be callable.')
  44. return (f, x, args, atol, rtol, maxiter_int, order_int, initial_step,
  45. step_factor, step_direction, preserve_shape, callback)
  46. _array_api_strict_skip_reason = 'Array API does not support fancy indexing assignment.'
  47. _dask_reason = 'boolean indexing assignment'
  48. @xp_capabilities(skip_backends=[('array_api_strict', _array_api_strict_skip_reason),
  49. ('dask.array', _dask_reason)], jax_jit=False)
  50. def derivative(f, x, *, args=(), tolerances=None, maxiter=10,
  51. order=8, initial_step=0.5, step_factor=2.0,
  52. step_direction=0, preserve_shape=False, callback=None):
  53. """Evaluate the derivative of an elementwise, real scalar function numerically.
  54. For each element of the output of `f`, `derivative` approximates the first
  55. derivative of `f` at the corresponding element of `x` using finite difference
  56. differentiation.
  57. This function works elementwise when `x`, `step_direction`, and `args` contain
  58. (broadcastable) arrays.
  59. Parameters
  60. ----------
  61. f : callable
  62. The function whose derivative is desired. The signature must be::
  63. f(xi: ndarray, *argsi) -> ndarray
  64. where each element of ``xi`` is a finite real number and ``argsi`` is a tuple,
  65. which may contain an arbitrary number of arrays that are broadcastable with
  66. ``xi``. `f` must be an elementwise function: each scalar element ``f(xi)[j]``
  67. must equal ``f(xi[j])`` for valid indices ``j``. It must not mutate the array
  68. ``xi`` or the arrays in ``argsi``.
  69. x : float array_like
  70. Abscissae at which to evaluate the derivative. Must be broadcastable with
  71. `args` and `step_direction`.
  72. args : tuple of array_like, optional
  73. Additional positional array arguments to be passed to `f`. Arrays
  74. must be broadcastable with one another and the arrays of `init`.
  75. If the callable for which the root is desired requires arguments that are
  76. not broadcastable with `x`, wrap that callable with `f` such that `f`
  77. accepts only `x` and broadcastable ``*args``.
  78. tolerances : dictionary of floats, optional
  79. Absolute and relative tolerances. Valid keys of the dictionary are:
  80. - ``atol`` - absolute tolerance on the derivative
  81. - ``rtol`` - relative tolerance on the derivative
  82. Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
  83. `atol` is the smallest normal number of the appropriate dtype, and
  84. the default `rtol` is the square root of the precision of the
  85. appropriate dtype.
  86. order : int, default: 8
  87. The (positive integer) order of the finite difference formula to be
  88. used. Odd integers will be rounded up to the next even integer.
  89. initial_step : float array_like, default: 0.5
  90. The (absolute) initial step size for the finite difference derivative
  91. approximation.
  92. step_factor : float, default: 2.0
  93. The factor by which the step size is *reduced* in each iteration; i.e.
  94. the step size in iteration 1 is ``initial_step/step_factor``. If
  95. ``step_factor < 1``, subsequent steps will be greater than the initial
  96. step; this may be useful if steps smaller than some threshold are
  97. undesirable (e.g. due to subtractive cancellation error).
  98. maxiter : int, default: 10
  99. The maximum number of iterations of the algorithm to perform. See
  100. Notes.
  101. step_direction : integer array_like
  102. An array representing the direction of the finite difference steps (for
  103. use when `x` lies near to the boundary of the domain of the function.)
  104. Must be broadcastable with `x` and all `args`.
  105. Where 0 (default), central differences are used; where negative (e.g.
  106. -1), steps are non-positive; and where positive (e.g. 1), all steps are
  107. non-negative.
  108. preserve_shape : bool, default: False
  109. In the following, "arguments of `f`" refers to the array ``xi`` and
  110. any arrays within ``argsi``. Let ``shape`` be the broadcasted shape
  111. of `x` and all elements of `args` (which is conceptually
  112. distinct from ``xi` and ``argsi`` passed into `f`).
  113. - When ``preserve_shape=False`` (default), `f` must accept arguments
  114. of *any* broadcastable shapes.
  115. - When ``preserve_shape=True``, `f` must accept arguments of shape
  116. ``shape`` *or* ``shape + (n,)``, where ``(n,)`` is the number of
  117. abscissae at which the function is being evaluated.
  118. In either case, for each scalar element ``xi[j]`` within ``xi``, the array
  119. returned by `f` must include the scalar ``f(xi[j])`` at the same index.
  120. Consequently, the shape of the output is always the shape of the input
  121. ``xi``.
  122. See Examples.
  123. callback : callable, optional
  124. An optional user-supplied function to be called before the first
  125. iteration and after each iteration.
  126. Called as ``callback(res)``, where ``res`` is a ``_RichResult``
  127. similar to that returned by `derivative` (but containing the current
  128. iterate's values of all variables). If `callback` raises a
  129. ``StopIteration``, the algorithm will terminate immediately and
  130. `derivative` will return a result. `callback` must not mutate
  131. `res` or its attributes.
  132. Returns
  133. -------
  134. res : _RichResult
  135. An object similar to an instance of `scipy.optimize.OptimizeResult` with the
  136. following attributes. The descriptions are written as though the values will
  137. be scalars; however, if `f` returns an array, the outputs will be
  138. arrays of the same shape.
  139. success : bool array
  140. ``True`` where the algorithm terminated successfully (status ``0``);
  141. ``False`` otherwise.
  142. status : int array
  143. An integer representing the exit status of the algorithm.
  144. - ``0`` : The algorithm converged to the specified tolerances.
  145. - ``-1`` : The error estimate increased, so iteration was terminated.
  146. - ``-2`` : The maximum number of iterations was reached.
  147. - ``-3`` : A non-finite value was encountered.
  148. - ``-4`` : Iteration was terminated by `callback`.
  149. - ``1`` : The algorithm is proceeding normally (in `callback` only).
  150. df : float array
  151. The derivative of `f` at `x`, if the algorithm terminated
  152. successfully.
  153. error : float array
  154. An estimate of the error: the magnitude of the difference between
  155. the current estimate of the derivative and the estimate in the
  156. previous iteration.
  157. nit : int array
  158. The number of iterations of the algorithm that were performed.
  159. nfev : int array
  160. The number of points at which `f` was evaluated.
  161. x : float array
  162. The value at which the derivative of `f` was evaluated
  163. (after broadcasting with `args` and `step_direction`).
  164. See Also
  165. --------
  166. jacobian, hessian
  167. Notes
  168. -----
  169. The implementation was inspired by jacobi [1]_, numdifftools [2]_, and
  170. DERIVEST [3]_, but the implementation follows the theory of Taylor series
  171. more straightforwardly (and arguably naively so).
  172. In the first iteration, the derivative is estimated using a finite
  173. difference formula of order `order` with maximum step size `initial_step`.
  174. Each subsequent iteration, the maximum step size is reduced by
  175. `step_factor`, and the derivative is estimated again until a termination
  176. condition is reached. The error estimate is the magnitude of the difference
  177. between the current derivative approximation and that of the previous
  178. iteration.
  179. The stencils of the finite difference formulae are designed such that
  180. abscissae are "nested": after `f` is evaluated at ``order + 1``
  181. points in the first iteration, `f` is evaluated at only two new points
  182. in each subsequent iteration; ``order - 1`` previously evaluated function
  183. values required by the finite difference formula are reused, and two
  184. function values (evaluations at the points furthest from `x`) are unused.
  185. Step sizes are absolute. When the step size is small relative to the
  186. magnitude of `x`, precision is lost; for example, if `x` is ``1e20``, the
  187. default initial step size of ``0.5`` cannot be resolved. Accordingly,
  188. consider using larger initial step sizes for large magnitudes of `x`.
  189. The default tolerances are challenging to satisfy at points where the
  190. true derivative is exactly zero. If the derivative may be exactly zero,
  191. consider specifying an absolute tolerance (e.g. ``atol=1e-12``) to
  192. improve convergence.
  193. References
  194. ----------
  195. .. [1] Hans Dembinski (@HDembinski). jacobi.
  196. https://github.com/HDembinski/jacobi
  197. .. [2] Per A. Brodtkorb and John D'Errico. numdifftools.
  198. https://numdifftools.readthedocs.io/en/latest/
  199. .. [3] John D'Errico. DERIVEST: Adaptive Robust Numerical Differentiation.
  200. https://www.mathworks.com/matlabcentral/fileexchange/13490-adaptive-robust-numerical-differentiation
  201. .. [4] Numerical Differentition. Wikipedia.
  202. https://en.wikipedia.org/wiki/Numerical_differentiation
  203. Examples
  204. --------
  205. Evaluate the derivative of ``np.exp`` at several points ``x``.
  206. >>> import numpy as np
  207. >>> from scipy.differentiate import derivative
  208. >>> f = np.exp
  209. >>> df = np.exp # true derivative
  210. >>> x = np.linspace(1, 2, 5)
  211. >>> res = derivative(f, x)
  212. >>> res.df # approximation of the derivative
  213. array([2.71828183, 3.49034296, 4.48168907, 5.75460268, 7.3890561 ])
  214. >>> res.error # estimate of the error
  215. array([7.13740178e-12, 9.16600129e-12, 1.17594823e-11, 1.51061386e-11,
  216. 1.94262384e-11])
  217. >>> abs(res.df - df(x)) # true error
  218. array([2.53130850e-14, 3.55271368e-14, 5.77315973e-14, 5.59552404e-14,
  219. 6.92779167e-14])
  220. Show the convergence of the approximation as the step size is reduced.
  221. Each iteration, the step size is reduced by `step_factor`, so for
  222. sufficiently small initial step, each iteration reduces the error by a
  223. factor of ``1/step_factor**order`` until finite precision arithmetic
  224. inhibits further improvement.
  225. >>> import matplotlib.pyplot as plt
  226. >>> iter = list(range(1, 12)) # maximum iterations
  227. >>> hfac = 2 # step size reduction per iteration
  228. >>> hdir = [-1, 0, 1] # compare left-, central-, and right- steps
  229. >>> order = 4 # order of differentiation formula
  230. >>> x = 1
  231. >>> ref = df(x)
  232. >>> errors = [] # true error
  233. >>> for i in iter:
  234. ... res = derivative(f, x, maxiter=i, step_factor=hfac,
  235. ... step_direction=hdir, order=order,
  236. ... # prevent early termination
  237. ... tolerances=dict(atol=0, rtol=0))
  238. ... errors.append(abs(res.df - ref))
  239. >>> errors = np.array(errors)
  240. >>> plt.semilogy(iter, errors[:, 0], label='left differences')
  241. >>> plt.semilogy(iter, errors[:, 1], label='central differences')
  242. >>> plt.semilogy(iter, errors[:, 2], label='right differences')
  243. >>> plt.xlabel('iteration')
  244. >>> plt.ylabel('error')
  245. >>> plt.legend()
  246. >>> plt.show()
  247. >>> (errors[1, 1] / errors[0, 1], 1 / hfac**order)
  248. (0.06215223140159822, 0.0625)
  249. The implementation is vectorized over `x`, `step_direction`, and `args`.
  250. The function is evaluated once before the first iteration to perform input
  251. validation and standardization, and once per iteration thereafter.
  252. >>> def f(x, p):
  253. ... f.nit += 1
  254. ... return x**p
  255. >>> f.nit = 0
  256. >>> def df(x, p):
  257. ... return p*x**(p-1)
  258. >>> x = np.arange(1, 5)
  259. >>> p = np.arange(1, 6).reshape((-1, 1))
  260. >>> hdir = np.arange(-1, 2).reshape((-1, 1, 1))
  261. >>> res = derivative(f, x, args=(p,), step_direction=hdir, maxiter=1)
  262. >>> np.allclose(res.df, df(x, p))
  263. True
  264. >>> res.df.shape
  265. (3, 5, 4)
  266. >>> f.nit
  267. 2
  268. By default, `preserve_shape` is False, and therefore the callable
  269. `f` may be called with arrays of any broadcastable shapes.
  270. For example:
  271. >>> shapes = []
  272. >>> def f(x, c):
  273. ... shape = np.broadcast_shapes(x.shape, c.shape)
  274. ... shapes.append(shape)
  275. ... return np.sin(c*x)
  276. >>>
  277. >>> c = [1, 5, 10, 20]
  278. >>> res = derivative(f, 0, args=(c,))
  279. >>> shapes
  280. [(4,), (4, 8), (4, 2), (3, 2), (2, 2), (1, 2)]
  281. To understand where these shapes are coming from - and to better
  282. understand how `derivative` computes accurate results - note that
  283. higher values of ``c`` correspond with higher frequency sinusoids.
  284. The higher frequency sinusoids make the function's derivative change
  285. faster, so more function evaluations are required to achieve the target
  286. accuracy:
  287. >>> res.nfev
  288. array([11, 13, 15, 17], dtype=int32)
  289. The initial ``shape``, ``(4,)``, corresponds with evaluating the
  290. function at a single abscissa and all four frequencies; this is used
  291. for input validation and to determine the size and dtype of the arrays
  292. that store results. The next shape corresponds with evaluating the
  293. function at an initial grid of abscissae and all four frequencies.
  294. Successive calls to the function evaluate the function at two more
  295. abscissae, increasing the effective order of the approximation by two.
  296. However, in later function evaluations, the function is evaluated at
  297. fewer frequencies because the corresponding derivative has already
  298. converged to the required tolerance. This saves function evaluations to
  299. improve performance, but it requires the function to accept arguments of
  300. any shape.
  301. "Vector-valued" functions are unlikely to satisfy this requirement.
  302. For example, consider
  303. >>> def f(x):
  304. ... return [x, np.sin(3*x), x+np.sin(10*x), np.sin(20*x)*(x-1)**2]
  305. This integrand is not compatible with `derivative` as written; for instance,
  306. the shape of the output will not be the same as the shape of ``x``. Such a
  307. function *could* be converted to a compatible form with the introduction of
  308. additional parameters, but this would be inconvenient. In such cases,
  309. a simpler solution would be to use `preserve_shape`.
  310. >>> shapes = []
  311. >>> def f(x):
  312. ... shapes.append(x.shape)
  313. ... x0, x1, x2, x3 = x
  314. ... return [x0, np.sin(3*x1), x2+np.sin(10*x2), np.sin(20*x3)*(x3-1)**2]
  315. >>>
  316. >>> x = np.zeros(4)
  317. >>> res = derivative(f, x, preserve_shape=True)
  318. >>> shapes
  319. [(4,), (4, 8), (4, 2), (4, 2), (4, 2), (4, 2)]
  320. Here, the shape of ``x`` is ``(4,)``. With ``preserve_shape=True``, the
  321. function may be called with argument ``x`` of shape ``(4,)`` or ``(4, n)``,
  322. and this is what we observe.
  323. """
  324. # TODO (followup):
  325. # - investigate behavior at saddle points
  326. # - multivariate functions?
  327. # - relative steps?
  328. # - show example of `np.vectorize`
  329. res = _derivative_iv(f, x, args, tolerances, maxiter, order, initial_step,
  330. step_factor, step_direction, preserve_shape, callback)
  331. (func, x, args, atol, rtol, maxiter, order,
  332. h0, fac, hdir, preserve_shape, callback) = res
  333. # Initialization
  334. # Since f(x) (no step) is not needed for central differences, it may be
  335. # possible to eliminate this function evaluation. However, it's useful for
  336. # input validation and standardization, and everything else is designed to
  337. # reduce function calls, so let's keep it simple.
  338. temp = eim._initialize(func, (x,), args, preserve_shape=preserve_shape)
  339. func, xs, fs, args, shape, dtype, xp = temp
  340. finfo = xp.finfo(dtype)
  341. atol = finfo.smallest_normal if atol is None else atol
  342. rtol = finfo.eps**0.5 if rtol is None else rtol # keep same as `hessian`
  343. x, f = xs[0], fs[0]
  344. df = xp.full_like(f, xp.nan)
  345. # Ideally we'd broadcast the shape of `hdir` in `_elementwise_algo_init`, but
  346. # it's simpler to do it here than to generalize `_elementwise_algo_init` further.
  347. # `hdir` and `x` are already broadcasted in `_derivative_iv`, so we know
  348. # that `hdir` can be broadcasted to the final shape. Same with `h0`.
  349. hdir = xp.broadcast_to(hdir, shape)
  350. hdir = xp.reshape(hdir, (-1,))
  351. hdir = xp.astype(xp.sign(hdir), dtype)
  352. h0 = xp.broadcast_to(h0, shape)
  353. h0 = xp.reshape(h0, (-1,))
  354. h0 = xp.astype(h0, dtype)
  355. h0 = xpx.at(h0)[h0 <= 0].set(xp.nan)
  356. status = xp.full_like(x, eim._EINPROGRESS, dtype=xp.int32) # in progress
  357. nit, nfev = 0, 1 # one function evaluations performed above
  358. # Boolean indices of left, central, right, and (all) one-sided steps
  359. il = hdir < 0
  360. ic = hdir == 0
  361. ir = hdir > 0
  362. io = il | ir
  363. # Most of these attributes are reasonably obvious, but:
  364. # - `fs` holds all the function values of all active `x`. The zeroth
  365. # axis corresponds with active points `x`, the first axis corresponds
  366. # with the different steps (in the order described in
  367. # `_derivative_weights`).
  368. # - `terms` (which could probably use a better name) is half the `order`,
  369. # which is always even.
  370. work = _RichResult(x=x, df=df, fs=f[:, xp.newaxis], error=xp.nan, h=h0,
  371. df_last=xp.nan, error_last=xp.nan, fac=fac,
  372. atol=atol, rtol=rtol, nit=nit, nfev=nfev,
  373. status=status, dtype=dtype, terms=(order+1)//2,
  374. hdir=hdir, il=il, ic=ic, ir=ir, io=io,
  375. # Store the weights in an object so they can't get compressed
  376. # Using RichResult to allow dot notation, but a dict would work
  377. diff_state=_RichResult(central=[], right=[], fac=None))
  378. # This is the correspondence between terms in the `work` object and the
  379. # final result. In this case, the mapping is trivial. Note that `success`
  380. # is prepended automatically.
  381. res_work_pairs = [('status', 'status'), ('df', 'df'), ('error', 'error'),
  382. ('nit', 'nit'), ('nfev', 'nfev'), ('x', 'x')]
  383. def pre_func_eval(work):
  384. """Determine the abscissae at which the function needs to be evaluated.
  385. See `_derivative_weights` for a description of the stencil (pattern
  386. of the abscissae).
  387. In the first iteration, there is only one stored function value in
  388. `work.fs`, `f(x)`, so we need to evaluate at `order` new points. In
  389. subsequent iterations, we evaluate at two new points. Note that
  390. `work.x` is always flattened into a 1D array after broadcasting with
  391. all `args`, so we add a new axis at the end and evaluate all point
  392. in one call to the function.
  393. For improvement:
  394. - Consider measuring the step size actually taken, since ``(x + h) - x``
  395. is not identically equal to `h` with floating point arithmetic.
  396. - Adjust the step size automatically if `x` is too big to resolve the
  397. step.
  398. - We could probably save some work if there are no central difference
  399. steps or no one-sided steps.
  400. """
  401. n = work.terms # half the order
  402. h = work.h[:, xp.newaxis] # step size
  403. c = work.fac # step reduction factor
  404. d = c**0.5 # square root of step reduction factor (one-sided stencil)
  405. # Note - no need to be careful about dtypes until we allocate `x_eval`
  406. if work.nit == 0:
  407. hc = h / c**xp.arange(n, dtype=work.dtype)
  408. hc = xp.concat((-xp.flip(hc, axis=-1), hc), axis=-1)
  409. else:
  410. hc = xp.concat((-h, h), axis=-1) / c**(n-1)
  411. if work.nit == 0:
  412. hr = h / d**xp.arange(2*n, dtype=work.dtype)
  413. else:
  414. hr = xp.concat((h, h/d), axis=-1) / c**(n-1)
  415. n_new = 2*n if work.nit == 0 else 2 # number of new abscissae
  416. x_eval = xp.zeros((work.hdir.shape[0], n_new), dtype=work.dtype)
  417. il, ic, ir = work.il, work.ic, work.ir
  418. x_eval = xpx.at(x_eval)[ir].set(work.x[ir][:, xp.newaxis] + hr[ir])
  419. x_eval = xpx.at(x_eval)[ic].set(work.x[ic][:, xp.newaxis] + hc[ic])
  420. x_eval = xpx.at(x_eval)[il].set(work.x[il][:, xp.newaxis] - hr[il])
  421. return x_eval
  422. def post_func_eval(x, f, work):
  423. """ Estimate the derivative and error from the function evaluations
  424. As in `pre_func_eval`: in the first iteration, there is only one stored
  425. function value in `work.fs`, `f(x)`, so we need to add the `order` new
  426. points. In subsequent iterations, we add two new points. The tricky
  427. part is getting the order to match that of the weights, which is
  428. described in `_derivative_weights`.
  429. For improvement:
  430. - Change the order of the weights (and steps in `pre_func_eval`) to
  431. simplify `work_fc` concatenation and eliminate `fc` concatenation.
  432. - It would be simple to do one-step Richardson extrapolation with `df`
  433. and `df_last` to increase the order of the estimate and/or improve
  434. the error estimate.
  435. - Process the function evaluations in a more numerically favorable
  436. way. For instance, combining the pairs of central difference evals
  437. into a second-order approximation and using Richardson extrapolation
  438. to produce a higher order approximation seemed to retain accuracy up
  439. to very high order.
  440. - Alternatively, we could use `polyfit` like Jacobi. An advantage of
  441. fitting polynomial to more points than necessary is improved noise
  442. tolerance.
  443. """
  444. n = work.terms
  445. n_new = n if work.nit == 0 else 1
  446. il, ic, io = work.il, work.ic, work.io
  447. # Central difference
  448. # `work_fc` is *all* the points at which the function has been evaluated
  449. # `fc` is the points we're using *this iteration* to produce the estimate
  450. work_fc = (f[ic][:, :n_new], work.fs[ic], f[ic][:, -n_new:])
  451. work_fc = xp.concat(work_fc, axis=-1)
  452. if work.nit == 0:
  453. fc = work_fc
  454. else:
  455. fc = (work_fc[:, :n], work_fc[:, n:n+1], work_fc[:, -n:])
  456. fc = xp.concat(fc, axis=-1)
  457. # One-sided difference
  458. work_fo = xp.concat((work.fs[io], f[io]), axis=-1)
  459. if work.nit == 0:
  460. fo = work_fo
  461. else:
  462. fo = xp.concat((work_fo[:, 0:1], work_fo[:, -2*n:]), axis=-1)
  463. work.fs = xp.zeros((ic.shape[0], work.fs.shape[-1] + 2*n_new), dtype=work.dtype)
  464. work.fs = xpx.at(work.fs)[ic].set(work_fc)
  465. work.fs = xpx.at(work.fs)[io].set(work_fo)
  466. wc, wo = _derivative_weights(work, n, xp)
  467. work.df_last = xp.asarray(work.df, copy=True)
  468. work.df = xpx.at(work.df)[ic].set(fc @ wc / work.h[ic])
  469. work.df = xpx.at(work.df)[io].set(fo @ wo / work.h[io])
  470. work.df = xpx.at(work.df)[il].multiply(-1)
  471. work.h /= work.fac
  472. work.error_last = work.error
  473. # Simple error estimate - the difference in derivative estimates between
  474. # this iteration and the last. This is typically conservative because if
  475. # convergence has begin, the true error is much closer to the difference
  476. # between the current estimate and the *next* error estimate. However,
  477. # we could use Richarson extrapolation to produce an error estimate that
  478. # is one order higher, and take the difference between that and
  479. # `work.df` (which would just be constant factor that depends on `fac`.)
  480. work.error = xp.abs(work.df - work.df_last)
  481. def check_termination(work):
  482. """Terminate due to convergence, non-finite values, or error increase"""
  483. stop = xp.astype(xp.zeros_like(work.df), xp.bool)
  484. i = work.error < work.atol + work.rtol*abs(work.df)
  485. work.status = xpx.at(work.status)[i].set(eim._ECONVERGED)
  486. stop = xpx.at(stop)[i].set(True)
  487. if work.nit > 0:
  488. i = ~((xp.isfinite(work.x) & xp.isfinite(work.df)) | stop)
  489. work.df = xpx.at(work.df)[i].set(xp.nan)
  490. work.status = xpx.at(work.status)[i].set(eim._EVALUEERR)
  491. stop = xpx.at(stop)[i].set(True)
  492. # With infinite precision, there is a step size below which
  493. # all smaller step sizes will reduce the error. But in floating point
  494. # arithmetic, catastrophic cancellation will begin to cause the error
  495. # to increase again. This heuristic tries to avoid step sizes that are
  496. # too small. There may be more theoretically sound approaches for
  497. # detecting a step size that minimizes the total error, but this
  498. # heuristic seems simple and effective.
  499. i = (work.error > work.error_last*10) & ~stop
  500. work.status = xpx.at(work.status)[i].set(_EERRORINCREASE)
  501. stop = xpx.at(stop)[i].set(True)
  502. return stop
  503. def post_termination_check(work):
  504. return
  505. def customize_result(res, shape):
  506. return shape
  507. return eim._loop(work, callback, shape, maxiter, func, args, dtype,
  508. pre_func_eval, post_func_eval, check_termination,
  509. post_termination_check, customize_result, res_work_pairs,
  510. xp, preserve_shape)
  511. def _derivative_weights(work, n, xp):
  512. # This produces the weights of the finite difference formula for a given
  513. # stencil. In experiments, use of a second-order central difference formula
  514. # with Richardson extrapolation was more accurate numerically, but it was
  515. # more complicated, and it would have become even more complicated when
  516. # adding support for one-sided differences. However, now that all the
  517. # function evaluation values are stored, they can be processed in whatever
  518. # way is desired to produce the derivative estimate. We leave alternative
  519. # approaches to future work. To be more self-contained, here is the theory
  520. # for deriving the weights below.
  521. #
  522. # Recall that the Taylor expansion of a univariate, scalar-values function
  523. # about a point `x` may be expressed as:
  524. # f(x + h) = f(x) + f'(x)*h + f''(x)/2!*h**2 + O(h**3)
  525. # Suppose we evaluate f(x), f(x+h), and f(x-h). We have:
  526. # f(x) = f(x)
  527. # f(x + h) = f(x) + f'(x)*h + f''(x)/2!*h**2 + O(h**3)
  528. # f(x - h) = f(x) - f'(x)*h + f''(x)/2!*h**2 + O(h**3)
  529. # We can solve for weights `wi` such that:
  530. # w1*f(x) = w1*(f(x))
  531. # + w2*f(x + h) = w2*(f(x) + f'(x)*h + f''(x)/2!*h**2) + O(h**3)
  532. # + w3*f(x - h) = w3*(f(x) - f'(x)*h + f''(x)/2!*h**2) + O(h**3)
  533. # = 0 + f'(x)*h + 0 + O(h**3)
  534. # Then
  535. # f'(x) ~ (w1*f(x) + w2*f(x+h) + w3*f(x-h))/h
  536. # is a finite difference derivative approximation with error O(h**2),
  537. # and so it is said to be a "second-order" approximation. Under certain
  538. # conditions (e.g. well-behaved function, `h` sufficiently small), the
  539. # error in the approximation will decrease with h**2; that is, if `h` is
  540. # reduced by a factor of 2, the error is reduced by a factor of 4.
  541. #
  542. # By default, we use eighth-order formulae. Our central-difference formula
  543. # uses abscissae:
  544. # x-h/c**3, x-h/c**2, x-h/c, x-h, x, x+h, x+h/c, x+h/c**2, x+h/c**3
  545. # where `c` is the step factor. (Typically, the step factor is greater than
  546. # one, so the outermost points - as written above - are actually closest to
  547. # `x`.) This "stencil" is chosen so that each iteration, the step can be
  548. # reduced by the factor `c`, and most of the function evaluations can be
  549. # reused with the new step size. For example, in the next iteration, we
  550. # will have:
  551. # x-h/c**4, x-h/c**3, x-h/c**2, x-h/c, x, x+h/c, x+h/c**2, x+h/c**3, x+h/c**4
  552. # We do not reuse `x-h` and `x+h` for the new derivative estimate.
  553. # While this would increase the order of the formula and thus the
  554. # theoretical convergence rate, it is also less stable numerically.
  555. # (As noted above, there are other ways of processing the values that are
  556. # more stable. Thus, even now we store `f(x-h)` and `f(x+h)` in `work.fs`
  557. # to simplify future development of this sort of improvement.)
  558. #
  559. # The (right) one-sided formula is produced similarly using abscissae
  560. # x, x+h, x+h/d, x+h/d**2, ..., x+h/d**6, x+h/d**7, x+h/d**7
  561. # where `d` is the square root of `c`. (The left one-sided formula simply
  562. # uses -h.) When the step size is reduced by factor `c = d**2`, we have
  563. # abscissae:
  564. # x, x+h/d**2, x+h/d**3..., x+h/d**8, x+h/d**9, x+h/d**9
  565. # `d` is chosen as the square root of `c` so that the rate of the step-size
  566. # reduction is the same per iteration as in the central difference case.
  567. # Note that because the central difference formulas are inherently of even
  568. # order, for simplicity, we use only even-order formulas for one-sided
  569. # differences, too.
  570. # It's possible for the user to specify `fac` in, say, double precision but
  571. # `x` and `args` in single precision. `fac` gets converted to single
  572. # precision, but we should always use double precision for the intermediate
  573. # calculations here to avoid additional error in the weights.
  574. fac = float(work.fac)
  575. # Note that if the user switches back to floating point precision with
  576. # `x` and `args`, then `fac` will not necessarily equal the (lower
  577. # precision) cached `_derivative_weights.fac`, and the weights will
  578. # need to be recalculated. This could be fixed, but it's late, and of
  579. # low consequence.
  580. diff_state = work.diff_state
  581. if fac != diff_state.fac:
  582. diff_state.central = []
  583. diff_state.right = []
  584. diff_state.fac = fac
  585. if len(diff_state.central) != 2*n + 1:
  586. # Central difference weights. Consider refactoring this; it could
  587. # probably be more compact.
  588. # Note: Using NumPy here is OK; we convert to xp-type at the end
  589. i = np.arange(-n, n + 1)
  590. p = np.abs(i) - 1. # center point has power `p` -1, but sign `s` is 0
  591. s = np.sign(i)
  592. h = s / fac ** p
  593. A = np.vander(h, increasing=True).T
  594. b = np.zeros(2*n + 1)
  595. b[1] = 1
  596. weights = np.linalg.solve(A, b)
  597. # Enforce identities to improve accuracy
  598. weights[n] = 0
  599. for i in range(n):
  600. weights[-i-1] = -weights[i]
  601. # Cache the weights. We only need to calculate them once unless
  602. # the step factor changes.
  603. diff_state.central = weights
  604. # One-sided difference weights. The left one-sided weights (with
  605. # negative steps) are simply the negative of the right one-sided
  606. # weights, so no need to compute them separately.
  607. i = np.arange(2*n + 1)
  608. p = i - 1.
  609. s = np.sign(i)
  610. h = s / np.sqrt(fac) ** p
  611. A = np.vander(h, increasing=True).T
  612. b = np.zeros(2 * n + 1)
  613. b[1] = 1
  614. weights = np.linalg.solve(A, b)
  615. diff_state.right = weights
  616. return (xp.asarray(diff_state.central, dtype=work.dtype),
  617. xp.asarray(diff_state.right, dtype=work.dtype))
  618. @xp_capabilities(skip_backends=[('array_api_strict', _array_api_strict_skip_reason),
  619. ('dask.array', _dask_reason)], jax_jit=False)
  620. def jacobian(f, x, *, tolerances=None, maxiter=10, order=8, initial_step=0.5,
  621. step_factor=2.0, step_direction=0):
  622. r"""Evaluate the Jacobian of a function numerically.
  623. Parameters
  624. ----------
  625. f : callable
  626. The function whose Jacobian is desired. The signature must be::
  627. f(xi: ndarray) -> ndarray
  628. where each element of ``xi`` is a finite real. If the function to be
  629. differentiated accepts additional arguments, wrap it (e.g. using
  630. `functools.partial` or ``lambda``) and pass the wrapped callable
  631. into `jacobian`. `f` must not mutate the array ``xi``. See Notes
  632. regarding vectorization and the dimensionality of the input and output.
  633. x : float array_like
  634. Points at which to evaluate the Jacobian. Must have at least one dimension.
  635. See Notes regarding the dimensionality and vectorization.
  636. tolerances : dictionary of floats, optional
  637. Absolute and relative tolerances. Valid keys of the dictionary are:
  638. - ``atol`` - absolute tolerance on the derivative
  639. - ``rtol`` - relative tolerance on the derivative
  640. Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
  641. `atol` is the smallest normal number of the appropriate dtype, and
  642. the default `rtol` is the square root of the precision of the
  643. appropriate dtype.
  644. maxiter : int, default: 10
  645. The maximum number of iterations of the algorithm to perform. See
  646. Notes.
  647. order : int, default: 8
  648. The (positive integer) order of the finite difference formula to be
  649. used. Odd integers will be rounded up to the next even integer.
  650. initial_step : float array_like, default: 0.5
  651. The (absolute) initial step size for the finite difference derivative
  652. approximation. Must be broadcastable with `x` and `step_direction`.
  653. step_factor : float, default: 2.0
  654. The factor by which the step size is *reduced* in each iteration; i.e.
  655. the step size in iteration 1 is ``initial_step/step_factor``. If
  656. ``step_factor < 1``, subsequent steps will be greater than the initial
  657. step; this may be useful if steps smaller than some threshold are
  658. undesirable (e.g. due to subtractive cancellation error).
  659. step_direction : integer array_like
  660. An array representing the direction of the finite difference steps (e.g.
  661. for use when `x` lies near to the boundary of the domain of the function.)
  662. Must be broadcastable with `x` and `initial_step`.
  663. Where 0 (default), central differences are used; where negative (e.g.
  664. -1), steps are non-positive; and where positive (e.g. 1), all steps are
  665. non-negative.
  666. Returns
  667. -------
  668. res : _RichResult
  669. An object similar to an instance of `scipy.optimize.OptimizeResult` with the
  670. following attributes. The descriptions are written as though the values will
  671. be scalars; however, if `f` returns an array, the outputs will be
  672. arrays of the same shape.
  673. success : bool array
  674. ``True`` where the algorithm terminated successfully (status ``0``);
  675. ``False`` otherwise.
  676. status : int array
  677. An integer representing the exit status of the algorithm.
  678. - ``0`` : The algorithm converged to the specified tolerances.
  679. - ``-1`` : The error estimate increased, so iteration was terminated.
  680. - ``-2`` : The maximum number of iterations was reached.
  681. - ``-3`` : A non-finite value was encountered.
  682. df : float array
  683. The Jacobian of `f` at `x`, if the algorithm terminated
  684. successfully.
  685. error : float array
  686. An estimate of the error: the magnitude of the difference between
  687. the current estimate of the Jacobian and the estimate in the
  688. previous iteration.
  689. nit : int array
  690. The number of iterations of the algorithm that were performed.
  691. nfev : int array
  692. The number of points at which `f` was evaluated.
  693. Each element of an attribute is associated with the corresponding
  694. element of `df`. For instance, element ``i`` of `nfev` is the
  695. number of points at which `f` was evaluated for the sake of
  696. computing element ``i`` of `df`.
  697. See Also
  698. --------
  699. derivative, hessian
  700. Notes
  701. -----
  702. Suppose we wish to evaluate the Jacobian of a function
  703. :math:`f: \mathbf{R}^m \rightarrow \mathbf{R}^n`. Assign to variables
  704. ``m`` and ``n`` the positive integer values of :math:`m` and :math:`n`,
  705. respectively, and let ``...`` represent an arbitrary tuple of integers.
  706. If we wish to evaluate the Jacobian at a single point, then:
  707. - argument `x` must be an array of shape ``(m,)``
  708. - argument `f` must be vectorized to accept an array of shape ``(m, ...)``.
  709. The first axis represents the :math:`m` inputs of :math:`f`; the remainder
  710. are for evaluating the function at multiple points in a single call.
  711. - argument `f` must return an array of shape ``(n, ...)``. The first
  712. axis represents the :math:`n` outputs of :math:`f`; the remainder
  713. are for the result of evaluating the function at multiple points.
  714. - attribute ``df`` of the result object will be an array of shape ``(n, m)``,
  715. the Jacobian.
  716. This function is also vectorized in the sense that the Jacobian can be
  717. evaluated at ``k`` points in a single call. In this case, `x` would be an
  718. array of shape ``(m, k)``, `f` would accept an array of shape
  719. ``(m, k, ...)`` and return an array of shape ``(n, k, ...)``, and the ``df``
  720. attribute of the result would have shape ``(n, m, k)``.
  721. Suppose the desired callable ``f_not_vectorized`` is not vectorized; it can
  722. only accept an array of shape ``(m,)``. A simple solution to satisfy the required
  723. interface is to wrap ``f_not_vectorized`` as follows::
  724. def f(x):
  725. return np.apply_along_axis(f_not_vectorized, axis=0, arr=x)
  726. Alternatively, suppose the desired callable ``f_vec_q`` is vectorized, but
  727. only for 2-D arrays of shape ``(m, q)``. To satisfy the required interface,
  728. consider::
  729. def f(x):
  730. m, batch = x.shape[0], x.shape[1:] # x.shape is (m, ...)
  731. x = np.reshape(x, (m, -1)) # `-1` is short for q = prod(batch)
  732. res = f_vec_q(x) # pass shape (m, q) to function
  733. n = res.shape[0]
  734. return np.reshape(res, (n,) + batch) # return shape (n, ...)
  735. Then pass the wrapped callable ``f`` as the first argument of `jacobian`.
  736. References
  737. ----------
  738. .. [1] Jacobian matrix and determinant, *Wikipedia*,
  739. https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant
  740. Examples
  741. --------
  742. The Rosenbrock function maps from :math:`\mathbf{R}^m \rightarrow \mathbf{R}`;
  743. the SciPy implementation `scipy.optimize.rosen` is vectorized to accept an
  744. array of shape ``(m, p)`` and return an array of shape ``p``. Suppose we wish
  745. to evaluate the Jacobian (AKA the gradient because the function returns a scalar)
  746. at ``[0.5, 0.5, 0.5]``.
  747. >>> import numpy as np
  748. >>> from scipy.differentiate import jacobian
  749. >>> from scipy.optimize import rosen, rosen_der
  750. >>> m = 3
  751. >>> x = np.full(m, 0.5)
  752. >>> res = jacobian(rosen, x)
  753. >>> ref = rosen_der(x) # reference value of the gradient
  754. >>> res.df, ref
  755. (array([-51., -1., 50.]), array([-51., -1., 50.]))
  756. As an example of a function with multiple outputs, consider Example 4
  757. from [1]_.
  758. >>> def f(x):
  759. ... x1, x2, x3 = x
  760. ... return [x1, 5*x3, 4*x2**2 - 2*x3, x3*np.sin(x1)]
  761. The true Jacobian is given by:
  762. >>> def df(x):
  763. ... x1, x2, x3 = x
  764. ... one = np.ones_like(x1)
  765. ... return [[one, 0*one, 0*one],
  766. ... [0*one, 0*one, 5*one],
  767. ... [0*one, 8*x2, -2*one],
  768. ... [x3*np.cos(x1), 0*one, np.sin(x1)]]
  769. Evaluate the Jacobian at an arbitrary point.
  770. >>> rng = np.random.default_rng(389252938452)
  771. >>> x = rng.random(size=3)
  772. >>> res = jacobian(f, x)
  773. >>> ref = df(x)
  774. >>> res.df.shape == (4, 3)
  775. True
  776. >>> np.allclose(res.df, ref)
  777. True
  778. Evaluate the Jacobian at 10 arbitrary points in a single call.
  779. >>> x = rng.random(size=(3, 10))
  780. >>> res = jacobian(f, x)
  781. >>> ref = df(x)
  782. >>> res.df.shape == (4, 3, 10)
  783. True
  784. >>> np.allclose(res.df, ref)
  785. True
  786. """
  787. xp = array_namespace(x)
  788. x0 = xp_promote(x, force_floating=True, xp=xp)
  789. if x0.ndim < 1:
  790. message = "Argument `x` must be at least 1-D."
  791. raise ValueError(message)
  792. m = x0.shape[0]
  793. i = xp.arange(m)
  794. def wrapped(x):
  795. p = () if x.ndim == x0.ndim else (x.shape[-1],) # number of abscissae
  796. new_shape = (m, m) + x0.shape[1:] + p
  797. xph = xp.expand_dims(x0, axis=1)
  798. if x.ndim != x0.ndim:
  799. xph = xp.expand_dims(xph, axis=-1)
  800. xph = xp_copy(xp.broadcast_to(xph, new_shape), xp=xp)
  801. xph = xpx.at(xph)[i, i].set(x)
  802. return f(xph)
  803. res = derivative(wrapped, x, tolerances=tolerances,
  804. maxiter=maxiter, order=order, initial_step=initial_step,
  805. step_factor=step_factor, preserve_shape=True,
  806. step_direction=step_direction)
  807. del res.x # the user knows `x`, and the way it gets broadcasted is meaningless here
  808. return res
  809. @xp_capabilities(skip_backends=[('array_api_strict', _array_api_strict_skip_reason),
  810. ('dask.array', _dask_reason)], jax_jit=False)
  811. def hessian(f, x, *, tolerances=None, maxiter=10,
  812. order=8, initial_step=0.5, step_factor=2.0):
  813. r"""Evaluate the Hessian of a function numerically.
  814. Parameters
  815. ----------
  816. f : callable
  817. The function whose Hessian is desired. The signature must be::
  818. f(xi: ndarray) -> ndarray
  819. where each element of ``xi`` is a finite real. If the function to be
  820. differentiated accepts additional arguments, wrap it (e.g. using
  821. `functools.partial` or ``lambda``) and pass the wrapped callable
  822. into `hessian`. `f` must not mutate the array ``xi``. See Notes
  823. regarding vectorization and the dimensionality of the input and output.
  824. x : float array_like
  825. Points at which to evaluate the Hessian. Must have at least one dimension.
  826. See Notes regarding the dimensionality and vectorization.
  827. tolerances : dictionary of floats, optional
  828. Absolute and relative tolerances. Valid keys of the dictionary are:
  829. - ``atol`` - absolute tolerance on the derivative
  830. - ``rtol`` - relative tolerance on the derivative
  831. Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
  832. `atol` is the smallest normal number of the appropriate dtype, and
  833. the default `rtol` is the square root of the precision of the
  834. appropriate dtype.
  835. order : int, default: 8
  836. The (positive integer) order of the finite difference formula to be
  837. used. Odd integers will be rounded up to the next even integer.
  838. initial_step : float, default: 0.5
  839. The (absolute) initial step size for the finite difference derivative
  840. approximation.
  841. step_factor : float, default: 2.0
  842. The factor by which the step size is *reduced* in each iteration; i.e.
  843. the step size in iteration 1 is ``initial_step/step_factor``. If
  844. ``step_factor < 1``, subsequent steps will be greater than the initial
  845. step; this may be useful if steps smaller than some threshold are
  846. undesirable (e.g. due to subtractive cancellation error).
  847. maxiter : int, default: 10
  848. The maximum number of iterations of the algorithm to perform. See
  849. Notes.
  850. Returns
  851. -------
  852. res : _RichResult
  853. An object similar to an instance of `scipy.optimize.OptimizeResult` with the
  854. following attributes. The descriptions are written as though the values will
  855. be scalars; however, if `f` returns an array, the outputs will be
  856. arrays of the same shape.
  857. success : bool array
  858. ``True`` where the algorithm terminated successfully (status ``0``);
  859. ``False`` otherwise.
  860. status : int array
  861. An integer representing the exit status of the algorithm.
  862. - ``0`` : The algorithm converged to the specified tolerances.
  863. - ``-1`` : The error estimate increased, so iteration was terminated.
  864. - ``-2`` : The maximum number of iterations was reached.
  865. - ``-3`` : A non-finite value was encountered.
  866. ddf : float array
  867. The Hessian of `f` at `x`, if the algorithm terminated
  868. successfully.
  869. error : float array
  870. An estimate of the error: the magnitude of the difference between
  871. the current estimate of the Hessian and the estimate in the
  872. previous iteration.
  873. nfev : int array
  874. The number of points at which `f` was evaluated.
  875. Each element of an attribute is associated with the corresponding
  876. element of `ddf`. For instance, element ``[i, j]`` of `nfev` is the
  877. number of points at which `f` was evaluated for the sake of
  878. computing element ``[i, j]`` of `ddf`.
  879. See Also
  880. --------
  881. derivative, jacobian
  882. Notes
  883. -----
  884. Suppose we wish to evaluate the Hessian of a function
  885. :math:`f: \mathbf{R}^m \rightarrow \mathbf{R}`, and we assign to variable
  886. ``m`` the positive integer value of :math:`m`. If we wish to evaluate
  887. the Hessian at a single point, then:
  888. - argument `x` must be an array of shape ``(m,)``
  889. - argument `f` must be vectorized to accept an array of shape
  890. ``(m, ...)``. The first axis represents the :math:`m` inputs of
  891. :math:`f`; the remaining axes indicated by ellipses are for evaluating
  892. the function at several abscissae in a single call.
  893. - argument `f` must return an array of shape ``(...)``.
  894. - attribute ``dff`` of the result object will be an array of shape ``(m, m)``,
  895. the Hessian.
  896. This function is also vectorized in the sense that the Hessian can be
  897. evaluated at ``k`` points in a single call. In this case, `x` would be an
  898. array of shape ``(m, k)``, `f` would accept an array of shape
  899. ``(m, ...)`` and return an array of shape ``(...)``, and the ``ddf``
  900. attribute of the result would have shape ``(m, m, k)``. Note that the
  901. axis associated with the ``k`` points is included within the axes
  902. denoted by ``(...)``.
  903. Currently, `hessian` is implemented by nesting calls to `jacobian`.
  904. All options passed to `hessian` are used for both the inner and outer
  905. calls with one exception: the `rtol` used in the inner `jacobian` call
  906. is tightened by a factor of 100 with the expectation that the inner
  907. error can be ignored. A consequence is that `rtol` should not be set
  908. less than 100 times the precision of the dtype of `x`; a warning is
  909. emitted otherwise.
  910. References
  911. ----------
  912. .. [1] Hessian matrix, *Wikipedia*,
  913. https://en.wikipedia.org/wiki/Hessian_matrix
  914. Examples
  915. --------
  916. The Rosenbrock function maps from :math:`\mathbf{R}^m \rightarrow \mathbf{R}`;
  917. the SciPy implementation `scipy.optimize.rosen` is vectorized to accept an
  918. array of shape ``(m, ...)`` and return an array of shape ``...``. Suppose we
  919. wish to evaluate the Hessian at ``[0.5, 0.5, 0.5]``.
  920. >>> import numpy as np
  921. >>> from scipy.differentiate import hessian
  922. >>> from scipy.optimize import rosen, rosen_hess
  923. >>> m = 3
  924. >>> x = np.full(m, 0.5)
  925. >>> res = hessian(rosen, x)
  926. >>> ref = rosen_hess(x) # reference value of the Hessian
  927. >>> np.allclose(res.ddf, ref)
  928. True
  929. `hessian` is vectorized to evaluate the Hessian at multiple points
  930. in a single call.
  931. >>> rng = np.random.default_rng(4589245925010)
  932. >>> x = rng.random((m, 10))
  933. >>> res = hessian(rosen, x)
  934. >>> ref = [rosen_hess(xi) for xi in x.T]
  935. >>> ref = np.moveaxis(ref, 0, -1)
  936. >>> np.allclose(res.ddf, ref)
  937. True
  938. """
  939. # todo:
  940. # - add ability to vectorize over additional parameters (*args?)
  941. # - error estimate stack with inner jacobian (or use legit 2D stencil)
  942. kwargs = dict(maxiter=maxiter, order=order, initial_step=initial_step,
  943. step_factor=step_factor)
  944. tolerances = {} if tolerances is None else tolerances
  945. atol = tolerances.get('atol', None)
  946. rtol = tolerances.get('rtol', None)
  947. xp = array_namespace(x)
  948. x0 = xp_promote(x, force_floating=True, xp=xp)
  949. finfo = xp.finfo(x0.dtype)
  950. rtol = finfo.eps**0.5 if rtol is None else rtol # keep same as `derivative`
  951. # tighten the inner tolerance to make the inner error negligible
  952. rtol_min = finfo.eps * 100
  953. message = (f"The specified `{rtol=}`, but error estimates are likely to be "
  954. f"unreliable when `rtol < {rtol_min}`.")
  955. if 0 < rtol < rtol_min: # rtol <= 0 is an error
  956. warnings.warn(message, RuntimeWarning, stacklevel=2)
  957. rtol = rtol_min
  958. def df(x):
  959. tolerances = dict(rtol=rtol/100, atol=atol)
  960. temp = jacobian(f, x, tolerances=tolerances, **kwargs)
  961. nfev.append(temp.nfev if len(nfev) == 0 else temp.nfev.sum(axis=-1))
  962. return temp.df
  963. nfev = [] # track inner function evaluations
  964. res = jacobian(df, x, tolerances=tolerances, **kwargs) # jacobian of jacobian
  965. nfev = xp.cumulative_sum(xp.stack(nfev), axis=0)
  966. res_nit = xp.astype(res.nit[xp.newaxis, ...], xp.int64) # appease torch
  967. res.nfev = xp.take_along_axis(nfev, res_nit, axis=0)[0]
  968. res.ddf = res.df
  969. del res.df # this is renamed to ddf
  970. del res.nit # this is only the outer-jacobian nit
  971. return res