solprop.backends.session#

The execution-session contract between solprop and a backend (SEP 47 section 5).

Python constructs and validates the scientific problem (solprop.translate.problem.PropagationProblem) and resolves every run policy into an immutable solprop.translate.run_request.RunRequest. A backend prepares them once (solprop.backends.protocol.Backend.prepare()), and the prepared execution starts one RunSession per trajectory. The session is the only owner of that trajectory’s mutable numerical state: the field, the method’s history, the controller and monitor, the counters and cursors, and the pending events. Python’s session loop (solprop.driver.session_loop) advances it, services the events it yields – files, callbacks, warnings, progress – and acknowledges them:

prepared = backend.prepare(problem, request)
with prepared.start(start, stop=token) as session:
    while not session.finished:
        batch = session.advance(work_limit=256, deadline=0.1)
        service(batch)
        session.acknowledge(batch.receipt)

Yields are exact transport no-ops (SEP 47 section 5.1): the attempt bound, the deadline, the event capacity and the timing of acknowledgments change when control returns, never the numerical state or the control trace.

Event storage is bounded (SEP 47 section 5.3): every event delivers, exactly once, the attempts and periodic rows made since the previous event – a yield’s Progress as much as an observation, a snapshot or the terminal event – and a row’s step indexes its own chunk’s attempts. A session therefore buffers no more than one advance’s attempts, and the service loop, not the session, assembles a plane’s or a checkpoint’s history from the chunks (solprop.backends.events.join_attempts()). The status counts every attempt once, as it is drained.

Control requests travel separately from the immutable request: a thread-safe StopToken asks for a stop at the next safe boundary, and RunSession.request_snapshot() latches a snapshot for the next eligible accepted endpoint (SEP 47 section 5.5).

foreign_request() and check_preparation() are the refusals a preparation makes before any session starts (section 5.2), on both backends.

Module Attributes

DEFAULT_WORK_LIMIT

Attempts one advance makes at most before yielding, as the native marches do.

DEFAULT_DEADLINE

Host seconds after which advance yields at its next safe boundary, s.

AttemptListener

Called with each attempt's end, length and acceptance, for a progress reporter.

Functions

check_preparation(name, own, problem, request)

Refuse a run a constructed backend cannot prepare, by name (SEP 47 5.2).

foreign_request(own, request)

Return why request is not a run of own, or None when it is.

positive_count(name, value)

Return an integral, positive budget or chunk as an int.

statistics_unavailable(problem, names)

Return why no executor computes some of a problem's statistics, or None.

Classes

ExecutionOptions([node_budget, node_chunk])

Execution choices that are not part of the numerical problem.

PreparedExecution(*args, **kwargs)

A backend's lowering of one problem and request, reusable across sessions.

RunSession(*args, **kwargs)

One trajectory's numerical execution, owned by its backend.

SessionState(*values)

Where a session is in its lifecycle.

SessionStatus(z, plane_index, attempts, ...)

A compact, read-only view of a session, for reporting.

SnapshotReceipt(request, coalesced)

Identifies a snapshot request until it is fulfilled or refused.

Start(field, z[, noise, plane_index, march, ...])

Where a session starts: an initial state, or a checkpoint being resumed.

StopToken()

A thread-safe request to stop a run at its next safe boundary.

Exceptions

SessionError(*args[, parameter, rule])

A session was used outside its lifecycle.

solprop.backends.session.AttemptListener#

Called with each attempt’s end, length and acceptance, for a progress reporter.

alias of Callable[[float, float, bool], None]

solprop.backends.session.DEFAULT_DEADLINE = 0.1#

Host seconds after which advance yields at its next safe boundary, s.

solprop.backends.session.DEFAULT_WORK_LIMIT = 256#

Attempts one advance makes at most before yielding, as the native marches do.

Python signal handlers run only between native calls, so a bounded return keeps a long run interruptible (SEP 47 section 5.5).

class solprop.backends.session.ExecutionOptions(node_budget=None, node_chunk=None)[source]#

Bases: object

Execution choices that are not part of the numerical problem.

Two runs may share their scientific description while differing in these (SEP 47 section 4.3). They are recorded as execution metadata, never compared by a restart.

Attributes:
node_budgetint or None

An explicit workspace budget for node chunks, bytes: any integral value (operator.index, a NumPy integer too), held as an int. None leaves the backend’s automatic choice. An explicit budget is authoritative: the backend plans its chunk from it and no machine rule overrides it (solprop.backends.node_chunk.plan_node_chunk()).

node_chunkint or None

An exact node chunk, integral and held as an int, which overrides both the budget and the automatic choice: a measurement’s or a test’s control, not a user setting. A backend takes at most every node, and on the planar kind whole transverse rows.

Raises:
solprop.exceptions.BackendError

If node_budget or node_chunk is given and is not a positive integer.

Examples

>>> from solprop.backends.session import ExecutionOptions
>>> ExecutionOptions(node_budget=2**26).node_budget
67108864
property budget: int | None[source]#

Explicit node budget as an int, or None.

property chunk: int | None[source]#

Exact node chunk as an int, or None.

node_budget: int | SupportsIndex | None = None#
node_chunk: int | SupportsIndex | None = None#
class solprop.backends.session.PreparedExecution(*args, **kwargs)[source]#

Bases: Protocol

A backend’s lowering of one problem and request, reusable across sessions.

property backend: str[source]#

Registered name of the backend that prepared it.

close()[source]#

Release the prepared resources; idempotent.

memory_ledger()[source]#

Return every retained buffer by name, bytes.

metadata()[source]#

Return the execution metadata recorded with the run.

start(start, *, listener=None, started=None, stop=None, owns=True)[source]#

Start a session from an initial state or a checkpoint.

Parameters:
startStart

The initial state or checkpoint the session starts from.

listenercallable or None, optional

Called with each attempt’s end, length and acceptance as it is made, for a progress reporter; it observes only.

startedcallable or None, optional

Called with the start, the end and the plane count when propagation begins.

stopsolprop.log.StopFlag or None, optional

The run’s stop token.

ownsbool, optional

Whether closing the session closes the backend.

class solprop.backends.session.RunSession(*args, **kwargs)[source]#

Bases: Protocol

One trajectory’s numerical execution, owned by its backend.

See solprop.backends.session for the loop that drives it.

acknowledge(receipt)[source]#

Release a batch and allow advancing across its barrier.

Parameters:
receiptsolprop.backends.events.Receipt

The pending batch’s receipt.

advance(*, work_limit=256, deadline=0.1)[source]#

Run until a barrier, the attempt bound or the deadline, and report it.

Parameters:
work_limitint, optional

Attempts before a yield.

deadlinefloat, optional

Host seconds before a yield, s.

close()[source]#

Release the session’s resources; idempotent.

property closed: bool[source]#

Whether the session was closed.

continue_monitor(continuation)[source]#

Continue a resumed run’s boundary-monitor record, before it watches the run.

As Start.monitor, for a service loop that reads the earlier execution’s record from its output after the session started.

Parameters:
continuationcollections.abc.Mapping

The continuation, as Start.monitor holds it.

execution_record()[source]#

Return the session’s execution facts for the run’s execution record.

export(ticket, recipe, out=None)[source]#

Fill a destination with a pending observation’s converted field.

Parameters:
ticketsolprop.backends.events.ExportTicket

The pending observation’s ticket.

recipesolprop.backends.export.ExportRecipe

The conversion.

outnumpy.ndarray or None, optional

The destination; a new array by default.

failure_ticket()[source]#

Return a ticket for the committed state after a failure outside the session.

A service failure – an output error, a signal during a commit – leaves the session’s batch pending, and the ticket is bound to it; when none is pending, the session issues a failed terminal batch at its committed state, so that the state can be exported for a terminal checkpoint and nothing advances again. None once the session closed, its state was poisoned or left in flight, or before it issued a batch it could bind the ticket to.

property finished: bool[source]#

Whether a terminal event was yielded.

property in_flight: tuple[float, float] | None[source]#

In-place step a failure left in flight, or None.

Its start and length, m, while the state is neither of the step’s ends: a low-storage step overwrites the state in place (SEP 47 section 5.5).

property march_refusal: str | None[source]#

Why the start’s method history could not be installed.

The reason, or None when it was installed or the start carried none.

march_snapshot(ticket)[source]#

Return the method history at a pending observation, when retained.

Parameters:
ticketsolprop.backends.events.ExportTicket

The pending observation’s ticket.

march_snapshot_nbytes()[source]#

Return the size a method-history snapshot would have, without making it.

monitor_record()[source]#

Return the boundary monitor’s record, or None without a monitor.

noise_phase(ticket)[source]#

Return the noise phase at a pending observation, when a noise model runs.

Parameters:
ticketsolprop.backends.events.ExportTicket

The pending observation’s ticket.

pending_ticket()[source]#

Return a ticket for the committed state after a failure outside the session.

None when nothing can be exported: the session is closed or poisoned, or no batch is pending to bind the ticket to.

request_snapshot()[source]#

Latch a snapshot for the next eligible accepted endpoint.

status()[source]#

Return a read-only summary of the session.

undelivered(ticket)[source]#

Deliver the attempts and rows made since the previous event, once.

For a terminal checkpoint after a failure outside the session, whose attempts no event delivered; empty when every attempt was delivered.

Parameters:
ticketsolprop.backends.events.ExportTicket

The checkpoint’s ticket.

Returns:
tuple

The attempts and the periodic rows.

exception solprop.backends.session.SessionError(*args, parameter=None, rule=None)[source]#

Bases: BackendError

A session was used outside its lifecycle.

Raised for a stale or foreign receipt, an advance across an unacknowledged barrier, use after close or after a terminal outcome, or an export with an expired ticket.

class solprop.backends.session.SessionState(*values)[source]#

Bases: Enum

Where a session is in its lifecycle.

Attributes:
READYstr

It can advance.

PENDINGstr

A batch is out; it advances again once that batch is acknowledged.

FINISHEDstr

It yielded a terminal event; nothing more can happen but close.

CLOSEDstr

Its resources are released.

CLOSED = 'closed'#
FINISHED = 'finished'#
PENDING = 'pending'#
READY = 'ready'#
class solprop.backends.session.SessionStatus(z, plane_index, attempts, rejected, state, outcome=None)[source]#

Bases: object

A compact, read-only view of a session, for reporting.

Attributes:
zfloat

The committed position, m.

plane_indexint

The next save plane to observe.

attemptsint

Attempts made, accepted and rejected.

rejectedint

Rejected attempts among them.

stateSessionState

Lifecycle state.

outcomesolprop.backends.events.Outcome or None

The terminal outcome, once finished.

attempts: int#
outcome: Outcome | None = None#
plane_index: int#
rejected: int#
state: SessionState#
z: float#
class solprop.backends.session.SnapshotReceipt(request, coalesced)[source]#

Bases: object

Identifies a snapshot request until it is fulfilled or refused.

Attributes:
requestint

Sequence number of the request in its session, from 1.

coalescedbool

Whether it joined an equivalent request still outstanding, so that one snapshot fulfils both (SEP 47 section 5.5 makes coalescing explicit).

coalesced: bool#
request: int#
class solprop.backends.session.Start(field, z, noise=None, plane_index=0, march=None, ledgers=None, monitor=None, plane_pending=True, resume=False)[source]#

Bases: object

Where a session starts: an initial state, or a checkpoint being resumed.

A start is handed to one session, which takes its field (take_field()): the session loads a copy made once at start, and the start forgets the array, so an input that nothing else holds – a runner’s caller’s array – is released before the first step rather than held through the run by every frame that passed the start along (SEP 47 section 5.4).

Attributes:
fieldnumpy.ndarray or None

The state in internal amplitude units and the FFT convention, complex, shape (n_modes, n_pol, n_omega); None once a session took it. Mutating the caller’s array after the start changes nothing.

zfloat

Its position, m.

noisesolprop.noise.NoiseRealisation or None

The run’s noise realisation, when a noise model is active.

plane_indexint

The first save plane strictly beyond z.

marchsolprop.output.records.MarchSnapshot or None

A method history to restore, when resuming one that was retained.

ledgerscollections.abc.Mapping or None

Persisted call ledgers to restore (TDSE and budgeted sources).

monitorcollections.abc.Mapping or None

When resuming a monitored run, the monitor’s continuation: "record", its persisted record; "plane", whether the resumed position is a saved plane; "unwatched", the spans the earlier executions left unwatched.

plane_pendingbool

Whether the plane at z is owed (the launch plane of a fresh run, or a resumed position whose plane was not saved).

resumebool

Whether field was loaded from a plane the run already saved, so that an input noise realisation is not added a second time.

classmethod entrance(problem, *, noise=None)[source]#

Return the fresh start of a problem: its launch state, its launch plane owed.

Parameters:
problemsolprop.translate.problem.PropagationProblem

The translated problem.

noisesolprop.noise.NoiseRealisation or None, optional

A realisation to carry instead of the one the problem was assembled with.

Returns:
Start

The start at problem.initial.z, before the first save plane.

field: Complex[ndarray, 'n_modes n_pol n_omega'] | None#
ledgers: Mapping[str, object] | None = None#
march: MarchSnapshot | None = None#
monitor: Mapping[str, object] | None = None#
noise: NoiseRealisation | None = None#
plane_index: int = 0#
plane_pending: bool = True#
resume: bool = False#
take_field()[source]#

Hand the field to the session starting here, and forget it.

Returns:
numpy.ndarray

The field, shape (n_modes, n_pol, n_omega); the caller copies it.

Raises:
SessionError

If a session already took it: a start is used once.

z: float#
class solprop.backends.session.StopToken[source]#

Bases: object

A thread-safe request to stop a run at its next safe boundary.

Setting it from any thread – a GUI’s stop button, a signal handler on the main thread, a scan’s supervisor – asks every session attached to it to finish the attempt in hand, complete that endpoint’s mandatory accounting, and end with STOPPED (SEP 47 section 5.5). It implements solprop.log.StopFlag.

Examples

>>> from solprop.backends.session import StopToken
>>> token = StopToken()
>>> token.is_set()
False
>>> token.set()
>>> token.is_set()
True
attach(listener)[source]#

Call listener whenever the token is set, and now if it already is.

Native sessions attach the store of their own atomic flag, so that a stop set from another thread reaches a march that holds no Python lock.

Parameters:
listenercallable

Called with no arguments. It must not raise and must not block.

Returns:
callable

Detaches the listener.

clear()[source]#

Withdraw the request, for a token reused between runs.

is_set()[source]#

Return whether a stop was requested.

Returns:
bool

True once set() was called and not cleared.

set()[source]#

Request a stop, and forward it to every attached session.

solprop.backends.session.check_preparation(name, own, problem, request)[source]#

Refuse a run a constructed backend cannot prepare, by name (SEP 47 5.2).

Parameters:
namestr

The backend’s registered name, for the message.

ownsolprop.translate.run_request.RunRequest

The request the backend was built for.

problemsolprop.translate.problem.PropagationProblem

The run’s problem.

requestsolprop.translate.run_request.RunRequest

The run’s request.

Raises:
solprop.backends.session.SessionError

If the request is not one run of the backend’s own (foreign_request()).

solprop.exceptions.BackendError

If the request asks for statistics the problem does not carry (statistics_unavailable()).

solprop.backends.session.foreign_request(own, request)[source]#

Return why request is not a run of own, or None when it is.

A backend lowers its method, error control, replay and itinerary where it is built (SEP 47 section 5.2), so a run it serves may differ from its own request only where for_run() changes it: the start, retention, statistics, monitor, history and snapshots. for_run keeps the other sections by identity, which is what is checked.

Parameters:
ownsolprop.translate.run_request.RunRequest

The request the backend was built for.

requestsolprop.translate.run_request.RunRequest

The request one run asks it to serve.

Returns:
str or None

The first section that differs, named, or None.

Examples

>>> from solprop.stepper import DOPRI5, PIController
>>> from solprop.stepper.settings import StepperSettings
>>> from solprop.translate.run_request import describe_run
>>> settings = StepperSettings(DOPRI5, PIController(rtol=1e-8, atol=1e-14),
...                            1e-9, 0.1, 1e-3, 1.1, None, [0.5, 1.0], "auto")
>>> own = describe_run(settings)
>>> foreign_request(own, own.for_run(start_plane=1)) is None
True
>>> foreign_request(own, describe_run(settings))
"the run's integration is not the backend's own"
solprop.backends.session.positive_count(name, value)[source]#

Return an integral, positive budget or chunk as an int.

Parameters:
namestr

"node_budget" or "node_chunk", for the message.

valueobject

Anything operator.index accepts, such as an int or a NumPy integer.

Returns:
int

The value.

Raises:
solprop.exceptions.BackendError

If value is a bool, not integral, or not positive.

Examples

>>> import numpy as np
>>> from solprop.backends.session import positive_count
>>> positive_count("node_budget", np.int64(2**26))
67108864
solprop.backends.session.statistics_unavailable(problem, names)[source]#

Return why no executor computes some of a problem’s statistics, or None.

What the problem does not carry, refused by name before any session starts, on every executor (SEP 47 section 6.3), rather than at the first plane: a modal statistic of a spatial route, a spatial statistic of a modal one, the plasma integration diagnostics of a problem without the field-grid plasma column (SEP 18), and the electron density or the peak ionisation rate of a problem with no compiled plasma response. The messages are the reference’s at its first plane.

Parameters:
problemsolprop.translate.problem.PropagationProblem

The translated problem.

namescollections.abc.Sequence of str

The statistics asked for, at planes or between them.

Returns:
str or None

The refusal, or None.

Examples

>>> from solprop.backends.session import statistics_unavailable
>>> from solprop.driver import Simulation
>>> simulation = Simulation.from_gnlse(
...     0.11, 0.01, [0.0, 0.0, -1.183e-26], wavelength=835e-9,
...     wavelength_limits=(500e-9, 2e-6), trange=1e-12,
...     width=100e-15, peak_power=9.8, shape="sech",
... )
>>> problem = simulation.translate()
>>> statistics_unavailable(problem, ["energy"]) is None
True
>>> statistics_unavailable(problem, ["beam_radius"])
"the 'beam_radius' statistic requires spatial geometry"