# SPDX-FileCopyrightText: 2026 John C. Travers and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""The bridge to solprop: this package's instrument model on solprop's free-space route.
solprop integrates the propagation; this package forms the input and reduces the
output. The bridge is everything in between, built once per configuration and reused
for every delay point of a scan:
- **grids** -- :meth:`solprop.grid.EnvelopeGrid.from_limits`, with its temporal collar
placed inside the requested window (``collar_placement="inside"``: this package
zeroes the collar's rates, so outside would only widen the grid), and
:class:`solprop.grid.FreeGrid` with no room for a real-space collar reproduce this
package's :func:`pnps.grids.time_grid` and :func:`pnps.grids.space_grid` sample for
sample;
:func:`check_grid_rule` refuses to proceed if they ever stop doing so;
- **operator** -- the fused-silica index (optmat's fit), a
:class:`solprop.linear.Frame` *pinned* to this package's co-moving frame
``beta1_ref omega + beta0_ref``, the envelope Kerr response, and this package's
spectral absorber as an :class:`solprop.boundaries.Absorber` with zero temporal rates;
- **schedule** -- a :class:`solprop.stepper.schedule.FixedSchedule` of equal steps
of at most ``h_target`` with every save plane a schedule edge, replayed by
solprop's Runge-Kutta march (the low-storage RK4IP by default, or DOPRI5) so there
is no dense output and no interpolation;
- **backend and reducer** -- the solprop backend holding the state, and the host
:class:`~pnps.reduce_numba.Reducer` that turns each saved plane into the measured
spectra.
The transverse-wavevector ramp is solprop's safety ramp, its
:class:`solprop.boundaries.SpatialAbsorber` without a real-space collar
(``Config.transverse_absorber``). solprop's 200 /m evanescent clamp is left at its
default (no active pair is evanescent on the production grid, so it cannot act;
``docs/dev/numerics.md``, "Evanescent census").
All the numbers that justify these identities are in ``docs/dev/numerics.md``.
"""
import dataclasses
import hashlib
import logging
import warnings
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from typing import Literal
import numpy as np
from jaxtyping import Complex, Float
from scipy.constants import c, epsilon_0
from solprop import __version__ as solprop_version
from solprop import boundaries
from solprop.backends.protocol import Backend
from solprop.boundaries import Absorber, SpatialAbsorber
from solprop.driver import Simulation, SimulationRunner, SimulationSettings
from solprop.grid import EnvelopeGrid, FreeGrid
from solprop.linear import Frame
from solprop.monitor import DEFAULT_BOUNDARY_CHECK, BoundaryCheck
from solprop.nonlinear.raman import bundle_response
from solprop.nonlinear.responses import KerrResponse
from solprop.output import CallbackOutput, SavedPlane
from solprop.physdata.glasses import SilicaBundle
from solprop.spatial import EVANESCENT_RATE, SpatialMedium
from solprop.stats import StatsSpec
from solprop.stepper import (
FixedSchedule,
LowStorageRungeKutta,
PIController,
RungeKutta,
)
from solprop.translate.problem import PropagationProblem
from solprop.translate.routes import transverse_of
from pnps.absorber import band_edges
from pnps.exact_windows import ExactWindows, nyquist_reach
from pnps.exceptions import ConfigError, EngineError, GridRuleError
from pnps.geometry import signal_half_plane
from pnps.kernels import size_thread_pool
from pnps.materials import (
SILICA_BUNDLE,
beta0_ref,
beta1_ref,
silica_index,
silica_k2,
silica_medium,
)
from pnps.observables import Observation
from pnps.pulse import energy_prefactor
from pnps.reduce_numba import Reducer
from pnps.reference import OperatorTables, apply_linear, configured_tables
from pnps.setup import Setup
from pnps.statistics import (
StatisticsScale,
observation_from_statistics,
statistics_spec,
statistics_unavailable,
)
__all__ = [
"ABSORBER_REFERENCE_LENGTH",
"BOUNDARY_CHECK",
"TABLEAUS",
"Bridge",
"Reduction",
"ReductionChoice",
"bridge_tables",
"build_bridge",
"check_grid_rule",
"peak_kerr_rate",
]
logger = logging.getLogger(__name__)
#: Where a saved plane is reduced to the observables: ``"host"`` copies the field out
#: of solprop and reduces it with :class:`~pnps.reduce_numba.Reducer`; ``"solprop"``
#: keeps no field and reads solprop's far-field statistics (:mod:`pnps.statistics`).
Reduction = Literal["host", "solprop"]
#: The reduction a configuration asks for: one of :data:`Reduction`, or ``"auto"``,
#: which takes ``"solprop"`` whenever solprop accepts the windows without a caveat
#: (:func:`pnps.statistics.statistics_unavailable`) and ``"host"`` otherwise.
ReductionChoice = Literal["auto", "host", "solprop"]
#: The march's photon-number coefficient: one Runge-Kutta step of length h may add at
#: most this times ``(kerr_rate * h)**2`` to the relative photon number
#: (:meth:`Bridge.photon_allowance`). The measurement it rests on is in
#: ``docs/dev/numerics.md``, "Photon number and the growth guard".
_MARCH_PHOTON_COEFFICIENT = 1e-2
#: Transforms per step that bound the march's rounding: two per stage of DOPRI5's seven
#: (RK4IP has four), and one for the combination of the stages.
_TRANSFORMS_PER_STEP = 15
#: The tableau each stepper's replayed Runge-Kutta march uses, recorded in every file.
TABLEAUS: dict[str, str] = {"rk4ip": "RK4IP", "dopri5": "DOPRI5"}
#: How solprop's boundary monitor watches a run. The time window is not watched:
#: this package's protection there is the lap budget
#: (:func:`pnps.absorber.spectral_absorber`), which by design lets walked-off light fill
#: the window, guards included, and removes only what would wrap onto the pulse; what
#: it removes is reported (``lap_lost``). A
#: guard check would warn about light the model means to carry, so its budget is the
#: whole field (a guard occupancy cannot exceed one). The transverse edge is watched at
#: solprop's default budget: light reaching it in real space would wrap round the
#: periodic grid, which nothing else here guards against.
BOUNDARY_CHECK = BoundaryCheck(
budget=1.0,
stop_factor=1.0,
transverse_budget=DEFAULT_BOUNDARY_CHECK.edge_budget,
)
#: Reference length of the spectral absorber, m: solprop caps a rate at
#: ``60 / reference_length``, so 5 um admits 1.2e7 /m, above the 1e7 /m power rate of
#: the default ``gamma_max``. It only sets that cap; the rate itself is given.
ABSORBER_REFERENCE_LENGTH = 5e-6
[docs]
@dataclass(frozen=True)
class Bridge:
"""One configuration set up on solprop, reusable across delay points.
Built by :func:`build_bridge`. Holds solprop's runner and its backend, whose
buffers persist until :meth:`close` (or the end of a ``with`` block): build one
bridge per scan, not one per delay point.
Attributes
----------
setup : Setup
The configuration this bridge runs.
zsave : numpy.ndarray
Save positions in m, strictly increasing from ``>= 0``; a position at 0 is
the input itself.
h_target : float
Largest step of the replayed schedule, m.
chi3 : float
The total chi3 given to solprop, m^2/V^2 (``setup.chi3``). With Raman the Kerr
response holds ``1 - f_R`` of it and the Raman response ``f_R``.
kerr_rate : float
The peak nonlinear wavenumber ``k0 n2 I`` of this configuration's input,
which no delay or plane exceeds, 1/m (:func:`peak_kerr_rate`); zero for a
linear bridge.
It scales the march's photon-number allowance (:meth:`photon_allowance`).
grid : solprop.grid.EnvelopeGrid
The temporal grid.
space : solprop.grid.FreeGrid
The transverse grid, no collar.
medium : solprop.spatial.SpatialMedium
The slab.
frame : solprop.linear.Frame
The co-moving frame (pinned unless built with ``pin_frame=False``).
responses : tuple
The nonlinear responses (the Kerr response, or empty for a linear run).
absorber : solprop.boundaries.Absorber
The spectral absorber, as solprop's power rate.
schedule : solprop.stepper.schedule.FixedSchedule
The replayed step schedule.
settings : solprop.driver.simulation.SimulationSettings
The settings the problem was translated with.
simulation : solprop.driver.simulation.Simulation
The translated simulation.
problem : solprop.translate.problem.PropagationProblem
The kernel problem the backend steps.
runner : solprop.driver.simulation.SimulationRunner
solprop's runner: the one backend every delay point runs on
(:attr:`backend`).
reducer : Reducer
The host reduction of saved planes (with ``reduction = "solprop"`` it only
computes the time-window edge diagnostic, when that is asked for).
reduction : {"host", "solprop"}
Where planes are reduced (:data:`Reduction`).
stats_spec : solprop.stats.StatsSpec or None
The statistics solprop evaluates at every plane with ``reduction =
"solprop"``; None for the host reduction.
scale : StatisticsScale or None
The constants turning those statistics into this package's units.
metadata : mapping
``/grid`` provenance keys describing this engine (see
:func:`pnps.io_h5.scan_grid_metadata`).
identity : str
A digest of the configuration, which with a delay names an input in
solprop's record in place of a SHA-256 of its bytes.
exact : ExactWindows or None
With ``Config.exact_windows`` and the host reduction, the windows' exact
hard-disc masks, which replace the rendered windows' spectra on the band;
None otherwise (through solprop the exact discs are its apertures).
tables : OperatorTables or None
With ``Config.exact_windows`` and the host reduction, the configured
operator, which carries the input to each plane for the subtraction; None
otherwise.
"""
setup: Setup
zsave: Float[np.ndarray, " n_z"]
h_target: float
chi3: float
kerr_rate: float
grid: EnvelopeGrid
space: FreeGrid
medium: SpatialMedium
frame: Frame
responses: tuple[object, ...]
absorber: Absorber
schedule: FixedSchedule
settings: SimulationSettings
simulation: Simulation
problem: PropagationProblem
runner: SimulationRunner
reducer: Reducer
reduction: Reduction
stats_spec: StatsSpec | None
scale: StatisticsScale | None
metadata: Mapping[str, object]
identity: str
exact: ExactWindows | None = None
tables: OperatorTables | None = None
[docs]
@property
def backend(self) -> Backend:
"""Return the solprop backend holding the state, the runner's.
Returns
-------
solprop.backends.protocol.Backend
The backend every delay point runs on.
"""
return self.runner.backend
[docs]
def visit(
self,
field0: Complex[np.ndarray, "n_y n_x n_omega"],
visitor: Callable[[float, Complex[np.ndarray, "n_y n_x n_omega"]], None],
*,
tau: float | None = None,
arms: Sequence[str] | None = None,
) -> None:
"""Propagate one input state and hand the field at every position to a callback.
The field is solprop's own buffer, read-only and valid only while ``visitor``
runs, so one plane at a time is ever held: this is the streaming form of
:meth:`march`, for studies at the production shape.
Parameters
----------
field0 : numpy.ndarray
The input state ``(n, n, nt)``, complex128, C-contiguous, at z = 0.
visitor : callable
Called with the position in m and the field there, ``(n, n, nt)``, at every
position of :attr:`zsave`, in order. Copy what must outlive the call.
tau : float or None, optional
The delay ``field0`` was formed for, which names the input in solprop's
record instead of a digest of its bytes; None digests it.
arms : sequence of str or None, optional
The arms ``field0`` was formed with (:func:`pnps.form_input.form_input`),
when not all of them: they complete the input's name, so that inputs of
one delay with different arms are told apart in solprop's record. Only
used with ``tau``.
Raises
------
ConfigError
If ``field0`` has the wrong shape, type or layout.
EngineError
If the bridge reduces with solprop's statistics, whose planes carry no
field.
"""
if self.reduction != "host":
raise EngineError(
"visiting the field needs reduction='host': solprop's statistics "
"keep no field"
)
n, nt = self.setup.sgrid.n, self.setup.tgrid.nt
def receive(z: float, plane: SavedPlane) -> None:
"""Hand the plane's field on in this package's layout.
Parameters
----------
z : float
The position, m.
plane : solprop.output.schema.SavedPlane
The saved plane.
"""
visitor(z, _field_of(plane).reshape(n, n, nt))
inputs = [field0]
del field0
self._run(inputs, receive, tau=tau, arms=arms)
[docs]
def march(
self,
field0: Complex[np.ndarray, "n_y n_x n_omega"],
*,
tau: float | None = None,
) -> list[tuple[float, Complex[np.ndarray, "n_y n_x n_omega"]]]:
"""Propagate one input state and return a copy of the field at every position.
Every field is kept, so this is for tests and small grids: a run keeps only
the reductions (:meth:`observations`), and a study streams the planes
(:meth:`visit`).
Parameters
----------
field0 : numpy.ndarray
The input state ``(n, n, nt)``, complex128, C-contiguous, at z = 0.
tau : float or None, optional
The delay ``field0`` was formed for, which names the input in solprop's
record instead of a digest of its bytes; None digests it.
Returns
-------
list of tuple of (float, numpy.ndarray)
The position in m and a copy of the field there, ``(n, n, nt)``.
Raises
------
ConfigError
If ``field0`` has the wrong shape, type or layout.
EngineError
If the bridge reduces with solprop's statistics.
"""
fields: list[tuple[float, Complex[np.ndarray, "n_y n_x n_omega"]]] = []
self.visit(field0, lambda z, field: fields.append((z, field.copy())), tau=tau)
return fields
[docs]
def observations(
self,
field0: Complex[np.ndarray, "n_y n_x n_omega"],
*,
tau: float | None = None,
) -> list[tuple[float, Observation]]:
"""Propagate one input state and return the observables at every position.
With ``reduction = "host"`` each plane's field, solprop's own read-only
observation, is reduced by :attr:`reducer` before the march goes on. With
``"solprop"`` no field leaves solprop (unless the time-window edge
diagnostic, which solprop cannot form, is asked for): the observables are
its statistics in this package's units (:mod:`pnps.statistics`). The
photon number ``sum eta |E|^2 / omega`` is checked at every plane: the
envelope Kerr and Raman responses conserve it and every absorber removes
it, so growth between two planes beyond the march's allowance
(:meth:`photon_allowance`) stops the run. The energy is not checked: the
Kerr response moves it physically, in proportion to the nonlinear phase.
Parameters
----------
field0 : numpy.ndarray
The input state ``(n, n, nt)``, complex128, C-contiguous, at z = 0. solprop
lets it go once loaded, so a caller that passes it without keeping a
reference (``bridge.observations(form(...))``) frees it before the first
step.
tau : float or None, optional
The delay ``field0`` was formed for, which names the input in solprop's
record instead of a SHA-256 of its bytes; None digests it.
Returns
-------
list of tuple of (float, Observation)
The position in m and the plane's observables.
Raises
------
ConfigError
If ``field0`` has the wrong shape, type or layout.
EngineError
If the photon number grows between two planes by more than the march's
allowance.
"""
n, nt = self.setup.sgrid.n, self.setup.tgrid.nt
unspecified = self.stats_spec is None or self.scale is None
if self.reduction == "solprop" and unspecified:
raise EngineError("a solprop-reduction bridge was built without its spec")
observed: list[tuple[float, Observation]] = []
photons: list[float] = []
want_field = self.reduction == "host" or self.reducer.edge_diagnostic
# The exact windows integrate the nonlinear part, the field less the input
# carried by the linear operator: the input is held for the subtraction.
e0 = field0.copy() if self.exact is not None else None
def reduce(z: float, plane: SavedPlane) -> None:
"""Reduce the plane to its observables and check the photon number.
Parameters
----------
z : float
The position, m.
plane : solprop.output.schema.SavedPlane
The saved plane.
Raises
------
EngineError
If the photon number has grown since the previous plane by more
than the march's allowance.
"""
if self.reduction == "host":
field = _field_of(plane).reshape(n, n, nt)
obs = self.reducer.reduce(field)
if self.exact is not None:
assert e0 is not None and self.tables is not None # built so
obs = _exact_windows(
obs, self.exact, field - apply_linear(e0, self.tables, z)
)
else:
assert self.scale is not None # checked above
edge = (
self.reducer.edge_fraction(_field_of(plane).reshape(n, n, nt))
if want_field
else float("nan")
)
obs = observation_from_statistics(
{name: np.asarray(value) for name, value in plane.stats.items()},
self.scale,
self.setup.gd_band,
edge,
signal_row=self.setup.cfg.geometry == "sd",
)
count = _photon_number(obs.i_omega_beam, self.setup.tgrid.omega)
if observed:
z_previous, previous = observed[-1][0], photons[-1]
allowance = self.photon_allowance(z_previous, z)
if count - previous > allowance * previous:
raise EngineError(
f"photon number grew between z = {z_previous:.3g} m and "
f"{z:.3g} m (to {count:.9g} from {previous:.9g}, in units of "
f"the beam spectrum), beyond the march's relative allowance "
f"{allowance:.3g}: numerical instability"
)
observed.append((z, obs))
photons.append(count)
inputs = [field0]
del field0
self._run(inputs, reduce, tau=tau)
return observed
[docs]
def photon_allowance(self, z_start: float, z_end: float) -> float:
"""Return how much the march may raise the photon number between two planes.
The relative growth of ``sum eta |E|^2 / omega`` that the fixed-step march and
rounding can produce over the steps between two schedule edges; growth beyond
it is a numerical instability (:meth:`observations`).
Parameters
----------
z_start, z_end : float
Two schedule edges, m, ``z_start < z_end`` (two save positions).
Returns
-------
float
The allowed relative growth, dimensionless, ``>= 0``.
"""
# Physics: the envelope Kerr response without third-harmonic generation, with
# solprop's coupling omega^2 / (2 c^2 eps0 Re k_z) and the measure
# eta = c Re k_z / omega, changes the photon number sum eta |E|^2 / omega at
# the rate sum Im(E* P_NL) / (c eps0), which is the time integral of
# Im(E* P_NL) over the grid and vanishes for P_NL = chi |E|^2 E and for a
# real Raman response alike (Parseval). Every absorber only removes photons.
# Only the march and rounding can add them.
#
# March. A step of the interaction picture with a unitary linear part
# conserves the photon number to first order in the Kerr rate exactly: each
# stage's increment is P_NL of a linearly propagated state, carried by the
# same unitary, so its first-order contribution is a sum of the conserving
# terms above. The error therefore starts at (kerr_rate * h)^2 per step
# (measured: quadratic in the pulse energy to 0.3 % over a factor 100). Its
# coefficient rises steeply while the step resolves the pulse's dispersion
# (about 1e6 /m of phase across the 1 fs pulse's band) and slowly once it
# does not. Measured on the test grid (docs/dev/numerics.md) for one step of
# 0.31 to 10 um, both tableaus, both layouts, Kerr and Raman, nonlinear
# phases from 0.009 to 0.9 rad, it is at most 1.45e-3 (SD, RK4IP, 10 um),
# rising 1.3 times per doubling of the step beyond 2.5 um: one step through
# a 40 um slab would reach 2.5e-3. The coefficient is four times that, for
# pulses and layouts not measured. kerr_rate is the peak rate of the input,
# which no plane exceeds, so summing over the steps can only overstate it.
steps = self.schedule.steps
edges = self.schedule.edges
tolerance = 1e-9 * float(edges[-1]) # edges are sums of steps
inside = (edges[:-1] >= z_start - tolerance) & (edges[1:] <= z_end + tolerance)
march = (
_MARCH_PHOTON_COEFFICIENT
* self.kerr_rate**2
* float(np.sum(steps[inside] ** 2))
)
# Rounding. A transform of M points moves the field's norm by a relative
# error growing as log2(M) eps, and the photon number by twice that; a step
# makes at most _TRANSFORMS_PER_STEP of them. Each plane's photon number is
# a sum of M positive terms, with a relative rounding error of standard
# deviation sqrt(M) eps (Higham, Accuracy and Stability of Numerical
# Algorithms, 2nd ed., 2002, ch. 4 and 24). Nothing here is worst case, but
# every term is counted: the linear test runs move the photon number by 2e-16
# over eight steps, against 1.5e-12 here.
cells = self.setup.sgrid.n**2 * self.setup.tgrid.nt
eps = float(np.finfo(np.float64).eps)
rounding = (
2.0
* eps
* (
_TRANSFORMS_PER_STEP * int(np.count_nonzero(inside)) * np.log2(cells)
+ 2.0 * np.sqrt(cells)
)
)
return march + float(rounding)
def _run(
self,
inputs: list[Complex[np.ndarray, "n_y n_x n_omega"]],
receive: Callable[[float, SavedPlane], None],
*,
tau: float | None,
arms: Sequence[str] | None = None,
) -> None:
"""Run one input on the runner, handing each save position's plane on.
Parameters
----------
inputs : list of numpy.ndarray
One input state ``(n, n, nt)``, C-contiguous complex128, which this takes
out of the list: so no frame holds it while solprop marches, and solprop
frees it once loaded.
receive : callable
Called with the position in m and solprop's saved plane, at every
position of :attr:`zsave`; the plane's field is read-only and solprop's
own, valid until ``receive`` returns.
tau : float or None
The delay, naming the input in solprop's record; None digests it.
arms : sequence of str or None, optional
The arms the input was formed with, which complete its name; None for
all of them.
Raises
------
ConfigError
If the input has the wrong shape, dtype or memory layout.
"""
n, nt = self.setup.sgrid.n, self.setup.tgrid.nt
field0 = inputs[0]
if (
field0.shape != (n, n, nt)
or field0.dtype != np.complex128
or not field0.flags.c_contiguous
):
raise ConfigError(
f"field0 must be a C-contiguous complex128 array of shape {(n, n, nt)}"
)
# A no-copy view in solprop's (n_columns, n_pol, n_omega) layout: the column
# index ix + n_x * iy is the C-order flattening of [iy, ix].
inputs[0] = field0.reshape(n * n, 1, nt)
del field0
entrance = bool(self.zsave[0] == 0.0)
def save(plane: SavedPlane) -> None:
"""Hand a plane on, unless it is an entrance nobody asked for.
Parameters
----------
plane : solprop.output.schema.SavedPlane
The saved plane, solprop's own until this returns.
"""
z = float(plane.z)
# solprop always delivers the entrance; it is kept only when asked for.
if z == 0.0 and not entrance:
return
receive(z, plane)
# The input's name in solprop's record: a scan's cache and resume trust it, so
# a subset of the arms is named as such.
configuration: dict[str, object] | None = None
identity: str | None = None
if tau is not None:
configuration = {"delay": float(tau)}
identity = f"pnps {self.identity}, delay {float(tau)!r} s"
if arms is not None:
configuration["arms"] = "+".join(arms)
identity += f", arms {configuration['arms']}"
self.runner.run(
inputs.pop(),
output=CallbackOutput(save),
configuration=configuration,
input_identity=identity,
progress="none",
)
[docs]
def close(self) -> None:
"""Release the runner and its backend's buffers. Idempotent."""
self.runner.close()
def __enter__(self) -> "Bridge": # noqa: UP037 - bound after the class body
"""Return the bridge, to be closed when the block ends.
Returns
-------
Bridge
This bridge.
"""
return self
def __exit__(self, *exc_info: object) -> None:
"""Close the bridge.
Parameters
----------
*exc_info : object
The exception type, value and traceback, if any (ignored).
"""
self.close()
[docs]
def check_grid_rule(setup: Setup, grid: EnvelopeGrid, space: FreeGrid) -> None:
"""Refuse grids that no longer reproduce this package's sampling.
Everything this package hands solprop -- the formed input, the absorber, the
collection tables -- is laid out on :func:`pnps.grids.time_grid` and
:func:`pnps.grids.space_grid`, so solprop's grids must be the same grids. Phase
0 measured them equal (``docs/dev/numerics.md``); this checks it on every build.
Parameters
----------
setup : Setup
The configuration.
grid : solprop.grid.EnvelopeGrid
The temporal grid solprop built.
space : solprop.grid.FreeGrid
The transverse grid solprop built.
Raises
------
GridRuleError
Naming the first divergence: the sample count, the band mask, the frequency
axis (relative 1e-12) or the momentum axis (relative 1e-12).
"""
tgrid, sgrid = setup.tgrid, setup.sgrid
if grid.n_t != tgrid.nt:
raise GridRuleError(
f"solprop's envelope grid has n_t = {grid.n_t} samples where this "
f"package's time_grid has {tgrid.nt}"
)
active = np.asarray(grid.active_mask)
if not np.array_equal(active, tgrid.sidx):
differ = np.flatnonzero(active != tgrid.sidx)
raise GridRuleError(
f"solprop's active band differs from this package's sidx in "
f"{differ.size} bins (first at index {int(differ[0])})"
)
omega = np.asarray(grid.omega)
rel = np.max(np.abs(omega - tgrid.omega)) / np.max(np.abs(tgrid.omega))
if not rel <= 1e-12:
raise GridRuleError(
f"solprop's frequency axis differs from this package's by {rel:.3g} "
"(relative), above 1e-12"
)
for name, solprop_axis in (("k_x", space.k_x), ("k_y", space.k_y)):
k_axis = np.asarray(solprop_axis)
if k_axis.shape != sgrid.kx.shape:
raise GridRuleError(
f"solprop's {name} has {k_axis.size} samples where this package's "
f"space_grid has {sgrid.kx.size}"
)
rel = np.max(np.abs(k_axis - sgrid.kx)) / np.max(np.abs(sgrid.kx))
if not rel <= 1e-12:
raise GridRuleError(
f"solprop's {name} differs from this package's kx by {rel:.3g} "
"(relative), above 1e-12"
)
def _responses(chi3: float, raman_fraction: float) -> tuple[object, ...]:
"""Return solprop's nonlinear responses of the slab.
Without Raman (``raman_fraction == 0``) the whole chi3 is the instantaneous Kerr
response. With it, the instantaneous response keeps ``1 - f_R`` of chi3 and the
delayed one is optmat's silica bundle shape (solprop's
:func:`~solprop.nonlinear.raman.bundle_response`) carrying the fraction ``f_R``
of a kernel that integrates to ``(3/2) chi3``. The 3/2 is the envelope forms':
the Kerr polarisation is ``(3/4) eps_0 chi3 |A|^2 A`` and the Raman one
``(1/2) eps_0 (h * |A|^2) A``, so a kernel of integral ``X`` acts like a Kerr
chi3 of ``2X/3``, and ``(2/3) f_R (3/2) chi3 + (1 - f_R) chi3 = chi3``: the two
together hold the total and agree with an instantaneous run for long pulses.
(solprop leaves the Kerr reduction to the author of a fractional response, and
its GNLSE mapping, ``raman_susceptibility``, is the same 3/2.)
Parameters
----------
chi3 : float
The total chi3 given to solprop, m^2/V^2.
raman_fraction : float
The Raman fraction f_R, in ``[0, 1)``; 0 for an instantaneous medium.
Returns
-------
tuple
The Kerr response, then the Raman response when there is one.
"""
if raman_fraction == 0.0:
return (KerrResponse(chi3=chi3, thg=False),)
raman = bundle_response(
SilicaBundle.resolve(SILICA_BUNDLE),
amplitude=1.5 * chi3,
fraction=raman_fraction,
thg=False,
)
return (KerrResponse(chi3=(1.0 - raman_fraction) * chi3, thg=False), raman)
def _signal(setup: Setup) -> tuple[float, float] | None:
"""Return the SD signal region as a mask-plane edge, or None for TG.
Parameters
----------
setup : Setup
The configuration.
Returns
-------
tuple of float or None
:func:`pnps.geometry.signal_half_plane` of the configuration.
"""
cfg = setup.cfg
return signal_half_plane(
cfg.geometry, cfg.beam.f_foc, cfg.mask_diam, cfg.mask_spacing
)
def _resolve_reduction(choice: str, setup: Setup) -> Reduction:
"""Resolve a reduction choice to the reduction a bridge runs.
Parameters
----------
choice : str
``"auto"``, ``"host"`` or ``"solprop"``.
setup : Setup
The configuration whose windows ``"auto"`` asks solprop about, as exact
hard discs on the nonlinear field with ``Config.exact_windows``.
Returns
-------
{"host", "solprop"}
The reduction to run.
Raises
------
ConfigError
For an unknown choice.
"""
match choice:
case "host" | "solprop":
return choice
case "auto":
reason = statistics_unavailable(
setup.windows,
setup.sgrid.kx,
_signal(setup),
exact=setup.cfg.exact_windows,
)
if reason is None:
return "solprop"
logger.debug("reduction='auto' stays on the host: %s", reason)
return "host"
case _:
raise ConfigError(
f"reduction must be 'auto', 'host' or 'solprop', got {choice!r}"
)
def _field_of(plane: SavedPlane) -> Complex[np.ndarray, "n_columns n_pol n_omega"]:
"""Return a saved plane's field, which the run was translated to deliver.
Parameters
----------
plane : solprop.output.schema.SavedPlane
The plane.
Returns
-------
numpy.ndarray
Its field, read-only, solprop's own.
Raises
------
EngineError
If the plane carries no field.
"""
if plane.field is None:
raise EngineError(
f"solprop saved the plane at z = {plane.z:.6g} m without its field"
)
return plane.field
def _photon_number(
beam: Float[np.ndarray, " n_omega"], omega: Float[np.ndarray, " n_omega"]
) -> float:
"""Return a plane's photon number, ``sum eta |E|^2 / omega``, in arbitrary units.
``beam`` is the beam spectrum ``sum eta |E|^2`` per frequency bin
(``Observation.i_omega_beam``) and ``omega`` the absolute frequencies, rad/s; a
non-positive frequency carries no flux and is left out. Only ratios of it mean
anything (:meth:`Bridge.observations`).
"""
live = omega > 0.0
return float(np.sum(beam[live] / omega[live]))
[docs]
def peak_kerr_rate(setup: Setup) -> float:
"""Return the peak nonlinear wavenumber of a configuration's input.
``k0 n2 I_peak`` at the carrier, with ``I_peak = n0 eps_0 c |e_peak|^2 / 2`` and
``e_peak`` the coherent sum of the arms' on-axis field at the focal centre: the
arms' on-axis spectral amplitudes ``|A(omega)|``, each read from the beamlet's
on-axis spectrum (``Setup.beamlets.i_omega_beamlet_reimaged``, ``n(omega)
|A|^2`` near the axis), summed over frequency and arm (the triangle inequality).
A transform-limited input at zero delay attains it; any other delay or spectral
phase stays below it, and lossless linear propagation keeps every
``|E(k, omega)|``, so no plane exceeds it until self-focusing does. Reading the
arms' admittance ``n cos(theta)`` as ``n`` leaves it ``theta^2 / 2`` low, 1e-4
for the PNPS holes. Its product with a length bounds that length's peak
nonlinear phase (the B-integral).
Parameters
----------
setup : Setup
The configuration (:func:`pnps.setup.build_setup`).
Returns
-------
float
The rate, 1/m.
"""
tgrid = setup.tgrid
omega = tgrid.omega
k2 = np.real(silica_k2(tgrid, absorption=setup.cfg.absorption))
live = (k2 > 0.0) & (omega > 0.0)
index = np.sqrt(np.where(live, k2, 1.0)) * c / np.where(omega > 0.0, omega, 1.0)
on_axis = np.clip(setup.beamlets.i_omega_beamlet_reimaged, 0.0, None)
amplitude = np.where(live, np.sqrt(on_axis / index), 0.0)
# A(omega) is a temporal DFT coefficient, so the field's peak is at most their
# sum over nt; the arms share the beamlet's spectrum.
e_peak = float(np.sum(setup.former.weights)) * float(np.sum(amplitude)) / tgrid.nt
omega0 = 2.0 * np.pi * c / setup.cfg.lam0
n0 = float(np.real(silica_index(np.array([omega0]), absorption=False)[0]))
return omega0 / c * setup.n2 * n0 * epsilon_0 * c / 2.0 * e_peak**2
def _schedule_planes(
zsave: Float[np.ndarray, "*shape"],
) -> Float[np.ndarray, " n_planes"]:
"""Validate the save positions and return solprop's (strictly positive) planes.
Parameters
----------
zsave : numpy.ndarray
Save positions in m, 1-D, strictly increasing from ``>= 0``.
Returns
-------
numpy.ndarray
The positions of ``zsave`` after z = 0, in m.
Raises
------
ConfigError
If ``zsave`` is empty, not 1-D, not strictly increasing, starts before
z = 0, or has no position after z = 0.
"""
if zsave.ndim != 1 or zsave.size == 0:
raise ConfigError("zsave must be a non-empty 1-D array of positions")
if np.any(np.diff(zsave) <= 0):
raise ConfigError("zsave must be strictly increasing")
if zsave[0] < 0:
raise ConfigError("zsave must start at or after z = 0")
planes = zsave[zsave > 0]
if planes.size == 0:
raise ConfigError("zsave must contain at least one position after z = 0")
return planes
@dataclass(frozen=True)
class _Translation:
"""A configuration translated for solprop, before any backend allocates."""
setup: Setup
zsave: Float[np.ndarray, " n_z"]
h_target: float
chi3: float
grid: EnvelopeGrid
space: FreeGrid
medium: SpatialMedium
frame: Frame
responses: tuple[object, ...]
absorber: Absorber
schedule: FixedSchedule
settings: SimulationSettings
simulation: Simulation
problem: PropagationProblem
tables: OperatorTables
reduction: Reduction
stats_spec: StatsSpec | None
pin_frame: bool
def _translate( # noqa: PLR0913 - build_bridge's arguments, passed through
setup: Setup,
zsave: Float[np.ndarray, "*shape"] | Sequence[float],
h_target: float,
*,
backend: str,
node_budget: int | None,
nonlinear: bool,
pin_frame: bool,
reduction: str | None,
) -> _Translation:
"""Translate a configuration for solprop, as :func:`build_bridge` documents.
Everything up to the backend: the validation, the grids and their check, the
medium, frame, responses and absorber, the schedule and settings, and solprop's
translation of them into a kernel problem, which holds one field volume (the
placeholder input it copies).
Parameters
----------
setup : Setup
The configuration.
zsave : array_like
Save positions in m.
h_target : float
Largest step of the replayed schedule, m.
backend : str
The solprop backend registry name.
node_budget : int or None
The per-chunk memory budget of solprop in bytes; None takes the configuration's.
nonlinear : bool
Include the Kerr (and Raman) response.
pin_frame : bool
Pin solprop's co-moving frame to this package's.
reduction : str or None
Where planes are reduced, as the caller gave it (validated here); None
takes the configuration's.
Returns
-------
_Translation
The translated pieces.
"""
cfg, tgrid, sgrid = setup.cfg, setup.tgrid, setup.sgrid
reduction = _resolve_reduction(
cfg.reduction if reduction is None else reduction, setup
)
if cfg.exact_windows:
band = tgrid.omega[tgrid.sidx & (tgrid.omega > 0.0)]
reason = nyquist_reach(sgrid, band, setup.windows)
if reason is not None:
raise ConfigError(reason)
node_budget = cfg.node_budget if node_budget is None else node_budget
zsave = np.asarray(zsave, dtype=float)
planes = _schedule_planes(zsave)
if not (np.isfinite(h_target) and h_target > 0):
raise ConfigError(f"h_target must be finite and positive, got {h_target!r}")
with warnings.catch_warnings():
# solprop warns that the envelope grid's band is wider than the requested
# wavelength limits (its fine-grid conventions); the band mask is checked
# bit for bit below, which is the identity that matters here.
warnings.simplefilter("ignore", UserWarning)
# The grid's length is the run's own end, the last save position: solprop
# marches every run to its grid's length (its SEP 51).
grid = EnvelopeGrid.from_limits(
float(planes[-1]), cfg.lam0, cfg.lam_lims, cfg.trange, thg=False,
fft_size=cfg.fftsize, collar_placement="inside",
) # fmt: skip
half_width = cfg.r_max * 1.1
space = FreeGrid(half_width, sgrid.n, half_width, sgrid.n)
check_grid_rule(setup, grid, space)
medium = silica_medium(absorption=cfg.absorption)
if pin_frame:
b0, b1 = beta0_ref(cfg.lam0), beta1_ref(cfg.lam0)
omega0 = float(grid.omega0)
# solprop subtracts beta0 + beta1 (omega - omega0); this package subtracts
# beta1 omega + beta0_ref. Equal when beta0 = beta0_ref + beta1 omega0.
frame = Frame(
omega0=omega0, subtract_beta0=True, beta0=b0 + b1 * omega0, beta1=b1
)
else:
frame = Frame.comoving(grid, thg=False)
chi3 = setup.chi3
responses = _responses(chi3, setup.raman_fraction) if nonlinear else ()
# The spectral absorber is an amplitude rate here and a power rate in solprop.
# The temporal rates are zero: this package has no temporal window (the lap
# budget lives in gamma_omega), and with zero rates solprop takes no temporal
# pass. The transverse boundary is the safety ramp below.
edges = dataclasses.replace(
boundaries.absorber(grid, temporal=False),
spectral_rate=2.0 * band_edges(setup.tgrid, cfg.gamma_max),
reference_length=ABSORBER_REFERENCE_LENGTH,
)
absorber = boundaries.custom_absorber(grid, 2.0 * setup.gamma_lap, collar=edges)
# With the solprop reduction the planes are statistics-only (SEP 22 section 5.1)
# unless the edge diagnostic, a time-domain quantity no statistic forms, needs
# the field on the host. With the host reduction solprop forms no statistics:
# without a spec it would form its route's defaults (since solprop 0.3), which
# nothing here reads.
stats_spec = (
statistics_spec(
setup.windows, sgrid.kx, _signal(setup), exact=cfg.exact_windows
)
if reduction == "solprop"
else None
)
fields = "none" if reduction == "solprop" and not cfg.edge_diagnostic else "all"
# The transverse-wavevector safety ramp (solprop's SEP 40 design), with no
# real-space collar: the grid has no room outside the requested size for one.
spatial_absorber: SpatialAbsorber | Literal[False] = (
SpatialAbsorber(real_space=False, safety_fraction=cfg.transverse_fraction)
if cfg.transverse_absorber
else False
)
z_end = float(planes[-1])
schedule = FixedSchedule.uniform(0.0, z_end, h_target, save_planes=planes)
settings = SimulationSettings(
# Replay accepts every step; the controller only scales the recorded error
# norm (solprop logs a replayed step above it, see Bridge.march).
controller=PIController(rtol=1e-6, atol=1e-14),
save_planes=planes,
dz_max=h_target,
dz_init=h_target,
schedule=schedule,
integrator=(
LowStorageRungeKutta(scheme="rk4ip")
if cfg.stepper == "rk4ip"
else RungeKutta()
),
backend=backend,
node_budget=int(node_budget),
absorber=absorber,
absorber_scheme="split_step",
spatial_absorber=spatial_absorber,
stats=StatsSpec(names=()) if stats_spec is None else stats_spec,
fields=fields,
boundary_check=BOUNDARY_CHECK if cfg.transverse_monitor else None,
)
# A placeholder input of the right shape: every delay point loads its own state
# with Backend.set_initial, so this one is never propagated. It is not zero
# because solprop derives bounds from the input's peak at translation. A
# broadcast row, which solprop keeps as the row alone rather than a field volume.
row = np.zeros((1, 1, tgrid.nt), dtype=complex)
row[0, 0, tgrid.sidx] = 1.0
placeholder = np.broadcast_to(row, (sgrid.n * sgrid.n, 1, tgrid.nt))
simulation = Simulation.from_free(
grid, space, medium, list(responses), placeholder, settings=settings,
frame=frame,
) # fmt: skip
problem = simulation.translate()
transverse = transverse_of(problem.route)
tables = configured_tables(
setup, grid, space, medium, frame, absorber, chi3, transverse
)
return _Translation(
setup=setup,
zsave=zsave,
h_target=float(h_target),
chi3=float(chi3),
grid=grid,
space=space,
medium=medium,
frame=frame,
responses=responses,
absorber=absorber,
schedule=schedule,
settings=settings,
simulation=simulation,
problem=problem,
tables=tables,
reduction=reduction,
stats_spec=stats_spec,
pin_frame=pin_frame,
)
[docs]
def build_bridge( # noqa: PLR0913 - the setup, schedule and engine overrides, all keyword after the schedule
setup: Setup,
zsave: Float[np.ndarray, "*shape"] | Sequence[float],
h_target: float,
*,
backend: str = "auto",
node_budget: int | None = None,
nonlinear: bool = True,
pin_frame: bool = True,
reduction: ReductionChoice | None = None,
) -> Bridge:
"""Set a configuration up on solprop, once, for any number of delay points.
Parameters
----------
setup : Setup
The configuration (:func:`pnps.setup.build_setup`).
zsave : array_like
Save positions in m, strictly increasing from ``>= 0``. Include 0.0 to
record the input. Every positive position is an edge of the schedule.
h_target : float
Largest step in m. Each interval between save positions is covered by the
fewest equal steps not longer than this. Choose it with
:mod:`pnps.calibrate`.
backend : str
Backend registry name in solprop: ``"auto"`` (which is ``"native"``),
``"native"`` or ``"numpy_ref"``.
node_budget : int or None
Per-chunk memory budget of solprop in bytes; None takes
``setup.cfg.node_budget``.
nonlinear : bool
Include the Kerr response. False builds the linear problem, for the exact
linear-parity validation.
pin_frame : bool
Pin solprop's co-moving frame to this package's ``beta1_ref omega +
beta0_ref`` (the default, and what every run uses). False leaves solprop to
derive the frame from the medium -- a validation control only: for a linear
run the observables must not depend on it.
reduction : {"auto", "host", "solprop"} or None
Where planes are reduced (:data:`ReductionChoice`); None takes
``setup.cfg.reduction``. ``"solprop"`` needs windows solprop can express
(:func:`pnps.statistics.statistics_refusal`); ``"auto"`` resolves to
``"solprop"`` when solprop accepts them without a warning and to ``"host"``
otherwise, and the bridge records the resolved choice.
Returns
-------
Bridge
Close it (or use it as a context manager) to release the backend.
Raises
------
ConfigError
For invalid save positions, a non-positive step, an unknown reduction, or
windows solprop cannot express with ``reduction="solprop"``.
GridRuleError
If solprop's grids do not reproduce this package's (:func:`check_grid_rule`).
"""
t = _translate(
setup,
zsave,
h_target,
backend=backend,
node_budget=node_budget,
nonlinear=nonlinear,
pin_frame=pin_frame,
reduction=reduction,
)
cfg, tgrid, sgrid = setup.cfg, setup.tgrid, setup.sgrid
grid, space, problem = t.grid, t.space, t.problem
runner = t.simulation.runner()
engine = runner.backend
size_thread_pool() # the reducer is a numba kernel
reducer = Reducer(
t.tables,
sgrid.kx,
setup.windows,
energy_prefactor(tgrid, sgrid),
cfg.edge_diagnostic,
setup.signal_region,
)
metadata: dict[str, object] = {
"backend": f"solprop:{engine.name}@{solprop_version}",
"stepper": (
"solprop-rk4ip-lowstorage"
if cfg.stepper == "rk4ip"
else "solprop-erk-dopri5-fixed"
),
"pnps_engine": "solprop",
"solprop_tableau": TABLEAUS[cfg.stepper],
"frame_pinned": int(t.pin_frame),
"gamma_k_applied": int(transverse_of(problem.route) is not None),
"evanescent_clamp": float(EVANESCENT_RATE),
"index_model": "optmat",
"measure": "flux",
"reduction": t.reduction,
}
# The exact windows on the host hold masks and the input; through solprop they
# are the backend's apertures (statistics_spec).
host_exact = cfg.exact_windows and t.reduction == "host"
return Bridge(
setup=setup,
zsave=t.zsave,
h_target=float(h_target),
chi3=float(t.chi3),
kerr_rate=peak_kerr_rate(setup) if nonlinear else 0.0,
grid=grid,
space=space,
medium=t.medium,
frame=t.frame,
responses=t.responses,
absorber=t.absorber,
schedule=t.schedule,
settings=t.settings,
simulation=t.simulation,
problem=problem,
runner=runner,
reducer=reducer,
reduction=t.reduction,
stats_spec=t.stats_spec,
scale=(
StatisticsScale.for_grids(
float(grid.dt), int(grid.n_t), float(space.spectral_weights[0])
)
if t.stats_spec is not None
else None
),
metadata=metadata,
identity=hashlib.sha256(repr(cfg).encode()).hexdigest()[:16],
exact=(
ExactWindows(sgrid, tgrid.omega, t.tables.k2, setup.windows)
if host_exact
else None
),
tables=t.tables if host_exact else None,
)
def _exact_windows(
obs: Observation,
exact: ExactWindows,
nonlinear: Complex[np.ndarray, "n_y n_x n_omega"],
) -> Observation:
"""Replace a plane's windowed spectra on the band by the exact hard discs'.
Parameters
----------
obs : Observation
The plane's observables through the rendered windows.
exact : ExactWindows
The windows' exact masks.
nonlinear : numpy.ndarray
The plane's nonlinear part, ``(n, n, nt)``.
Returns
-------
Observation
``obs`` with ``i_omega_win`` and ``i_omega_reimaged`` exact on the band
(off it nothing propagates and both are zero).
"""
energy, axis = exact.reduce(nonlinear)
win, reimaged = obs.i_omega_win.copy(), obs.i_omega_reimaged.copy()
win[:, exact.bins], reimaged[:, exact.bins] = (
energy[:, exact.bins],
axis[:, exact.bins],
)
return obs._replace(i_omega_win=win, i_omega_reimaged=reimaged)
[docs]
def bridge_tables(bridge: Bridge) -> OperatorTables:
"""Build the operator from the solprop objects a bridge configured.
The configured operator: solprop's material wavenumber squares, its frame
subtraction, its permeability ``1/(eps_0 c^2)``, the bridge's chi3, the absorber's
spectral rate, the hard band limit and the evanescent clamp.
Parameters
----------
bridge : Bridge
The bridge whose operator to tabulate.
Returns
-------
OperatorTables
The configured operator tables.
"""
return configured_tables(
bridge.setup,
bridge.grid,
bridge.space,
bridge.medium,
bridge.frame,
bridge.absorber,
bridge.chi3,
transverse_of(bridge.problem.route),
)