Python

Everything below is importable from ddma unless the section names a submodule.

Data and partitions

class RectangularPartition(edges)[source]

Product partition of the box [lo, hi] into rectangular cells.

classmethod uniform(lo, hi, n_cells)[source]

Uniform partition of [lo, hi] with n_cells[i] cells along coordinate i.

classmethod with_margins(lo, hi, inner_lo, inner_hi, n_inner)[source]

Uniform cells on [inner_lo, inner_hi] plus one margin cell on each side.

Edges are [lo, linspace(inner_lo, inner_hi, n_inner + 1), hi] per coordinate; a margin cell is dropped where inner_lo == lo (or inner_hi == hi). This is the partition used in the experiments of the TAC and ADHS papers.

classmethod from_data(Z, lo, hi)[source]

Data-induced partition: one breakpoint per distinct data coordinate.

On this partition the fixed-partition simulating map coincides with the minimal simulating map (almost everywhere). The number of cells is up to (|K| + 1)^n, so this is only practical for small data sets or low dimension.

classmethod product(*parts)[source]

Cartesian product of partitions (coordinates concatenated in order).

property ndim

Number of coordinates.

property shape

Number of cells along each coordinate.

property n_cells

Total number of cells.

property lo

Lower corner of the partitioned box.

property hi

Upper corner of the partitioned box.

project(dims)[source]

Partition of the selected coordinates.

same_as(other)[source]

Whether both partitions have the same edges.

search(i, values, side='right')[source]

np.searchsorted(self.edges[i], values, side), O(1) per value on uniform axes.

On a uniform axis the index is computed arithmetically and then corrected by comparing with the actual edges, so the result is identical to searchsorted.

contains(Z)[source]

Boolean mask of points inside the closed box [lo, hi].

locate(Z)[source]

Cell index (N, n) of each point. Points outside [lo, hi] raise ValueError.

cell_bounds(idx)[source]

Lower and upper corners of the cells with index array idx (N, n).

cell_centers(idx)[source]

Centres of the cells with subscripts idx (K, n).

all_indices()[source]

All cell indices in C order, shape (n_cells, n).

grid_bounds()[source]

Lower/upper corners of all cells as arrays of shape (*shape, n).

box_to_cells(a, b)[source]

Index range of the cells that intersect the closed boxes [a, b].

a and b are (N, n) arrays inside [lo, hi]. Returns (first, last) index arrays; the cells meeting [a_k, b_k] are exactly first_k <= q <= last_k.

transitions_to_data(X, U, Xnext, g=None)[source]

Data (z_k, y_k) = ((x_k, u_k), x_k’ - g(x_k, u_k)) for learning f + D.

Models of monotone systems

class PartitionedSimulatingMap(partition, lower, upper, d_lo, d_hi, signs)[source]

Interval-valued simulating map sigma on a fixed rectangular partition.

Variables:
  • partition – RectangularPartition of the input box.

  • lower – arrays of shape (*partition.shape, m), the bounds of sigma(q). Entries are -inf/+inf where no data point constrains the cell.

  • upper – arrays of shape (*partition.shape, m), the bounds of sigma(q). Entries are -inf/+inf where no data point constrains the cell.

  • d_lo – as in ddma.MinimalSimulatingMap.

  • d_hi – as in ddma.MinimalSimulatingMap.

  • signs – as in ddma.MinimalSimulatingMap.

classmethod from_data(Z, Y, partition, d_lo=0.0, d_hi=0.0, signs=None, backend='auto', compact=False)[source]

Compute sigma from data (Z, Y) on partition.

Data points outside the partitioned box are allowed: they still bound the cells they dominate (or are dominated by).

backend: “auto” (compiled kernel if installed, else NumPy), “cpp” or “numpy”. Both backends give identical results.

compact=True stores the bounds as float32 (half the memory), rounded outward (lower bounds down, upper bounds up), so the map stays a sound over-approximation.

property m

Output dimension.

property n

Input dimension.

bounds_at(idx)[source]

sigma(q) for cell indices idx (N, n).

bounds(z)[source]

sigma(phi(z)) at points z (M, n) inside the partitioned box.

f_bounds(z)[source]

Bounds on the unknown function f: [lower - d_lo, upper - d_hi].

contains(z, y, tol=1e-12)[source]

Whether each pair (z, y) satisfies y in sigma(phi(z)).

compact()[source]

Store the bounds as float32, rounded outward (sound). Returns self.

intersect_(other)[source]

In-place intersection (no copy of the bound arrays). Returns self.

intersect(other)[source]

Map of the union of both data sets (intersection of the two maps).

update(Z, Y)[source]

Refine the map with new data, without revisiting the old data.

widths()[source]

upper - lower per cell and output (inf where unbounded).

bounded_fraction()[source]

Fraction of cells whose interval is bounded in every output.

is_empty()[source]

Cells where lower > upper. Never happens for consistent data.

class MinimalSimulatingMap(Z, Y, d_lo=0.0, d_hi=0.0, signs=None)[source]

Exact (pointwise) minimal simulating map of a data set.

Parameters:
  • Z – (K, n) array of inputs z_k.

  • Y – (K, m) array of outputs y_k (or (K,) for m = 1).

  • d_lo – disturbance bounds, scalars or (m,) arrays.

  • d_hi – disturbance bounds, scalars or (m,) arrays.

  • signs – optional (m, n) or (n,) monotonicity pattern (see ddma._signs).

Evaluation costs O(|K| n) per query point. For large data sets use ddma.PartitionedSimulatingMap, which is computed once on a grid.

property n

Input dimension.

property m

Output dimension.

property theta

Width of the disturbance interval, d_hi - d_lo.

bounds(z, chunk=2000000)[source]

Lower and upper bounds of S_m at the query points z (M, n).

f_bounds(z)[source]

Bounds on the unknown monotone function f itself.

f(z) lies in [S_lo(z) - d_lo, S_hi(z) - d_hi] = [sup{y_k - d_hi : z_k <= z}, inf{y_k - d_lo : z <= z_k}].

estimate(z)[source]

Midpoint of the f-bounds (set-membership estimate); nan where unbounded.

merge(other)[source]

Map of the union of both data sets; equals the intersection of both maps.

is_consistent(tol=1e-12)[source]

Whether some monotone f + [d_lo, d_hi] can explain the data.

Equivalent to y_k in S_m(z_k) for every data point, i.e. y_k <= y_l + (d_hi - d_lo) whenever z_k <= z_l. A violation shows that the monotonicity assumption (or the sign pattern) or the disturbance bounds are wrong.

Models of systems with bounded derivatives

class BoundedDerivativeModel(partition, n_x, groups, Am, Ap, Bm, Bp, g, g_bounds, d_lo, d_hi, backend, compact, method='two_matrix', components=None)[source]

Data-driven model of f + g + W for f with bounded partial derivatives.

Variables:

Use – meth:from_data (and update() to add data in batches). The model is defined

on a rectangular partition of the joint (x, u) space and can be passed to ddma.SymbolicAbstraction in place of a simulating map (g_bounds is then not used: g is already part of the model).

features[i] (optional) lists the (x, u) coordinates that output i depends on. Each output is then learned on that sub-grid only, which can save orders of magnitude of memory (e.g. Lorenz: x+ depends on (x, y) only). Derivative bounds outside the listed coordinates are taken as zero: listing features asserts that f_i does not depend on the other coordinates.

method selects one of the five approaches of the thesis (module docstring). All of them are sound; “lin_*” are the tightest and the slowest (one small linear program per cell). “two_matrix” leaves cells unbounded where no data point lies on the right side; the other methods bound every cell as soon as there is data. For methods other than “two_matrix”, update() refits exactly (same result as fitting all data at once), and for “growth” / “lin_growth” update_local() offers the cheaper windowed update.

property m

Number of outputs (the state dimension).

property sigma_minus

Map of f- (only when all outputs share one set of inputs).

property sigma_plus

Map of f+ (only when all outputs share one set of inputs).

classmethod from_data(X, U, Xnext, partition, A_lo, A_hi, B_lo, B_hi, d_lo=0.0, d_hi=0.0, g=None, g_bounds=None, backend='auto', features=None, compact=False, method='two_matrix', local=None)[source]

Learn the model from transitions (x_k, u_k, x’_k).

partition partitions the joint (x, u) box. g (vectorized, (X, U) -> R^n) and g_bounds (interval bounds of g over boxes, see ddma.affine_bounds()) describe the known part; leave both None when g = 0. features: see the class docstring. compact=True stores the bounds as float32, rounded outward (“two_matrix”, “all_matrix”, “lin_mono”). method: see the class docstring. local (“growth” / “lin_growth” only): also intersect with the cones of the data points in each cell ("cell") or in the cell’s slabs ("slab", tighter and never looser than min over data of the cone’s max over the cell); see ddma._bd_components.GrowthComponent.

update(X, U, Xnext)[source]

Add a batch of transitions (in place; maps are intersected, TAC Prop. 3).

update_local(X, U, Xnext, window)[source]

Windowed update for “growth” / “lin_growth” (thesis Section 3.2, Prop. 13).

Each transition tightens the model only on the cells within window cells of its own cell (an int, or one int per coordinate of the output’s features). Meant for online use, one or a few points at a time. Sound; not as tight as update(), which spreads each point over the whole grid.

f_bounds_at(joint_idx)[source]

Bounds of f(x, u) + W per cell, without g (methods other than “two_matrix”).

successor_bounds(joint_idx, x_lo, x_hi, u_lo, u_hi)[source]

Box containing f(x, u) + g(x, u) + W for all (x, u) in the given cells.

bounds(x, u)[source]

Box containing f(x, u) + g(x, u) + W at given points (via their cells).

class GrowthMap(partition, g_lo, g_hi, d_lo, d_hi, local='slab', final='box', backend='auto')[source]

Interval model of f + D for one scalar output, on a rectangular partition.

Parameters:
  • partition – RectangularPartition of the input box Z.

  • g_lo – bounds on the partial derivatives of f (length n).

  • g_hi – bounds on the partial derivatives of f (length n).

  • d_lo – bounds on the measurement disturbance.

  • d_hi – bounds on the measurement disturbance.

  • local – "slab" (default, tightest), "cell" or None; see ddma.BoundedDerivativeModel.

  • final – "box" (default, approach 4) or "lp" (approach 5).

  • backend – "auto" (default: compiled kernel for batch fits if installed), "cpp" or "numpy"; same model either way.

Variables:
  • lower – arrays of shape partition.shape; bounds on f + d per cell (-inf / +inf where the data say nothing yet).

  • upper – arrays of shape partition.shape; bounds on f + d per cell (-inf / +inf where the data say nothing yet).

  • n_data – number of data points added.

classmethod from_data(Z, y, partition, g_lo, g_hi, d_lo, d_hi, **kwargs)[source]

Model from data Z (K, n), y (K,).

update(Z, y)[source]

Add data (exact; in place; returns self).

update_local(Z, y, window)[source]

Add data, updating only window cells around each point (in place).

copy()[source]

An independent copy of the model.

cell_index(Z)[source]

Cell index (K, n) of each point (points outside the box: nearest edge cell).

bounds(Z)[source]

Bounds on f(z) + d at the cells of the points Z: (lower (K,), upper (K,)).

f_bounds()[source]

Bounds on f itself per cell: (lower - d_lo, upper - d_hi).

widths()[source]

upper - lower per cell (inf where unbounded).

vertex_values(Z, y)

Exact bounds at all vertices from the data (Z, y) alone (eqs. 3.20-3.21).

estimate_derivative_bounds(Z, Y, n_lp_pairs=50000, n_w_pairs=1000000, rng=None, w_weight=1.0)[source]

Estimate derivative and disturbance bounds from data (TAC paper, Section IV).

Data (z_k, y_k) with y_k in f(z_k) + [-w, w]. Random pairs of samples are drawn; for each output i the linear program (32) on n_lp_pairs pairs gives the derivative bounds a_lo_i, a_hi_i, then (33) on n_w_pairs fresh pairs gives w_i.

w_weight multiplies the disturbance term of the LP cost (1 = equation (32) of the paper). Larger values trade slightly wider derivative bounds for a smaller disturbance bound; the original MATLAB experiments used 50. Any value keeps the guarantee of Proposition 9, which only concerns the second step (33).

Returns (a_lo, a_hi, w) with shapes (m, n), (m, n), (m,). The disturbance interval is [-w, w]. See scenario_confidence() for the probabilistic guarantee.

scenario_confidence(n_w_pairs, beta)[source]

Proposition 9: with probability >= 1 - beta, a fresh pair of samples satisfies the estimated bounds with probability >= beta ** (1 / n_w_pairs).

Abstraction

class SymbolicAbstraction(state_partition, input_partition, sim_map, g_bounds=None, features=None, chunk=1000000, assumption=None, lazy=False, backend='auto')[source]

Symbolic abstraction on state cells x input cells.

Parameters:
  • state_partition – RectangularPartition of X and U.

  • input_partition – RectangularPartition of X and U.

  • sim_map – PartitionedSimulatingMap of f + D. Its inputs are the coordinates features of the stacked vector (x, u) (default: all of them), and its partition must be the projection of state_partition x input_partition on these coordinates. Leaving out coordinates states that f does not depend on them.

  • g_bounds – optional function (x_lo, x_hi, u_lo, u_hi) -> (g_lo, g_hi) giving an interval containing g over a cell pair (rows are cell pairs). Use affine_bounds() for affine g. None means g = 0. sim_map may instead be a model with a successor_bounds method (e.g. ddma.BoundedDerivativeModel), which already includes g.

  • assumption – optional (lo, hi) state box describing an environment assumption, for assume-guarantee contracts (“if the leader’s speed stays in [a, b] then …”). Successor sets are restricted to the state cells inside this box (on the constrained coordinates), and clamped into it if they would miss it entirely, which is conservative: trajectories that break the assumption are not the controller’s responsibility. Use -inf / inf for unconstrained coordinates; finite bounds should lie on cell edges.

  • lazy – if True, transitions are not precomputed: pair_boxes() evaluates them on demand. Memory is then O(|Q|) instead of O(|Q| |P|). Use with ddma.safety(), which evaluates only the pairs it needs; the other synthesis functions need the eager abstraction.

  • backend – “auto” (compiled kernel if installed, else NumPy), “cpp” or “numpy”. The compiled kernel computes the transitions on all cores (see ddma.set_num_threads()); both backends give identical abstractions.

pair_boxes(Q, P)[source]

Transitions of the state-input pairs (Q[k], P[k]) (flat cell indices).

Returns (enabled, first, last): enabled (k,) and the successor box of cells first..last (k, n) (zeros where not enabled). This is what the eager abstraction stores for every pair; a lazy abstraction calls it on demand.

refresh(states=None)[source]

Recompute the transitions of some state cells after the model was refined.

states: flat indices or boolean mask of the state cells to recompute. By default, the cells changed by the model’s last update_local calls (its changed_boxes, which are then cleared): a state cell is recomputed when its coordinates lie in a changed box (for all inputs). A lazy abstraction stores no transitions, so only the mask is returned. Returns the boolean mask of the recomputed states. After a refinement the successor boxes only shrink, so the previous winning set stays controlled invariant: pass it to ddma.safety() as known_winning for an exact, cheaper update.

property n_states

Number of state cells.

property n_inputs

Number of input cells.

successors(q, p)[source]

Flat indices of the successor cells of (q, p) (empty if p is not enabled).

state_mask(predicate)[source]

Boolean mask over state cells from a predicate on cell corners (lo, hi).

cells_inside(box_lo, box_hi)[source]

Mask of state cells contained in the box [box_lo, box_hi].

cells_meeting(box_lo, box_hi)[source]

Mask of state cells whose closure intersects the box [box_lo, box_hi].

Conservative (closed cells), so it is the right choice for obstacles.

affine_bounds(A, B=None, c=None)[source]

Exact interval image of g(x, u) = A x + B u + c over boxes.

Returns a function (x_lo, x_hi, u_lo, u_hi) -> (g_lo, g_hi) usable as g_bounds (an AffineBounds, which the compiled abstraction kernel evaluates per cell pair without building the bounds of every pair in NumPy).

class AffineBounds(A, B=None, c=None)[source]

Interval image of g(x, u) = A x + B u + c over boxes (see affine_bounds()).

Calling it with (x_lo, x_hi, u_lo, u_hi) returns (g_lo, g_hi). parts() returns the state and input parts separately, so that the compiled abstraction kernel can combine them per cell pair with the same arithmetic.

parts(x_lo, x_hi, u_lo, u_hi)[source]

(x_mid, x_rad, u_mid, u_rad): mid = x_mid + u_mid, rad = x_rad + u_rad (u_mid = u_rad = None when B is None: mid = x_mid, rad = x_rad).

Synthesis and closed loop

safety(abs_, safe, max_iter=100000, backend='auto', known_winning=None, check=True)[source]

Maximal controlled invariant subset of safe (flat boolean mask over state cells).

Greatest fixed point: remove cells with no input whose successors all stay in the current set, until nothing changes. Each state keeps a pointer to its first input not yet ruled out; the set only shrinks, so an input that fails once fails for ever and the pointer only moves forward. Over the whole fixed point every (state, input) pair is examined at most once, plus one check of the current pointer per state and round.

backend: “auto” (compiled kernel if installed, else NumPy), “cpp” or “numpy”. Both give the same result as the textbook iteration.

With a lazy abstraction (SymbolicAbstraction(..., lazy=True)) the same scan runs in NumPy and evaluates a transition only when the scan reaches it: states outside safe are never expanded and each state stops at its first good input. Memory is O(|Q|) instead of O(|Q| |P|); the controller computes its allowed inputs on demand. Same result.

known_winning: incremental update. A set of cells known to be controlled invariant inside safe, typically the previous winning set after the model was refined (refined successor boxes can only shrink, so the old winning set stays controlled invariant and the new maximal set contains it). Every round of the fixed point contains the maximal set, so these cells are never removed: they are kept and not tested, and only the other cells are examined. The result is the same maximal set. With check=True (default) the assumption is verified first, in one cheap round, and a ValueError is raised if it does not hold. The saving is modest with the pointer scan (known cells cost one check per round anyway; most of the work is removing losing cells), about 10 % on the pendulum example; the main use is the guarantee that the winning set only grows during online refinement.

reach_avoid(abs_, target, avoid=None, max_iter=100000, backend='auto')[source]

States that can be driven to target while avoiding avoid (least fixed point).

value[q] is the number of steps needed (inf if unreachable). At a state with value k > 0 the allowed inputs are those whose successors all have value < k. Only undecided states are examined in each round; the compiled kernel also skips a state when no cell that entered the reach set in the last round lies in the hull of its successor boxes. backend as in safety().

class Controller(abstraction, allowed, domain, value=None)[source]

Symbolic controller: allowed[q, p] says input cell p may be used in state cell q.

domain is the set of state cells where the controller is defined (the winning set); value is the number of steps to the target for reach-avoid controllers.

allowed_row(q)[source]

allowed[q, :]. For a lazy abstraction (allowed is None) it is computed on demand from the transitions of q and the domain.

winning_fraction()[source]

Fraction of the state cells in the domain (winning set).

domain_grid()[source]

Domain as a boolean array over the state grid shape.

input_cells(x)[source]

Allowed input-cell indices at the concrete state x (empty outside the domain).

__call__(x, pick='center', rng=None)[source]

A concrete input for state x: a point of an allowed input cell.

pick = “center” (centre of the first allowed cell), “random” (uniform in a random allowed cell), or “min_norm” (the allowed cell centre with smallest norm). Any point of an allowed cell is admissible. Returns None outside the domain.

filter(x, u_desired)[source]

Safety filter: the admissible input closest to u_desired (Euclidean).

Returns u_desired unchanged when it lies in an allowed input cell, the nearest point of the allowed cells otherwise, and None outside the domain.

simulate(step, controller, x0, n_steps, rng=None, pick='center', stop_in=None, nominal=None)[source]

Closed-loop simulation of the concrete system step(x, u, rng) -> x+.

With nominal (a function x -> desired input) the controller acts as a safety filter around it (Controller.filter()); otherwise inputs are chosen by pick. Stops early if the state leaves the controller domain (returns what was simulated) or, when stop_in (a state-cell mask) is given, once the state enters it. Returns (states (T+1, n), inputs (T, nu)).

Safe envelopes without a grid (ddma.invariance)

Safe operating envelopes (controlled invariant sets) straight from data, without a grid.

Two methods, both deterministic and both working on raw transitions (x_k, u_k, x_k+):

ivar *:

func:monotone_envelope for monotone systems with an additive bounded disturbance,

x+ = f(x, u) + w, f monotone, w in [w_lo, w_hi],

and a lower-closed safety specification (e.g. “every temperature at most 26 C”). Each valid combination of data points gives a corner T whose lower set {x <= T} is robustly invariant with a constant input; the envelope is the union of these lower sets, stored as its maximal corners (a skyline) with the largest allowed input of each. Method of A. Makdesi, M. Zamani, “Data-driven synthesis of controlled invariant sets for monotone systems”, IFAC World Congress 2026.

ivar *:

func:embedding_envelope for general nonlinear systems with bounded Jacobians,

x+ = f(x, u) + w, df_i/dx_j in [a_ij, b_ij], df_i/du_k in [c_ik, d_ik].

Every pair of data points spans a box of states and a box of inputs. The growth cones of the two points bound where the whole box can go (an LP with two cone constraints, solved here exactly in closed form); if that bound fits back inside the box, the box is robustly invariant for every input in its input box. Method of A. Makdesi, M. Zamani, S. Jafarpour, “Data-driven controlled invariance via monotone embeddings”, IFAC World Congress 2026 (the box test is the paper’s monotone-embedding condition z’ <= z on the pair data).

Coordinates: monotone systems are often monotone only after flipping some coordinates (e.g. distance -> -distance, cooling -> -cooling). Pass state_signs / input_signs (+1 or -1 per coordinate) and work in the original coordinates everywhere else.

Disturbances are in state units (the change they cause in x+ in one step). In the data, x_k+ = f(x_k, u_k) + w_k with w_k unknown; the guarantee holds for every w in the bounds.

Example:

env = monotone_envelope(X, Xn, U, w_lo=[0, 0, 0], w_hi=[0.15] * 3,
                        input_signs=[-1], x_hi=[26, 26, 26])
env.contains(x)            # in the certified envelope?
u = env.safe_input(x, u_desired)   # closest certified input (None outside)
monotone_envelope(X, Xn, U=None, w_lo=None, w_hi=None, x_lo=None, x_hi=None, state_signs=None, input_signs=None, u_lo=None, u_hi=None, max_states=2000000)[source]

Certified safe envelope of a monotone system from transitions (no model, no grid).

Parameters:
  • X – (N, n) states and measured successors, x_k+ = f(x_k, u_k) + w_k.

  • Xn – (N, n) states and measured successors, x_k+ = f(x_k, u_k) + w_k.

  • U – (N, m) inputs, or None for an autonomous system.

  • w_lo – bounds on the additive disturbance, in state units (default 0).

  • w_hi – bounds on the additive disturbance, in state units (default 0).

  • x_lo – safety specification as a box (use +-inf for “no bound”). It must be lower-closed in the flipped coordinates: only x_hi where state_signs is +1, only x_lo where it is -1.

  • x_hi – safety specification as a box (use +-inf for “no bound”). It must be lower-closed in the flipped coordinates: only x_hi where state_signs is +1, only x_lo where it is -1.

  • state_signs – +1 / -1 per coordinate so that f is increasing in (state_signs * x, input_signs * u).

  • input_signs – +1 / -1 per coordinate so that f is increasing in (state_signs * x, input_signs * u).

  • u_lo – input range in which f is known to be monotone; certified inputs stay in it (default: the range of the data).

  • u_hi – input range in which f is known to be monotone; certified inputs stay in it (default: the range of the data).

Returns:

MonotoneEnvelope. Every state in it can be kept in it forever, for every disturbance sequence, with the inputs it certifies.

embedding_envelope(X, Xn, U=None, jx_lo=None, jx_hi=None, ju_lo=None, ju_hi=None, w_lo=None, w_hi=None, x_lo=None, x_hi=None, pairs=None, chunk=20000)[source]

Certified safe envelope of a nonlinear system with bounded Jacobians, from data.

Parameters:
  • X – (N, n) states and measured successors, x_k+ = f(x_k, u_k) + w_k.

  • Xn – (N, n) states and measured successors, x_k+ = f(x_k, u_k) + w_k.

  • U – (N, m) inputs, or None.

  • jx_lo – (n, n) bounds on df_i/dx_j (scalars broadcast).

  • jx_hi – (n, n) bounds on df_i/dx_j (scalars broadcast).

  • ju_lo – (n, m) bounds on df_i/du_k (needed when U is given).

  • ju_hi – (n, m) bounds on df_i/du_k (needed when U is given).

  • w_lo – additive disturbance bounds, in state units (default 0).

  • w_hi – additive disturbance bounds, in state units (default 0).

  • x_lo – safety box (default unbounded); every certified box lies inside it.

  • x_hi – safety box (default unbounded); every certified box lies inside it.

  • pairs – (P, 2) index pairs to examine (default: all pairs i < j).

Returns:

BoxEnvelope: boxes [min(x_i, x_j), max(x_i, x_j)] whose image under f + w, for every input in [min(u_i, u_j), max(u_i, u_j)], provably stays inside them.

class MonotoneEnvelope(corners, pairs_T, pairs_U, state_signs, input_signs, u_lo, u_hi, n_valid=0)[source]

Union of lower sets {x : s * x <= s * T} (s = state signs), with allowed inputs.

Variables:
  • corners – (L, n) maximal corners T, in original coordinates (the skyline).

  • pairs_T – (P, n), (P, m) every non-dominated (corner, input limit) pair: for x below T (in the order of state_signs), every input u with input_signs * u <= input_signs * U and inside [u_lo, u_hi] is certified.

  • pairs_U – (P, n), (P, m) every non-dominated (corner, input limit) pair: for x below T (in the order of state_signs), every input u with input_signs * u <= input_signs * U and inside [u_lo, u_hi] is certified.

  • state_signs – the coordinate flips that make f monotone increasing.

  • input_signs – the coordinate flips that make f monotone increasing.

  • u_lo – the input range in which monotonicity was assumed (default: the data’s).

  • u_hi – the input range in which monotonicity was assumed (default: the data’s).

  • n_valid – number of valid corner candidates found by the search (before the skyline).

property n_corners

Number of maximal corners.

contains(x)[source]

Boolean per state (rows of x): inside the certified envelope.

input_limits(x)[source]

Maximal input limits U valid at one state x (rows; empty if x is outside).

safe_input(x, u_desired=None)[source]

A certified input at x, as close as possible to u_desired (None outside).

Without u_desired the input closest to the middle of [u_lo, u_hi] is returned.

class BoxEnvelope(lo, hi, ulo, uhi, pairs, n_pairs=0)[source]

Union of robustly invariant boxes, each with a box of certified inputs.

Variables:
  • lo – (K, n) the state boxes.

  • hi – (K, n) the state boxes.

  • ulo – (K, m) for every state in box k, every input in [ulo_k, uhi_k] keeps the successor in box k, for every disturbance.

  • uhi – (K, m) for every state in box k, every input in [ulo_k, uhi_k] keeps the successor in box k, for every disturbance.

  • pairs – (K, 2) indices of the data points spanning each box.

  • n_pairs – number of pairs examined.

property n_boxes

Number of certified boxes.

boxes_containing(x)[source]

Indices of the boxes that contain the state x.

contains(x)[source]

Boolean per state (rows of x): inside some certified box.

safe_input(x, u_desired=None)[source]

Certified input at x closest to u_desired (None if x is in no box).

bounding_box()[source]

(lo, hi) of the smallest box containing every certified box.

maximal_points(P, return_index=False)[source]

Rows of P that no other row dominates (componentwise >=; duplicates kept once).

Sort-filter skyline: rows sorted by decreasing sum can only be dominated by earlier rows, so each block is compared with the current skyline and with its own earlier rows.

max_min_cones(p, q, alpha, beta)[source]

max over s in [0, 1]^d of min(p + alpha . s, q + beta . (1 - s)), exactly.

Vectorized over leading axes (p, q: (…), alpha, beta: (…, d), all alpha, beta >= 0). This is the LP of the embedding method: two cones with apexes at opposite corners of a box, each increasing towards the other corner. By LP duality it equals min over lam in [0, 1] of lam p + (1 - lam)(q + sum beta) + sum max(0, lam(alpha+beta) - beta), a convex piecewise-linear function whose minimum sits at 0, 1 or a breakpoint beta_j / (alpha_j + beta_j); the slope test below finds it after one sort.

Assumption monitor

Assumption monitor: are the data consistent with the model’s assumptions?

Every ddma model rests on assumptions that are given, not learned: a monotonicity sign pattern, bounds on partial derivatives, bounds on the disturbance. If one of them is wrong, the model (and every safe set built on it) can be wrong too. This module checks data against these assumptions: the learning data before learning (check_data()), and new transitions while the system runs (AssumptionMonitor).

One form for all models. Each assumption is written as an interval of slopes per output i and input j, plus a disturbance width per output:

sign +1 -> df_i/dz_j in [0, +inf) sign -1 -> df_i/dz_j in (-inf, 0] sign 0 -> df_i/dz_j in [0, 0] (f_i does not depend on z_j) bounded slopes -> df_i/dz_j in [g_lo_ij, g_hi_ij] disturbance -> theta_i = d_hi_i - d_lo_i

Two data points a, b (with y = f(z) + d, d in [d_lo, d_hi]) are consistent with these assumptions if and only if, for every output i,

y_a,i - y_b,i <= theta_i + sum_j s_ij(z_a,j - z_b,j), s_ij(t) = g_hi_ij t (t > 0), g_lo_ij t (t < 0), 0 (t = 0) (*)

(the growth cone of point b contains point a; for the sign patterns this is exactly the consistency condition of the minimal simulating map). A pair that violates (*) is a proof that at least one assumption is wrong (or that the data are corrupted): there are no false alarms.

Which assumption? For a violating pair, the gap of (*) can be closed by changing a single assumption, all others fixed:

theta_i must grow by the gap; g_hi_ij (dz_j > 0) must reach r_j / dz_j, g_lo_ij (dz_j < 0) must reach r_j / dz_j, with r_j = y_a,i - y_b,i - theta_i - sum_{k != j} s_ik(dz_k); a bound whose dz_j has the other sign (or is 0) cannot close the gap.

Widening one bound never breaks a pair that was consistent before, so the extreme of these values over all violating pairs is exactly the smallest change of that one assumption that makes all data consistent (AssumptionMonitor.needed()).

Three levels (each alarm is a proof; Violation records the level):

  1. "cells": the new point against the model’s bounds at its cell (cheap, catches large violations);

  2. "sample": against a fresh random sample of stored points (only with full="later");

  3. "full": against every earlier point, in the same step (full="step", the default) or later, all at once, with AssumptionMonitor.flush() (full="later": collect during a run, check back at base).

The pair checks run in the C++ core (OpenMP, bit-identical for any number of threads), with exact pruning by a grid of cells (prune=True): a cell is skipped only when no pair with it can violate (*), so pruning changes the work, never the result.

Quarantine. A point that fails a check is kept aside: it counts for the diagnosis, but later points are not blamed for disagreeing with it. When a pair conflicts, the earlier point is trusted (unless it is itself quarantined).

Responses (on_violation): "alarm" records; "fallback" latches AssumptionMonitor.fallback_active until AssumptionMonitor.reset(); "widen" applies the smallest change of the chosen assumption; "widen_then_fallback" widens while the needed change stays within a limit, and falls back beyond it. After a widening the model must be refit from AssumptionMonitor.data().

Example:

print(ddma.check_data(Z, Y, d_lo=d_lo, d_hi=d_hi, signs=signs).report())
sigma = PartitionedSimulatingMap.from_data(Z, Y, part, d_lo, d_hi)
mon = AssumptionMonitor.for_model(sigma, Z, Y, on_violation="widen_then_fallback")
...
mon.check(z_new, y_new)          # every new transition
if mon.fallback_active:
    u = backup(x)
print(mon.report())
check_data(Z, Y, slope_lo=None, slope_hi=None, d_lo=0.0, d_hi=0.0, *, signs=None, tol=1e-09, prune=True, backend='auto', input_names=None, output_names=None)[source]

Check every pair of data points against the assumptions, before learning.

Needs only the data and the assumptions (no model). Give the slope intervals slope_lo, slope_hi (m, n), or a sign pattern signs (as for the monotone models). Y: (K, m), or (K,) for one output. Exact: every conflicting pair is found. prune skips cells of a grid in which no pair can conflict (same result, less work). Runs in the C++ core on all cores (ddma.set_num_threads); backend="numpy" checks all pairs in NumPy (slow, same result).

class DataCheck(ok, n_points, pairs_evaluated, violating, worst, worst_pair, conflicts, needed, slope_lo, slope_hi, theta, tol=1e-09, input_names=None, output_names=None)[source]

Result of check_data().

Variables:
  • ok – no pair of data points contradicts the assumptions.

  • violating – (m,) number of conflicting pairs per output.

  • worst – (m,) largest gap per output (-inf if none); worst_pair : (m, 2) the two points of that pair (later, earlier), -1 if none.

  • conflicts – (K,) number of points each point conflicts with (any output); points with many conflicts are the first suspects for corrupted data.

  • needed – smallest single change of each assumption that makes all data consistent (same as AssumptionMonitor.needed(); nan = this bound alone cannot).

  • pairs_evaluated – pairs actually computed (fewer than K(K-1)/2 with pruning).

suspects(k=None)[source]

Indices of points with conflicts, most conflicts first (k: the first k).

report()[source]

Plain-words summary: conflicting pairs, the single changes that would explain them, and the points with most conflicts.

class AssumptionMonitor(slope_lo, slope_hi, d_lo=0.0, d_hi=0.0, *, m=None, on_violation='alarm', widen='disturbance', widen_limit=2.0, slope_limit=None, margin=0.0, full='step', sample=2000, prune=True, model_bounds=None, inside=None, callback=None, tol=1e-09, g=None, features=None, input_names=None, output_names=None, seed=0, backend='auto')[source]

Check new transitions against the assumptions of a ddma model.

Parameters:
  • slope_lo – (m, n) slope intervals (-inf / +inf allowed), see the module docstring. (n,) arrays apply to every output; give m then.

  • slope_hi – (m, n) slope intervals (-inf / +inf allowed), see the module docstring. (n,) arrays apply to every output; give m then.

  • d_lo – disturbance bounds, scalars or (m,).

  • d_hi – disturbance bounds, scalars or (m,).

  • on_violation – "alarm" (default), "widen", "fallback" or "widen_then_fallback".

  • widen – what widening changes: "disturbance" (default) or ("slope_lo", i, j) / ("slope_hi", i, j). A slope bound can be widened only if both of its ends are finite (a sign has no scale) and only with slope_limit.

  • widen_limit – "widen_then_fallback": largest disturbance width allowed, as a multiple of the original width (scalar or (m,)); beyond it: fallback.

  • slope_limit – absolute limit of the widened slope bound (required for a slope target).

  • margin – relative extra widening (0.1 = 10 % more than the smallest change).

  • full – "step" (default): each new point is checked against all earlier points in the same step. "later": during a run only levels 1 and 2; flush() then checks all pending points at once.

  • sample – level 2, points per step (full="later" only; 0 = off).

  • prune – skip grid cells where no pair can conflict (same result, less work).

  • model_bounds – optional function Z (N, n) -> (lo, hi) (N, m) with bounds of y at Z from the model, and inside (optional) Z -> bool mask of points where it applies. Set by for_model(). Level 1 checks them.

  • callback – called with the list of Violation found at once.

  • tol – violations smaller than tol are ignored (rounding).

  • g – how observe() turns transitions (x, u, x’) into data: z = (x, u)[features], y = x’ - g(x, u).

  • features – how observe() turns transitions (x, u, x’) into data: z = (x, u)[features], y = x’ - g(x, u).

  • input_names – used in report().

  • output_names – used in report().

  • seed – seed of the level-2 samples (same samples in Python and MATLAB).

  • backend – "auto" (C++ if installed), "cpp" or "numpy" (same results).

classmethod monotone(signs, d_lo=0.0, d_hi=0.0, *, m, n, **kwargs)[source]

Monitor of a monotone model with sign pattern signs ((m, n), (n,) or None).

classmethod for_model(model, Z=None, Y=None, **kwargs)[source]

Monitor of a ddma model, seeded with the data (Z, Y) it was learned from.

model: ddma.MinimalSimulatingMap (its data are used when Z is None), ddma.PartitionedSimulatingMap, ddma.GrowthMap or ddma.BoundedDerivativeModel (data Z = [X U], Y = X’ - g(X, U), as in ddma.transitions_to_data()). The model’s cell bounds are level 1 (inside its partition). For BoundedDerivativeModel the slope intervals are those the method relies on: [min(g_lo, 0), max(g_hi, 0)] for “two_matrix”, “all_matrix” and “lin_mono”, [g_lo, g_hi] for the growth methods; zero outside features. Monotone models can only widen the disturbance.

set_model(model_bounds, inside=None)[source]

Use new model bounds (e.g. after a refit); clears needs_refit.

property m

Number of outputs.

property n

Number of inputs.

property theta

Disturbance width per output, d_hi - d_lo (the only part data can test).

property ok

No violation since the start (or the last reset()).

property n_points

Number of stored data points (clean and quarantined).

property pending

Checked points whose full check (level 3) has not run yet (full="later").

status()[source]

Counts: stored points, pending full checks, quarantined points, grid cells.

data(quarantined=False)[source]

Stored data (Z, Y), e.g. for a refit: clean points only, or all with quarantined=True.

quarantine()[source]

The quarantined points: ids (seed: negative; checked: transition index), Z, Y and the violations that put them there.

add(Z, Y)[source]

Store data without checking them (e.g. the data the model was learned from; check those with check_data()). Pending full checks are run first. Room is reserved for at least half as many new points, so a run does not trigger a copy.

rebuild_index()[source]

Rebuild the cell grid used for pruning from all stored points (done by add(), and when the data have doubled since the last build).

observe(X, U, Xnext)[source]

check() for transitions (x, u, x’): z = (x, u)[features], y = x’ - g(x, u).

check(Z, Y)[source]

Check new transitions one by one, store them, and respond. Returns the violations found during this call (with full="later": levels 1 and 2 only; flush() runs level 3).

flush()[source]

Run the full check (level 3) of all pending points now, record and respond. Returns the violations found.

needed()[source]

Smallest single changes that make all stored data consistent.

Returns a dict with width (m,): the disturbance width d_hi - d_lo needed, slope_lo, slope_hi (m, n): the slope bound needed, each with all other assumptions unchanged. Entries equal to the current value need no change; nan means that this bound alone cannot explain the violations. Exact once no full check is pending (pending = 0, see flush()); before that, the values cover the pairs checked so far. Violations found only by level 1 (the model’s bounds) are not included; widening also covers them.

widen(target='disturbance', at=None)[source]

Apply the smallest change of one assumption (times 1 + margin) that makes all stored data consistent; pending full checks are run first. Quarantined points then rejoin the data. Returns whether anything changed.

After widening, the model must be refit from data() with the new assumptions (needs_refit); its guarantees then hold for assumptions fitted to the data seen so far, not given in advance. A slope bound is never widened beyond slope_limit.

consistent()[source]

Whether all stored data (quarantined too) are consistent with the current assumptions (all pairs, exact).

reset()[source]

Clear the violation record, the fallback flag and the needed changes (assumptions and quarantine stay as they are).

summary()[source]

Counts per output (violations, worst gap, per level) and the monitor’s state.

report()[source]

Plain-words summary of the checks, the violations and what would explain them.

class Violation(index, output, level, gap, witness=None, found_at=None)[source]

One transition that contradicts the assumptions.

Variables:
  • index – position of the transition among all checked ones (0-based).

  • output – output i whose assumption is contradicted.

  • level – which check found it: "cells" (the model’s bounds at its cell), "sample" (a random sample of stored points) or "full" (all earlier points).

  • gap – by how much (in output units) the assumptions are exceeded.

  • witness – the stored point it conflicts with (seed points: -1, -2, … in the order added; checked points: their index), None for "cells".

  • found_at – index of the last checked transition when it was found (found_at - index = delay; with full="later" the delay is that of the flush()).

slopes_from_signs(signs, m, n)[source]

Slope intervals (m, n) of a sign pattern: +1 -> [0, inf), -1 -> (-inf, 0], 0 -> [0, 0].

Reinforcement learning (ddma.rl)

Needs gymnasium (pip install "ddma[rl]").

Certified safety filters for reinforcement learning (Gymnasium).

SafetyFilterWrapper puts a ddma controller (from ddma.safety()) around any Gymnasium environment: every action of the agent goes through ddma.Controller.filter(), which returns it unchanged when it is safe and the nearest safe action otherwise. As long as the state starts in the controller’s domain, the system stays in the safe set for ever, whatever the agent does, during training as well as deployment.

CruiseControlEnv is a small benchmark: the adaptive cruise control problem of the TAC paper as an RL task (drive close to 22 m/s behind a leader whose speed changes). An agent trained without the filter crashes or drops out of the speed range while it learns; with the filter it never leaves the safe set.

Needs gymnasium (pip install ddma[rl]).

class SafetyFilterWrapper(env, controller, state_fn=None, penalty=0.0, outside='pass', reset_in_domain=True)[source]

Certified safety filter around a Gymnasium environment.

Parameters:
  • env – the environment; its actions are the inputs u of the abstraction.

  • controller – ddma.Controller from ddma.safety() (maximal controlled invariant set of the safe set).

  • state_fn – function env -> state x of the abstraction (default: env.unwrapped.state); the filter needs the true state, not an observation.

  • penalty – reward penalty per unit of correction ||u_safe - u|| (default 0), to teach the agent to propose safe actions itself.

  • outside – what to do when the state is outside the controller domain (only possible if the episode starts there): "pass" the action unchanged (default) or "raise".

  • reset_in_domain – redraw the initial state (up to 1000 resets) until it lies in the controller domain (default True), so that the guarantee holds from the start.

info gains safe_action, filtered (bool), correction (norm) and outside_domain; n_steps, n_filtered count over the wrapper’s life.

in_domain()[source]

Whether the current state lies in the controller domain.

reset(**kwargs)[source]

Reset the environment; with reset_in_domain, redraw until the state lies in the controller domain.

safe_action(action)[source]

(safe action, inside the domain?) for the current state.

step(action)[source]

Filter the action (closest certified action), then step the environment.

class CruiseControlEnv(horizon=400, init_lo=(20.0, 12.0), init_hi=(40.0, 18.0))[source]

Adaptive cruise control as an RL task (TAC paper, Section V-B).

State x = (h, v): gap to the leader [m], own speed [m/s]; action u in [-3, 3] m/s^2.

h+ = h - T v + T v_l, v+ = v + T (u - (f0 + f1 v + f2 v^2) / M) + w, |w| <= 0.05,

with T = 0.5 s and a leader speed v_l in [13, 17] m/s that switches between fast and slow phases. Reward per step: 1 - ((v - 22) / 10)^2 (drive close to 22 m/s, faster than the leader can go, and keep driving). The episode ends with reward -50 when the state leaves the safe set h in [10, 50], v in [2, 28] (a crash or a lost leader), otherwise after horizon steps. Observation (h, v, h - h_prev): the leader’s speed is not observed. info["violation"] is True on a violating step.

SAFE_LO = array([10.,  2.])
SAFE_HI = array([50., 28.])
classmethod speed_update(v, u)[source]

The follower’s speed update without disturbance (the dynamics the agent and ddma do not know).

reset(*, seed=None, options=None)[source]

Random initial state in [init_lo, init_hi] and a random leader phase.

step(action)[source]

One step of 0.5 s; terminates with reward -50 when the state leaves the safe set.

Threads and backends

set_num_threads(n=None)[source]

Use n threads in the compiled kernels (None or 0: OpenMP’s default).

Has no effect when the compiled kernel is not installed or was built without OpenMP (then everything runs on one thread, with the same results).

get_num_threads()[source]

Number of threads the compiled kernels will use (1 without OpenMP).

openmp_available()[source]

Whether the compiled kernel was built with OpenMP (threads).

compiled_backend_available()[source]

Whether the compiled C++ kernel (ddma._core) is installed.

Plotting (ddma.plotting)

Needs matplotlib.

Figures in the style of the papers (requires matplotlib; 3-D sets use scikit-image if installed, voxels otherwise).

ivar *:

func:plot_staircase_bounds - transparent piecewise-constant upper / lower bounds of a simulating map over a 2-D input space, optionally with the true function (TAC Fig. 8).

ivar *:

func:plot_set_3d - a set of cells of a 3-D partition (controllable set, invariant set) as a shaded surface (TAC Figs. 11, 12; ADHS Fig. 6).

ivar *:

func:plot_set_2d - the same for 2-D partitions (L4DC Fig. 5).

plot_staircase_bounds(sigma, output=0, ax=None, true_fn=None, trim=1, clip=None, alpha=0.3, cmap='viridis', bound_color='0.25', bound_cmap='plasma', region=None, cell_edges='auto')[source]

Transparent staircase upper/lower bounds of a 2-D-input simulating map.

Variables:

sigma – PartitionedSimulatingMap with two inputs. trim outer cells are dropped on

every side (their bounds are typically infinite). true_fn(Z) -> values draws the true function as a solid surface. clip=(lo, hi) clips infinite values for display. The bounds are transparent, coloured by height with bound_cmap (or plain bound_color if bound_cmap=None). region=(i0, i1, j0, j1) zooms on the cells i0 <= i < i1, j0 <= j < j1 (after trimming), where the steps are visible. cell_edges: draw the cell outlines on the bounds (True / False); “auto” draws them only up to 30 cells per axis, since on dense grids they cover the true function.

plot_set_3d(partition, mask, ax=None, color='#2a9d8f', alpha=0.95, step=1, axis_labels=None)[source]

A set of cells of a 3-D partition as a shaded surface.

mask is a boolean array over the cells (flat or of shape partition.shape). Uses the marching-cubes surface of the cell indicator (scikit-image) mapped to the cell edges; if scikit-image is missing, falls back to voxels.

plot_set_2d(partition, mask, ax=None, color='#d62828', points=None, alpha=0.85)[source]

A set of cells of a 2-D partition, optionally with data points.