diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a91018..6370840 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,24 @@ A second correctness review: every fix below was reproduced against a brute-force reference or a closed-form value and has a regression test. +### Generator cardinality + +- Minimal generators can need more than `min(|S+|, |S-|) + 1` states. The skip-one chain (the first-order Markov + chain on `Z_6` moving `i -> i + 1` or `i + 2`, with light cells `1e-3`) has `|S+| = |S-| = 6`, vanishing + persistent crypticities, and `C_g = G[S+ : S-] = 2.037622` with 8 states; 7 states give at least 2.269805. The + remarks in `global_bound` and the docs that every certified case needs at most `|S+| + 1` states are replaced, + and `global_bound_states` (default `min(|S+|, |S-|) + 1`) is documented as a convention, not a bound. +- New `generator_bounds.one_wide_exact_common_information(P)`: exact `G[X : Y]` when every rectangle in the support + lies in one row or one column, by enumerating row-or-column assignments of the cells on each connected component; + `by_terms[k]` gives the optimum with at most `k` values. The skip-one chain is its regression test. +- `separating_optima` tries at most `min(m, 8)` terms, `m` the number of support cells: Kumar, Li & El Gamal's + argument restricted to the support bounds the terms of some optimum by `m` (was `|S+| |S-|`). +- Citations: `Feldman1998b` now points to Feldman & Crutchfield's "Discovering Noncritical Organization" (Entropy + 2022, SFI working paper 1998); `Travers2010` to J. Stat. Phys. 145 (2011). `structural_information` cites + Feldman & Crutchfield (2003) and Travers & Crutchfield's asymptotic synchronization paper (2011); + `predictability_gain` notes that `h_mu(L) - h_mu` is Bialek et al.'s learning curve and Crutchfield & Feldman's + `r(L)`, whose "predictability gain" is the first difference `h_mu(L) - h_mu(L - 1)`. + ### Restricted global bound (SCIP) - New `sofic.generators.global_bound`: `generator_global_bound(bidir, k)` minimizes the state entropy over the diff --git a/docs/generators/generative_models.rst b/docs/generators/generative_models.rst index b5556d6..343a1bf 100644 --- a/docs/generators/generative_models.rst +++ b/docs/generators/generative_models.rst @@ -374,6 +374,35 @@ feeds them to :func:`~sofic.generators.generator_caps.generator_coverage_bound` on :math:`C_g` from the forward ε-machine alone. On the :math:`(2, \infty)` process a two-symbol window already gives :math:`C_g \ge 3/2`. +Supports without 2 × 2 rectangles +--------------------------------- + +When no two forward causal states share two reverse causal states, every rectangle in the support +of the causal-state joint lies in one row or one column, and +:func:`~sofic.generators.generator_bounds.one_wide_exact_common_information` computes +:math:`\op{G}{S^+ : S^-}` exactly. Every distribution on such a block is a product, so with the +blocks fixed the decompositions form a product of simplices (each cell's mass split among the +blocks covering it), on which the concave entropy is minimized at a vertex: a partition of the +support. Merging two blocks of one row or one column lowers the entropy, so some optimal partition +sends each cell to its row's block or to its column's block; the function enumerates these +assignments on each connected component of the support and also reports the least entropy with at +most ``k`` blocks. Kumar, Li & El Gamal :cite:`Kumar2014` show that some optimal separating +variable has at most :math:`|S^+||S^-|` values (and at most :math:`2^{\min(|S^+|, |S^-|)} - 1`); +their argument restricted to the support gives at most the number of support cells, which caps the +number of terms :func:`~sofic.generators.coupled_generators.separating_optima` tries. The partition +solver is not from the literature. + +The skip-one chain shows that a minimal generator can need more than +:math:`\min(|S^+|, |S^-|) + 1` states. It is the first-order Markov chain on :math:`\mathbb{Z}_6` +that moves from :math:`i` to :math:`i + 1` or :math:`i + 2`, with the twelve cells +:math:`(i, i + 1), (i, i + 2)` of the joint of consecutive symbols, in cycle order, weighing heavy, +heavy, light (light cells :math:`10^{-3}`, heavy ones :math:`0.1245`). Its causal states are the +previous and the next symbol, so :math:`|S^+| = |S^-| = 6`. Both persistent crypticities vanish, so +:math:`C_g = \op{G}{S^+ : S^-}`, and the support, a 12-cycle, has no :math:`2 \times 2` rectangle. +The optimum pairs adjacent heavy cells and keeps the light ones apart: 8 blocks and +:math:`C_g = 2.037622`, while 7 blocks give at least :math:`2.269805`. This family has no published +source. + Restricted global bound ----------------------- @@ -385,9 +414,11 @@ With the bidirectional edge chain it adds two-step path flows and the two-step e weights are sorted, so caps on the heaviest states enter as linear cuts, and an objective limit (the entropy of a verified generator) lets SCIP prune. The result bounds the state entropy of every generator with at most ``k`` states and says nothing about larger ones. It is therefore a lower -bound on :math:`C_g` only once the number of states of a minimal generator is bounded, which is open -(every certified case so far needs at most :math:`|S^+| + 1` states). It is also numerical, not a -certificate: the equations with data on the right-hand side are relaxed by ``data_tol``, and SCIP +bound on :math:`C_g` only once the number of states of a minimal generator is bounded. No general +bound is known, and :math:`\min(|S^+|, |S^-|) + 1` is not one: the skip-one chain (under +`Supports without 2 × 2 rectangles`_) needs :math:`|S^+| + 2` states. When both persistent +crypticities vanish, ``k`` equal to the number of cells in the support of the causal-state joint +suffices. It is also numerical, not a certificate: the equations with data on the right-hand side are relaxed by ``data_tol``, and SCIP works to its own tolerances. SCIP's solution satisfies necessary conditions only; :func:`~sofic.generators.hmm_search.hmm_generator_search` with ``initial`` polishes it into a generator. On the binary process with symbol matrices @@ -398,7 +429,8 @@ generator. On the binary process with symbol matrices generator with at most 3 states does :math:`10^{-4}` bits better. The pipeline runs it with ``global_bound=True``, after the belief-free search, for -``global_bound_states`` states (default :math:`\min(|S^+|, |S^-|) + 1`). It gets half the remaining +``global_bound_states`` states (default :math:`\min(|S^+|, |S^-|) + 1`, a convention, not a bound). +It gets half the remaining budget (120 s without a budget) and the best candidate's entropy as its objective limit, and it is skipped above 2,000 SCIP variables. The value goes to ``restricted_lower`` and ``restricted_states``, not to ``lower``, so ``certified`` is unchanged; the polished solution is offered as a candidate. The @@ -464,6 +496,9 @@ Coupled generators and bounds .. autofunction:: sofic.generators.coupled_generators.line_split_seeds .. autofunction:: sofic.generators.coupled_generators.targeted_line_split_seeds .. autofunction:: sofic.generators.generator_bounds.support_type_bound +.. autofunction:: sofic.generators.generator_bounds.one_wide_exact_common_information +.. autoclass:: sofic.generators.generator_bounds.OneWidePartitionResult + :members: .. autofunction:: sofic.generators.generator_bounds.flow_bound .. autofunction:: sofic.generators.generator_bounds.flow_bound_result .. autofunction:: sofic.generators.generator_bounds.rll_flow_bound_certified diff --git a/docs/references.bib b/docs/references.bib index 414df1c..31c03dd 100644 --- a/docs/references.bib +++ b/docs/references.bib @@ -508,13 +508,25 @@ @article{Shalizi1999 @article{Feldman1998b, author = {Feldman, David P. and Crutchfield, James P.}, - title = {Structural Information in Non-Critical Systems}, + title = {Discovering Noncritical Organization: Statistical Mechanical, Information Theoretic, and Computational Views of Patterns in One-Dimensional Spin Systems}, + journal = {Entropy}, + volume = {24}, + number = {9}, + pages = {1282}, + year = {2022}, + doi = {10.3390/e24091282}, + note = {First appeared as Santa Fe Institute Working Paper 98-04-026 (1998)}, +} + +@article{Feldman2003, + author = {Feldman, David P. and Crutchfield, James P.}, + title = {Structural Information in Two-Dimensional Patterns: {E}ntropy Convergence and Excess Entropy}, journal = {Physical Review E}, - volume = {57}, - number = {3}, - pages = {2459--2464}, - year = {1998}, - doi = {10.1103/PhysRevE.57.2459}, + volume = {67}, + number = {5}, + pages = {051104}, + year = {2003}, + doi = {10.1103/PhysRevE.67.051104}, } @article{riechers2017spectral2, @@ -938,18 +950,29 @@ @book{Nasu1995 } @article{Travers2010, - author = {Travers, Nicholas and Crutchfield, James P.}, + author = {Travers, Nicholas F. and Crutchfield, James P.}, title = {Exact Synchronization for Finite-State Sources}, - journal = {Chaos}, - volume = {20}, - number = {3}, - pages = {037115}, - year = {2010}, - doi = {10.1063/1.3485620}, + journal = {Journal of Statistical Physics}, + volume = {145}, + number = {5}, + pages = {1181--1201}, + year = {2011}, + doi = {10.1007/s10955-011-0342-4}, eprint = {1008.4182}, archivePrefix = {arXiv}, } +@article{Travers2011, + author = {Travers, Nicholas F. and Crutchfield, James P.}, + title = {Asymptotic Synchronization for Finite-State Sources}, + journal = {Journal of Statistical Physics}, + volume = {145}, + number = {5}, + pages = {1202--1223}, + year = {2011}, + doi = {10.1007/s10955-011-0349-x}, +} + @article{Cerny1964, author = {{\v{C}}ern{\'y}, J{\'a}n}, title = {Pozn{\'a}mka k homog{\'e}nnym experimentom s kone{\v{c}}n{\'y}mi automatmi}, diff --git a/sofic/generators/alternative_complexity.py b/sofic/generators/alternative_complexity.py index 5cd0a20..72a954e 100644 --- a/sofic/generators/alternative_complexity.py +++ b/sofic/generators/alternative_complexity.py @@ -18,14 +18,14 @@ def structural_information(machine: EpsilonMachine) -> float: """Structural information, i.e. the excess entropy ``E``. - Feldman & Crutchfield :cite:`Feldman1998b` take the excess entropy + Feldman & Crutchfield :cite:`Feldman2003` take the excess entropy :math:`E = I[X_{-\\infty:0} : X_{0:\\infty}] = \\lim_{L\\to\\infty} (H[X_{0:L}] - h_\\mu L)` as the measure of structural information. For an epsilon-machine it equals the forward/reverse causal-state mutual information :math:`E = I[S^+ : S^-]` :cite:`Ellison2009`, which is what is returned. (By contrast the state uncertainty :math:`H[S_L \\mid X_{0:L}]` vanishes as :math:`L \\to \\infty` for every finite-state epsilon-machine - :cite:`Travers2010`; it does not converge to ``E``.) + :cite:`Travers2011`; it does not converge to ``E``.) """ return machine.excess_entropy() diff --git a/sofic/generators/block_entropy.py b/sofic/generators/block_entropy.py index a6288f6..5046ca3 100644 --- a/sofic/generators/block_entropy.py +++ b/sofic/generators/block_entropy.py @@ -517,10 +517,11 @@ def _entropy_rate_estimates(entropies: np.ndarray) -> np.ndarray: def _predictability_gain(block_entropy: np.ndarray, h_mu: float) -> np.ndarray: - """PG(L) = h_mu(L) - h_mu with h_mu(L) = H(L) - H(L-1) (Bialek et al., 2001). + """PG(L) = h_mu(L) - h_mu with h_mu(L) = H(L) - H(L-1). - The predictability gain is the excess of the length-``L`` entropy-rate estimate - over the asymptotic entropy rate, not the second difference of the block entropy. + Bialek et al.'s learning curve and Crutchfield & Feldman's per-symbol redundancy r(L); their + "predictability gain" is the second difference of the block entropy, h_mu(L) - h_mu(L-1). See + :meth:`~sofic.generators.epsilon_machine.EpsilonMachine.predictability_gain`. """ gain = np.full(len(block_entropy), math.nan, dtype=float) if len(block_entropy) > 1: diff --git a/sofic/generators/coupled_generators.py b/sofic/generators/coupled_generators.py index 650674f..742bc40 100644 --- a/sofic/generators/coupled_generators.py +++ b/sofic/generators/coupled_generators.py @@ -608,17 +608,18 @@ def separating_optima( """Distinct optima of the exact common information ``G[S+ : S-]`` found by multistart exact decomposition. Runs :func:`_decompose` (SLSQP with exact constraints) from ``starts`` random points for each number of terms in - ``sizes`` (default ``2 .. min(|S+| |S-|, 8)``, within the Kumar-Li-El Gamal bound :cite:`Kumar2014`), keeps the - solutions within ``atol`` of the best value, removes duplicates (equal sets of terms up to relabeling) and - returns ``(best value, channels)``. The optimum need not be unique, and only some optima may be generator - states; :func:`generator_kernel` decides which. No new start begins after ``deadline`` (a - :func:`time.monotonic` value) once some decomposition has been found. + ``sizes`` (default ``2 .. min(m, 8)``, where ``m`` is the number of cells in the support of the joint: some + optimum has at most ``m`` terms, by Kumar, Li & El Gamal's argument for their bound of ``|S+| |S-|`` + :cite:`Kumar2014` restricted to the support), keeps the solutions within ``atol`` of the best value, removes + duplicates (equal sets of terms up to relabeling) and returns ``(best value, channels)``. The optimum need not + be unique, and only some optima may be generator states; :func:`generator_kernel` decides which. No new start + begins after ``deadline`` (a :func:`time.monotonic` value) once some decomposition has been found. """ problem = _as_problem(bidir) rng = rng or np.random.default_rng() P = _pair_joint(problem) na, nb = P.shape - sizes = sizes or range(2, min(na * nb, 8) + 1) + sizes = sizes or range(2, min(int(np.count_nonzero(P > 1e-12)), 8) + 1) found = [] for k in sizes: for _ in range(starts): diff --git a/sofic/generators/epsilon_machine.py b/sofic/generators/epsilon_machine.py index 2fb1750..32c3a84 100644 --- a/sofic/generators/epsilon_machine.py +++ b/sofic/generators/epsilon_machine.py @@ -449,14 +449,20 @@ def gauge_information(self, max_length: int) -> float: return float(estimates.gauge_information_estimate[max_length]) def predictability_gain(self, max_length: int) -> float: - """Finite-block predictability gain ``PG(L) = h_mu(L) - h_mu`` (Bialek et al., 2001).""" + """Excess ``PG(L) = h_mu(L) - h_mu`` of the length-``L`` entropy-rate estimate over the entropy rate. + + This is the discrete learning curve :math:`\\Lambda(N)` of Bialek, Nemenman & Tishby + :cite:`bialek2001predictability` and the per-symbol redundancy :math:`r(L)` of Crutchfield & Feldman + :cite:`CrutchfieldFeldman2003` (their eq. 35). Crutchfield & Feldman reserve "predictability gain" for the + first difference :math:`\\Delta^2 H(L) = h_\\mu(L) - h_\\mu(L - 1)` (their eq. 36); the method keeps its name. + """ if max_length < 1: raise ValueError("max_length must be at least 1 for predictability gain") estimates = self.block_entropy_estimates(max_length) return float(estimates.predictability_gain_estimate[max_length]) def structural_information(self) -> float: - """Asymptotic structural information (Feldman & Crutchfield, 1998).""" + """Asymptotic structural information (Feldman & Crutchfield, 2003).""" from sofic.generators.alternative_complexity import structural_information return structural_information(self) diff --git a/sofic/generators/generative_search.py b/sofic/generators/generative_search.py index 680351f..df09a03 100644 --- a/sofic/generators/generative_search.py +++ b/sofic/generators/generative_search.py @@ -1055,8 +1055,9 @@ def generative_model_from_bidirectional( """Run the generator-search pipeline on an existing bidirectional machine; see the module docstring. ``global_bound`` (needs PySCIPOpt, ``pip install sofic[global]``) adds the restricted global bound for - generators with at most ``global_bound_states`` states (default :math:`\\min(|S^+|, |S^-|) + 1`), reported as - ``restricted_lower``; see :class:`GenerativeModelResult`. + generators with at most ``global_bound_states`` states, reported as ``restricted_lower``; see + :class:`GenerativeModelResult`. The default, :math:`\\min(|S^+|, |S^-|) + 1`, is a convention, not a bound: + minimal generators can need more states. """ return _bracket_search( bidir, diff --git a/sofic/generators/generator_bounds.py b/sofic/generators/generator_bounds.py index 864dfdc..0620416 100644 --- a/sofic/generators/generator_bounds.py +++ b/sofic/generators/generator_bounds.py @@ -26,6 +26,7 @@ from fractions import Fraction from typing import TYPE_CHECKING +import networkx as nx import numpy as np if TYPE_CHECKING: @@ -308,6 +309,105 @@ def support_type_bound( return res.value, res.types, res.masses or () +@dataclass(frozen=True) +class OneWidePartitionResult: + """Exact common information of a joint whose support has no 2 x 2 rectangle. + + ``value`` is :math:`\\op{G}{X : Y}`; ``blocks`` is an optimal partition of the support with the fewest blocks + (each a tuple of cells ``(x, y)`` in one row or one column, heaviest first); ``by_terms[k]`` is the least + :math:`\\H{W}` over separating variables with at most ``k`` values, from the fewest feasible ``k`` up to + ``len(blocks)``. + """ + + value: float + blocks: tuple[tuple[tuple[int, int], ...], ...] + by_terms: dict[int, float] + + +def _one_wide_component( + P: np.ndarray, cells: list[tuple[int, int]], max_cells: int +) -> dict[int, tuple[float, tuple[tuple[tuple[int, int], ...], ...]]]: + """Least entropy with exactly ``k`` blocks over the row-or-column assignments of one component's cells.""" + m = len(cells) + if m > max_cells: + raise ValueError(f"a component of the support has {m} cells (max_cells={max_cells})") + rows = sorted({a for a, _ in cells}) + cols = sorted({b for _, b in cells}) + to_rows = np.zeros((m, len(rows))) + to_cols = np.zeros((m, len(cols))) + for j, (a, b) in enumerate(cells): + to_rows[j, rows.index(a)] = to_cols[j, cols.index(b)] = P[a, b] + best: dict[int, tuple[float, int]] = {} + bits = np.arange(m) + chunk = 1 << 16 + for start in range(0, 1 << m, chunk): + codes = np.arange(start, min(start + chunk, 1 << m)) + in_row = (codes[:, None] >> bits) & 1 + loads = np.hstack([in_row @ to_rows, (1 - in_row) @ to_cols]) + entropy = -(loads * np.log2(np.where(loads > 0, loads, 1.0))).sum(axis=1) + count = (loads > 0).sum(axis=1) + for k in np.unique(count): + sel = np.flatnonzero(count == k) + i = sel[np.argmin(entropy[sel])] + if entropy[i] < best.get(int(k), (np.inf, 0))[0]: + best[int(k)] = (float(entropy[i]), int(codes[i])) + out = {} + for k, (value, code) in best.items(): + groups: dict[tuple[str, int], list[tuple[int, int]]] = {} + for j, (a, b) in enumerate(cells): + groups.setdefault(("x", a) if code >> j & 1 else ("y", b), []).append((a, b)) + out[k] = (value, tuple(tuple(g) for g in groups.values())) + return out + + +def one_wide_exact_common_information( + P: np.ndarray, *, atol: float = 1e-12, max_cells: int = 24 +) -> OneWidePartitionResult: + r"""Exact :math:`\op{G}{X : Y}` when every rectangle in the support of ``P`` lies in one row or one column. + + Every value of a separating variable has a rectangular support, here part of one row or one column, and every + distribution on such a block is a product. With the blocks fixed, the decompositions are a product of + simplices (each cell's mass split among the blocks covering it), on which the concave :math:`\H{W}` is + minimized at a vertex: a partition of the support into blocks. Merging two blocks of one row (or one column) + lowers the entropy, so some optimal partition sends each cell to its row's block or to its column's block. The + solver enumerates these :math:`2^m` assignments on each connected component of the support (``m`` cells) and + combines the components; the same argument with at most ``k`` blocks gives ``by_terms``. + + Kumar, Li & El Gamal :cite:`Kumar2014` show that some optimal separating variable has at most :math:`|X||Y|` + values; their argument, restricted to the support, gives at most the number of support cells. The partition + solver is not from the literature. Cells with ``P <= atol`` are dropped. Raises ``ValueError`` when the + support contains a 2 x 2 rectangle or a component has more than ``max_cells`` cells. + """ + P = np.asarray(P, dtype=float) + P = P / P.sum() + support = np.asarray(atol < P, dtype=int) + overlap = support @ support.T + np.fill_diagonal(overlap, 0) + if (overlap >= 2).any(): + raise ValueError("the support contains a 2 x 2 rectangle") + graph = nx.Graph() + graph.add_edges_from((("x", int(a)), ("y", int(b)), {"cell": (int(a), int(b))}) for a, b in np.argwhere(support)) + totals: dict[int, tuple[float, tuple[tuple[tuple[int, int], ...], ...]]] = {0: (0.0, ())} + for nodes in nx.connected_components(graph): + cells = [cell for _, _, cell in graph.subgraph(nodes).edges(data="cell")] + component = _one_wide_component(P, cells, max_cells) + merged: dict[int, tuple[float, tuple[tuple[tuple[int, int], ...], ...]]] = {} + for k1, (v1, b1) in totals.items(): + for k2, (v2, b2) in component.items(): + if v1 + v2 < merged.get(k1 + k2, (np.inf, ()))[0]: + merged[k1 + k2] = (v1 + v2, b1 + b2) + totals = merged + value = min(v for v, _ in totals.values()) + k_opt = min(k for k, (v, _) in totals.items() if v <= value + 1e-12) + by_terms: dict[int, float] = {} + running = np.inf + for k in range(min(totals), k_opt + 1): + running = min(running, totals.get(k, (np.inf, ()))[0]) + by_terms[k] = float(running) + blocks = tuple(sorted(totals[k_opt][1], key=lambda b: -sum(P[c] for c in b))) + return OneWidePartitionResult(float(value), blocks, by_terms) + + def _concave_entropy_min( A_ub: np.ndarray, b_ub: np.ndarray, A_eq: np.ndarray, b_eq: np.ndarray, *, tol: float = 1e-7, max_nodes: int = 20000 ) -> float: @@ -477,12 +577,14 @@ def generator_support_bound(bidir: BidirectionalEpsilonMachine) -> float: __all__ = [ "FlowBoundResult", + "OneWidePartitionResult", "SupportTypeBoundResult", "flow_bound", "flow_bound_result", "generator_support_bound", "is_rll_three_state_machine", "maximal_rectangles", + "one_wide_exact_common_information", "rll_flow_bound_certified", "support_exact_cover_bound", "support_type_bound", diff --git a/sofic/generators/global_bound.py b/sofic/generators/global_bound.py index 9fde3a2..3bdf5cc 100644 --- a/sofic/generators/global_bound.py +++ b/sofic/generators/global_bound.py @@ -19,9 +19,13 @@ :math:`\H{\pi}` over them with SCIP's spatial branch and bound :cite:`Achterberg2009,Vigerske2018` through PySCIPOpt :cite:`Maher2016`. Its dual bound therefore bounds the state entropy of every generator with at most ``k`` states from below; it says nothing about larger generators, so it is a lower bound on the generative -complexity :math:`C_g` only once a bound on the number of states of a minimal generator is known (open; every -certified case so far needs at most :math:`|S^+| + 1`). The two-step flows and this restricted use are not from -the literature. +complexity :math:`C_g` only once a bound on the number of states of a minimal generator is known. No general bound +is known, and :math:`\min(|S^+|, |S^-|) + 1` is not one: a Markov chain on six symbols with +:math:`|S^+| = |S^-| = 6` needs 8 states (see +:func:`~sofic.generators.generator_bounds.one_wide_exact_common_information`). When both persistent crypticities +vanish, every separating variable is a generator state, and some optimal one has at most as many values as the +causal-state joint has support cells (the argument of :cite:`Kumar2014`, restricted to the support), so ``k`` equal +to that number suffices. The two-step flows and this restricted use are not from the literature. The bound is numerical, not a certificate: the data are floats, the equations with data on the right-hand side are relaxed to ``|lhs - rhs| <= data_tol`` (which only enlarges the feasible set), and SCIP works to its own diff --git a/sofic/generators/synchronization.py b/sofic/generators/synchronization.py index 2d04c5e..3441d8f 100644 --- a/sofic/generators/synchronization.py +++ b/sofic/generators/synchronization.py @@ -396,7 +396,7 @@ def is_asymptotically_synchronizable_from_graph(graph: TopologicalUnifilarGraph) An epsilon-machine is asymptotically synchronizable iff the observer's state uncertainty vanishes as ``L -> infinity`` for almost every generated sequence (``Pr(WSYN(M)) = 1``) :cite:`Travers2010`. Every finite-state - epsilon-machine has this property, so this returns ``True`` for any + epsilon-machine has this property :cite:`Travers2011`, so this returns ``True`` for any non-empty presentation -- it is theorem-backed rather than computed. """ return bool(graph.states) diff --git a/tests/test_generator_bounds.py b/tests/test_generator_bounds.py index cabd119..2f2029a 100644 --- a/tests/test_generator_bounds.py +++ b/tests/test_generator_bounds.py @@ -4,13 +4,18 @@ import itertools import time +from collections.abc import Iterator from fractions import Fraction import numpy as np -from hypothesis import given, settings +import pytest +from hypothesis import assume, given, settings from hypothesis import strategies as st +from sofic.examples.epsilon_machines import from_symbol_matrices from sofic.generators import generator_bounds as gb +from sofic.generators.coupled_generators import _GeneratorProblem, _pair_joint +from sofic.generators.generative_search import _persistent_criteria def _type_inequalities(joint: dict) -> tuple[list, int]: @@ -71,3 +76,73 @@ def test_support_bound_is_fast_with_many_rectangles() -> None: result = gb.support_type_bound_result(joint) assert time.monotonic() - start < 60 assert result.certified and 0 < result.value <= np.log2(len(cells)) + + +def _set_partitions(items: list) -> Iterator[list[list]]: + if not items: + yield [] + return + first, rest = items[0], items[1:] + for part in _set_partitions(rest): + for i in range(len(part)): + yield [*part[:i], [first, *part[i]], *part[i + 1 :]] + yield [[first], *part] + + +@st.composite +def _one_wide_joints(draw): + cells = draw(st.sets(st.tuples(st.integers(0, 3), st.integers(0, 3)), min_size=1, max_size=7)) + support = np.zeros((4, 4), dtype=int) + for c in cells: + support[c] = 1 + overlap = support @ support.T + np.fill_diagonal(overlap, 0) + assume((overlap < 2).all()) + P = np.zeros((4, 4)) + for c in sorted(cells): + P[c] = draw(st.integers(1, 9)) + return P / P.sum() + + +@settings(max_examples=60, deadline=None) +@given(_one_wide_joints()) +def test_one_wide_partition_matches_brute_force(P) -> None: + cells = [tuple(map(int, c)) for c in np.argwhere(P > 0)] + exact: dict[int, float] = {} + for part in _set_partitions(cells): + if all(len({a for a, _ in block}) == 1 or len({b for _, b in block}) == 1 for block in part): + masses = np.array([sum(P[c] for c in block) for block in part]) + exact[len(part)] = min(exact.get(len(part), np.inf), float(-(masses * np.log2(masses)).sum())) + result = gb.one_wide_exact_common_information(P) + assert result.value == pytest.approx(min(exact.values()), abs=1e-12) + for k, value in result.by_terms.items(): + assert value == pytest.approx(min(v for j, v in exact.items() if j <= k), abs=1e-12) + assert sorted(c for block in result.blocks for c in block) == sorted(cells) + + +def test_one_wide_partition_rejects_rectangles() -> None: + with pytest.raises(ValueError, match="2 x 2 rectangle"): + gb.one_wide_exact_common_information(np.full((2, 2), 0.25)) + + +def _skip_one_chain(): + """Markov chain on Z_6 moving i -> i + 1 or i + 2; the cells (i, i + 1), (i, i + 2) in cycle order repeat + heavy, heavy, light.""" + cells = [(j // 2, (j // 2 + 1 + j % 2) % 6) for j in range(12)] + P = np.zeros((6, 6)) + for j, c in enumerate(cells): + P[c] = 1e-3 if j % 3 == 2 else (1 - 4e-3) / 8 + T = P / P.sum(axis=1, keepdims=True) + mats = {x: np.where(np.arange(6)[None, :] == x, T, 0.0) for x in range(6)} + return from_symbol_matrices(tuple(range(6)), tuple(range(6)), mats) + + +def test_skip_one_chain_needs_more_than_min_plus_one_states() -> None: + # Both persistent crypticities vanish, so C_g = G[S+ : S-], and the support (a 12-cycle) has no 2 x 2 rectangle. + problem = _GeneratorProblem(_skip_one_chain().to_bidirectional()) + assert (problem.n_plus, problem.n_minus) == (6, 6) + assert max(_persistent_criteria(problem)) < 1e-10 + result = gb.one_wide_exact_common_information(_pair_joint(problem)) + assert result.value == pytest.approx(2.0376224, abs=1e-6) + assert len(result.blocks) == 8 + assert result.by_terms[7] == pytest.approx(2.2698054, abs=1e-6)