Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions changelog.d/533-save-planes-count.fixed.md
Original file line number Diff line number Diff line change
@@ -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)).
11 changes: 9 additions & 2 deletions docs/guide/setup/recipes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
26 changes: 26 additions & 0 deletions docs/guide/setup/running.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)).
Expand Down
137 changes: 111 additions & 26 deletions src/solprop/driver/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"LOW_STORAGE_BACKENDS",
"NoiseSetting",
"SimulationSettings",
"counted_save_planes",
"default_collar",
"keyword_settings",
]
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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"))
Expand Down Expand Up @@ -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,
Expand All @@ -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:
Expand Down
31 changes: 29 additions & 2 deletions src/solprop/recipe/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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.

Expand Down
19 changes: 18 additions & 1 deletion src/solprop/recipe/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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
):
Expand Down
5 changes: 3 additions & 2 deletions src/solprop/recipe/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down
Loading
Loading