Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ classifiers = [
"Topic :: Scientific/Engineering :: Physics",
]
dependencies = [
"dit>=2.3",
"dit>=2.4",
"networkx>=2.6",
"numpy>=1.22",
"pyyaml>=6.0",
Expand All @@ -48,7 +48,7 @@ test = [
"pytest-cov",
"pytest-rerunfailures",
"pytest-sugar",
"pytest-xdist",
"pytest-xdist>=3.2",
]
docs = [
"sphinx",
Expand Down Expand Up @@ -80,7 +80,7 @@ capacity = [
]
symbolic = [
"sympy>=1.12",
"dit[symbolic]>=2.3",
"dit[symbolic]>=2.4",
]

# ── uv ──────────────────────────────────────────────────────────────────
Expand Down Expand Up @@ -111,6 +111,7 @@ addopts = [
"--cov=sofic",
"--cov-report=term-missing",
"--numprocesses=auto",
"--dist=worksteal",
"--durations=25",
"--durations-min=1.0",
"--reruns=1",
Expand Down
83 changes: 64 additions & 19 deletions sofic/generators/coverage_bound.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,35 @@ def mu_k_spectral_cap(M: np.ndarray, k: int) -> float:
return float(M.sum()) - max(0.0, tail - slack)


def _cross(a: np.ndarray, b: np.ndarray) -> np.ndarray:
return np.stack(
[
a[..., 1] * b[..., 2] - a[..., 2] * b[..., 1],
a[..., 2] * b[..., 0] - a[..., 0] * b[..., 2],
a[..., 0] * b[..., 1] - a[..., 1] * b[..., 0],
],
axis=-1,
)


def _solve_square_systems(G: np.ndarray, h: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Solutions of ``G x = h`` over the leading axes, and which systems are regular (``|det G| > 1e-14``).

The solutions of singular systems are arbitrary finite values. Systems of size three, the common case,
are solved by Cramer's rule, which beats a LAPACK call per tiny matrix.
"""
m = G.shape[-1]
if m != 3:
regular = np.abs(np.linalg.det(G)) > 1e-14
return np.linalg.solve(np.where(regular[..., None, None], G, np.eye(m)), h[..., None])[..., 0], regular
r0, r1, r2 = G[..., 0, :], G[..., 1, :], G[..., 2, :]
c0, c1, c2 = _cross(r1, r2), _cross(r2, r0), _cross(r0, r1)
det = (r0 * c0).sum(axis=-1)
regular = np.abs(det) > 1e-14
x = (h[..., 0, None] * c0 + h[..., 1, None] * c1 + h[..., 2, None] * c2) / np.where(regular, det, 1.0)[..., None]
return x, regular


def _column_box_lp(U: np.ndarray, A: np.ndarray, C: np.ndarray) -> np.ndarray:
"""``max 1.x`` over ``0 <= x <= U[b]``, ``A[p].x <= 0``, ``C[p].x >= 0`` for every column ``b`` and pair ``p``.

Expand All @@ -174,9 +203,7 @@ def _column_box_lp(U: np.ndarray, A: np.ndarray, C: np.ndarray) -> np.ndarray:
G[:, :, 2 * m] = A[None]
G[:, :, 2 * m + 1] = -C[None]
combos = np.array(list(combinations(range(2 * m + 2), m)))
Gs, hs = G[:, :, combos], h[:, :, combos]
regular = np.abs(np.linalg.det(Gs)) > 1e-14
x = np.linalg.solve(np.where(regular[..., None, None], Gs, np.eye(m)), hs[..., None])[..., 0]
x, regular = _solve_square_systems(G[:, :, combos], h[:, :, combos])
slack = np.einsum("bpkm,bpcm->bpck", G, x) - h[:, :, None, :]
feasible = regular & (slack.max(axis=-1) <= 1e-12 * (1.0 + float(U.max())))
return np.where(feasible, x.sum(axis=-1), -np.inf).max(axis=-1)
Expand Down Expand Up @@ -291,24 +318,41 @@ def _logsumexp(x: np.ndarray) -> float:
_VERTEX_PERTURBATION = 1e-7


def _tree_potentials(tree: frozenset, L: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Solve ``p_a + q_b = L_ab`` on the edges of a spanning tree of ``K_{na,nb}`` with ``p_0 = 0``."""
def _tree_walk(tree: frozenset, L: np.ndarray) -> tuple[np.ndarray, np.ndarray, list[tuple[int, int]], list[int]]:
"""Solve ``p_a + q_b = L_ab`` on the edges of a spanning tree of ``K_{na,nb}`` with ``p_0 = 0``.

Also returns the tree edges (in the tree's iteration order) and, for each edge ``(a, b)``, the bitmask
of the nodes (rows ``0..na-1``, then columns) left on row ``a``'s side when the edge is removed.
"""
na, nb = L.shape
adj: list[list[int]] = [[] for _ in range(na + nb)]
for a, b in tree:
adj[a].append(na + b)
adj[na + b].append(a)
pot = np.full(na + nb, np.nan)
pot[0] = 0.0
pot = [0.0] * (na + nb)
parent = [-1] * (na + nb)
parent[0] = 0
order = []
stack = [0]
while stack:
x = stack.pop()
order.append(x)
for y in adj[x]:
if np.isnan(pot[y]):
if parent[y] < 0:
parent[y] = x
a, b = (x, y - na) if x < na else (y, x - na)
pot[y] = L[a, b] - pot[x]
stack.append(y)
return pot[:na], pot[na:]
subtree = [1 << x for x in range(na + nb)]
for x in reversed(order[1:]):
subtree[parent[x]] |= subtree[x]
full = (1 << (na + nb)) - 1
edges, sides = [], []
for a, b in tree:
below = subtree[na + b] if parent[na + b] == a else subtree[a]
edges.append((a, b))
sides.append(below if below >> a & 1 else full ^ below)
return np.array(pot[:na]), np.array(pot[na:]), edges, sides


def _initial_tree(L: np.ndarray) -> frozenset:
Expand Down Expand Up @@ -369,23 +413,24 @@ def mu1_vertex(M: np.ndarray, *, max_vertices: int = 200_000) -> Mu1Result | Non
seen = {start}
queue = [start]
best, best_pq = -np.inf, None
bits = 1 << np.arange(na + nb)
while queue:
tree = queue.pop()
p, q = _tree_potentials(tree, L)
p, q, edges, sides = _tree_walk(tree, L)
value = _logsumexp(p) + _logsumexp(q)
if value > best:
best, best_pq = value, (p, q)
slack = L - p[:, None] - q[None, :]
for edge in tree:
comp = _components(na, nb, tree - {edge})
side = comp[edge[0]]
rows_out = np.array([comp[a] != side for a in range(na)])
cols_in = np.array([comp[na + b] == side for b in range(nb)])
if not rows_out.any() or not cols_in.any():
# For each tree edge: rows off and columns on row a's side once it is removed, and the entering
# cell, the first slack minimum in row-major order over that rows x columns block.
on_side = (np.array(sides)[:, None] & bits) != 0
rows_out, cols_in = ~on_side[:, :na], on_side[:, na:]
blocks = rows_out[:, :, None] & cols_in[:, None, :]
entering_cells = np.where(blocks, slack, np.inf).reshape(len(edges), -1).argmin(axis=1)
for edge, has_block, cell in zip(edges, blocks.any(axis=(1, 2)), entering_cells.tolist(), strict=True):
if not has_block:
continue
sub = slack[np.ix_(rows_out, cols_in)]
i, j = np.unravel_index(int(np.argmin(sub)), sub.shape)
entering = (int(np.flatnonzero(rows_out)[i]), int(np.flatnonzero(cols_in)[j]))
entering = divmod(cell, nb)
nxt = (tree - {edge}) | {entering}
if nxt not in seen:
if len(seen) >= max_vertices:
Expand Down
34 changes: 19 additions & 15 deletions sofic/generators/generator_caps.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,29 +242,33 @@ def _sparse(rows: list[list[tuple[int, float]]], n: int) -> sp.csr_matrix:
return sp.csr_matrix((d, (r, c)), shape=(len(rows), n))


def _outward(value: Fraction, down: bool) -> float:
"""``value`` rounded to a float in the given direction."""
f = float(value)
if down and Fraction(f) > value:
return math.nextafter(f, -math.inf)
if not down and Fraction(f) < value:
return math.nextafter(f, math.inf)
return f
def _outward_sum(terms: list[float], *, up: bool) -> float:
"""The exact sum of ``terms`` rounded up (or down) to a float.

``math.fsum`` rounds the exact sum to nearest, and the sign of the correctly rounded residual is exact.
"""
total = math.fsum(terms)
residual = math.fsum([*terms, -total])
if up and residual > 0.0:
return math.nextafter(total, math.inf)
if not up and residual < 0.0:
return math.nextafter(total, -math.inf)
return total


def _tighten(lo: np.ndarray, hi: np.ndarray) -> tuple[np.ndarray, np.ndarray] | None:
"""Shrink a box to its intersection with the probability simplex (``None`` if empty).

The new bounds are computed exactly and rounded outward, so no point of the simplex in the box is lost.
"""
lows, highs = [float(v) for v in lo], [float(v) for v in hi]
for _ in range(3):
exact_lo = [Fraction(float(v)) for v in lo]
sum_lo = sum(exact_lo, Fraction(0))
hi = np.minimum(hi, [_outward(1 - (sum_lo - v), down=False) for v in exact_lo])
exact_hi = [Fraction(float(v)) for v in hi]
sum_hi = sum(exact_hi, Fraction(0))
lo = np.maximum(lo, [_outward(1 - (sum_hi - v), down=True) for v in exact_hi])
return (lo, hi) if np.all(lo <= hi) else None
neg = [-v for v in lows]
highs = [min(h, _outward_sum([1.0, *neg[:i], *neg[i + 1 :]], up=True)) for i, h in enumerate(highs)]
neg = [-v for v in highs]
lows = [max(v, _outward_sum([1.0, *neg[:i], *neg[i + 1 :]], up=False)) for i, v in enumerate(lows)]
lo_out, hi_out = np.array(lows), np.array(highs)
return (lo_out, hi_out) if np.all(lo_out <= hi_out) else None


def _branch_and_bound(
Expand Down
117 changes: 72 additions & 45 deletions sofic/generators/lifted_common_information.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@

import numpy as np
from scipy.optimize import minimize
from scipy.special import entr

from sofic.exceptions import StochasticValidationError
from sofic.generators.minimal_generative_model import (
Expand All @@ -84,6 +85,8 @@
from sofic.generators.bidirectional_epsilon_machine import BidirectionalEpsilonMachine

_LN2 = np.log(2.0)
# I[a : b | c] = H[a, c] + H[b, c] - H[a, b, c] - H[c]
_CMI_SIGNS = np.array([1.0, 1.0, -1.0, -1.0])
_COARSE_TOL = 5e-8
_REFINE = 5
_SUPPORT_CUTOFF = 1e-8
Expand Down Expand Up @@ -120,42 +123,71 @@ def __init__(self, bidir: BidirectionalEpsilonMachine, joint: dict[tuple[Hashabl
transition.data.get(ATTR_PROB, 0.0)
)
self.edges /= self.edges.sum()
# The edge law flattened both ways, and p(s+, s- | pair), for the matrix products below.
self._edges_rows = self.edges.reshape(n * len(symbols), n) # [(p, x), q]
self._edges_cols = self.edges.reshape(n, len(symbols) * n) # [p, (x, q)]
self._pair_labels = (self.plus[:, :, None] * self.minus[:, None, :]).reshape(n, -1) # [p, (a, b)]
self._cached: tuple[tuple[int, ...], bytes, dict[str, np.ndarray]] | None = None

def _products(self, c: np.ndarray) -> dict[str, np.ndarray]:
"""The tensors of :meth:`tensors` and the intermediate products, for the last ``c`` seen.

SLSQP evaluates the constraints and their Jacobian at the same point, so the last one is kept.
"""
key = c.tobytes()
if self._cached is not None and self._cached[0] == c.shape and self._cached[1] == key:
return self._cached[2]
n, k = c.shape
n_plus, n_minus, n_sym = self.plus.shape[1], self.minus.shape[1], self.edges.shape[1]
plus_c = (self.plus[:, :, None] * c[:, None, :]).reshape(n, n_plus * k) # [p, (a, g)]
minus_c = (self.minus[:, :, None] * c[:, None, :]).reshape(n, n_minus * k) # [q, (s, v)]
forward = self._edges_rows @ c # [(p, x), v]
past = (plus_c.T @ forward.reshape(n, n_sym * k)).reshape(n_plus, k, n_sym * k) # [a, g, (x, v)]
products = {
"plus_c": plus_c,
"minus_c": minus_c,
"forward": forward,
# The three joints of constraint_informations, each indexed [a, b, c] for I[a : b | c].
"screen": (self._pair_labels.T @ (self.p[:, None] * c)).reshape(n_plus, n_minus, k),
"future": (c.T @ (self._edges_rows @ minus_c).reshape(n, -1)).reshape(k * n_sym, n_minus, k),
"past": past.transpose(0, 2, 1),
}
self._cached = (c.shape, key, products)
return products

def tensors(self, c: np.ndarray) -> tuple[np.ndarray, ...]:
"""``p(s+, s-, g)``, ``p(g_0, x_0, s-_1, g_1)`` and ``p(s+_0, g_0, x_0, g_1)``."""
joint_g = self.p[:, None] * c
screen = np.einsum("pa,pb,pg->abg", self.plus, self.minus, joint_g)
forward = np.einsum("pxq,qv->pxv", self.edges, c)
future = np.einsum("pg,pxq,qs,qv->gxsv", c, self.edges, self.minus, c)
past = np.einsum("pa,pg,pxv->agxv", self.plus, c, forward)
return screen, future, past
products = self._products(c)
k = c.shape[1]
n_plus, n_minus, n_sym = products["screen"].shape[0], products["screen"].shape[1], self.edges.shape[1]
future = products["future"].reshape(k, n_sym, n_minus, k)
past = products["past"].transpose(0, 2, 1).reshape(n_plus, k, n_sym, k)
return products["screen"], future, past

def constraint_informations(self, c: np.ndarray) -> np.ndarray:
"""``I[S+ : S- | G]``, ``I[G_0 X_0 : S-_1 | G_1]`` and ``I[S+_0 : X_0 G_1 | G_0]`` in bits."""
screen, future, past = self.tensors(c)
return np.array(
[
_conditional_mutual_information(screen),
_conditional_mutual_information(future.reshape(-1, *future.shape[2:])),
_conditional_mutual_information(np.moveaxis(past, 1, -1).reshape(past.shape[0], -1, past.shape[1])),
]
)
products = self._products(c)
return _conditional_mutual_informations((products["screen"], products["future"], products["past"]))

def constraint_jacobian(self, c: np.ndarray) -> np.ndarray:
"""Gradients of :meth:`constraint_informations` in ``c``, shape ``(3, *c.shape)``."""
screen, future, past = self.tensors(c)
products = self._products(c)
screen = products["screen"]
n, k = c.shape
n_plus, n_minus, n_sym = screen.shape[0], screen.shape[1], self.edges.shape[1]
g_screen = _cmi_gradient(screen)
g_future = _cmi_gradient(future.reshape(-1, *future.shape[2:])).reshape(future.shape)
moved = np.moveaxis(past, 1, -1)
g_past = np.moveaxis(_cmi_gradient(moved.reshape(past.shape[0], -1, past.shape[1])).reshape(moved.shape), -1, 1)
jac = np.empty((3, *c.shape))
jac[0] = self.p[:, None] * np.einsum("pa,pb,abg->pg", self.plus, self.minus, g_screen)
jac[1] = np.einsum("gxsv,pxq,qs,qv->pg", g_future, self.edges, self.minus, c) + np.einsum(
"gxsv,pg,pxq,qs->qv", g_future, c, self.edges, self.minus
)
jac[2] = np.einsum("agxv,pa,pxq,qv->pg", g_past, self.plus, self.edges, c) + np.einsum(
"agxv,pa,pg,pxq->qv", g_past, self.plus, c, self.edges
)
g_future = _cmi_gradient(products["future"]).reshape(k * n_sym, n_minus * k) # [(g, x), (s, v)]
g_past = _cmi_gradient(products["past"]).transpose(0, 2, 1).reshape(n_plus * k, n_sym * k) # [(a, g), (x, v)]
jac = np.empty((3, n, k))
jac[0] = self.p[:, None] * (self._pair_labels @ g_screen.reshape(-1, k))
# d/dc[p, g] through the c_0 factor of the future, then d/dc[q, v] through the c_1 factor.
through_target = (g_future @ products["minus_c"].T).reshape(k, n_sym * n) # [g, (x, q)]
through_source = ((c.T @ self._edges_cols).reshape(k * n_sym, n).T @ g_future).reshape(n, n_minus, k)
jac[1] = self._edges_cols @ through_target.T + np.einsum("qs,qsv->qv", self.minus, through_source)
# Likewise for the past, whose c_1 factor sits inside the forward map.
through_forward = (products["forward"].reshape(n, n_sym * k) @ g_past.T).reshape(n, n_plus, k)
through_plus = (products["plus_c"] @ g_past).reshape(n * n_sym, k)
jac[2] = np.einsum("pa,pag->pg", self.plus, through_forward) + self._edges_rows.T @ through_plus
return jac

def markov_residual(self, c: np.ndarray) -> float:
Expand Down Expand Up @@ -189,19 +221,18 @@ def seeds(self, k: int) -> list[np.ndarray]:


def _entropy_bits(p: np.ndarray) -> float:
p = p[p > 0.0]
return float(-(p * np.log2(p)).sum())


def _conditional_mutual_information(joint: np.ndarray) -> float:
"""``I[a : b | c]`` in bits for a joint indexed ``[a, b, c]``."""
return max(
0.0,
_entropy_bits(joint.sum(axis=1))
+ _entropy_bits(joint.sum(axis=0))
- _entropy_bits(joint)
- _entropy_bits(joint.sum(axis=(0, 1))),
)
return float(entr(np.maximum(p, 0.0)).sum()) / _LN2


def _conditional_mutual_informations(joints: Sequence[np.ndarray]) -> np.ndarray:
"""``I[a : b | c]`` in bits for each joint indexed ``[a, b, c]``, from one pass over all the entropies."""
parts = []
for joint in joints:
ac = joint.sum(axis=1)
parts += [ac.ravel(), joint.sum(axis=0).ravel(), joint.ravel(), ac.sum(axis=0)]
starts = np.cumsum([0] + [part.size for part in parts[:-1]])
entropies = np.add.reduceat(entr(np.maximum(np.concatenate(parts), 0.0)), starts).reshape(-1, 4)
return np.maximum(entropies @ _CMI_SIGNS / _LN2, 0.0)


def _cmi_gradient(joint: np.ndarray) -> np.ndarray:
Expand All @@ -210,12 +241,8 @@ def _cmi_gradient(joint: np.ndarray) -> np.ndarray:
def log(x: np.ndarray) -> np.ndarray:
return np.log2(np.maximum(x, 1e-300))

return (
log(joint)
+ log(joint.sum(axis=(0, 1)))[None, None, :]
- log(joint.sum(axis=1))[:, None, :]
- log(joint.sum(axis=0))[None, :, :]
)
ac = joint.sum(axis=1)
return log(joint) + log(ac.sum(axis=0))[None, None, :] - log(ac)[:, None, :] - log(joint.sum(axis=0))[None, :, :]


def _unconstrained_channel(
Expand Down
Loading
Loading