diff --git a/benchmarks/builders.py b/benchmarks/builders.py index c4631b474..b7732ffb3 100644 --- a/benchmarks/builders.py +++ b/benchmarks/builders.py @@ -28,6 +28,7 @@ "soliton", "spatial", "spatial_grids", + "window", ] if TYPE_CHECKING: @@ -550,6 +551,66 @@ def _fibre_or_capillary( raise SuiteError(f"unknown builder {builder}") +def window(simulation: Simulation, stop: float, **settings: Any) -> Simulation: + """Return a case run to `stop`, m, with `settings` replaced. + + A run ends at its grid's length (SEP 51), so a shortened run (``ab --length``) is + the case rebuilt on its grid cut at `stop`, with everything the whole length set + carried over unchanged: the absorber's rates, the default steps and the profiles + already in the case's settings and simulation. At the case's own length the + settings are replaced on the case itself. + + Parameters + ---------- + simulation : solprop.driver.Simulation + The whole case, untranslated. + stop : float + Where the run ends, m, at most the case's length. + **settings : Any + Fields of :class:`~solprop.driver.SimulationSettings` to replace. + + Returns + ------- + solprop.driver.Simulation + The case, untranslated. + + Raises + ------ + SuiteError + When a shortened case was already translated, as a coupled launch is. + """ + from solprop.driver import Simulation # noqa: PLC0415 + + if stop >= simulation.grid.length: + simulation.settings = dataclasses.replace(simulation.settings, **settings) + return simulation + if simulation._problem is not None: + msg = "this case is translated at construction and runs only its whole length" + raise SuiteError(msg) + whole = simulation._base_grid + return Simulation( + dataclasses.replace(whole, length=stop), + simulation.modes, + simulation.responses, + simulation.initial, + settings=dataclasses.replace( + simulation.settings, **({"save_planes": []} | settings) + ), + noise=simulation.noise, + noise_resolution=simulation.noise_resolution, + profiles=simulation.profiles, + configuration=simulation.configuration, + spatial_grid=simulation.spatial_grid, + medium=simulation.medium, + frame=simulation.frame, + general=simulation.general, + guide=simulation.guide, + wall=simulation.wall, + taper_coupling=simulation.taper_coupling, + materials=simulation.materials, + ) + + def build(configuration: Record) -> Simulation: """Build a case for the configured backend, stepper and observations. @@ -580,7 +641,6 @@ def build(configuration: Record) -> Simulation: options = variant(configuration) if case.builder in ("kerr", "spatial"): settings = SimulationSettings( - save_planes=itinerary, dz_max=case.length, dz_init=case.length * 1e-4, auto_init=True, @@ -590,18 +650,29 @@ def build(configuration: Record) -> Simulation: field_planes=observed["field_planes"], node_budget=_node_budget(), ) + replay: dict[str, Any] = {} if case.step is not None: settings = dataclasses.replace( settings, integrator=LowStorageRungeKutta(scheme="rk4ip"), schedule=FixedSchedule( - np.diff(np.linspace(0.0, stop, max(1, round(stop / case.step)) + 1)) + np.diff( + np.linspace( + 0.0, case.length, max(1, round(case.length / case.step)) + 1 + ) + ) ), propagator_mode="tabulate", ) - if case.builder == "kerr": - return kerr(case.name, settings, options["fft_size"]) - return spatial(case.name, settings, options) + replay["schedule"] = FixedSchedule( + np.diff(np.linspace(0.0, stop, max(1, round(stop / case.step)) + 1)) + ) + whole = ( + kerr(case.name, settings, options["fft_size"]) + if case.builder == "kerr" + else spatial(case.name, settings, options) + ) + return window(whole, stop, save_planes=itinerary, **replay) if case.builder == "exercise": from benchmarks.exercises import exercise # noqa: PLC0415 @@ -615,7 +686,10 @@ def build(configuration: Record) -> Simulation: simulation = advanced(case.name, case.length, options) if case.name == "grin_nonlinear": # Translated at construction (its launch is coupled): only the backend - # and the field retention may still change. + # and the field retention may still change, so it runs whole. + if stop < case.length: + msg = "grin_nonlinear couples its launch at construction; run it whole" + raise SuiteError(msg) simulation.settings = dataclasses.replace( simulation.settings, backend=configuration["backend"], @@ -628,5 +702,4 @@ def build(configuration: Record) -> Simulation: if chosen is not None: observed["integrator"] = chosen observed["node_budget"] = _node_budget() # None: the translation's default - simulation.settings = dataclasses.replace(simulation.settings, **observed) - return simulation + return window(simulation, stop, **observed) diff --git a/benchmarks/guides.py b/benchmarks/guides.py index 6acd57bad..9756070cb 100644 --- a/benchmarks/guides.py +++ b/benchmarks/guides.py @@ -11,6 +11,7 @@ from __future__ import annotations +import dataclasses from collections.abc import Mapping from dataclasses import dataclass from types import MappingProxyType @@ -26,6 +27,7 @@ from solprop.constants import C from solprop.coupling import CouplingModel from solprop.driver import Simulation +from solprop.driver.settings import default_collar from solprop.grid import FieldGrid from solprop.modes import ( CoherentWall, @@ -308,11 +310,15 @@ def grin( q = float(grid.omega[centre]) / C * radius * 1.45 beta = np.sqrt(q * q - 2 * q * np.sqrt(2 * contrast) * np.array([1, 3])) / radius length = float(2 * np.pi / (beta[0] - beta[1])) + # A run ends at its grid's length (SEP 51): the millimetre grid the guide was + # sampled for is cut at the beat length, and keeps the collar the millimetre gave. + whole, grid = grid, dataclasses.replace(grid, length=length) simulation = Simulation.from_waveguide( (), length, provider=guide, grid=grid, + absorber=default_collar(whole), wavelength=wavelength, fwhm=40e-15, energy=1e-15, diff --git a/benchmarks/sessions.py b/benchmarks/sessions.py index 0e4692474..f6025f7d6 100644 --- a/benchmarks/sessions.py +++ b/benchmarks/sessions.py @@ -34,7 +34,7 @@ import numpy as np -from benchmarks.builders import SOLITON_PEAK, SOLITON_WIDTH, soliton +from benchmarks.builders import SOLITON_PEAK, SOLITON_WIDTH, soliton, window from benchmarks.records import Record, SuiteError from benchmarks.registry import CASES from solprop.driver import Simulation @@ -100,13 +100,16 @@ def fibre( extra["integrator"] = Multistep() if name.endswith("adams") else RungeKutta() if case.snapshots is not None: extra["step_planes"] = 1 + replay: dict[str, Any] = {} if case.step is not None: - extra["schedule"] = FixedSchedule.uniform( + replay["schedule"] = FixedSchedule.uniform( 0.0, stop, case.step, save_planes=itinerary ) # The in-stage collar is stable only up to 0.42 mm steps on this window. extra["absorber_scheme"] = "split_step" - return soliton(case.length, options, save_planes=itinerary, **extra) + # The case over its length, then run to `stop` on its grid cut there (SEP 51). + whole = soliton(case.length, options, **extra) + return window(whole, stop, save_planes=itinerary, **replay) class _Steps(NullReporter): @@ -238,7 +241,7 @@ def repetition( record = { "accepted": sum(run.accepted for run in watch.runs), "rejected": sum(run.rejected for run in watch.runs), - "z": float(simulation.settings.save_planes[-1]), + "z": float(np.asarray(simulation.settings.save_planes)[-1]), "runs": len(SCALES), "finite": None if None in finite else all(finite), } diff --git a/changelog.d/533-save-planes-count.fixed.md b/changelog.d/533-save-planes-count.fixed.md new file mode 100644 index 000000000..e76dfa02b --- /dev/null +++ b/changelog.d/533-save-planes-count.fixed.md @@ -0,0 +1,3 @@ +A recipe's `save_planes = 80` in an object route's `[build.settings]` is no longer read +as one plane at 80 m, with the run marching until something unrelated stopped it: it is +refused with "write `n_save = 80`", and every run now ends at its grid's length (#533). diff --git a/changelog.d/856-scaffold-n-save.changed.md b/changelog.d/856-scaffold-n-save.changed.md new file mode 100644 index 000000000..0a4897740 --- /dev/null +++ b/changelog.d/856-scaffold-n-save.changed.md @@ -0,0 +1,4 @@ +`solprop.driver.scaffold.propagate_fixed_rk4`'s `n_save` now means what it means on every +`Simulation` route: the number of evenly spaced saved planes over `[0, z_end]`, both ends +included, at least 2 (default 2). `n_steps` must be a multiple of `n_save - 1`. A call +that passed `n_save=4` now passes `n_save=5` for the same planes (#856). diff --git a/changelog.d/sep-0051-save-planes.changed.md b/changelog.d/sep-0051-save-planes.changed.md new file mode 100644 index 000000000..497af28b8 --- /dev/null +++ b/changelog.d/sep-0051-save-planes.changed.md @@ -0,0 +1,26 @@ +Every route now follows one rule for the saved planes and the end of a run +([SEP 51](docs/dev/seps/archive/sep-0051-save-planes.md)). A run marches from `initial_z` to its +length, `length` or `grid.length`, and always records both ends. `n_save=N` gives `N` +evenly spaced observations over that interval, both ends included, and +`save_planes=[...]` lists positions inside it. `SimulationSettings` gains `n_save`, its +`save_planes` becomes optional (given neither, a run records 201), and a recipe's +object-route `[build.settings]` takes `n_save` too. Migration: +`save_planes=80` is refused with "pass `n_save=80`" in Python and "write `n_save = 80`" +in a recipe; `save_planes=0.25` must be `[0.25]`; `n_save` and `save_planes` together, +`n_save` below 2, and positions before the entrance or beyond the end are refused; a +position within eight ulps of an endpoint is that endpoint. Positions short of the length +no longer end the run: it continues to the length and records it, so indices counted +from the end (`field_planes=[-1, …]`) may name other planes, and a short window of a +longer setup is now a shorter grid, with `boundary_length` pinned to keep the absorber. +`length` is optional on the keyword routes; given beside `grid=`, the two must agree, and +a call with neither is refused (`prop_capillary` and `from_capillary` therefore refuse a +missing `gas` themselves). `n_save` beside an interior launch counts over +`[initial_z, length]`. A replayed `FixedSchedule` must start at the entrance and end at +the length, within the rounding its step sum accumulates, or it is refused before the +run. The resolved recipe writes the run's positions in `[build.settings]` on an object +route and drops `n_save`. +In the front end, every sheet's *Saved planes* row offers *Evenly spaced* (`n_save`) and +*Explicit positions* (`save_planes`), and typing into one form removes the other in the +same undoable edit. A setup opens on the form it holds; the object sheets no longer turn +a count into a list of positions, nor rewrite the positions when the length changes. An +object-sheet count of 80 planes, which left out the entrance, is `n_save = 81`. diff --git a/docs/auto_tutorials/free_space/images/sphx_glr_plot_08_radial_capillary_coupling_001.png b/docs/auto_tutorials/free_space/images/sphx_glr_plot_08_radial_capillary_coupling_001.png index 58b56c36c..5dc9bf263 100644 Binary files a/docs/auto_tutorials/free_space/images/sphx_glr_plot_08_radial_capillary_coupling_001.png and b/docs/auto_tutorials/free_space/images/sphx_glr_plot_08_radial_capillary_coupling_001.png differ diff --git a/docs/auto_tutorials/free_space/images/sphx_glr_plot_08_radial_capillary_coupling_002.png b/docs/auto_tutorials/free_space/images/sphx_glr_plot_08_radial_capillary_coupling_002.png index 633ea6e7c..3fc99b87e 100644 Binary files a/docs/auto_tutorials/free_space/images/sphx_glr_plot_08_radial_capillary_coupling_002.png and b/docs/auto_tutorials/free_space/images/sphx_glr_plot_08_radial_capillary_coupling_002.png differ diff --git a/docs/auto_tutorials/free_space/images/sphx_glr_plot_08_radial_capillary_coupling_003.png b/docs/auto_tutorials/free_space/images/sphx_glr_plot_08_radial_capillary_coupling_003.png index e4e013726..ef0d87764 100644 Binary files a/docs/auto_tutorials/free_space/images/sphx_glr_plot_08_radial_capillary_coupling_003.png and b/docs/auto_tutorials/free_space/images/sphx_glr_plot_08_radial_capillary_coupling_003.png differ diff --git a/docs/auto_tutorials/free_space/images/sphx_glr_plot_08_radial_capillary_coupling_004.png b/docs/auto_tutorials/free_space/images/sphx_glr_plot_08_radial_capillary_coupling_004.png index ce7a5bfa3..48ccd1fe8 100644 Binary files a/docs/auto_tutorials/free_space/images/sphx_glr_plot_08_radial_capillary_coupling_004.png and b/docs/auto_tutorials/free_space/images/sphx_glr_plot_08_radial_capillary_coupling_004.png differ diff --git a/docs/auto_tutorials/free_space/images/sphx_glr_plot_08_radial_capillary_coupling_005.png b/docs/auto_tutorials/free_space/images/sphx_glr_plot_08_radial_capillary_coupling_005.png index 452dca4f3..ac3e579be 100644 Binary files a/docs/auto_tutorials/free_space/images/sphx_glr_plot_08_radial_capillary_coupling_005.png and b/docs/auto_tutorials/free_space/images/sphx_glr_plot_08_radial_capillary_coupling_005.png differ diff --git a/docs/auto_tutorials/free_space/images/thumb/sphx_glr_plot_08_radial_capillary_coupling_thumb.png b/docs/auto_tutorials/free_space/images/thumb/sphx_glr_plot_08_radial_capillary_coupling_thumb.png index 0db4e9791..bc5222495 100644 Binary files a/docs/auto_tutorials/free_space/images/thumb/sphx_glr_plot_08_radial_capillary_coupling_thumb.png and b/docs/auto_tutorials/free_space/images/thumb/sphx_glr_plot_08_radial_capillary_coupling_thumb.png differ diff --git a/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.codeobj.json b/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.codeobj.json index cfc9371b8..c43cdb427 100644 --- a/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.codeobj.json +++ b/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.codeobj.json @@ -54,6 +54,22 @@ "name": "CouplingModel" } ], + "DEFAULT_BOUNDARY_N": [ + { + "is_class": false, + "is_explicit": false, + "module": "builtins", + "module_short": "builtins", + "name": "int" + }, + { + "is_class": false, + "is_explicit": false, + "module": "solprop.boundaries", + "module_short": "solprop.boundaries", + "name": "DEFAULT_BOUNDARY_N" + } + ], "EPS0": [ { "is_class": false, @@ -665,6 +681,22 @@ "name": "Simulation" } ], + "absorber": [ + { + "is_class": false, + "is_explicit": false, + "module": "builtins", + "module_short": "builtins", + "name": "function" + }, + { + "is_class": false, + "is_explicit": false, + "module": "solprop.boundaries", + "module_short": "solprop.boundaries", + "name": "absorber" + } + ], "admittance": [ { "is_class": false, @@ -841,6 +873,22 @@ "name": "Displayed.with_input" } ], + "capillary_grid": [ + { + "is_class": false, + "is_explicit": false, + "module": "solprop.grid", + "module_short": "solprop.grid", + "name": "EnvelopeGrid" + }, + { + "is_class": false, + "is_explicit": false, + "module": "solprop", + "module_short": "solprop", + "name": "EnvelopeGrid" + } + ], "carrier": [ { "is_class": false, diff --git a/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.ipynb b/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.ipynb index af0ab0dff..d65fd8213 100644 --- a/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.ipynb +++ b/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.ipynb @@ -15,7 +15,7 @@ }, "outputs": [], "source": [ - "import math\nimport time\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.special import j0, jn_zeros\n\nfrom solprop import fourier\nfrom solprop.constants import EPS0, C\nfrom solprop.coupling import CouplingModel, couple\nfrom solprop.driver import Simulation, SimulationSettings\nfrom solprop.grid import EnvelopeGrid, RadialGrid\nfrom solprop.modes.capillary import MarcatiliMode\nfrom solprop.nonlinear.optmat_rates import OptmatRate\nfrom solprop.nonlinear.responses import KerrResponse\nfrom solprop.physdata import chi3, gamma3, refractive_index\nfrom solprop.physdata.species import species\nfrom solprop.processing import field_plane, get_spectral_density\nfrom solprop.pulses import GaussianPulse, SpatialPulse\nfrom solprop.spatial import SpatialMedium, critical_power\nfrom solprop.stats import StatsSpec\nfrom solprop.stepper import PIController\n\nstarted = time.perf_counter()" + "import math\nimport time\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.special import j0, jn_zeros\n\nfrom solprop import fourier\nfrom solprop.boundaries import DEFAULT_BOUNDARY_N, absorber\nfrom solprop.constants import EPS0, C\nfrom solprop.coupling import CouplingModel, couple\nfrom solprop.driver import Simulation, SimulationSettings\nfrom solprop.grid import EnvelopeGrid, RadialGrid\nfrom solprop.modes.capillary import MarcatiliMode\nfrom solprop.nonlinear.optmat_rates import OptmatRate\nfrom solprop.nonlinear.responses import KerrResponse\nfrom solprop.physdata import chi3, gamma3, refractive_index\nfrom solprop.physdata.species import species\nfrom solprop.processing import field_plane, get_spectral_density\nfrom solprop.pulses import GaussianPulse, SpatialPulse\nfrom solprop.spatial import SpatialMedium, critical_power\nfrom solprop.stats import StatsSpec\nfrom solprop.stepper import PIController\n\nstarted = time.perf_counter()" ] }, { @@ -123,7 +123,7 @@ }, "outputs": [], "source": [ - "capillary = Simulation.from_capillary(\n RADIUS,\n LENGTH,\n \"Ar\",\n PRESSURE,\n wavelength=WAVELENGTH,\n grid=grid,\n envelope=True,\n fwhm=FWHM,\n energy=energy,\n modes=8,\n kerr=True,\n thg=False,\n plasma=False,\n raman=False,\n noise=None,\n n_save=21,\n)\nport = capillary.input_port()\nmodel = CouplingModel(\"scalar_paraxial\", model_error=0.05)\ncoupled = {name: couple(plane, port, model=model) for name, plane in planes.items()}\nshares = {\n name: np.sum(weights * np.abs(result.launch.samples[:, 0, :]) ** 2, axis=1)\n / result.report.incident_energy\n for name, result in coupled.items()\n}\nprint(coupled[\"Kerr\"].report)\nfor name, result in coupled.items():\n report = result.report\n print(\n f\"{name:>6}: s11 = {shares[name][0]:.5f}, s12 = {shares[name][1]:.5f}, \"\n f\"s13 = {shares[name][2]:.2e}; launched {report.efficiency:.5f} \"\n f\"of {report.incident_energy * 1e6:.3f} uJ; budget {report.budget:.3f}\"\n )\ndelta = shares[\"Kerr\"] - shares[\"linear\"]\nprint(f\"change: ds11 = {delta[0]:+.3e}, ds12 = {delta[1]:+.3e}, ds13 = {delta[2]:+.2e}\")" + "# The capillary's grid samples as the gap's does -- a launch is bound to its\n# lattice -- and is built for the capillary's own 5 mm, since a run ends at its\n# grid's length; its collar keeps the rate the gap's 20 mm grid gives.\ncapillary_grid = EnvelopeGrid.from_limits(\n LENGTH, WAVELENGTH, (500e-9, 1.4e-6), 300e-15, thg=False\n)\ncapillary = Simulation.from_capillary(\n RADIUS,\n LENGTH,\n \"Ar\",\n PRESSURE,\n wavelength=WAVELENGTH,\n grid=capillary_grid,\n absorber=absorber(capillary_grid, boundary_length=GAP / DEFAULT_BOUNDARY_N),\n envelope=True,\n fwhm=FWHM,\n energy=energy,\n modes=8,\n kerr=True,\n thg=False,\n plasma=False,\n raman=False,\n noise=None,\n n_save=21,\n)\nport = capillary.input_port()\nmodel = CouplingModel(\"scalar_paraxial\", model_error=0.05)\ncoupled = {name: couple(plane, port, model=model) for name, plane in planes.items()}\nshares = {\n name: np.sum(weights * np.abs(result.launch.samples[:, 0, :]) ** 2, axis=1)\n / result.report.incident_energy\n for name, result in coupled.items()\n}\nprint(coupled[\"Kerr\"].report)\nfor name, result in coupled.items():\n report = result.report\n print(\n f\"{name:>6}: s11 = {shares[name][0]:.5f}, s12 = {shares[name][1]:.5f}, \"\n f\"s13 = {shares[name][2]:.2e}; launched {report.efficiency:.5f} \"\n f\"of {report.incident_energy * 1e6:.3f} uJ; budget {report.budget:.3f}\"\n )\ndelta = shares[\"Kerr\"] - shares[\"linear\"]\nprint(f\"change: ds11 = {delta[0]:+.3e}, ds12 = {delta[1]:+.3e}, ds13 = {delta[2]:+.2e}\")" ] }, { @@ -247,7 +247,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.14.5" + "version": "3.14.7" } }, "nbformat": 4, diff --git a/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.py b/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.py index 57c14a8bf..019aee432 100644 --- a/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.py +++ b/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.py @@ -41,6 +41,7 @@ from scipy.special import j0, jn_zeros from solprop import fourier +from solprop.boundaries import DEFAULT_BOUNDARY_N, absorber from solprop.constants import EPS0, C from solprop.coupling import CouplingModel, couple from solprop.driver import Simulation, SimulationSettings @@ -276,13 +277,20 @@ # mode *m*, in its native true-power metric, over the incident energy of the # whole entrance plane in the coupling's common measure. +# The capillary's grid samples as the gap's does -- a launch is bound to its +# lattice -- and is built for the capillary's own 5 mm, since a run ends at its +# grid's length; its collar keeps the rate the gap's 20 mm grid gives. +capillary_grid = EnvelopeGrid.from_limits( + LENGTH, WAVELENGTH, (500e-9, 1.4e-6), 300e-15, thg=False +) capillary = Simulation.from_capillary( RADIUS, LENGTH, "Ar", PRESSURE, wavelength=WAVELENGTH, - grid=grid, + grid=capillary_grid, + absorber=absorber(capillary_grid, boundary_length=GAP / DEFAULT_BOUNDARY_N), envelope=True, fwhm=FWHM, energy=energy, diff --git a/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.py.md5 b/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.py.md5 index 147788a7c..0f168ce8c 100644 --- a/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.py.md5 +++ b/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.py.md5 @@ -1 +1 @@ -9e4fe96e839f0bc0b4f86df05a6d4597 \ No newline at end of file +af0e3d832e983700d7024ab3a450eb75 \ No newline at end of file diff --git a/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.rst b/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.rst index 43d41d357..903da4a33 100644 --- a/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.rst +++ b/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.rst @@ -47,7 +47,7 @@ capillary. The ionisation they would carry is estimated offline at the end. functions and a target on-axis nonlinear phase of the linear Gaussian beam, :math:`B_{\rm lin} = 0.3` rad, accumulated from the launch plane to the focus. -.. GENERATED FROM PYTHON SOURCE LINES 35-61 +.. GENERATED FROM PYTHON SOURCE LINES 35-62 .. code-block:: Python @@ -60,6 +60,7 @@ functions and a target on-axis nonlinear phase of the linear Gaussian beam, from scipy.special import j0, jn_zeros from solprop import fourier + from solprop.boundaries import DEFAULT_BOUNDARY_N, absorber from solprop.constants import EPS0, C from solprop.coupling import CouplingModel, couple from solprop.driver import Simulation, SimulationSettings @@ -84,7 +85,7 @@ functions and a target on-axis nonlinear phase of the linear Gaussian beam, -.. GENERATED FROM PYTHON SOURCE LINES 62-79 +.. GENERATED FROM PYTHON SOURCE LINES 63-80 The energy from the material functions -------------------------------------- @@ -104,7 +105,7 @@ Integrating :math:`k_0 n_2 I_0` from :math:`z = -L` to the focus gives energy is that of the beam through its launch plane, in the argon (:doc:`/guide/free-space/flux`). -.. GENERATED FROM PYTHON SOURCE LINES 79-109 +.. GENERATED FROM PYTHON SOURCE LINES 80-110 .. code-block:: Python @@ -154,7 +155,7 @@ energy is that of the beam through its launch plane, in the argon -.. GENERATED FROM PYTHON SOURCE LINES 110-117 +.. GENERATED FROM PYTHON SOURCE LINES 111-118 Two propagations through the gap -------------------------------- @@ -164,7 +165,7 @@ converged ones of the refinement study described at the end: 1 mm radial domain with 256 nodes, a 300 fs window over 500 nm to 1.4 um, and steps no longer than 0.25 mm. The only difference between the two runs is the response list. -.. GENERATED FROM PYTHON SOURCE LINES 117-138 +.. GENERATED FROM PYTHON SOURCE LINES 118-139 .. code-block:: Python @@ -196,13 +197,13 @@ with 256 nodes, a 300 fs window over 500 nm to 1.4 um, and steps no longer than -.. GENERATED FROM PYTHON SOURCE LINES 139-142 +.. GENERATED FROM PYTHON SOURCE LINES 140-143 The beam radius is the second moment of the time-integrated axial flux. The Kerr lens pulls the beam to a slightly smaller spot and moves its focus a little upstream. Its peak intensity rises by about 14 % but stays far from collapse. -.. GENERATED FROM PYTHON SOURCE LINES 142-163 +.. GENERATED FROM PYTHON SOURCE LINES 143-164 .. code-block:: Python @@ -245,7 +246,7 @@ upstream. Its peak intensity rises by about 14 % but stays far from collapse. -.. GENERATED FROM PYTHON SOURCE LINES 164-177 +.. GENERATED FROM PYTHON SOURCE LINES 165-178 The fields at the entrance -------------------------- @@ -261,7 +262,7 @@ L}(r,\omega_0)]`. Both planes carry the same reference, because both runs share one frame. It is masked where the linear field's amplitude at that bin falls below 1 % of its peak, where neither phase means much. -.. GENERATED FROM PYTHON SOURCE LINES 177-211 +.. GENERATED FROM PYTHON SOURCE LINES 178-212 .. code-block:: Python @@ -317,7 +318,7 @@ one frame. It is masked where the linear field's amplitude at that bin falls bel -.. GENERATED FROM PYTHON SOURCE LINES 212-224 +.. GENERATED FROM PYTHON SOURCE LINES 213-225 The fluence is the time integral of the axial flux, :math:`n_0\varepsilon_0c|E|^2/2` summed over the spectrum (:doc:`/guide/free-space/flux`). The Kerr beam arrives @@ -332,7 +333,7 @@ brighter, and the power through the whole plane is unchanged, since the gap is lossless. The plane's spectrum broadens a little by self-phase modulation, which shows only in its wings, three decades down. -.. GENERATED FROM PYTHON SOURCE LINES 224-264 +.. GENERATED FROM PYTHON SOURCE LINES 225-265 .. code-block:: Python @@ -388,7 +389,7 @@ shows only in its wings, three decades down. -.. GENERATED FROM PYTHON SOURCE LINES 265-278 +.. GENERATED FROM PYTHON SOURCE LINES 266-279 Coupling into the capillary --------------------------- @@ -404,18 +405,25 @@ The modal share is :math:`s_m = U_m/U_{\rm incident}`: the energy launched into mode *m*, in its native true-power metric, over the incident energy of the whole entrance plane in the coupling's common measure. -.. GENERATED FROM PYTHON SOURCE LINES 278-316 +.. GENERATED FROM PYTHON SOURCE LINES 279-324 .. code-block:: Python + # The capillary's grid samples as the gap's does -- a launch is bound to its + # lattice -- and is built for the capillary's own 5 mm, since a run ends at its + # grid's length; its collar keeps the rate the gap's 20 mm grid gives. + capillary_grid = EnvelopeGrid.from_limits( + LENGTH, WAVELENGTH, (500e-9, 1.4e-6), 300e-15, thg=False + ) capillary = Simulation.from_capillary( RADIUS, LENGTH, "Ar", PRESSURE, wavelength=WAVELENGTH, - grid=grid, + grid=capillary_grid, + absorber=absorber(capillary_grid, boundary_length=GAP / DEFAULT_BOUNDARY_N), envelope=True, fwhm=FWHM, energy=energy, @@ -484,14 +492,14 @@ whole entrance plane in the coupling's common measure. -.. GENERATED FROM PYTHON SOURCE LINES 317-321 +.. GENERATED FROM PYTHON SOURCE LINES 325-329 The Kerr-prepared beam puts 2.4 % of the incident energy less into :math:`HE_{11}` and almost all of it into :math:`HE_{12}`. The total captured share barely moves: the change is a redistribution between modes, not a loss. The narrower, more curved entrance field looks more like the second mode. -.. GENERATED FROM PYTHON SOURCE LINES 321-353 +.. GENERATED FROM PYTHON SOURCE LINES 329-361 .. code-block:: Python @@ -539,7 +547,7 @@ The narrower, more curved entrance field looks more like the second mode. -.. GENERATED FROM PYTHON SOURCE LINES 354-373 +.. GENERATED FROM PYTHON SOURCE LINES 362-381 The 5 mm capillary ------------------ @@ -561,7 +569,7 @@ of :math:`HE_{12}`. Because both cases go through the same capillary physics, th beating, the loss and the Kerr coupling are the same in both. The difference between the outputs comes from the prepared incident field. -.. GENERATED FROM PYTHON SOURCE LINES 373-422 +.. GENERATED FROM PYTHON SOURCE LINES 381-430 .. code-block:: Python @@ -637,7 +645,7 @@ between the outputs comes from the prepared incident field. -.. GENERATED FROM PYTHON SOURCE LINES 423-430 +.. GENERATED FROM PYTHON SOURCE LINES 431-438 In both cases :math:`HE_{12}` gives energy to :math:`HE_{11}` along the capillary, far more than its wall loss. Linear modes of a uniform capillary do not @@ -647,7 +655,7 @@ advances. The Kerr-prepared launch leaves the capillary with about 0.27 uJ less in :math:`HE_{11}` and 0.27 uJ more in :math:`HE_{12}`, close to the 0.29 uJ moved at the entrance. -.. GENERATED FROM PYTHON SOURCE LINES 432-440 +.. GENERATED FROM PYTHON SOURCE LINES 440-448 Checks ------ @@ -658,7 +666,7 @@ window, is printed below. So is the coupling's numerical item, which measures th entrance planes' content in the outer fifth of their transverse spectral window. Both are far below anything that could affect the shares. -.. GENERATED FROM PYTHON SOURCE LINES 440-457 +.. GENERATED FROM PYTHON SOURCE LINES 448-465 .. code-block:: Python @@ -687,13 +695,13 @@ Both are far below anything that could affect the shares. .. code-block:: none - linear: outer-domain fluence 2.7e-27, spectral-edge content 2.7e-36 + linear: outer-domain fluence 2.7e-27, spectral-edge content 2.4e-36 Kerr: outer-domain fluence 6.1e-27, spectral-edge content 8.9e-28 -.. GENERATED FROM PYTHON SOURCE LINES 458-474 +.. GENERATED FROM PYTHON SOURCE LINES 466-482 **Convergence.** A separate refinement study varied the radial domain (0.8 to 1.5 mm), the radial nodes (192 to 512), the window (200 to 500 fs), the @@ -712,7 +720,7 @@ share. The two differ by the ratio of the gas index to the mode index, about field of a 30 fs Gaussian at the highest on-axis intensity of the Kerr run. This is an offline estimate, not part of the propagation. -.. GENERATED FROM PYTHON SOURCE LINES 474-491 +.. GENERATED FROM PYTHON SOURCE LINES 482-499 .. code-block:: Python @@ -747,7 +755,7 @@ is an offline estimate, not part of the propagation. -.. GENERATED FROM PYTHON SOURCE LINES 492-501 +.. GENERATED FROM PYTHON SOURCE LINES 500-509 An ionised fraction of about 1e-7 lowers the index by about 2e-9. The Kerr index change it competes with is 6e-6. Leaving plasma out is defensible at this @@ -759,7 +767,7 @@ it through the window's Fresnel transmission yourself, or transport the plane through a :class:`~solprop.coupling.elements.PlanarInterface`, before giving it (:doc:`/guide/free-space/flux`, :doc:`/guide/workflows/coupling`). -.. GENERATED FROM PYTHON SOURCE LINES 501-504 +.. GENERATED FROM PYTHON SOURCE LINES 509-512 .. code-block:: Python @@ -774,12 +782,12 @@ through a :class:`~solprop.coupling.elements.PlanarInterface`, before giving it .. code-block:: none - run time 1.5 s + run time 9.6 s -.. GENERATED FROM PYTHON SOURCE LINES 505-512 +.. GENERATED FROM PYTHON SOURCE LINES 513-520 Related reading --------------- @@ -792,7 +800,7 @@ The design is .. rst-class:: sphx-glr-timing - **Total running time of the script:** (0 minutes 1.483 seconds) + **Total running time of the script:** (0 minutes 9.602 seconds) .. _sphx_glr_download_auto_tutorials_free_space_plot_08_radial_capillary_coupling.py: diff --git a/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.zip b/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.zip index c6ebd4210..09b3987eb 100644 Binary files a/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.zip and b/docs/auto_tutorials/free_space/plot_08_radial_capillary_coupling.zip differ diff --git a/docs/auto_tutorials/waveguides/images/sphx_glr_plot_05_general_modal_001.png b/docs/auto_tutorials/waveguides/images/sphx_glr_plot_05_general_modal_001.png index 44b56af4a..bf4abae05 100644 Binary files a/docs/auto_tutorials/waveguides/images/sphx_glr_plot_05_general_modal_001.png and b/docs/auto_tutorials/waveguides/images/sphx_glr_plot_05_general_modal_001.png differ diff --git a/docs/auto_tutorials/waveguides/images/thumb/sphx_glr_plot_05_general_modal_thumb.png b/docs/auto_tutorials/waveguides/images/thumb/sphx_glr_plot_05_general_modal_thumb.png index a83d6792c..856d8bb76 100644 Binary files a/docs/auto_tutorials/waveguides/images/thumb/sphx_glr_plot_05_general_modal_thumb.png and b/docs/auto_tutorials/waveguides/images/thumb/sphx_glr_plot_05_general_modal_thumb.png differ diff --git a/docs/auto_tutorials/waveguides/plot_05_general_modal.codeobj.json b/docs/auto_tutorials/waveguides/plot_05_general_modal.codeobj.json index 3255921ea..75dc0d0be 100644 --- a/docs/auto_tutorials/waveguides/plot_05_general_modal.codeobj.json +++ b/docs/auto_tutorials/waveguides/plot_05_general_modal.codeobj.json @@ -24,6 +24,22 @@ "name": "float" } ], + "DEFAULT_BOUNDARY_N": [ + { + "is_class": false, + "is_explicit": false, + "module": "builtins", + "module_short": "builtins", + "name": "int" + }, + { + "is_class": false, + "is_explicit": false, + "module": "solprop.boundaries", + "module_short": "solprop.boundaries", + "name": "DEFAULT_BOUNDARY_N" + } + ], "EnvelopeGrid.from_limits": [ { "is_class": true, @@ -412,6 +428,22 @@ "name": "ndarray" } ], + "absorber": [ + { + "is_class": false, + "is_explicit": false, + "module": "builtins", + "module_short": "builtins", + "name": "function" + }, + { + "is_class": false, + "is_explicit": false, + "module": "solprop.boundaries", + "module_short": "solprop.boundaries", + "name": "absorber" + } + ], "area": [ { "is_class": false, @@ -728,6 +760,15 @@ "name": "IndexMaterial" } ], + "envelope": [ + { + "is_class": false, + "is_explicit": false, + "module": "builtins", + "module_short": "builtins", + "name": "dict" + } + ], "envelope_grid": [ { "is_class": false, @@ -797,6 +838,15 @@ "name": "ndarray" } ], + "field": [ + { + "is_class": false, + "is_explicit": false, + "module": "builtins", + "module_short": "builtins", + "name": "dict" + } + ], "fig": [ { "is_class": false, @@ -854,6 +904,15 @@ "name": "float" } ], + "gentle": [ + { + "is_class": false, + "is_explicit": false, + "module": "builtins", + "module_short": "builtins", + "name": "float" + } + ], "grid": [ { "is_class": false, @@ -1457,6 +1516,38 @@ "name": "tuple" } ], + "run_envelope_grid": [ + { + "is_class": false, + "is_explicit": false, + "module": "solprop.grid", + "module_short": "solprop.grid", + "name": "EnvelopeGrid" + }, + { + "is_class": false, + "is_explicit": false, + "module": "solprop", + "module_short": "solprop", + "name": "EnvelopeGrid" + } + ], + "run_grid": [ + { + "is_class": false, + "is_explicit": false, + "module": "solprop.grid", + "module_short": "solprop.grid", + "name": "FieldGrid" + }, + { + "is_class": false, + "is_explicit": false, + "module": "solprop", + "module_short": "solprop", + "name": "FieldGrid" + } + ], "runs": [ { "is_class": false, diff --git a/docs/auto_tutorials/waveguides/plot_05_general_modal.ipynb b/docs/auto_tutorials/waveguides/plot_05_general_modal.ipynb index d6c2274ef..b623b4ffc 100644 --- a/docs/auto_tutorials/waveguides/plot_05_general_modal.ipynb +++ b/docs/auto_tutorials/waveguides/plot_05_general_modal.ipynb @@ -15,7 +15,7 @@ }, "outputs": [], "source": [ - "import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom solprop import fourier\nfrom solprop.constants import C\nfrom solprop.driver import prop_gnlse, prop_waveguide\nfrom solprop.grid import EnvelopeGrid, FieldGrid\nfrom solprop.modes import (\n IndexMaterial,\n MaterialKerr,\n MaterialRegion,\n ModalGuide,\n StepIndexMode,\n)\nfrom solprop.nonlinear.normalisation import modal_kerr_coefficient\nfrom solprop.physdata import chi3_from_n2, n2_from_chi3\nfrom solprop.translate.modal_tables import channel_area, sample_modal_table\n\nLENGTH = 2e-5\n\"\"\"Twenty microns, in about ten accepted steps.\n\nWhat sets the step here is neither the self-phase modulation nor the general\nroute: it is the explicit in-stage temporal collar (see \"Boundaries\" in the model\ndocumentation), whose\nrate is set by the length the *grid* was built for, and whose stable step is set\nby that rate. A general modal step is expensive, so this example builds its\ngrids for a millimetre -- a gentle collar -- and propagates twenty microns of it,\nto stay inside the documentation build's budget.\n\"\"\"\n\nWINDOW_LENGTH = 1e-3\n\"\"\"Length the grids and their collar are declared for, m.\"\"\"\n\nN2 = 2.6e-20\nCHI3 = chi3_from_n2(N2, 1.45)\n\"\"\"The core's absolute susceptibility, m^2/V^2.\n\nsolprop's own conversion, against the core's linear index: a hand-written\n``4 eps0 c n^2 n2 / 3`` beside it would be a second copy of the relation.\n\"\"\"" + "import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom solprop import fourier\nfrom solprop.boundaries import DEFAULT_BOUNDARY_N, absorber\nfrom solprop.constants import C\nfrom solprop.driver import prop_gnlse, prop_waveguide\nfrom solprop.grid import EnvelopeGrid, FieldGrid\nfrom solprop.modes import (\n IndexMaterial,\n MaterialKerr,\n MaterialRegion,\n ModalGuide,\n StepIndexMode,\n)\nfrom solprop.nonlinear.normalisation import modal_kerr_coefficient\nfrom solprop.physdata import chi3_from_n2, n2_from_chi3\nfrom solprop.translate.modal_tables import channel_area, sample_modal_table\n\nLENGTH = 2e-5\n\"\"\"Twenty microns, in about ten accepted steps.\n\nWhat sets the step here is neither the self-phase modulation nor the general\nroute: it is the explicit in-stage temporal collar (see \"Boundaries\" in the model\ndocumentation), whose\nrate is set by the length the *grid* was built for, and whose stable step is set\nby that rate. A general modal step is expensive, so this example propagates\ntwenty microns -- a run ends at its grid's length, so its grids are built for\ntwenty microns -- and keeps the collar a millimetre's grid would have, a gentle one,\nthrough ``boundary_length``, to stay inside the documentation build's budget.\n\"\"\"\n\nWINDOW_LENGTH = 1e-3\n\"\"\"Length the collar's rate is declared for, m.\"\"\"\n\nN2 = 2.6e-20\nCHI3 = chi3_from_n2(N2, 1.45)\n\"\"\"The core's absolute susceptibility, m^2/V^2.\n\nsolprop's own conversion, against the core's linear index: a hand-written\n``4 eps0 c n^2 n2 / 3`` beside it would be a second copy of the relation.\n\"\"\"" ] }, { @@ -69,7 +69,7 @@ }, "outputs": [], "source": [ - "linear_guide = ModalGuide.from_provider(\n ModalGuide.from_step_index(\n [mode],\n core=core_law,\n cladding=cladding_law,\n regions=(\n MaterialRegion(\"core\", 0.0, mode.core_radius, core_law),\n MaterialRegion(\"cladding\", mode.core_radius, None, cladding_law),\n ),\n ).field_provider,\n guide.sampling.omega,\n nodes=nodes,\n)\ncommon = {\n \"noise\": None, # a 40 pJ comparison of two routes: the lesson is noiseless\n \"wavelength\": 835e-9,\n \"fwhm\": 40e-15,\n \"energy\": 4e-11,\n \"shape\": \"gauss\",\n \"n_save\": 2,\n \"backend\": \"numpy_ref\",\n \"progress\": \"none\",\n \"dz_max\": LENGTH / 10,\n \"dz_init\": LENGTH / 10,\n}\nchannel = guide.mode_collection.modes[0]\nruns = {\n \"general\": prop_waveguide(\n (), LENGTH, provider=guide, grid=grid, kerr_form=\"analytic\", **common\n ),\n \"general, linear\": prop_waveguide(\n (), LENGTH, provider=linear_guide, grid=grid, kerr_form=\"analytic\", **common\n ),\n \"gnlse\": prop_gnlse(\n gamma, LENGTH, grid=envelope_grid, fibre=channel, shock=True, **common\n ),\n \"gnlse, linear\": prop_gnlse(\n 0.0, LENGTH, grid=envelope_grid, fibre=channel, shock=True, **common\n ),\n}\n\n\ndef nonlinear_phase(turned, straight, kind):\n \"\"\"Return the phase the nonlinearity added, against time in the run's frame.\"\"\"\n a = fourier.inverse(turned.planes()[-1].field[0, 0], kind=kind)\n b = fourier.inverse(straight.planes()[-1].field[0, 0], kind=kind)\n if kind == \"field\":\n a, b = fourier.analytic_signal(a), fourier.analytic_signal(b)\n keep = np.abs(b) ** 2 > 1e-3 * np.max(np.abs(b) ** 2)\n return keep, np.angle(a[keep] / b[keep]), np.abs(b[keep]) ** 2" + "linear_guide = ModalGuide.from_provider(\n ModalGuide.from_step_index(\n [mode],\n core=core_law,\n cladding=cladding_law,\n regions=(\n MaterialRegion(\"core\", 0.0, mode.core_radius, core_law),\n MaterialRegion(\"cladding\", mode.core_radius, None, cladding_law),\n ),\n ).field_provider,\n guide.sampling.omega,\n nodes=nodes,\n)\ncommon = {\n \"noise\": None, # a 40 pJ comparison of two routes: the lesson is noiseless\n \"wavelength\": 835e-9,\n \"fwhm\": 40e-15,\n \"energy\": 4e-11,\n \"shape\": \"gauss\",\n \"n_save\": 2,\n \"backend\": \"numpy_ref\",\n \"progress\": \"none\",\n \"dz_max\": LENGTH / 10,\n \"dz_init\": LENGTH / 10,\n}\nchannel = guide.mode_collection.modes[0]\n# The runs' grids sample as the guide's did, over the twenty microns they propagate,\n# with the collar of a millimetre.\nrun_grid = FieldGrid.from_limits(LENGTH, 835e-9, (790e-9, 890e-9), 200e-15)\nrun_envelope_grid = EnvelopeGrid.from_limits(LENGTH, 835e-9, (790e-9, 890e-9), 200e-15)\ngentle = WINDOW_LENGTH / DEFAULT_BOUNDARY_N\nfield = {\"grid\": run_grid, \"absorber\": absorber(run_grid, boundary_length=gentle)}\nenvelope = {\n \"grid\": run_envelope_grid,\n \"absorber\": absorber(run_envelope_grid, boundary_length=gentle),\n}\nruns = {\n \"general\": prop_waveguide(\n (), LENGTH, provider=guide, kerr_form=\"analytic\", **field, **common\n ),\n \"general, linear\": prop_waveguide(\n (), LENGTH, provider=linear_guide, kerr_form=\"analytic\", **field, **common\n ),\n \"gnlse\": prop_gnlse(gamma, LENGTH, fibre=channel, shock=True, **envelope, **common),\n \"gnlse, linear\": prop_gnlse(\n 0.0, LENGTH, fibre=channel, shock=True, **envelope, **common\n ),\n}\n\n\ndef nonlinear_phase(turned, straight, kind):\n \"\"\"Return the phase the nonlinearity added, against time in the run's frame.\"\"\"\n a = fourier.inverse(turned.planes()[-1].field[0, 0], kind=kind)\n b = fourier.inverse(straight.planes()[-1].field[0, 0], kind=kind)\n if kind == \"field\":\n a, b = fourier.analytic_signal(a), fourier.analytic_signal(b)\n keep = np.abs(b) ** 2 > 1e-3 * np.max(np.abs(b) ** 2)\n return keep, np.angle(a[keep] / b[keep]), np.abs(b[keep]) ** 2" ] }, { @@ -114,7 +114,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.14.5" + "version": "3.14.7" } }, "nbformat": 4, diff --git a/docs/auto_tutorials/waveguides/plot_05_general_modal.py b/docs/auto_tutorials/waveguides/plot_05_general_modal.py index 3c7de1643..c47c832df 100644 --- a/docs/auto_tutorials/waveguides/plot_05_general_modal.py +++ b/docs/auto_tutorials/waveguides/plot_05_general_modal.py @@ -23,6 +23,7 @@ import numpy as np from solprop import fourier +from solprop.boundaries import DEFAULT_BOUNDARY_N, absorber from solprop.constants import C from solprop.driver import prop_gnlse, prop_waveguide from solprop.grid import EnvelopeGrid, FieldGrid @@ -44,13 +45,14 @@ route: it is the explicit in-stage temporal collar (see "Boundaries" in the model documentation), whose rate is set by the length the *grid* was built for, and whose stable step is set -by that rate. A general modal step is expensive, so this example builds its -grids for a millimetre -- a gentle collar -- and propagates twenty microns of it, -to stay inside the documentation build's budget. +by that rate. A general modal step is expensive, so this example propagates +twenty microns -- a run ends at its grid's length, so its grids are built for +twenty microns -- and keeps the collar a millimetre's grid would have, a gentle one, +through ``boundary_length``, to stay inside the documentation build's budget. """ WINDOW_LENGTH = 1e-3 -"""Length the grids and their collar are declared for, m.""" +"""Length the collar's rate is declared for, m.""" N2 = 2.6e-20 CHI3 = chi3_from_n2(N2, 1.45) @@ -154,18 +156,26 @@ "dz_init": LENGTH / 10, } channel = guide.mode_collection.modes[0] +# The runs' grids sample as the guide's did, over the twenty microns they propagate, +# with the collar of a millimetre. +run_grid = FieldGrid.from_limits(LENGTH, 835e-9, (790e-9, 890e-9), 200e-15) +run_envelope_grid = EnvelopeGrid.from_limits(LENGTH, 835e-9, (790e-9, 890e-9), 200e-15) +gentle = WINDOW_LENGTH / DEFAULT_BOUNDARY_N +field = {"grid": run_grid, "absorber": absorber(run_grid, boundary_length=gentle)} +envelope = { + "grid": run_envelope_grid, + "absorber": absorber(run_envelope_grid, boundary_length=gentle), +} runs = { "general": prop_waveguide( - (), LENGTH, provider=guide, grid=grid, kerr_form="analytic", **common + (), LENGTH, provider=guide, kerr_form="analytic", **field, **common ), "general, linear": prop_waveguide( - (), LENGTH, provider=linear_guide, grid=grid, kerr_form="analytic", **common - ), - "gnlse": prop_gnlse( - gamma, LENGTH, grid=envelope_grid, fibre=channel, shock=True, **common + (), LENGTH, provider=linear_guide, kerr_form="analytic", **field, **common ), + "gnlse": prop_gnlse(gamma, LENGTH, fibre=channel, shock=True, **envelope, **common), "gnlse, linear": prop_gnlse( - 0.0, LENGTH, grid=envelope_grid, fibre=channel, shock=True, **common + 0.0, LENGTH, fibre=channel, shock=True, **envelope, **common ), } diff --git a/docs/auto_tutorials/waveguides/plot_05_general_modal.py.md5 b/docs/auto_tutorials/waveguides/plot_05_general_modal.py.md5 index b61c4e3bc..cc8ebb108 100644 --- a/docs/auto_tutorials/waveguides/plot_05_general_modal.py.md5 +++ b/docs/auto_tutorials/waveguides/plot_05_general_modal.py.md5 @@ -1 +1 @@ -a1aef66c98ee8a3d05fa70ce2c572615 \ No newline at end of file +e9d2cb84def22d706be5ed1c0a0b97d7 \ No newline at end of file diff --git a/docs/auto_tutorials/waveguides/plot_05_general_modal.rst b/docs/auto_tutorials/waveguides/plot_05_general_modal.rst index 27831b1f7..3d6f5bd74 100644 --- a/docs/auto_tutorials/waveguides/plot_05_general_modal.rst +++ b/docs/auto_tutorials/waveguides/plot_05_general_modal.rst @@ -33,7 +33,7 @@ vector coefficient, which carries the longitudinal field and the ``|E.E|^2`` term, agrees with the scalar ``n2 omega / (c A_eff)`` to a fraction of a per cent here. On a sub-micron strand the two differ by a quarter. -.. GENERATED FROM PYTHON SOURCE LINES 21-63 +.. GENERATED FROM PYTHON SOURCE LINES 21-65 .. code-block:: Python @@ -42,6 +42,7 @@ a per cent here. On a sub-micron strand the two differ by a quarter. import numpy as np from solprop import fourier + from solprop.boundaries import DEFAULT_BOUNDARY_N, absorber from solprop.constants import C from solprop.driver import prop_gnlse, prop_waveguide from solprop.grid import EnvelopeGrid, FieldGrid @@ -63,13 +64,14 @@ a per cent here. On a sub-micron strand the two differ by a quarter. route: it is the explicit in-stage temporal collar (see "Boundaries" in the model documentation), whose rate is set by the length the *grid* was built for, and whose stable step is set - by that rate. A general modal step is expensive, so this example builds its - grids for a millimetre -- a gentle collar -- and propagates twenty microns of it, - to stay inside the documentation build's budget. + by that rate. A general modal step is expensive, so this example propagates + twenty microns -- a run ends at its grid's length, so its grids are built for + twenty microns -- and keeps the collar a millimetre's grid would have, a gentle one, + through ``boundary_length``, to stay inside the documentation build's budget. """ WINDOW_LENGTH = 1e-3 - """Length the grids and their collar are declared for, m.""" + """Length the collar's rate is declared for, m.""" N2 = 2.6e-20 CHI3 = chi3_from_n2(N2, 1.45) @@ -92,13 +94,13 @@ a per cent here. On a sub-micron strand the two differ by a quarter. -.. GENERATED FROM PYTHON SOURCE LINES 64-67 +.. GENERATED FROM PYTHON SOURCE LINES 66-69 The guide: a 4 um core at a 0.01 index step, with the Kerr response declared on the core region and nothing on the cladding, which is how a linear cladding is said to be linear. -.. GENERATED FROM PYTHON SOURCE LINES 67-98 +.. GENERATED FROM PYTHON SOURCE LINES 69-100 .. code-block:: Python @@ -155,13 +157,13 @@ said to be linear. -.. GENERATED FROM PYTHON SOURCE LINES 99-102 +.. GENERATED FROM PYTHON SOURCE LINES 101-104 The vector coefficient, and the scalar one the GNLSE would use. ``metric=`` is the channel's own sampled Poynting flux -- the metric the route's projection map contracts with -- so the coefficient is the same statement that map makes. -.. GENERATED FROM PYTHON SOURCE LINES 102-117 +.. GENERATED FROM PYTHON SOURCE LINES 104-119 .. code-block:: Python @@ -194,7 +196,7 @@ map contracts with -- so the coefficient is the same statement that map makes. -.. GENERATED FROM PYTHON SOURCE LINES 118-131 +.. GENERATED FROM PYTHON SOURCE LINES 120-133 A short run through each route, and each one's own dispersion-only reference: a guide whose regions declare no response, and gamma = 0. @@ -210,7 +212,7 @@ the general modal manual page says why — so what the comparison measures is the two routes and not the choice of form. -.. GENERATED FROM PYTHON SOURCE LINES 131-183 +.. GENERATED FROM PYTHON SOURCE LINES 133-193 .. code-block:: Python @@ -240,18 +242,26 @@ comparison measures is the two routes and not the choice of form. "dz_init": LENGTH / 10, } channel = guide.mode_collection.modes[0] + # The runs' grids sample as the guide's did, over the twenty microns they propagate, + # with the collar of a millimetre. + run_grid = FieldGrid.from_limits(LENGTH, 835e-9, (790e-9, 890e-9), 200e-15) + run_envelope_grid = EnvelopeGrid.from_limits(LENGTH, 835e-9, (790e-9, 890e-9), 200e-15) + gentle = WINDOW_LENGTH / DEFAULT_BOUNDARY_N + field = {"grid": run_grid, "absorber": absorber(run_grid, boundary_length=gentle)} + envelope = { + "grid": run_envelope_grid, + "absorber": absorber(run_envelope_grid, boundary_length=gentle), + } runs = { "general": prop_waveguide( - (), LENGTH, provider=guide, grid=grid, kerr_form="analytic", **common + (), LENGTH, provider=guide, kerr_form="analytic", **field, **common ), "general, linear": prop_waveguide( - (), LENGTH, provider=linear_guide, grid=grid, kerr_form="analytic", **common - ), - "gnlse": prop_gnlse( - gamma, LENGTH, grid=envelope_grid, fibre=channel, shock=True, **common + (), LENGTH, provider=linear_guide, kerr_form="analytic", **field, **common ), + "gnlse": prop_gnlse(gamma, LENGTH, fibre=channel, shock=True, **envelope, **common), "gnlse, linear": prop_gnlse( - 0.0, LENGTH, grid=envelope_grid, fibre=channel, shock=True, **common + 0.0, LENGTH, fibre=channel, shock=True, **envelope, **common ), } @@ -280,14 +290,14 @@ comparison measures is the two routes and not the choice of form. -.. GENERATED FROM PYTHON SOURCE LINES 184-188 +.. GENERATED FROM PYTHON SOURCE LINES 194-198 In the internal FFT convention both routes turn by ``-gamma P(t) L`` (the public optics-convention phase has the opposite sign), plotted against the local power so that the two grids' different time samples fall on one curve. -.. GENERATED FROM PYTHON SOURCE LINES 188-213 +.. GENERATED FROM PYTHON SOURCE LINES 198-223 .. code-block:: Python @@ -328,7 +338,7 @@ so that the two grids' different time samples fall on one curve. -.. GENERATED FROM PYTHON SOURCE LINES 214-221 +.. GENERATED FROM PYTHON SOURCE LINES 224-231 Related reading --------------- @@ -341,7 +351,7 @@ For a paced propagation lesson, return to .. rst-class:: sphx-glr-timing - **Total running time of the script:** (0 minutes 4.537 seconds) + **Total running time of the script:** (0 minutes 8.945 seconds) .. _sphx_glr_download_auto_tutorials_waveguides_plot_05_general_modal.py: diff --git a/docs/auto_tutorials/waveguides/plot_05_general_modal.zip b/docs/auto_tutorials/waveguides/plot_05_general_modal.zip index 44a0f300f..ec01f741a 100644 Binary files a/docs/auto_tutorials/waveguides/plot_05_general_modal.zip and b/docs/auto_tutorials/waveguides/plot_05_general_modal.zip differ diff --git a/docs/auto_tutorials/waveguides/plot_06_graded_index.codeobj.json b/docs/auto_tutorials/waveguides/plot_06_graded_index.codeobj.json index 8842b2f55..5dc38ecb9 100644 --- a/docs/auto_tutorials/waveguides/plot_06_graded_index.codeobj.json +++ b/docs/auto_tutorials/waveguides/plot_06_graded_index.codeobj.json @@ -1333,7 +1333,7 @@ { "is_class": false, "is_explicit": false, - "module": "solprop.output.schema", + "module": "solprop.output.records", "module_short": "solprop.output", "name": "SavedPlane" }, @@ -1658,8 +1658,8 @@ { "is_class": false, "is_explicit": false, - "module": "solprop.output.schema", - "module_short": "solprop.output.schema", + "module": "solprop.output.store", + "module_short": "solprop.output.store", "name": "PlaneStore.planes" }, { diff --git a/docs/auto_tutorials/waveguides/plot_06_graded_index.ipynb b/docs/auto_tutorials/waveguides/plot_06_graded_index.ipynb index 8f3c2f248..3782d213d 100644 --- a/docs/auto_tutorials/waveguides/plot_06_graded_index.ipynb +++ b/docs/auto_tutorials/waveguides/plot_06_graded_index.ipynb @@ -76,7 +76,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "A continuous wave in both channels at once, propagated to that length in ten\nsteps. One coarse bin is exactly periodic on the time window, so the beat is\nthe two channels' relative phase and nothing else. A wave that fills the window\nwants neither the temporal collar nor the watch on the window's edges.\n\n" + "A continuous wave in both channels at once, propagated to that length in ten\nsteps. One coarse bin is exactly periodic on the time window, so the beat is\nthe two channels' relative phase and nothing else. A wave that fills the window\nwants neither the temporal collar nor the watch on the window's edges. A run\nends at its grid's length, so its grid samples as the guide's did, built for the\nimaging length.\n\n" ] }, { @@ -87,7 +87,7 @@ }, "outputs": [], "source": [ - "simulation = Simulation.from_waveguide(\n (),\n length,\n provider=guide,\n grid=grid,\n wavelength=WAVELENGTH,\n fwhm=40e-15,\n energy=1e-15,\n shape=\"gauss\",\n n_save=9,\n dz_max=length / 10,\n dz_init=length / 10,\n noise=None,\n absorber=False,\n boundary_check=None,\n)\nlaunch = np.zeros((2, 1, grid.n_omega), dtype=complex)\nlaunch[:, 0, centre] = 1.0\nrun = simulation.with_input(launch).run(progress=\"none\")\nplanes = run.planes()" + "simulation = Simulation.from_waveguide(\n (),\n length,\n provider=guide,\n grid=FieldGrid.from_limits(length, WAVELENGTH, (1.0e-6, 1.06e-6), 100e-15),\n wavelength=WAVELENGTH,\n fwhm=40e-15,\n energy=1e-15,\n shape=\"gauss\",\n n_save=9,\n dz_max=length / 10,\n dz_init=length / 10,\n noise=None,\n absorber=False,\n boundary_check=None,\n)\nlaunch = np.zeros((2, 1, grid.n_omega), dtype=complex)\nlaunch[:, 0, centre] = 1.0\nrun = simulation.with_input(launch).run(progress=\"none\")\nplanes = run.planes()" ] }, { diff --git a/docs/auto_tutorials/waveguides/plot_06_graded_index.py b/docs/auto_tutorials/waveguides/plot_06_graded_index.py index 28f26416d..91c85eb6e 100644 --- a/docs/auto_tutorials/waveguides/plot_06_graded_index.py +++ b/docs/auto_tutorials/waveguides/plot_06_graded_index.py @@ -112,12 +112,14 @@ # A continuous wave in both channels at once, propagated to that length in ten # steps. One coarse bin is exactly periodic on the time window, so the beat is # the two channels' relative phase and nothing else. A wave that fills the window -# wants neither the temporal collar nor the watch on the window's edges. +# wants neither the temporal collar nor the watch on the window's edges. A run +# ends at its grid's length, so its grid samples as the guide's did, built for the +# imaging length. simulation = Simulation.from_waveguide( (), length, provider=guide, - grid=grid, + grid=FieldGrid.from_limits(length, WAVELENGTH, (1.0e-6, 1.06e-6), 100e-15), wavelength=WAVELENGTH, fwhm=40e-15, energy=1e-15, diff --git a/docs/auto_tutorials/waveguides/plot_06_graded_index.py.md5 b/docs/auto_tutorials/waveguides/plot_06_graded_index.py.md5 index 5a949440a..9a7a3a456 100644 --- a/docs/auto_tutorials/waveguides/plot_06_graded_index.py.md5 +++ b/docs/auto_tutorials/waveguides/plot_06_graded_index.py.md5 @@ -1 +1 @@ -d3c231fe50cfeddc7ebd10a4e1aa6560 \ No newline at end of file +f3f61dd45d997e94d82ee41097abcd59 \ No newline at end of file diff --git a/docs/auto_tutorials/waveguides/plot_06_graded_index.rst b/docs/auto_tutorials/waveguides/plot_06_graded_index.rst index 47ca0cc74..80dd63b58 100644 --- a/docs/auto_tutorials/waveguides/plot_06_graded_index.rst +++ b/docs/auto_tutorials/waveguides/plot_06_graded_index.rst @@ -193,14 +193,16 @@ is 1 and 3. Their spacing sets the self-imaging length ``2 pi / Delta beta``. -.. GENERATED FROM PYTHON SOURCE LINES 112-116 +.. GENERATED FROM PYTHON SOURCE LINES 112-118 A continuous wave in both channels at once, propagated to that length in ten steps. One coarse bin is exactly periodic on the time window, so the beat is the two channels' relative phase and nothing else. A wave that fills the window -wants neither the temporal collar nor the watch on the window's edges. +wants neither the temporal collar nor the watch on the window's edges. A run +ends at its grid's length, so its grid samples as the guide's did, built for the +imaging length. -.. GENERATED FROM PYTHON SOURCE LINES 116-137 +.. GENERATED FROM PYTHON SOURCE LINES 118-139 .. code-block:: Python @@ -208,7 +210,7 @@ wants neither the temporal collar nor the watch on the window's edges. (), length, provider=guide, - grid=grid, + grid=FieldGrid.from_limits(length, WAVELENGTH, (1.0e-6, 1.06e-6), 100e-15), wavelength=WAVELENGTH, fwhm=40e-15, energy=1e-15, @@ -232,13 +234,13 @@ wants neither the temporal collar nor the watch on the window's edges. -.. GENERATED FROM PYTHON SOURCE LINES 138-141 +.. GENERATED FROM PYTHON SOURCE LINES 140-143 The transverse intensity along the beat. The two channels' patterns add in phase at the entrance, cancel on the axis half a beat later, and come back at the imaging length: the guide has reproduced its own launch. -.. GENERATED FROM PYTHON SOURCE LINES 141-164 +.. GENERATED FROM PYTHON SOURCE LINES 143-166 .. code-block:: Python @@ -277,13 +279,13 @@ the imaging length: the guide has reproduced its own launch. -.. GENERATED FROM PYTHON SOURCE LINES 165-168 +.. GENERATED FROM PYTHON SOURCE LINES 167-170 The residual phase after a full turn is the solved spacing's departure from the ideal one, and nothing else: the guide reproduces its own dispersion, and what is left over is the P1 discretisation of an analytic answer. -.. GENERATED FROM PYTHON SOURCE LINES 168-177 +.. GENERATED FROM PYTHON SOURCE LINES 170-179 .. code-block:: Python @@ -310,14 +312,14 @@ is left over is the P1 discretisation of an analytic answer. -.. GENERATED FROM PYTHON SOURCE LINES 178-182 +.. GENERATED FROM PYTHON SOURCE LINES 180-184 A launch declared as a **field** rather than as a channel. The route projects it onto the channels through the record's coordinate dual and reports what the bound channels did not capture, so a profile the guide cannot carry says so instead of being quietly rescaled. -.. GENERATED FROM PYTHON SOURCE LINES 182-193 +.. GENERATED FROM PYTHON SOURCE LINES 184-195 .. code-block:: Python @@ -350,13 +352,13 @@ instead of being quietly rescaled. -.. GENERATED FROM PYTHON SOURCE LINES 194-197 +.. GENERATED FROM PYTHON SOURCE LINES 196-199 A field the channels cannot span leaves a remainder, and the projection names it rather than rescaling it away: here the same pattern with its sign flipped on every other node, which is no combination of the two channels at all. -.. GENERATED FROM PYTHON SOURCE LINES 197-202 +.. GENERATED FROM PYTHON SOURCE LINES 199-204 .. code-block:: Python @@ -378,7 +380,7 @@ on every other node, which is no combination of the two channels at all. -.. GENERATED FROM PYTHON SOURCE LINES 203-209 +.. GENERATED FROM PYTHON SOURCE LINES 205-211 The same happens, less obviously, to a profile declared at **one** frequency and held across the band: the channels' patterns change with frequency, so away from @@ -387,7 +389,7 @@ projection reports that too. The share is a reconstruction residual on the guide's nodes, not radiated power: the energy account of an incident beam is what ``incident=`` records (:doc:`/guide/waveguides/general-modal`). -.. GENERATED FROM PYTHON SOURCE LINES 209-215 +.. GENERATED FROM PYTHON SOURCE LINES 211-217 .. code-block:: Python @@ -410,7 +412,7 @@ what ``incident=`` records (:doc:`/guide/waveguides/general-modal`). -.. GENERATED FROM PYTHON SOURCE LINES 216-222 +.. GENERATED FROM PYTHON SOURCE LINES 218-224 Related reading --------------- @@ -422,7 +424,7 @@ For a paced propagation lesson, return to .. rst-class:: sphx-glr-timing - **Total running time of the script:** (0 minutes 2.357 seconds) + **Total running time of the script:** (0 minutes 1.800 seconds) .. _sphx_glr_download_auto_tutorials_waveguides_plot_06_graded_index.py: diff --git a/docs/auto_tutorials/waveguides/plot_06_graded_index.zip b/docs/auto_tutorials/waveguides/plot_06_graded_index.zip index 10a49a985..110675b47 100644 Binary files a/docs/auto_tutorials/waveguides/plot_06_graded_index.zip and b/docs/auto_tutorials/waveguides/plot_06_graded_index.zip differ diff --git a/docs/dev/gui/design.md b/docs/dev/gui/design.md index 508fd2984..204d76dd8 100644 --- a/docs/dev/gui/design.md +++ b/docs/dev/gui/design.md @@ -698,7 +698,7 @@ and the output size, and Run starts from it. it says it is unknown. Timing warm-up steps with `Simulation.estimate()` takes seconds, so it runs on request (21.1). - **Numerics** (Advanced on the sheet): backend (from `backends.registry.available()`), tolerance - (`rtol`, with the route's default shown), integrator, save planes (`n_save` or a spacing), statistics (`StatsSpec`, with the route's default set and the class's required + (`rtol`, with the route's default shown), integrator, save planes (`n_save` or explicit positions, SEP 51), statistics (`StatsSpec`, with the route's default set and the class's required statistics ticked), threads (`SOLPROP_THREADS`), boundary check and absorber, snapshots. - **Output**: run title and workspace folder (defaults filled in). - **Resume** replaces Run for an existing run of the same recipe that solprop reports resumable @@ -1359,7 +1359,7 @@ table, scan editor, compressor chain) and the pyqtgraph views. |---|---| | W1 Frame (built locally) | The `classes` layer. The controller moved out of `MainWindow`. Home, the three stages, the sheet frame, the rail and the z scrubber. Built as: `classes/` holds the four classes as data, a test holding every row to its class's example; `ui/document.py` (`SetupDocument`) owns the recipe, undo, checks and files for both windows; `solprop-gui --workflow` opens the new window beside the step window, which Other geometry still opens. Setup edits and checks a real recipe with solprop's numbers; Run and Analyse host the existing views under the new frame, with their sliders replaced by the scrubber. Left to W2: the live sheet (preview plot, typed targets, fast numbers), plain-language rows, and the pages not built, which say so on the rail. | | W2 Capillary (built locally) | End to end: the live sheet with typed targets, the Run stage and every page of 11.3. Checked by walking S1 and S4 by hand. Built as: `service/sheet.py` gives the numbers (about 120 ms, `tools.capillary_params` on the resolved recipe), the curve and dispersive wave (about 170 ms) and the output's size; a number with a target is a button that writes `[pins]`, and the row it moves shows what it solved. Run and Analyse are one widget (`ui/analyse.py`), the Overview under a progress strip or beside the rail, and the pages are `ui/analysis_pages.py` over a shared `ui/analysis.py`, drawing only while on screen. Not built: a rough time on the Ready line, the step-size sparkline on the strip, and a choice among several roots of a target. A ZDW target takes about 290 ms to solve, over the sheet's 150 ms (P8). | -| W3 Radial filament (built locally) | Its sheet and pages, with the spatial readers and beam numbers of 21.2. Checked by walking S6. Built as: rows that move several paths, because the object routes write a gas or wavelength several times and a run's length as its last saved plane (`Field.also`, `moves_planes`, `planes_over`, #533); switches for Kerr and plasma, whose entries come back from the class's example; a lens as an option on the beam. The live numbers come from `tools.beam_params`. The Overview grows from each plane's fluence and the beam's spectrum, and reads the on-axis spectrum from the file when the run ends. Not built: a far field or spectrogram while a run goes. | +| W3 Radial filament (built locally) | Its sheet and pages, with the spatial readers and beam numbers of 21.2. Checked by walking S6. Built as: rows that move several paths, because the object routes write a gas or wavelength several times (`Field.also`); a saved-planes row of two forms, a count (`n_save`) or explicit positions (`save_planes`), one replacing the other in one edit (`Field.positions`, SEP 51); switches for Kerr and plasma, whose entries come back from the class's example; a lens as an option on the beam. The live numbers come from `tools.beam_params`. The Overview grows from each plane's fluence and the beam's spectrum, and reads the on-axis spectrum from the file when the run ends. Not built: a far field or spectrogram while a run goes. | | W4 Fibres (built locally) | Solid-core and antiresonant, as classes. Checked by running both through every page. Built as: the solid-core sheet reads its mode and `tools`, with no targets, since pins cover the capillary only; the antiresonant sheet uses `tools.soliton_params` on its own mode, and only the soliton order is a target, because a fibre has many zeros and resonances. Its zero is read from the curve inside the run's window, where the tool's nearest in frequency can lie far beyond it. Its loss curve and cross-section sit below the dispersion curve. A sheet edit costs about 280 ms on the antiresonant route against the 150 ms of the capillary. Not built: Noise and coherence, which stays disabled as no run is a seeded ensemble until scans exist. | | W5 Design a waveguide (built locally) | The workflow of 7.4, reusing the explorer's quantities and sweeps. Checked by walking S2 by script. Built as: a stage of the workflow window, opened from Home, that never touches the open setup. A design is always a class's example with the design's values set, so what it shows is what that recipe builds, and *Simulate this* opens it as a new sheet. It covers capillary and antiresonant fibre, with pages Curves (β₂, D, β₃, n_eff − 1, group index), ZDW map (pressure against radius per zero, capillary only), Phase matching and Loss. It has a sweep of pressure, radius or gas, where a click takes a curve's value or a map point's radius and pressure. It solves the pressure for a ZDW, and the energy too for an order. A curve costs about 90 ms, a sweep of four about 250 ms, and a map about 2 s. Not built: a sweep of the mode order, the solid-core fibre, a figure export (CSV only), and Copy as Python. | | W6 Other geometry (built locally) | Every other route on the generic form. The step window is deleted. Checked by running each example of those routes (hollow rectangular, graded-index, Cartesian and line beams, both planar) from Home through every page. Built as: Home's Other geometry tile lists those examples. A recipe on a route with no class gets a class made from solprop's metadata: its sections are the metadata groups, holding the keywords the recipe sets, with the rest under Advanced. Its numbers are the summary's energy and peak power, and its rail is Overview, At this plane, Along z and Run health. A planar run has no Overview, since its planes are slab amplitudes no map reads yet. A beam's plane is summed across the beam. A general modal guide's energy is its physical energy. `solprop-gui` opens the workflow window, and `--workflow` is accepted and ignored. A service run re-attaches in the new window. Removed with the step window: `ui/main_window`, `ui/start`, `ui/design_tool`, `ui/scan_editor`, `views/explorer`, `views/zdw_chart` and their tests. Not built: scans, which wait for their own mode (12.7); a cross-section on the generic form; per-width labels (J/m) for line and planar beams; a fluence map page for Cartesian and line beams (#455 gives the reader). | diff --git a/docs/dev/roadmap.md b/docs/dev/roadmap.md index dcb9eb4a1..4b9ccc5d0 100644 --- a/docs/dev/roadmap.md +++ b/docs/dev/roadmap.md @@ -35,13 +35,6 @@ being implemented. routes, bound response and other geometries remain follow-up work; the first route is a single-mode capillary with node quadrature. -- [SEP 51 — One rule for the saved planes and the end of a run](seps/sep-0051-save-planes.md): - the length stated once, as `length` or `grid.length`, is the limit and the end of every - run; every run records its entrance and end, and every route, recipe and front-end - sheet takes the same `n_save` (evenly spaced over the launched interval) or - `save_planes` (positions), with no bare numbers. Continuing a finished run stays in - [#141](https://github.com/LupoLab/solprop/issues/141). - - [SEP 52 — One backend shape and a small native seam](seps/sep-0052-backend-shape.md): `numpy_ref` and `native` built from the same workspace, engines, marches and session, reading shared run records; `HostDriver` removed; the `Batch` executor, every group path diff --git a/docs/dev/seps/archive/index.md b/docs/dev/seps/archive/index.md index 7dd2e80a5..21f7a125a 100644 --- a/docs/dev/seps/archive/index.md +++ b/docs/dev/seps/archive/index.md @@ -46,4 +46,5 @@ sep-0046-machine-calibration sep-0047-run-ownership sep-0048-julia-backend sep-0049-tdse-on-native +sep-0051-save-planes ``` diff --git a/docs/dev/seps/sep-0051-save-planes.md b/docs/dev/seps/archive/sep-0051-save-planes.md similarity index 76% rename from docs/dev/seps/sep-0051-save-planes.md rename to docs/dev/seps/archive/sep-0051-save-planes.md index ff5ec8889..aed71aaae 100644 --- a/docs/dev/seps/sep-0051-save-planes.md +++ b/docs/dev/seps/archive/sep-0051-save-planes.md @@ -6,7 +6,7 @@ | **Title** | One rule for the saved planes and the end of a run | | **Author** | John Travers | | **Drafting agent** | Opus 5.5 (2026-11-15) | -| **Status** | Accepted | +| **Status** | Final | | **Review status** | Reviewed | | **Reviewers** | John Travers (human); GPT-6 (AI) | | **Type** | Change | @@ -15,8 +15,8 @@ | **Requires** | — | | **Supersedes** | — | | **Superseded-by** | — | -| **Implementation** | — | -| **Manual pages** | — | +| **Implementation** | Opus 5.5 (AI), for John Travers. Phases 1 and 2 on `feature/sep-0051-save-planes`, [PR #851](https://github.com/LupoLab/solprop/pull/851) | +| **Manual pages** | `guide/setup/running.md`, `guide/setup/recipes.md`, `guide/free-space/beams.md` | ## Part I — Proposal @@ -523,6 +523,257 @@ None beyond solprop's own documentation and issues, cited where used. ## Part II — Implementation record +### Phase 1 — Driver and recipes + +**Scope.** 2026-11-16; Opus 5.5 (AI) for John Travers; branch +`feature/sep-0051-save-planes`, commits from `e8de3270` (the helper and adoption) to the +commit that appends this report. The front end (§5.10, phase 2) is untouched. + +**Survey (§11), before any call site was edited.** An instrumented `Simulation.settings` +setter and the two grid helpers recorded, for every run the default test lane builds, +what the new rule would do. The lane was cancelled from outside at 91 % (twice; the +numbers are of the second run); the slow lane and `native/tests` were not run. + +| What the rule changes | Count | +|---|---| +| The run's end moves later (last plane before `grid.length`) | 371 adoptions, 189 tests, 52 call sites in 25 files | +| A plane beyond the end, refused | 1 (`tests/output/test_record_arrays.py`, a `length` of 1 cm on a 10 µm grid) | +| A plane before an interior launch, refused | 1 (already a refusal test) | +| A replay schedule not covering the run, refused | 92 adoptions, 32 tests, 16 sites in 10 files | +| A replay start that is not the entrance | 0 | +| A plane normalized onto the end | 0 | +| A keyword call with both `length` and `grid` | 2199 calls at 224 sites; 43 calls at 13 sites disagree | + +A static scan of the tree (Python files and the Python blocks of Markdown pages) found 509 +keyword-route calls that pass `length` positionally, in 227 hand-written files (150 test +files, 43 gallery scripts, 12 guide pages, 12 native tests, 5 benchmarks, the README, two +package files and one design page), and 185 call sites passing `length` beside `grid=`. +That count is what decided the first deviation below. + +**Delivered.** + +- `src/solprop/driver/settings.py`: `SimulationSettings.n_save`, an optional + `save_planes`, and four private helpers: `_selectors` (the refusals that need no + interval), `_observation_planes` (placement, endpoint normalization within + `LANDING_ULPS` ulps of each endpoint, the interval refusals; it replaces + `_save_planes`), `_run_length` (the length/grid table of §5.1) and `_adopted` (the + entrance check, the replay check of §5.7 with `replay_tolerance`, and resolution). +- `src/solprop/driver/simulation.py`: the `settings` setter adopts every settings object + through `_adopted` before any comparison, so the constructor, the keyword builders, + `with_input`, `with_mixture` and anything else that builds a `Simulation` share one + rule; `length` is optional on `from_gnlse`, `from_capillary` and `from_waveguide` and + resolved by `_run_length` before anything uses it; the keyword routes pass `n_save` and + `save_planes` through unresolved. `src/solprop/driver/interface.py`: the same + signatures on `prop_*`. `src/solprop/driver/routes/general.py`: the general modal + route's tables span `grid.length`, the run's end. +- `src/solprop/recipe/`: the settings metadata drops the integer form of `save_planes` + and gains `n_save`; `refuse_plane_count` refuses `save_planes = N` with "write + `n_save = N`" on every route; `plane_parameter` turns the driver's refusals of the + planes, the length and replay into a `RecipeError` naming the keyword, in + `build_object` and `Recipe.build`; a keyword-route recipe with neither `length` nor + `grid` is refused before the route is called; `resolved_document` writes the resolved + positions in `[build.settings]` on an object route (and at the top level otherwise) + and drops `n_save`. +- `benchmarks/builders.py`: `window`, which runs a case to a shorter stop (`ab + --length`) by rebuilding it on its grid cut at the stop, carrying the whole case's + collar, steps and profiles; `benchmarks/sessions.py` and the linear GRIN case use it or + cut their own grid. +- Tests: `tests/driver/test_save_planes.py` (the refusal table, placement and endpoints, + the rounding cases, count/positions parity of planes and hash, interior launches on and + off a zero-based lattice, `with_input`, setter replacement and reuse at other lengths, + the length/grid table on all three keyword routes, replay drift and refusals) and + `tests/recipe/test_save_planes.py` (refusals as `RecipeError` with their paths on + object and keyword routes, `n_save` in settings, the resolved recipe for a count, a + list, a short list and no selector, and its independence of the default count). + `tests/builders.py` gains `grid_at` and `held_collar`. +- Pages: `docs/guide/setup/running.md` (a section on the length and the saved planes), + `docs/guide/setup/recipes.md` (the settings' selectors and the resolved recipe), + `docs/guide/free-space/beams.md` (the `linspace` idiom becomes `n_save`); docstrings of + `SimulationSettings`, `Simulation`, its setter, `with_input`, `from_free`, + `from_planar` and the keyword routes. Changelog: `changelog.d/sep-0051-save-planes.changed.md` + (the migration) and `changelog.d/533-save-planes-count.fixed.md`. + +**Existing tests changed (Q7's closing paragraph).** No tolerance was changed. + +- *A short window of a longer grid, physics kept* (the grid cut at the run's end with + `grid_at`, the collar the longer grid gave with `held_collar` or by building it on the + longer grid, and a length-derived default step pinned where one applied): the + sixth-order soliton of `tests/driver/test_prop_gnlse.py`; the general modal fixtures of + `test_general_modal.py`, `test_modal_metrics.py`, `test_modal_resume.py`, + `test_material_manifest.py`, `test_modal_launch.py` (also `dz_max`) and + `test_route_keywords.py`; the far-field cases of `test_far_field_statistics.py` and + `test_native_far_field.py`; two planar-hybrid runs; `tests/record_routes.py`. +- *A `length` that disagreed with `grid`* (the run's own end kept, the grid built there, + the collar pinned): `tests/backends/adams_source_cases.py` (the Adams source ladder), + the general entry point of `tests/backends/general_rows.py`, the native noisy-run + reference of `test_native_session_history.py`, the two capillary receivers of + `tests/coupling/test_workflows.py`, the wide case of `tests/coupled_flow_cases.py` + (its collar was already pinned), `test_vector_coupling.py` and the linear GRIN + benchmark. +- *Construction or refusal only, shortened freely*: three cases of + `test_simulation.py`, `test_backend_default.py`, `test_record_arrays.py`, one refusal + of `test_coherent_capillary.py`, `tests/translate/test_routes.py` and two far-field + geometry refusals. +- *Replay*: the dispersive capillary's one-step row now records its whole replayed + schedule (the rung takes the first step alone, so the step is unchanged); + `tests/sessions/test_group.py`'s schedule past the last plane, which existed to test + the ignored tail, is now a refusal test. +- *Messages and harness*: `tests/recipe/test_pins.py` (the refusal of a recipe with + neither length nor grid), `tests/test_benchmark_cases.py` and + `tests/test_benchmark_guides.py` (a shortened case's grid is cut at its stop, with the + whole case's collar and steps). + +**Deviations from the proposal.** + +1. *`length` is optional but stays positional-or-keyword* (§5.1, Q7 item 6). Making it + keyword-only would edit about 509 calls in 227 files and regenerate 43 galleries. The + maintainer accepted this deviation on 2026-11-16, so the positional form stays. + Because Python allows no required parameter after an optional one, + `from_capillary`'s and `prop_capillary`'s `gas` now defaults to `None` and is refused + when omitted. A hazard for the keyword-only form: with `length` keyword-only, the next + positional parameter (`betas` on the GNLSE routes, `gas` on the capillary and + waveguide routes) takes the freed slot, so `from_capillary(r, 0.2, "Ar")` would bind + `0.2` to `gas` instead of failing with Python's own error; a guaranteed failure would + need those parameters keyword-only as well. +2. *A recipe with neither `length` nor `grid`* is refused by the recipe before the route + is called, as "a length or a grid is required" against `length`, rather than by the + route; otherwise a recipe with pins reported it against the pinned keyword. +3. *A recipe's integer `save_planes`* says "write `n_save = 80`", the recipe's spelling, + where Python says "pass `n_save=80`". +4. *Endpoint slack* is `LANDING_ULPS` ulps of the endpoint itself (§5.4, D5), so at an + entrance of zero it is exact; the replay check is skipped for an interior launch, + which the existing rule refuses with its own message. + +**Decisions.** + +- Resolution returns the same settings object when they are already resolved for the + run, so a repeated adoption is free and a translated run's settings compare by identity. +- The default count is read when the planes are resolved, not when the helper is + defined, so the resolved-recipe test can change it. +- The benchmark harness rebuilds a shortened case rather than running the whole one, and + refuses to shorten `grin_nonlinear`, which is translated at construction. + +**Verification.** `numpy_ref` and the native CPU build on the Xeon, eight logical CPUs, +one thread per worker. Passing: the 29 modules the survey flagged and every module +edited, the two new modules, `tests/recipe`, the resume and scan modules of +`tests/driver`, `tests/test_guide_snippets.py`, and the doctests of the edited source +modules, `tests/backends/test_parity_catalogue.py` (737 tests with `test_coherent_capillary.py`), and the 15 modules touched only to satisfy the type checker. Repository-wide `ruff check`, `ruff format --check` and `basedpyright` (0 errors) pass; numpydoc, codespell, `reuse` and `tests/test_seps.py` pass on the touched files. Not run locally: the full default lane, the slow lane, the +coverage lane, `native/tests`, the front-end gate and the galleries; CI is the gate. + +**Sources checked.** None needed: no constant, coefficient or citation was transcribed. + +**Limitations.** + +- The survey covers 91 % of the default lane. +- Other setup depends on `grid.length` besides the default absorber, and is not pinned + when a test's grid is cut: `LossPolicy.limit(grid.length)` clamps a mode's attenuation + (`src/solprop/linear.py`), the boundary monitor's quiet-window spacing is + `grid.length / CHECKS`, and the walk-off warning integrates over `grid.length`. None of + the changed tests moved; §3 does not list them. +- `test_modal_launch.py`'s general runs keep the default first step, which is a fraction + of the length and refined by the start-up rule; their checks are of the launch. +- A recipe cannot hold a TDSE response (`tdse` has no recipe form), so the TDSE + capillary's resolved recipe is checked at construction, through `resolved_document`, + not round-tripped through `Recipe.from_output`. Added after review: + `tests/driver/test_save_planes.py` resumes an interrupted file, one holding a terminal + checkpoint and a completed one to the length, directly and through + `recipe.resume_file`, and replays `from_history` and `uniform` schedules drifting + below and above the length; `tests/recipe/test_save_planes.py` rebuilds a run from its + file's resolved recipe with `DEFAULT_N_SAVE` changed, keeping its hash. + +**Open questions.** + +- Q8: keyword-only `length` (deviation 1), with the slide of `betas`/`gas` into its + slot. Settled by the maintainer: `length` stays positional-or-keyword. +- Q9: `driver/scaffold.py`'s fixed-step tool had its own `n_save`, which did not count + the entrance. Settled by the maintainer: it now takes SEP 51's meaning, evenly spaced + planes over `[0, z_end]` with both ends counted, at least 2. +- Q10: whether the loss clamp and the monitor spacing should follow a pinned reference + length, as the absorber's does. Owner: an issue. + +**Cost** (`git diff --numstat` against `094a7fb8`): package code and +docstrings +473 −113 lines (`src/`), benchmarks +94 −12, tests +758 −121 (of which +507 in the two new modules and 29 in `tests/builders.py`), manual pages +72 −2. The +proposal estimated about 250 code lines, 100 docstring lines and 450 test lines, and 10–30 +edited tests; about 45 existing test and benchmark files were edited, about a third of +them only to wrap a now-optional `save_planes` for the type checker. + +**Handoff.** Phase 2 (§5.10) needs the object sheets to stop expanding a count into a +list over `grid.length`: the settings metadata now offers `n_save` beside `save_planes` +(an array only), and the resolved planes always end at the length. + +### Phase 2 — Front end + +**Scope.** 2026-11-16; Opus 5.5 (AI) for John Travers; branch +`feature/sep-0051-gui`, on phase 1, commits from `3646b0e5` (the sheets) to the commit +that appends this report; carried onto `feature/sep-0051-save-planes` as `d3702160` to +`e410e79f`. + +**Delivered.** + +- `gui/src/solprop_gui/classes/problem.py`: `Field.positions` replaces `planes_over` and + `moves_planes`. A saved-planes row reads the positions a recipe lists, or else its + count, and never turns a list into its count; its change writes a list as the + positions and anything else as the count, and unsets the other selector in the same + change. `even_planes` and the length row's rewriting of the list are removed. + `sheet_paths` and `other_keywords` count the positions as the row's, so the keyword + routes' `save_planes` leaves Advanced. +- `gui/src/solprop_gui/classes/catalog.py`: every class's "Saved planes" row is + `n_save` with `positions="save_planes"`, at the top level on the keyword routes and in + `settings` on the object routes; the object sheets' length rows no longer move planes. +- `gui/src/solprop_gui/ui/fields.py`: a row may name its forms (`mode_titles`); its + picker then shows them on a sheet, its text editor shows only what no other editor + holds, and leaving the text as shown writes nothing, so switching forms never replaces + a value by itself. `ParameterRow.current_mode` is new. +- `gui/src/solprop_gui/ui/sheet.py`: the row offers "Evenly spaced" (the count's integer + form) and "Explicit positions" (the positions' array form, as inline TOML). One value + typed as positions is a list of one. An issue on the positions shows at the row. +- Tests: `gui/tests/test_classes.py` (both forms on every class, at the route's level; a + uniform and a non-uniform loaded list shown as lists; each form replacing the other, + and clearing both; a length change moving the length alone; a count on the filament + built by solprop, ending at the shortened length, and a position beyond it refused at + `settings.save_planes`). `gui/tests/test_ui_workflow.py` (the keyword sheet: it opens + on its count; a length change keeps the count; switching forms writes nothing until an + entry; the entry replaces the count in one undoable edit, undone and redone; a lone + position; a position beyond a shortened length shown at the row and the Ready line; + save and reopen on the positions; back to a count; a non-uniform list opening as + itself; and the filament's object sheet opening its listed planes as explicit + positions, replaced by a count and restored by one undo). Every step checks that the + recipe never holds both selectors. +- Pages: `docs/guide/front-end/first-run.md` (the row's two forms), + `docs/dev/gui/design.md` (W3's rows and the numerics line), and a front-end sentence + in `changelog.d/sep-0051-save-planes.changed.md`. + +**Deviations from the proposal.** None in behaviour. One reading of §5.10: switching +the picker shows the other form's editor, empty, and the first entry there is the one +undoable edit that writes it and removes the other selector. A switch alone writes +nothing, because a count has no positions to show and a list has no count (D7), so +neither can be written for the user. + +**Verification.** On the Xeon, through Slurm, one thread per worker: `ruff format`, +`ruff check`, codespell on the touched files, `poe gui-types` (0 errors) and +`poe gui-docstrings` pass; `tests/test_classes.py` and the doctests of +`solprop_gui.classes` and `ui/fields.py` (91 passed); the whole front-end suite without +coverage, 440 passed: 433 in one run, and the seven that start a run passed when rerun +with the Slurm job's environment unset (inside a Slurm job, a run's worker records +itself as a Slurm job, which the window then cannot follow; they fail the same way on +phase 1's commit). `tests/test_seps.py`, `poe changelog-check` and the Sphinx build +(`-W -n`) pass; the build first failed on a cross-reference phase 1 added to +`guide/setup/recipes.md` (`solprop.recipe.RecipeError`, documented as +`solprop.recipe.errors.RecipeError`), corrected in its own commit. Not run locally: `gui-test` with coverage (the 100 % bar on +`classes`), which CI runs. + +**Sources checked.** None needed. + +**Limitations.** The positions are typed as inline TOML (`["5 cm", "10 cm"]`), as +Advanced edits them; a friendlier list editor is not part of this phase. Advanced's +`settings` editor on the object routes still shows `n_save` and `save_planes` side by +side, so a recipe edited there can hold both, which solprop's check refuses at the row. + +**Cost** (`git diff --numstat` against `ccadb278`): front-end code +133 −88 +(`classes` +47 −68), tests +206 −20, pages +17 −2 and the changelog +5. The proposal +estimated about 60 lines removed plus the new field and its tests. + ## Part III — History - 2026-11-15: Drafted, after the investigation of #533 found that no route ties the @@ -533,6 +784,13 @@ None beyond solprop's own documentation and issues, cited where used. - 2026-11-15: John Travers reviewed the proposal and recorded decisions D1–D8. The drafting agent revised Part I to match and responded to R1–R10. - 2026-11-15: Accepted by John Travers in PR #847. Part I is frozen. +- 2026-11-15: Implementation started on `feature/sep-0051-save-planes`. +- 2026-11-16: Phase 1 (driver and recipes) reported in Part II, with an interim + deviation on keyword-only `length` pending with the maintainer. +- 2026-11-16: Phase 2 (front end) reported in Part II, on `feature/sep-0051-gui`. +- 2026-11-16: Final. Both phases are reported in Part II and merge in PR #851. Open questions moved to issues: keyword-only `length` ([#857](https://github.com/LupoLab/solprop/issues/857)), the fixed-step scaffold's `n_save` ([#856](https://github.com/LupoLab/solprop/issues/856)) and further length-dependent defaults ([#855](https://github.com/LupoLab/solprop/issues/855)). +- 2026-11-16: The maintainer settled Q8 (`length` stays positional-or-keyword) and Q9 + (the scaffold's `n_save` takes SEP 51's meaning, in PR #851). ### AI review — 2026-11-15 diff --git a/docs/dev/seps/index.md b/docs/dev/seps/index.md index f025ed224..473f2a0be 100644 --- a/docs/dev/seps/index.md +++ b/docs/dev/seps/index.md @@ -33,7 +33,6 @@ Proposals that are active, in draft, accepted, in progress or deferred. | [11](sep-0011-finite-density-gas-index.md) | Finite-density gas index and mixture optics | Draft | Change | | [17](sep-0017-gas-two-photon-ionisation.md) | Broadband two-photon continuum response beside strong-field ionisation | Accepted | Feature | | [32](sep-0032-raman-maxwell-bloch.md) | Raman Maxwell–Bloch dynamics | Draft | Feature | -| [51](sep-0051-save-planes.md) | One rule for the saved planes and the end of a run | Accepted | Change | | [52](sep-0052-backend-shape.md) | One backend shape and a small native seam | In progress | Change | SEP 13, the standalone numerical prerequisite for SEP 12, SEP 14, which carried it to @@ -87,6 +86,7 @@ Proposals that are final, rejected, withdrawn or superseded; the | [47](archive/sep-0047-run-ownership.md) | Backend-owned execution sessions | Final | Change | | [48](archive/sep-0048-julia-backend.md) | A Julia backend: one engine for CPUs and GPUs, in both precisions | Withdrawn | Feature | | [49](archive/sep-0049-tdse-on-native.md) | The TDSE response on native | Final | Change | +| [51](archive/sep-0051-save-planes.md) | One rule for the saved planes and the end of a run | Final | Change | ```{toctree} :hidden: @@ -103,7 +103,6 @@ sep-0010-low-rank-raman sep-0011-finite-density-gas-index sep-0017-gas-two-photon-ionisation sep-0032-raman-maxwell-bloch -sep-0051-save-planes sep-0052-backend-shape template archive/index diff --git a/docs/guide/free-space/beams.md b/docs/guide/free-space/beams.md index 23c96171e..c9291a414 100644 --- a/docs/guide/free-space/beams.md +++ b/docs/guide/free-space/beams.md @@ -105,7 +105,7 @@ beam = SpatialPulse( ) settings = SimulationSettings( controller=PIController(rtol=1e-6, atol=1e-12), - save_planes=np.linspace(0, length, planes + 1)[1:], + n_save=planes + 1, # the entrance and `planes` more, to the end dz_init=1e-4, dz_max=length / planes, stats=StatsSpec(names=("energy", "beam_radius", "peak_intensity")), @@ -373,3 +373,5 @@ through lenses, apertures and free space or coupled into a capillary or fibre A beam's displacement and tilt were proposed and carried out by [SEP 41](../../dev/seps/archive/sep-0041-recipes-and-front-ends.md). +The saved planes follow +[SEP 51](../../dev/seps/archive/sep-0051-save-planes.md). diff --git a/docs/guide/front-end/first-run.md b/docs/guide/front-end/first-run.md index 7a67ba7fc..9f0ac70b0 100644 --- a/docs/guide/front-end/first-run.md +++ b/docs/guide/front-end/first-run.md @@ -24,6 +24,21 @@ gradient *from* 1.2 bar *to* 0 bar along the capillary, the example's own profil does when it is left empty. **Advanced** holds every other keyword of the route, with a *Find any setting* box. +**Saved planes**, in the simulation window, takes one of two forms +([the length and the saved planes](../setup/running.md#the-length-and-the-saved-planes)): + +- *Evenly spaced* is a count of observations, `n_save`, spread from the run's entrance + to its end with both ends counted. Changing the length spreads them again. +- *Explicit positions* is a list, `save_planes`, written as a recipe writes it: + `["5 cm", "10 cm"]`. The entrance and the end are recorded as well, one position is a + list of one, and `[]` keeps only the two ends. The positions stay as typed when the + length changes, and a position beyond the end is shown as an error at the row. + +Typing into the other form replaces the first in one edit, which **Undo** takes back, +so a setup never holds both. A setup opens on the form it holds, and a list is always +shown as the list, never as its count. Left empty, the row takes solprop's default +count. + As you type, the right side follows: - **What this gives** is computed by solprop from the setup as it stands @@ -98,3 +113,6 @@ setup. **⋯ → Save** keeps the setup as a recipe file of your own, and **⋯ → Show as Python** shows the script that builds the same simulation. Each results page's **Export** menu has *Copy as Python* too: the code that draws that page from the results file, with {py:mod}`solprop.processing` and {py:mod}`solprop.plotting`. + +The two forms of the saved planes were proposed and implemented by +[SEP 51](../../dev/seps/archive/sep-0051-save-planes.md). diff --git a/docs/guide/setup/recipes.md b/docs/guide/setup/recipes.md index 81882516b..a980a7550 100644 --- a/docs/guide/setup/recipes.md +++ b/docs/guide/setup/recipes.md @@ -180,6 +180,16 @@ dz_max = "2 mm" stats = { type = "StatsSpec", names = ["energy"] } ``` +The settings' planes follow the rule of every route +([the length and the saved planes](running.md#the-length-and-the-saved-planes)): the run +ends at the grid's `length` and records its entrance and end, `n_save = 81` gives 81 +evenly spaced observations over the run, and `save_planes` lists positions inside it, so +the table above could say `save_planes = []`. A bare integer, `save_planes = 80`, is +refused by `Recipe.check()` and `build()` with "write `n_save = 80`", as are both +selectors together, a position beyond the end and, on a keyword route, a `length` its +`grid` disagrees with: each is a {py:class}`~solprop.recipe.errors.RecipeError` naming the +keyword. + A recipe holds the `from_*` form, so the temporal absorber and its scheme are keywords of the `settings` table, `absorber = { type = "absorber" }` built on the `grid`, and not of `[build]`, although `prop_free` and `prop_planar` take them as @@ -330,6 +340,11 @@ goes to each point's run. A simulation built by `recipe.build()` carries its recipe, and its first run records it in the output beside the run, as the recipe was written and as it resolved: the recipe that rebuilds the run, seed included ([the file's layout](../results/output.md#the-recipe-a-run-was-built-from)). +The resolved recipe writes the run's planes as positions, ending at its length, where the +route reads them (at the top level of a keyword route, in `[build.settings]` on an +object route), and drops `n_save`; a route default, the TDSE capillary's two +observations and natural steps included, is written out too, so a later change of a +default cannot change the run it rebuilds. A change the recipe would not describe drops it with a warning, and the run then records none: `with_input`, `with_mixture`, or a new value of a setting other than `fields`, `field_planes` and `resume_history`. @@ -433,3 +448,5 @@ its reason, in the test that holds the examples to the gallery, so the list stay This page documents the functionality proposed and implemented by [SEP 41](../../dev/seps/archive/sep-0041-recipes-and-front-ends.md). +The saved planes follow +[SEP 51](../../dev/seps/archive/sep-0051-save-planes.md). diff --git a/docs/guide/setup/running.md b/docs/guide/setup/running.md index ff4ce7365..7be7aebc5 100644 --- a/docs/guide/setup/running.md +++ b/docs/guide/setup/running.md @@ -132,6 +132,61 @@ field's content in the collar. for two-colour and multi-colour inputs, on every keyword entry point of this page ([several pulses at once](pulses.md#several-pulses-at-once)). +### The length and the saved planes + +Every run marches from its entrance, `initial_z` (zero unless an interior launch sets +it), to its length, and always records both. The length is stated once. On a keyword +route it is `length`, or the length of a `grid=` passed instead; given both, they must +agree to within the marches' landing slack of eight ulps +({py:data}`~solprop.stepper.schedule.LANDING_ULPS`), and the grid's is then used, while +a disagreement is refused naming both values, as is a call with neither. On +{py:class}`~solprop.driver.simulation.Simulation` and the free-space and planar +constructors the length is `grid.length`. Everything that depends on the length uses +that one value: the run's end, the default steps and profiles, and the default +absorber's strength ([boundaries](../numerics/boundaries.md)). + +What is recorded in between is chosen by one of two selectors, on every route and in +{py:class}`~solprop.driver.settings.SimulationSettings` alike: + +- `n_save=N`, an integer of at least 2: `N` evenly spaced observations over + `[initial_z, length]`, both ends included; +- `save_planes=[...]`, positions in metres, finite and strictly increasing, inside that + interval. The entrance and the end are added when absent, and either may be listed; + `save_planes=[]` records the two endpoints alone. + +Given neither, a run records 201 (the TDSE capillary, its entrance and end with every +natural step). Giving both is refused, as are a bare number (`save_planes=80` says +"pass `n_save=80`"), a count below two and a position outside the interval: + +```{code-block} python +from solprop.driver import SimulationSettings + +SimulationSettings(n_save=81, dz_max=1e-3, dz_init=1e-6) # 81 over [0, grid.length] +SimulationSettings(save_planes=[0.05], dz_max=1e-3, dz_init=1e-6) # 0, 0.05 m, the end +SimulationSettings(save_planes=[], dz_max=1e-3, dz_init=1e-6) # the entrance and end +``` + +A position within eight ulps of an endpoint is that endpoint: `0.1 + 0.2` and the float +just below `0.3` both end a run of length `0.3`, and each endpoint is recorded once. +Settings are resolved when a simulation adopts them — at construction, on assigning +{py:attr}`~solprop.driver.simulation.Simulation.settings`, and in +{py:meth}`~solprop.driver.simulation.Simulation.with_input` — into the positions after +the entrance, the last exactly the length, so a count and the positions it stands for +are one run with one configuration hash. Resolved settings reused on a run of another +length are checked again: a position beyond the new end is refused and a shorter list +gains the new end. To carry a count instead, pass +`dataclasses.replace(settings, n_save=N, save_planes=None)`. An interior launch counts +over its own interval, and `with_input(..., initial_z=z)` keeps the observations +already resolved beyond `z`. A replayed `schedule=` must cover the run: its start at the +entrance, its end at the length to within the rounding its step sum accumulates +({py:func}`~solprop.stepper.schedule.replay_tolerance`). + +Every observation obeys `fields` and `field_planes`, so `fields="none"` still records +statistics at both ends without storing a field +([output](../results/output.md#statistics-only-planes-which-planes-keep-their-field)). +A short window of a long setup is therefore a shorter grid: shorten it and pin what the +longer length set, such as the absorber's `boundary_length`. + ### A table or mode as the GNLSE fibre Give exactly one of `betas`, `beta` and `fibre`, and one of `gamma` and `n2`. @@ -397,7 +452,7 @@ simulation = Simulation( pulse, settings=SimulationSettings( controller=PIController(rtol=1e-9, atol=1e-18), - save_planes=[0.25, 0.5, 0.75, 1.0], + n_save=5, # the entrance, 0.25, 0.5, 0.75 and grid.length dz_max=0.1, dz_init=1e-4, ), @@ -637,3 +692,6 @@ handler with no state written, and a run with an optmat ionisation rate, which r peak rates back from its output, neither reports its peak field nor warns past the rate's range ({py:class}`~solprop.exceptions.MaterialRangeWarning`). Read `peak_ionisation_rate` in the callable where that matters. + +The length and the saved planes were proposed and implemented by +[SEP 51](../../dev/seps/archive/sep-0051-save-planes.md). diff --git a/docs/tutorials/free_space/plot_08_radial_capillary_coupling.py b/docs/tutorials/free_space/plot_08_radial_capillary_coupling.py index 57c14a8bf..019aee432 100644 --- a/docs/tutorials/free_space/plot_08_radial_capillary_coupling.py +++ b/docs/tutorials/free_space/plot_08_radial_capillary_coupling.py @@ -41,6 +41,7 @@ from scipy.special import j0, jn_zeros from solprop import fourier +from solprop.boundaries import DEFAULT_BOUNDARY_N, absorber from solprop.constants import EPS0, C from solprop.coupling import CouplingModel, couple from solprop.driver import Simulation, SimulationSettings @@ -276,13 +277,20 @@ # mode *m*, in its native true-power metric, over the incident energy of the # whole entrance plane in the coupling's common measure. +# The capillary's grid samples as the gap's does -- a launch is bound to its +# lattice -- and is built for the capillary's own 5 mm, since a run ends at its +# grid's length; its collar keeps the rate the gap's 20 mm grid gives. +capillary_grid = EnvelopeGrid.from_limits( + LENGTH, WAVELENGTH, (500e-9, 1.4e-6), 300e-15, thg=False +) capillary = Simulation.from_capillary( RADIUS, LENGTH, "Ar", PRESSURE, wavelength=WAVELENGTH, - grid=grid, + grid=capillary_grid, + absorber=absorber(capillary_grid, boundary_length=GAP / DEFAULT_BOUNDARY_N), envelope=True, fwhm=FWHM, energy=energy, diff --git a/docs/tutorials/waveguides/plot_05_general_modal.py b/docs/tutorials/waveguides/plot_05_general_modal.py index 3c7de1643..c47c832df 100644 --- a/docs/tutorials/waveguides/plot_05_general_modal.py +++ b/docs/tutorials/waveguides/plot_05_general_modal.py @@ -23,6 +23,7 @@ import numpy as np from solprop import fourier +from solprop.boundaries import DEFAULT_BOUNDARY_N, absorber from solprop.constants import C from solprop.driver import prop_gnlse, prop_waveguide from solprop.grid import EnvelopeGrid, FieldGrid @@ -44,13 +45,14 @@ route: it is the explicit in-stage temporal collar (see "Boundaries" in the model documentation), whose rate is set by the length the *grid* was built for, and whose stable step is set -by that rate. A general modal step is expensive, so this example builds its -grids for a millimetre -- a gentle collar -- and propagates twenty microns of it, -to stay inside the documentation build's budget. +by that rate. A general modal step is expensive, so this example propagates +twenty microns -- a run ends at its grid's length, so its grids are built for +twenty microns -- and keeps the collar a millimetre's grid would have, a gentle one, +through ``boundary_length``, to stay inside the documentation build's budget. """ WINDOW_LENGTH = 1e-3 -"""Length the grids and their collar are declared for, m.""" +"""Length the collar's rate is declared for, m.""" N2 = 2.6e-20 CHI3 = chi3_from_n2(N2, 1.45) @@ -154,18 +156,26 @@ "dz_init": LENGTH / 10, } channel = guide.mode_collection.modes[0] +# The runs' grids sample as the guide's did, over the twenty microns they propagate, +# with the collar of a millimetre. +run_grid = FieldGrid.from_limits(LENGTH, 835e-9, (790e-9, 890e-9), 200e-15) +run_envelope_grid = EnvelopeGrid.from_limits(LENGTH, 835e-9, (790e-9, 890e-9), 200e-15) +gentle = WINDOW_LENGTH / DEFAULT_BOUNDARY_N +field = {"grid": run_grid, "absorber": absorber(run_grid, boundary_length=gentle)} +envelope = { + "grid": run_envelope_grid, + "absorber": absorber(run_envelope_grid, boundary_length=gentle), +} runs = { "general": prop_waveguide( - (), LENGTH, provider=guide, grid=grid, kerr_form="analytic", **common + (), LENGTH, provider=guide, kerr_form="analytic", **field, **common ), "general, linear": prop_waveguide( - (), LENGTH, provider=linear_guide, grid=grid, kerr_form="analytic", **common - ), - "gnlse": prop_gnlse( - gamma, LENGTH, grid=envelope_grid, fibre=channel, shock=True, **common + (), LENGTH, provider=linear_guide, kerr_form="analytic", **field, **common ), + "gnlse": prop_gnlse(gamma, LENGTH, fibre=channel, shock=True, **envelope, **common), "gnlse, linear": prop_gnlse( - 0.0, LENGTH, grid=envelope_grid, fibre=channel, shock=True, **common + 0.0, LENGTH, fibre=channel, shock=True, **envelope, **common ), } diff --git a/docs/tutorials/waveguides/plot_06_graded_index.py b/docs/tutorials/waveguides/plot_06_graded_index.py index 28f26416d..91c85eb6e 100644 --- a/docs/tutorials/waveguides/plot_06_graded_index.py +++ b/docs/tutorials/waveguides/plot_06_graded_index.py @@ -112,12 +112,14 @@ # A continuous wave in both channels at once, propagated to that length in ten # steps. One coarse bin is exactly periodic on the time window, so the beat is # the two channels' relative phase and nothing else. A wave that fills the window -# wants neither the temporal collar nor the watch on the window's edges. +# wants neither the temporal collar nor the watch on the window's edges. A run +# ends at its grid's length, so its grid samples as the guide's did, built for the +# imaging length. simulation = Simulation.from_waveguide( (), length, provider=guide, - grid=grid, + grid=FieldGrid.from_limits(length, WAVELENGTH, (1.0e-6, 1.06e-6), 100e-15), wavelength=WAVELENGTH, fwhm=40e-15, energy=1e-15, diff --git a/gui/src/solprop_gui/classes/catalog.py b/gui/src/solprop_gui/classes/catalog.py index 2e510d9c2..4586d6754 100644 --- a/gui/src/solprop_gui/classes/catalog.py +++ b/gui/src/solprop_gui/classes/catalog.py @@ -66,7 +66,7 @@ ( Field("wavelength_limits", "Wavelengths"), Field("trange", "Time window"), - Field("n_save", "Saved planes"), + Field("n_save", "Saved planes", positions="save_planes"), ), folded=True, ) @@ -187,7 +187,7 @@ ), ), Field("medium.pressure", "Pressure"), - Field("grid.length", "Propagate", moves_planes="settings.save_planes"), + Field("grid.length", "Propagate"), ), ), Section( @@ -233,7 +233,7 @@ Field("grid.wavelength_limits", "Wavelengths"), Field("grid.trange", "Time window"), Field( - "settings.save_planes", "Saved planes", planes_over="grid.length" + "settings.n_save", "Saved planes", positions="settings.save_planes" ), ), folded=True, @@ -300,7 +300,7 @@ ( Field("grid.wavelength_limits", "Wavelengths"), Field("grid.trange", "Time window"), - Field("n_save", "Saved planes"), + Field("n_save", "Saved planes", positions="save_planes"), ), folded=True, ), @@ -359,7 +359,7 @@ ( Field("wavelength_limits", "Wavelengths"), Field("trange", "Time window"), - Field("n_save", "Saved planes"), + Field("n_save", "Saved planes", positions="save_planes"), ), folded=True, ), @@ -411,7 +411,7 @@ ( Field("grid.wavelength_limits", "Wavelengths"), Field("grid.trange", "Time window"), - Field("n_save", "Saved planes"), + Field("n_save", "Saved planes", positions="save_planes"), ), folded=True, ), @@ -447,7 +447,7 @@ also=("responses[*].chi3.gas",), ), Field("medium.pressure", "Pressure"), - Field("grid.length", "Propagate", moves_planes="settings.save_planes"), + Field("grid.length", "Propagate"), ), ), Section( @@ -501,7 +501,7 @@ Field("grid.wavelength_limits", "Wavelengths"), Field("grid.trange", "Time window"), Field( - "settings.save_planes", "Saved planes", planes_over="grid.length" + "settings.n_save", "Saved planes", positions="settings.save_planes" ), ), folded=True, @@ -545,7 +545,7 @@ also=("responses[*].chi3.gas",), ), Field("medium.pressure", "Pressure"), - Field("grid.length", "Propagate", moves_planes="settings.save_planes"), + Field("grid.length", "Propagate"), ), ), Section( @@ -581,7 +581,7 @@ Field("grid.wavelength_limits", "Wavelengths"), Field("grid.trange", "Time window"), Field( - "settings.save_planes", "Saved planes", planes_over="grid.length" + "settings.n_save", "Saved planes", positions="settings.save_planes" ), ), folded=True, @@ -635,7 +635,7 @@ Field("grid.wavelength_limits", "Wavelengths"), Field("grid.trange", "Time window"), Field( - "settings.save_planes", "Saved planes", planes_over="grid.length" + "settings.n_save", "Saved planes", positions="settings.save_planes" ), ), folded=True, diff --git a/gui/src/solprop_gui/classes/problem.py b/gui/src/solprop_gui/classes/problem.py index da2f76b38..0baa03648 100644 --- a/gui/src/solprop_gui/classes/problem.py +++ b/gui/src/solprop_gui/classes/problem.py @@ -25,7 +25,6 @@ "Target", "derived_text", "derived_value", - "even_planes", "field_changes", "field_meta", "field_value", @@ -58,10 +57,9 @@ class Field: negated : bool Whether the row shows the value with its sign changed, as a distance to a focus is the launch's distance from it. - planes_over : str or None - Makes this a count of evenly spaced saved planes, over the length at this path. - moves_planes : str or None - The saved planes at this path, which this length respaces. + positions : str or None + Makes this the saved planes' row (SEP 51): it holds either the count of evenly + spaced planes at its path or the explicit positions at this path, never both. member : str or None Makes this a switch: whether a list at the path holds an entry of this type. goes_with : tuple of str @@ -76,8 +74,7 @@ class Field: choices: str | None = None also: tuple[str, ...] = () negated: bool = False - planes_over: str | None = None - moves_planes: str | None = None + positions: str | None = None member: str | None = None goes_with: tuple[str, ...] = () blank: str | None = None @@ -460,10 +457,18 @@ def sheet_paths(problem: ProblemClass) -> Iterator[str]: ... ) >>> list(sheet_paths(problem)) ['radius', 'length'] + >>> planes = (Field("n_save", positions="save_planes"),) + >>> problem = ProblemClass( + ... "c", "C", "", "gnlse", "soliton", (Section("S", planes),), (), "" + ... ) + >>> list(sheet_paths(problem)) + ['n_save', 'save_planes'] """ for section in problem.sections: for row in section.fields: yield row.path + if row.positions is not None: + yield row.positions def field_meta( @@ -641,35 +646,6 @@ def negated_value(value: object) -> object: return f"{flipped} {unit}".strip() -def even_planes(count: int, length: object) -> list[object]: - """Return evenly spaced saved planes along a length, ending at it. - - Parameters - ---------- - count : int - How many, the entrance not counted. - length : object - The length, a quantity string or a number. - - Returns - ------- - list - The positions, in the length's own unit. - - Examples - -------- - >>> even_planes(2, "25 cm") - ['12.5 cm', '25 cm'] - >>> even_planes(2, 1.0) - [0.5, 1.0] - """ - if isinstance(length, int | float): - return [float(length) * index / count for index in range(1, count + 1)] - number, unit = split(str(length)) - total = float(number) - return [f"{total * index / count:.8g} {unit}" for index in range(1, count + 1)] - - def field_value(row: Field, build: Mapping[str, object]) -> object: """Return what a sheet's row shows of a recipe. @@ -683,13 +659,16 @@ def field_value(row: Field, build: Mapping[str, object]) -> object: Returns ------- object - The value as the row shows it; a switch's is whether its entry is there. + The value as the row shows it; a switch's is whether its entry is there, and + the saved planes' row shows the positions the recipe lists or else its count. Examples -------- >>> build = {"planes": ["1 m", "2 m"], "launch": "-5 cm", "list": [{"type": "A"}]} - >>> field_value(Field("planes", planes_over="length"), build) - 2 + >>> field_value(Field("count", positions="planes"), build) + ['1 m', '2 m'] + >>> field_value(Field("count", positions="planes"), {"count": 81}) + 81 >>> field_value(Field("launch", negated=True), build) '5 cm' >>> field_value(Field("list", member="A"), build) @@ -704,8 +683,9 @@ def field_value(row: Field, build: Mapping[str, object]) -> object: isinstance(entry, Mapping) and entry.get("type") == row.member for entry in entries ) - if row.planes_over is not None: - return len(held) if isinstance(held, Sequence) else MISSING + if row.positions is not None: + listed = _held(build, row.positions) + return held if listed is MISSING else listed return negated_value(held) if row.negated else held @@ -775,8 +755,9 @@ def field_changes( ) -> list[tuple[str, object]]: """Return what a sheet's row changes in a recipe. - The object routes write some values several times, and a run's length as its last - saved plane (#533), so one row can move several paths. + The object routes write some values several times, so one row can move several + paths. The saved planes' row writes a list as the positions and anything else as + the count, and unsets the other in the same change, so a recipe never holds both. Parameters ---------- @@ -802,28 +783,24 @@ def field_changes( >>> build = {"gas": "Ar", "list": [{"gas": "Ar"}], "planes": ["1 m", "2 m"]} >>> field_changes(problem, Field("gas", also=("list[*].gas",)), "He", build) [('gas', 'He'), ('list[0].gas', 'He')] - >>> field_changes(problem, Field("length", moves_planes="planes"), "4 m", build) - [('length', '4 m'), ('planes', ['2 m', '4 m'])] - >>> build["length"] = "6 m" - >>> field_changes(problem, Field("planes", planes_over="length"), 3, build) - [('planes', ['2 m', '4 m', '6 m'])] + >>> planes = Field("count", positions="planes") + >>> field_changes(problem, planes, 81, build) + [('count', 81), ('planes', MISSING)] + >>> field_changes(problem, planes, ["5 cm"], build) + [('planes', ['5 cm']), ('count', MISSING)] >>> field_changes(problem, Field("x", negated=True), "5 cm", build) [('x', '-5 cm')] """ if row.member is not None: return _switched(problem, row, bool(value), build, example or {}) - if row.planes_over is not None: - length = _held(build, row.planes_over) - return [(row.path, even_planes(int(value), length))] # pyright: ignore[reportArgumentType] + if row.positions is not None: + if isinstance(value, list): + return [(row.positions, value), (row.path, MISSING)] + return [(row.path, value), (row.positions, MISSING)] written = negated_value(value) if row.negated else value changes: list[tuple[str, object]] = [(row.path, written)] for pattern in row.also: changes += [(path, written) for path in linked_paths(build, pattern)] - if row.moves_planes is not None and value is not MISSING: - held = _held(build, row.moves_planes) - count = len(held) if isinstance(held, Sequence) else 0 - if count: - changes.append((row.moves_planes, even_planes(count, value))) return changes @@ -859,10 +836,12 @@ def other_keywords( """ # A switch shows one entry of a list: the rest of the list is reachable only there. shown = { - row.path + path for section in problem.sections for row in section.fields if row.member is None + for path in (row.path, row.positions) + if path is not None } entries: Sequence[Mapping[str, object]] = description["parameters"] # pyright: ignore[reportAssignmentType] return [entry for entry in entries if entry.get("name") not in shown] diff --git a/gui/src/solprop_gui/ui/fields.py b/gui/src/solprop_gui/ui/fields.py index 9ce02059f..0b46b67f9 100644 --- a/gui/src/solprop_gui/ui/fields.py +++ b/gui/src/solprop_gui/ui/fields.py @@ -16,11 +16,13 @@ - anything else (a mapping, an array) is a line of inline TOML. Where a keyword takes several forms (a constant pressure or a gradient), a small -picker chooses the form. The launch is a table of modes; a keyword solprop can pin to -a design target offers "pinned" too, whose entry goes in the recipe's ``[pins]`` -table in place of the value. Leaving a field empty, or picking the default, unsets the -keyword so that solprop's default applies and follows solprop's improvements; the -reset button does the same for any form. +picker chooses the form. A sheet's row may name its forms instead (``mode_titles``), +as the saved planes' "Evenly spaced" and "Explicit positions" are: each editor then +shows only a value of its own kind. The launch is a table of modes; a keyword solprop +can pin to a design target offers "pinned" too, whose entry goes in the recipe's +``[pins]`` table in place of the value. Leaving a field empty, or picking the default, +unsets the keyword so that solprop's default applies and follows solprop's +improvements; the reset button does the same for any form. """ from collections.abc import Mapping, Sequence @@ -217,6 +219,8 @@ def __init__( # noqa: PLR0912, PLR0915 - one widget per form self.issue.hide() self.choice_titles: Mapping[str, str] = meta.get("choice_titles") or {} # pyright: ignore[reportAttributeAccessIssue] + self.mode_titles: Mapping[str, str] = meta.get("mode_titles") or {} # pyright: ignore[reportAttributeAccessIssue] + self._text_shown = "" self.modes = modes_of(self.forms, self.catalog, self.name) self.stack = QStackedWidget() self.editors: dict[str, QWidget] = {} @@ -310,7 +314,7 @@ def make_row(child: Mapping[str, object]) -> QWidget: self.mode = QComboBox() self.mode.setObjectName(f"mode-{self.name}") for mode in self.modes: - self.mode.addItem(_MODE_TITLES[mode], mode) + self.mode.addItem(self.mode_titles.get(mode, _MODE_TITLES[mode]), mode) self._update_picker() self.mode.setToolTip("The form of the value.") self.mode.currentIndexChanged.connect(self._mode_changed) @@ -474,6 +478,9 @@ def _fits(self, mode: str, value: object) -> bool: # noqa: PLR0911 - one per ed return any(c == value and type(c) is type(value) for c in self.choices) if mode == "pin": return False + if mode == "text" and self.mode_titles: + # Named forms are separate values: text holds what no other editor does. + return not any(self._fits(m, value) for m in self.modes if m != "text") if mode == "table": return launch_rows(value) is not None if mode == "object": @@ -541,9 +548,14 @@ def _show_mode(self, mode: str) -> None: def _update_picker(self) -> None: """Show the form picker where there is a real choice of form. - On a sheet, free text does not count as one, unless it is what holds the value. + On a sheet, free text does not count as one, unless it is what holds the value + or one of the row's named forms. """ - offered = [m for m in self.modes if m != "text" or not self.on_sheet] + offered = [ + m + for m in self.modes + if m != "text" or not self.on_sheet or self.mode_titles + ] shown = self.modes[self.mode.currentIndex()] if self.mode.count() else "" self.mode.setVisible(len(offered) > 1 or shown == "text") @@ -617,6 +629,8 @@ def _text_finished(self) -> None: if self._updating: return text = self.text.text().strip() + if self.mode_titles and text == self._text_shown: + return # left as shown, so nothing replaces the value another form holds if not text: value: object = MISSING else: @@ -713,11 +727,24 @@ def _show(self, value: object, mode: str) -> None: elif mode == "pin": pass # the pin shows its own entry (set_pin) else: - self.text.setText("" if unset else inline(value)) + blank = unset or not self._fits("text", value) + self._text_shown = "" if blank else inline(value) + self.text.setText(self._text_shown) self.text.setPlaceholderText(self._placeholder()) finally: self._updating = False + @property + def current_mode(self) -> str: + """Return the form whose editor shows, as :func:`modes_of` names it. + + Returns + ------- + str + The form. + """ + return self.modes[self.mode.currentIndex()] + @property def value(self) -> object: """Return the value the row holds. diff --git a/gui/src/solprop_gui/ui/sheet.py b/gui/src/solprop_gui/ui/sheet.py index cc0f795a6..4889a8c28 100644 --- a/gui/src/solprop_gui/ui/sheet.py +++ b/gui/src/solprop_gui/ui/sheet.py @@ -65,6 +65,9 @@ _NARROW = 1000 """Below this width, in pixels, the plot moves below the form.""" +_PLANE_MODES = {"number": "Evenly spaced", "text": "Explicit positions"} +"""The saved planes' two forms (SEP 51): a count of ``n_save``, or ``save_planes``.""" + class TargetEditor(QFrame): """The strip that asks what a derived number should be, and what moves to give it. @@ -507,7 +510,8 @@ def build( if meta is None: continue self._fields[row.path] = row - widget = self._row(self._entry(row, meta), catalog, on_sheet=True) + entry = self._entry(row, meta, description, build) + widget = self._row(entry, catalog, on_sheet=True) if row.blank is not None: for box in widget.findChildren(QLineEdit): if not box.placeholderText(): @@ -668,9 +672,20 @@ def _row_edited(self, path: str, table: str, value: object) -> None: if row is None or table != "build": self.edited.emit(path, table, value) return + widget = self.rows.get((path, table)) + explicit = widget is not None and widget.current_mode == "text" + if row.positions is not None and explicit and value is not MISSING: + # Typed as explicit positions, one value is a list of one (SEP 51). + value = value if isinstance(value, list) else [value] self._move(row, value) - def _entry(self, row: Field, meta: Mapping[str, object]) -> dict[str, object]: + def _entry( + self, + row: Field, + meta: Mapping[str, object], + description: Mapping[str, object], + build: Mapping[str, object], + ) -> dict[str, object]: """Return the metadata of a sheet's row: its path, its label, what it offers. Parameters @@ -679,6 +694,10 @@ def _entry(self, row: Field, meta: Mapping[str, object]) -> dict[str, object]: The sheet's row. meta : Mapping Its keyword's metadata. + description : Mapping + The kernel's description of the route. + build : Mapping + The open recipe's ``[build]`` table. Returns ------- @@ -691,10 +710,13 @@ def _entry(self, row: Field, meta: Mapping[str, object]) -> dict[str, object]: "name": row.path, "label": row.label or label(name), } - if row.planes_over is not None: - entry["forms"] = [{"kind": "integer", "minimum": 1}] - entry["default_value"] = None - entry["default"] = None + positions = None + if row.positions is not None: + positions = field_meta(row.positions, description, build) + if positions is not None: + # The saved planes' explicit positions are a second form beside the count. + entry["forms"] = [*_forms(meta), *_forms(positions)] + entry["mode_titles"] = _PLANE_MODES listed = self._lists.get(row.choices or "") if listed: forms: Sequence[Mapping[str, object]] = meta.get("forms", ()) # pyright: ignore[reportAssignmentType] @@ -1138,8 +1160,7 @@ def show_issues(self, issues: Sequence[Mapping[str, object]]) -> None: """ self._issues = list(issues) for issue in issues: - where = issue.get("parameter") - named = where if isinstance(where, list | tuple) else [where] + named = self._issue_paths(issue) # An issue on an Advanced keyword needs its row made to stand beside it. if ( any(path and (path, "build") not in self.rows for path in named) @@ -1149,9 +1170,7 @@ def show_issues(self, issues: Sequence[Mapping[str, object]]) -> None: for row in self.rows.values(): row.set_issue(None) for issue in issues: - where = issue.get("parameter") - paths = where if isinstance(where, list | tuple) else [where] - for path in paths: + for path in self._issue_paths(issue): keyword = issue_keyword(path)[0] if path else None for (name, _), row in self.rows.items(): if name in (path, keyword): @@ -1174,6 +1193,26 @@ def show_issues(self, issues: Sequence[Mapping[str, object]]) -> None: self.ready.setProperty("warn", bool(warnings) and not errors) repolish(self.ready) + def _issue_paths(self, issue: Mapping[str, object]) -> list[object]: + """Return the paths an issue names, as the sheet's rows are named. + + The saved planes' positions are shown in the row of their count. + + Parameters + ---------- + issue : Mapping + The issue. + + Returns + ------- + list + Its paths; ``None`` where it names none. + """ + where = issue.get("parameter") + paths = where if isinstance(where, list | tuple) else [where] + aliases = {f.positions: f.path for f in self._fields.values() if f.positions} + return [aliases.get(str(path), path) for path in paths] + def _show_ready(self) -> None: """Write the Ready line: solprop's verdict, and the run's size where known.""" parts = [self._verdict] diff --git a/gui/tests/test_classes.py b/gui/tests/test_classes.py index c724a2fa5..58f732866 100644 --- a/gui/tests/test_classes.py +++ b/gui/tests/test_classes.py @@ -9,8 +9,10 @@ from pathlib import Path from typing import Any +import numpy as np import pytest from solprop.recipe import Recipe +from solprop.recipe.paths import set_path from solprop.service.handlers import HANDLERS, describe, describe_output from solprop.stats import CATALOGUE @@ -30,7 +32,6 @@ Target, derived_text, derived_value, - even_planes, field_changes, field_meta, field_value, @@ -202,9 +203,8 @@ def test_every_link_of_a_class_is_in_its_example() -> None: for row in section.fields: for pattern in row.also: assert linked_paths(build, pattern), (problem.key, pattern) - for path in (row.planes_over, row.moves_planes, *row.goes_with): - if path is not None: - assert linked_paths(build, path), (problem.key, path) + for path in row.goes_with: + assert linked_paths(build, path), (problem.key, path) def test_a_switch_takes_an_entry_out_and_brings_it_back_with_today_s_gas() -> None: @@ -248,18 +248,106 @@ def test_the_filament_s_linked_rows_write_a_recipe_solprop_builds() -> None: "responses[1].gas", "responses[1].rate.source", } + assert negated_value(True) is True + + +def _planes_row(problem: ProblemClass) -> Field: + return next( + row + for section in problem.sections + for row in section.fields + if row.positions is not None + ) + + +def _applied( + build: dict[str, Any], changes: list[tuple[str, object]] +) -> dict[str, Any]: + for path, value in changes: + if value is MISSING: + head, _, name = path.rpartition(".") + (build[head] if head else build).pop(name, None) + else: + build = set_path(build, path, value) + return build + + +@pytest.mark.parametrize("problem", CLASSES, ids=lambda p: p.key) +def test_every_class_offers_both_forms_of_the_saved_planes( + problem: ProblemClass, +) -> None: + # SEP 51: the count and the explicit positions, at the route's level. + row = _planes_row(problem) + nested = "settings." if row.path.startswith("settings.") else "" + assert (row.path, row.positions) == (f"{nested}n_save", f"{nested}save_planes") + + +def test_a_loaded_list_is_shown_as_the_list_and_never_as_its_count() -> None: + row = _planes_row(FILAMENT) + example: Any = Recipe.example("filament").to_dict()["build"] + uniform = example["settings"]["save_planes"] + assert len(uniform) > 2 + assert field_value(row, example) == uniform + uneven = {"settings": {"save_planes": ["1 cm", "4 cm", "4.5 cm"]}} + assert field_value(row, uneven) == ["1 cm", "4 cm", "4.5 cm"] + assert field_value(row, {"settings": {"save_planes": []}}) == [] + assert field_value(row, {"settings": {"n_save": 81}}) == 81 + assert field_value(row, {}) is MISSING + + +def test_each_form_of_the_saved_planes_replaces_the_other() -> None: + row = _planes_row(FILAMENT) + build: dict[str, Any] = Recipe.example("filament").to_dict()["build"] + count = field_changes(FILAMENT, row, 81, build) + assert count == [("settings.n_save", 81), ("settings.save_planes", MISSING)] + build = _applied(build, count) + assert build["settings"]["n_save"] == 81 + assert "save_planes" not in build["settings"] + listed = field_changes(FILAMENT, row, ["5 cm", "8 cm"], build) + assert listed == [ + ("settings.save_planes", ["5 cm", "8 cm"]), + ("settings.n_save", MISSING), + ] + build = _applied(build, listed) + assert "n_save" not in build["settings"] + # Unset, neither is held, and the route's default count applies. + cleared = field_changes(FILAMENT, row, MISSING, build) + assert dict(cleared) == { + "settings.n_save": MISSING, + "settings.save_planes": MISSING, + } + + +def test_a_length_moves_the_length_alone() -> None: + # A count follows the length by itself; explicit positions stay as entered. + length = FILAMENT.sections[0].fields[2] + assert length.path == "grid.length" + build = Recipe.example("filament").to_dict()["build"] + assert field_changes(FILAMENT, length, "20 cm", build) == [("grid.length", "20 cm")] + + +def test_solprop_takes_a_count_and_refuses_a_position_beyond_a_shortened_length() -> ( + None +): + row = _planes_row(FILAMENT) length = FILAMENT.sections[0].fields[2] - moved: dict[str, Any] = dict(field_changes(FILAMENT, length, "20 cm", build)) - assert moved["settings.save_planes"][-1] == "20 cm" - assert len(moved["settings.save_planes"]) == 80 - assert field_changes(FILAMENT, length, MISSING, build) == [("grid.length", MISSING)] - assert field_changes(FILAMENT, length, "20 cm", {"grid": {"length": "25 cm"}}) == [ - ("grid.length", "20 cm") + document: Any = Recipe.example("filament").to_dict() + build = document["build"] + build = _applied(build, field_changes(FILAMENT, row, 11, build)) + build = _applied(build, field_changes(FILAMENT, length, "10 cm", build)) + simulation = Recipe.from_dict({**document, "build": build}).build() + planes = np.asarray(simulation.settings.save_planes) + # Eleven observations over [0, 10 cm], so ten planes after the entrance. + assert planes.shape == (10,) + # The end is the length: one rounding of "10 cm" to metres at most. + assert planes[-1] == pytest.approx(0.1, rel=1e-15) + build = _applied(build, field_changes(FILAMENT, row, ["5 cm", "12 cm"], build)) + errors = [ + issue + for issue in Recipe.from_dict({**document, "build": build}).check() + if issue.severity == "error" ] - planes = Field("settings.save_planes", planes_over="grid.length") - assert field_value(planes, {}) is MISSING - assert negated_value(True) is True - assert even_planes(2, 4.0) == [2.0, 4.0] + assert [issue.parameter for issue in errors] == ["settings.save_planes"] def test_other_geometry_s_form_comes_from_the_metadata() -> None: diff --git a/gui/tests/test_ui_workflow.py b/gui/tests/test_ui_workflow.py index d2c2e8463..e499b9be3 100644 --- a/gui/tests/test_ui_workflow.py +++ b/gui/tests/test_ui_workflow.py @@ -740,12 +740,21 @@ def test_the_filament_s_sheet_links_its_rows( # noqa: PLR0915 - one story assert model.get("settings.ionisation_field_range") is MISSING plasma.click() assert len(model.get("responses")) == 2 # pyright: ignore[reportArgumentType] - planes = sheet.rows["settings.save_planes", "build"].number.number - planes.setText("10") - planes.textEdited.emit("10") - held = model.get("settings.save_planes") - assert isinstance(held, list) - assert len(held) == 10 + # The example lists its planes, so they open as explicit positions, unchanged. + planes = sheet.rows["settings.n_save", "build"] + listed = model.get("settings.save_planes") + assert isinstance(listed, list) + assert planes.current_mode == "text" + assert planes.mode.currentText() == "Explicit positions" + assert planes.value == listed + planes.mode.setCurrentIndex(planes.modes.index("number")) + planes.number.number.setText("10") + planes.number.number.textEdited.emit("10") + assert model.get("settings.n_save") == 10 + assert model.get("settings.save_planes") is MISSING + window.document.undo.undo() + assert model.get("settings.save_planes") == listed + assert model.get("settings.n_save") is MISSING sheet.apply_lens(50e-6, 0.1) assert str(model.get("initial.waist")).endswith("um") assert str(model.get("initial.propz")).startswith("-") @@ -764,6 +773,95 @@ def test_the_filament_s_sheet_links_its_rows( # noqa: PLR0915 - one story window.document.undo.undo() +def _planes_held(model: RecipeModel) -> tuple[object, object]: + """Return the count and the positions a keyword route's recipe holds.""" + return model.get("n_save"), model.get("save_planes") + + +def test_the_saved_planes_are_a_count_or_positions_never_both( # noqa: PLR0915 - one story + window: WorkflowWindow, qtbot: QtBot, tmp_path: Path +) -> None: + open_tiny(window, qtbot) + sheet = window.sheet + model = window.document.model + assert model is not None + row = sheet.rows["n_save", "build"] + assert ("save_planes", "build") not in sheet.rows + assert row.current_mode == "number" + assert not row.mode.isHidden() + assert [row.mode.itemText(i) for i in range(row.mode.count())] == [ + "Evenly spaced", + "Explicit positions", + ] + assert row.number.number.text() == "6" + # A length change leaves the count to spread itself. + sheet.rows["length", "build"].edited.emit("length", "build", "4 cm") + assert _planes_held(model) == (6, MISSING) + window.document.undo.undo() + # Switching shows the other editor, empty: a count is never shown as positions. + row.mode.setCurrentIndex(row.modes.index("text")) + assert row.text.text() == "" + row.text.editingFinished.emit() + assert _planes_held(model) == (6, MISSING) + # The first entry in the new form replaces the count, in one undoable edit. + done = window.document.undo.index() + row.text.setText('["1 cm", "4 cm"]') + row.text.editingFinished.emit() + assert _planes_held(model) == (MISSING, ["1 cm", "4 cm"]) + assert window.document.undo.index() == done + 1 + window.document.undo.undo() + assert _planes_held(model) == (6, MISSING) + assert row.current_mode == "number" + window.document.undo.redo() + assert _planes_held(model) == (MISSING, ["1 cm", "4 cm"]) + assert row.current_mode == "text" + # One position typed is a list of one. + row.text.setText('"2 cm"') + row.text.editingFinished.emit() + assert _planes_held(model) == (MISSING, ["2 cm"]) + row.text.setText('["1 cm", "4 cm"]') + row.text.editingFinished.emit() + # Explicit positions stay as entered; one beyond a shorter length is refused there. + sheet.rows["length", "build"].edited.emit("length", "build", "3 cm") + assert _planes_held(model) == (MISSING, ["1 cm", "4 cm"]) + qtbot.waitUntil(lambda: not row.issue.isHidden(), timeout=WAIT_MS) + assert "length" in row.issue.text() + assert sheet.ready.text().startswith("Not ready") + sheet.rows["length", "build"].edited.emit("length", "build", "5 cm") + qtbot.waitUntil(row.issue.isHidden, timeout=WAIT_MS) + # Saved and opened again, the setup opens on the form it holds. + path = tmp_path / "planes.toml" + assert window.document.save_as(path) + assert "n_save" not in path.read_text(encoding="utf-8") + window.document.set_model(RecipeModel(TINY), base=None) + qtbot.waitUntil(lambda: sheet.rows["n_save", "build"].value == 6, timeout=WAIT_MS) + window.open_setup(str(path)) + qtbot.waitUntil( + lambda: sheet.rows["n_save", "build"].current_mode == "text", timeout=WAIT_MS + ) + reopened = window.document.model + assert reopened is not None + assert _planes_held(reopened) == (MISSING, ["1 cm", "4 cm"]) + assert sheet.rows["n_save", "build"].text.text() == '["1 cm", "4 cm"]' + # Back to a count: one edit takes the positions away. + row = sheet.rows["n_save", "build"] + row.mode.setCurrentIndex(row.modes.index("number")) + assert row.number.number.text() == "" + row.number.number.setText("9") + row.number.number.textEdited.emit("9") + assert _planes_held(reopened) == (9, MISSING) + + +def test_an_uneven_list_opens_as_itself(window: WorkflowWindow, qtbot: QtBot) -> None: + text = TINY.replace("n_save = 6", 'save_planes = ["1 cm", "1.5 cm", "4 cm"]') + window.document.set_model(RecipeModel(text), base=None) + qtbot.waitUntil(lambda: bool(window.sheet.rows), timeout=WAIT_MS) + row = window.sheet.rows["n_save", "build"] + qtbot.waitUntil(lambda: row.current_mode == "text", timeout=WAIT_MS) + assert row.value == ["1 cm", "1.5 cm", "4 cm"] + assert row.number.number.text() == "" + + def test_every_page_of_a_filament_shows_it( # noqa: PLR0915 - one story window: WorkflowWindow, qtbot: QtBot, filament_run: Path, tmp_path: Path ) -> None: diff --git a/native/tests/test_general_modal.py b/native/tests/test_general_modal.py index 65831772c..ca0797f60 100644 --- a/native/tests/test_general_modal.py +++ b/native/tests/test_general_modal.py @@ -188,11 +188,13 @@ def _case( ) -> Case: with warnings.catch_warnings(): warnings.simplefilter("ignore", GeneralModalBasisWarning) + # The run ends at its grid's length (SEP 51): the millimetre grid cut at the + # ten-step window, whose collar is removed below. simulation = Simulation.from_waveguide( (), - FIBRE, + Z_END, provider=guide, - grid=grid, + grid=dataclasses.replace(grid, length=Z_END), backend="numpy_ref", kerr_form=kerr_form, save_planes=[Z_END], diff --git a/src/solprop/capabilities.py b/src/solprop/capabilities.py index b0b379c96..b07e8fa9a 100644 --- a/src/solprop/capabilities.py +++ b/src/solprop/capabilities.py @@ -330,6 +330,7 @@ class Rule: _CAPILLARY: Final = ("capillary",) _WAVEGUIDE: Final = ("waveguide",) _MODAL: Final = ("capillary", "waveguide") +_KEYWORD: Final = ("gnlse", "capillary", "waveguide") _RULES: Final = ( # The grid, the input pulse and the saved planes, on both routes. @@ -391,6 +392,36 @@ class Rule: "The saved planes are given as positions or as a count, not both.", _BOTH, ), + Rule( + "save-planes-count", + ("save_planes",), + "save_planes takes positions in m; a count of evenly spaced planes is n_save.", + _KEYWORD, + ), + Rule( + "save-planes-outside", + ("save_planes",), + "Every saved plane lies inside the run, from its entrance to its length.", + _KEYWORD, + ), + Rule( + "length-or-grid", + ("length", "grid"), + "A run's length is given as length or as its grid's; one of them is needed.", + _KEYWORD, + ), + Rule( + "length-grid", + ("length", "grid"), + "A length given beside a grid agrees with the grid's length.", + _KEYWORD, + ), + Rule( + "replay-interval", + ("schedule",), + "A replayed schedule covers the run, from its entrance to its length.", + _KEYWORD, + ), Rule( "fields-planes-step-planes", ("fields", "step_planes"), diff --git a/src/solprop/driver/_scan_run.py b/src/solprop/driver/_scan_run.py index 108a57db2..384843812 100644 --- a/src/solprop/driver/_scan_run.py +++ b/src/solprop/driver/_scan_run.py @@ -161,7 +161,7 @@ def __init__( """Initialize the declared scan component.""" super().__init__(block=1) self.options = options - self.count = len(simulation.settings.save_planes) + 1 + self.count = len(np.asarray(simulation.settings.save_planes)) + 1 problem = simulation.translate() self._field_shape = tuple(problem.shape) self.selected = ( @@ -598,7 +598,7 @@ def _output_bytes( - ``statistics``: one plane of statistics with resolved species and mode axes. - Returns: retained array bytes; adaptive periodic rows use the memory headroom. """ - count = len(simulation.settings.save_planes) + 1 + count = len(np.asarray(simulation.settings.save_planes)) + 1 selected = ( count if self.options.fields == "all" diff --git a/src/solprop/driver/inputs.py b/src/solprop/driver/inputs.py index 05093d9ec..296c789b0 100644 --- a/src/solprop/driver/inputs.py +++ b/src/solprop/driver/inputs.py @@ -117,17 +117,11 @@ def _check_initial_position( """Validate an absolute launch before translation can normalize its field. - ``simulation``: declared optical input, grid and absolute launch position in m. + + The position itself, finite, nonnegative and before the end, with every plane + after it, is already checked where the settings were adopted (SEP 51). """ z = simulation.initial_z - if ( - not np.isfinite(z) - or z < 0 - or z >= simulation.grid.length - or np.any(np.asarray(settings.save_planes) <= z) - ): - raise DriverError( - "initial_z must be finite, nonnegative and before every save plane" - ) if z == 0: return if ( diff --git a/src/solprop/driver/interface.py b/src/solprop/driver/interface.py index 7a58dfd52..54035f410 100644 --- a/src/solprop/driver/interface.py +++ b/src/solprop/driver/interface.py @@ -184,7 +184,7 @@ def _propagate(build: Callable[..., Simulation], scope: Mapping[str, object]) -> "%s: %d modes, %d save planes, %r backend", build.__name__, len(simulation.modes), - len(simulation.settings.save_planes), + len(np.asarray(simulation.settings.save_planes)), simulation.settings.backend, ) # Each control is the type Simulation.run declares: prop_* declares it the same. @@ -275,7 +275,7 @@ def prop_planar( # numpydoc ignore=PR01 @_propagates(Simulation.from_gnlse) def prop_gnlse( # numpydoc ignore=PR01 gamma: float | None, - length: float, + length: float | None = None, betas: Sequence[float] | np.ndarray | None = None, *, wavelength: float, @@ -389,8 +389,8 @@ def prop_gnlse( # numpydoc ignore=PR01 @_propagates(Simulation.from_capillary) def prop_capillary( # numpydoc ignore=PR01 radius: float | ZProfile, - length: float, - gas: Gas | str | Mapping[str, float] | Mixture, + length: float | None = None, + gas: Gas | str | Mapping[str, float] | Mixture | None = None, pressure: Pressure | None = None, *, pressure_floor: float | None = None, @@ -531,7 +531,7 @@ def prop_capillary( # numpydoc ignore=PR01 @_propagates(Simulation.from_waveguide) def prop_waveguide( # numpydoc ignore=PR01 modes: Sequence[Mode], - length: float, + length: float | None = None, gas: Gas | str | Mapping[str, float] | Mixture | None = None, pressure: Pressure | None = None, *, diff --git a/src/solprop/driver/routes/general.py b/src/solprop/driver/routes/general.py index fe0b03e8b..a451b63d7 100644 --- a/src/solprop/driver/routes/general.py +++ b/src/solprop/driver/routes/general.py @@ -29,7 +29,6 @@ from solprop.driver.settings import ( NoiseSetting, _boundary, - _save_planes, keyword_settings, ) from solprop.exceptions import DriverError, TranslationError @@ -182,7 +181,6 @@ def _from_general(cls: type["Simulation"], request: _GeneralRequest) -> "Simulat "provider.mode_collection.modes" ) raise DriverError(msg) - planes = _save_planes(request.length, request.save_planes, request.n_save) refuse_beside( request.launch, channel=request.channel, @@ -208,7 +206,8 @@ def _from_general(cls: type["Simulation"], request: _GeneralRequest) -> "Simulat route = general_modal_route( provider, working, - z_max=float(np.max(planes)), + # The run ends at its length (SEP 51), so the tables cover the grid's. + z_max=float(working.length), omega_reference=float(working.omega0), kerr_form=request.kerr_form, selection=MaterialSelection() @@ -266,7 +265,8 @@ def _from_general(cls: type["Simulation"], request: _GeneralRequest) -> "Simulat atol=request.atol, dz_max=request.dz_max, dz_init=request.dz_init, - save_planes=planes, + save_planes=request.save_planes, + n_save=request.n_save, schedule=request.schedule, integrator=request.integrator, interpolate_planes=request.interpolate_planes, diff --git a/src/solprop/driver/routes/hollow.py b/src/solprop/driver/routes/hollow.py index f4acd9aa7..cfaebc099 100644 --- a/src/solprop/driver/routes/hollow.py +++ b/src/solprop/driver/routes/hollow.py @@ -47,7 +47,6 @@ from solprop.driver.settings import ( NoiseSetting, _boundary, - _save_planes, keyword_settings, ) from solprop.driver.tdse_run import _entry_overrides, _tdse_entry, _tdse_stats @@ -697,7 +696,8 @@ def _from_hollow( # noqa: PLR0915 - the route's whole build, keyword by keyword atol=request.atol, dz_max=request.dz_max, dz_init=request.dz_init, - save_planes=_save_planes(request.length, request.save_planes, n_save), + save_planes=request.save_planes, + n_save=n_save, schedule=request.schedule, integrator=request.integrator, interpolate_planes=request.interpolate_planes, diff --git a/src/solprop/driver/scaffold.py b/src/solprop/driver/scaffold.py index 79de04647..71c8cc03e 100644 --- a/src/solprop/driver/scaffold.py +++ b/src/solprop/driver/scaffold.py @@ -128,7 +128,7 @@ def propagate_fixed_rk4( z_end: float, n_steps: int, *, - n_save: int = 1, + n_save: int = 2, ) -> tuple[Float[np.ndarray, " n_z"], Complex[np.ndarray, "n_z n_omega"]]: """Propagate a mode-averaged envelope spectrum with fixed-step IP-RK4. @@ -160,15 +160,17 @@ def propagate_fixed_rk4( z_end : float Propagation length, m, positive. n_steps : int - Number of equal steps, at least 1 and a multiple of ``n_save``. + Number of equal steps, at least 1 and a multiple of ``n_save - 1``. n_save : int, optional - Number of planes to save after ``z = 0``, at least 1. Default 1: the end only. + Number of evenly spaced planes to save over ``[0, z_end]``, both ends included, + as on every :class:`~solprop.driver.simulation.Simulation` route; at least 2. + Default 2: the entrance and the end. Returns ------- tuple - ``(z, spectra)``: the saved positions, shape ``(n_save + 1,)``, m, starting at - zero; and the stored spectra there, shape ``(n_save + 1, n_omega)``. + ``(z, spectra)``: the saved positions, shape ``(n_save,)``, m, from zero to + ``z_end``; and the stored spectra there, shape ``(n_save, n_omega)``. Raises ------ @@ -176,8 +178,8 @@ def propagate_fixed_rk4( If the grid is not an envelope grid, or the spectrum does not match it. StepperError If the fibre varies along z, ``z_end`` is not positive and finite, - ``n_steps`` or ``n_save`` is below 1, or ``n_steps`` is not a multiple of - ``n_save``. + ``n_steps`` is below 1, ``n_save`` is below 2, or ``n_steps`` is not a + multiple of ``n_save - 1``. Examples -------- @@ -221,19 +223,26 @@ def propagate_fixed_rk4( if n_steps < 1: msg = f"n_steps must be at least 1, got {n_steps!r}" raise StepperError(msg) - if n_save < 1: - msg = f"n_save must be at least 1, got {n_save!r}" + if n_save < 2: + msg = ( + "n_save counts the saved planes, both ends included, so it must be at " + f"least 2, got {n_save!r}" + ) raise StepperError(msg) - if n_steps % n_save: - msg = f"n_steps ({n_steps}) must be a multiple of n_save ({n_save})" + intervals = n_save - 1 + if n_steps % intervals: + msg = ( + f"n_steps ({n_steps}) must be a multiple of n_save - 1 ({intervals}), the " + "number of intervals between saved planes" + ) raise StepperError(msg) operator = dispersion_operator(problem.mode, grid, Frame.comoving(grid)) step = z_end / n_steps half = np.exp(0.5 * step * operator) - per_save = n_steps // n_save + per_save = n_steps // intervals state = values * grid.active_mask - saved = np.empty((n_save + 1, grid.n_omega), dtype=np.complex128) + saved = np.empty((n_save, grid.n_omega), dtype=np.complex128) saved[0] = state logger.debug( "scaffold IP-RK4: %d steps of %.6e m over %.6e m, saving %d planes", @@ -252,4 +261,4 @@ def propagate_fixed_rk4( state = state + step / 6.0 * k4 if (index + 1) % per_save == 0: saved[(index + 1) // per_save] = state - return np.linspace(0.0, z_end, n_save + 1), saved + return np.linspace(0.0, z_end, n_save), saved diff --git a/src/solprop/driver/settings.py b/src/solprop/driver/settings.py index 41bb6cf3b..3d4f8f2ff 100644 --- a/src/solprop/driver/settings.py +++ b/src/solprop/driver/settings.py @@ -10,6 +10,8 @@ """ import dataclasses +import math +import numbers import warnings from collections.abc import Callable, Sequence from dataclasses import dataclass @@ -17,6 +19,7 @@ import numpy as np from jaxtyping import Float +from numpy.typing import ArrayLike from solprop._display import Displayed, engineering, line, summarise from solprop._ownership import frozen_copy @@ -45,7 +48,7 @@ from solprop.stepper.low_storage import LowStorageRungeKutta from solprop.stepper.multistep import Multistep from solprop.stepper.runge_kutta import RungeKutta -from solprop.stepper.schedule import FixedSchedule +from solprop.stepper.schedule import LANDING_ULPS, FixedSchedule, replay_tolerance from solprop.translate.masks import AbsorberScheme from solprop.translate.problem import PropagatorMode @@ -68,7 +71,11 @@ """ DEFAULT_N_SAVE = 201 -"""Planes a GNLSE run stores, counting the one at ``z = 0``.""" +"""Observations a run records when given neither ``n_save`` nor ``save_planes``. + +Evenly spaced over the run's interval ``[initial_z, length]``, both ends included +(SEP 51). The TDSE capillary's route default is two instead. +""" _RECIPE_EXECUTION = ("fields", "field_planes", "resume_history") """The settings a recipe's ``[execution]`` table holds: a change of any other one drops @@ -150,11 +157,22 @@ class SimulationSettings(Displayed): grid. An explicit controller always wins, and settings that already belong to a route keep its default. The other fields are keyword-only. - save_planes : numpy.ndarray - Positions to save at, m, increasing and positive, shape ``(n_z,)``. The plane at - ``z = 0`` is saved as well and is not listed here. A sequence is adopted as a - read-only float64 array, so that two runs specified the same way record the same - planes whichever type they passed and therefore hash alike. + save_planes : numpy.ndarray or None + Positions to record the run at, m, finite and strictly increasing, inside the + run's interval ``[initial_z, length]``, where ``length`` is the grid's + (SEP 51). The entrance and the end are recorded anyway and are added when + absent; either may be listed and is kept once, a position within + :data:`~solprop.stepper.schedule.LANDING_ULPS` ulps of an endpoint being that + endpoint. An empty list records the two endpoints alone. A sequence is adopted + as a read-only float64 array, so that two runs specified the same way record + the same planes whichever type they passed and therefore hash alike. Give this + or `n_save`, not both; given neither, the run records + :data:`DEFAULT_N_SAVE`. A simulation holds its settings *resolved*: the + positions after its entrance, the last exactly its length, and `n_save` + ``None``. + n_save : int or None + How many evenly spaced observations to record over ``[initial_z, length]``, + both ends included: an integer of at least 2. Give this or `save_planes`. dz_max : float Cap on the controller's proposal, m. dz_init : float @@ -325,9 +343,11 @@ class SimulationSettings(Displayed): Raises ------ DriverError - If the save planes are empty, not increasing, or not positive. The same check - runs again in :func:`solprop.translate.assembly.assemble`; here it fires before - a run has built anything. Also if the field retention is not valid, asks for + If `save_planes` is a bare number, holds a position that is not finite or + does not increase strictly, or is given beside `n_save`, or if `n_save` is not + an integer of at least 2; each message names the fix. Positions outside the + run's interval are refused when a simulation adopts the settings, where the + interval is known. Also if the field retention is not valid, asks for ``fields='planes'`` beside `step_planes`. Examples @@ -345,7 +365,10 @@ class SimulationSettings(Displayed): controller: PIController | None = None _: dataclasses.KW_ONLY - save_planes: Float[np.ndarray, " n_z"] | Sequence[float] + # A bare number is admitted by the annotation so that it is refused by name, with + # the fix, rather than by the run-time type check. + save_planes: Float[np.ndarray, " n_z"] | Sequence[float] | float | None = None + n_save: int | SupportsIndex | float | None = None dz_max: float dz_init: float dz_min: float | None = None @@ -401,6 +424,9 @@ class SimulationSettings(Displayed): def _planes_text(self) -> str: """Return the save planes summarised, for printing.""" + if self.save_planes is None: + count = DEFAULT_N_SAVE if self.n_save is None else self.n_save + return f"{count} planes" + ("" if self.n_save else " (default)") planes = np.asarray(self.save_planes, dtype=float) return summarise(planes, "m").replace("values", "planes") @@ -475,27 +501,17 @@ def _describe(self) -> tuple[str, list[tuple[str, object]]]: ] def __post_init__(self) -> None: - """Adopt a read-only plane array and check it. + """Adopt a read-only plane array and check the selectors. Raises ------ DriverError - If the planes are empty, not increasing, or not positive, or if + If the plane selectors are malformed (:func:`_selectors`), or if `resume_history` is not a boolean or ``None``. """ - planes = frozen_copy(np.reshape(self.save_planes, -1), np.float64) - if ( - planes.size == 0 - or not np.all(np.isfinite(planes)) - or not np.all(np.diff(planes) > 0.0) - or planes[0] <= 0.0 - ): - msg = ( - f"save_planes must be positive and increasing, got {planes}; the plane " - "at z = 0 is saved anyway and is not one of them" - ) - raise DriverError(msg, parameter="save_planes") + planes, count = _selectors(self.save_planes, self.n_save) object.__setattr__(self, "save_planes", planes) + object.__setattr__(self, "n_save", count) refusal = field_retention_refusal(self.fields, self.field_planes) if refusal is not None: raise DriverError(refusal, parameter=("fields", "field_planes")) @@ -912,32 +928,204 @@ def _same_setting(old: object, new: object) -> bool: return False -def _save_planes( - length: float, - save_planes: Sequence[float] | np.ndarray | None, +_BOTH_SELECTORS = ( + "give one of n_save and save_planes, not both; to carry a count to settings that " + "hold positions, pass dataclasses.replace(settings, n_save=N, save_planes=None)" +) + + +def _selectors( + save_planes: object, n_save: object +) -> tuple[Float[np.ndarray, " n_z"] | None, int | None]: + """Return the plane selectors as settings hold them, refusing a malformed one. + + The checks that need no interval (SEP 51 section 5.5): a bare number, a position + that is not finite or does not increase strictly, both selectors, and a count that + is not an integer of at least 2. Positions are a read-only float64 array, m. + """ + if save_planes is not None and n_save is not None: + raise DriverError( + _BOTH_SELECTORS, + parameter=("save_planes", "n_save"), + rule="save-planes-or-n-save", + ) + count = None + if n_save is not None: + if isinstance(n_save, bool) or not isinstance(n_save, numbers.Integral): + msg = f"n_save is an integer of at least 2, got {n_save!r}" + raise DriverError(msg, parameter="n_save") + count = int(n_save) + if count < 2: + msg = ( + f"n_save is an integer of at least 2, got {count}: it counts the " + "entrance and the end, which a run always records" + ) + raise DriverError(msg, parameter="n_save") + if save_planes is None: + return None, count + if isinstance(save_planes, bool): + msg = f"save_planes takes positions in m, got {save_planes!r}" + raise DriverError(msg, parameter="save_planes") + if isinstance(save_planes, numbers.Integral): + msg = ( + f"save_planes={save_planes!r} reads as one position in m, not a count; for " + f"evenly spaced planes pass n_save={save_planes!r}" + ) + raise DriverError(msg, parameter="save_planes", rule="save-planes-count") + given = cast("ArrayLike", save_planes) + if isinstance(save_planes, numbers.Real) or np.ndim(given) == 0: + msg = ( + f"save_planes={save_planes!r} is a single position; pass " + f"[{save_planes!r}], or n_save for evenly spaced planes" + ) + raise DriverError(msg, parameter="save_planes") + planes = frozen_copy(np.reshape(given, -1), np.float64) + for index, position in enumerate(planes.tolist()): + if not math.isfinite(position): + msg = f"save plane {position!r} is not finite" + raise DriverError(msg, parameter="save_planes") + previous = float(planes[index - 1]) + if index and position <= previous: + relation = "repeats" if position == previous else "follows" + msg = ( + f"save plane {position!r} m {relation} {previous!r} m; the positions " + "must increase strictly" + ) + raise DriverError(msg, parameter="save_planes") + return planes, count + + +def _at(position: float, endpoint: float) -> bool: + """Return whether a position is an endpoint, within the marches' landing slack. + + :data:`~solprop.stepper.schedule.LANDING_ULPS` ulps of the endpoint itself, the + slack a march lands on a target with (SEP 51 section 5.4). + """ + return bool(abs(position - endpoint) <= LANDING_ULPS * math.ulp(endpoint)) + + +def _observation_planes( + save_planes: Float[np.ndarray, " _"] | None, n_save: int | None, + *, + entrance: float, + length: float, + default: int | None = None, ) -> Float[np.ndarray, " n_z"]: - """Return the save planes a keyword interface asks for. - - - ``length``: fibre length, m. - - ``save_planes``: positions given by the caller, m. - - Returns: the planes after ``z = 0``, m, shape ``(n_z,)``. + """Return the positions a run records after its entrance, the last exactly `length`. + + The one placement rule of SEP 51, for selectors :func:`_selectors` admitted: a + count places that many observations evenly over ``[entrance, length]``, both + included; positions within :data:`~solprop.stepper.schedule.LANDING_ULPS` ulps of + an endpoint become it, each endpoint is kept once, the end is added when absent and + a position outside the interval is refused; neither selector takes `default`, + :data:`DEFAULT_N_SAVE` unless given. + Resolving the result again against the same interval returns it unchanged. + Positions in m; `entrance` before `length`. """ - if save_planes is not None: - if n_save is not None: - msg = "give save_planes or n_save, not both" - raise DriverError( - msg, parameter=("save_planes", "n_save"), rule="save-planes-or-n-save" + if save_planes is None: + count = n_save or (DEFAULT_N_SAVE if default is None else default) + # linspace's last value is exactly `length`. + return frozen_copy(np.linspace(entrance, length, count)[1:], np.float64) + planes = np.array(save_planes, dtype=np.float64) + for index, position in enumerate(planes): + if _at(position, length): + planes[index] = length + elif _at(position, entrance): + planes[index] = entrance + elif position < entrance: + msg = ( + f"save plane {position:g} m lies before the entrance, initial_z = " + f"{entrance:g} m; the run records [{entrance:g} m, {length:g} m]" + ) + raise DriverError(msg, parameter="save_planes", rule="save-planes-outside") + elif position > length: + msg = ( + f"save plane {position:g} m lies beyond the end of the run, " + f"grid.length = {length:g} m; the run records [{entrance:g} m, " + f"{length:g} m]: raise length (or grid.length), or drop the plane" ) - return np.ascontiguousarray(save_planes, dtype=np.float64).reshape(-1) - count = DEFAULT_N_SAVE if n_save is None else n_save - if count < 2: + raise DriverError(msg, parameter="save_planes", rule="save-planes-outside") + # Normalization can only merge an endpoint with a listed neighbour. + interior = np.unique(planes[(planes > entrance) & (planes < length)]) + return frozen_copy(np.append(interior, length), np.float64) + + +def _run_length(length: float | None, grid: TimeGrid | None) -> float: + """Return a keyword route's one length, m, from `length`, `grid` or both (SEP 51). + + Given both, they must agree within :data:`~solprop.stepper.schedule.LANDING_ULPS` + ulps of ``grid.length``, which is then the canonical value; a supplied grid is never + rebuilt, and a conflict is never settled silently. + """ + if grid is None: + if length is None: + msg = "a length or a grid is required: pass length=, or grid=" + raise DriverError(msg, parameter=("length", "grid"), rule="length-or-grid") + return length + if length is not None and not _at(length, float(grid.length)): + msg = ( + f"length = {length!r} m and grid.length = {grid.length!r} m disagree: the " + "run ends at its one length, so give one of them, or make them agree" + ) + raise DriverError(msg, parameter=("length", "grid"), rule="length-grid") + return float(grid.length) + + +def _replay_refusal( + schedule: FixedSchedule, entrance: float, length: float +) -> str | None: + """Return why a replayed schedule does not cover a run's interval, or ``None``. + + Its start agrees with the entrance under the endpoint rule, and its end with the + length within :func:`~solprop.stepper.schedule.replay_tolerance`, which allows the + rounding its step sum accumulates (SEP 51 section 5.7). + """ + if not _at(schedule.z_start, entrance): + return ( + f"the replayed schedule starts at {schedule.z_start:g} m, but the run's " + f"entrance is {entrance:g} m" + ) + if abs(schedule.z_end - length) > replay_tolerance(schedule, length): + return ( + f"the replayed schedule ends at {schedule.z_end!r} m, but the run ends at " + f"its length, {length!r} m; replay a schedule over the run's interval, " + "such as FixedSchedule.uniform(z_start, length, ...)" + ) + return None + + +def _adopted( + settings: SimulationSettings, *, entrance: float, length: float +) -> SimulationSettings: + """Return settings resolved for a run over ``[entrance, length]``, m (SEP 51 5.6). + + Validated against the run whatever they hold, a count, a list or resolved + positions; the result holds the positions after the entrance ending exactly at + `length`, and ``n_save=None``. Settings already resolved for the run are returned + as they are. An interior launch's schedule is left to its own refusal. + """ + if not (math.isfinite(entrance) and 0.0 <= entrance < length): msg = ( - f"n_save counts the plane at z = 0, so it must be at least 2, got {count}; " - "a run always stores the entrance" + f"initial_z must be finite, nonnegative and before the end of the run, " + f"grid.length = {length:g} m; got {entrance!r}" ) - raise DriverError(msg, parameter="n_save") - return np.linspace(0.0, length, count)[1:] + raise DriverError(msg, parameter="initial_z") + # __post_init__ holds the selectors as _selectors returns them. + planes = _observation_planes( + cast("np.ndarray | None", settings.save_planes), + cast("int | None", settings.n_save), + entrance=entrance, + length=length, + ) + if settings.schedule is not None and entrance == 0.0: + refusal = _replay_refusal(settings.schedule, entrance, length) + if refusal is not None: + raise DriverError(refusal, parameter="schedule", rule="replay-interval") + current = settings.save_planes + if current is not None and np.array_equal(current, planes): + return settings + return dataclasses.replace(settings, save_planes=planes, n_save=None) def _scheme(settings: SimulationSettings) -> AbsorberScheme: diff --git a/src/solprop/driver/simulation.py b/src/solprop/driver/simulation.py index 921456270..1055acd61 100644 --- a/src/solprop/driver/simulation.py +++ b/src/solprop/driver/simulation.py @@ -129,10 +129,11 @@ _RECIPE_EXECUTION, NoiseSetting, SimulationSettings, + _adopted, _boundary, _quiet_collar, + _run_length, _same_setting, - _save_planes, _scheme, _spatial_default, _spatial_settings, @@ -297,8 +298,9 @@ class Simulation(Displayed): settings : SimulationSettings How to step it, what to record and which backend to use. initial_z : float, optional - Absolute position of an array input, m, default zero. Every requested save - plane must follow it. An interior launch keeps the original profiles and + Absolute position of an array input, m, default zero, before + ``grid.length``: the run records ``[initial_z, grid.length]`` (SEP 51), a count + spread over that interval. An interior launch keeps the original profiles and propagation frame; it requires a modal array input, no noise and no fixed step schedule. noise : solprop.noise.NoiseRealisation or None, optional @@ -445,6 +447,7 @@ def __init__( # every run repeated (``_transverse_edge``). self._edge_k_min: dict[float, float] = {} self.settings = settings + settings = self.settings if settings.controller is None: msg = ( "settings.controller is None: Simulation.from_free and " @@ -543,6 +546,12 @@ def settings(self) -> SimulationSettings: # numpydoc ignore=RT01 def settings(self, settings: SimulationSettings) -> None: """Replace settings; after translation, execution resources alone. + The replacement is adopted as the constructor adopts its settings (SEP 51): + validated against this run's interval ``[initial_z, grid.length]`` and + resolved into the positions after the entrance, ending exactly at the length, + before anything is compared, so a count and the positions it resolves to are + the same setting. + Parameters ---------- settings : SimulationSettings @@ -551,10 +560,15 @@ def settings(self, settings: SimulationSettings) -> None: Raises ------ DriverError - If the simulation has already been translated and the replacement changes - a setting other than ``backend``, ``resume_history``, ``fields``, - ``field_planes``, ``tdse_execution`` or ``boundary_check``, naming them. + If the planes do not fit this run's interval, a replayed schedule does not + cover it, or the simulation has already been translated and the + replacement changes a setting other than ``backend``, ``resume_history``, + ``fields``, ``field_planes``, ``tdse_execution`` or ``boundary_check``, + naming them. """ + settings = _adopted( + settings, entrance=float(self.initial_z), length=float(self.grid.length) + ) if self._problem is not None: changed = [ one.name @@ -710,7 +724,7 @@ def translate(self) -> PropagationProblem: initial_z=self.initial_z, # Simulation.__init__ refuses a missing controller. controller=cast("PIController", settings.controller), - save_planes=settings.save_planes, + save_planes=np.asarray(settings.save_planes), dz_max=settings.dz_max, dz_init=settings.dz_init, dz_min=settings.dz_min, @@ -815,7 +829,8 @@ def input_port(self, z: float | None = None) -> InputPort: ) raise DriverError(msg) if z is not None and not ( - math.isfinite(z) and 0.0 <= z < float(np.max(self.settings.save_planes)) + math.isfinite(z) + and 0.0 <= z < float(np.max(np.asarray(self.settings.save_planes))) ): msg = f"an interior entrance lies inside the run, got z = {z!r} m" raise DriverError(msg) @@ -890,8 +905,10 @@ def with_input( the seed a resume's file or a scan point supplies. initial_z : float or None, optional Absolute launch position in metres. None retains this simulation's - launch. An explicit position keeps only existing save planes beyond - it, preserving all absolute profiles, propagation tables and the frame. + launch. An explicit position keeps the already resolved observations + beyond it, which always include the end, and records the new entrance + there (SEP 51): it requests no new count. All absolute profiles, + propagation tables and the frame are kept. configuration : collections.abc.Mapping or None, optional Caller keys merged into the derived run's configuration record, and so into its configuration hash: the delay of a scan, the label of an input. @@ -1017,7 +1034,9 @@ def with_input( ) request = self._run_request() updated._request = request.with_stepper( - dataclasses.replace(request.stepper, save_planes=settings.save_planes) + dataclasses.replace( + request.stepper, save_planes=updated.settings.save_planes + ) ) route = updated._problem.route if isinstance(route, SpatialRoute): @@ -2046,7 +2065,9 @@ def from_free( columns, on a radial grid; a Cartesian DFT spectrum in V/m, ``n_x*n_y`` columns, otherwise. settings : SimulationSettings - Step tolerances, positive save positions in m, statistics and backend. + Step tolerances, the saved planes (``n_save`` or positions in m over + ``[0, grid.length]``; the run ends at ``grid.length``), statistics and + backend. Absolute tolerance has the input spectrum's units. frame : solprop.linear.Frame or None, optional Moving frame. None uses the declared responses' THG choice. @@ -2173,7 +2194,9 @@ def from_planar( amplitudes in sqrt(W/m), shape ``(n_p*n_y, 1, n_omega)``, the mode index fastest. Any other pulse is refused by name. settings : SimulationSettings - Step tolerances, positive save positions in m, statistics and backend. + Step tolerances, the saved planes (``n_save`` or positions in m over + ``[0, grid.length]``; the run ends at ``grid.length``), statistics and + backend. Absolute tolerance has the input spectrum's units, sqrt(W/m). frame : solprop.linear.Frame or None, optional Moving frame. None uses the declared responses' THG choice, following @@ -2267,7 +2290,7 @@ def from_planar( def from_gnlse( cls, gamma: float | None, - length: float, + length: float | None = None, betas: Sequence[float] | np.ndarray | None = None, *, wavelength: float, @@ -2322,8 +2345,12 @@ def from_gnlse( ---------- gamma : float or None Nonlinear coefficient in 1/(W m), positive for a self-focusing medium. - length : float - Fibre length, m, positive. + length : float or None, optional + Fibre length, which is the run's length and its end, m, positive + (SEP 51): the grid is built with it, and the default steps + derive from it. Optional beside `grid`, whose ``grid.length`` it must + then agree with to within :data:`~solprop.stepper.schedule.LANDING_ULPS` + ulps; one of the two is required. betas : array_like, optional Taylor coefficients of ``beta`` about `wavelength`, ``beta_0, beta_1, ...``, in s^n/m. ``beta_0`` and ``beta_1`` only fix the frame and change no @@ -2341,7 +2368,8 @@ def from_gnlse( An envelope grid to propagate on instead of building one from `length`, `wavelength`, `wavelength_limits` and `trange`. This is the way to choose the sample spacing, the oversampling factor or the transform size. A field - grid is refused: the GNLSE mapping is the envelope Kerr response. + grid is refused: the GNLSE mapping is the envelope Kerr response. Its + length is the run's (`length`). beta : tuple or callable, optional The propagation constant as data instead of a series: a pair of arrays ``(omega, beta)`` in rad/s and 1/m with strictly increasing frequencies, or @@ -2439,7 +2467,8 @@ def from_gnlse( A fixed schedule to replay instead of stepping adaptively, which makes a run bit-identical on re-running (``docs/dev/stepper.md`` section 8). Its edges must contain every save plane, which - :meth:`solprop.stepper.schedule.FixedSchedule.uniform` guarantees. + :meth:`solprop.stepper.schedule.FixedSchedule.uniform` guarantees, and it + must cover the run, from the entrance to the length (SEP 51). integrator : Multistep, RungeKutta or LowStorageRungeKutta, optional The method that steps the run (``docs/guide/numerics/choosing-a-stepper.md``). ``None``, the default, @@ -2456,12 +2485,13 @@ def from_gnlse( Also save the end of every `step_planes`-th accepted step, the march's own positions, beside the requested planes (SEP 14); ``None``, the default, and ``0`` save the requested planes only. - save_planes : array_like, optional - Positions along the fibre to save at, m, increasing and positive; the plane - at ``z = 0`` is saved as well. Give this or `n_save`. - n_save : int, optional - Number of planes to store, counting the one at ``z = 0``, spread evenly over - the fibre. Default 201. + save_planes : sequence of float or None, optional + Positions to record the run at, m, finite, strictly increasing and inside + ``[0, length]``; the entrance and the end are added when absent, and an + empty list records them alone (SEP 51). Give this or `n_save`. + n_save : int or None, optional + How many evenly spaced observations to record over the run, both ends + included: an integer of at least 2. Default 201. stats : solprop.stats.StatsSpec, optional Which statistics to record at every plane; ``None`` records :func:`solprop.stats.default_spec` of a mode-averaged run. A ``periodic`` @@ -2520,6 +2550,7 @@ def from_gnlse( >>> simulation.settings.save_planes.tolist() [0.005, 0.01] """ + length = _run_length(length, grid) materials = MaterialSelection() if materials is None else materials _refuse_dispersive_policy(materials, "a GNLSE run's fitted gamma") working = _gnlse_grid( @@ -2562,7 +2593,8 @@ def from_gnlse( atol=atol, dz_max=dz_max, dz_init=dz_init, - save_planes=_save_planes(length, save_planes, n_save), + save_planes=save_planes, + n_save=n_save, schedule=schedule, integrator=integrator, interpolate_planes=interpolate_planes, @@ -2600,8 +2632,8 @@ def from_gnlse( def from_capillary( cls, radius: float | ZProfile, - length: float, - gas: Gas | str | Mapping[str, float] | Mixture, + length: float | None = None, + gas: Gas | str | Mapping[str, float] | Mixture | None = None, pressure: Pressure | None = None, *, pressure_floor: float | None = None, @@ -2685,11 +2717,16 @@ def from_capillary( ---------- radius : float or solprop.profiles.ZProfile Core radius, m, constant or along z. - length : float - Capillary length, m. + length : float or None, optional + Capillary length, which is the run's length and its end, m, positive + (SEP 51): the grid is built with it, and the default steps and profiles + derive from it. Optional beside `grid`, whose ``grid.length`` it must + then agree with to within :data:`~solprop.stepper.schedule.LANDING_ULPS` + ulps; one of the two is required. gas : Gas, str, Mapping or Mixture - Built-in gas, mole fractions keyed by species name, or ordered populations - carrying their own density paths. A mapping uses total pressure. + Required. Built-in gas, mole fractions keyed by species name, or + ordered populations carrying their own density paths. A mapping uses + total pressure. pressure : float, sequence, ZProfile or None, optional None uses one bar for a gas or fractions. Omit pressure beside a Mixture; every explicit pressure is refused because it already carries its paths. @@ -2729,7 +2766,8 @@ def from_capillary( Requested width of the time window, s. Required unless `grid` is given. grid : solprop.grid.TimeGrid or None, optional A grid of one's own, instead of the three keywords above; the only way to - reach ``dt``, ``ffac`` or the transform size. + reach ``dt``, ``ffac`` or the transform size. Its length is the run's + (`length`). envelope : bool, optional Propagate an envelope. Plasma is off by default; explicit ``plasma=True`` selects cycle averaging of instantaneous rates. Plasma forbids THG. @@ -2939,9 +2977,12 @@ def from_capillary( ``1`` with a `tdse` response, which saves every accepted step without imposing a landing (SEP 20 section 5.8). save_planes : sequence of float or None, optional - Positions to save at, m. Give this or `n_save`. + Positions to record the run at, m, finite, strictly increasing and inside + ``[0, length]``; the entrance and the end are added when absent, and an + empty list records them alone (SEP 51). Give this or `n_save`. n_save : int or None, optional - How many planes to save, counting ``z = 0``. + How many evenly spaced observations to record over the run, both ends + included: an integer of at least 2. stats : solprop.stats.StatsSpec or None, optional Which statistics to record; ``None`` takes :func:`solprop.stats.default_spec` with the profiles, for a multimode run @@ -3011,6 +3052,10 @@ def from_capillary( >>> sorted(simulation.profiles) ['core_radius', 'density', 'pressure'] """ + length = _run_length(length, grid) + if gas is None: + msg = "a capillary run needs its fill: pass gas=" + raise DriverError(msg, parameter="gas") return _from_hollow( cls, keyword_request( @@ -3025,7 +3070,7 @@ def from_capillary( def from_waveguide( cls, modes: Sequence[Mode], - length: float, + length: float | None = None, gas: Gas | str | Mapping[str, float] | Mixture | None = None, pressure: Pressure | None = None, *, @@ -3126,8 +3171,12 @@ def from_waveguide( `provider` it must be empty or exactly the guide's own ordered channels: a guide supplies its channels itself, and the provider has already validated their order against its fields. - length : float - Waveguide length, m. + length : float or None, optional + Waveguide length, which is the run's length and its end, m, positive + (SEP 51): the grid is built with it, and the default steps and profiles + derive from it. Optional beside `grid`, whose ``grid.length`` it must + then agree with to within :data:`~solprop.stepper.schedule.LANDING_ULPS` + ulps; one of the two is required. gas : Gas, str, Mapping, Mixture or None Built-in gas, mole fractions keyed by species name, or ordered populations carrying their own density paths. A mapping uses total pressure. Required @@ -3232,7 +3281,8 @@ def from_waveguide( Requested width of the time window, s. Required unless `grid` is given. grid : solprop.grid.TimeGrid or None, optional A grid of one's own, instead of the three keywords above; the only way to - reach ``dt``, ``ffac`` or the transform size. + reach ``dt``, ``ffac`` or the transform size. Its length is the run's + (`length`). envelope : bool, optional Propagate an envelope. Plasma is off by default; explicit ``plasma=True`` selects cycle averaging of instantaneous rates. Plasma forbids THG. @@ -3406,9 +3456,12 @@ def from_waveguide( march's own positions, beside the requested planes (SEP 14); ``None``, the default, and ``0`` save the requested planes only. save_planes : sequence of float or None, optional - Positions to save at, m. Give this or `n_save`. + Positions to record the run at, m, finite, strictly increasing and inside + ``[0, length]``; the entrance and the end are added when absent, and an + empty list records them alone (SEP 51). Give this or `n_save`. n_save : int or None, optional - How many planes to save, counting ``z = 0``. + How many evenly spaced observations to record over the run, both ends + included: an integer of at least 2. stats : solprop.stats.StatsSpec or None, optional Which statistics to record; ``None`` takes :func:`solprop.stats.default_spec` with the profiles, for a multimode run @@ -3456,6 +3509,7 @@ def from_waveguide( provider, a general-guide keyword is given without one, or any supplied setting is invalid. """ + length = _run_length(length, grid) if provider is not None: # The gas-filled keywords are carried to be refused by name if set. scope = locals() diff --git a/src/solprop/recipe/core.py b/src/solprop/recipe/core.py index 13139a3f2..1410a9263 100644 --- a/src/solprop/recipe/core.py +++ b/src/solprop/recipe/core.py @@ -23,7 +23,7 @@ import numpy as np -from solprop.exceptions import SolpropError, SolpropWarning +from solprop.exceptions import DriverError, SolpropError, SolpropWarning from solprop.output.records import RecipeRecord from solprop.recipe.document import ( FORMAT, @@ -52,6 +52,7 @@ BuildContext, coerce, decode_keyword, + plane_parameter, retired, ) @@ -667,6 +668,12 @@ def _require_keywords(self) -> None: that solve its pins have dropped ``[pins]``, so a pinned keyword looks missing on them. """ + given = set(self._document["build"]) | set(self._document.get("pins", {})) + table = self._table() + if "length" in table and "grid" in table and not given & {"length", "grid"}: + # A keyword route's length is stated once, as length or as a grid's + # (SEP 51): either will do, so neither is required alone. + raise RecipeError("a length or a grid is required", path="length") missing = self._missing() if len(missing) == 1: raise RecipeError("a required keyword is missing", path=missing[0]) @@ -694,11 +701,21 @@ def build(self) -> "Simulation": if self._document.get("pins"): return self.resolve().build() builder = surface(self.route) - simulation = builder(**self.keywords()) - if not self._grid_first() and any( - _needs_grid(value) for value in self._document["build"].values() - ): - simulation = builder(**self.keywords(grid=simulation._base_grid)) + try: + simulation = builder(**self.keywords()) + if not self._grid_first() and any( + _needs_grid(value) for value in self._document["build"].values() + ): + simulation = builder(**self.keywords(grid=simulation._base_grid)) + except DriverError as error: + # SEP 51's refusals of the planes, the length and replay are the recipe's. + planes = plane_parameter(error) + if planes is None: + raise + prefix = "settings." if self.route in OBJECT_ROUTES else "" + if planes in ("length", "grid"): + prefix = "" + raise RecipeError(str(error), path=f"{prefix}{planes}") from error execution = self._execution() if execution: simulation.settings = dataclasses.replace(simulation.settings, **execution) diff --git a/src/solprop/recipe/metadata.py b/src/solprop/recipe/metadata.py index 9421a0c9b..c28df8d4e 100644 --- a/src/solprop/recipe/metadata.py +++ b/src/solprop/recipe/metadata.py @@ -447,7 +447,7 @@ def _pressure(values: Mapping[str, object]) -> Resolution: _CHECK: Final = Form("object", types=("BoundaryCheck",)) _MATERIALS: Final = Form("object", types=("MaterialSelection",)) _SCHEMES: Final = Form("choice", choices=("nonlinear", "split_step")) -_SAVE_PLANES: Final = Form("array", unit="m", minimum=0.0, exclusive=True) +_SAVE_PLANES: Final = Form("array", unit="m", minimum=0.0) _PHASES: Final = Form("array", elements="phases") _SHAPES: Final = Form("choice", choices=("gauss", "sech")) _BACKENDS: Final = Form("string") @@ -473,7 +473,7 @@ def _shared(route: str) -> tuple[Parameter, ...]: (_POSITIVE_LENGTH,), "geometry", "basic", - "Propagation length.", + "Propagation length, the run's end; optional beside a grid.", "guide/setup/running.md#one-call", display="m", ), @@ -670,7 +670,7 @@ def _shared(route: str) -> tuple[Parameter, ...]: (_SAVE_PLANES,), "output", "basic", - "Positions to save the field at, after the entrance.", + "Positions to record the run at; the entrance and the end are added.", _OUTPUT_PAGE, display="mm", resolvable=True, @@ -680,7 +680,7 @@ def _shared(route: str) -> tuple[Parameter, ...]: (Form("integer", minimum=2),), "output", "basic", - "Number of evenly spaced planes to save, counting the entrance.", + "Evenly spaced observations over the run, both ends included.", _OUTPUT_PAGE, ), Parameter( @@ -2861,11 +2861,17 @@ def _plasma(*extra: Row) -> tuple[Parameter, ...]: ), _keyword( "save_planes", - (Form("array", unit="m", minimum=0.0, exclusive=True), _integer(1)), + Form("array", unit="m", minimum=0.0), "basic", - "Positions to save at, or how many equally spaced planes.", + "Positions to record the run at; the entrance and the end are added.", display="m", ), + _keyword( + "n_save", + _integer(2), + "basic", + "Evenly spaced observations over the run, both ends included.", + ), _keyword("dz_max", _LENGTH, "advanced", "Largest step.", display="mm"), _keyword("dz_init", _LENGTH, "advanced", "First step.", display="mm"), _keyword( diff --git a/src/solprop/recipe/provenance.py b/src/solprop/recipe/provenance.py index b89d015bf..c3b31228f 100644 --- a/src/solprop/recipe/provenance.py +++ b/src/solprop/recipe/provenance.py @@ -30,7 +30,7 @@ encode_integer, read_data_file, ) -from solprop.recipe.metadata import REQUIRED, parameters +from solprop.recipe.metadata import OBJECT_ROUTES, REQUIRED, parameters if TYPE_CHECKING: from solprop.driver.simulation import Simulation @@ -150,8 +150,18 @@ def resolved_document( entry = table.get(name) if entry is not None and entry.resolvable and name not in build: build[name] = value - # save_planes is resolvable on every route, so the planes n_save stood for are now - # written out. + # The run's resolved positions, ending at its length, replace whatever selector + # was authored or defaulted (SEP 51 section 5.9), at the level the route reads + # them: a later change of a default count cannot change the rebuilt run. + planes = np.asarray(simulation.settings.save_planes, dtype=float).tolist() + nested = build.get("settings") + if recipe.route in OBJECT_ROUTES and isinstance(nested, Mapping): + settings_table = dict(nested) + settings_table.pop("n_save", None) + settings_table["save_planes"] = planes + build["settings"] = settings_table + else: + build["save_planes"] = planes build.pop("n_save", None) noise = simulation.noise if noise is not None and noise.seed is not None and "seed" not in build: diff --git a/src/solprop/recipe/registry.py b/src/solprop/recipe/registry.py index b0c40ddda..fa32febea 100644 --- a/src/solprop/recipe/registry.py +++ b/src/solprop/recipe/registry.py @@ -32,6 +32,7 @@ from solprop.boundaries import SpatialAbsorber, absorber from solprop.driver.settings import SimulationSettings +from solprop.exceptions import DriverError from solprop.grid import ( EnvelopeGrid, FieldGrid, @@ -87,6 +88,7 @@ from solprop.stepper.schedule import FixedSchedule __all__ = [ + "PLANE_PARAMETERS", "REGISTRY", "RETIRED_KEYWORDS", "BuildContext", @@ -97,6 +99,8 @@ "coerce", "decode", "decode_keyword", + "plane_parameter", + "refuse_plane_count", "retired", "unit_of", ] @@ -732,15 +736,95 @@ def build_object( "route's gas, pressure and temperature, so a mode table names no fill" ) raise RecipeError(msg, path=path) + if factory.target is SimulationSettings: + refuse_plane_count(key, item, f"{path}.{key}") decoded = decode(item, factory.units.get(key), context, f"{path}.{key}") arguments[key] = coerce(factory.target, key, decoded) if factory.solves and context.stand_in: # A solve on a band that is not the run's would refuse what the run accepts. return None + return _constructed(factory, positional, arguments, path) + + +def _constructed( + factory: Factory, + positional: Sequence[object], + arguments: Mapping[str, object], + path: str, +) -> object: + """Call a factory's target, its refusals of the planes reported as the recipe's.""" try: return factory.target(*positional, **arguments) except TypeError as error: raise RecipeError(f"{factory.name}: {error}", path=path) from error + except DriverError as error: + planes = plane_parameter(error) + if planes is None: + raise + raise RecipeError(str(error), path=f"{path}.{planes}") from error + + +PLANE_PARAMETERS: Final = ("save_planes", "n_save", "length", "grid", "schedule") +"""The keywords whose refusals SEP 51 states, which a recipe reports as its own.""" + + +def plane_parameter(error: DriverError) -> str | None: + """Return the keyword a refusal of the planes, the length or replay names. + + Parameters + ---------- + error : solprop.exceptions.DriverError + A refusal raised while a recipe's run is built. + + Returns + ------- + str or None + The first keyword it names of :data:`PLANE_PARAMETERS`, or ``None`` for + another refusal, which keeps its own type. + + Examples + -------- + >>> from solprop.exceptions import DriverError + >>> from solprop.recipe.registry import plane_parameter + >>> plane_parameter(DriverError("...", parameter=("save_planes", "n_save"))) + 'save_planes' + """ + named = error.parameter + paths = (named,) if isinstance(named, str) else tuple(named or ()) + return next((one for one in paths if one in PLANE_PARAMETERS), None) + + +def refuse_plane_count(key: str, value: object, path: str) -> None: + """Refuse a bare integer given as ``save_planes``, naming ``n_save`` (SEP 51). + + A recipe once read ``save_planes = 80`` as one plane at 80 m (#533); positions and + a count have one name each, so the integer is refused with the fix. + + Parameters + ---------- + key : str + The keyword. + value : object + Its value as TOML read it. + path : str + The value's parameter path, for the error. + + Raises + ------ + RecipeError + If `key` is ``save_planes`` and `value` an integer. + + Examples + -------- + >>> from solprop.recipe.registry import refuse_plane_count + >>> refuse_plane_count("save_planes", [0.1, 0.2], "settings.save_planes") + """ + if key == "save_planes" and isinstance(value, int) and not isinstance(value, bool): + msg = ( + f"save_planes = {value} reads as one position in m, not a count; for " + f"evenly spaced planes write n_save = {value}" + ) + raise RecipeError(msg, path=path) @functools.cache @@ -903,6 +987,7 @@ def decode_keyword(entry: Parameter, value: object, context: BuildContext) -> ob "hold; use the Python export (Recipe.to_python)" ) raise RecipeError(msg, path=entry.name) + refuse_plane_count(entry.name, value, entry.name) unit = unit_of(entry, value) if unit is None and _numeric_rows(entry, value): msg = f"{entry.name} takes one row of numbers, not a list of rows" diff --git a/tests/backend_corpus_cases.py b/tests/backend_corpus_cases.py index 09fe2d42c..48d8d275d 100644 --- a/tests/backend_corpus_cases.py +++ b/tests/backend_corpus_cases.py @@ -328,7 +328,7 @@ def general_modal( One HE11 channel of a 1.5 um strand with a Kerr core, over the catalogue's 0.2 mm. """ simulation = general_constant(None) - length = float(simulation.settings.save_planes[-1]) + length = float(np.asarray(simulation.settings.save_planes)[-1]) planes = (length / 2, length) schedule = _schedule(length, planes[:1]) simulation.settings = dataclasses.replace( diff --git a/tests/backends/adams_source_cases.py b/tests/backends/adams_source_cases.py index 564386b13..8e2b6c737 100644 --- a/tests/backends/adams_source_cases.py +++ b/tests/backends/adams_source_cases.py @@ -16,6 +16,7 @@ import numpy as np from backends.matched import fixed_order +from builders import grid_at, held_collar from parity_ladder import Built from solprop.driver.simulation import Simulation from solprop.grid import EnvelopeGrid, FieldGrid @@ -47,11 +48,14 @@ def source_case(route, length, **settings): temporal collar. """ limits = (0.01, 800e-9, (200e-9, 2e-6), 100e-15) - grid = ( + window = ( EnvelopeGrid.from_limits(*limits, thg=False) if route.get("envelope") else FieldGrid.from_limits(*limits) ) + # A run ends at its grid's length (SEP 51): the grid is cut at the run's length, + # with the collar the centimetre window gave. + grid = grid_at(window, length) simulation = Simulation.from_capillary( 150e-6, length, @@ -61,6 +65,7 @@ def source_case(route, length, **settings): fwhm=10e-15, energy=5e-5, grid=grid, + absorber=held_collar(grid, window.length), n_save=2, noise=None, integrator=Multistep(formulation="interaction"), diff --git a/tests/backends/dispersive_rows.py b/tests/backends/dispersive_rows.py index a607460a7..fe2967f6d 100644 --- a/tests/backends/dispersive_rows.py +++ b/tests/backends/dispersive_rows.py @@ -306,9 +306,9 @@ def multimode_capillary_rows(evaluator: str) -> Iterator[Row]: capillary, evaluator, stepped=True, - n_save=None, integrator=RungeKutta(), - save_planes=[LENGTH / STEPS], + # The rung takes the schedule's first step alone; the run records + # the whole replayed schedule, which ends at its length (SEP 51). **grid, ), rungs={"one_step": one_step_of(capillary_evaluation)}, diff --git a/tests/backends/general_rows.py b/tests/backends/general_rows.py index 331f8018a..0c58e3ad3 100644 --- a/tests/backends/general_rows.py +++ b/tests/backends/general_rows.py @@ -82,6 +82,7 @@ from backends.flow_rows import driver_case from backends.session_rows import without_collar, without_modal_flow +from builders import grid_at, held_collar from general_parity import ( LENGTH, STEPS, @@ -207,7 +208,11 @@ def entry_simulation(noise: str | None = "input", **keywords: Any) -> Simulation ``numba_cpu``'s retired entry-point test, on its input: a 20 fs, 20 pJ Gaussian with an input shot-noise draw (seed 5) by default; `keywords` go to the constructor. """ - grid, guide, _, _ = _scaled("pair") + window, guide, _, _ = _scaled("pair") + # A run ends at its grid's length (SEP 51): the grid is cut at the entry point's + # run, with the collar the millimetre gave. + grid = grid_at(window, ENTRY_LENGTH) + keywords = {"absorber": held_collar(grid, window.length), **keywords} return Simulation.from_waveguide( (), ENTRY_LENGTH, diff --git a/tests/backends/test_envelope_plasma_host.py b/tests/backends/test_envelope_plasma_host.py index b8354c69f..de28530d0 100644 --- a/tests/backends/test_envelope_plasma_host.py +++ b/tests/backends/test_envelope_plasma_host.py @@ -18,7 +18,7 @@ from backends.envelope_host_cases import argon_host_case from backends.mixture_rows import host from bounds import scan_bound -from builders import load_reference +from builders import grid_at, load_reference from sessions.runs import run as session_run from solprop.backends.node_chunk import plan_node_chunk from solprop.backends.numpy_ref import NumpyRefBackend @@ -214,7 +214,8 @@ def test_direct_simulation_records_carrier_approximation_and_runs(host_case): assert assembly is not None mode = MarcatiliMode(125e-6, "Ar", 1.0, loss=False) simulation = Simulation( - grid, + # The run ends at its grid's length (SEP 51); no collar reads the length. + grid_at(grid, 8e-6), mode, [EnvelopePlasmaResponse("Ar", assembly.channels[0].rate, preionisation=0.1)], original.initial.field0, diff --git a/tests/backends/test_far_field_statistics.py b/tests/backends/test_far_field_statistics.py index 91eb4bcc8..ebab17e59 100644 --- a/tests/backends/test_far_field_statistics.py +++ b/tests/backends/test_far_field_statistics.py @@ -20,6 +20,7 @@ from backends.planar_cases import planar_case from bounds import EPS, assert_within, gamma +from builders import grid_at from legacy_geometry import bare_absorber from sessions.runs import launch_statistics from solprop.backends import registry, select @@ -102,8 +103,11 @@ def free_simulation(grid, space, launch, *, medium=None, spec=None, **settings): "stats": far_spec() if spec is None else spec, } options.update(settings) + # A run ends at its grid's length (SEP 51): the run's grid is the fixture's cut at + # the last plane, while every collar is the fixture grid's own, so the rates the + # millimetre gave are kept. return Simulation.from_free( - grid, + grid_at(grid, float(np.max(options["save_planes"]))), space, SpatialMedium() if medium is None else medium, [], @@ -214,7 +218,7 @@ def test_the_bands_follow_the_shapes_and_the_budget(monkeypatch): def test_a_radial_problem_takes_no_partials(grid): radial = Simulation.from_free( - grid, + grid_at(grid, 1e-4), RadialGrid(3e-4, 8), SpatialMedium(), [], @@ -668,7 +672,7 @@ def test_the_operator_refuses_a_share_above_the_total(grid, lossy_launch): def test_radial_and_planar_geometry_are_refused_before_any_step(grid): spec = StatsSpec(names=("energy", "beam_spectrum")) radial = Simulation.from_free( - grid, + grid_at(grid, 1e-4), RadialGrid(3e-4, 16), SpatialMedium(), [], diff --git a/tests/backends/test_native_far_field.py b/tests/backends/test_native_far_field.py index de1586453..689dba8ed 100644 --- a/tests/backends/test_native_far_field.py +++ b/tests/backends/test_native_far_field.py @@ -40,6 +40,7 @@ from backends.forced_threads import assert_threaded from backends.matched import native_thread_fields from bounds import assert_within, gamma +from builders import grid_at from sessions.executors import IDENTITY from sessions.runs import launched, load_native from solprop.backends import select @@ -85,8 +86,10 @@ def problem_of( boundary=None, ): """The kernel problem of one state and its statistics, for Kokkos.""" + # A run ends at its grid's length (SEP 51): the run's grid is cut at its plane, + # and the collar is the given grid's own, so its rates are kept. simulation = Simulation.from_free( - grid, + grid_at(grid, 1e-4), space, SpatialMedium(1 + 1e-6j) if medium is None else medium, [], @@ -762,7 +765,8 @@ def test_a_native_run_forms_the_statistics_at_planes_and_between_them(): def simulation_on(backend): return Simulation.from_free( - grid, + # Cut at the last plane (SEP 51); the collar keeps the full grid's rates. + grid_at(grid, 2e-4), space, SpatialMedium(1 + 1e-6j), [], diff --git a/tests/backends/test_planar_hybrid.py b/tests/backends/test_planar_hybrid.py index 2c7f68477..13fe75ba6 100644 --- a/tests/backends/test_planar_hybrid.py +++ b/tests/backends/test_planar_hybrid.py @@ -27,7 +27,7 @@ from backends.planar_hybrid_cases import ENVELOPE, FAMILIES, HALF_GAP, LENGTH, ORDERS from backends.rate_bounds import rate_error_bound from bounds import fft_bound, gamma, step_evaluations -from builders import load_reference +from builders import grid_at, load_reference from legacy_geometry import bare_absorber from sessions.runs import bare, final_field from sessions.runs import run as session_run @@ -342,6 +342,8 @@ def test_a_linear_beam_diffracts_in_y_and_decays_as_each_slab_mode(): backend="numpy_ref", absorber=bare_absorber(grid), ) + # A run ends at its grid's length (SEP 51); the bare collar has no length. + grid = grid_at(grid, length) hybrid = Simulation.from_planar(grid, space, [], field0, settings=settings) problem, run_request = hybrid.translate(), hybrid._run_request() backend = NumpyRefBackend(problem, run_request, grid=grid) @@ -487,6 +489,8 @@ def test_the_planar_launch_carries_the_coupled_share_of_the_incident_energy(): stats=spec, absorber=bare_absorber(grid), ) + # A run ends at its grid's length (SEP 51); the bare collar has no length. + grid = grid_at(grid, 1e-3) simulation = Simulation.from_planar(grid, space, [], pulse, settings=settings) problem = simulation.translate() run_request = simulation._run_request() diff --git a/tests/builders.py b/tests/builders.py index 2d7e54a9d..6576e43b9 100644 --- a/tests/builders.py +++ b/tests/builders.py @@ -9,6 +9,7 @@ pinned, when it was migrated, by the configuration hash of what the old copies built. """ +import dataclasses import subprocess import sys import textwrap @@ -20,8 +21,10 @@ from legacy_geometry import LEGACY_GRID, bare_absorber from march_bounds import FIXED_ORDER from solprop.backends.numpy_ref import NumpyRefBackend +from solprop.boundaries import DEFAULT_BOUNDARY_N, Absorber, absorber from solprop.driver import Simulation from solprop.driver.scan import ScanPoint +from solprop.exceptions import GridError from solprop.grid import EnvelopeGrid, TimeGrid from solprop.stats import StatsSpec from solprop.stepper import FixedSchedule @@ -31,6 +34,8 @@ __all__ = [ "HASH_PROBE", "fixed_fibre_point", + "grid_at", + "held_collar", "launch_derivative", "load_reference", "numpy_ref_launch_derivative", @@ -82,6 +87,30 @@ def load_reference( return workspace.committed() +def grid_at[G: TimeGrid](grid: G, length: float) -> G: + """Return `grid` with another length, m, and every sample as it was. + + A run ends at its grid's length (SEP 51), so a test that ran a short window of a + longer grid shortens the grid instead. The length also sets the default absorber's + reference length; :func:`held_collar` keeps the rates the old length gave. + """ + return dataclasses.replace(grid, length=length) + + +def held_collar(grid: TimeGrid, length: float) -> Absorber: + """Return the default collar on `grid`, at the rates a grid of `length` gave. + + :func:`solprop.driver.settings.default_collar` with its reference length pinned to + ``length / DEFAULT_BOUNDARY_N``, m, so that shortening a test's grid to the window + it runs (:func:`grid_at`) leaves its absorber unchanged. + """ + reference = length / DEFAULT_BOUNDARY_N + try: + return absorber(grid, boundary_length=reference) + except GridError: + return absorber(grid, boundary_length=reference, temporal=False) + + def launch_derivative(backend: NumpyRefBackend, problem: PropagationProblem) -> Any: """Return an open ``numpy_ref`` backend's stage derivative ``N(E, z=0)`` at launch. diff --git a/tests/calibration/test_refine.py b/tests/calibration/test_refine.py index b0348886c..b69c98aac 100644 --- a/tests/calibration/test_refine.py +++ b/tests/calibration/test_refine.py @@ -264,7 +264,7 @@ def test_a_low_storage_simulation_times_its_own_march(profiled: Path) -> None: from solprop.stepper import FixedSchedule, LowStorageRungeKutta # noqa: PLC0415 simulation = problems.build("gnlse") - planes = list(simulation.settings.save_planes) + planes = list(np.asarray(simulation.settings.save_planes)) length = float(max(planes)) simulation.settings = dataclasses.replace( simulation.settings, diff --git a/tests/coupled_flow_cases.py b/tests/coupled_flow_cases.py index 34bce9fe6..38a21f62c 100644 --- a/tests/coupled_flow_cases.py +++ b/tests/coupled_flow_cases.py @@ -30,6 +30,7 @@ import numpy as np import pytest +from builders import grid_at from flow_parity import formation_bound, radial_family from legacy_geometry import LEGACY_GRID from modal_provider_cases import ( @@ -520,7 +521,9 @@ def wide_simulation(modes: int, backend: str = "numpy_ref") -> Simulation: cladding=1.45, modes=modes, wavelength=800e-9, - grid=GRID, + # A run ends at its grid's length (SEP 51): the shared grid cut at the wide + # run's; the collar is pinned already. + grid=grid_at(GRID, length), absorber=WEAK_COLLAR, fwhm=30e-15, energy=ENERGY, diff --git a/tests/coupling/test_envelopes.py b/tests/coupling/test_envelopes.py index 5a6444d23..5dcecae48 100644 --- a/tests/coupling/test_envelopes.py +++ b/tests/coupling/test_envelopes.py @@ -37,6 +37,7 @@ import pytest from scipy.special import jn_zeros, jv +from builders import grid_at from facet_mode_matching import ( Y_VACUUM, Beam, @@ -1165,11 +1166,12 @@ def facet_port(contrast, v_centre): nodes=provider.node_rule(0.99 * active[0], n_r=48, n_theta=48), degenerate_blocks=((0, 1),), ) + # Built for its port only: the grid is the tenth it would run (SEP 51). simulation = Simulation.from_waveguide( (), 1e-4, provider=guide, - grid=grid, + grid=grid_at(grid, 1e-4), wavelength=wavelength, energy=1e-12, fwhm=20e-15, diff --git a/tests/coupling/test_vector_coupling.py b/tests/coupling/test_vector_coupling.py index a8af42755..8e4f269c2 100644 --- a/tests/coupling/test_vector_coupling.py +++ b/tests/coupling/test_vector_coupling.py @@ -20,6 +20,7 @@ import numpy as np import pytest +from builders import held_collar from modal_provider_cases import GENERAL_Z_END, general_grid, general_guide from solprop.constants import C from solprop.coupling import ( @@ -75,8 +76,8 @@ def strand(grid, descriptors=PARITIES[:1], blocks=(), n_r=24, circular=None): @pytest.fixture(scope="module") def grid(): - """The general modal tests' field grid.""" - return general_grid() + """The general modal tests' field grid, at the tenth of a millimetre they run.""" + return general_grid(GENERAL_Z_END / 10) def simulation(guide, grid): @@ -94,6 +95,8 @@ def simulation(guide, grid): dz_max=GENERAL_Z_END / 20, dz_init=GENERAL_Z_END / 20, n_save=2, + # The collar of the millimetre grid these tests were written on (SEP 51). + absorber=held_collar(grid, GENERAL_Z_END), noise=None, ) diff --git a/tests/coupling/test_workflows.py b/tests/coupling/test_workflows.py index 1818df478..3c9203e1e 100644 --- a/tests/coupling/test_workflows.py +++ b/tests/coupling/test_workflows.py @@ -29,6 +29,7 @@ from scipy.integrate import quad from scipy.special import j0, jn_zeros, k0 +from builders import grid_at, held_collar from legacy_geometry import LEGACY_GRID from solprop import fourier from solprop.backends.registry import available @@ -245,13 +246,17 @@ def test_a_kerr_prepared_radial_beam_into_a_capillary(): dz_init=gap / 10, backend="numpy_ref", ) + # The receiver ends at its grid's length (SEP 51): the gap's grid cut at the + # capillary's 2 mm, with the collar the gap's grid gave. + receiver_grid = grid_at(grid, 2e-3) receiver = Simulation.from_capillary( 75e-6, 2e-3, "Ar", PRESSURE, wavelength=800e-9, - grid=grid, + grid=receiver_grid, + absorber=held_collar(receiver_grid, gap), modes=4, plasma=False, thg=False, @@ -349,13 +354,17 @@ def test_a_field_grid_kerr_plasma_thg_entrance_is_transferred_with_its_harmonic( start.spectral_energy(), start.omega, *harmonic ) assert 5e-8 < generated < 1.2e-7 + # The receiver ends at its grid's length (SEP 51): the gap's grid cut at the + # capillary's millimetre, with the collar the gap's grid gave. + receiver_grid = grid_at(grid, 1e-3) receiver = Simulation.from_capillary( 75e-6, 1e-3, "Ar", 1.0, wavelength=800e-9, - grid=grid, + grid=receiver_grid, + absorber=held_collar(receiver_grid, gap), modes=4, plasma=False, noise=None, diff --git a/tests/driver/test_backend_default.py b/tests/driver/test_backend_default.py index 3d41ee77c..65cd4c174 100644 --- a/tests/driver/test_backend_default.py +++ b/tests/driver/test_backend_default.py @@ -15,6 +15,7 @@ import numpy as np import pytest +from builders import grid_at from legacy_geometry import LEGACY_GRID from solprop.backends.registry import select from solprop.driver import ( @@ -95,6 +96,8 @@ def run(simulation, *args, **kwargs): return output monkeypatch.setattr(Simulation, "run", run) + # Nothing runs: the grid is the millimetre the calls ask for (SEP 51). + narrow_grid = grid_at(narrow_grid, 0.001) keywords: _BackendChoice = {"backend": "numpy_ref"} if explicit else {} with warnings.catch_warnings(): warnings.simplefilter("ignore", MaterialRangeWarning) diff --git a/tests/driver/test_coherent_capillary.py b/tests/driver/test_coherent_capillary.py index 67903ad7a..e3c67281c 100644 --- a/tests/driver/test_coherent_capillary.py +++ b/tests/driver/test_coherent_capillary.py @@ -770,10 +770,11 @@ def test_a_wall_declared_on_another_route_is_refused_by_name(): spatial.wall = CoherentWall() with pytest.raises(TranslationError, match="a spatial geometry"): spatial.translate() - grid = general_grid() + # Refused before any step: the grid is the tenth it would run (SEP 51). + grid = general_grid(GENERAL_Z_END / 10) general = Simulation.from_waveguide( (), - GENERAL_Z_END, + GENERAL_Z_END / 10, provider=general_guide(grid=grid), grid=grid, wavelength=835e-9, diff --git a/tests/driver/test_coupling_relaunch.py b/tests/driver/test_coupling_relaunch.py index 9d0ed361e..6c6c7e9ce 100644 --- a/tests/driver/test_coupling_relaunch.py +++ b/tests/driver/test_coupling_relaunch.py @@ -16,6 +16,7 @@ import numpy as np import pytest +from builders import grid_at, held_collar from solprop.backends.registry import available from solprop.coupling import CouplingModel, couple from solprop.driver import Simulation, SimulationSettings @@ -127,7 +128,11 @@ def test_an_interior_relaunch_continues_its_own_run(reference): def radial(pressure=1.0, length=2e-3, backend="numpy_ref"): - grid = FieldGrid.from_limits(2e-3, 800e-9, (600e-9, 1.2e-6), 400e-15) + window = FieldGrid.from_limits(2e-3, 800e-9, (600e-9, 1.2e-6), 400e-15) + # A run ends at its grid's length (SEP 51): a stage runs on the window cut at its + # length, with the collar the whole two millimetres gave, so every stage and the + # whole run share one absorber. + grid = grid_at(window, length) settings = SimulationSettings( controller=PIController(rtol=1e-10, atol=1e-16), save_planes=np.linspace(0.0, length, 3)[1:], @@ -145,6 +150,7 @@ def radial(pressure=1.0, length=2e-3, backend="numpy_ref"): [], pulse, settings=settings, + absorber=held_collar(grid, window.length), noise=None, ) diff --git a/tests/driver/test_estimate.py b/tests/driver/test_estimate.py index fcc3e3e50..15f16016f 100644 --- a/tests/driver/test_estimate.py +++ b/tests/driver/test_estimate.py @@ -107,7 +107,7 @@ def test_the_output_size_counts_only_the_retained_fields(): def test_a_low_storage_run_takes_four_calls_a_step(): simulation = _built("soliton", "numpy_ref") - planes = list(simulation.settings.save_planes) + planes = list(np.asarray(simulation.settings.save_planes)) schedule = FixedSchedule.uniform( 0.0, planes[-1], planes[-1] / 200, save_planes=planes ) @@ -167,7 +167,7 @@ def counted(): def test_an_adams_run_takes_one_call_and_a_schedule_counts_its_total(): assert _built("rdw", "numpy_ref").estimate().calls_per_step == 1 simulation = _built("rdw", "numpy_ref") - planes = list(simulation.settings.save_planes) + planes = list(np.asarray(simulation.settings.save_planes)) # Steps short enough for the Adams method's collar (h alpha / 2 below 0.0877). end = planes[-1] schedule = FixedSchedule.uniform(0.0, end, end / 2000, save_planes=planes) diff --git a/tests/driver/test_general_modal.py b/tests/driver/test_general_modal.py index 4dd83c7eb..95a7fecdc 100644 --- a/tests/driver/test_general_modal.py +++ b/tests/driver/test_general_modal.py @@ -33,7 +33,7 @@ from numpy.testing import assert_allclose from bounds import departure -from builders import load_reference +from builders import grid_at, held_collar, load_reference from legacy_geometry import LEGACY_GRID from march_bounds import ( FIXED_ORDER, @@ -103,12 +103,17 @@ pytestmark = pytest.mark.filterwarnings("ignore::solprop.exceptions.BoundaryWarning") PULSE = {"wavelength": 835e-9, "fwhm": 20e-15, "energy": 1e-12, "shape": "gauss"} +SHORT_Z = GENERAL_Z_END / 10 +"""Length the construction tests run, m: a tenth of the cap.""" + RUN = { # A tenth of a millimetre in two steps: these tests are about construction, # the launch, the refusals and the identity of a repeated draw, and none of # them needs a long propagation. The two end-to-end systems below take the - # whole millimetre. - "save_planes": [GENERAL_Z_END / 10], + # whole millimetre. A run ends at its grid's length (SEP 51), so the grid is the + # tenth, with the collar the millimetre gave. + "save_planes": [SHORT_Z], + "absorber": held_collar(general_grid(SHORT_Z), GENERAL_Z_END), "backend": "numpy_ref", "dz_max": GENERAL_Z_END / 20, "dz_init": GENERAL_Z_END / 20, @@ -123,8 +128,8 @@ def kept(field: np.ndarray | None) -> np.ndarray: @pytest.fixture(scope="module") def grid(): - """The field grid the construction tests use.""" - return general_grid() + """The field grid the construction tests use: the tenth of a millimetre they run.""" + return general_grid(SHORT_Z) @pytest.fixture(scope="module") @@ -147,7 +152,7 @@ def build(guide, grid, **overrides): """Return a general modal simulation on this guide and grid.""" return Simulation.from_waveguide( (), - GENERAL_Z_END, + SHORT_Z, provider=guide, grid=grid, **({"integrator": Multistep(), **({"noise": None, **PULSE | RUN | overrides})}), @@ -175,7 +180,7 @@ def test_a_provider_builds_a_simulation_that_translates_to_the_general_route( assert ( Simulation.from_waveguide( list(guide.mode_collection.modes), - GENERAL_Z_END, + SHORT_Z, provider=guide, grid=grid, **({"integrator": Multistep(), **({"noise": None, **PULSE | RUN})}), @@ -319,7 +324,7 @@ def test_modes_of_ones_own_are_refused_beside_a_guide(guide, grid): with pytest.raises(DriverError, match="supplies its own 1 ordered channel"): Simulation.from_waveguide( list(other.mode_collection.modes), - GENERAL_Z_END, + SHORT_Z, provider=guide, grid=grid, **({"integrator": Multistep(), **({"noise": None, **PULSE | RUN})}), @@ -327,7 +332,7 @@ def test_modes_of_ones_own_are_refused_beside_a_guide(guide, grid): def test_an_envelope_grid_is_refused_at_the_entry_point(guide): - envelope = EnvelopeGrid.from_limits(GENERAL_Z_END, 835e-9, (815e-9, 860e-9), 60e-15) + envelope = EnvelopeGrid.from_limits(SHORT_Z, 835e-9, (815e-9, 860e-9), 60e-15) with pytest.raises(DriverError, match="propagates on a field grid"): build(guide, envelope) @@ -365,7 +370,7 @@ def test_the_route_constructors_refusals_reach_the_caller_as_driver_errors(grid) with pytest.raises(DriverError, match="declares no sampling") as caught: Simulation.from_waveguide( (), - GENERAL_Z_END, + SHORT_Z, provider=unsampled, grid=grid, **({"integrator": Multistep(), **({"noise": None, **PULSE | RUN})}), @@ -581,7 +586,7 @@ def launched(guide, grid, incident, **overrides): """Return a general modal simulation coupling an incident beam.""" return Simulation.from_waveguide( (), - GENERAL_Z_END, + None, provider=guide, grid=grid, wavelength=PULSE["wavelength"], @@ -751,7 +756,7 @@ def test_the_incident_launch_refuses_what_it_does_not_carry( with pytest.raises(DriverError, match="incident= belongs to the general modal"): Simulation.from_waveguide( (MarcatiliMode(125e-6, "He", 1.0),), - GENERAL_Z_END, + SHORT_Z, gas="He", pressure=1.0, grid=grid, @@ -831,7 +836,7 @@ def test_a_poorly_captured_beam_launches_only_what_the_guide_takes( "MemoryOutput", prop_waveguide( (), - GENERAL_Z_END, + SHORT_Z, provider=incident_guide, grid=grid, wavelength=PULSE["wavelength"], @@ -877,7 +882,8 @@ def test_the_incident_launch_is_the_same_on_every_cpu_receiver( step = 5e-7 simulation = launched( incident_guide, - grid, + # Ten steps on a grid of their length (SEP 51), the collar still the run's. + grid_at(grid, 10 * step), beam, backend=backend, save_planes=[10 * step], @@ -904,7 +910,7 @@ def test_a_multichannel_input_is_refused_by_the_launch(pair_guide, grid): both = np.repeat(simulation._field0[:1], 2, axis=0) carried = Simulation.from_waveguide( (), - GENERAL_Z_END, + SHORT_Z, provider=pair_guide, grid=grid, **({"integrator": Multistep(), **({"noise": None, **PULSE | RUN})}), @@ -1201,7 +1207,7 @@ def test_an_hdf5_file_carries_the_labels_and_the_identities(guide, grid, tmp_pat # ------------------------------------------------------------ a fixed schedule -FIXED_Z = GENERAL_Z_END / 10 +FIXED_Z = SHORT_Z """Length a fixed-schedule general modal test propagates, m: a tenth of the cap.""" @@ -1218,11 +1224,12 @@ def fixed_run(guide, grid, **overrides): # march (SEP 25 4.4). "integrator": FIXED_ORDER, "save_planes": [FIXED_Z], + "absorber": RUN["absorber"], "backend": "numpy_ref", } simulation = Simulation.from_waveguide( (), - GENERAL_Z_END, + SHORT_Z, provider=guide, grid=grid, **({"integrator": Multistep(), **({"noise": None, **settings | overrides})}), @@ -1908,6 +1915,7 @@ def test_the_collar_and_not_the_route_sets_the_step_on_every_route(): # optmat's argon index covers this grid's active band, to 1774 nm (the former # registry's stopped at 1 um and warned; SEP 3), so the runs are quiet. for collar in (True, False): + # The run always went to its last plane, the millimetre (SEP 51 states it). simulation = Simulation.from_capillary( 50e-6, GENERAL_Z_END, diff --git a/tests/driver/test_grin_system.py b/tests/driver/test_grin_system.py index fb003b997..ad3001bd9 100644 --- a/tests/driver/test_grin_system.py +++ b/tests/driver/test_grin_system.py @@ -22,6 +22,7 @@ import numpy as np import pytest +from builders import grid_at, held_collar from modal_provider_cases import ( GENERAL_CHI3, grin_grid, @@ -177,11 +178,15 @@ def test_grin_self_imaging(grid, linear_guide, imaging, record_property): record_property("grin_phase_budget_rad", turn) record_property("grin_interpolation_budget_rad", interpolation) length, centre = imaging["length"], imaging["index"] + # A run ends at its grid's length (SEP 51): the millimetre grid cut at the + # imaging length, with the collar the millimetre gave. + window = grid_at(grid, length) simulation = Simulation.from_waveguide( (), length, provider=linear_guide, - grid=grid, + grid=window, + absorber=held_collar(window, grid.length), wavelength=1.03e-6, fwhm=40e-15, energy=1e-15, diff --git a/tests/driver/test_interface_defaults.py b/tests/driver/test_interface_defaults.py index 365379fef..45c06814b 100644 --- a/tests/driver/test_interface_defaults.py +++ b/tests/driver/test_interface_defaults.py @@ -696,4 +696,4 @@ def test_the_settings_leave_the_caller_s_planes_writeable(): assert not held.flags.writeable # Not a view either: a later write by the caller leaves the settings alone. planes[0] = 0.25 - assert settings.save_planes[0] == 0.5 + assert np.asarray(settings.save_planes)[0] == 0.5 diff --git a/tests/driver/test_material_manifest.py b/tests/driver/test_material_manifest.py index b0b309a63..35dac827e 100644 --- a/tests/driver/test_material_manifest.py +++ b/tests/driver/test_material_manifest.py @@ -18,6 +18,7 @@ import pytest from optmat.gas.models.registry import default_model +from builders import grid_at, held_collar from former_raman import FORMER_SILICA_TENSOR from modal_provider_cases import ( GENERAL_CHI3, @@ -697,12 +698,18 @@ def test_a_derived_run_keeps_its_own_log_from_its_parents(): def general(guide, grid, materials: MaterialSelection | None = SELECTION) -> Any: - """A general modal run of `guide`, a tenth of a millimetre in two steps.""" + """A general modal run of `guide`, a tenth of a millimetre in two steps. + + A run ends at its grid's length (SEP 51): the grid is cut at that tenth, with the + collar the full grid gave. + """ + short = grid_at(grid, GENERAL_Z_END / 10) return Simulation.from_waveguide( (), - GENERAL_Z_END, + GENERAL_Z_END / 10, provider=guide, - grid=grid, + grid=short, + absorber=held_collar(short, grid.length), wavelength=835e-9, fwhm=20e-15, energy=1e-12, diff --git a/tests/driver/test_modal_launch.py b/tests/driver/test_modal_launch.py index df4643440..75bcd6d78 100644 --- a/tests/driver/test_modal_launch.py +++ b/tests/driver/test_modal_launch.py @@ -17,12 +17,14 @@ import pytest from numpy.testing import assert_allclose +from builders import grid_at, held_collar from modal_provider_cases import GENERAL_Z_END, general_grid, general_guide from solprop import fourier from solprop.backends import available from solprop.coupling import CouplingModel from solprop.driver import Simulation from solprop.driver._launch import _resolve_launch, launch_pulse +from solprop.driver.defaults import default_step from solprop.exceptions import DriverError, OutputError from solprop.modes import MarcatiliMode from solprop.modes.collection import ModeCollection @@ -103,14 +105,20 @@ def circular_guide(grid): def general(guide, grid, **overrides): - """Return a general modal simulation on a guide.""" + """Return a general modal simulation on a guide. + + A run ends at its grid's length (SEP 51): the grid is cut at the tenth of a + millimetre it runs, with the collar and the largest step the millimetre gave. + """ + short = grid_at(grid, GENERAL_Z_END / 10) return Simulation.from_waveguide( (), - GENERAL_Z_END, + GENERAL_Z_END / 10, provider=guide, - grid=grid, + grid=short, + absorber=held_collar(short, grid.length), + dz_max=default_step("dz_max", grid.length), noise=None, - save_planes=[GENERAL_Z_END / 10], backend="numpy_ref", **PULSE | overrides, ) diff --git a/tests/driver/test_parameter_paths.py b/tests/driver/test_parameter_paths.py index 9e112ed73..9ac2bbe49 100644 --- a/tests/driver/test_parameter_paths.py +++ b/tests/driver/test_parameter_paths.py @@ -184,7 +184,7 @@ def _parameters(records: pytest.WarningsRecorder) -> list[ParameterPath | None]: lambda: _gnlse(save_planes=[0.01, 0.005], n_save=None), DriverError, "save_planes", - "positive and increasing", + "must increase strictly", id="gnlse-planes-order", ), pytest.param( diff --git a/tests/driver/test_prop_gnlse.py b/tests/driver/test_prop_gnlse.py index 740401da9..96b93e3a1 100644 --- a/tests/driver/test_prop_gnlse.py +++ b/tests/driver/test_prop_gnlse.py @@ -16,6 +16,7 @@ import pytest from bounds import departure +from builders import grid_at, held_collar from legacy_geometry import LEGACY_GRID, bare_absorber from march_bounds import FIXED_ORDER, assert_matched, simulation_bound from selected_backend import selected_backend @@ -245,7 +246,10 @@ def test_the_sixth_order_soliton_runs_the_same_through_the_interface( stop, [0.0, 0.0, soliton.beta2], wavelength=soliton.wavelength, - grid=wide_grid, + # The run ends at its grid's length (SEP 51): the grid is the tenth it runs, + # with the collar the metre-long grid gave, so the problem is unchanged. + grid=grid_at(wide_grid, stop), + absorber=held_collar(grid_at(wide_grid, stop), wide_grid.length), width=soliton.tau0, peak_power=soliton.peak_power(6), shape="sech", diff --git a/tests/driver/test_route_keywords.py b/tests/driver/test_route_keywords.py index af9d5f2f5..c7dbf99fe 100644 --- a/tests/driver/test_route_keywords.py +++ b/tests/driver/test_route_keywords.py @@ -20,6 +20,7 @@ import pytest from numpy.testing import assert_array_equal +from builders import grid_at, held_collar from modal_provider_cases import GENERAL_Z_END, general_grid, general_guide from solprop.driver import ( Simulation, @@ -75,13 +76,16 @@ def guide(grid): def general(guide, grid, **overrides): + # A run ends at its grid's length (SEP 51): the grid is cut at the tenth it runs, + # with the collar the millimetre gave. + short = grid_at(grid, GENERAL_Z_END / 10) return Simulation.from_waveguide( (), - GENERAL_Z_END, + GENERAL_Z_END / 10, provider=guide, - grid=grid, + grid=short, + absorber=held_collar(short, grid.length), noise=None, - save_planes=[GENERAL_Z_END / 10], backend="numpy_ref", dz_max=GENERAL_Z_END / 40, **PULSE | overrides, diff --git a/tests/driver/test_run.py b/tests/driver/test_run.py index 42c940e9a..6f4f54d29 100644 --- a/tests/driver/test_run.py +++ b/tests/driver/test_run.py @@ -548,11 +548,10 @@ def test_the_loop_runs_without_a_simulation(narrow_grid, soliton): @pytest.mark.parametrize( ("save_planes", "message"), - [([1.0, 0.5], "positive and increasing"), ([0.0, 0.5], "saved anyway")], + [([1.0, 0.5], "must increase strictly"), ([0.5, 0.5], "repeats")], ) -def test_the_settings_refuse_save_planes_out_of_order_or_at_the_entrance( - save_planes, message -): +def test_the_settings_refuse_save_planes_out_of_order_or_repeated(save_planes, message): + # The entrance may be listed (SEP 51 D8): it is kept once, at adoption. with pytest.raises(DriverError, match=message): SimulationSettings( controller=PIController(rtol=1e-8, atol=1e-18), diff --git a/tests/driver/test_runner.py b/tests/driver/test_runner.py index cf99c6b8a..4ff9936a5 100644 --- a/tests/driver/test_runner.py +++ b/tests/driver/test_runner.py @@ -101,7 +101,7 @@ def capillary(backend: str, *, dense: bool = False) -> Simulation: schedule=None if dense else FixedSchedule.uniform( - 0.0, LENGTH, LENGTH / STEPS, save_planes=settings.save_planes + 0.0, LENGTH, LENGTH / STEPS, save_planes=np.asarray(settings.save_planes) ), interpolate_planes=dense, ) @@ -278,7 +278,7 @@ def test_a_load_restores_what_a_failed_run_left_as_a_fresh_backend_holds(dense): finally: fresh.close() after = stored(runner.run(inputs(simulation)[1], progress="none")) - assert after.n_saved == len(simulation.settings.save_planes) + 1 + assert after.n_saved == len(np.asarray(simulation.settings.save_planes)) + 1 @pytest.mark.medium @@ -309,7 +309,11 @@ def serving(*args, **keywords): runner.run(inputs(simulation)[0], progress=_Stop()) after = stored(runner.run(field, progress="none")) assert served == ["NativeSession"] * 3 - assert after.n_saved == fresh.n_saved == len(simulation.settings.save_planes) + 1 + assert ( + after.n_saved + == fresh.n_saved + == len(np.asarray(simulation.settings.save_planes)) + 1 + ) assert np.array_equal(after["field"], fresh["field"]) for name in fresh.stat_names: assert np.array_equal( @@ -696,7 +700,7 @@ def test_a_runner_runs_an_input_without_noise_when_it_has_none(): simulation = capillary("numpy_ref") with simulation.runner() as runner: output = stored(runner.run(inputs(simulation)[0], noise=None, progress="none")) - assert output.n_saved == len(simulation.settings.save_planes) + 1 + assert output.n_saved == len(np.asarray(simulation.settings.save_planes)) + 1 @pytest.mark.medium diff --git a/tests/driver/test_save_planes.py b/tests/driver/test_save_planes.py new file mode 100644 index 000000000..96a1b4906 --- /dev/null +++ b/tests/driver/test_save_planes.py @@ -0,0 +1,531 @@ +# SPDX-FileCopyrightText: 2026 John C. Travers and contributors +# +# SPDX-License-Identifier: GPL-3.0-or-later + +"""One rule for the saved planes and the end of a run (SEP 51). + +Every run records its entrance and ends at its length; ``n_save`` counts evenly spaced +observations over ``[initial_z, length]`` and ``save_planes`` lists positions inside it. +The placement, the endpoint rounding and every refusal are one helper's, reached by +every adoption: the constructor, the keyword builders, the settings setter and +``with_input``. Resolved planes are compared exactly: they are one ``linspace`` or one +normalized copy, a structural contract. +""" + +import dataclasses +import math + +import numpy as np +import pytest + +from builders import grid_at +from solprop.backends.numpy_ref import NumpyRefBackend +from solprop.driver import Simulation, SimulationSettings +from solprop.driver.settings import DEFAULT_N_SAVE, _observation_planes +from solprop.exceptions import DriverError +from solprop.grid import EnvelopeGrid +from solprop.log import NullReporter +from solprop.output.hdf5 import resume +from solprop.recipe import Recipe, resume_file +from solprop.stats import StatsSpec +from solprop.stepper import FixedSchedule, LowStorageRungeKutta, Multistep, RungeKutta +from solprop.stepper.schedule import LANDING_ULPS, replay_tolerance + +LENGTH = 1e-5 +"""The tiny fibre's length, m: ten micrometres.""" + +STEPS = {"dz_max": 1e-6, "dz_init": 1e-6} + +ULP = math.ulp(LENGTH) +"""One representable increment at the run's end, m.""" + + +def grid(length: float = LENGTH) -> EnvelopeGrid: + """Return the tiny fibre's grid.""" + return EnvelopeGrid.from_limits(length, 800e-9, (500e-9, 1.6e-6), 200e-15) + + +def fibre(length: float | None = LENGTH, **keywords) -> Simulation: + """Return a GNLSE fibre that builds in milliseconds; nothing here runs it.""" + arguments = { + "wavelength": 800e-9, + "wavelength_limits": (500e-9, 1.6e-6), + "trange": 200e-15, + "fwhm": 20e-15, + "peak_power": 1.0, + "backend": "numpy_ref", + "noise": None, + **STEPS, + } | keywords + return Simulation.from_gnlse(0.0, length, [0.0, 0.0, -1e-26], **arguments) + + +def settings(**keywords) -> SimulationSettings: + """Return object-route settings with the tiny fibre's steps.""" + return SimulationSettings(backend="numpy_ref", **STEPS, **keywords) + + +def adopted(simulation: Simulation, chosen: SimulationSettings, **keywords): + """Return a direct Simulation of `simulation`'s physics adopting `chosen`.""" + return Simulation( + keywords.pop("grid", simulation.grid), + simulation.modes, + simulation.responses, + simulation._field0, + settings=dataclasses.replace(chosen, controller=simulation.settings.controller), + **keywords, + ) + + +# ------------------------------------------------------------------- the refusals + + +@pytest.mark.parametrize( + ("given", "match"), + [ + ({"save_planes": 80}, r"pass n_save=80"), + ({"save_planes": 0.25}, r"pass \[0\.25\], or n_save"), + ({"save_planes": True}, r"takes positions in m, got True"), + ({"save_planes": [0.1], "n_save": 3}, r"give one of n_save and save_planes"), + ({"n_save": 1}, r"n_save is an integer of at least 2, got 1"), + ({"n_save": 2.5}, r"n_save is an integer of at least 2, got 2\.5"), + ({"n_save": True}, r"n_save is an integer of at least 2, got True"), + ({"save_planes": [0.1, math.nan]}, r"save plane nan is not finite"), + ({"save_planes": [0.2, 0.1]}, r"save plane 0\.1 m follows 0\.2 m"), + ({"save_planes": [0.1, 0.1]}, r"save plane 0\.1 m repeats 0\.1 m"), + ], +) +def test_a_malformed_selector_is_refused_by_name_with_its_fix(given, match): + with pytest.raises(DriverError, match=match) as refused: + settings(**given) + assert refused.value.parameter in ( + "save_planes", + "n_save", + ("save_planes", "n_save"), + ) + + +@pytest.mark.parametrize( + ("selectors", "shown"), + [({"n_save": 5}, "5 planes"), ({}, f"{DEFAULT_N_SAVE} planes (default)")], + ids=["count", "default"], +) +def test_unadopted_settings_print_their_count(selectors, shown): + settings = SimulationSettings(dz_max=1e-3, dz_init=1e-4, **selectors) + assert settings._planes_text() == shown + + +def test_both_selectors_name_how_to_carry_a_count(): + with pytest.raises(DriverError, match=r"dataclasses\.replace\(settings, n_save=N"): + settings(save_planes=[], n_save=2) + + +def test_a_numpy_count_is_a_count(): + assert settings(n_save=np.int64(5)).n_save == 5 + + +# ------------------------------------------------------------- placement and ends + + +def test_a_count_places_that_many_observations_over_the_whole_run(): + simulation = fibre(n_save=5) + planes = np.asarray(simulation.settings.save_planes) + # The entrance is observation 0, so four positions follow it, the last the end. + assert planes.tolist() == np.linspace(0.0, LENGTH, 5)[1:].tolist() + assert planes[-1] == LENGTH == simulation.grid.length + assert simulation.settings.n_save is None + + +def test_neither_selector_takes_the_default_count(): + planes = np.asarray(fibre().settings.save_planes) + assert planes.size + 1 == DEFAULT_N_SAVE + assert planes[-1] == LENGTH + + +def test_positions_short_of_the_length_gain_the_end(): + assert np.asarray( + fibre(save_planes=[LENGTH / 2]).settings.save_planes + ).tolist() == [ + LENGTH / 2, + LENGTH, + ] + + +def test_an_empty_list_records_the_two_endpoints_alone(): + assert np.asarray(fibre(save_planes=[]).settings.save_planes).tolist() == [LENGTH] + + +def test_listed_endpoints_are_kept_once(): + planes = np.asarray( + fibre(save_planes=[0.0, LENGTH / 2, LENGTH]).settings.save_planes + ) + assert planes.tolist() == [LENGTH / 2, LENGTH] + + +@pytest.mark.parametrize( + "end", + [np.nextafter(0.3, 0.0), 0.3, 0.1 + 0.2, 0.3 + LANDING_ULPS * math.ulp(0.3)], + ids=["below", "equal", "sum", "bound"], +) +def test_a_position_within_the_landing_slack_of_the_end_is_the_end(end): + planes = _observation_planes(np.array([0.1, end]), None, entrance=0.0, length=0.3) + assert planes.tolist() == [0.1, 0.3] + + +def test_a_position_just_beyond_the_slack_is_refused_and_one_below_it_kept(): + ulp = math.ulp(0.3) + beyond = 0.3 + (LANDING_ULPS + 1) * ulp + with pytest.raises(DriverError, match="beyond the end of the run"): + _observation_planes(np.array([beyond]), None, entrance=0.0, length=0.3) + below = 0.3 - (LANDING_ULPS + 1) * ulp + planes = _observation_planes(np.array([below]), None, entrance=0.0, length=0.3) + assert planes.tolist() == [below, 0.3] + + +def test_a_position_beyond_the_end_names_the_interval_and_the_fix(): + with pytest.raises( + DriverError, match=r"raise length \(or grid\.length\)" + ) as refused: + fibre(save_planes=[2 * LENGTH]) + assert "[0 m, 1e-05 m]" in str(refused.value) + assert refused.value.parameter == "save_planes" + + +def test_resolving_resolved_planes_adds_nothing(): + first = _observation_planes(np.array([0.1]), None, entrance=0.0, length=0.3) + again = _observation_planes(first, None, entrance=0.0, length=0.3) + assert again.tolist() == first.tolist() == [0.1, 0.3] + simulation = fibre(n_save=4) + resolved = simulation.settings + simulation.settings = resolved + assert simulation.settings is resolved + + +def test_a_count_and_the_positions_it_resolves_to_are_one_run(): + counted = fibre(n_save=4) + listed = fibre(save_planes=counted.settings.save_planes) + assert ( + np.asarray(listed.settings.save_planes).tolist() + == np.asarray(counted.settings.save_planes).tolist() + ) + assert ( + listed.metadata().configuration_hash() + == counted.metadata().configuration_hash() + ) + + +def test_an_object_route_runs_to_its_grid_length(): + simulation = fibre() + direct = adopted(simulation, settings(n_save=3)) + assert np.asarray(direct.settings.save_planes).tolist() == [LENGTH / 2, LENGTH] + + +# ------------------------------------------------------------- interior launches + + +def test_a_count_at_an_interior_launch_spans_the_launched_interval(): + simulation = fibre() + launched = adopted(simulation, settings(n_save=4), initial_z=4e-6) + # Three steps of 2 um from the launch at 4 um: not the zero-based lattice. + np.testing.assert_array_equal( + launched.settings.save_planes, np.linspace(4e-6, LENGTH, 4)[1:] + ) + assert np.asarray(launched.settings.save_planes)[-1] == LENGTH + + +def test_an_interior_launch_on_the_zero_based_lattice_still_spans_its_interval(): + simulation = fibre() + launched = adopted(simulation, settings(n_save=3), initial_z=5e-6) + # 5 um is on the lattice of a zero-based count of three; the count is not. + np.testing.assert_array_equal( + launched.settings.save_planes, np.linspace(5e-6, LENGTH, 3)[1:] + ) + + +def test_a_position_before_an_interior_launch_is_refused(): + simulation = fibre() + with pytest.raises(DriverError, match="before the entrance, initial_z"): + adopted(simulation, settings(save_planes=[2e-6]), initial_z=4e-6) + + +def test_with_input_keeps_the_resolved_observations_beyond_the_launch(): + simulation = fibre(n_save=5) + derived = simulation.with_input(simulation._field0, initial_z=3e-6) + # No new count: the parent's resolved positions beyond 3 um, the end among them. + np.testing.assert_array_equal( + derived.settings.save_planes, np.linspace(0.0, LENGTH, 5)[2:] + ) + assert derived.initial_z == 3e-6 + + +# --------------------------------------------------------- adoption and replacement + + +def test_replaced_settings_are_resolved_against_the_run(): + simulation = fibre(n_save=2) + simulation.settings = dataclasses.replace( + simulation.settings, save_planes=None, n_save=3 + ) + assert np.asarray(simulation.settings.save_planes).tolist() == [LENGTH / 2, LENGTH] + + +def test_after_translation_a_count_equal_to_the_planes_is_no_change(): + simulation = fibre(n_save=3) + simulation.translate() + simulation.settings = dataclasses.replace( + simulation.settings, save_planes=None, n_save=3 + ) + with pytest.raises(DriverError, match="a new save_planes would be ignored"): + simulation.settings = dataclasses.replace( + simulation.settings, save_planes=None, n_save=4 + ) + + +def test_resolved_settings_reused_at_another_length_are_validated_afresh(): + simulation = fibre(save_planes=[LENGTH / 2]) + resolved = simulation.settings + longer = adopted(simulation, resolved, grid=grid_at(simulation.grid, 2 * LENGTH)) + assert np.asarray(longer.settings.save_planes).tolist() == [ + LENGTH / 2, + LENGTH, + 2 * LENGTH, + ] + with pytest.raises(DriverError, match="beyond the end of the run"): + adopted(simulation, resolved, grid=grid_at(simulation.grid, LENGTH / 4)) + + +# ------------------------------------------------------------- the length, once + + +def test_a_grid_alone_gives_the_length(): + simulation = fibre(None, grid=grid(), wavelength_limits=None, trange=None) + assert np.asarray(simulation.settings.save_planes)[-1] == LENGTH + + +def test_a_length_within_the_slack_of_the_grid_s_is_the_grid_s(): + near = np.nextafter(LENGTH, 0.0) + simulation = fibre(near, grid=grid(), wavelength_limits=None, trange=None) + assert np.asarray(simulation.settings.save_planes)[-1] == LENGTH + + +def test_a_length_and_a_grid_that_disagree_are_refused_naming_both(): + with pytest.raises(DriverError, match=r"length = 2e-05 m and grid\.length = 1e-05"): + fibre(2 * LENGTH, grid=grid(), wavelength_limits=None, trange=None) + + +@pytest.mark.parametrize("route", ["gnlse", "capillary", "waveguide"]) +def test_a_keyword_route_without_a_length_or_a_grid_is_refused(route): + with pytest.raises(DriverError, match="a length or a grid is required"): + if route == "gnlse": + fibre(None) + elif route == "capillary": + Simulation.from_capillary(125e-6, gas="He", wavelength=800e-9) + else: + Simulation.from_waveguide([], gas="He", wavelength=800e-9) + + +def test_a_capillary_without_its_gas_is_refused(): + with pytest.raises(DriverError, match="needs its fill"): + Simulation.from_capillary(125e-6, 0.1, wavelength=800e-9) + + +# ---------------------------------------------------------------- replay schedules + + +def history(steps: np.ndarray, z_start: float = 0.0) -> FixedSchedule: + """Return the schedule a run that accepted `steps` from `z_start` records.""" + starts = z_start + np.concatenate(([0.0], np.cumsum(steps)[:-1])) + return FixedSchedule.from_history(starts, steps) + + +def drift(schedule: FixedSchedule) -> float: + """Return how far a schedule's step sum ends from the run's length, in ulps.""" + return (schedule.z_end - LENGTH) / math.ulp(LENGTH) + + +@pytest.mark.parametrize( + ("schedule", "below"), + [ + # 160 and 300 equal steps of a 10 um run end 13 ulps short and 21 ulps past + # it: beyond the landing slack, within replay_tolerance's step count. + (history(np.full(160, LENGTH / 160)), True), + (history(np.full(300, LENGTH / 300)), False), + (FixedSchedule.uniform(0.0, LENGTH - 3 * math.ulp(LENGTH), LENGTH / 100), True), + ( + FixedSchedule.uniform(0.0, LENGTH + 3 * math.ulp(LENGTH), LENGTH / 100), + False, + ), + ], + ids=["history-below", "history-above", "uniform-below", "uniform-above"], +) +def test_a_replayed_schedule_whose_sum_drifts_within_its_tolerance_is_accepted( + schedule, below +): + assert (drift(schedule) < 0) == below and drift(schedule) != 0 + assert abs(schedule.z_end - LENGTH) <= replay_tolerance(schedule, LENGTH) + simulation = fibre(schedule=schedule, integrator=LowStorageRungeKutta(), n_save=2) + assert simulation.settings.schedule is schedule + assert np.asarray(simulation.settings.save_planes)[-1] == LENGTH + + +def test_an_adaptive_run_s_own_history_replays_over_the_same_run(): + # No collar, whose in-stage stability would cap the replayed steps. + run = fibre(n_save=2, integrator=RungeKutta(), absorber=False).run(progress="none") + schedule = FixedSchedule.from_history( + np.asarray(run["step_history/z"]), + np.asarray(run["step_history/h"]), + np.asarray(run["step_history/accepted"]), + ) + replayed = fibre( + n_save=2, integrator=RungeKutta(), absorber=False, schedule=schedule + ) + assert replayed.run(progress="none")["z"][-1] == LENGTH + + +@pytest.mark.parametrize( + "schedule", + [ + history(np.full(10, LENGTH / 20)), + history(np.full(30, LENGTH / 20)), + history(np.full(10, LENGTH / 10), z_start=LENGTH / 10), + ], + ids=["shorter", "longer", "late-start"], +) +def test_a_history_that_does_not_cover_the_run_is_refused_before_it_runs(schedule): + with pytest.raises(DriverError, match="the replayed schedule") as refused: + fibre(schedule=schedule, integrator=LowStorageRungeKutta(), n_save=2) + assert refused.value.rule == "replay-interval" + + +def test_a_uniform_schedule_over_the_run_is_accepted(): + schedule = FixedSchedule.uniform(0.0, LENGTH, LENGTH / 7) + assert ( + fibre(schedule=schedule, integrator=Multistep()).settings.schedule is schedule + ) + + +@pytest.mark.parametrize( + ("schedule", "match"), + [ + (FixedSchedule.uniform(0.0, LENGTH / 2, LENGTH / 10), "ends at"), + (FixedSchedule.uniform(0.0, 2 * LENGTH, LENGTH / 10), "ends at"), + (FixedSchedule(np.full(10, LENGTH / 10), 1e-7), "starts at"), + ], + ids=["shorter", "longer", "late-start"], +) +def test_a_schedule_that_does_not_cover_the_run_is_refused_at_adoption(schedule, match): + with pytest.raises(DriverError, match=f"the replayed schedule {match}") as refused: + fibre(schedule=schedule, integrator=Multistep()) + assert refused.value.parameter == "schedule" + + +def test_an_interior_launch_still_refuses_a_schedule(): + simulation = fibre() + replay = settings(schedule=FixedSchedule.uniform(4e-6, LENGTH, 1e-6)) + with pytest.raises( + DriverError, match="refuses the modified noise model and a fixed" + ): + adopted(simulation, replay, initial_z=4e-6) + + +# ------------------------------------------------------- resume to the declared end + + +class CrashError(RuntimeError): + """What an interrupted run raises, standing in for a machine going away.""" + + +class Interrupt(NullReporter): + """Stop a run once it has saved `after` planes.""" + + def __init__(self, after: int) -> None: + self.after, self.seen = after, 0 + + def plane(self, z: float, summary: object) -> None: + del z, summary + self.seen += 1 + if self.seen >= self.after: + raise CrashError(f"stopped after plane {self.seen}") + + +def resumable(**keywords) -> Simulation: + """Return the tiny fibre with five observations, one statistic at each.""" + return fibre( + n_save=5, + integrator=RungeKutta(), + stats=StatsSpec(names=("energy",)), + **keywords, + ) + + +def ends_complete(path) -> None: + """Assert a file holds its whole run, ending at the grid's length.""" + state = resume(path) + assert state.plane.z == LENGTH + assert state.n_saved == 5 + assert state.checkpoint is None + assert state.outcome is not None and state.outcome.status == "complete" + + +def test_an_interrupted_file_resumes_to_the_declared_end(tmp_path): + path = tmp_path / "run.h5" + with pytest.raises(CrashError): + resumable().run(path, progress=Interrupt(2)) + assert resume(path).plane.z < LENGTH + resumable().run(path, resume=True, progress="none") + ends_complete(path) + + +def test_a_file_holding_a_terminal_checkpoint_resumes_to_the_declared_end( + tmp_path, monkeypatch +): + path = tmp_path / "run.h5" + original = NumpyRefBackend.stats + calls: list[int] = [] + + def fail_at_the_end(self, spec): + calls.append(1) + if len(calls) == 5: + raise CrashError("the last plane's statistics failed") + return original(self, spec) + + with monkeypatch.context() as patch: + patch.setattr(NumpyRefBackend, "stats", fail_at_the_end) + with pytest.raises(CrashError): + resumable().run(path, progress="none") + stopped = resume(path) + # The march reached the end; its last plane was never saved. + assert stopped.checkpoint is not None and stopped.n_saved < 5 + resumable().run(path, resume=True, progress="none") + ends_complete(path) + + +def test_a_completed_file_resumes_to_its_end_and_saves_nothing_more(tmp_path): + path = tmp_path / "run.h5" + resumable().run(path, progress="none") + resumable().run(path, resume=True, progress="none") + ends_complete(path) + + +def test_a_recipe_s_file_resumes_to_the_declared_end_from_the_file_alone(tmp_path): + recipe = Recipe.from_keywords( + "gnlse", + gamma=0.0, + length=LENGTH, + betas=[0.0, 0.0, -1e-26], + wavelength=800e-9, + wavelength_limits=[500e-9, 1.6e-6], + trange=200e-15, + fwhm=20e-15, + peak_power=1.0, + n_save=5, + backend="numpy_ref", + noise=None, + dz_max=1e-6, + dz_init=1e-6, + ) + path = tmp_path / "run.h5" + with pytest.raises(CrashError): + recipe.build().run(path, progress=Interrupt(2)) + resume_file(path, progress="none") + ends_complete(path) diff --git a/tests/driver/test_scaffold.py b/tests/driver/test_scaffold.py index 8c8deedbc..e2d4e45dc 100644 --- a/tests/driver/test_scaffold.py +++ b/tests/driver/test_scaffold.py @@ -70,7 +70,7 @@ def test_the_fundamental_soliton_is_stationary_with_its_phase(grid, problem): def test_saving_planes_does_not_change_the_steps(grid, problem): initial = soliton(grid, 1) z, spectra = propagate_fixed_rk4( - problem, grid, initial, DISPERSION_LENGTH, 40, n_save=4 + problem, grid, initial, DISPERSION_LENGTH, 40, n_save=5 ) _, direct = propagate_fixed_rk4(problem, grid, initial, DISPERSION_LENGTH, 40) np.testing.assert_allclose(z, np.linspace(0.0, DISPERSION_LENGTH, 5)) @@ -148,11 +148,11 @@ def test_the_scaffold_rejects_a_spectrum_of_the_wrong_shape(grid, problem): ({"z_end": 0.0}, "z_end must be positive"), ({"z_end": math.inf}, "z_end must be positive"), ({"n_steps": 0}, "n_steps must be at least 1"), - ({"n_save": 0}, "n_save must be at least 1"), - ({"n_steps": 10, "n_save": 3}, "must be a multiple of n_save"), + ({"n_save": 1}, "must be at least 2"), + ({"n_steps": 10, "n_save": 4}, r"must be a multiple of n_save - 1 \(3\)"), ], ) def test_the_scaffold_rejects_a_bad_request(grid, problem, overrides, message): - request = {"z_end": 1.0, "n_steps": 10, "n_save": 1} | overrides + request = {"z_end": 1.0, "n_steps": 10, "n_save": 2} | overrides with pytest.raises(ValueError, match=message): propagate_fixed_rk4(problem, grid, soliton(grid, 1), **request) diff --git a/tests/driver/test_scan_worker_validation.py b/tests/driver/test_scan_worker_validation.py index aadf6ae00..ef04bf8ea 100644 --- a/tests/driver/test_scan_worker_validation.py +++ b/tests/driver/test_scan_worker_validation.py @@ -247,7 +247,7 @@ def test_admission_counts_every_mode_of_a_retained_and_reduced_field(): simulation = capillary(modes=3, length=2e-3) shape = simulation.translate().shape assert shape[0] == 3 - count = len(simulation.settings.save_planes) + 1 + count = len(np.asarray(simulation.settings.save_planes)) + 1 plane = math.prod(shape) * 16 retained = _Work(build, _Options((), "all", (), "none"), "worker") assert retained._output_bytes(simulation, {}) == count * plane + count * 8 diff --git a/tests/driver/test_sep12_sep14_integration.py b/tests/driver/test_sep12_sep14_integration.py index 176639e74..a30f83622 100644 --- a/tests/driver/test_sep12_sep14_integration.py +++ b/tests/driver/test_sep12_sep14_integration.py @@ -372,7 +372,7 @@ def plane(self, z, summary): assert checkpoint is not None and checkpoint.landed # The equal-approach rule may shorten this natural step. Its actual saved # accepted endpoint, rather than the requested step length, defines landing. - assert 0.0 < checkpoint.plane.z < simulation.settings.save_planes[0] + assert 0.0 < checkpoint.plane.z < np.asarray(simulation.settings.save_planes)[0] assert checkpoint.plane.z == ( output["step_history/z"][-1] + output["step_history/h"][-1] ) diff --git a/tests/driver/test_simulation.py b/tests/driver/test_simulation.py index 1ffc24582..9b987ddef 100644 --- a/tests/driver/test_simulation.py +++ b/tests/driver/test_simulation.py @@ -16,6 +16,7 @@ import numpy as np import pytest +from builders import grid_at from solprop._identity import canonical_json from solprop.constants import C from solprop.driver import Simulation, SimulationSettings @@ -160,7 +161,7 @@ def test_the_modes_and_the_profiles_reach_the_backend(narrow_grid, soliton): wavelength=wavelength, width=soliton.tau0, peak_power=soliton.peak_power(1) ) simulation = Simulation( - narrow_grid, + grid_at(narrow_grid, 0.005), fibre.mode, [fibre.kerr], pulse, @@ -199,7 +200,7 @@ def test_a_built_spectrum_is_accepted_as_the_input(narrow_grid, soliton): peak_power=soliton.peak_power(1), ).build(narrow_grid) simulation = Simulation( - narrow_grid, + grid_at(narrow_grid, 0.005), fibre.mode, [fibre.kerr], spectrum, @@ -230,7 +231,7 @@ def test_an_input_that_is_neither_a_pulse_nor_a_spectrum_is_refused( not_a_pulse: Any = SimpleNamespace(build="a pulse, honest") with pytest.raises(DriverError, match="build\\(grid\\) method"): Simulation( - narrow_grid, + grid_at(narrow_grid, 0.005), fibre.mode, [fibre.kerr], not_a_pulse, diff --git a/tests/driver/test_taper_coupling.py b/tests/driver/test_taper_coupling.py index 7afdb6437..a14a7b1fa 100644 --- a/tests/driver/test_taper_coupling.py +++ b/tests/driver/test_taper_coupling.py @@ -199,7 +199,7 @@ def test_the_opt_out_is_the_adiabatic_route_without_a_warning(): list(simulation.responses), simulation._field0, controller=cast("PIController", simulation.settings.controller), - save_planes=simulation.settings.save_planes, + save_planes=np.asarray(simulation.settings.save_planes), dz_max=simulation.settings.dz_max, dz_init=simulation.settings.dz_init, schedule=simulation.settings.schedule, @@ -236,7 +236,7 @@ def test_a_wall_and_the_opt_out_are_refused_together(): list(simulation.responses), simulation._field0, controller=cast("PIController", simulation.settings.controller), - save_planes=simulation.settings.save_planes, + save_planes=np.asarray(simulation.settings.save_planes), dz_max=simulation.settings.dz_max, dz_init=simulation.settings.dz_init, wall=CoherentWall(), @@ -569,7 +569,7 @@ def test_a_second_field_component_beside_the_coupling_is_refused(): list(simulation.responses), field, controller=cast("PIController", simulation.settings.controller), - save_planes=simulation.settings.save_planes, + save_planes=np.asarray(simulation.settings.save_planes), dz_max=simulation.settings.dz_max, dz_init=simulation.settings.dz_init, quadrature=simulation.settings.quadrature, diff --git a/tests/driver/test_tdse_entry.py b/tests/driver/test_tdse_entry.py index 9bade7922..bad95dfcf 100644 --- a/tests/driver/test_tdse_entry.py +++ b/tests/driver/test_tdse_entry.py @@ -204,16 +204,19 @@ def test_statistics_default_excludes_what_a_tdse_response_cannot_supply(): def test_tdse_output_defaults_and_their_explicit_overrides(): final_only = _capillary(tdse=_sae()) assert final_only.settings.step_planes == 1 - assert tuple(final_only.settings.save_planes) == (_LENGTH,) + assert tuple(np.asarray(final_only.settings.save_planes)) == (_LENGTH,) entry = plain(final_only.configuration["tdse_entry"]) assert entry["requested_planes"] == "final_only" assert entry["step_planes"] == {"requested": None, "resolved": 1} no_steps = _capillary(tdse=_sae(), step_planes=0) assert no_steps.settings.step_planes == 0 planes = _capillary(tdse=_sae(), n_save=5) - assert len(planes.settings.save_planes) == 4 and planes.settings.step_planes == 1 + assert ( + len(np.asarray(planes.settings.save_planes)) == 4 + and planes.settings.step_planes == 1 + ) explicit = _capillary(tdse=_sae(), save_planes=[_LENGTH / 2, _LENGTH]) - assert tuple(explicit.settings.save_planes) == (_LENGTH / 2, _LENGTH) + assert tuple(np.asarray(explicit.settings.save_planes)) == (_LENGTH / 2, _LENGTH) assert plain(explicit.configuration["tdse_entry"])["requested_planes"] == ( "explicit" ) @@ -253,7 +256,7 @@ def test_without_tdse_a_representative_call_is_unchanged(): record = { "configuration": serialise(simulation.configuration), "responses": serialise(list(simulation.responses)), - "save_planes": [float(x) for x in simulation.settings.save_planes], + "save_planes": [float(x) for x in np.asarray(simulation.settings.save_planes)], "step_planes": simulation.settings.step_planes, "backend": simulation.settings.backend, "stats": list(stats.names), @@ -270,7 +273,7 @@ def test_without_tdse_a_representative_call_is_unchanged(): / "test_without_tdse_a_representative_call_is_unchanged.npz", ) assert simulation.settings.step_planes == 0 - assert len(simulation.settings.save_planes) == 200 + assert len(np.asarray(simulation.settings.save_planes)) == 200 def test_prop_capillary_forwards_the_tdse_keywords(monkeypatch): diff --git a/tests/moving_guide_cases.py b/tests/moving_guide_cases.py index 084669639..b03655786 100644 --- a/tests/moving_guide_cases.py +++ b/tests/moving_guide_cases.py @@ -25,6 +25,7 @@ import numpy as np +from builders import grid_at, held_collar from coupled_flow_cases import Case, parity_bound from modal_provider_cases import GENERAL_CHI3, grin_grid, grin_provider, make_provider from solprop.driver import Simulation @@ -89,16 +90,22 @@ def kinked_radius(): def moving_simulation(guide, grid, *, steps=STEPS, length=LENGTH, **overrides): - """Return a general modal simulation of a guide on a fixed schedule.""" + """Return a general modal simulation of a guide on a fixed schedule. + + A run ends at its grid's length (SEP 51): the grid is cut at `length`, with the + collar the whole grid gave. + """ + window = grid_at(grid, length) simulation = Simulation.from_waveguide( (), length, provider=guide, - grid=grid, + grid=window, **( { "noise": None, **{ + "absorber": held_collar(window, grid.length), "save_planes": [length], "dz_max": length / steps, "dz_init": length / steps, @@ -159,7 +166,8 @@ def ten_step_simulation(guide, grid, length=LENGTH, **pulse) -> Simulation: (), length, provider=guide, - grid=grid, + # A run ends at its grid's length (SEP 51); no collar is kept. + grid=grid_at(grid, length), save_planes=[length], dz_max=length / STEPS, dz_init=length / STEPS, @@ -375,6 +383,8 @@ def bound_step_problem(descriptors, *, blocks=(), basis_block=None): if basis_block is None else circular_pair(provider_channels(provider), basis_block), ) + # A run ends at its grid's length (SEP 51); its collar is removed below. + grid = grid_at(grid, BOUND_STEP_LENGTH) simulation = Simulation.from_waveguide( (), BOUND_STEP_LENGTH, diff --git a/tests/output/test_callback.py b/tests/output/test_callback.py index 794c9b9c8..459fd7e77 100644 --- a/tests/output/test_callback.py +++ b/tests/output/test_callback.py @@ -223,7 +223,7 @@ def receive(plane: SavedPlane) -> None: handler = CallbackOutput(receive) assert simulation.run(handler, progress="none") is handler - planes = simulation.settings.save_planes + planes = np.asarray(simulation.settings.save_planes) assert handler.n_saved == len(kept) == len(planes) + 1 assert kept == [index < 2 for index in range(len(kept))] # The positions are the save planes, landed on within a relative rounding. @@ -250,7 +250,7 @@ def test_the_fields_setting_says_what_every_plane_carries(backend, fields, carri @pytest.mark.parametrize("backend", available()) def test_the_planes_of_natural_steps_reach_the_callable(backend): simulation = cartesian(backend, replay=False) - end = simulation.settings.save_planes[-1:] + end = np.asarray(simulation.settings.save_planes)[-1:] simulation.settings = dataclasses.replace( simulation.settings, step_planes=2, save_planes=end ) @@ -378,7 +378,7 @@ def test_saving_a_plane_allocates_no_volume(backend): volume = simulation._field0.nbytes handler = _Measured(nothing) simulation.run(handler, progress="none") - assert handler.n_saved == len(simulation.settings.save_planes) + 1 + assert handler.n_saved == len(np.asarray(simulation.settings.save_planes)) + 1 assert max(handler.peaks) < volume / 10 assert max(handler.left) < volume / 10 @@ -648,7 +648,7 @@ def refuse_the_second(plane: SavedPlane) -> None: assert not runner.closed assert runner.run( simulation._field0, output=CallbackOutput(nothing), progress="none" - ).n_saved == handler.n_saved + len(simulation.settings.save_planes) + ).n_saved == handler.n_saved + len(np.asarray(simulation.settings.save_planes)) @pytest.mark.parametrize("backend", available()) diff --git a/tests/output/test_modal_resume.py b/tests/output/test_modal_resume.py index c4be1416a..c85f4c670 100644 --- a/tests/output/test_modal_resume.py +++ b/tests/output/test_modal_resume.py @@ -20,6 +20,7 @@ import numpy as np import pytest +from builders import held_collar from driver.test_resume import read_file, run_until from march_bounds import FIXED_ORDER, assert_stored_matched, simulation_bound from modal_provider_cases import ( @@ -71,10 +72,16 @@ """Every row `RunMetadata._describe` adds for a general modal identity.""" PULSE = {"wavelength": 835e-9, "fwhm": 20e-15, "energy": 1e-12, "shape": "gauss"} +SHORT_Z = GENERAL_Z_END / 10 +"""Length these runs propagate, m: a tenth of the cap.""" + RUN = { # Two steps over a tenth of a millimetre. A resume is an identity statement - # and needs no more; the route's arithmetic is qualified elsewhere. - "save_planes": [GENERAL_Z_END / 20, GENERAL_Z_END / 10], + # and needs no more; the route's arithmetic is qualified elsewhere. A run ends at + # its grid's length (SEP 51), so the grid is that tenth, with the collar the + # millimetre gave. + "save_planes": [GENERAL_Z_END / 20, SHORT_Z], + "absorber": held_collar(general_grid(SHORT_Z), GENERAL_Z_END), "backend": "numpy_ref", "dz_max": GENERAL_Z_END / 40, "dz_init": GENERAL_Z_END / 40, @@ -101,8 +108,8 @@ def at(record, *keys) -> Any: @pytest.fixture(scope="module") def grid(): - """The field grid these runs are on.""" - return general_grid() + """The field grid these runs are on: the tenth of a millimetre they run.""" + return general_grid(SHORT_Z) @pytest.fixture(scope="module") @@ -115,7 +122,7 @@ def build(guide, grid, **overrides): """Return a general modal simulation on this guide and grid.""" return Simulation.from_waveguide( (), - GENERAL_Z_END, + SHORT_Z, provider=guide, grid=grid, **({"noise": None, **PULSE | RUN | overrides}), @@ -449,7 +456,7 @@ def scheduled(guide, grid): planes = [length / 2, length] simulation = Simulation.from_waveguide( (), - GENERAL_Z_END, + SHORT_Z, provider=guide, grid=grid, **( diff --git a/tests/output/test_record_arrays.py b/tests/output/test_record_arrays.py index 7fab3299b..905e15446 100644 --- a/tests/output/test_record_arrays.py +++ b/tests/output/test_record_arrays.py @@ -409,7 +409,7 @@ def test_a_plane_exports_from_a_file_through_the_stored_flux_plan(tmp_path): def test_a_noise_realisation_travels_beside_the_record(tmp_path): - grid = EnvelopeGrid.from_limits(1e-5, 800e-9, (700e-9, 900e-9), 100e-15, thg=False) + grid = EnvelopeGrid.from_limits(0.01, 800e-9, (700e-9, 900e-9), 100e-15, thg=False) simulation = Simulation.from_gnlse( 0.11, 0.01, diff --git a/tests/processing/test_modal_metrics.py b/tests/processing/test_modal_metrics.py index cf8cd3ab3..b0e4f3044 100644 --- a/tests/processing/test_modal_metrics.py +++ b/tests/processing/test_modal_metrics.py @@ -29,6 +29,7 @@ import pytest from numpy.testing import assert_allclose +from builders import held_collar from legacy_geometry import LEGACY_GRID from modal_provider_cases import GENERAL_Z_END, general_grid, general_guide from sessions.runs import run as run_session @@ -68,11 +69,17 @@ pytestmark = pytest.mark.filterwarnings("ignore::solprop.exceptions.BoundaryWarning") PULSE = {"wavelength": 835e-9, "fwhm": 20e-15, "energy": 1e-12, "shape": "gauss"} +SHORT_Z = GENERAL_Z_END / 10 +"""Length these runs propagate, m: a tenth of the cap.""" + RUN = { # Two steps over a tenth of a millimetre: a reconstruction is made on one # saved plane and needs no propagation at all, and the route's arithmetic is # qualified end to end in tests/driver/test_general_modal.py. - "save_planes": [GENERAL_Z_END / 10], + # A run ends at its grid's length (SEP 51), so the grid is that tenth, with the + # collar the millimetre gave. + "save_planes": [SHORT_Z], + "absorber": held_collar(general_grid(SHORT_Z), GENERAL_Z_END), "backend": "numpy_ref", "dz_max": GENERAL_Z_END / 20, "dz_init": GENERAL_Z_END / 20, @@ -90,8 +97,8 @@ @pytest.fixture(scope="module") def grid(): - """The field grid these runs are on.""" - return general_grid() + """The field grid these runs are on: the tenth of a millimetre they run.""" + return general_grid(SHORT_Z) @pytest.fixture(scope="module") @@ -113,8 +120,8 @@ def pair_guide(grid): def route_for(guide, grid): """Return the route a run of these tests builds, rebuilt from the guide. - `_from_general` passes the **last save plane** as `z_max`, so a - caller rebuilding the reference for a reconstruction passes the same: the + `_from_general` passes the run's length, its **last save plane**, as `z_max`, + so a caller rebuilding the reference for a reconstruction passes the same: the tables' `z_span` is part of their identity and a different one is refused by name, which is the point of the check. """ @@ -136,7 +143,7 @@ def tables(guide, grid): def run(guide, grid): """One general modal run, in memory, with its two saved planes.""" simulation = Simulation.from_waveguide( - (), GENERAL_Z_END, provider=guide, grid=grid, **({"noise": None, **PULSE | RUN}) + (), SHORT_Z, provider=guide, grid=grid, **({"noise": None, **PULSE | RUN}) ) return cast("MemoryOutput", simulation.run(progress="none")) @@ -362,7 +369,7 @@ def test_a_coordinate_intensity_is_not_the_physical_one(pair_guide, grid): route = route_for(pair_guide, grid) simulation = Simulation.from_waveguide( (), - GENERAL_Z_END, + SHORT_Z, provider=pair_guide, grid=grid, **({"noise": None, **PULSE | RUN}), diff --git a/tests/recipe/test_pins.py b/tests/recipe/test_pins.py index c8852de38..4c35c08fa 100644 --- a/tests/recipe/test_pins.py +++ b/tests/recipe/test_pins.py @@ -186,7 +186,7 @@ def test_a_pinned_required_keyword_builds_where_a_missing_one_is_refused(): without = pinned({"radius": pin}, drop=("radius", "length")) for call in (without.build, without.resolve, lambda: without.pin_roots("radius")): with pytest.raises( - RecipeError, match=r"^length: a required keyword is missing$" + RecipeError, match=r"^length: a length or a grid is required$" ) as caught: call() assert caught.value.parameter == "length" diff --git a/tests/recipe/test_provenance.py b/tests/recipe/test_provenance.py index ba1e2ef74..29c78b547 100644 --- a/tests/recipe/test_provenance.py +++ b/tests/recipe/test_provenance.py @@ -164,7 +164,7 @@ def test_the_keywords_left_to_the_build_would_move_the_record(): # An explicit first step turns the start-up rule off (SEP 41 section 5.2). recipe = Recipe.example("soliton") simulation = recipe.build() - length = simulation.settings.save_planes[-1] + length = np.asarray(simulation.settings.save_planes)[-1] with_step = recipe.to_dict() with_step["build"]["dz_init"] = float(length * 1e-4) assert _hash(Recipe.from_dict(with_step).build()) != _hash(simulation) diff --git a/tests/recipe/test_save_planes.py b/tests/recipe/test_save_planes.py new file mode 100644 index 000000000..eaa270b45 --- /dev/null +++ b/tests/recipe/test_save_planes.py @@ -0,0 +1,232 @@ +# SPDX-FileCopyrightText: 2026 John C. Travers and contributors +# +# SPDX-License-Identifier: GPL-3.0-or-later + +"""A recipe's saved planes and length under SEP 51's one rule. + +The refusals a recipe meets are the driver's, reported as a +:class:`~solprop.recipe.RecipeError` against the keyword; a count in an object route's +``[build.settings]`` is ``n_save``; and the resolved recipe writes the run's canonical +positions at the level the route reads them, so a later change of a default count +cannot change the rebuilt run. +""" + +import warnings +from typing import Any, cast + +import numpy as np +import pytest + +from driver.test_tdse_entry import _LENGTH as TDSE_LENGTH +from driver.test_tdse_entry import _sae as tdse_response +from recipe.test_free_space import RADIAL +from recipe.test_recipe import GNLSE +from solprop.driver import Simulation +from solprop.driver import settings as settings_module +from solprop.exceptions import DriverError, MaterialRangeWarning +from solprop.output.hdf5 import open_file +from solprop.recipe import Recipe, RecipeError, provenance + +pytestmark = pytest.mark.filterwarnings("ignore::solprop.exceptions.BoundaryWarning") + +LISTED = 'save_planes = ["0.5 mm", "1 mm"]' +"""The radial recipe's own positions, which each case here replaces.""" + + +def _hash(simulation) -> str: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return simulation.metadata().configuration_hash() + + +def radial(selector: str) -> Recipe: + """Return the radial recipe with its settings' planes written as `selector`.""" + return Recipe.loads(RADIAL.replace(LISTED, selector)) + + +# ------------------------------------------------------------------- refusals + + +@pytest.mark.parametrize( + ("selector", "match", "path"), + [ + ("save_planes = 80", "write n_save = 80", "settings.save_planes"), + ( + 'save_planes = "0.25 mm"', + r"pass \[0\.00025\], or n_save", + "settings.save_planes", + ), + ("n_save = 1", "n_save is an integer of at least 2", "settings.n_save"), + ( + 'save_planes = ["1 mm"]\nn_save = 3', + "give one of n_save and save_planes", + "settings.save_planes", + ), + ( + 'save_planes = ["2 mm"]', + r"raise length \(or grid\.length\)", + "settings.save_planes", + ), + ], + ids=["count", "lone", "small", "both", "beyond"], +) +def test_an_object_route_recipe_refuses_what_the_driver_refuses(selector, match, path): + recipe = radial(selector) + with pytest.raises(RecipeError, match=match) as refused: + recipe.build() + assert refused.value.parameter == path + errors = [issue for issue in recipe.check() if issue.severity == "error"] + assert [issue.parameter for issue in errors] == [path] + + +def test_another_refusal_of_the_settings_keeps_its_own_type(): + # Only the refusals SEP 51 states become the recipe's; any other stays the driver's. + recipe = radial(f"{LISTED}\nnode_budget = -1") + with pytest.raises(DriverError, match="node_budget must be a positive") as refused: + recipe.build() + assert not isinstance(refused.value, RecipeError) + + +def test_a_keyword_route_recipe_refuses_an_integer_save_planes(): + with pytest.raises(RecipeError, match="write n_save = 80") as refused: + Recipe.loads(GNLSE.replace("n_save = 3", "save_planes = 80")).build() + assert refused.value.parameter == "save_planes" + + +def test_a_keyword_route_recipe_refuses_a_length_its_grid_disagrees_with(): + text = GNLSE.replace( + 'wavelength_limits = ["500 nm", "2 um"]\ntrange = "4 ps"\n', + 'grid = { type = "EnvelopeGrid.from_limits", length = "2 cm", ' + 'reference_wavelength = "835 nm", wavelength_limits = ["500 nm", "2 um"], ' + 'trange = "4 ps" }\n', + ) + with pytest.raises(RecipeError, match=r"length = 0\.01 m and grid\.length = 0\.02"): + Recipe.loads(text).build() + + +# ------------------------------------------------------------------ the selectors + + +def test_an_object_route_recipe_takes_a_count_over_its_grid_length(): + simulation = radial("n_save = 81").build() + planes = np.asarray(simulation.settings.save_planes) + assert planes.tolist() == np.linspace(0.0, 1e-3, 81)[1:].tolist() + assert planes[-1] == simulation.grid.length + + +def test_an_object_route_recipe_without_a_selector_takes_the_default_count(): + simulation = radial("").build() + assert ( + np.asarray(simulation.settings.save_planes).size + 1 + == settings_module.DEFAULT_N_SAVE + ) + + +def test_the_count_and_its_positions_build_the_same_run(): + counted = radial("n_save = 3").build() + listed = radial(LISTED).build() + assert _hash(counted) == _hash(listed) + + +# ------------------------------------------------------------- the resolved recipe + + +@pytest.mark.parametrize( + "selector", ["n_save = 5", LISTED, 'save_planes = ["0.5 mm"]', ""] +) +def test_the_resolved_recipe_writes_the_canonical_positions_in_the_settings(selector): + recipe = radial(selector) + simulation = recipe.build() + document = provenance.resolved_document(recipe, simulation) + table = cast("dict[str, object]", document["build"]["settings"]) + assert "n_save" not in table + assert table["save_planes"] == np.asarray(simulation.settings.save_planes).tolist() + assert "save_planes" not in document["build"] + assert _hash(Recipe.from_dict(document).build()) == _hash(simulation) + + +def test_a_resolved_recipe_does_not_depend_on_the_default_count(monkeypatch): + recipe = radial("") + simulation = recipe.build() + document = provenance.resolved_document(recipe, simulation) + monkeypatch.setattr(settings_module, "DEFAULT_N_SAVE", 11) + assert np.asarray(radial("").build().settings.save_planes).size == 10 + assert _hash(Recipe.from_dict(document).build()) == _hash(simulation) + + +def test_a_keyword_route_s_resolved_recipe_drops_its_count(): + recipe = Recipe.loads(GNLSE) + simulation = recipe.build() + document = provenance.resolved_document(recipe, simulation) + assert "n_save" not in document["build"] + assert document["build"]["save_planes"] == [0.005, 0.01] + assert _hash(Recipe.from_dict(document).build()) == _hash(simulation) + + +# ------------------------------------------------- defaults written out resolved + + +def tiny_fibre() -> Recipe: + """Return a ten-micrometre GNLSE recipe with no plane selector.""" + return Recipe.from_keywords( + "gnlse", + gamma=0.0, + length=1e-5, + betas=[0.0, 0.0, -1e-26], + wavelength=800e-9, + wavelength_limits=[500e-9, 1.6e-6], + trange=200e-15, + fwhm=20e-15, + peak_power=1.0, + backend="numpy_ref", + noise=None, + dz_max=1e-6, + dz_init=1e-6, + ) + + +def test_a_rebuilt_run_keeps_its_hash_when_the_default_count_changes( + tmp_path, monkeypatch +): + path = tmp_path / "run.h5" + tiny_fibre().build().run(path, progress="none") + with open_file(path) as stored: + assert stored.metadata is not None + recorded = stored.metadata.configuration_hash() + monkeypatch.setattr(settings_module, "DEFAULT_N_SAVE", 11) + assert np.asarray(tiny_fibre().build().settings.save_planes).size == 10 + rebuilt = Recipe.from_output(path, resolved=True).build() + assert _hash(rebuilt) == recorded + + +def test_the_tdse_capillary_s_defaults_are_written_out_resolved(): + """A recipe cannot hold a TDSE response (``tdse`` has no recipe form), so the + resolved document is checked at construction: the route's two observations and + every natural step are written as values, not left to the defaults.""" + keywords: dict[str, Any] = { + "radius": 256e-6, + "length": TDSE_LENGTH, + "gas": "He", + "pressure": 0.1, + "wavelength": 800e-9, + "wavelength_limits": [400e-9, 1.6e-6], + "trange": 60e-15, + "fwhm": 6e-15, + "energy": 1e-12, + "modes": 1, + "n_r": 4, + "noise": None, + "dz_init": 2.0**-20, + "dz_max": 2.0**-20, + } + recipe = Recipe.from_keywords("capillary", **keywords) + # Python takes the window's limits as a pair, the recipe as a list. + python: dict[str, Any] = keywords | {"wavelength_limits": (400e-9, 1.6e-6)} + with warnings.catch_warnings(): + warnings.simplefilter("ignore", MaterialRangeWarning) + simulation = Simulation.from_capillary(**python, tdse=tdse_response()) + document = provenance.resolved_document(recipe, simulation) + build = document["build"] + assert build["save_planes"] == [TDSE_LENGTH] + assert build["step_planes"] == 1 + assert "n_save" not in build diff --git a/tests/record_routes.py b/tests/record_routes.py index 3b28e16ca..70bbde2cd 100644 --- a/tests/record_routes.py +++ b/tests/record_routes.py @@ -13,6 +13,7 @@ import warnings from collections.abc import Callable +from builders import grid_at, held_collar from modal_provider_cases import general_grid, general_guide from solprop.boundaries import absorber from solprop.driver import Simulation, SimulationSettings @@ -118,12 +119,16 @@ def cartesian() -> Simulation: def general() -> Simulation: """Return a general modal run on a provider's guide.""" - grid = general_grid() + window = general_grid() + # A run ends at its grid's length (SEP 51): the millimetre grid cut at the run's + # tenth, with the collar the millimetre gave. + grid = grid_at(window, 1e-4) return Simulation.from_waveguide( (), 1e-4, - provider=general_guide(grid=grid), + provider=general_guide(grid=window), grid=grid, + absorber=held_collar(grid, window.length), fwhm=30e-15, energy=1e-9, wavelength=800e-9, diff --git a/tests/service/test_record.py b/tests/service/test_record.py index 040756b61..134485a77 100644 --- a/tests/service/test_record.py +++ b/tests/service/test_record.py @@ -99,8 +99,14 @@ def test_progress_is_kept_on_a_period_and_the_summary_has_the_latest( def test_a_quiet_run_still_beats(tmp_path, monkeypatch): monkeypatch.setattr(record, "HEARTBEAT", 0.05) log = EventLog(tmp_path, "r1") - time.sleep(0.3) + # Poll to a generous deadline rather than read once after a fixed sleep: a loaded + # runner can delay the writer thread, and on Windows a read that meets the summary's + # atomic replace fails and reads as no summary (issue #664). + deadline = time.monotonic() + 10.0 status = read_status(tmp_path) + while status is None and time.monotonic() < deadline: + time.sleep(0.05) + status = read_status(tmp_path) log.close() assert status is not None and status["run_id"] == "r1" diff --git a/tests/sessions/test_native_session_history.py b/tests/sessions/test_native_session_history.py index b945fec00..8db33a048 100644 --- a/tests/sessions/test_native_session_history.py +++ b/tests/sessions/test_native_session_history.py @@ -26,6 +26,7 @@ import numpy as np import pytest +from builders import grid_at, held_collar from sessions.executors import ( IDENTITY, PLANES, @@ -553,10 +554,16 @@ def _noisy(noise: Any, *, check: bool, march: str = "adams") -> Any: from solprop.pulses import SechPulse # noqa: PLC0415 - beside its one use from solprop.stepper import LowStorageRungeKutta # noqa: PLC0415 - grid = window() - method: dict[str, Any] = {"integrator": Multistep()} + # A run ends at its grid's length (SEP 51): the metre window cut at the run's + # length, with the collar the metre gave. + grid = grid_at(window(), LENGTH) + method: dict[str, Any] = { + "integrator": Multistep(), + "absorber": held_collar(grid, window().length), + } if march == "low-storage": method = { + "absorber": method["absorber"], "integrator": LowStorageRungeKutta(), "schedule": FixedSchedule.uniform( 0.0, LENGTH, LENGTH / 80, save_planes=list(PLANES) diff --git a/tests/test_benchmark_cases.py b/tests/test_benchmark_cases.py index e06f036ab..d0386b479 100644 --- a/tests/test_benchmark_cases.py +++ b/tests/test_benchmark_cases.py @@ -67,11 +67,19 @@ def test_runs_save_evenly_to_their_stop_and_a_fraction_stops_early(): case = CASES["argon_blueshift"] full = build(configuration("argon_blueshift")) np.testing.assert_allclose( - full.settings.save_planes, np.linspace(0, case.length, case.planes + 1)[1:] + np.asarray(full.settings.save_planes), + np.linspace(0, case.length, case.planes + 1)[1:], ) short = build(configuration("argon_blueshift", fraction=0.25)) - assert short.settings.save_planes[-1] == pytest.approx(case.length / 4) - assert short.grid.length == case.length + assert np.asarray(short.settings.save_planes)[-1] == pytest.approx(case.length / 4) + # A run ends at its grid's length (SEP 51): the shortened case is the whole one on + # its grid cut at the stop, its collar and steps those of the whole length. + assert short.grid.length == np.asarray(short.settings.save_planes)[-1] + assert full.settings.absorber is not None and short.settings.absorber is not None + assert short.settings.absorber.reference_length == ( + full.settings.absorber.reference_length + ) + assert short.settings.dz_max == full.settings.dz_max def test_fixed_step_cases_run_their_schedule_and_refuse_overrides(): diff --git a/tests/test_benchmark_guides.py b/tests/test_benchmark_guides.py index 6b7265f2c..71747ee41 100644 --- a/tests/test_benchmark_guides.py +++ b/tests/test_benchmark_guides.py @@ -47,7 +47,8 @@ def test_wall_cases_keep_full_profiles(name): def test_linear_grin_launch_is_configurable_before_translation(stepper): case = CASES["grin_linear"] simulation = build(configuration("grin_linear", stepper)) - assert simulation.grid.length == 1e-3 + # The millimetre grid cut at the beat length the run ends at (SEP 51). + assert simulation.grid.length == case.length waveguide = simulation.configuration["waveguide"] assert isinstance(waveguide, dict) assert waveguide["length"] == case.length diff --git a/tests/translate/test_routes.py b/tests/translate/test_routes.py index bc4f223eb..071f7951b 100644 --- a/tests/translate/test_routes.py +++ b/tests/translate/test_routes.py @@ -96,10 +96,11 @@ def spatial(kind): def general(): """A general modal guide: the general route.""" - grid = general_grid() + # Translated, not run: the grid is the tenth it would run (SEP 51). + grid = general_grid(GENERAL_Z_END / 10) return Simulation.from_waveguide( (), - GENERAL_Z_END, + GENERAL_Z_END / 10, provider=general_guide(grid=grid), grid=grid, noise=None,