.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/verification/merge_prediction.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_verification_merge_prediction.py: Warm starts from the optimal mesh ================================= This script checks the merge rules that build ``mesh_optimal``, the mesh a later call with ``same_f=True`` starts from. After an integration, pairs of neighbouring subintervals are merged when the merged subinterval is predicted to pass its tolerance with a margin. With ``merge_rule="predicted"`` (the default) the merged subinterval's integral and error estimate are computed from the integrand values already stored for the two neighbours, by interpolation; with ``merge_rule="power_law"`` (padaquad 1.3.0 and 1.4.0) the neighbours' summed error is multiplied by ``2**(error_exponent - 1)``. See the user guide, "The optimal mesh and the merge rule". What a warm start must not do is make the result less accurate than the call it started from. Each chain below is one call from an explicit starting mesh (the cold call) followed by four ``same_f=True`` calls (the warm calls). A warm call passes when its error is at most the largest of - the tolerance ``max(atol, rtol * |I|)``; - 1.05 times the cold call's error (a cold call already outside the tolerance is a limit of the error estimate, not of merging); - the sum of the rounding floors ``50 * eps * |Q_i|`` of its subintervals, the accuracy padaquad accepts when the tolerance is below what the dtype can resolve. The script also checks that ``"predicted"`` costs no more integrand evaluations than ``"power_law"`` on a smooth integrand, and prints the evaluations of both for every chain. Run it with:: python examples/verification/merge_prediction.py It exits with status 1 if a check fails, except for the known limitation of ``dopri5`` explained below, which is reported as ``[KNOWN]``. Known limitation: no merge rule can see what the stored values miss ------------------------------------------------------------------- Every merge rule decides from values the integration already stored. A feature that lies between the stored nodes is invisible to all of them, and the next call evaluates the merged subinterval at new nodes. For Gauss-Kronrod and Clenshaw-Curtis methods the merged subinterval's error estimate then catches the feature and the subinterval is split again. ``dopri5``'s error weights are much smaller than its integration weights at some nodes, so its estimate can accept the merged subinterval with a larger error, under every merge rule. .. GENERATED FROM PYTHON SOURCE LINES 51-58 Warm-start chains in float64 ---------------------------- Every method except ``adaptive_heun`` and ``fehlberg2`` (their meshes are large at this tolerance), on three integrands with known integrals: a smooth one, a narrow peak and a kink. Every chain starts from 16 equal subintervals, so the output is the same on every machine. .. GENERATED FROM PYTHON SOURCE LINES 58-151 .. code-block:: Python from __future__ import annotations import math import torch from padaquad import UNIFORM_METHODS, VARIABLE_METHODS, adaptive_quadrature THIRD = 1.0 / 3.0 INTEGRANDS = { "exp": (torch.exp, math.e - 1.0), "peak": ( lambda t: 1.0 / (1.0 + 625.0 * (t - 0.5) ** 2), 2.0 * math.atan(12.5) / 25.0, ), "kink": (lambda t: torch.abs(t - THIRD), (THIRD**2 + (1.0 - THIRD) ** 2) / 2.0), } KNOWN_LIMITATIONS = {"dopri5"} N_WARM = 4 failures = 0 known = 0 def chain(sampling, name, f, exact, mesh, dtype, merge_rule, atol, rtol): """Run a cold call from ``mesh`` and N_WARM same_f calls. Returns the warm calls' integrand evaluations, their starting subintervals that had to be split again, the worst warm error divided by its bound, and whether every warm call is finite and converged. """ solver = adaptive_quadrature( sampling, name, atol=atol, rtol=rtol, dtype=dtype, device="cpu", max_batch=100_000, merge_rule=merge_rule, ) count = [0] def counted(t): count[0] += t.shape[0] return f(t) eps = torch.finfo(dtype).eps tol = max(atol, rtol * abs(exact)) cold = solver.integrate(f=counted, mesh=mesh, take_gradient=False) cold_error = abs(float(cold.integral) - exact) count[0] = 0 splits, worst, healthy = 0, 0.0, True for _ in range(N_WARM): warm = solver.integrate(f=counted, same_f=True, take_gradient=False) floor = float((50 * eps * warm.mesh_quadratures.abs()).sum()) bound = max(tol, 1.05 * cold_error, floor) worst = max(worst, abs(float(warm.integral) - exact) / bound) splits += warm.n_start_steps_split healthy &= bool(torch.isfinite(warm.integral).all()) and warm.converged return count[0], splits, worst, healthy runs = [ ("uniform", n) for n in UNIFORM_METHODS if n not in ("adaptive_heun", "fehlberg2") ] runs += [("variable", n) for n in VARIABLE_METHODS if n not in UNIFORM_METHODS] mesh = torch.linspace(0.0, 1.0, 17, dtype=torch.float64).unsqueeze(-1) print( f"{'method':24s} {'integrand':9s} {'warm evaluations':>17s} {'(power_law)':>12s} " f"{'re-split':>9s} {'worst error/bound':>18s}" ) for sampling, name in runs: for fname, (f, exact) in INTEGRANDS.items(): evals, splits, worst, healthy = chain( sampling, name, f, exact, mesh, torch.float64, "predicted", 1e-6, 1e-5 ) evals_old, *_ = chain( sampling, name, f, exact, mesh, torch.float64, "power_law", 1e-6, 1e-5 ) print( f"{name:24s} {fname:9s} {evals:17d} {evals_old:12d} {splits:9d} {worst:18.2e}" ) if worst > 1.0 or not healthy: status = "KNOWN" if name in KNOWN_LIMITATIONS else "FAIL" known += status == "KNOWN" failures += status == "FAIL" print(f" [{status}] {name} on {fname}: a warm call is outside its bound") if fname == "exp" and evals > evals_old: failures += 1 print(f" [FAIL] {name} on exp: predicted used more evaluations") .. rst-class:: sphx-glr-script-out .. code-block:: none method integrand warm evaluations (power_law) re-split worst error/bound bosh3 exp 260 260 0 8.46e-02 bosh3 peak 1444 1444 0 1.35e-02 bosh3 kink 100 100 0 2.03e-01 dopri5 exp 116 116 0 3.42e-03 dopri5 peak 396 396 0 9.72e-01 dopri5 kink 158 158 0 9.52e-01 gk7 exp 139 139 0 2.58e-11 gk7 peak 481 508 0 6.21e-06 gk7 kink 211 211 0 1.05e-01 gk15 exp 259 259 0 2.58e-11 gk15 peak 480 531 0 7.59e-08 gk15 kink 395 395 0 2.38e-01 gk21 exp 349 349 0 2.58e-11 gk21 peak 510 648 0 8.26e-10 gk21 kink 533 533 0 5.27e-02 gk31 exp 499 499 0 2.58e-11 gk31 peak 664 730 0 6.52e-10 gk31 kink 730 730 0 1.97e-01 cc5 exp 104 104 0 5.03e-06 cc5 peak 644 644 0 1.31e-03 cc5 kink 119 119 0 9.48e-01 cc9 exp 139 139 0 9.17e-10 cc9 peak 481 481 0 2.77e-05 cc9 kink 211 211 0 3.32e-02 cc17 exp 259 259 0 2.58e-11 cc17 peak 378 531 0 9.72e-05 cc17 kink 395 395 0 1.00e-01 cc33 exp 499 499 0 2.58e-11 cc33 peak 664 730 0 2.72e-07 cc33 kink 730 730 0 2.46e-01 cc65 exp 979 979 0 2.58e-11 cc65 peak 1044 1434 0 2.33e-11 cc65 kink 1434 1434 0 7.17e-02 interpolatory3_variable exp 388 388 0 3.31e-05 interpolatory3_variable peak 1660 1660 0 9.62e-04 interpolatory3_variable kink 82 82 0 0.00e+00 .. GENERATED FROM PYTHON SOURCE LINES 152-159 Rounding-level tolerances ------------------------- At rtol = 1e-14 the tolerance of sin(200 t), whose integral is about 200 times smaller than the sum of the subintervals' absolute contributions, is below what float64 can certify, and sin(2 pi t) integrates to 0, so only the rounding floors set its tolerance. Every chain starts from 64 equal subintervals. .. GENERATED FROM PYTHON SOURCE LINES 159-178 .. code-block:: Python mesh = torch.linspace(0.0, 1.0, 65, dtype=torch.float64).unsqueeze(-1) rounding = { "sin(200 t)": (lambda t: torch.sin(200.0 * t), (1.0 - math.cos(200.0)) / 200.0), "sin(2 pi t)": (lambda t: torch.sin(2.0 * math.pi * t), 0.0), } for name in ("gk21", "cc33", "cc65"): for fname, (f, exact) in rounding.items(): evals, splits, worst, healthy = chain( "uniform", name, f, exact, mesh, torch.float64, "predicted", 0.0, 1e-14 ) print( f"{name:6s} rtol 1e-14 {fname:12s} warm evaluations {evals:6d}, " f"re-split {splits}, worst error/bound {worst:.2e}" ) if worst > 1.0 or not healthy: failures += 1 print(f" [FAIL] {name} on {fname}: a warm call is outside its bound") .. rst-class:: sphx-glr-script-out .. code-block:: none gk21 rtol 1e-14 sin(200 t) warm evaluations 5432, re-split 0, worst error/bound 6.77e-03 gk21 rtol 1e-14 sin(2 pi t) warm evaluations 1384, re-split 0, worst error/bound 1.96e-03 cc33 rtol 1e-14 sin(200 t) warm evaluations 7924, re-split 0, worst error/bound 3.67e-03 cc33 rtol 1e-14 sin(2 pi t) warm evaluations 1984, re-split 0, worst error/bound 9.82e-04 cc65 rtol 1e-14 sin(200 t) warm evaluations 14044, re-split 0, worst error/bound 1.25e-02 cc65 rtol 1e-14 sin(2 pi t) warm evaluations 3904, re-split 0, worst error/bound 7.85e-03 .. GENERATED FROM PYTHON SOURCE LINES 179-185 float32 ------- In float32 the error estimates of the high-degree methods sit at the rounding level, where ``"power_law"`` merges nothing; ``"predicted"`` must stay finite and within the bound. .. GENERATED FROM PYTHON SOURCE LINES 185-206 .. code-block:: Python mesh = torch.linspace(0.0, 1.0, 17, dtype=torch.float32).unsqueeze(-1) for name in ("gk21", "cc33"): for fname in ("exp", "kink"): f, exact = INTEGRANDS[fname] evals, splits, worst, healthy = chain( "uniform", name, f, exact, mesh, torch.float32, "predicted", 1e-5, 1e-5 ) evals_old, *_ = chain( "uniform", name, f, exact, mesh, torch.float32, "power_law", 1e-5, 1e-5 ) print( f"{name:6s} float32 {fname:5s} warm evaluations {evals:5d} " f"(power_law {evals_old:5d}), re-split {splits}, worst error/bound {worst:.2e}" ) if worst > 1.0 or not healthy: failures += 1 print( f" [FAIL] {name} on {fname} in float32: a warm call is outside its bound" ) .. rst-class:: sphx-glr-script-out .. code-block:: none gk21 float32 exp warm evaluations 349 (power_law 1476), re-split 0, worst error/bound 9.07e-03 gk21 float32 kink warm evaluations 510 (power_law 1384), re-split 0, worst error/bound 5.79e-02 cc33 float32 exp warm evaluations 499 (power_law 2116), re-split 0, worst error/bound 9.07e-03 cc33 float32 kink warm evaluations 730 (power_law 2116), re-split 0, worst error/bound 6.99e-02 .. GENERATED FROM PYTHON SOURCE LINES 207-209 Result ------ .. GENERATED FROM PYTHON SOURCE LINES 209-217 .. code-block:: Python if known: print(f"[KNOWN] {known} chain(s) of a method with a known limitation exceeded") print(" the bound (see the explanation at the top of this script).") if failures: print(f"[FAIL] {failures} check(s) failed.") raise SystemExit(1) print("Every warm start stayed within its bound.") .. rst-class:: sphx-glr-script-out .. code-block:: none Every warm start stayed within its bound. .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.447 seconds) .. _sphx_glr_download_auto_examples_verification_merge_prediction.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: merge_prediction.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: merge_prediction.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: merge_prediction.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_