mirror of
https://github.com/fjosw/pyerrors.git
synced 2026-08-04 11:31:21 +02:00
* [chore] Stricter ruff rules * [chore] Furture lint rules and removal of flake8 * [ci] Bump github action versions * [chore] Add additional test coverage * Revert RNG switch to np.random.default_rng() Restore use of the global np.random state in pseudo_Obs (misc.py) and the prior id generation (fits.py), keeping seed behavior unchanged. The switch to a module-local generator is out of scope for this lint-focused PR. * Silence NPY002 on intentional legacy np.random calls The RNG migration was reverted to keep np.random.seed() behavior, so add per-line noqa: NPY002 on the three legacy np.random calls instead of the Generator API. * [Fix] Fix exception messages
44 lines
1.5 KiB
Python
44 lines
1.5 KiB
Python
import numpy as np
|
|
import scipy.optimize
|
|
from autograd import jacobian
|
|
|
|
from .obs import derived_observable
|
|
|
|
|
|
def find_root(d, func, guess=1.0, **kwargs):
|
|
r'''Finds the root of the function func(x, d) where d is an `Obs`.
|
|
|
|
Parameters
|
|
-----------------
|
|
d : Obs
|
|
Obs passed to the function.
|
|
func : object
|
|
Function to be minimized. Any numpy functions have to use the autograd.numpy wrapper.
|
|
Example:
|
|
```python
|
|
import autograd.numpy as anp
|
|
def root_func(x, d):
|
|
return anp.exp(-x ** 2) - d
|
|
```
|
|
guess : float
|
|
Initial guess for the minimization.
|
|
|
|
Returns
|
|
-------
|
|
res : Obs
|
|
`Obs` valued root of the function.
|
|
'''
|
|
d_val = np.vectorize(lambda x: x.value)(np.array(d))
|
|
|
|
root = scipy.optimize.fsolve(func, guess, d_val)
|
|
|
|
# Error propagation as detailed in arXiv:1809.01289
|
|
try:
|
|
dx = jacobian(func)(root[0], d_val)
|
|
da = jacobian(lambda u, v: func(v, u))(d_val, root[0])
|
|
except (TypeError, ValueError, np.linalg.LinAlgError):
|
|
raise Exception("It is required to use autograd.numpy instead of numpy within root functions, see the documentation for details.") from None
|
|
deriv = - da / dx
|
|
res = derived_observable(lambda x, **kwargs: (x[0] + np.finfo(np.float64).eps) / (np.array(d).reshape(-1)[0].value + np.finfo(np.float64).eps) * root[0],
|
|
np.array(d).reshape(-1), man_grad=np.array(deriv).reshape(-1))
|
|
return res
|