Skip to content

Runtime API

Tier: Stable Core

Runner lifecycle, system points, timebase helpers, and feedback harness support.

pyrung.PLC

Generator-driven PLC execution engine.

Executes PLC logic as pure functions: Logic(state) -> new_state. The consumer controls execution via step(), enabling: - Input injection via patch() - Inspection of retained historical state via runner.history - Pause/resume at any scan boundary

Attributes:

Name Type Description
current_state SystemState

The current SystemState snapshot.

history History

Query interface for retained SystemState snapshots.

simulation_time float

Current simulation clock (seconds).

dt float

Configured scan period in seconds.

time_mode TimeMode

Current time mode (FIXED_STEP or REALTIME).

program property

program: Any

The Program object if the PLC was constructed from one, else None.

state property

state: SystemState

Current state snapshot.

tags property

tags: MappingProxyType[str, Tag]

Return a read-only mapping of tag name to Tag object.

The mapping holds the tags that the runner knows and the slots that its rungs reach. Reading a slot that a range reaches creates a tag for it.

bounds_violations property

bounds_violations: dict[str, BoundsViolation]

Constraint violations from the most recent scan, if any.

history property

history: History

Read-only history query surface.

playhead property

playhead: int

Current scan id used for inspection/time-travel queries.

dataview property

dataview: Any

Chainable query over this program's tag dependency graph.

Convenience shorthand for plc.program.dataview() — builds (and caches) the static program graph lazily on first access.

query property

query: Any

Survey namespace for whole-program dynamic analysis.

simulation_time property

simulation_time: float

Current simulation clock in seconds.

dt property

dt: float

Configured scan period in seconds.

time_mode property

time_mode: TimeMode

Current time mode.

debug property

debug: _DebugNamespace

Debugger-facing methods and internal runtime access.

mode property

mode: Literal['run', 'stop']

PLC mode: "run" or "stop".

keep_forces_on_run property writable

keep_forces_on_run: bool

Whether active forces survive a STOP -> RUN transition.

This is off by default. Entering RUN then clears forces along with patches, like a fresh start. When it is on, forces are kept and apply from the first scan. Tags and pending patches still reset. reboot() clears forces either way.

battery_present property writable

battery_present: bool

Whether the project's Battery Backup Setup box is checked (default True).

sys.battery_present (SC203 on a CLICK) reads it. The property mirrors that setting and does not detect a battery. With it True, :meth:reboot keeps the retentive tags. With it False, :meth:reboot resets every tag.

forces property

forces: Mapping[str, bool | int | float | str]

Read-only view of active persistent overrides.

pending_patches property

pending_patches: Mapping[str, bool | int | float | str]

Read-only view of patches not yet in the committed state.

A patch stays here until a scan that applied it commits. That includes a patch that a scan paused in debug.scan_steps_debug() has applied.

seek

seek(scan_id: int) -> SystemState

Move playhead to a retained scan and return that snapshot.

rewind

rewind(seconds: float) -> SystemState

Move playhead backward in time by seconds and return snapshot.

rung_firings

rung_firings(scan_id: int | None = None) -> PMap

Return rung firings for the given scan (default: playhead).

Returns PMap[int, PMap[str, Any]] mapping each rung index that fired (had any write, even if all were filtered by PDG) during the scan to the filtered {tag_name: value_written} map. Synthesized on demand from per-rung range-encoded timelines (:class:RungFiringTimelines); rungs with no timeline covering scan_id contribute nothing.

Populated uniformly by both the non-debug (step() / run()) and debug (DAP pyrungStepScan / continue) scan paths via ScanContext.capturing_rung.

Values are attempted writes, including a later writer reasserting the already-pending value. Transition consumers compare committed state. Causal execution consumers retain the exact writer occurrence.

If a column grew too long to keep, or a loop's record cannot speak for it, the method steps the scan again from the nearest checkpoint. It raises UnrecordedScansError where that is too far.

diff

diff(
    scan_a: int, scan_b: int
) -> dict[str, tuple[Any, Any]]

Return changed tag values between two retained historical scans.

cause

cause(
    tag: Tag | str,
    scan: int | None = None,
    *,
    to: Any = _SENTINEL,
    assume: dict[str, Any] | None = None,
    deep: bool = True,
    since: int | None = None,
) -> CausalChain | None

Explain what caused a tag to transition.

Recorded (default, to omitted): walks recorded history backward from the transition. Returns None if no transition was found. With deep=True, each fired rung's steady enablers are recursively explained through their establishing transitions or an observed writer of their current value. Non-firing static writers are not swept into the result. Terminals are classified in :attr:~pyrung.core.analysis.causal.CausalChain.roots.

Projected (to=value): projects forward from the current state, finding reachable paths that would drive the tag to value. Returns a CausalChain with mode='projected' (reachable) or mode='unreachable' (stranded, with blockers). Never returns None in projected mode.

Parameters:

Name Type Description Default
tag Tag | str

Tag object or tag name string.

required
scan int | None

Specific scan to examine (recorded mode only).

None
to Any

Target value for projected mode. When provided, the method returns the path that would drive tag to this value from the current state.

_SENTINEL
assume dict[str, Any] | None

Tag-to-value overrides for projected mode. Pins the given tags to specified values during analysis. Raises ValueError if used without to= or if any key is a readonly tag.

None
deep bool

Recorded mode only. False restores the shallow trigger-only walk (no recursive enabler explanation).

True
since int | None

Recorded mode only. Inclusive earliest transition scan for an incident-local explanation. The state immediately before this scan is boundary context, not a cause to chase. Omit it to traverse the runner's complete inherited epoch lineage.

None

Returns:

Name Type Description
A CausalChain | None

class:~pyrung.core.analysis.causal.CausalChain, or None

CausalChain | None

(recorded mode only, when no transition was found).

effect

effect(
    tag: Tag | str,
    scan: int | None = None,
    *,
    from_: Any = _SENTINEL,
    to_value: Any = _SENTINEL,
    assume: dict[str, Any] | None = None,
    steady_state_k: int = 3,
    max_scans: int = 1000,
) -> CausalChain | None

Trace the downstream effects of a tag transition.

Recorded (default, from_ omitted): walks recorded history forward from an actual transition. Returns None if no transition was found.

Projected (from_=value): what-if analysis — if the tag transitioned from value right now, what downstream effects would follow? Returns mode='projected' (possibly empty steps for dead-end) or mode='unreachable' if the trigger can't fire. Never returns None in projected mode.

Parameters:

Name Type Description Default
tag Tag | str

Tag object or tag name string.

required
scan int | None

Specific scan of the transition (recorded mode only).

None
from_ Any

Current value for projected what-if analysis. For Bool tags the TO value is inferred as not from_.

_SENTINEL
assume dict[str, Any] | None

Tag-to-value overrides for projected mode. Pins the given tags to specified values during analysis. Raises ValueError if used without from_= or if any key is a readonly tag.

None
steady_state_k int

Stop after this many consecutive scans with no new effects (recorded mode only, default 3).

3
max_scans int

Hard cap on forward scans (recorded mode only, default 1000).

1000

Returns:

Name Type Description
A CausalChain | None

class:~pyrung.core.analysis.causal.CausalChain, or None

CausalChain | None

(recorded mode only, when no transition was found).

why

why(*tags: Tag | str) -> CausalChain

Explain how tags reached their current values from a snapshot.

No history required. Walks the program graph backward from each tag, using the current state as evidence. Terminates at external inputs. Active forces on tags in the chain are named in it.

For a write through a pointer that lists no targets, it reads the scan history to see whether the write stored the tag's value. When the history cannot say, or the rung does not conduct, it runs the next scan on a throwaway copy of the PLC to see where the write stores.

Several tags produce one tree. It is a single explanation that is consistent with all observations.

Parameters:

Name Type Description Default
tags Tag | str

One or more Tag objects or tag name strings.

()

Returns:

Name Type Description
A CausalChain

class:~pyrung.core.analysis.causal.CausalChain with

CausalChain

mode='why'.

how

how(
    *conditions: Any,
    avoid: Any = None,
    max_scans: int = 4000,
    unlink: list[str] | None = None,
    on_event: Any = None,
    wall_clock_s: float | None = 300.0,
) -> Any

Find an input-change sequence that reaches a target state.

For a target with more than one route — a Bool (Running, Running == False) or a word value (State == 5) — PILOT never reports ambiguous: it picks a deterministic default route, reaches the goal, and records where it went on Path.route. Exclude a reported route with avoid= and PILOT will look for another.

avoid X means do not take a path that depends on X. It excludes routes, operator actions, and observed scan states that satisfy the predicate. Momentary commands count as actions, not just settled states. So avoid=C_Complete will not press C_Complete, even though it settles back to rest. A path is excluded if it depends on the avoided condition at any of these three gates. If every path is excluded, the returned Path is unreachable, and its reason names the violated avoid condition(s). If a check raises on the state how() starts from, or on a scan a trial runs, how() raises AvoidCheckError, because the check has not said that state is clear. A check that raises on a state how() is only weighing, such as a hold laid over a state, says nothing about the route and denies nothing.

Parameters:

Name Type Description Default
conditions Any

Target condition(s). Each is a Tag (Running) or a comparison (State == 3). Pass more than one for an AND goal — how(Running, State == 3) reaches a single state where every target holds, or reports why they can't coexist.

()
avoid Any

Condition(s) to keep the path (and the chosen route) clear of. One condition, or a tuple/list = union of exclusions (each condition avoided independently). Express a composite prohibition explicitly — avoid=And(A, B) avoids only the combined state, not A or B alone.

None
max_scans int

Work budget for the search. Each scan the search steps counts one, and so do the first two scans and the last scan of each wait. The other scans of a wait count a hundredth each, so a long timer fits a small budget. A wait pyrung cannot run compiled counts one for every scan. That happens when the program writes a read-only system tag or has a run_function() that keeps state between calls, or when a tag is forced.

4000
wall_clock_s float | None

Seconds of real time before the search stops and says so, or None for no limit. A search this ends may have reached on a faster machine.

300.0
unlink list[str] | None

Harness-feedback tag names to free for fault injection. how() removes the link= coupling from the named tags. The harness then stops driving them, and PILOT may steer them directly. Use this to reach a fault, such as a dead sensor, that the intact physical link would otherwise hold out of reach.

None

Returns:

Name Type Description
A Any

class:~pyrung.core.analysis.graph.Path.

recovers

recovers(
    tag: Tag | str, *, assume: dict[str, Any] | None = None
) -> bool

True if tag has a reachable clear path from the current state.

Convenience predicate: cause(tag, to=resting).mode != 'unreachable'. For the underlying chain (witness or blockers), call cause() directly.

Tags marked external=True always return True — the recovery path exists outside the ladder by declaration. When assume is provided the external shortcut is skipped so the analysis runs with the given overrides.

Parameters:

Name Type Description Default
tag Tag | str

Tag object or tag name string.

required
assume dict[str, Any] | None

Tag-to-value overrides. Pins the given tags to specified values during projected analysis.

None

fork

fork(
    scan_id: int | None = None,
    *,
    history_budget: int | float | None = None,
    inherit_log: bool = True,
) -> PLC

Create an independent runner from retained historical state.

Parameters:

Name Type Description Default
scan_id int | None

Snapshot to fork from. Defaults to current committed tip state.

None
history_budget int | float | None

Byte ceiling for the child's recent-state cache. Defaults to the parent's budget. Pass math.inf to disable eviction entirely — every state the child produces stays cached, guaranteeing full-fidelity cause() chains without replay. Useful for ephemeral forks that will be discarded shortly after causal analysis.

None

fork_from

fork_from(scan_id: int) -> PLC

Create an independent runner from a retained historical snapshot.

replay_to

replay_to(target_scan_id: int) -> PLC

Reconstruct historical state, preferring compiled replay when supported.

replay_trace_at

replay_trace_at(
    target_scan_id: int,
) -> dict[int, RungTrace]

Reconstruct the rung-trace dict for a historical scan.

Runs the same replay walk as replay_to up to target_scan_id - 1 on the plain scan path, then drives _scan_steps_debug for target_scan_id so the replay fork's _current_rung_traces gets populated. Returns a copy of that dict; the replay fork is discarded.

The _replay_mode guards in _commit_scan (monitors, breakpoints) and _set_rtc_and_record cover the debug path too — both generators funnel through the same commit sink.

A one-slot cache (_cached_replay_trace) hits when the same target_scan_id is requested back-to-back. It is cleared on any tip advance (_run_single_scan) and on reset paths that reset the log (reboot, stop→run, via _clear_retained_debug_trace_caches).

Traces only exist for scans that actually executed — the fork anchor / initial scan was never stepped in debug mode — so target_scan_id must be strictly greater than _initial_scan_id.

start

start() -> None

Transition STOP -> RUN now, without executing a scan.

Performs the same transition the next step() would: non-retentive tags reset, scan_id and timestamp restart at 0, pending patches are dropped, and forces are cleared unless :attr:keep_forces_on_run. Patches and forces applied afterwards reach the first scan. Does nothing in RUN mode.

stop

stop() -> None

Transition PLC to STOP mode.

reboot

reboot() -> SystemState

Power-cycle the runner and return the reset state.

Reboot is destructive. With :attr:battery_present True the retentive tags keep their values and the rest return to their defaults, as over STOP -> RUN. With it False every tag returns to its default. Forces are cleared either way. state.scan_id and state.timestamp return to 0. Post-reboot scan_ids would alias pre-reboot entries in every sparse channel (patches, forces, rtc_base_changes, dts). So the reboot resets the scan log and checkpoints to a fresh recording session that starts at the post-reboot scan 0. You cannot replay pre-reboot history. If you need it, call fork() before rebooting.

set_rtc

set_rtc(value: datetime) -> None

Set the current RTC value for the runner.

patch

patch(
    tags: Mapping[str, bool | int | float | str]
    | Mapping[Tag, bool | int | float | str]
    | Mapping[str | Tag, bool | int | float | str],
) -> None

Queue tag values for next scan (one-shot).

The next scan applies the values at its start. Each value stays queued until a scan that applied it commits. A scan that raises leaves it for the next scan. Use for momentary inputs like button presses.

Parameters:

Name Type Description Default
tags Mapping[str, bool | int | float | str] | Mapping[Tag, bool | int | float | str] | Mapping[str | Tag, bool | int | float | str]

Dict of tag names or Tag objects to values.

required

patch_as_recorded

patch_as_recorded(
    recorded: Mapping[str, bool | int | float | str],
) -> None

Queue a patch that a scan log recorded. See InputOverrideManager.restore_patch.

force

force(
    tag: str | Tag, value: bool | int | float | str
) -> None

Persistently override a tag value until explicitly removed.

The forced value is applied at the pre-logic force pass (phase 3) and re-applied at the post-logic force pass (phase 5) every scan. Logic may temporarily diverge the value mid-scan, but the post-logic pass restores it before outputs are written.

Forces persist across scans until unforce() or clear_forces() is called. Multiple forces may be active simultaneously.

If a tag is both patched and forced in the same scan, the force overwrites the patch during the pre-logic pass.

Parameters:

Name Type Description Default
tag str | Tag

Tag name or Tag object to override.

required
value bool | int | float | str

Value to hold. Must be compatible with the tag's type.

required

Raises:

Type Description
ValueError

If the tag is a read-only system point.

unforce

unforce(tag: str | Tag) -> None

Remove a single persistent force override.

After removal the tag resumes its logic-computed value starting from the next scan.

Parameters:

Name Type Description Default
tag str | Tag

Tag name or Tag object whose force to remove.

required

clear_forces

clear_forces() -> None

Remove all active persistent force overrides.

All forced tags resume their logic-computed values starting from the next scan.

forced

forced(
    overrides: Mapping[str, bool | int | float | str]
    | Mapping[Tag, bool | int | float | str]
    | Mapping[str | Tag, bool | int | float | str],
) -> Iterator[PLC]

Temporarily apply forces for the duration of the context.

On entry, saves the current force map and adds the given overrides. On exit (normally or on exception), the exact previous force map is restored — forces that existed before the context are reinstated, and forces added inside the context are removed.

Safe for nesting: inner forced() contexts layer on top of outer ones without disrupting them.

Parameters:

Name Type Description Default
overrides Mapping[str, bool | int | float | str] | Mapping[Tag, bool | int | float | str] | Mapping[str | Tag, bool | int | float | str]

Mapping of tag name / Tag object to forced value.

required
Example
with plc.forced({"AutoMode": True, "Fault": False}):
    plc.run(5)
# AutoMode and Fault forces released here

monitor

monitor(
    tag: str | Tag, callback: Callable[[Any, Any], None]
) -> _RunnerHandle

Call callback(current, previous) after commit when tag value changes.

when

when(
    *conditions: Condition
    | Tag
    | Callable[[SystemState], bool]
    | tuple[Condition | Tag, ...]
    | list[Condition | Tag],
) -> _BreakpointBuilder

Create a breakpoint builder evaluated after each committed scan.

Accepts Tag/Condition expressions (implicit AND) or a single callable predicate receiving SystemState.

live_value

live_value(tag: str | Tag, default: Any = None) -> Any

Return a tag's value as Tag.value reads it now.

The value is the tag's force, if it has one. Otherwise it is a write that no scan has stored yet, then the system value, then the committed tag. A tag that has none of these returns default, or the tag's own default when you pass a Tag.

step

step() -> SystemState

Execute one full scan cycle and return the committed state.

run

run(cycles: int) -> SystemState

Execute up to cycles scans, stopping early on pause breakpoints.

Parameters:

Name Type Description Default
cycles int

Number of scans to execute.

required

Returns:

Type Description
SystemState

The final SystemState after all cycles.

run_for

run_for(seconds: float, *, jit: bool = True) -> SystemState

Run until simulation time advances by N seconds or a pause breakpoint fires.

Parameters:

Name Type Description Default
seconds float

Minimum simulation time to advance.

required
jit bool

When True (default), a long run goes through the compiled kernel and its guarded loop, which run every scan without recording causal timelines. False steps every scan interpreted.

True

Returns:

Type Description
SystemState

The final SystemState after reaching the target time.

run_until

run_until(
    *conditions: Condition
    | Tag
    | Callable[[SystemState], bool]
    | tuple[Condition | Tag, ...]
    | list[Condition | Tag],
    max_cycles: int = 10000,
    jit: bool = True,
) -> SystemState

Run until condition is true, pause breakpoint fires, or max_cycles reached.

Accepts Tag/Condition expressions (implicit AND) or a single callable predicate receiving SystemState.

Parameters:

Name Type Description Default
conditions Condition | Tag | Callable[[SystemState], bool] | tuple[Condition | Tag, ...] | list[Condition | Tag]

Condition expressions or a single callable predicate.

()
max_cycles int

Maximum scans before giving up (default 10000).

10000
jit bool

When True (default), a long run goes through the compiled kernel and its guarded loop, which run every scan without recording causal timelines. False, or a callable predicate, steps every scan interpreted.

True

Returns:

Type Description
SystemState

The state that matched the condition, or final state if max reached.

pyrung.SystemState

Bases: Mapping[str, Any]

Immutable snapshot of PLC state at a point in time.

A read-only mapping of its four fields, evolved with :meth:set, :meth:with_tags and :meth:with_memory.

Attributes:

Name Type Description
scan_id int

Monotonically increasing scan counter.

timestamp float

Simulation clock in seconds.

tags PMap

Immutable mapping of tag names to values (bool, int, float, str).

memory PMap

Immutable mapping for internal state (timers, counters, etc).

create classmethod

create(
    kwargs: Mapping[str, Any],
    _factory_fields: Any = None,
    ignore_extra: bool = False,
) -> SystemState

Build a state from a mapping of its fields. A state passed in is returned as is.

set

set(*args: Any, **kwargs: Any) -> SystemState

Return this state with fields replaced: set(name, value) or set(name=value).

update

update(*maps: Mapping[str, Any]) -> SystemState

Return this state with the fields in maps replaced, the last map winning.

with_tags

with_tags(
    updates: Mapping[str, bool | int | float | str],
) -> SystemState

Return new state with updated tags. Original unchanged.

with_memory

with_memory(updates: dict[str, Any]) -> SystemState

Return new state with updated memory. Original unchanged.

next_scan

next_scan(dt: float) -> SystemState

Return new state for next scan cycle.

Parameters:

Name Type Description Default
dt float

Time delta in seconds to add to timestamp.

required

committed

committed(
    tags: PMap, memory: PMap, dt: float
) -> SystemState

Return the state after a scan, with these tags and memory, on the next scan.

scanned

scanned(
    scan_id: int, timestamp: float, tags: PMap, memory: PMap
) -> SystemState

Return this state with every field replaced, or itself when none of them changes.

pyrung.AvoidCheckError

Bases: Exception

Raised when an avoid= check raises on a real state.

A real state is the one where how() starts, or a scan that a trial ran. A check that raised did not say the state is clear, so how() does not go through that state. The check also proved nothing about the target. So how() has no plan to return, and the check's own exception is the __cause__. A check that raises on a state how() is only weighing, such as a hold laid over a state, does not cause this error.

pyrung.UnrecordedScansError

Bases: ValueError

Raised when a question reaches more scans without records than it may step again.

pyrung.DataView dataclass

Lazy, chainable query over a program's tag dependency graph.

tags property

tags: frozenset[str]

The current narrowed tag set.

from_graph classmethod

from_graph(graph: ProgramGraph) -> DataView

Create a root view covering all classified tags.

inputs

inputs() -> DataView

Tags with role INPUT.

pivots

pivots() -> DataView

Tags with role PIVOT.

terminals

terminals() -> DataView

Tags with role TERMINAL.

isolated

isolated() -> DataView

Tags with role ISOLATED.

physical_inputs

physical_inputs() -> DataView

Tags backed by physical input hardware.

physical_outputs

physical_outputs() -> DataView

Tags backed by physical output hardware.

internal

internal() -> DataView

Tags that are neither physical inputs nor outputs.

contains

contains(needle: str) -> DataView

Filter to tags matching needle (contains + abbreviation).

upstream

upstream(tag: str) -> DataView

Upstream dependency cone of tag, intersected with current view.

For a tag written in a subroutine, the cone includes the condition tags of the rungs that call the subroutine, up the call chain. The call condition is the subroutine's enable. The cone stops at those tags.

downstream

downstream(tag: str) -> DataView

Downstream dependency cone of tag, intersected with current view.

This is the reverse of :meth:upstream. If tag is read in the condition of a rung that calls a subroutine, the cone includes every tag that the subroutine, or a subroutine it calls, writes. Only tag itself crosses into a subroutine.

roles

roles() -> dict[str, TagRole]

Return {tag: role} for tags in the current view.

details

details() -> dict[str, TagDetail]

Return {tag: TagDetail} with full metadata for tags in the view.

structures

structures() -> list[StructureInfo]

Return definitions for all UDTs and named_arrays found in the view.

pyrung.Physical dataclass

Declares how a feedback answers its linked command.

Each kind takes its own keywords, and a feedback has one kind::

Physical("MotorFb", on_delay="2s", off_delay="500ms")
Physical("Encoder", flasher_on="8ms", flasher_off="8ms")
Physical("Horn", timed="200ms", maintained=True)
Physical("Lamp", toggle=True)
Physical("Temp", ramp_on=0.8, ramp_off=-0.05)
Physical("Oven", approach_to="Oven_SP", approach_rate=0.3)

Times are strings with units. Rates are numbers per second. approach_to is a number or a tag name. system groups related feedback for reporting.

kind_spec property

kind_spec: PhysicalKind

Return the row of PHYSICAL_KINDS that this feedback belongs to.

kind property

kind: str

Return delay, flasher, timed, toggle, ramp or approach.

from_text classmethod

from_text(
    name: str,
    values: Mapping[str, str | bool],
    *,
    system: str | None = None,
) -> Physical

Build from comment text: {"flasher_on": "8ms", ...}, with a flag as True.

Raises ValueError for an unknown key, a bad value, or keys that make no one kind.

keywords

keywords() -> dict[str, Any]

Return the response keywords set on this feedback, leaving out a key at its default.

Physical(p.name, **p.keywords(), system=p.system) == p.

comment_text

comment_text() -> dict[str, str | bool]

Return the response keys as a comment writes them, with a flag as True.

tokens

tokens() -> list[str]

Return the comment tokens for the response: ["flasher_on=8ms", "flasher_off=8ms"].

pyrung.PHYSICAL_KEYS module-attribute

PHYSICAL_KEYS: dict[str, PhysicalKey] = {
    key.name: key
    for kind in PHYSICAL_KINDS
    for key in kind.keys
}

pyrung.PHYSICAL_KINDS module-attribute

PHYSICAL_KINDS: tuple[PhysicalKind, ...] = (
    PhysicalKind(
        "delay",
        "bool",
        "On/off delay",
        "Turns on after the command has held for a time, and off a time after it drops.",
        "debounce",
        (
            _duration(
                "on_delay",
                "delay",
                "On delay",
                "How long the command must hold before the feedback turns on. Leaving it out means 0.",
                "500ms",
                required=False,
            ),
            _duration(
                "off_delay",
                "delay",
                "Off delay",
                "How long the feedback stays on after the command drops. Leaving it out means 0.",
                "200ms",
                required=False,
            ),
        ),
        needs="any",
    ),
    PhysicalKind(
        "flasher",
        "bool",
        "Flasher",
        "Blinks while the command is on, like a pulse sensor.",
        "flasher",
        (
            _duration(
                "flasher_on",
                "flasher",
                "On time",
                "How long each blink stays on.",
                "500ms",
            ),
            _duration(
                "flasher_off",
                "flasher",
                "Off time",
                "How long the feedback stays off between blinks.",
                "500ms",
            ),
        ),
    ),
    PhysicalKind(
        "timed",
        "bool",
        "Timed",
        "Turns on for a set time on each command.",
        "timed",
        (
            _duration(
                "timed",
                "timed",
                "On time",
                "How long the feedback stays on per command.",
                "200ms",
            ),
            PhysicalKey(
                "maintained",
                "timed",
                "flag",
                "Maintained",
                "Stays on for at least the on time, then follows the command.",
                required=False,
                default=False,
            ),
        ),
    ),
    PhysicalKind(
        "toggle",
        "bool",
        "Toggle",
        "Each command flips the feedback (push-on, push-off).",
        "toggle",
        (
            PhysicalKey(
                "toggle",
                "toggle",
                "flag",
                "Toggle",
                "Each new command flips the feedback on or off.",
            ),
        ),
    ),
    PhysicalKind(
        "ramp",
        "analog",
        "Ramp",
        "An analog value that moves at a steady rate.",
        "math",
        (
            PhysicalKey(
                "ramp_on",
                "ramp",
                "number",
                "Rate on",
                "Change per second while the command is on. Negative moves down.",
                unit=_RATE_UNIT,
                suggested="1.0",
            ),
            PhysicalKey(
                "ramp_off",
                "ramp",
                "number",
                "Rate off",
                "Change per second while the command is off. 0 holds the value.",
                unit=_RATE_UNIT,
                required=False,
                default=0.0,
                suggested="-0.5",
            ),
        ),
    ),
    PhysicalKind(
        "approach",
        "analog",
        "Approach",
        "An analog value that closes on a target, fast at first and slower near it.",
        "math",
        (
            PhysicalKey(
                "approach_to",
                "approach",
                "number_or_tag",
                "Target",
                "The number or tag name the value moves toward while the command is on.",
                suggested="100",
            ),
            PhysicalKey(
                "approach_rate",
                "approach",
                "number",
                "Rate",
                "Share of the remaining gap closed per second. The value holds while the command is off.",
                unit=_RATE_UNIT,
                suggested="0.3",
            ),
        ),
    ),
)

pyrung.FeedbackType module-attribute

FeedbackType = Literal['bool', 'analog']

pyrung.PhysicalKey dataclass

One Physical keyword, which is also its comment key.

default is the value when the key is left out (None means nothing). suggested is the comment text a dialog starts with.

dap_field property

dap_field: str

Return the pyrungLink request field for this key: flasher_on -> flasherOn.

parse

parse(text: str) -> Any

Return the Python value for comment text. Raise ValueError naming the key.

check

check(value: Any, *, owner: str) -> Any

Return the stored value for a keyword argument, or raise naming owner and the key.

text

text(value: Any) -> str

Return comment text for a stored value. A flag's text is its key.

token

token(value: Any) -> str

Return the comment token: key=text, or the bare key for a flag.

pyrung.PhysicalKind dataclass

One way a device answers its command, and the keys that describe it.

needs is "any" when at least one key must be given, and "all" when every required key must be. runs_as names the CLICK instruction the kind behaves like.

missing

missing(given: Iterable[str]) -> tuple[str, ...]

Return the keys this kind still needs when given are set.

pyrung.kind_of_keys

kind_of_keys(
    keys: Iterable[str], *, owner: str | None = None
) -> PhysicalKind | None

Return the kind that the response keys keys belong to, or None for no keys.

Raises ValueError for a name that is no response key, for keys of two kinds, and for a kind missing a key it needs (maintained without timed).

pyrung.physical_kind

physical_kind(name: str) -> PhysicalKind

Return the kind called name ("delay", "flasher", ...).

pyrung.Harness dataclass

Automatic feedback harness driven by Physical + link= declarations.

Walks all known tags to find link= couplings and lowers each to plant rungs scanned pre-logic (the input-read phase): an on_delay/off_delay Physical becomes a debounce coil, a flasher_on/flasher_off one a flasher coil, a timed or toggle one the coil of that name, and ramp_on/approach_to math rows on an analog register. No Python tick, no monitors.

The couplings found in the program are the declared ones. Overrides (:meth:set_overrides) replace or cut a declared coupling, or add one, keyed by feedback tag, without touching the program; the harness runs declared couplings plus overrides. unlink is an override that cuts.

Usage::

plc = PLC(logic, dt=0.010)
harness = Harness(plc)
harness.install()
plc.run_for(0.5)  # Fb synthesized automatically

overrides property

overrides: Mapping[str, Coupling | None]

Return the overrides by feedback tag: a coupling to run, or None to cut.

pending_count property

pending_count: int

How many bool couplings are mid-transition this scan.

Under the dwell model there is no schedule heap; a bool coupling is "pending" while its feedback has not yet reached the value its currently sustained enable implies — i.e. an on/off-delay timer is still counting toward a Fb flip. PILOT's settle/coast (run_until pending_count == 0) advances scans until every bool feedback has caught up to its held command, exactly as draining the old heap did.

install

install() -> None

Put the plant on the runner.

Each feedback whose enable is on starts as if the enable had been on for a long time.

fork_onto

fork_onto(
    plc: PLC, *, as_recorded: bool = False
) -> Harness

Create a copy of this harness installed on plc.

The fork inherits the parent's committed state — including each bool timer's accumulator registers — so the dwell carries over with no re-seed; only the (stateless) timer instructions and the carry are copied. This is the seam the synthesis-overlay install grows into.

A state from before a link changed may hold a count in another unit's register, and it moves here unless as_recorded: a replay of the scans as they ran keeps the state they ran from.

unlink(tags: list[str]) -> None

Remove couplings for the named feedback tags.

After unlinking, the Harness no longer synthesizes feedback for these tags — they become free inputs the caller can steer directly. Models a broken sensor or fault scenario.

declared

declared() -> tuple[Coupling, ...]

Return the couplings that the program declares with physical= and link=.

Overrides do not change this list.

set_overrides

set_overrides(
    overrides: Mapping[str, Coupling | None],
) -> None

Replace all overrides and resynthesize.

Each key is a feedback tag name. A Coupling value runs instead of any declared coupling on that feedback (or adds one); None cuts the declared coupling, leaving the feedback a free input. A coupling on a feedback no timer has counted for starts cold: under a held enable the feedback follows after its on-delay, as freshly wired hardware would. A coupling replaced, or cut and linked again, keeps the time its timers have counted, whatever unit the new delays count in. If its enable turned on while it was cut, it counts its on-delay from 0. A timed or toggle coupling new to its feedback takes an enable already on as a rise, so it fires on the next scan.

pending

pending(fb_name: str) -> bool

Return True while a bool coupling on fb_name is still counting toward a flip.

pending_ms

pending_ms() -> dict[str, int]

Return the simulated ms left before each mid-transition bool feedback flips.

Keyed by feedback name. A feedback that agrees with its enable is absent. On a rise the on side counts. On a fall the off side counts, and the debounce drops the feedback a scan after that count is done.

couplings

couplings() -> Iterator[Coupling]

Iterate over all discovered couplings (bool and profile).

advance_profiles

advance_profiles() -> Iterator[Any]

Yield every harness-owned :class:AdvanceProfile.

This is the static reading of "En drives Fb toward a threshold" that PILOT's accumulator resolver consumes exactly like a timer's profile — so how(Fb >= threshold) learns "hold En, coast N scans" without running anything.

A bool coupling is a debounce coil, and the coil's own profile holds the enable at the value wanted. The coil is not in the user's :class:Program, so a walk of the program alone cannot find it. A flasher coil has no profile and an analog coupling has no instruction to give one, so their profiles are built here. So are those of a timed or toggle coil (see :meth:_edge_profile).

pyrung.Coupling dataclass

Public view of one enable→feedback coupling discovered by the harness.

pyrung.system module-attribute

system = SystemNamespaces(
    sys=SysNamespace(
        always_on=Bool("sys.always_on"),
        first_scan=Bool("sys.first_scan"),
        scan_clock_toggle=Bool("sys.scan_clock_toggle"),
        clock_10ms=Bool("sys.clock_10ms"),
        clock_100ms=Bool("sys.clock_100ms"),
        clock_500ms=Bool("sys.clock_500ms"),
        clock_1s=Bool("sys.clock_1s"),
        clock_1m=Bool("sys.clock_1m"),
        clock_1h=Bool("sys.clock_1h"),
        mode_switch_run=Bool("sys.mode_switch_run"),
        mode_run=Bool("sys.mode_run"),
        cmd_mode_stop=Bool("sys.cmd_mode_stop"),
        cmd_watchdog_reset=Bool("sys.cmd_watchdog_reset"),
        fixed_scan_mode=Bool("sys.fixed_scan_mode"),
        battery_present=Bool("sys.battery_present"),
        scan_counter=Int(
            "sys.scan_counter", retentive=False
        ),
        scan_time_current_ms=Int(
            "sys.scan_time_current_ms", retentive=False
        ),
        scan_time_min_ms=Int(
            "sys.scan_time_min_ms", retentive=False
        ),
        scan_time_max_ms=Int(
            "sys.scan_time_max_ms", retentive=False
        ),
        scan_time_fixed_setup_ms=Int(
            "sys.scan_time_fixed_setup_ms", retentive=False
        ),
        interrupt_scan_time_ms=Int(
            "sys.interrupt_scan_time_ms", retentive=False
        ),
        dt=Real("sys.dt", retentive=False),
    ),
    rtc=RtcNamespace(
        year4=Int("rtc.year4", retentive=False),
        year2=Int("rtc.year2", retentive=False),
        month=Int("rtc.month", retentive=False),
        day=Int("rtc.day", retentive=False),
        weekday=Int("rtc.weekday", retentive=False),
        hour=Int("rtc.hour", retentive=False),
        minute=Int("rtc.minute", retentive=False),
        second=Int("rtc.second", retentive=False),
        new_year4=Int("rtc.new_year4", retentive=False),
        new_month=Int("rtc.new_month", retentive=False),
        new_day=Int("rtc.new_day", retentive=False),
        new_hour=Int("rtc.new_hour", retentive=False),
        new_minute=Int("rtc.new_minute", retentive=False),
        new_second=Int("rtc.new_second", retentive=False),
        apply_date=Bool("rtc.apply_date"),
        apply_date_error=Bool("rtc.apply_date_error"),
        apply_time=Bool("rtc.apply_time"),
        apply_time_error=Bool("rtc.apply_time_error"),
    ),
    fault=FaultNamespace(
        plc_error=Bool("fault.plc_error"),
        division_error=Bool("fault.division_error"),
        out_of_range=Bool("fault.out_of_range"),
        address_error=Bool("fault.address_error"),
        math_operation_error=Bool(
            "fault.math_operation_error"
        ),
        code=Int("fault.code", retentive=False),
    ),
    firmware=FirmwareNamespace(
        main_ver_low=Int(
            "firmware.main_ver_low", retentive=False
        ),
        main_ver_high=Int(
            "firmware.main_ver_high", retentive=False
        ),
        sub_ver_low=Int(
            "firmware.sub_ver_low", retentive=False
        ),
        sub_ver_high=Int(
            "firmware.sub_ver_high", retentive=False
        ),
    ),
    storage=StorageNamespace(
        sd=StorageSdNamespace(
            eject_cmd=Bool("storage.sd.eject_cmd"),
            delete_all_cmd=Bool(
                "storage.sd.delete_all_cmd"
            ),
            ready=Bool("storage.sd.ready"),
            write_status=Bool("storage.sd.write_status"),
            error=Bool("storage.sd.error"),
            error_code=Int(
                "storage.sd.error_code", retentive=False
            ),
        )
    ),
)