Source code for pnps.calibrate

# SPDX-FileCopyrightText: 2026 John C. Travers and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later

"""Accuracy harnesses: Richardson step calibration and the observed order.

There is no in-loop error norm in this package — deliberately. A whole-field local
truncation error, the usual adaptive-step control, is blind to the four-wave-mixing
signal living orders of magnitude below the pumps in the same array. Here the error is
controlled on the *measured quantity*: run the fixed-step propagation at step target h
and h/2 and compare every extracted observable (:func:`richardson_metric`, or per save
plane and window with :func:`richardson_table`); confirm the expected convergence order
(:func:`convergence_order`); then run the production scan at a step size whose metric is
comfortably below the target accuracy.

The propagation is solprop's Runge-Kutta march (DOPRI5, fifth order) replayed
on a fixed schedule, so a healthy configuration shows an observed order near 5;
the first-Born check that validates the emergent signal independently of any
stepper is :func:`pnps.reference.first_born_signal`.
"""

from collections.abc import Mapping
from dataclasses import dataclass

import numpy as np
from jaxtyping import Float

from pnps.bridge import build_bridge
from pnps.setup import Setup
from pnps.simulate import OBSERVABLES, run_delay_point

__all__ = [
    "RichardsonTable",
    "convergence_order",
    "richardson_metric",
    "richardson_table",
]


[docs] @dataclass(frozen=True) class RichardsonTable: """The h against h/2 differences of every observable, per save plane and window. Attributes ---------- h_target : float The coarser step target ``h``, m. difference : mapping of str to numpy.ndarray For each observable of :data:`pnps.simulate.OBSERVABLES`, the largest absolute difference over frequency between the h and h/2 runs: ``(n_z, n_windows)`` for the windowed spectra, ``(n_z,)`` for ``i_omega_full``. peak : mapping of str to numpy.ndarray The h/2 run's peak over frequency, the same shapes. alias_fraction : numpy.ndarray The h/2 run's share of the energy outside the inner momentum box at each plane, ``(n_z,)`` (:attr:`pnps.observables.Observation.alias_fraction`). """ h_target: float difference: Mapping[str, Float[np.ndarray, "*shape"]] peak: Mapping[str, Float[np.ndarray, "*shape"]] alias_fraction: Float[np.ndarray, " n_z"]
[docs] def relative(self, key: str) -> Float[np.ndarray, "*shape"]: """Return one observable's differences over its own peaks. A spectrum with a zero peak (a window dark at the entrance) contributes zero. Parameters ---------- key : str An observable of :data:`pnps.simulate.OBSERVABLES`. Returns ------- numpy.ndarray ``difference / peak``, the shape of ``difference[key]``. """ peak = self.peak[key] return self.difference[key] / np.where(peak > 0, peak, np.inf)
[docs] @property def worst(self) -> float: # numpydoc ignore=RT01 """The largest peak-normalised difference over everything compared.""" return max(float(np.max(self.relative(key))) for key in self.difference)
[docs] def richardson_metric( setup: Setup, tau: float, zsave: Float[np.ndarray, " n_z"], h_target: float, *, backend: str = "auto", ) -> float: """Worst peak-normalised observable change between step targets h and h/2. For every save position, window and observable, the difference between the h and h/2 runs is normalised to that spectrum's peak — the error measure a trace retrieval sees (max abs difference over the trace peak). Bin-relative errors in near-empty spectral wings are deliberately *not* what this reports: a few-percent wiggle on a 1e-4-of-peak bin is a 1e-6 trace error. Parameters ---------- setup : Setup The configuration (:func:`pnps.setup.build_setup`). tau : float The delay to probe, in s. tau = 0 (maximum beam overlap, strongest nonlinearity) is the worst case; check one large delay as well. zsave : numpy.ndarray Save positions, as for :func:`pnps.simulate.simulate_delay_point`. h_target : float The candidate step target in m. backend : str Backend registry name in solprop, see :func:`pnps.bridge.build_bridge`. Returns ------- float ``D(h)`` — the maximum peak-normalised difference over everything compared. The production run should use an ``h_target`` with ``D`` comfortably below the accuracy you need. For the fifth-order march, ``D`` is the h-run's own error up to a factor ``32/31`` and the h/2-run's error is about ``D/31``. """ return richardson_table(setup, tau, zsave, h_target, backend=backend).worst
[docs] def richardson_table( setup: Setup, tau: float, zsave: Float[np.ndarray, " n_z"], h_target: float, *, backend: str = "auto", ) -> RichardsonTable: """Tabulate the h against h/2 differences per save plane, window and observable. The table behind :func:`richardson_metric`, whose number is its :attr:`RichardsonTable.worst`. Keeping the differences and the peaks apart lets a caller normalise by a trace's peak over several delays rather than by each spectrum's own. Parameters ---------- setup : Setup The configuration (:func:`pnps.setup.build_setup`). tau : float The delay to probe, in s. zsave : numpy.ndarray Save positions, as for :func:`pnps.simulate.simulate_delay_point`. h_target : float The coarser step target in m. backend : str Backend registry name in solprop, see :func:`pnps.bridge.build_bridge`. Returns ------- RichardsonTable The differences, the h/2 run's peaks and its aliasing proxy. """ coarse, fine = ( _run(setup, tau, zsave, h, backend) for h in (h_target, h_target / 2) ) return RichardsonTable( h_target=float(h_target), difference={ key: np.max(np.abs(coarse[key] - fine[key]), axis=-1) for key in OBSERVABLES }, peak={key: np.max(fine[key], axis=-1) for key in OBSERVABLES}, alias_fraction=np.asarray(fine["alias_fraction"], dtype=float), )
[docs] def convergence_order( setup: Setup, tau: float, zsave: Float[np.ndarray, " n_z"], h_list: list[float], *, backend: str = "auto", ) -> tuple[Float[np.ndarray, " n_h"], Float[np.ndarray, " n_h-1"]]: """Observed convergence order between successive step targets. Runs :func:`richardson_metric` for each ``h`` in ``h_list`` (typically a halving sequence) and returns the metrics with the pairwise observed orders ``log2(D(h_i) / D(h_{i+1})) / log2(h_i / h_{i+1})``. The replayed DOPRI5 march shows orders near 5 in its asymptotic regime — this is itself a correctness test of the stepper on your configuration. Parameters ---------- setup : Setup The configuration (:func:`pnps.setup.build_setup`). tau : float The delay to probe, in s. zsave : numpy.ndarray Save positions in m. h_list : list of float Step targets in m, decreasing. backend : str Backend registry name in solprop, see :func:`pnps.bridge.build_bridge`. Returns ------- tuple of numpy.ndarray ``(metrics, orders)`` with ``len(orders) == len(h_list) - 1``. """ metrics = np.array( [richardson_metric(setup, tau, zsave, h, backend=backend) for h in h_list] ) ratios = metrics[:-1] / metrics[1:] steps = np.array(h_list) orders = np.log2(ratios) / np.log2(steps[:-1] / steps[1:]) return metrics, orders
def _run( setup: Setup, tau: float, zsave: Float[np.ndarray, " n_z"], h_target: float, backend: str, ) -> dict[str, Float[np.ndarray, "*_"]]: """Run one delay point on a bridge built for this step target. Parameters ---------- setup : Setup The configuration. tau : float The delay in s. zsave : numpy.ndarray Save positions in m. h_target : float Largest step in m. backend : str Backend registry name in solprop. Returns ------- dict of numpy.ndarray The observables of :func:`pnps.simulate.run_delay_point`. """ with build_bridge(setup, zsave, h_target, backend=backend) as bridge: return run_delay_point(bridge, tau)