Source code for pnps.separation

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

"""Separate the transient-grating field from the arms' own Kerr light.

The nonlinear part ``N`` of the field (:func:`pnps.simulate.visit_nonlinear`) holds
everything the Kerr response generated: the three-arm transient grating, which is the
signal, and the third-order light of fewer arms, which a large collection window also
gathers: each arm's self-phase modulation and the cross-phase modulation and
four-wave mixing of each pair. The polarisation is cubic in the field, so its
three-arm part is the term that holds one factor from every arm, and inclusion and
exclusion over the input arms isolates it: with ``N(S)`` the nonlinear part of a run
whose input holds only the arms ``S``,

``N_TG = N(123) - N(12) - N(13) - N(23) + N(1) + N(2) + N(3)``.

To first order in the response, where every term of ``N`` holds three factors of the
input, this is exactly the part with a factor from each arm. Beyond first order it is
the part of ``N`` that vanishes whenever any arm is absent, which is the defining
property of the three-arm signal and includes its cascaded corrections.

The windows are quadratic in the field, so the combination is made on ``N`` itself, at
every save plane, before any window acts: the separated field is then collected
through the exact hard discs (:class:`pnps.exact_windows.ExactWindows`), as
``Config.exact_windows`` collects the whole ``N``.

Each subset is one propagation. The subsets of the gate pair alone carry no delay, so
their part ``N(12) - N(1) - N(2)`` is computed once and kept for every delay
(:meth:`Separation.gate_terms`); each delay then needs the four runs with the test
arm. The runs follow each other on the one backend; the host keeps one field volume
per save plane for the combination and one for the gate part. The linear parts of
the seven runs cancel in ``N_TG`` identically (each arm enters with weights summing
to zero), so ``N_TG`` is the same combination of the propagated fields, and the
linear propagation is subtracted only for the records of the whole ``N(123)`` and of
the remainder ``N(123) - N_TG``.
"""

import logging
from collections.abc import Sequence

import numpy as np
from jaxtyping import Complex, Float

from pnps.absorber import lap_lost
from pnps.bridge import Bridge
from pnps.exceptions import ConfigError, EngineError
from pnps.form_input import form_input
from pnps.pulse import energy_prefactor
from pnps.reference import apply_linear
from pnps.simulate import _check_delay  # pyright: ignore[reportPrivateUsage] - the one delay guard

__all__ = [
    "FIELD_PART",
    "GATE_SUBSETS",
    "PARTS",
    "SUBSETS",
    "TEST_SUBSETS",
    "Separation",
    "part_trace_names",
]

logger = logging.getLogger(__name__)

#: The ``/grid`` value of ``field_part`` in a file whose ``Iω_*`` traces hold the
#: transient-grating field alone.
FIELD_PART = "transient_grating"

#: The arm subsets and their signs in ``N_TG``, the whole input first.
SUBSETS: tuple[tuple[tuple[str, ...], int], ...] = (
    (("gate1", "gate2", "test"), +1),
    (("gate1", "gate2"), -1),
    (("gate1", "test"), -1),
    (("gate2", "test"), -1),
    (("gate1",), +1),
    (("gate2",), +1),
    (("test",), +1),
)

#: The delay-free subsets and their signs in the remainder ``N(123) - N_TG``.
GATE_SUBSETS: tuple[tuple[tuple[str, ...], int], ...] = (
    (("gate1", "gate2"), +1),
    (("gate1",), -1),
    (("gate2",), -1),
)

#: The delayed subsets other than the whole input, and their signs in the remainder.
TEST_SUBSETS: tuple[tuple[tuple[str, ...], int], ...] = (
    (("gate1", "test"), +1),
    (("gate2", "test"), +1),
    (("test",), -1),
)

#: The further parts a separation records beside the transient grating: the whole
#: nonlinear field ``N(123)`` and the remainder ``N(123) - N_TG``.
PARTS = ("nonlinear", "remainder")


[docs] def part_trace_names(n_windows: int, part: str) -> list[str]: """Return the dataset names of one part's window traces. The transient grating fills the usual :func:`pnps.io_h5.trace_names`; each further part (:data:`PARTS`) puts its name after the window's: ``Iω_win_2_remainder`` and ``Iω_win_2_remainder_reimaged``. Parameters ---------- n_windows : int Number of collection windows, >= 1. part : str One of :data:`PARTS`. Returns ------- list of str ``2 * n_windows`` names: for each window, the collected trace followed by its re-imaged partner. Raises ------ ConfigError If ``part`` is not one of :data:`PARTS`. Examples -------- >>> part_trace_names(2, "remainder") ['Iω_win_remainder', 'Iω_win_remainder_reimaged', 'Iω_win_2_remainder', \ 'Iω_win_2_remainder_reimaged'] """ if part not in PARTS: raise ConfigError(f"part must be one of {PARTS}, got {part!r}") names = [] for j in range(n_windows): suffix = "" if j == 0 else f"_{j + 1}" names.extend((f"Iω_win{suffix}_{part}", f"Iω_win{suffix}_{part}_reimaged")) return names
[docs] class Separation: """The transient-grating separation of one configuration, over its delays. Built on a bridge with the host reduction and the exact windows; holds, once computed, the linear propagator to each save plane and the delay-free gate part, and per delay the combination being formed. At the production shape each of these is one field volume per plane (5.7 GB at 768 x 768 x 600), so three planes take about 50 GB of host memory beside the exact windows' masks; the backend holds one run's state at a time, as in a scan. Parameters ---------- bridge : Bridge The configuration on solprop, built with ``reduction="host"`` from a configuration with ``exact_windows`` and the three-arm (``"tg"``) layout. Raises ------ ConfigError If the layout is not ``"tg"`` or the configuration has no exact windows. EngineError If the bridge reduces with solprop's statistics, which keep no field. """ def __init__(self, bridge: Bridge) -> None: if bridge.reduction != "host": raise EngineError( "the separation combines fields on the host: build the bridge with " "reduction='host'" ) if bridge.setup.cfg.geometry != "tg": raise ConfigError( "the separation isolates the three-arm transient grating, which the " f"{bridge.setup.cfg.geometry!r} layout does not have" ) if bridge.exact is None or bridge.tables is None: raise ConfigError( "the separation collects the separated field through the exact hard " "discs: set Config.exact_windows" ) self.bridge = bridge self._exact = bridge.exact self._tables = bridge.tables self._gate: list[Complex[np.ndarray, "n_y n_x n_omega"]] | None = None self._propagators: list[Complex[np.ndarray, "n_y n_x n_omega"]] | None = None self._rest: list[Complex[np.ndarray, "n_y n_x n_omega"]] | None = None def _accumulate( self, targets: Sequence[Complex[np.ndarray, "n_y n_x n_omega"]], tau: float, arms: tuple[str, ...], sign: int, ) -> None: """Propagate the input of ``arms`` and add ``sign`` times each plane's field.""" setup = self.bridge.setup planes = iter(targets) def visit(_z: float, field: Complex[np.ndarray, "n_y n_x n_omega"]) -> None: """Add the plane's field to its target. Parameters ---------- _z : float The position, m. field : numpy.ndarray The field there, solprop's buffer. """ target = next(planes) if sign > 0: target += field else: target -= field # Formed without a name, so solprop frees it once loaded. self.bridge.visit( form_input(setup.former, tau, arms=arms), visit, tau=tau, arms=arms )
[docs] def gate_terms(self) -> list[Complex[np.ndarray, "n_y n_x n_omega"]]: """Return the delay-free part ``N(12) - N(1) - N(2)`` at every save plane. Computed on the first call (three propagations) and kept. Its linear parts cancel, so it is the same combination of the propagated fields. Returns ------- list of numpy.ndarray One ``(n, n, nt)`` complex128 field per save position, the separation's own: do not modify. """ if self._gate is None: setup = self.bridge.setup gate = [ np.zeros(setup.former.shape, dtype=np.complex128) for _ in self.bridge.zsave ] for arms, sign in GATE_SUBSETS: self._accumulate(gate, 0.0, arms, sign) self._gate = gate return self._gate
def _linear_propagators(self) -> list[Complex[np.ndarray, "n_y n_x n_omega"]]: """Return ``exp(L z)`` on the grid at every save plane, computed once.""" if self._propagators is None: ones = np.ones(self.bridge.setup.former.shape, dtype=np.complex128) self._propagators = [ apply_linear(ones, self._tables, float(z)) for z in self.bridge.zsave ] return self._propagators
[docs] def point(self, tau: float) -> dict[str, Float[np.ndarray, "*_"]]: """Separate one delay point and collect each part through the exact discs. Parameters ---------- tau : float The delay in s. Returns ------- dict of numpy.ndarray The records of :func:`pnps.simulate.run_delay_point` that a scan file holds, for the transient-grating field ``N_TG``: ``i_omega_win`` and ``i_omega_reimaged`` through the exact discs, ``(nz, n_windows, nt)``; ``i_omega_full`` and ``i_omega_beam``, ``(nz, nt)``, of the signal region and the whole beam; ``lap_lost``, ``(nt,)``, of ``N_TG``'s beam spectrum; and ``z``. Beside them, ``i_omega_win_<part>`` and ``i_omega_reimaged_<part>`` for each of :data:`PARTS`, and ``energy_win`` and ``energy_win_<part>``, ``(nz, n_windows)``, the energy each window collects, J. All spectra are in the units of :func:`pnps.simulate.run_delay_point`. Raises ------ DelayError If ``tau`` is not a scalar. ConfigError If light that wraps the time window could act at the delay (:func:`pnps.absorber.wrap_coupling`). """ bridge = self.bridge setup = bridge.setup _check_delay(setup, tau) tau = float(tau) zsave = bridge.zsave n_z, n_win, nt = len(zsave), len(setup.windows), setup.tgrid.nt gate = self.gate_terms() propagators = self._linear_propagators() if self._rest is None: self._rest = [np.empty_like(g) for g in gate] rest = self._rest for target, part in zip(rest, gate, strict=True): np.copyto(target, part) # rest = N(12) - N(1) - N(2) + N(13) + N(23) - N(3) + the linear part of # N(123)'s input: the remainder before the subtraction. for arms, sign in TEST_SUBSETS: self._accumulate(rest, tau, arms, sign) out: dict[str, Float[np.ndarray, "*_"]] = { "i_omega_win": np.zeros((n_z, n_win, nt)), "i_omega_reimaged": np.zeros((n_z, n_win, nt)), "i_omega_full": np.zeros((n_z, nt)), "i_omega_beam": np.zeros((n_z, nt)), } for part in PARTS: out[f"i_omega_win_{part}"] = np.zeros((n_z, n_win, nt)) out[f"i_omega_reimaged_{part}"] = np.zeros((n_z, n_win, nt)) e0 = form_input(setup.former, tau) planes = iter(range(n_z)) def visit(_z: float, field: Complex[np.ndarray, "n_y n_x n_omega"]) -> None: """Form the three parts at this plane and collect each. Parameters ---------- _z : float The position, m. field : numpy.ndarray The whole input's field there, solprop's buffer. """ iz = next(planes) # The linear parts cancel in N_TG, so it is the propagated fields' sum. separated = field - rest[iz] obs = bridge.reducer.reduce(separated) out["i_omega_full"][iz] = obs.i_omega_full out["i_omega_beam"][iz] = obs.i_omega_beam out["i_omega_win"][iz], out["i_omega_reimaged"][iz] = self._exact.reduce( separated ) remainder = rest[iz] remainder -= propagators[iz] * e0 win, axis = self._exact.reduce(remainder) out["i_omega_win_remainder"][iz] = win out["i_omega_reimaged_remainder"][iz] = axis separated += remainder # now N(123) win, axis = self._exact.reduce(separated) out["i_omega_win_nonlinear"][iz] = win out["i_omega_reimaged_nonlinear"][iz] = axis bridge.visit(e0.copy(), visit, tau=tau) out["z"] = zsave.copy() out["lap_lost"] = lap_lost( out["i_omega_beam"], zsave, setup.gamma_omega, setup.gamma_lap ) prefactor = energy_prefactor(setup.tgrid, setup.sgrid) out["energy_win"] = prefactor * out["i_omega_win"].sum(axis=-1) for part in PARTS: out[f"energy_win_{part}"] = prefactor * out[f"i_omega_win_{part}"].sum( axis=-1 ) return out