|
| 1 | +# Integration, derivatives, root finding and ODEs |
| 2 | + |
| 3 | +pynumerics wraps the Numerics calculus routines in four modules: |
| 4 | + |
| 5 | +| Module | Numerics types | |
| 6 | +| --- | --- | |
| 7 | +| `pynumerics.integration` | `Integration`, `TrapezoidalRule`, `SimpsonsRule`, `AdaptiveSimpsonsRule`, `AdaptiveSimpsonsRule2D`, `AdaptiveGaussKronrod`, `AdaptiveGaussKronrod2D`, `AdaptiveGaussLobatto`, `MonteCarloIntegration`, `Miser`, `Vegas`, `IntegrationStatus` | |
| 8 | +| `pynumerics.differentiation` | `NumericalDerivative` | |
| 9 | +| `pynumerics.roots` | `Bisection`, `Brent` (`brent_solve`, `brent_bracket`), `Secant`, `NewtonRaphson` | |
| 10 | +| `pynumerics.ode` | `RungeKutta` | |
| 11 | + |
| 12 | +Every function argument accepts any of three forms (see `pynumerics.callbacks`): |
| 13 | + |
| 14 | +- a Python callable, which crosses from .NET into Python on each evaluation (about 2 microseconds); |
| 15 | +- a string of C# source, compiled once with Roslyn, which runs entirely in .NET; |
| 16 | +- a .NET delegate of the right type. |
| 17 | + |
| 18 | +A Python callable and the equivalent C# source give the same bits, so code can start in Python |
| 19 | +and move hot integrands to C# without changing results. |
| 20 | + |
| 21 | +## Integration |
| 22 | + |
| 23 | +The fixed rules return a float: |
| 24 | + |
| 25 | +```python |
| 26 | +import math |
| 27 | +from pynumerics import integration |
| 28 | + |
| 29 | +f = lambda x: math.exp(-x * x) |
| 30 | +print(integration.gauss_legendre(f, -3.0, 3.0)) # 10-point Gauss-Legendre |
| 31 | +print(integration.gauss_legendre_20(f, -3.0, 3.0)) # 20-point Gauss-Legendre |
| 32 | +print(integration.trapezoidal_rule(f, -3.0, 3.0, 1000)) |
| 33 | +print(integration.simpsons_rule(f, -3.0, 3.0, 1000)) |
| 34 | +print(integration.midpoint_rule(f, -3.0, 3.0, 1000)) |
| 35 | +``` |
| 36 | + |
| 37 | +Each Numerics `Integrator` has an `integrate_*` function returning an `IntegrationResult` with |
| 38 | +`value`, `standard_error` (NaN when the method has none), `iterations`, `function_evaluations` and |
| 39 | +`status` (an `IntegrationStatus`). The `Integrator` settings are keyword arguments, listed in |
| 40 | +`integration.INTEGRATOR_SETTINGS`; anything left out keeps the Numerics default. |
| 41 | + |
| 42 | +```python |
| 43 | +import math |
| 44 | +from pynumerics import integration |
| 45 | +from pynumerics.integration import IntegrationStatus |
| 46 | + |
| 47 | +result = integration.integrate_adaptive_gauss_kronrod( |
| 48 | + lambda x: math.exp(-x * x), -3.0, 3.0, absolute_tolerance=1e-10, relative_tolerance=1e-10) |
| 49 | +print(result.value, result.standard_error, result.status) |
| 50 | +assert result.status is IntegrationStatus.SUCCESS |
| 51 | + |
| 52 | +# The same integral with a compiled C# integrand: no Python call per evaluation. |
| 53 | +compiled = integration.integrate_adaptive_gauss_kronrod("x => Math.Exp(-x * x)", -3.0, 3.0, |
| 54 | + absolute_tolerance=1e-10, relative_tolerance=1e-10) |
| 55 | +assert compiled == result |
| 56 | + |
| 57 | +print(integration.integrate_adaptive_simpson(math.sin, 0.0, math.pi).value) |
| 58 | +print(integration.integrate_adaptive_gauss_lobatto(math.sin, 0.0, math.pi).value) |
| 59 | +print(integration.integrate_trapezoidal(math.sin, 0.0, math.pi).value) |
| 60 | +print(integration.integrate_simpson(math.sin, 0.0, math.pi).value) |
| 61 | +``` |
| 62 | + |
| 63 | +The Gauss-Kronrod recorder reports every node of the accepted intervals, and both adaptive 1-D |
| 64 | +rules can integrate over stratification bins: |
| 65 | + |
| 66 | +```python |
| 67 | +import math |
| 68 | +from pynumerics import integration, sampling |
| 69 | + |
| 70 | +nodes = [] |
| 71 | +result = integration.integrate_adaptive_gauss_kronrod( |
| 72 | + lambda x: math.exp(-x * x), -3.0, 3.0, recorder=lambda x, w, fx: nodes.append((x, w, fx))) |
| 73 | +print(len(nodes), sum(w * fx for _, w, fx in nodes), result.value) |
| 74 | + |
| 75 | +bins = sampling.stratify_x_values(-3.0, 3.0, 4) |
| 76 | +print(integration.integrate_adaptive_gauss_kronrod(lambda x: math.exp(-x * x), -3.0, 3.0, bins=bins).value) |
| 77 | +``` |
| 78 | + |
| 79 | +`integrate_adaptive_gauss_kronrod` takes `method=`, an `AdaptiveGaussKronrodMethod` or its name. The |
| 80 | +default is local bisection. `method="qags"` runs QUADPACK QAGS, the |
| 81 | +algorithm behind `scipy.integrate.quad`, with the same evaluation counts and errors (results agree to |
| 82 | +rounding, since the Kronrod sum order differs). Choose it for endpoint |
| 83 | +singularities: `1 / sqrt(x)` on [0, 1] takes 231 evaluations and is accurate to about 1e-15, where local |
| 84 | +bisection takes 1911 and leaves an error of 5.5e-9. Keep the default for cheap smooth integrands, where QAGS |
| 85 | +is about 1.4 times slower, and for recorder sampling that must reproduce earlier nodes. |
| 86 | + |
| 87 | +```python |
| 88 | +import math |
| 89 | +from pynumerics import integration |
| 90 | + |
| 91 | +qags = integration.integrate_adaptive_gauss_kronrod(lambda x: 1.0 / math.sqrt(x), 0.0, 1.0, method="qags") |
| 92 | +print(qags.value, qags.function_evaluations) # 1.9999999999999993 231 |
| 93 | +``` |
| 94 | + |
| 95 | +Two-dimensional integrands take `(x, y)`: |
| 96 | + |
| 97 | +```python |
| 98 | +import math |
| 99 | +from pynumerics import integration |
| 100 | + |
| 101 | +f = lambda x, y: math.exp(-x * x - y * y) |
| 102 | +print(integration.integrate_adaptive_simpson_2d(f, -2.0, 2.0, -2.0, 2.0).value) |
| 103 | +print(integration.integrate_adaptive_gauss_kronrod_2d(f, -2.0, 2.0, -2.0, 2.0).value) |
| 104 | +``` |
| 105 | + |
| 106 | +The sampling integrators take box bounds; the integrand receives a NumPy array. `seed` fixes the |
| 107 | +Mersenne Twister. Vegas integrands also receive the sample weight, and Vegas returns a |
| 108 | +`VegasResult` with the chi-squared and the adapted grid: |
| 109 | + |
| 110 | +```python |
| 111 | +import numpy as np |
| 112 | +from pynumerics import integration |
| 113 | + |
| 114 | +lower, upper = [0.0, 0.0, 0.0], [1.0, 1.0, 1.0] |
| 115 | +square = lambda x: float(np.sum(x * x)) # the exact integral is 1 |
| 116 | +print(integration.integrate_monte_carlo(square, lower, upper, seed=7, max_iterations=40000).value) |
| 117 | +print(integration.integrate_miser(square, lower, upper, max_function_evaluations=40000).value) |
| 118 | + |
| 119 | +vegas = integration.integrate_vegas(lambda x, w: float(np.sum(x * x)), lower, upper) |
| 120 | +print(vegas.value, vegas.standard_error, vegas.chi_squared, vegas.grid.shape) |
| 121 | + |
| 122 | +# A rare-event probability: P(U1 + U2 > 1.98) = 0.0002. |
| 123 | +tail = integration.integrate_vegas("(x, w) => x[0] + x[1] > 1.98 ? 1.0 : 0.0", [0.0, 0.0], [1.0, 1.0], |
| 124 | + rare_event_probability=2e-4) |
| 125 | +print(tail.value) |
| 126 | +``` |
| 127 | + |
| 128 | +None of these integrators has a parallel switch; every `integrate_*` function still applies |
| 129 | +`callbacks.apply_parallel_policy`, so a Python callback never runs on several threads. |
| 130 | + |
| 131 | +## Derivatives |
| 132 | + |
| 133 | +```python |
| 134 | +import math |
| 135 | +import numpy as np |
| 136 | +from pynumerics import differentiation |
| 137 | + |
| 138 | +print(differentiation.derivative(math.exp, 1.0)) # central difference |
| 139 | +print(differentiation.forward_difference(math.exp, 1.0)) |
| 140 | +print(differentiation.backward_difference(math.exp, 1.0)) |
| 141 | +print(differentiation.central_difference(math.exp, 1.0, step_size=1e-4)) |
| 142 | +print(differentiation.ridders(math.exp, 1.0)) # (derivative, error estimate); default step 0.1 * (1 + |x|) |
| 143 | +# The default step 0.105 leaves the domain of the logarithm, where f returns NaN, so it is halved: about 20 |
| 144 | +print(differentiation.ridders(lambda x: math.log(x) if x > 0 else math.nan, 0.05)) |
| 145 | +print(differentiation.second_derivative(math.exp, 1.0)) |
| 146 | +print(differentiation.calculate_step_size(1.0)) |
| 147 | + |
| 148 | +f = lambda t: float(t[0] ** 2 * t[1]) |
| 149 | +print(differentiation.gradient(f, [1.0, 2.0])) |
| 150 | +print(differentiation.hessian(f, [1.0, 2.0])) |
| 151 | +print(differentiation.jacobian(lambda t: np.array([t[0] * t[1], t[0] ** 2]), [1.0, 2.0])) |
| 152 | +print(differentiation.jacobian_at(lambda x, t: t[0] * math.exp(t[1] * x), [0.0, 1.0, 2.0], [1.5, 0.5])) |
| 153 | +``` |
| 154 | + |
| 155 | +`gradient`, `hessian` and `jacobian` accept `lower_bounds` and `upper_bounds` and switch to |
| 156 | +one-sided differences near a bound. |
| 157 | + |
| 158 | +## Root finding |
| 159 | + |
| 160 | +```python |
| 161 | +import numpy as np |
| 162 | +from pynumerics import roots |
| 163 | + |
| 164 | +f = lambda x: x * x - 2.0 |
| 165 | +print(roots.bisection_solve(f, 1.0, 0.0, 4.0)) |
| 166 | +print(roots.secant_solve(f, 0.0, 4.0)) |
| 167 | +print(roots.newton_raphson_solve(f, lambda x: 2.0 * x, 1.0)) |
| 168 | +print(roots.newton_raphson_robust_solve(f, lambda x: 2.0 * x, 1.0, 0.0, 4.0)) |
| 169 | +print(roots.brent_solve(f, 0.0, 4.0)) |
| 170 | + |
| 171 | +# A system: x^2 + y^2 = 4 and x = y. |
| 172 | +solution = roots.newton_raphson_solve_system( |
| 173 | + lambda x: np.array([x[0] ** 2 + x[1] ** 2 - 4.0, x[0] - x[1]]), |
| 174 | + lambda x: np.array([[2.0 * x[0], 2.0 * x[1]], [1.0, -1.0]]), |
| 175 | + [1.0, 1.0]) |
| 176 | +print(solution) |
| 177 | +``` |
| 178 | + |
| 179 | +A solver that fails raises `ValueError` with the Numerics message; pass `report_failure=False` to |
| 180 | +get the last iterate instead. |
| 181 | + |
| 182 | +`brent_solve` is a literal port of SciPy's `brentq.c`: `brent_solve(f, a, b, xtol, maxiter, |
| 183 | +relative_tolerance=rtol)` returns the same float as `scipy.optimize.brentq(f, a, b, xtol=xtol, |
| 184 | +rtol=rtol, maxiter=maxiter)`. The default `relative_tolerance` is |
| 185 | +`roots.BRENT_MINIMUM_RELATIVE_TOLERANCE` (4 * 2**-52), SciPy's default and smallest `rtol`. |
| 186 | + |
| 187 | +```python |
| 188 | +from pynumerics import roots |
| 189 | + |
| 190 | +print(roots.brent_solve(lambda x: x * x - 2.0, 0.0, 2.0, 1e-12, relative_tolerance=1e-10)) # 1.4142135623731364 |
| 191 | +``` |
| 192 | + |
| 193 | +## ODE solvers |
| 194 | + |
| 195 | +The right-hand side is `f(t, y)` for one state variable: |
| 196 | + |
| 197 | +```python |
| 198 | +import math |
| 199 | +from pynumerics import ode |
| 200 | + |
| 201 | +f = lambda t, y: -2.0 * t * y # y = exp(-t^2) |
| 202 | +print(ode.runge_kutta_fourth_order(f, 1.0, 0.0, 2.0, 11)) # values on 11 even times |
| 203 | +print(ode.runge_kutta_second_order(f, 1.0, 0.0, 2.0, 11)) |
| 204 | +print(ode.runge_kutta_fourth_order_step(f, 1.0, 0.0, 0.1)) # one step |
| 205 | +print(ode.runge_kutta_fehlberg(f, 1.0, 0.0, 2.0, 1e-6, 1e-10), math.exp(-4.0)) |
| 206 | +print(ode.runge_kutta_cash_karp("(t, y) => -2.0 * t * y", 1.0, 0.0, 2.0, 1e-6, 1e-10)) |
| 207 | +``` |