MATLAB¶
The +ddma package in matlab/. Functions work on structs (S = ddma.fit(...),
A = ddma.abstraction(...)). Below each signature is the function’s help text, as
help ddma.<name> shows it in MATLAB. Run build_mex once to use the compiled
kernels; without it the .m code gives the same results.
Each function’s Python counterpart is listed in Python ↔ MATLAB.
Partitions¶
Grids are cell arrays of edge vectors, one per coordinate. Cell subscripts are 0-based (as in Python); linear indices are 1-based, column-major.
ddma.uniform_partition¶
Edges of a uniform rectangular partition of [lo, hi].
function edges = uniform_partition(lo, hi, ncells)
edges = ddma.uniform_partition(lo, hi, ncells) returns a cell array with one
increasing edge vector per coordinate (ncells(j) cells along coordinate j).
ddma.margin_partition¶
Uniform cells on [inner_lo, inner_hi] plus one margin cell per side.
function edges = margin_partition(lo, hi, inner_lo, inner_hi, ninner)
Edges per coordinate: [lo, linspace(inner_lo, inner_hi, ninner+1), hi]. This is the
partition used in the experiments of the TAC and ADHS papers.
ddma.data_partition¶
function edges = data_partition(Z, lo, hi)
Data-induced partition of [lo, hi]: one breakpoint per distinct data
coordinate inside the box. On it the fixed-partition map of ddma.fit coincides with
the minimal simulating map (almost everywhere). Up to (K + 1)^n cells: only for small
data sets. Same as the Python RectangularPartition.from_data.
(Other partitions: ddma.uniform_partition, ddma.margin_partition; the product of two
partitions is the concatenation of their edge cell arrays, [E1(:); E2(:)].)
ddma.grid_shape¶
Number of cells along each coordinate (row vector).
function shape = grid_shape(edges)
ddma.cell_bounds¶
Lower and upper corners of cells with 0-based subscripts sub (K x n).
function [lo, hi] = cell_bounds(edges, sub)
ddma.cells_inside¶
Logical column vector of the cells contained in the box [lo, hi].
function mask = cells_inside(edges, lo, hi)
ddma.cells_meeting¶
Logical column vector of the cells whose closure meets the box [lo, hi].
function mask = cells_meeting(edges, lo, hi)
Conservative (closed cells): the right choice for obstacles.
Same as the Python SymbolicAbstraction.cells_meeting.
ddma.locate¶
Cell subscripts (0-based, K x n) of the points Z (K x n).
function q = locate(edges, Z)
Cells are [e(c), e(c+1)); the last cell along each axis is closed. Points must lie in
the partitioned box.
ddma.searchsorted¶
Number of edges e < z (side ‘left’) or e <= z (side ‘right’).
function idx = searchsorted(e, z, side)
Same result as numpy.searchsorted(e, z, side). e must be increasing.
Works in MATLAB and Octave.
ddma.all_subs¶
0-based subscripts of all cells, in column-major order (prod(shape) x n).
function sub = all_subs(shape)
ddma.all_subs_of¶
0-based subscripts of the cells with 1-based linear indices f.
function sub = all_subs_of(shape, f)
ddma.flat_index¶
1-based column-major linear index of 0-based subscripts (K x n).
function f = flat_index(shape, sub)
Models of monotone systems¶
ddma.transitions_to_data¶
Data (z_k, y_k) = ((x_k, u_k), x_k’ - g(x_k, u_k)) for learning f + W.
function [Z, Y] = transitions_to_data(X, U, Xnext, g)
g (optional): handle g(X, U) -> K x nx of the known part. Same as the Python function.
ddma.fit¶
Tightest interval-valued simulating map on a fixed rectangular partition.
function S = fit(Z, Y, edges, d_lo, d_hi, signs, backend, compact)
S = ddma.fit(Z, Y, edges, d_lo, d_hi) computes sigma (TAC paper, Theorem 2) with the
O(|K| log|Q| + |Q|) sweep (Proposition 5).
Z (K x n), Y (K x m) data; edges: cell array of edge vectors (one per input);
d_lo, d_hi: disturbance bounds (scalars or 1 x m).
Optional: signs (m x n, -1/0/+1), backend 'auto' (MEX if compiled) | 'mex' | 'matlab'.
compact = true: store the bounds as single, rounded outward (half the memory, still
sound; see ddma.compact).
S.lower, S.upper: N x m, cells in column-major order; S.shape, S.edges, S.d_lo, ...
Refine with new data: ddma.fit_update (exact, TAC Prop. 3).
ddma.fit_update¶
function S = fit_update(S, Z, Y)
Refine a map from ddma.fit with new data, without revisiting the old data:
the map of the union of both data sets is the intersection of the two maps (TAC
Prop. 3). A compact (single) map stays compact, rounded outward.
Same as the Python PartitionedSimulatingMap.update.
ddma.intersect¶
function S = intersect(S, T)
Intersection of two maps from ddma.fit on the same partition, disturbance
bounds and sign pattern: the map of the union of both data sets. If S is compact
(single), T is rounded outward first. Same as the Python PartitionedSimulatingMap.intersect.
ddma.compact¶
function S = compact(S)
Store the bounds of a map from ddma.fit as single (half the memory), rounded
outward (lower bounds down, upper bounds up), so the map stays sound.
Same as the Python PartitionedSimulatingMap.compact / fit(..., compact=True).
ddma.bounds¶
function [lo, hi] = bounds(S, zq)
Evaluate a fitted map S (from ddma.fit or ddma.bd_fit) at points zq (M x n):
bounds on f(z) + d at the cells of the points.
ddma.f_bounds¶
function [lo, hi] = f_bounds(S, zq)
Bounds on the unknown function f itself at points zq (M x n):
[lower - d_lo, upper - d_hi] of the cells of the points. S from ddma.fit,
ddma.bd_fit or ddma.growth_map. Same as the Python f_bounds methods.
ddma.contains¶
function ok = contains(S, z, y, tol)
Whether each pair (z(k, :), y(k, :)) satisfies y in the interval of the cell
of z (S from ddma.fit or ddma.bd_fit). Same as the Python PartitionedSimulatingMap.contains.
ddma.widths¶
upper - lower per cell and output (Inf where unbounded), N x m.
function w = widths(S)
ddma.bounded_fraction¶
Fraction of cells whose interval is bounded in every output.
function f = bounded_fraction(S)
ddma.is_empty¶
Cells where lower > upper in some output (never for consistent data).
function e = is_empty(S)
ddma.msm_bounds¶
Minimal simulating map (TAC paper, Theorem 1) at query points zq.
function [lo, hi] = msm_bounds(Z, Y, d_lo, d_hi, zq, signs)
[lo, hi] = ddma.msm_bounds(Z, Y, d_lo, d_hi, zq) with data Z (K x n), Y (K x m),
disturbance bounds d_lo, d_hi (1 x m or scalars), queries zq (M x n).
Optional signs (m x n, entries -1/0/+1): monotonicity pattern of each output.
ddma.msm_f_bounds¶
function [lo, hi] = msm_f_bounds(Z, Y, d_lo, d_hi, zq, signs)
Bounds on the unknown monotone f at query points zq:
[S_lo(z) - d_lo, S_hi(z) - d_hi] of the minimal simulating map (TAC Thm. 1).
Same as the Python MinimalSimulatingMap.f_bounds.
ddma.msm_estimate¶
function e = msm_estimate(Z, Y, d_lo, d_hi, zq, signs)
Midpoint of the f-bounds of the minimal simulating map (set-membership
estimate); NaN where unbounded. Same as the Python MinimalSimulatingMap.estimate.
ddma.msm_is_consistent¶
function ok = msm_is_consistent(Z, Y, d_lo, d_hi, signs, tol)
Whether some monotone f + [d_lo, d_hi] can explain the data:
y_k <= y_l + (d_hi - d_lo) whenever z_k <= z_l (in the order of the sign pattern).
A violation shows that the monotonicity assumption, the sign pattern or the
disturbance bounds are wrong. (Merging two data sets = concatenating Z and Y.)
Same as the Python MinimalSimulatingMap.is_consistent.
Models of systems with bounded derivatives¶
ddma.bd_fit¶
Model of a map with bounded partial derivatives on a rectangular partition.
function S = bd_fit(Z, Y, edges, g_lo, g_hi, d_lo, d_hi, method, local, backend, features)
S = ddma.bd_fit(Z, Y, edges, g_lo, g_hi, d_lo, d_hi, method) learns, for every cell
and output i, an interval containing f_i(z) + d_i for all z in the cell, from data
Y(k, i) = f_i(Z(k, :)) + d_i with d_i in [d_lo(i), d_hi(i)], for an unknown f whose
partial derivatives satisfy g_lo(i, j) <= df_i/dz_j <= g_hi(i, j).
Thesis, Chapter 3 (approaches of Section 3.4); same models as the Python
BoundedDerivativeModel(method=...):
'two_matrix' (approach 1, default) two monotone transforms, interval final step
'all_matrix' (2) all 2^n slope choices per output
'lin_mono' (3) as 'all_matrix', linear-programming final step
'growth' (4) growth cones at the grid vertices
'lin_growth' (5) as 'growth', linear-programming final step
Z (K x n), Y (K x m); edges: cell array of edge vectors (one per input);
g_lo, g_hi: m x n (or 1 x n for all outputs); d_lo, d_hi: scalars or 1 x m.
Optional: local = '' (default) | 'cell' | 'slab' (growth methods: also intersect with
the cones of the data in each cell / in its slabs); backend = 'auto' (MEX if compiled)
| 'mex' | 'matlab'. The 'lin_*' methods need linprog (Optimization Toolbox) or
Octave's glpk; their bounds are certified by weak duality, so they stay sound
whatever the solver tolerance.
S has the fields of ddma.fit (edges, shape, lower, upper: N x m, cells in
column-major order, d_lo, d_hi), so ddma.bounds and ddma.abstraction take it as is.
As with ddma.fit, subtract a known part g from the data first and pass its bounds to
ddma.abstraction.
features (optional): cell array with, for each output i, the coordinates (1-based)
that f_i depends on. Output i is then learned on that sub-grid only, which can save
orders of magnitude of memory (e.g. Lorenz). Derivative bounds outside the listed
coordinates are ignored: listing features asserts that f_i does not depend on the
others. With features, S.lower and S.upper are empty; read bounds with ddma.bounds
(or pass S to ddma.abstraction, which handles them).
Online use: ddma.bd_update adds data exactly (same model as a refit on all data);
ddma.bd_update_local (growth methods) updates a window of cells around each point;
then ddma.abstraction_refresh and ddma.safety(..., known_winning).
ddma.bd_update¶
Add data to a model from ddma.bd_fit (exact: same model as a refit on all data).
function S = bd_update(S, Z, Y)
S = ddma.bd_update(S, Z, Y) with Z (K x n), Y (K x m) as in ddma.bd_fit. The stored
maps are intersected with those of the new data (sign-matrix methods: the simulating
maps; growth methods: the vertex values and local maps), then the final step is
recomputed on all cells. The bounds only shrink, so every model along the way is
sound. For the 'lin_*' methods the final step solves one LP per cell: for frequent
small updates prefer 'growth' with ddma.bd_update_local.
Same as the Python BoundedDerivativeModel.update.
ddma.bd_update_local¶
Windowed update of a growth model (thesis Section 3.2, Prop. 13).
function S = bd_update_local(S, Z, Y, window)
S = ddma.bd_update_local(S, Z, Y, window): each data point tightens the model only on
the cells within window cells of its own cell (scalar, or 1 x n per coordinate), and
only those cells are recomputed. Sound; cheaper than ddma.bd_update on large grids and
never tighter than it. Meant for online use, one or a few points at a time.
The changed cell boxes are appended to S.changed (rows [first, last], 0-based, in the
coordinates of S); ddma.abstraction_refresh recomputes the transitions of the
affected states. Same model as the Python update_local.
ddma.growth_map¶
Growth-cone model of one scalar function with bounded derivatives.
function S = growth_map(Z, y, edges, g_lo, g_hi, d_lo, d_hi, local, final, backend)
S = ddma.growth_map(Z, y, edges, g_lo, g_hi, d_lo, d_hi) for an unknown f with
df/dz_j in [g_lo(j), g_hi(j)] and data y(k) = f(Z(k, :)) + d, d in [d_lo, d_hi]:
for every cell an interval containing f(z) + d for all z in the cell. local =
'slab' (default, tightest), 'cell' or ''; final = 'box' (default, approach 4) or
'lp' (approach 5). This is ddma.bd_fit with method 'growth' / 'lin_growth' for one
output, so ddma.bd_update, ddma.bd_update_local, ddma.bounds and ddma.f_bounds apply.
Same as the Python GrowthMap.
ddma.estimate_derivative_bounds¶
Derivative and disturbance bounds from data (TAC Sec. IV).
function [a_lo, a_hi, w] = estimate_derivative_bounds(Z, Y, n_lp_pairs, n_w_pairs, w_weight, pairs)
[a_lo, a_hi, w] = ddma.estimate_derivative_bounds(Z, Y) with data 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 (default 50000) gives the derivative bounds
a_lo(i, :), a_hi(i, :), then (33) on n_w_pairs fresh pairs (default 1e6) gives w(i).
w_weight (default 1) multiplies the disturbance term of the LP cost (the original
experiments used 50); any value keeps the guarantee of Proposition 9, which concerns
only the second step. pairs (optional) fixes the pairs: struct with 1-based index
vectors a1, b1 (first step) and a2, b2 (second step).
a_lo, a_hi: m x n; w: 1 x m (disturbance interval [-w, w]). See
ddma.scenario_confidence for the probabilistic guarantee. Needs linprog or glpk.
Same as the Python estimate_derivative_bounds.
ddma.scenario_confidence¶
function c = scenario_confidence(n_w_pairs, beta)
Proposition 9 (TAC): with probability >= 1 - beta, a fresh pair of
samples satisfies the bounds of ddma.estimate_derivative_bounds with probability
>= beta^(1 / n_w_pairs). Same as the Python scenario_confidence.
ddma.max_min_affine¶
Certified upper bounds of max over a box of a minimum of affine functions.
function out = max_min_affine(offsets, slopes, lo, hi, fallback)
out(k) >= max_{z in [lo(k,:), hi(k,:)]} min_l (offsets(k, l) + slopes(l, :) * z')
offsets: N x L (entries may be +Inf: constraint absent); slopes: L x n; lo, hi: N x n
(finite); fallback: N x 1 sound upper bounds (default +Inf).
One small LP per cell (linprog, or glpk in Octave). Its value is not used directly:
from the dual multipliers lam (normalized to sum 1) the bound
sum_l lam_l off_l + sum_j max(mu_j lo_j, mu_j hi_j), mu = sum_l lam_l a_l,
is an upper bound for any such lam (weak duality), so the result is sound whatever
the solver accuracy. Same method as ddma/_box_lp.py.
Abstraction¶
ddma.abstraction¶
Symbolic abstraction of x+ in f(x,u) + g(x,u) + W from a fitted map S.
function A = abstraction(Xedges, Uedges, S, g_bounds, features, assumption, lazy, backend)
A = ddma.abstraction(Xedges, Uedges, S, g_bounds, features, assumption)
Xedges, Uedges: state and input partitions (cell arrays of edges);
S: map of f + W from ddma.fit or ddma.bd_fit, on the (x, u) coordinates listed in
features (default all), whose partition must be the projection of Xedges x Uedges;
g_bounds: [] (g = 0) or handle [glo, ghi] = g_bounds(xlo, xhi, ulo, uhi);
assumption: [] or 2 x nx [lo; hi] state box for assume-guarantee contracts
(use -Inf/Inf for free coordinates; finite bounds on cell edges).
A.first, A.last: nQ x nP x nx (0-based successor cell ranges), A.enabled: nQ x nP.
Cells are numbered in column-major order. A.opts keeps g_bounds, features and
assumption for ddma.abstraction_refresh.
lazy = true: no transitions are stored (A.first, A.last, A.enabled are empty; A.S
keeps the map). ddma.safety then evaluates a transition only when its scan reaches
it: states outside the safe set are never expanded and each state stops at its first
good input. Memory O(nQ) instead of O(nQ nP); same winning set. ddma.controller_input
computes the allowed inputs on demand. reach_avoid needs an eager abstraction.
Same as the Python SymbolicAbstraction(..., lazy=True).
backend: 'auto' (default: the MEX kernel ddma_abs_mex if built, on all cores, see
ddma.set_num_threads), 'mex' or 'matlab'. All give the same abstraction.
ddma.abstraction_refresh¶
Recompute the transitions of some states after the model was refined.
function [A, S, mask] = abstraction_refresh(A, S, states)
[A, S, mask] = ddma.abstraction_refresh(A, S) recomputes, for all inputs, the
transitions of the state cells whose coordinates lie in a box changed by
ddma.bd_update_local (S.changed, which is then cleared). Same result as rebuilding
the abstraction with ddma.abstraction (options from A.opts), at the cost of the
changed states only. mask (nQ x 1 logical): the recomputed states.
ddma.abstraction_refresh(A, S, states): recompute the given states instead (logical
mask or 1-based indices), e.g. all of them after ddma.bd_update.
After a refinement the successor boxes only shrink, so the previous winning set stays
controlled invariant: pass it to ddma.safety as known_winning.
A lazy abstraction stores no transitions: only its map is replaced by S.
Same as the Python SymbolicAbstraction.refresh.
ddma.affine_bounds¶
Interval image of g(x, u) = A x + B u + c over boxes.
function f = affine_bounds(A, B, c)
f = ddma.affine_bounds(A, B, c) returns a handle [glo, ghi] = f(xlo, xhi, ulo, uhi)
(rows are boxes) usable as g_bounds in ddma.abstraction.
ddma.box_all_in¶
good(q, p): input p enabled at q and all successor cells of (q, p) are in W.
function good = box_all_in(A, W, backend)
backend: 'auto' (MEX if compiled, see build_mex) | 'mex' | 'matlab'. Same result.
Synthesis and closed loop¶
ddma.safety¶
Maximal controlled invariant subset of the safe cells (greatest fixed point).
function [domain, allowed] = safety(A, safe, backend, known_winning, check)
[domain, allowed] = ddma.safety(A, safe): safe is a logical nQ x 1 mask;
domain (nQ x 1) is the winning set, allowed(q, p) the safe inputs at q.
backend: 'auto' (MEX if compiled, see build_mex) | 'mex' | 'matlab'. Same result.
The MEX kernel keeps, for each state, a pointer to its first input not yet ruled
out; the set only shrinks, so each (state, input) pair is examined at most once.
ddma.safety(A, safe, backend, known_winning): incremental update. known_winning is a
set of cells known to be controlled invariant inside safe, typically the previous
winning set after the model was refined (ddma.bd_update / bd_update_local, then
ddma.abstraction_refresh): refined successor boxes only shrink, so the old set stays
controlled invariant and the new maximal set contains it. These cells are kept and
not tested; the result is the same maximal set, and it only grows during online
refinement. With check = true (default) the assumption is verified first and an
error is raised if it does not hold. Same as the Python safety(known_winning=).
With a lazy abstraction (ddma.abstraction(..., lazy=true)) transitions are evaluated
on demand by the pointer scan, and allowed is returned as a struct (lazy, domain,
sat, n_evaluated = number of transitions evaluated) from which ddma.controller_input computes the allowed inputs of a state.
ddma.reach_avoid¶
States that can be driven to target while avoiding avoid (least fixed point).
function [domain, allowed, value] = reach_avoid(A, target, avoid, backend)
value(q) = number of steps needed (Inf if unreachable); allowed(q, p) inputs whose
successors all have a smaller value.
backend: 'auto' (MEX if compiled, see build_mex) | 'mex' | 'matlab'. Same result.
ddma.controller_input¶
A concrete input at state x: point of an allowed input cell.
function u = controller_input(A, allowed, x, pick)
pick: 'center' (default, first allowed cell), 'random', or a desired input vector
(safety filter: nearest admissible point). Returns [] outside the domain.
allowed: the matrix from ddma.safety / ddma.reach_avoid, or the struct that
ddma.safety returns for a lazy abstraction.
ddma.simulate¶
Closed-loop simulation of the concrete system x+ = step(x, u).
function [xs, us] = simulate(step, A, allowed, x0, n_steps, pick, stop_in, nominal)
[xs, us] = ddma.simulate(step, A, allowed, x0, n_steps) with the controller (A,
allowed) from ddma.safety / ddma.reach_avoid. pick: 'center' (default), 'random';
nominal (optional handle x -> desired input): the controller acts as a safety filter
around it (ddma.controller_input with the desired input). Stops early if the state
leaves the controller domain, or once it enters stop_in (logical state-cell mask).
xs: (T+1) x nx states, us: T x nu inputs. Same as the Python simulate.
Safe envelopes without a grid¶
ddma.monotone_envelope¶
Certified safe envelope of a monotone system from transitions, no grid.
function E = monotone_envelope(X, Xn, U, opts)
E = ddma.monotone_envelope(X, Xn, U, opts) with X, Xn (N x n) states and measured
successors, x_k+ = f(x_k, u_k) + w_k, and U (N x m) inputs ([] if autonomous).
opts (struct, all fields optional):
w_lo, w_hi additive disturbance bounds in state units (default 0)
x_lo, x_hi safety box, lower-closed in the flipped coordinates (default +-Inf)
state_signs, input_signs +1/-1 so that f increases in (s.*x, su.*u) (default +1)
u_lo, u_hi input range where f is monotone (default: the data's range)
max_states limit on partial corners kept by the search (default 2e6)
E.corners (L x n): maximal corners T (original coordinates); every state below T (in
the flipped order) can be kept below it forever. E.pairs_T, E.pairs_U: non-dominated
(corner, input limit) pairs. Use ddma.envelope_contains and ddma.envelope_input.
Method of Makdesi & Zamani, IFAC WC 2026. Same as Python ddma.invariance.monotone_envelope.
ddma.embedding_envelope¶
Certified safe envelope of a nonlinear system with bounded Jacobians.
function E = embedding_envelope(X, Xn, U, jx_lo, jx_hi, ju_lo, ju_hi, opts)
E = ddma.embedding_envelope(X, Xn, U, jx_lo, jx_hi, ju_lo, ju_hi, opts) with
X, Xn (N x n) states and measured successors, x_k+ = f(x_k, u_k) + w_k, U (N x m)
inputs ([] if autonomous), jx_lo/jx_hi (n x n) bounds on df_i/dx_j and ju_lo/ju_hi
(n x m) on df_i/du_k ([] if autonomous). opts (struct, optional fields): w_lo, w_hi
(disturbance, state units, default 0), x_lo, x_hi (safety box), pairs (P x 2, 1-based;
default all i < j in the order of Python's triu_indices), chunk.
Every pair spans a state box and an input box; growth cones of the two points bound
where the box can go; boxes that provably map into themselves are kept.
E.lo, E.hi (K x n), E.ulo, E.uhi (K x m), E.pairs (K x 2, 1-based), E.n_pairs.
Method of Makdesi, Zamani & Jafarpour, IFAC WC 2026. Same as the Python
ddma.invariance.embedding_envelope.
ddma.envelope_contains¶
Which states (rows of x) lie in a certified envelope.
function in = envelope_contains(E, x)
in = ddma.envelope_contains(E, x) for E from ddma.monotone_envelope or
ddma.embedding_envelope. Same as the Python contains() methods.
ddma.envelope_input¶
Certified input at state x closest to u_desired ([] outside the envelope).
function u = envelope_input(E, x, u_desired)
u = ddma.envelope_input(E, x, u_desired) for E from ddma.monotone_envelope or
ddma.embedding_envelope (u_desired optional). Same as the Python safe_input().
ddma.maximal_points¶
Rows of P that no other row dominates (componentwise >=), duplicates once.
function [M, keep] = maximal_points(P)
[M, keep] = ddma.maximal_points(P) returns M = P(keep, :). Sort-filter skyline: rows
sorted by decreasing sum can only be dominated by earlier rows. Same as the Python
ddma.invariance.maximal_points.
ddma.max_min_cones¶
max over s in [0,1]^d of min(p + alphas, q + beta(1 - s)), exactly.
function val = max_min_cones(p, q, alpha, beta)
val = ddma.max_min_cones(p, q, alpha, beta): p, q are R x 1, alpha, beta are R x d
(all >= 0); val is R x 1. By LP duality this is the minimum over lam in [0, 1] of a
convex piecewise-linear function; one sort of the breakpoints beta./(alpha+beta) finds
it. Same as the Python ddma.invariance.max_min_cones.
Assumption monitor¶
Check data against the model’s assumptions: the learning data before learning (check_data), new transitions while the system runs (monitor*).
ddma.check_data¶
Check every pair of data points against the assumptions, before learning.
function R = check_data(Z, Y, slope_lo, slope_hi, d_lo, d_hi, opts)
R = ddma.check_data(Z, Y, slope_lo, slope_hi, d_lo, d_hi, opts)
R = ddma.check_data(Z, Y, [], [], d_lo, d_hi, struct('signs', signs))
Needs only the data and the assumptions (no model): slope intervals (m x n) or a sign
pattern (opts.signs, as for ddma.fit). Exact: every conflicting pair is found.
opts: signs, tol (1e-9), prune (true: skip grid cells where no pair can conflict;
same result), backend ('auto' | 'mex' | 'matlab'), input_names, output_names.
R: ok, n_points, pairs_evaluated, violating (1 x m conflicting pairs per output),
worst (1 x m), worst_pair (m x 2, 1-based [later, earlier], nan if none), conflicts
(K x 1 partners each point conflicts with), suspects (points with conflicts, most
first), needed (as ddma.monitor_needed), report (text). Same as Python ddma.check_data.
ddma.monitor¶
function M = monitor(slope_lo, slope_hi, d_lo, d_hi, opts)
Check data against a model's assumptions (signs, derivative bounds, disturbance
bounds) while the system runs. Same as the Python ddma.AssumptionMonitor.
M = ddma.monitor(slope_lo, slope_hi, d_lo, d_hi, opts)
slope_lo, slope_hi (m x n): interval of df_i/dz_j assumed by the model (-inf / inf
allowed): sign +1 -> [0, inf], sign -1 -> [-inf, 0], sign 0 or not a feature ->
[0, 0], bounded derivatives -> [g_lo, g_hi] (see ddma.monitor_monotone and
ddma.monitor_for_model). d_lo, d_hi: disturbance bounds (scalars or 1 x m).
Two data points a, b are consistent with the assumptions iff for every output i
y_a(i) - y_b(i) <= (d_hi(i) - d_lo(i)) + sum_j s_ij(z_a(j) - z_b(j)),
s_ij(t) = slope_hi(i,j) t (t > 0), slope_lo(i,j) t (t < 0), 0 (t = 0).
A violation proves that some assumption is wrong. ddma.monitor_check checks each new
transition at three levels: 'cells' (the model's cell bounds, if opts.model),
'sample' (a fresh random sample of stored points; only with full = 'later') and
'full' (every earlier point). A point that fails is quarantined: kept for the
diagnosis, but later points are not blamed for disagreeing with it.
ddma.monitor_needed gives, for each assumption, the smallest change that alone makes
all stored data consistent; ddma.monitor_report summarises in plain words.
opts (struct, all optional):
on_violation 'alarm' (default) | 'widen' | 'fallback' | 'widen_then_fallback'
widen 'disturbance' (default) | {'slope_lo', i, j} | {'slope_hi', i, j}
(a slope bound only if both of its ends are finite, with slope_limit)
widen_limit 'widen_then_fallback': largest disturbance width as a multiple of
the original width (default 2; scalar or 1 x m); beyond: fallback
slope_limit absolute limit of a widened slope bound (required for a slope target)
margin relative extra widening (default 0)
full 'step' (default): full check of each point in its step; 'later':
levels 1-2 during the run, ddma.monitor_flush checks the rest
sample level 2: points per step (default 2000; full = 'later' only)
prune skip grid cells where no pair can conflict (default true; same results)
model fitted map (ddma.fit / ddma.bd_fit / ddma.growth_map) whose cell
bounds are level 1; set by ddma.monitor_for_model
tol violations below tol are ignored (default 1e-9)
callback function handle called with the violations found at once
input_names, output_names cell arrays of names for the report
seed seed of the level-2 samples (default 0; same samples as Python)
backend 'auto' (MEX if built) | 'mex' | 'matlab' (same results)
Indices are 1-based (transitions in the order checked; seed data -1, -2, ...).
ddma.monitor_monotone¶
function M = monitor_monotone(signs, d_lo, d_hi, opts)
Assumption monitor of a monotone model with sign pattern signs (m x n):
+1 -> slope in [0, inf], -1 -> [-inf, 0], 0 -> [0, 0]. See ddma.monitor.
ddma.monitor_for_model¶
Assumption monitor of a fitted map, seeded with its data (Z, Y).
function M = monitor_for_model(S, Z, Y, opts)
S from ddma.fit (signs), ddma.bd_fit or ddma.growth_map (derivative bounds: [g_lo, g_hi]
for the growth methods, [min(g_lo,0), max(g_hi,0)] for the others, 0 outside features).
The map's cell bounds are level 1. Monotone maps (ddma.fit) can only widen the
disturbance. Same as AssumptionMonitor.for_model.
ddma.monitor_add¶
function M = monitor_add(M, Z, Y)
Store data without checking them (e.g. the data the model was learned from;
check those with ddma.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.
ddma.monitor_check¶
function [M, viol] = monitor_check(M, Z, Y)
Check new transitions one by one, store them and respond. viol: struct
array with fields index (1-based position among the checked transitions), output,
level ('cells', 'sample' or 'full'), gap, witness (id of the stored point it
conflicts with: seed data -1, -2, ..., checked points their index; nan for 'cells')
and found_at (index of the last checked transition when found). With full = 'later'
only levels 1-2 run here; ddma.monitor_flush runs level 3.
Same as AssumptionMonitor.check.
ddma.monitor_flush¶
function [M, viol] = monitor_flush(M)
Run the full check (level 3) of all pending points now (full = 'later':
e.g. back at base after a run), record and respond. Same as AssumptionMonitor.flush.
ddma.monitor_status¶
Counts: stored points, pending full checks, quarantined points, cells.
function s = monitor_status(M)
ddma.monitor_data¶
function [Z, Y] = monitor_data(M, quarantined)
Stored data, e.g. for a refit: clean points only, or all with
ddma.monitor_data(M, true).
ddma.monitor_quarantine¶
function Q = monitor_quarantine(M)
The quarantined points: struct with ids (seed: negative; checked:
transition index, 1-based), Z, Y and the violations that put them there.
ddma.monitor_needed¶
function need = monitor_needed(M)
Smallest single changes that make all stored data consistent: struct with
width (1 x m, disturbance width d_hi - d_lo needed), slope_lo, slope_hi (m x n), each
with all other assumptions unchanged. Equal to the current value: no change needed;
nan: this bound alone cannot explain the violations. Exact once no full check is
pending (ddma.monitor_flush). Same as AssumptionMonitor.needed.
ddma.monitor_widen¶
function [M, changed] = monitor_widen(M, target, at)
Apply the smallest change of one assumption (times 1 + margin) that makes
all stored data consistent: target 'disturbance' (default; widened symmetrically) or
{'slope_lo', i, j} / {'slope_hi', i, j} (never beyond M.slope_limit). Pending full
checks are run first; quarantined points then rejoin the data. The model must be
refit from ddma.monitor_data(M) with the new assumptions (M.needs_refit).
Same as AssumptionMonitor.widen.
ddma.monitor_consistent¶
function ok = monitor_consistent(M)
Whether all stored data (quarantined too) are consistent with the
current assumptions (all pairs, exact). Same as AssumptionMonitor.consistent.
ddma.monitor_reset¶
function M = monitor_reset(M)
Clear the violation record, the fallback flag and the needed changes
(assumptions and quarantine stay as they are). Same as AssumptionMonitor.reset.
ddma.monitor_report¶
function txt = monitor_report(M)
Plain-words summary: checks, violations, the levels that found them, and
the single changes of the assumptions that would explain them. Same text as
AssumptionMonitor.report (transition numbers are 1-based here).
ddma.monitor_rebuild_index¶
function M = monitor_rebuild_index(M)
Rebuild the cell grid used for pruning from all stored points (done
by ddma.monitor_add, and when the data have doubled since the last build). Only with
the MEX kernel; the MATLAB code checks all pairs (same results).
Reinforcement learning¶
Wrappers for environments in the form used by the Reinforcement Learning Toolbox (rlFunctionEnv).
ddma.safe_step¶
Certified safety filter around an environment step function.
function wrapped = safe_step(step_fcn, A, allowed, state_fcn, penalty)
wrapped = ddma.safe_step(step_fcn, A, allowed) returns a step function with the
signature of the Reinforcement Learning Toolbox (rlFunctionEnv):
[NextObs, Reward, IsDone, LoggedSignals] = wrapped(Action, LoggedSignals)
Each action first goes through the safety filter of the controller (A, allowed) from
ddma.safety (ddma.controller_input with the action as desired input): a safe action
passes unchanged, an unsafe one is replaced by the nearest safe one. As long as the
state starts in the controller domain (see ddma.safe_reset), the system stays in the
safe set for ever, whatever the agent does, during training as well.
state_fcn (optional): handle LoggedSignals -> state x of the abstraction (default:
LoggedSignals.State). penalty (optional, default 0): reward penalty per unit of
correction. LoggedSignals gains SafeAction, Filtered, Correction, OutsideDomain.
Same as the Python ddma.rl.SafetyFilterWrapper.
With the Reinforcement Learning Toolbox (not needed by ddma):
env = rlFunctionEnv(obsInfo, actInfo, ddma.safe_step(@myStep, A, allowed), ...
ddma.safe_reset(@myReset, A, allowed));
agent = rlPPOAgent(obsInfo, actInfo); train(agent, env, trainOpts);
ddma.safe_reset¶
function wrapped = safe_reset(reset_fcn, A, allowed, state_fcn, max_tries)
Reset function that redraws the initial state until it lies in the domain
of the safety controller (A, allowed) from ddma.safety, so that ddma.safe_step
guarantees safety from the first step. Signature of the Reinforcement Learning
Toolbox (rlFunctionEnv): [InitialObs, LoggedSignals] = wrapped().
state_fcn (optional): LoggedSignals -> state (default LoggedSignals.State).
Same as the Python SafetyFilterWrapper(reset_in_domain=True).
Threads, plotting and helpers¶
ddma.set_num_threads¶
Number of threads used by the compiled kernels.
function set_num_threads(n)
ddma.set_num_threads(n) makes the MEX kernels of ddma.fit, ddma.fit_update,
ddma.bd_fit / ddma.bd_update (growth methods), ddma.growth_map and ddma.abstraction
use n threads.
ddma.set_num_threads() or ddma.set_num_threads(0) restores the default: the value of
the environment variable OMP_NUM_THREADS if it is set (before MATLAB starts),
otherwise all cores.
Results are bit-identical for any number of threads. Without the MEX files, or when
they were built without OpenMP, everything runs on one thread (same results).
See also ddma.get_num_threads, build_mex.
ddma.get_num_threads¶
Number of threads the compiled learning kernels will use.
function [n, openmp] = get_num_threads()
[n, openmp] = ddma.get_num_threads(): n threads (1 without the MEX files or without
OpenMP); openmp = true if the MEX files were built with OpenMP.
See also ddma.set_num_threads.
ddma.plot_bounds¶
Transparent staircase bounds of a 2-input map S (from ddma.fit), TAC Fig. 8.
function h = plot_bounds(S, output, trueFun, trim)
ddma.plot_bounds(S) draws the upper and lower bounds of output 1 as transparent
piecewise-constant surfaces (one flat top per cell, as kron(.., ones(2)) in the
original scripts). ddma.plot_bounds(S, i, trueFun) also draws trueFun(Z) (Z: K x 2)
as a solid surface. trim (default 1) drops that many outer cells on each side.
(Not render-tested in CI: Octave in the CI image has no working graphics.)
ddma.plot_set¶
Draw a set of cells (controllable / invariant set), TAC Figs. 11-12, ADHS Fig. 6.
function h = plot_set(edges, mask, color)
ddma.plot_set(edges, mask) with a 3-D partition draws the isosurface of the cell
indicator (cell centres as coordinates); with a 2-D partition, filled cells.
mask: logical, one entry per cell (column-major order or array of the grid shape).
An empty mask draws the text 'empty set'. Rendered in MATLAB R2025 (MATLAB Online);
not render-tested in CI (Octave in the CI image has no working graphics).
ddma.seed¶
Seed the random number generator in both MATLAB and Octave.
function seed(n)