Modelling MDPs¶
Everything you import when writing an MDP, a State class, or a policy.
These names live in dynaplex.modelling. Event distributions and random
number generation are on the
distributions & randomness page; the language rules for
compiled code are in the language reference.
The MDP contract¶
There is no universal state class in DynaPlex. Each MDP defines its own
State: a plain dataclass holding exactly the quantities that describe the
system between decisions, plus one required field, category, which tells
the engine whether the state next expects an event or an action. For the
airplane ticket MDP, that looks like:
@dataclass(slots=True)
class State:
remaining_days: int
remaining_seats: int
price_offered_per_seat: int
category: StateCategory = StateCategory.AWAIT_EVENT
In the signatures below, StateType is a type variable standing for
whatever State class your MDP defines — MDPProtocol is generic in it.
An MDP, then, is a class whose methods operate on that state: it creates
one (get_initial_state) and modifies it in place
(modify_state_with_event, modify_state_with_action,
write_action_validity). A policy operates on the same State class, and
this shared type is what ties them together: assert_policy_for_mdp
lets the type checker verify that a policy's StateType matches its
MDP's.
What is a protocol, and why the assert_* functions?
A protocol is
Python's way of describing an interface by shape rather than by
inheritance: any class that has the listed attributes and methods
satisfies MDPProtocol — you never subclass it or import it into your
model. That leaves one gap: nothing tells you when your class doesn't
match, e.g. a misspelled method or a wrong signature. That is what
assert_mdp and friends are for. They do nothing at runtime, but a call
like assert_mdp(mdp) gives a type checker such as
pyright a place to verify
conformance, so pyright my_model.py reports exactly which member is
missing or mistyped — before anything is run or compiled.
MDPProtocol ¶
Bases: Protocol[StateType, ContextType]
The interface every DynaPlex MDP class implements.
An MDP class provides two attributes — horizon_type and
num_actions — and four methods operating on a user-defined State
class: get_initial_state, modify_state_with_event,
modify_state_with_action, and write_action_validity.
This is a structural protocol: any class with these members satisfies
it, no inheritance needed. Call assert_mdp on an instance to have the
type checker verify conformance (a no-op at runtime).
Optionally an MDP declares its own trajectory context — a
@trajectory_context class carrying per-trajectory statistics — by adding
make_context(self) -> MyContext (the sibling of get_initial_state:
the return annotation declares the class, the body constructs it) and
annotating the context parameters of the transition methods with the
same class. See MakesContext and trajectory_context.
Example
A minimal skeleton (see the tutorials for complete models):
@const_dataclass(init=False, slots=True)
class MyMDP:
horizon_type: HorizonType
num_actions: int
def get_initial_state(self, context: TrajectoryContext) -> MyState:
...
def modify_state_with_event(
self, state: MyState, context: TrajectoryContext
) -> None:
...
def modify_state_with_action(
self, state: MyState, context: TrajectoryContext, action: int
) -> None:
...
def write_action_validity(self, state: MyState, valid: Validity) -> None:
...
assert_mdp(MyMDP(...)) # pyright verifies protocol conformance
get_initial_state ¶
Generates and returns an initial state of the MDP.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
ContextType
|
Trajectory context; its |
required |
Returns:
| Type | Description |
|---|---|
StateType
|
The initial state of the MDP. |
modify_state_with_event ¶
Generate an event and modify state in place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
StateType
|
Current state (modified in place) |
required |
context
|
ContextType
|
Trajectory context containing rng and cumulative_cost |
required |
modify_state_with_action ¶
Apply an action to the state (modify in place).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
StateType
|
Current state (modified in place) |
required |
context
|
ContextType
|
Trajectory context containing cumulative_cost (updated in place) |
required |
action
|
int
|
Action to apply to the state |
required |
write_action_validity ¶
write_action_validity(state: StateType, valid: Validity) -> None
valid.set(i, True) if action i is allowed in the current state,
valid.set(i, False) otherwise — for EVERY i in range(num_actions).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
StateType
|
Current state |
required |
valid
|
Validity
|
Validity sink to write the mask to (not pre-initialised) |
required |
Policies: the two shapes¶
A policy maps a decision state to an action index. DynaPlex recognizes
exactly two get_action signatures and tells the policy kinds apart by
shape:
@const_dataclass
class GreedyPolicy: # deterministic — by construction
mdp: MyMDP
def get_action(self, state: MyState) -> int: ...
@const_dataclass
class NoisyPolicy: # context-driven
mdp: MyMDP
def get_action(self, state: MyState, context: TrajectoryContext) -> int: ...
A policy with the (self, state) signature is deterministic by
construction: it is never handed a source of randomness, so there is
nothing it could draw from. Adding the second parameter — the exact name
context with the exact annotation TrajectoryContext — makes the policy
context-driven: the built-in algorithms (the
comparer, DCL)
pass the trajectory's context on every call. Through it the policy can use:
context.policy_rng— a random stream dedicated to policy draws, separate from the event stream and reseeded per trajectory from global coordinates. Results with a context-driven policy are therefore reproducible, independent of the number of worker threads, and safe for common-random-number comparisons.context.valid— a reusable action-validity scratch (aValidityWritersized to the MDP's action space). Hand it tomdp.write_action_validity(state, context.valid)and read the mask back from it — no per-call allocation. It is overwritten on every use and carries no meaning between calls.
The shape is validated before anything compiles or runs: exact parameter
names, exact annotations, plain positional parameters, no defaults and no
*args. Anything else is rejected with an error naming both accepted
signatures.
Rules a context-driven policy must follow
The context also exposes trajectory state that a policy must leave
alone. Draw only from context.policy_rng — never from
context.rng, which is the MDP's event stream (touching it silently
breaks common-random-number comparisons) — and never write
context.cumulative_cost or context.time_elapsed. These rules are
not yet enforced mechanically; today they are part of the contract.
PolicyProtocol ¶
Bases: Protocol[PolicyStateType]
The interface every DynaPlex policy class implements.
A policy provides one method: get_action(state) -> int, mapping a
state awaiting a decision to the index of the chosen action. This is a
structural protocol — no inheritance needed; call assert_policy_for_mdp
to have the type checker verify that a policy fits an MDP (their State
types must match).
Example
A minimal rule-based policy (see the tutorials for complete models):
get_action ¶
Determine which action to take given the current state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
PolicyStateType
|
Current state |
required |
Returns:
| Type | Description |
|---|---|
int
|
Action index (must be valid for the current state according to the MDP) |
ContextPolicyProtocol ¶
Bases: Protocol[PolicyStateType, ContextType]
The interface of a CONTEXT-DRIVEN DynaPlex policy.
Identical to PolicyProtocol except that get_action receives a second
argument: the trajectory's context — TrajectoryContext, or the MDP's own
@trajectory_context class when it declares one (the policy must annotate
the SAME class as the MDP's transition methods). Through it the policy may
draw from the dedicated POLICY stream (context.policy_rng — independent
of the event stream, so policy draws never perturb event draws and
common-random-number comparisons across policies stay valid) and use the
context's reusable action-validity scratch (context.valid, a
ValidityWriter to hand to mdp.write_action_validity — no per-call
allocation).
The two signatures are how DynaPlex tells the policy kinds apart: a policy
whose get_action takes (self, state) is deterministic BY
CONSTRUCTION (it is never handed a source of randomness); adding the
context: <the MDP's context class> parameter — that exact name —
makes it context-driven, and the built-in algorithms (PolicyComparer, DCL)
hand it the per-trajectory context. The context's policy stream is reseeded
per trajectory from global coordinates, so results stay reproducible and
worker-count-invariant.
Convention (not yet enforced): a policy must only use context.policy_rng
for randomness — never context.rng, the event stream — and must not
write context.cumulative_cost / context.time_elapsed. Mechanical
validation of this contract is future work (roadmap
mdp_validation_improvements).
Example:
```python
@const_dataclass
class EpsilonGreedyPolicy:
mdp: MyMDP
eps: float
def get_action(self, state: MyState, context: TrajectoryContext) -> int:
if context.policy_rng.random() < self.eps:
return context.policy_rng.choice(2)
return 1 if state.inventory < 5 else 0
```
get_action ¶
Determine which action to take given the current state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
PolicyStateType
|
Current state |
required |
context
|
ContextType
|
The trajectory's context — use |
required |
Returns:
| Type | Description |
|---|---|
int
|
Action index (must be valid for the current state according to the MDP) |
States and trajectories¶
StateCategory ¶
Bases: Enum
The category of a state, determining which operation runs next.
Every DynaPlex state carries a category field of this type; the
trajectory loop dispatches on it:
- AWAIT_EVENT: a random event is next —
modify_state_with_eventruns - AWAIT_ACTION: a decision is next — the policy picks an action and
modify_state_with_actionruns - FINAL: terminal state (finite-horizon MDPs); the trajectory has ended
HorizonType ¶
Bases: Enum
Horizon type determines whether the MDP has a finite or infinite horizon.
- FINITE: Episodes naturally terminate (reach StateCategory.FINAL)
- INFINITE: Episodes never naturally terminate (simulation must be limited externally)
TrajectoryContext
dataclass
¶
Context information for a trajectory/episode — the vanilla context every MDP
runs with unless it declares its own (see trajectory_context and the
make_context MDP method).
- rng: event stream — dynaplex.Generator (xoshiro256++); CPython draws are bit-identical to compiled draws
- policy_rng: policy stream, separate so that policy draws never perturb the event stream (common-random-number comparisons across policies stay valid even when a policy is randomized)
- cumulative_cost: running total of costs
- time_elapsed: number of time steps elapsed in the trajectory
- valid: reusable action-validity scratch for context-driven policies (a writer over a dedicated single-row [1, num_actions] mask, fully overwritten by each policy call, never reset between trajectories)
Construct with TrajectoryContext(mdp) and reseed(seed) it before use; the
kernels do this per trajectory. Seeds given at construction are placeholders.
TrajectoryStats
dataclass
¶
TrajectoryStats(cumulative_cost: Final[Annotated[NDArray[np.float64], Rank(1)]], time_elapsed: Final[Annotated[NDArray[np.int64], Rank(1)]])
The statistics holder of the vanilla context, and the base of every
user-declared holder: the two base scalars, one value per trajectory.
A holder field is the context field with one leading trajectory axis, so a
scalar becomes 1-D and a k-D array becomes (k+1)-D (Array2D for a
1-D statistic, ...). Every field is Final — the holder is a bundle,
filled row by row by the kernels.
trajectory_context ¶
Trajectory contexts — the per-trajectory bookkeeping object of DynaPlex MDPs (roadmap/comparer_statistics.md).
Every trajectory runs with a context: the random streams, the cumulative cost,
the elapsed time and an action-validity scratch. TrajectoryContext is the
library's vanilla context. An MDP that wants per-trajectory STATISTICS declares
its own context class — a @trajectory_context dataclass with the same five
base members plus scalar / Final[ndarray] statistics — and constructs it in a
make_context(self) method (the sibling of get_initial_state).
This module is the single home of the stream convention: @trajectory_context
synthesizes reseed, which gives every Final[Generator] field its own
combine_seeds stream in declaration order (rng = 0, policy_rng = 1, ...).
Scratch
module-attribute
¶
Per-trajectory scratch on a @trajectory_context: Scratch[int],
Scratch[NDArray[np.int64]], Final[Scratch[Array2D[np.float64]]]. Same types
as a statistic (float/int/bool scalars, float/int/bool ndarrays of any rank),
carried by clones — but neither collected (absent from Stats, write_stats,
stats_spec) nor touched by reset(): the kernels never write it, so its
validity is the POLICY's responsibility (a reset may in principle happen at any
point of a trajectory, and the context has no idea what the scratch means).
The home of intermediate storage a context-driven policy needs across the
decisions of one trajectory (a production plan, a cached ranking); decide from
the STATE when it is stale (e.g. "first decision of a period") rather than from
anything the context did. Scratch ndarrays may be Final (in-place mutation, no
allocation in the loop — recommended) or not.
MakesContext ¶
Bases: Protocol[_CtxT]
An MDP that declares + constructs its own trajectory context. The return
annotation of make_context IS the declaration (a TypeVar slot here, so the
protocol matches any annotated return type; the concrete class is read off
the MDP's own annotation by infer_context_type and by the compiler).
HasStats ¶
Bases: Protocol[_StatsT]
A context that names its statistics holder: Stats = MyStats in the class
body (see trajectory_context). Matched structurally by PolicyComparer to
type assessment.stats.
TrajectoryStats
dataclass
¶
TrajectoryStats(cumulative_cost: Final[Annotated[NDArray[np.float64], Rank(1)]], time_elapsed: Final[Annotated[NDArray[np.int64], Rank(1)]])
The statistics holder of the vanilla context, and the base of every
user-declared holder: the two base scalars, one value per trajectory.
A holder field is the context field with one leading trajectory axis, so a
scalar becomes 1-D and a k-D array becomes (k+1)-D (Array2D for a
1-D statistic, ...). Every field is Final — the holder is a bundle,
filled row by row by the kernels.
TrajectoryContext
dataclass
¶
Context information for a trajectory/episode — the vanilla context every MDP
runs with unless it declares its own (see trajectory_context and the
make_context MDP method).
- rng: event stream — dynaplex.Generator (xoshiro256++); CPython draws are bit-identical to compiled draws
- policy_rng: policy stream, separate so that policy draws never perturb the event stream (common-random-number comparisons across policies stay valid even when a policy is randomized)
- cumulative_cost: running total of costs
- time_elapsed: number of time steps elapsed in the trajectory
- valid: reusable action-validity scratch for context-driven policies (a writer over a dedicated single-row [1, num_actions] mask, fully overwritten by each policy call, never reset between trajectories)
Construct with TrajectoryContext(mdp) and reseed(seed) it before use; the
kernels do this per trajectory. Seeds given at construction are placeholders.
validity_scratch ¶
A context's own single-row action-validity scratch: a ValidityWriter over
a dedicated [1, num_actions] mask, fully overwritten by every context-driven
policy call and never reset between trajectories. The one ValidityWriter
construction a context __init__ ever writes.
context_fields ¶
The validated field table of a decorated context class, in declaration order: (name, kind, info) with kind in {'scalar', 'array', 'generator', 'generator_list', 'valid'}; info['scratch'] marks a Scratch[...] scalar/array (neither reset nor collected).
collected_fields ¶
(name, dtype, rank) of the COLLECTED fields — scalars (rank 0) and arrays, minus
Scratch — in declaration order: exactly the fields of the derived Stats holder,
which adds one leading trajectory axis to each.
allocate_stats ¶
A zeroed type(ctx).Stats holder for n trajectories, sized from
ctx.stats_spec() (CPython; the comparer's allocation step).
trajectory_context ¶
Class decorator (apply ABOVE @dataclass; slots=True is optional — note
that zero-arg super() does not work inside a slots=True dataclass in
CPython) for trajectory
context classes: validates the closed field table and synthesizes the absent
housekeeping methods.
Field table: the five base members first (rng: Final[Generator],
policy_rng: Final[Generator], cumulative_cost: float, time_elapsed: int,
valid: Final[ValidityWriter]), then any number of statistics — float /
int / bool scalars (re-assignable), Final[NDArray[...]] of float / int /
bool dtype (fixed shape, mutated in place) — extra Final[Generator]
streams, Final[list[Generator]] (a fixed number of streams decided in
__init__, e.g. one per action), and per-trajectory SCRATCH: the same scalars / ndarrays wrapped in
Scratch[...] (carried by clones, but neither collected nor reset — the
kernels never write it; intermediate storage owned by a context-driven
policy, which decides from the state when it is stale; a scratch ndarray
need not be Final). Nothing else (in particular no other lists). Scalars are the only
non-Final fields apart from scratch ndarrays.
Statistics holder. Name it as a class attribute — Stats = MyStats in the
class body, with @dataclass class MyStats(TrajectoryStats) — carrying
exactly the collected fields (cumulative_cost, time_elapsed, every
statistic) under the same names, each Final with one leading trajectory
axis (a scalar -> Array1D, a 1-D array -> Array2D, ...). The decorator
checks names, dtypes, ranks and Final; pyright then types
PolicyComparer(mdp).assess(...).stats as MyStats. Without Stats the
holder is DERIVED (MyContext.Stats, named <Context>Stats) — same
runtime, but untyped (Any) for pyright.
Synthesized: reseed(global_seed, eval=0, sample=0, trajectory=0) — every
generator field gets its own combine_seeds stream, in declaration order,
then every generator of every list
(never hand-written: the stream convention is machine-owned) — and reset()
— zero every scalar and zero-fill every array in place, generators and
scratch untouched (hand-written reset wins); write_stats(out, row) — copy every collected
field into row row of the holder Cls.Stats (a hand-written write_stats
names its own holder in its out annotation and is not checked) — and
stats_spec() (CPython-only, sizes read off the instance). The first three
compile: the kernels call them per trajectory. Construction is the class's own
business: write __init__(self, mdp) (recommended — shapes come straight off
the MDP) and construct the context in the MDP's make_context(self). The five
base members are inherited from TrajectoryContext: call super().__init__(mdp)
first in __init__ (roadmap/dataclass_inheritance.md).
new_context ¶
The one context factory: the MDP's own make_context() when it declares
one, else a vanilla TrajectoryContext — SEEDED: the streams are derived
from seed (reseed(seed)), so rng and policy_rng differ and two
contexts with different seeds differ. The engine reseeds per trajectory
anyway; the seed here is for hand-driven simulation. Compiled,
implements is a constexpr-if resolved per MDP type (the untaken branch
is discarded); in CPython it is the same memoized conformance check.
Typed by two overloads: an MDP with make_context(self) -> MyContext yields
MyContext (pyright follows the MDP's own annotation), any other MDP yields
TrajectoryContext.
infer_context_type ¶
The MDP's context class: read off the context annotation of
get_initial_state / modify_state_with_event / modify_state_with_action
and, when present, make_context's return annotation — all of which must
agree. A custom context without make_context is an error (the kernels
could not construct it). The result is what the kernels bind Ctx to.
MakesContext ¶
Bases: Protocol[_CtxT]
An MDP that declares + constructs its own trajectory context. The return
annotation of make_context IS the declaration (a TypeVar slot here, so the
protocol matches any annotated return type; the concrete class is read off
the MDP's own annotation by infer_context_type and by the compiler).
HasStats ¶
Bases: Protocol[_StatsT]
A context that names its statistics holder: Stats = MyStats in the class
body (see trajectory_context). Matched structurally by PolicyComparer to
type assessment.stats.
new_context ¶
The one context factory: the MDP's own make_context() when it declares
one, else a vanilla TrajectoryContext — SEEDED: the streams are derived
from seed (reseed(seed)), so rng and policy_rng differ and two
contexts with different seeds differ. The engine reseeds per trajectory
anyway; the seed here is for hand-driven simulation. Compiled,
implements is a constexpr-if resolved per MDP type (the untaken branch
is discarded); in CPython it is the same memoized conformance check.
Typed by two overloads: an MDP with make_context(self) -> MyContext yields
MyContext (pyright follows the MDP's own annotation), any other MDP yields
TrajectoryContext.
validity_scratch ¶
A context's own single-row action-validity scratch: a ValidityWriter over
a dedicated [1, num_actions] mask, fully overwritten by every context-driven
policy call and never reset between trajectories. The one ValidityWriter
construction a context __init__ ever writes.
Validity
module-attribute
¶
Annotation for the action-validity mask parameter of write_action_validity.
The MDP method signature is def write_action_validity(self, state, valid:
Validity) -> None; inside, mark allowed actions with valid.set(a, cond).
At least one action must remain valid in every AWAIT_ACTION state.
For a worked example (accept/reject constrained by remaining seats), see
write_action_validity in the
airplane tutorial code.
Const classes and annotations¶
Compiled DynaML code relies on a few concepts that standard Python has no
syntax for — most importantly constness: MDP and policy objects are
read-only during a trajectory, and marking their classes with
@const_dataclass lets the compiler enforce and exploit that. Similarly,
the compiler needs some information that ordinary annotations do not
carry, such as the rank of a NumPy array field; the Rank, Array*D and
ConstArray*D annotations supply it. The names below are the API for
declaring all of this; what constness means inside compiled methods,
and the rules for array dtypes and ranks, are explained in the language
reference under
const classes and read-only containers
and NumPy arrays.
const_dataclass ¶
Declare a read-only DynaML dataclass — the standard decorator for MDP and policy classes.
Combines @dataclass with const marking: every instance of the
decorated class (and everything reachable through its object-typed
fields) is read-only in compiled DynaML code. This is the required
convention for MDP and policy classes, whose self must not change
during a trajectory: construct and fill the object in __init__
(plain CPython, unrestricted — load data, validate, precompute), and
compiled methods then only read it.
Accepts the same keyword arguments as @dataclass. The common form
for an MDP is @const_dataclass(init=False, slots=True) with a
hand-written __init__:
Example
@const_dataclass(init=False, slots=True)
class MyMDP:
num_actions: int
demand_dist: DiscreteDist
demand_sampler: AliasSampler
def __init__(self, mean_demand: float):
# plain CPython: unrestricted
self.num_actions = 2
self.demand_dist = DiscreteDist.poisson(mean_demand)
self.demand_sampler = self.demand_dist.alias_sampler()
Const ¶
Metadata marker for Annotated types: declares a list or NDArray as const.
Usage
Annotated[list[int], Const()] Annotated[NDArray[np.float64], Const()]
Rank ¶
Rank metadata for ndarray annotations.
Intended usage
Annotated[NDArray[np.float64], Rank(2)]
Array1D
module-attribute
¶
Array1D: TypeAlias = Annotated[NDArray[_NDArrayScalar], Rank(1)]
A 1-dimensional NumPy array annotation.
In DynaML, every array annotation must fix both the number of dimensions and
the element dtype: Array1D[np.float64] declares a 1-dimensional ndarray
holding float64 values. The allowed dtypes are np.float64, np.float32,
np.int64, and np.bool_. (Equivalent to
Annotated[NDArray[np.float64], Rank(1)].)
Array2D
module-attribute
¶
Array2D: TypeAlias = Annotated[NDArray[_NDArrayScalar], Rank(2)]
A 2-dimensional NumPy array annotation, e.g. Array2D[np.int64] — see
Array1D for the dimension-and-dtype rules.
Array3D
module-attribute
¶
Array3D: TypeAlias = Annotated[NDArray[_NDArrayScalar], Rank(3)]
A 3-dimensional NumPy array annotation, e.g. Array3D[np.float32] — see
Array1D for the dimension-and-dtype rules.
ConstList
module-attribute
¶
ConstList: TypeAlias = Annotated[list[_T], Const()]
A read-only list annotation: ConstList[int] declares a list whose
contents compiled code may read but not modify. (Equivalent to
Annotated[list[int], Const()].)
ConstArray1D
module-attribute
¶
A read-only 1-dimensional NumPy array annotation, e.g.
ConstArray1D[np.float64]: compiled code may read but not write the array.
See Array1D for the dimension-and-dtype rules.
ConstArray2D
module-attribute
¶
A read-only 2-dimensional NumPy array annotation — see ConstArray1D.
ConstArray3D
module-attribute
¶
A read-only 3-dimensional NumPy array annotation — see ConstArray1D.
Copying state¶
clone ¶
clone — deep copy for branching (e.g. Sequential-Halving rollouts) — and
clone_into — deep IN-PLACE assignment.
clone(x) returns an independent, MUTABLE copy of x; everything DEEPLY const it reaches
is SHARED (linked), not duplicated. A structurally-const list of MUTABLE-class elements is
NOT deeply const: it is copied and its elements cloned (both here and in the interpreter).
This is a real Python function (used when DynaML code runs in pure CPython) AND is
recognized by the interpreter frontend as a builtin that lowers to the C++ clone opcode —
the same dual role as sync_worlds.
clone_into(src, dst) recursively overwrites dst's contents so it becomes value-equal
to a deep copy of src, preserving dst's identity (objects, lists, ndarray backings)
wherever structure matches. THIS function is the semantic spec the interpreter builtin is
parity-tested against; it carries the same two-map algorithm as the C++ walker (memo on
id(src) reproduces src-side sharing; consumed on id(dst) prevents a dst object already
claimed at one position from being overwritten again from another). Same-store row reuse
in the interpreter corresponds exactly to in-place mutation here.
Const detection here is by explicit @const_dataclass (__dynapl_const__). The interpreter
shares by the propagated const flag; the two differ only for a class that is const only
by propagation (never decorated), and only in is-identity (value-equivalent, since const
is immutable). The same identity-only caveat applies to deeply-const LISTS and const
ndarray fields (no runtime const marker exists here, so the clone mirror copies them; the
interpreter shares them — value-equivalent because they are immutable). DCL's shared
immutable data is always explicitly const, so it is exact there. clone_into reads FIELD
const-ness from the Annotated[..., Const()] hints, so its links are exact.
clone ¶
Deep-copy x: independent mutable copy, sharing const_dataclass subgraphs.
Typed identity (clone(x) has the same static type as x) so type checkers keep the
argument's type instead of collapsing to Any.
clone_into ¶
Deep in-place assignment: overwrite dst so it becomes value-equal to a deep
copy of src, preserving dst's identity wherever structure matches.
Both arguments must be two instances of the same MUTABLE dataclass, or two lists of
the same type. External aliases of reused dst sub-objects observe the new values
(that is the defined semantics, not an accident); where structure mismatches (None
flips, ndarray shape changes, aliasing duals) the affected position falls back to a
fresh clone. Overlapping src/dst graphs are unsupported. clone_into(x, x) is a
no-op. Returns None (unmistakably a mutation).
Validating your model¶
assert_mdp ¶
assert_mdp(mdp: MDPProtocol[StateType, ContextType]) -> MDPProtocol[StateType, ContextType]
Type assertion function for MDP protocol validation.
This is a no-op function at runtime, but type checkers (like pyright) will verify that the provided MDP satisfies the MDPProtocol interface. The type checker automatically infers StateType and ContextType from the MDP's method signatures.
This pattern enables static type checking of protocol conformance without runtime overhead. If the MDP doesn't satisfy the protocol, the type checker will report an error.
It does not run the model. For that, call dynaplex.check_mdp (plain-Python
trajectories that catch a degenerate decision structure — a category that never
changes, time that never advances, an unwritten validity mask, no real choice at
any decision) and then dynaplex.rehearse (the checked compiled pass with
CPython parity). The static promises (@mdp, @policy) are checked when a
harness compiles the model.
assert_policy_for_mdp ¶
assert_policy_for_mdp(mdp: MDPProtocol[StateType, ContextType], policy: PolicyProtocol[StateType]) -> PolicyProtocol[StateType]
Type assertion function for validating policy compatibility with an MDP.
This is a no-op function at runtime, but type checkers (like pyright) will verify that the policy's StateType matches the MDP's StateType. The type checker automatically infers StateType from both the policy's and MDP's method signatures and ensures they are compatible.
This pattern enables static type checking of policy-MDP compatibility without runtime overhead. If the policy doesn't work with the MDP (different StateType), the type checker will report an error.
It does not run the policy. To see it act on the model, call
dynaplex.check_mdp(mdp, policy) (plain-Python trajectories; fails if the policy
ever picks an action the MDP marks invalid, among the model-level checks) and
then dynaplex.rehearse(mdp, policy) (the checked compiled pass with CPython
parity).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mdp
|
MDPProtocol[StateType, ContextType]
|
MDP instance to check compatibility with |
required |
policy
|
PolicyProtocol[StateType]
|
Policy instance to validate |
required |
Returns:
| Type | Description |
|---|---|
PolicyProtocol[StateType]
|
The same policy instance (for chaining if needed) |
assert_featurizer_for_mdp ¶
assert_featurizer_for_mdp(features_cls, mdp) -> dict[str, TensorSpec]
Validate a featurizer class against an MDP and return its spec.
Declaration is truth, the probe is the TEST: field-walk strictness, spec structure, then a dress rehearsal — allocate a ONE-ROW holder at the declared sizes and drive the real path (bind / reset / write_features / finish) on a probe state. A spec that disagrees with what write_features actually writes dies here, loudly, at sizing time (writer overflow on too-small, finish underfill on too-large) — never as a silently mis-shaped slab.
implements ¶
Does obj's class conform to proto? The instance form used in kernels;
inside compiled code it is a COMPILE-TIME constant, legal only as the entire
condition of an if/else (the untaken branch is discarded before
type-checking). In plain CPython it is this ordinary memoized function.
conforms ¶
Does class cls structurally conform to protocol proto? (Memoized.)
Promises¶
A class can carry promises about what its methods do to their parameters; the compiler checks them whenever the methods compile (the named promises, their assumptions and fixes: Promises reference; the short form: language reference → Promises).
dynaplex.mdp— class decorator, above@const_dataclass: the class promises the base MDP contract (dynaplex.validation.BASE_MDP_CONTRACT) formodify_state_with_event,modify_state_with_actionandwrite_action_validity.@mdp(promises=contract)appends a furtherRoleContract.dynaplex.policy— the same for a policy'sget_action(BASE_POLICY_CONTRACT).@featurizerattachesFEATURIZER_CONTRACT(write_featuresonly reads the state) by itself.dynaplex.validation—validate(engine_or_program, contract, cls=...)returning aVerdict(ok,violations,format(),raise_if_any()), andDISCRETE_IDENTIFIABLE_EVENTS, the set the exact solver requires.
from dynaplex import Engine, mdp, const_dataclass
from dynaplex.validation import DISCRETE_IDENTIFIABLE_EVENTS, validate
@mdp
@const_dataclass(init=False, slots=True)
class MyMDP:
...
verdict = validate(Engine(MyMDP, *ctor_args), DISCRETE_IDENTIFIABLE_EVENTS, cls=MyMDP)
print(verdict.format()) # "ok (2 function(s) checked)" or the violations
Failing on purpose¶
fail ¶
dynaplex.fail(msg) — unconditional failure (roadmap/checks_mode.md §2).
Unlike assert, which is a check and is compiled out in fast mode, fail
is control flow: it always fires, in every mode. Use it for the "cannot
happen" branch of a decision (no feasible action, unreachable case), where
reaching the statement is a definite error rather than a violated invariant.
Compiled: lowers to TRAP with the message; typed NoReturn — the statement
closes its block, so a function may end on it and code after it is dead.
CPython: raises dynaplex.DynaPlexError(msg) (the same type the engine
raises), so the two runtimes agree.
The message must be a string literal or a simple f-string (same rules as
assert messages: bare {expr} placeholders are kept as text).
fail ¶
Raise DynaPlexError(msg); compiled code traps with the same message.
Compile-time requirements¶
static_require ¶
dynaplex.static_require(condition, message) — a compile-time requirement.
The condition is evaluated the way the head of if static(condition): is
(roadmap/folding.md): it must be STATICALLY KNOWN — a constant, a chain of
Final/const hops from the engine root, an enum comparison, or a constexpr
implements(obj, Protocol) — and the compiler decides at compile time:
- known True: the statement compiles to NOTHING;
- known False: a COMPILE ERROR carrying the message and the site;
- not statically known: the
static()diagnostic naming the hop that broke the chain.
Because it fires only when the statement is actually compiled, a
static_require(False, "...") in a method body is the "this method must never
be compiled" stub: a pruned static()/implements() branch never reaches
it, and a method nobody calls is never compiled. The exact solver's
EventProbe uses it for the generator methods it cannot enumerate.
Unlike assert it is never stripped — it is not a check but a requirement
on the configuration being compiled, present in every checks mode. Unlike
dynaplex.fail it is decided before any code runs.
CPython: an ordinary always-on check — condition is evaluated as plain
Python (static is the identity, implements the real conformance test)
and a falsy value raises dynaplex.DynaPlexError(message).
The message must be a string literal or a simple f-string (the fail /
assert-message rules); the Literal[False] overload lets a type checker see
the stub form as NoReturn.
static_require ¶
Raise DynaPlexError(message) unless condition holds; compiled code
decides at compile time (known False = compile error).