From 3db9d567ea69e21c791dfba47e25c4406549a69a Mon Sep 17 00:00:00 2001 From: John Travers Date: Sun, 15 Nov 2026 19:09:07 +0000 Subject: [PATCH 1/3] Refuse a bare integer save_planes and share the n_save placement SimulationSettings read save_planes=80 as one plane at z = 80 m. A bare integer is now refused with a pointer to counted_save_planes, the new public helper that places a count as n_save does (z = 0 counted, the end included); n_save uses it too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XGENPwwkUUG9KSAwneHjgH --- src/solprop/driver/settings.py | 137 ++++++++++++++++++++++++++------ tests/driver/test_simulation.py | 57 +++++++++++++ 2 files changed, 168 insertions(+), 26 deletions(-) diff --git a/src/solprop/driver/settings.py b/src/solprop/driver/settings.py index 2276c5543..0fa73a8c6 100644 --- a/src/solprop/driver/settings.py +++ b/src/solprop/driver/settings.py @@ -55,6 +55,7 @@ "LOW_STORAGE_BACKENDS", "NoiseSetting", "SimulationSettings", + "counted_save_planes", "default_collar", "keyword_settings", ] @@ -154,7 +155,11 @@ class SimulationSettings(Displayed): 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. + planes whichever type they passed and therefore hash alike. A bare integer is + refused: it would read as one plane that many metres away, but means a count, + which the settings cannot place without the propagation length. + :func:`counted_save_planes` places a count as ``n_save`` does, and a recipe's + settings table takes ``save_planes = 80`` and places it over ``grid.length``. dz_max : float Cap on the controller's proposal, m. dz_init : float @@ -325,9 +330,10 @@ 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 the save planes are empty, not increasing, not positive, or a bare integer + or boolean. 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 ``fields='planes'`` beside `step_planes`. Examples @@ -341,6 +347,13 @@ class SimulationSettings(Displayed): ... ) >>> settings.save_planes.tolist(), settings.backend ([0.5, 1.0], 'numpy_ref') + + A count of planes is placed over a length first: + + >>> from solprop.driver.settings import counted_save_planes + >>> counted = counted_save_planes(1.0, 5) + >>> SimulationSettings(save_planes=counted, dz_max=0.1, dz_init=1e-3).save_planes + array([0.25, 0.5 , 0.75, 1. ]) """ controller: PIController | None = None @@ -480,22 +493,10 @@ def __post_init__(self) -> None: Raises ------ DriverError - If the planes are empty, not increasing, or not positive, or if - `resume_history` is not a boolean or ``None``. + If the planes are empty, not increasing, not positive, or a bare integer + or boolean, 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") - object.__setattr__(self, "save_planes", planes) + object.__setattr__(self, "save_planes", _adopted_planes(self.save_planes)) refusal = field_retention_refusal(self.fields, self.field_planes) if refusal is not None: raise DriverError(refusal, parameter=("fields", "field_planes")) @@ -908,6 +909,96 @@ def _same_setting(old: object, new: object) -> bool: return False +def _adopted_planes( + save_planes: Float[np.ndarray, " n_z"] | Sequence[float] | float, +) -> Float[np.ndarray, " n_z"]: + """Return the save planes as settings hold them: checked positions, read-only. + + A lone number, which the annotation of the field excludes, reaches here unchecked + in production, so it is admitted and judged here. + + - Returns: a float64 array of positive, increasing positions in m. + """ + if isinstance(save_planes, bool | np.bool_ | int | np.integer): + # A bare integer means a count (issue #533), and np.reshape would read it as + # one plane that many metres away. + msg = ( + f"save_planes={save_planes!r} is not a list of positions: an integer " + "counts planes, which settings cannot place without the propagation " + f"length; pass counted_save_planes(grid.length, {save_planes!r}) for that " + "many planes counting z = 0, as n_save places them, or the positions in m" + ) + raise DriverError(msg, parameter="save_planes") + planes = frozen_copy(np.reshape(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") + return planes + + +def counted_save_planes( + length: float, count: int, *, name: str = "save_planes" +) -> Float[np.ndarray, " n_z"]: + """Place a count of save planes evenly over a propagation length. + + The one rule for ``n_save`` on the keyword routes and for an integer + ``save_planes`` in a recipe's settings table: ``count`` planes span ``[0, length]`` + with both ends included, and the one at ``z = 0``, which every run stores, is left + out of the positions returned. + + Parameters + ---------- + length : float + Propagation length, m, positive: ``grid.length`` on an object route. + count : int + Planes counting the one at ``z = 0``, at least 2. + name : str, optional + The keyword the count was given as, named in a refusal. + + Returns + ------- + numpy.ndarray + The ``count - 1`` positions after ``z = 0``, m, the last equal to `length`, + shape ``(count - 1,)``. + + Raises + ------ + DriverError + If `count` is a boolean, not an integer (a float is refused even when it is a + whole number), or below 2, or `length` is not positive. + + Examples + -------- + >>> from solprop.driver.settings import counted_save_planes + >>> counted_save_planes(0.25, 5).tolist() + [0.0625, 0.125, 0.1875, 0.25] + """ + if isinstance(count, bool | np.bool_) or not isinstance(count, int | np.integer): + msg = f"{name} counts planes, so it takes an integer, not {count!r}" + raise DriverError(msg, parameter=name) + if count < 2: + msg = ( + f"{name} counts the plane at z = 0, so it must be at least 2, got {count}; " + "a run always stores the entrance" + ) + raise DriverError(msg, parameter=name) + if not length > 0.0: + msg = ( + f"{name} = {count} counts planes over a propagation length of " + f"{length!r} m, which must be positive" + ) + raise DriverError(msg, parameter=name) + return np.linspace(0.0, length, int(count))[1:] + + def _save_planes( length: float, save_planes: Sequence[float] | np.ndarray | None, @@ -927,13 +1018,7 @@ def _save_planes( ) 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: - 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" - ) - raise DriverError(msg, parameter="n_save") - return np.linspace(0.0, length, count)[1:] + return counted_save_planes(length, count, name="n_save") def _scheme(settings: SimulationSettings) -> AbsorberScheme: diff --git a/tests/driver/test_simulation.py b/tests/driver/test_simulation.py index aacd515e7..e4411b4fd 100644 --- a/tests/driver/test_simulation.py +++ b/tests/driver/test_simulation.py @@ -16,10 +16,12 @@ import numpy as np import pytest +from runtime_types import unchecked from solprop.constants import C from solprop.driver import Simulation, SimulationSettings from solprop.driver import settings as settings_module from solprop.driver import simulation as simulation_module +from solprop.driver.settings import counted_save_planes from solprop.exceptions import DriverError, MaterialRangeWarning from solprop.nonlinear.gnlse import problem_from from solprop.profiles import Constant @@ -103,6 +105,61 @@ def test_the_backend_alone_may_change_after_translation(build_simulation): assert handler.metadata.backend.name == "numpy_ref" +def test_a_counted_save_planes_is_placed_as_n_save_places_its_planes( + build_simulation, +): + """One rule for n_save and a count of planes: z = 0 counted, the end included.""" + simulation = build_simulation(n_save=5) + counted = counted_save_planes(simulation.grid.length, 5) + # The same linspace call on the same length: a structural contract, so exact. + assert counted.tolist() == np.asarray(simulation.settings.save_planes).tolist() + assert counted.size == 4 + assert counted[-1] == simulation.grid.length + + +@pytest.mark.parametrize("count", [80, 2, 0, True]) +def test_a_bare_integer_save_planes_is_refused_not_read_as_metres(count): + """Regression for issue #533: ``save_planes=80`` was one plane at z = 80 m. + + The annotation already excludes an integer; production code runs unchecked, where + the settings themselves must refuse it. + """ + settings = object.__new__(SimulationSettings) + with pytest.raises(DriverError, match="counted_save_planes") as caught: + unchecked(SimulationSettings.__init__)( + settings, save_planes=count, dz_max=0.1, dz_init=1e-3 + ) + assert caught.value.parameter == "save_planes" + + +def test_a_lone_float_save_planes_is_still_one_position(): + """Only an integer is a count; a float, even a whole one, stays metres.""" + settings = object.__new__(SimulationSettings) + unchecked(SimulationSettings.__init__)( + settings, save_planes=2.0, dz_max=0.1, dz_init=1e-3 + ) + assert np.asarray(settings.save_planes).tolist() == [2.0] + + +@pytest.mark.parametrize( + ("length", "count", "match"), + [ + (1.0, 1, "at least 2, got 1"), + (1.0, 0, "at least 2, got 0"), + (1.0, True, "takes an integer, not True"), + (1.0, 80.0, "takes an integer, not 80.0"), + (1.0, 2.5, "takes an integer, not 2.5"), + (0.0, 5, "must be positive"), + ], +) +def test_counted_save_planes_refuses_what_is_not_a_count_over_a_length( + length, count, match +): + with pytest.raises(DriverError, match=match) as caught: + unchecked(counted_save_planes)(length, count, name="n_save") + assert caught.value.parameter == "n_save" + + def test_a_setting_that_cannot_be_compared_is_not_the_same(): """A container of arrays has no truth value; it is never taken as unchanged.""" same = settings_module._same_setting From 95e1171201f71aedca09d6c5864c64b354ea662f Mon Sep 17 00:00:00 2001 From: John Travers Date: Sun, 15 Nov 2026 19:09:07 +0000 Subject: [PATCH 2/3] Read an integer save_planes in a recipe as a count over grid.length On the object routes a settings table's save_planes = 80 is now 80 planes over grid.length, counting the entrance, placed with counted_save_planes; check() warns when a listed last plane is not grid.length. TOML keeps the count as written and the Python export writes counted_save_planes(grid.length, 80) (#533). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XGENPwwkUUG9KSAwneHjgH --- src/solprop/recipe/core.py | 31 ++++++++++++- src/solprop/recipe/export.py | 19 +++++++- src/solprop/recipe/metadata.py | 5 +- src/solprop/recipe/registry.py | 57 +++++++++++++++++++++-- tests/recipe/test_free_space.py | 81 +++++++++++++++++++++++++++++++++ 5 files changed, 185 insertions(+), 8 deletions(-) diff --git a/src/solprop/recipe/core.py b/src/solprop/recipe/core.py index 13139a3f2..f4c866d39 100644 --- a/src/solprop/recipe/core.py +++ b/src/solprop/recipe/core.py @@ -549,7 +549,9 @@ def check(self) -> list[RecipeIssue]: its path. If none is refused, the simulation is built and translated, which is where the refusals that depend on several values are found, stopping before a backend is constructed; the first refusal is reported with its parameter, and - every warning of solprop's with its own. It costs a translation: call it on a + every warning of solprop's with its own. On an object route, whose run ends at + its last save plane, a last plane other than ``grid.length``, the length the + grid was built for, is a warning too. It costs a translation: call it on a pause in typing, not on every keystroke. Returns @@ -578,9 +580,12 @@ def check(self) -> list[RecipeIssue]: with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always", SolpropWarning) try: - resolved.build().translate() + simulation = resolved.build() + simulation.translate() except SolpropError as error: issues.append(_issue(error)) + else: + issues.extend(_length_issues(self.route, simulation)) issues.extend( RecipeIssue( str(record.message), @@ -1197,6 +1202,28 @@ def _needs_grid(value: object) -> bool: return False +def _length_issues(route: str, simulation: "Simulation") -> list[RecipeIssue]: + """Return the warning that an object route's run does not end at ``grid.length``. + + The keyword routes place their planes over their own length; an object route's run + ends at its last save plane, which nothing else ties to the length its grid was + built for (issue #533). A counted ``save_planes`` ends there by construction. + """ + if route not in OBJECT_ROUTES: + return [] + end = float(np.max(simulation.settings.save_planes)) + length = float(simulation.grid.length) + # Rounding of a position spelled in another unit, "25.0000 cm", is not a mismatch. + if math.isclose(end, length, rel_tol=1e-9): + return [] + message = ( + f"the run ends at its last save plane, z = {end:g} m, but grid.length is " + f"{length:g} m, the length the grid was built for; make them agree, or give " + "save_planes as an integer count of planes over grid.length" + ) + return [RecipeIssue(message, "settings.save_planes", "warning")] + + def _issue(error: SolpropError, keyword: str | None = None) -> RecipeIssue: """Return the issue a refusal makes. diff --git a/src/solprop/recipe/export.py b/src/solprop/recipe/export.py index ec7789dea..db3f63c64 100644 --- a/src/solprop/recipe/export.py +++ b/src/solprop/recipe/export.py @@ -76,6 +76,18 @@ def expression( # noqa: PLR0911 - one return per kind of value # "none" says None for a keyword only; inside a table it is read as it stands. return repr(decode(value, unit, BuildContext(), path)) + def count(self, count: object, path: str) -> str: + """Return a count of save planes as the call that places it on the grid. + + Settings in Python take positions, so ``save_planes = 80`` is written as + ``counted_save_planes(grid.length, 80)``, which keeps the count as written. + """ + if self.grid is None: # pragma: no cover - an object route names its grid + msg = "a count of save planes is placed over the recipe's grid; give grid" + raise RecipeError(msg, path=path) + self.need("solprop.driver.settings", "counted_save_planes") + return f"counted_save_planes({self.grid}.length, {count!r})" + def factory(self, table: Mapping[str, object], path: str) -> str: """Return a registered type's call. @@ -97,7 +109,12 @@ def factory(self, table: Mapping[str, object], path: str) -> str: for key, item in table.items(): if key in ("type", "file", "sha256"): continue - rendered = self.expression(item, factory.units.get(key), f"{path}.{key}") + if factory.counted(key, item): + rendered = self.count(item, f"{path}.{key}") + else: + rendered = self.expression( + item, factory.units.get(key), f"{path}.{key}" + ) if isinstance(item, list) and isinstance( coerce(factory.target, key, []), tuple ): diff --git a/src/solprop/recipe/metadata.py b/src/solprop/recipe/metadata.py index 9421a0c9b..a56f55cc3 100644 --- a/src/solprop/recipe/metadata.py +++ b/src/solprop/recipe/metadata.py @@ -2861,9 +2861,10 @@ 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, exclusive=True), _integer(2)), "basic", - "Positions to save at, or how many equally spaced planes.", + "Positions to save at after the entrance, or how many evenly spaced " + "planes over grid.length, counting the entrance.", display="m", ), _keyword("dz_max", _LENGTH, "advanced", "Largest step.", display="mm"), diff --git a/src/solprop/recipe/registry.py b/src/solprop/recipe/registry.py index b0c40ddda..11ed5b0a3 100644 --- a/src/solprop/recipe/registry.py +++ b/src/solprop/recipe/registry.py @@ -26,12 +26,13 @@ from collections.abc import Callable, Mapping, Sequence from dataclasses import dataclass, field from pathlib import Path -from typing import Final, Literal +from typing import Final, Literal, cast import numpy as np from solprop.boundaries import SpatialAbsorber, absorber -from solprop.driver.settings import SimulationSettings +from solprop.driver.settings import SimulationSettings, counted_save_planes +from solprop.exceptions import DriverError from solprop.grid import ( EnvelopeGrid, FieldGrid, @@ -179,12 +180,19 @@ class Factory: solves : bool Whether calling the target solves on the grid, so that it is not called on a stand-in grid (:attr:`BuildContext.stand_in`). + counts : tuple of str + Keywords whose bare integer is a count of planes, placed over the route's + grid's length by :func:`~solprop.driver.settings.counted_save_planes` rather + than read in the keyword's unit: ``SimulationSettings``' ``save_planes = 80`` + is 80 planes, while a list or a float is positions in metres. Examples -------- >>> from solprop.recipe.registry import REGISTRY >>> REGISTRY["GaussianPulse"].units["fwhm"] 's' + >>> REGISTRY["SimulationSettings"].counts + ('save_planes',) """ name: str @@ -195,6 +203,24 @@ class Factory: omitted: tuple[str, ...] = () fill: tuple[str, ...] = () solves: bool = False + counts: tuple[str, ...] = () + + def counted(self, key: str, value: object) -> bool: + """Return whether a keyword's value is a count of planes (:attr:`counts`). + + Parameters + ---------- + key : str + The keyword. + value : object + Its value as TOML read it; a boolean counts too, to be refused as one. + + Returns + ------- + bool + True for a bare integer given to one of :attr:`counts`. + """ + return key in self.counts and isinstance(value, int) def _pressure_pair(index: int) -> Unit: @@ -494,6 +520,7 @@ def retired(owner: str, key: str, value: object, path: str) -> bool: "evanescent_rate": "m^-1", }, omitted=_SETTINGS_OMITTED, + counts=("save_planes",), ), Factory( "PIController", @@ -732,7 +759,7 @@ def build_object( "route's gas, pressure and temperature, so a mode table names no fill" ) raise RecipeError(msg, path=path) - decoded = decode(item, factory.units.get(key), context, f"{path}.{key}") + decoded = _keyword_value(factory, key, item, 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. @@ -743,6 +770,30 @@ def build_object( raise RecipeError(f"{factory.name}: {error}", path=path) from error +def _keyword_value( + factory: Factory, key: str, item: object, context: BuildContext, path: str +) -> object: + """Return one keyword's value decoded, a count of planes placed on the grid.""" + if factory.counted(key, item): + return _counted_planes(item, context, path) + return decode(item, factory.units.get(key), context, path) + + +def _counted_planes(count: object, context: BuildContext, path: str) -> np.ndarray: + """Place a recipe's count of save planes over the route's grid's length. + + - ``count``: the integer the recipe wrote, counting the plane at ``z = 0``. + - Returns: the positions after ``z = 0``, m, the last at ``grid.length``. + """ + if context.grid is None: + msg = "a count of save planes is placed over the route's grid, not built yet" + raise RecipeError(msg, path=path) + try: + return counted_save_planes(context.grid.length, cast("int", count)) + except DriverError as error: + raise RecipeError(str(error), path=path) from error + + @functools.cache def _hints(target: Callable[..., object]) -> Mapping[str, object]: """Return the annotations of a callable's parameters.""" diff --git a/tests/recipe/test_free_space.py b/tests/recipe/test_free_space.py index 637917073..b64f83da8 100644 --- a/tests/recipe/test_free_space.py +++ b/tests/recipe/test_free_space.py @@ -12,6 +12,7 @@ call's configuration hash, so those comparisons are of digests and exact. """ +import dataclasses import json import textwrap import warnings @@ -24,6 +25,7 @@ from solprop.boundaries import SpatialAbsorber, absorber from solprop.capabilities import route from solprop.driver import Simulation, SimulationSettings +from solprop.driver.settings import counted_save_planes from solprop.grid import EnvelopeGrid, FieldGrid, FreeGrid, LineGrid, RadialGrid from solprop.modes import ModeCollection, PlanarGrid, SlabMode from solprop.monitor import BoundaryCheck @@ -368,6 +370,85 @@ def test_check_is_clean(name): assert Recipe.loads(CASES[name][0]).check() == [] +COUNTED = RADIAL.replace('save_planes = ["0.5 mm", "1 mm"]', "save_planes = 80") + + +def test_an_integer_save_planes_counts_planes_over_the_grid_length(): + """Regression for issue #533: ``save_planes = 80`` was one plane at z = 80 m. + + It is 80 planes, the entrance among them, as ``n_save = 80`` is on a keyword route: + 79 positions after z = 0, evenly spaced, the last at the grid's 1 mm. + """ + recipe = Recipe.loads(COUNTED) + assert recipe.check() == [] + simulation = recipe.build() + planes = np.asarray(simulation.settings.save_planes) + # One linspace over one length on both sides: a structural contract, so exact. + assert planes.tolist() == np.linspace(0.0, simulation.grid.length, 80)[1:].tolist() + assert planes.size + 1 == 80 + assert planes[-1] == simulation.grid.length == 1e-3 + + +def test_a_counted_recipe_is_the_python_call_with_the_same_count(): + call = _radial_call() + call.settings = dataclasses.replace( + call.settings, save_planes=counted_save_planes(call.grid.length, 80) + ) + assert _hash(Recipe.loads(COUNTED).build()) == _hash(call) + + +@pytest.mark.parametrize( + ("value", "match"), + [("1", "at least 2, got 1"), ("0", "at least 2, got 0"), ("true", "not True")], +) +def test_a_save_planes_count_below_two_or_a_boolean_is_refused_at_check(value, match): + text = COUNTED.replace("save_planes = 80", f"save_planes = {value}") + issues = Recipe.loads(text).check() + assert [issue.severity for issue in issues] == ["error"] + assert match in issues[0].message + assert issues[0].parameter == "settings.save_planes" + + +def test_a_count_of_planes_needs_the_route_s_grid(): + table = { + "type": "SimulationSettings", + "save_planes": 80, + "dz_max": 0.1, + "dz_init": 1e-3, + } + with pytest.raises(RecipeError, match="placed over the route's grid") as caught: + build_object(table, BuildContext(), "settings") + assert caught.value.parameter == "settings.save_planes" + + +def test_check_warns_when_the_last_plane_is_not_the_grid_length(): + text = RADIAL.replace('["0.5 mm", "1 mm"]', '["0.5 mm", "2 mm"]') + issues = Recipe.loads(text).check() + mismatch = [issue for issue in issues if "grid.length" in issue.message] + assert len(mismatch) == 1 + assert mismatch[0].severity == "warning" + assert mismatch[0].parameter == "settings.save_planes" + assert "z = 0.002 m" in mismatch[0].message + assert "0.001 m" in mismatch[0].message + + +def test_a_counted_save_planes_round_trips_through_toml_and_python(): + recipe = Recipe.loads(COUNTED) + document = recipe.to_dict() + settings = document["build"]["settings"] + assert isinstance(settings, dict) and settings["save_planes"] == 80 + # The canonical text, written from the tables rather than the text read. + again = Recipe.loads(Recipe.from_dict(document).to_text()) + settings = again.to_dict()["build"]["settings"] + assert isinstance(settings, dict) and settings["save_planes"] == 80 + assert again == recipe + script = recipe.to_python() + assert "save_planes=counted_save_planes(grid.length, 80)," in script + assert "import SimulationSettings, counted_save_planes" in script + # A list stays positions in metres in the export. + assert "save_planes=[0.0005, 0.001]" in Recipe.loads(RADIAL).to_python() + + def test_the_object_routes_list_their_objects_and_leave_the_absorber_to_settings(): for name in OBJECT_ROUTES: table = parameters(name) From 382ee16b4028ed6e0b194c31d87c0753ea4e4eec Mon Sep 17 00:00:00 2001 From: John Travers Date: Sun, 15 Nov 2026 19:09:07 +0000 Subject: [PATCH 3/3] Document counted save planes in the guide and changelog Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XGENPwwkUUG9KSAwneHjgH --- changelog.d/533-save-planes-count.fixed.md | 10 +++++++++ docs/guide/setup/recipes.md | 11 +++++++-- docs/guide/setup/running.md | 26 ++++++++++++++++++++++ 3 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 changelog.d/533-save-planes-count.fixed.md 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..296f3e94e --- /dev/null +++ b/changelog.d/533-save-planes-count.fixed.md @@ -0,0 +1,10 @@ +An integer `save_planes` in a recipe's `SimulationSettings` table, on the radial, free +and planar routes, is now a count of planes, as `n_save` is on the keyword routes: +`save_planes = 80` saves 80 evenly spaced planes over `grid.length`, counting the +entrance and ending at `grid.length`, where it was read as one plane at z = 80 m. A +count below 2 or a boolean is refused; a list is still positions in metres. In Python, +`SimulationSettings` now refuses a bare integer `save_planes`, which also read as one +plane that many metres away: pass positions, or the new +`solprop.driver.settings.counted_save_planes(grid.length, count)`. `Recipe.check()` now +warns when an object route's last save plane is not `grid.length` +([#533](https://github.com/LupoLab/solprop/issues/533)). diff --git a/docs/guide/setup/recipes.md b/docs/guide/setup/recipes.md index 81882516b..ecd3c4048 100644 --- a/docs/guide/setup/recipes.md +++ b/docs/guide/setup/recipes.md @@ -186,8 +186,15 @@ of `[build]`, although `prop_free` and `prop_planar` take them as keywords too. The settings table takes the stepping, the planes, the statistics, the absorber and the backend; `fields`, `field_planes` and `resume_history` stay in `[execution]`, and the fields a route's builder sets (the density, the -transverse quadrature) are not the recipe's. On the `planar` route a slab mode names its -fill, `{ type = "SlabMode", half_gap = "63.5 um", gas = "Ar", pressure = "1 bar" }`, +transverse quadrature) are not the recipe's. The run ends at its last save plane, so +`save_planes` in the settings table is either a list of positions, `["5 cm", "10 cm"]`, +or an integer count, `save_planes = 80`, which spreads 80 planes evenly over +`grid.length`, counting the entrance at `z = 0` and ending at `grid.length`, as +`n_save` does on the keyword routes; a count is at least 2. Saving the recipe writes +either form back as given; the Python export writes a count as +`counted_save_planes(grid.length, 80)`, since settings in Python take positions. +`Recipe.check()` warns when a list's last position is not `grid.length`, the length the +grid was built for. On the `planar` route a slab mode names its fill, `{ type = "SlabMode", half_gap = "63.5 um", gas = "Ar", pressure = "1 bar" }`, because the fill of its channels is the run's; on the `waveguide` route the same keywords are refused, since every supplied mode is rebound to the route's fill. A launch built as an array, a `Frame` and a design pin have no table form on these routes. diff --git a/docs/guide/setup/running.md b/docs/guide/setup/running.md index f1c9e6c7f..9a83e08da 100644 --- a/docs/guide/setup/running.md +++ b/docs/guide/setup/running.md @@ -425,6 +425,32 @@ simulation are the same run and must digest alike. with another input pulse or another fill while sharing what translation built ([scans](../workflows/scans.md#reuse-a-translated-simulation)). +`SimulationSettings.save_planes` is positions in metres, positive and increasing, after +the entrance at `z = 0`, which is always saved; the run ends at the last one. A bare integer is +refused rather than read as one plane that many metres away: a number of planes needs a +length to be placed over, which the settings do not have. +{py:func}`~solprop.driver.settings.counted_save_planes` places a count the way `n_save` +does on the keyword routes, evenly over `[0, length]`, counting the entrance and ending +at `length`, so five planes over the grid's 1 m are 0, 0.25, 0.5, 0.75 and 1 m. A +recipe's settings table takes the count itself, `save_planes = 80`, and places it over +`grid.length` ([recipes](recipes.md)). + +```python +from solprop.driver import SimulationSettings +from solprop.driver.settings import counted_save_planes +from solprop.grid import EnvelopeGrid +from solprop.stepper import PIController + +counted_grid = EnvelopeGrid.from_limits(1.0, 835e-9, (500e-9, 2e-6), 4e-12) +counted = SimulationSettings( + controller=PIController(rtol=1e-8, atol=1e-14), + save_planes=counted_save_planes(counted_grid.length, 5), + dz_max=0.1, + dz_init=1e-3, +) +print(counted.save_planes) # [0.25 0.5 0.75 1. ]: four positions, five planes +``` + `SimulationSettings.fields` and `field_planes` choose which saved planes keep their field — every one by default, the named ones, or none for a run wanted as statistics alone ([output](../results/output.md#statistics-only-planes-which-planes-keep-their-field)).