diff --git a/docs/generators/generative_models.rst b/docs/generators/generative_models.rst index 343a1bf..c96fab9 100644 --- a/docs/generators/generative_models.rst +++ b/docs/generators/generative_models.rst @@ -207,8 +207,10 @@ runs the same search when the bidirectional machine is already known. :func:`~sofic.generators.coverage_bound.mu_hyperplane_cap` (branch and bound over the plane containing the columns of a rank-2 matrix; exact since nonnegative rank two equals rank two :cite:`cohen1993nonnegative`); -* the persistent-crypticity criteria; when both vanish every separating variable - is a generator state and :math:`C_g = \op{G}{S^+ : S^-}`; +* the persistent-crypticity criteria, with the cryptic orders and the block persistent crypticities; when both + criteria vanish (cryptic order at most 1) every separating variable is a generator state, + :math:`C_g = \op{G}{S^+ : S^-}`, and the exact path computes it with at most :math:`K(P)` states + (:doc:`separating_generators`); at cryptic orders 2 and 3 the lookahead generator is a candidate; * the exact-common-information optima (dit, several starts, since the optimum need not be unique and only some optima generate), each polished to exact separation with :func:`~sofic.generators.coupled_generators.polish_separating_channel` @@ -389,8 +391,9 @@ assignments on each connected component of the support and also reports the leas 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. +number of terms :func:`~sofic.generators.coupled_generators.separating_optima` tries, and merges and +null moves bring any decomposition down to :math:`K(P) = \lfloor (|\mathrm{supp}\, P| + \min(|S^+|, |S^-|)) / 2 +\rfloor` terms (:doc:`separating_generators`). 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` @@ -417,9 +420,12 @@ generator with at most ``k`` states and says nothing about larger ones. It is th 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; +crypticities vanish (cryptic order at most 1), ``k`` equal to :math:`K(P)` suffices +(:doc:`separating_generators`). 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, and its presolve and optimization-based bound tightening can go wrong +(``presolve=False, obbt=False`` gives a second opinion; see :doc:`separating_generators`). +:func:`~sofic.generators.global_bound.separating_global_bound` is the static version, over separating +decompositions with ``k`` terms. 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 :math:`T^{(0)} = \begin{pmatrix} p & 0 \\ q & 0 \end{pmatrix}` and @@ -429,11 +435,13 @@ 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`, a convention, not a bound). +``global_bound_states`` states (default :math:`K(P)`, lowered until the model has at most 2,000 SCIP +variables; a bound on the states of a minimal generator only at cryptic order at most 1). 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 +skipped above 2,000 SCIP variables. The value goes to ``restricted_lower`` and ``restricted_states``. +It enters ``lower`` (as a numerical bound) only at cryptic order at most 1 with :math:`K(P)` states; +otherwise ``certified`` is unchanged. The polished solution is offered as a candidate. The two-step flows and this restricted use are not from the literature. API @@ -461,6 +469,8 @@ Coupled generators and bounds .. autofunction:: sofic.generators.hmm_search.coupled_seed_from_hmm .. autofunction:: sofic.generators.global_bound.generator_global_bound .. autoclass:: sofic.generators.global_bound.GlobalBoundResult +.. autofunction:: sofic.generators.global_bound.separating_global_bound +.. autoclass:: sofic.generators.global_bound.SeparatingBoundResult .. autoclass:: sofic.generators.generative_search.GenerativeModelResult :members: certified, gap, g_optima_generate .. autofunction:: sofic.generators.coverage_bound.coverage_entropy_lower diff --git a/docs/generators/generators.rst b/docs/generators/generators.rst index 9568e07..81ec64f 100644 --- a/docs/generators/generators.rst +++ b/docs/generators/generators.rst @@ -48,6 +48,7 @@ Computational mechanics predictive_rate_distortion symbolic_hmm generative_models + separating_generators canonical_generators directional_flow alternative_complexity diff --git a/docs/generators/separating_generators.rst b/docs/generators/separating_generators.rst new file mode 100644 index 0000000..4af4801 --- /dev/null +++ b/docs/generators/separating_generators.rst @@ -0,0 +1,137 @@ +.. separating_generators.rst +.. py:module:: sofic.generators.separating_generators + +************************************** +Cryptic Order and Exact Generators +************************************** + +Every generator state separates the forward and reverse causal states, so +:math:`C_g \ge \op{G}{S^+ : S^-}` :cite:`LohrAy2009`, the exact common information :cite:`Kumar2014` of the +causal-state joint :math:`P`. :mod:`sofic.generators.separating_generators` computes :math:`C_g` exactly when the +cryptic order is at most 1, and bounds it above by lookahead generators when the cryptic order is larger +(:doc:`generative_models` describes the rest of the search). + +Cryptic order at most 1 +======================= + +The persistent crypticity :math:`p.\chi^+ = \H{S^+_1 \mid S^-_0, X_0}` equals :math:`\H{S^+_1 \mid X_{0:}}`, +because the reverse causal state :math:`S^-_0` shields the future from the past. That is +:math:`\chi^+ - \H{S^+_0 \mid X_0, S^+_1}`, Theorem 1 of Mahoney, Ellison and Crutchfield :cite:`Mahoney2009` at +:math:`k = 1`, so :math:`p.\chi^+` vanishes exactly when the cryptic order :math:`\kappa^+` is at most 1. The +forward and reverse cryptic orders are equal, the cryptic-order counterpart of the time symmetry of the Markov +order :cite:`Ellison2011`. When :math:`\chi^+ = 0` the past depends on the future only through :math:`S^+`, so +:math:`S^-` is a relabeling of :math:`S^+` and :math:`\chi^- = 0`. For orders of at least 1, the two persistent +crypticities of each block process (below) vanish together, so :math:`\max(\kappa^+, 1) = \max(\kappa^-, 1)`. Both +persistent crypticities therefore vanish exactly when the cryptic order is at most 1, and then every separating +variable of :math:`P` is a generator state and :math:`C_g = \op{G}{S^+ : S^-}`. + +:func:`theorem_generator` writes the generator down. For a separating decomposition +:math:`P = \sum_w \pi_w Q_w R_w^\top` let :math:`c(w \mid a, b) = \pi_w Q_w(a) R_w(b) / P(a, b)`, and let +:math:`\phi(b, x) = S^+_1` be the forward state after :math:`X_0 = x` from :math:`S^-_0 = b`, a function because +:math:`p.\chi^+ = 0`. The kernel + +.. math:: + + K(x, v \mid w) = \sum_{b, b'} R_w(b) \Pr(X_0 = x, S^-_1 = b' \mid S^-_0 = b)\, c(v \mid \phi(b, x), b') + +satisfies the coupled generator equations, and its word process is the source's. + +The support bound +----------------- + +A decomposition :math:`P = \sum_w A_w R_w^\top`, with row masses :math:`A_w = \pi_w Q_w` and column distributions +:math:`R_w`, has two moves that keep it exact and do not raise the entropy of the weights +(:func:`reduce_decomposition`). Two terms with proportional row masses or equal column factors merge. When the +column factors of the terms covering a row are linearly dependent, mass moves along the dependency until one of +those cells empties, at whichever end has less entropy (the entropy is concave along the move). At the end the +terms covering each row have independent column factors, and each row has at most one term supported on that row +alone, so at most + +.. math:: + + K(P) = \left\lfloor \frac{|\mathrm{supp}\, P| + \min(|S^+|, |S^-|)}{2} \right\rfloor + +terms remain (:func:`support_bound_states`; the moves run on the side with fewer rows or columns). Kumar, Li and +El Gamal :cite:`Kumar2014` bound the number of values by :math:`|S^+||S^-|` and :math:`2^{\min(|S^+|, |S^-|)} - 1`. +So at cryptic order at most 1 some minimal generator has at most :math:`K(P)` states. + +Computing the exact common information +-------------------------------------- + +:func:`separating_decomposition` works on each connected component of the support. A component in one row or +column is a single term. A component without :math:`2 \times 2` rectangles is solved exactly by +:func:`~sofic.generators.generator_bounds.one_wide_exact_common_information`. Otherwise SCIP minimizes the entropy +over decompositions with the component's :math:`K` terms +(:func:`~sofic.generators.global_bound.separating_global_bound`). The components combine as +:math:`\H{C} + \sum_c \Pr(c)\, G_c`, since the component label :math:`C` is a common function of both sides. + +SCIP needs a second opinion. On Kumar, Li and El Gamal's Example 2, the erasure joint +:math:`\begin{pmatrix} 0.05 & 0 & 0.45 \\ 0 & 0.05 & 0.45 \end{pmatrix}`, presolve declares the model with +:math:`k = 2` infeasible, though :math:`W = S^+` is feasible. On the :math:`3 \times 3` joint with five cells in +``tests/test_separating_generators.py``, optimization-based bound tightening (OBBT) at :math:`k = 3` cuts off the +optimum and SCIP reports "optimal" at :math:`1.447803`, above a feasible :math:`1.343763`. With presolve and OBBT +off (``presolve=False, obbt=False``) both come out right. Each component therefore runs both settings, an +"infeasible" counts as no bound (a decomposition with :math:`K` terms always exists), and the smaller dual bound is +the component's lower bound. SCIP's primal solutions satisfy the constraints only to about :math:`10^{-6}`, which +can put their entropy below the true optimum, so each is reduced, projected onto exact decompositions by least +squares on its support, and descended, alongside multistart descents; the best exact decomposition is kept. +Without PySCIPOpt the multistart descents alone give the upper bound and such components contribute 0 to the +lower bound. + +In the pipeline +--------------- + +:func:`~sofic.generators.generative_search.generative_model` logs the cryptic orders and the block persistent +crypticities in its ``persistent criteria`` stage. When both persistent crypticities vanish it runs the +``exact path`` stage after the ε-machine candidates: :func:`separating_decomposition`, :func:`reduce_decomposition` +and :func:`theorem_generator`, offering the generator as a candidate. Its lower bound enters ``lower``. It is +labelled ``separating global bound (numerical)``, with ``lower_certified`` False, whenever SCIP solved a +component; the certified bounds that run later can replace it. The restricted global bound +(``global_bound=True``) defaults to :math:`K(P)` states, lowered to fit its variable cap, and at cryptic order at +most 1 with :math:`K(P)` states it enters ``lower`` too. + +On the 510 processes of cryptic order at most 1 in a survey dataset of 808 two- and three-state ε-machines on two +and three symbols, the exact path reproduced every certified value to :math:`10^{-6}` bits, with at most +:math:`K(P)` states, generator residuals below :math:`3 \times 10^{-11}` and word-process errors below +:math:`2 \times 10^{-11}`. Of the 1,140 components, 970 were single rows or columns, 115 rectangle-free and 55 went +to SCIP, where the numerical lower bound came within :math:`10^{-5}` bits. + +Block processes and lookahead generators +======================================== + +A generator whose state determines its next :math:`L - 1` symbols is the same thing as a generator of the +sliding-block process :math:`Y_t = X_{t:t+L}`. The forward causal states of :math:`Y_L` are pairs +:math:`(X_{t:t+L-1}, S^+_{t+L-1})`, and its persistent crypticity is :math:`\H{S^+_L \mid X_{0:}}`. That vanishes +exactly when :math:`L` reaches the cryptic order, which Mahoney et al. define as the least such :math:`L` +:cite:`Mahoney2011`. At :math:`L = \kappa` the construction above applies to :math:`Y_L`, and keeping the first +symbol of each emission gives a generator of the source, so + +.. math:: + + C_g \le \H{X_{0:L-1}} + \sum_u \Pr(u)\, \op{G}{S^+_{L-1} : S^-_0 \mid X_{0:L-1} = u}. + +:func:`lookahead_generator` builds :math:`Y_L`'s ε-machine, runs :func:`separating_decomposition` and +:func:`theorem_generator` on it, projects, and checks the word process against the source exactly. On the +:math:`(2, \infty)` process (``restricted_golden_mean(2)``, cryptic order 2) it gives :math:`3/2 = C_g` with 3 +states. On the butterfly process (cryptic order 2) it gives :math:`3.1219`, with 9 states, above +:math:`C_g = C_\mu = \log_2 5 = 2.3219` (the support-type bound certifies the ε-machine): the construction can +lose to the ε-machine. On the survey dataset the lookahead value equals the certified :math:`C_g` on 32 of the 49 +closed processes of cryptic order 2 and on none of the closed processes of cryptic order 3, whose minimal +generators do not determine their next two symbols. It takes at most about a second there, and the pipeline offers it as a +candidate at cryptic orders 2 and 3; with a 60 s budget it lowered the pipeline's upper bound on 4 of 81 such +processes and tied on 45. + +The support bound, the reduction, the kernel of :func:`theorem_generator` and the lookahead construction are not +from the literature, and none of :cite:`Mahoney2009,Mahoney2011,Crutchfield2009,Ellison2011` states the equality +of the cryptic orders. + +API +=== + +.. autofunction:: support_bound_states +.. autofunction:: reduce_decomposition +.. autofunction:: separating_decomposition +.. autoclass:: SeparatingDecomposition +.. autofunction:: theorem_generator +.. autofunction:: lookahead_generator +.. autoclass:: LookaheadGenerator diff --git a/docs/references.bib b/docs/references.bib index 31c03dd..74fe502 100644 --- a/docs/references.bib +++ b/docs/references.bib @@ -419,6 +419,18 @@ @article{Mahoney2011 eprint = {1108.1510}, } +@article{Mahoney2009, + author = {Mahoney, John R. and Ellison, Christopher J. and Crutchfield, James P.}, + title = {Information Accessibility and Cryptic Processes}, + journal = {Journal of Physics A: Mathematical and Theoretical}, + volume = {42}, + number = {36}, + pages = {362002}, + year = {2009}, + doi = {10.1088/1751-8113/42/36/362002}, + eprint = {0905.4787}, +} + @article{James2013, author = {James, Ryan G. and Burke, John R. and Crutchfield, James P.}, title = {Chaos Forgets and Remembers: Information Anatomy of Complex Processes}, diff --git a/scripts/benchmark_generative_robustness.py b/scripts/benchmark_generative_robustness.py index fd9822e..51fc010 100644 --- a/scripts/benchmark_generative_robustness.py +++ b/scripts/benchmark_generative_robustness.py @@ -17,6 +17,7 @@ from sofic.examples import golden_mean, golden_mean_bidirectional from sofic.examples.epsilon_machines import from_symbol_matrices +from sofic.examples.processes import rip, stretched_gm from sofic.generators.bidirectional_epsilon_machine import BidirectionalEpsilonMachine from sofic.generators.generative_search import generative_model, generative_model_from_bidirectional @@ -25,6 +26,23 @@ def _h(p: float) -> float: return float(-(p * np.log2(p) + (1 - p) * np.log2(1 - p))) +def _entropy(p: list[float]) -> float: + p = np.asarray(p, dtype=float) + return float(-(p * np.log2(p)).sum()) + + +def _kappa1_scip() -> object: + """Cryptic order 1 with a full-support 2 x 2 causal-state joint: the exact path solves it with SCIP.""" + return from_symbol_matrices( + (0, 1), + (0, 1), + { + 0: np.array([[0.8620162340426342, 0.0], [0.26088622236842307, 0.0]]), + 1: np.array([[0.0, 0.1379837659573659], [0.0, 0.7391137776315769]]), + }, + ) + + def _rll() -> BidirectionalEpsilonMachine: machine = from_symbol_matrices( ("A", "B", "C"), @@ -107,8 +125,13 @@ def main() -> None: cases = [ Case("golden_mean_forward", golden_mean(0.5), gm_target, True), Case("golden_mean_bidir", golden_mean_bidirectional(0.5), gm_target, True), - Case("rll", _rll(), 1.5, False), + Case("rll", _rll(), 1.5, True), Case("interleaved_0.1", _interleaved(0.1), 2 * _h(4 / 9), None), + # cryptic order at most 1: certified by the exact path (separating_generators) + Case("rip", rip(), _entropy([0.4, 0.2, 0.4]), True), + Case("stretched_gm_2", stretched_gm(2), 1.5, True), + Case("stretched_gm_3", stretched_gm(3), _entropy([0.4, 0.2, 0.2, 0.2]), True), + Case("kappa1_scip", _kappa1_scip(), 0.7970965391094695, True), ] print(f"{'case':<22} {'time':>6} {'upper':>8} {'lower':>8} {'gap':>8} {'cert':>5} {'source':<40}") diff --git a/sofic/generators/generative_search.py b/sofic/generators/generative_search.py index df09a03..f8f5a35 100644 --- a/sofic/generators/generative_search.py +++ b/sofic/generators/generative_search.py @@ -11,8 +11,16 @@ full supports, where the support-type bound vanishes; and coverage with caps on the heaviest generator states from the generator equations (:mod:`~sofic.generators.generator_caps`, ``generator_caps`` explicit states), which can exceed :math:`\op{G}{S^+ : S^-}`. -2. *Persistent crypticity.* When both :math:`p.\chi^\pm` vanish on the bidirectional edge, - :math:`C_g = \op{G}{S^+ : S^-}`. +2. *Persistent crypticity.* Logs the cryptic orders :math:`\kappa^\pm` and the persistent crypticities of the + block processes, :math:`\H{S^+_L \mid X_{0:}}` and :math:`\H{S^-_0 \mid X_{:L}}`, which vanish exactly from + :math:`L = \kappa`. When both :math:`p.\chi^\pm` vanish on the bidirectional edge (cryptic order at most 1), + :math:`C_g = \op{G}{S^+ : S^-}` and the *exact path* runs + (:mod:`~sofic.generators.separating_generators`): a least-entropy separating decomposition with at most + :math:`K(P)` terms, exact on rectangle-free components and from SCIP otherwise, whose generator is written + down directly; SCIP's dual bound enters ``lower`` as a numerical bound (``lower_certified`` False). Without + PySCIPOpt, components with rectangles fall back to multistart descents and the lower bounds below. For + cryptic order 2 or 3 the lookahead generator + (:func:`~sofic.generators.separating_generators.lookahead_generator`) is offered as a candidate. 3. *Exact optima + kernel LP.* Enumerate :math:`\op{G}{S^+ : S^-}` optima; optional :func:`~sofic.generators.coupled_generators.bilevel_search` when none generate; then an **entropy-ordered sweep** over all multistart separating decompositions (not only @@ -29,9 +37,11 @@ (7 without a budget, where it is capped at 2,000 boxes). 6. *Restricted global bound* (opt-in, ``global_bound``; runs after the belief-free search). SCIP's lower bound on the state entropy of generators with at most ``global_bound_states`` states - (:func:`~sofic.generators.global_bound.generator_global_bound`) is reported as ``restricted_lower``. It does - not enter ``lower``: no bound on the number of states of a minimal generator is known. SCIP's solution, - polished by the belief-free search, is offered as a candidate. + (:func:`~sofic.generators.global_bound.generator_global_bound`; default :math:`K(P)`, lowered to fit the + variable cap) is reported as ``restricted_lower``. When the cryptic order is at most 1 and the bound runs at + :math:`K(P)` states, a minimal generator has that many states, so it enters ``lower`` as well (numerical). + Otherwise it does not: no bound on the number of states of a minimal generator is known when :math:`p.\chi` + is positive. SCIP's solution, polished by the belief-free search, is offered as a candidate. Every candidate is word-verified. ``certified`` reports when ``lower`` meets ``upper``. :func:`minimal_wyner_model` runs the same stages ranked by :math:`\I{W : S^+, S^-}`; the functional @@ -40,6 +50,7 @@ from __future__ import annotations +import math import time import warnings from collections.abc import Sequence @@ -79,6 +90,14 @@ support_type_bound, ) from sofic.generators.hmm_search import coupled_seed_from_hmm, hmm_generator_search +from sofic.generators.separating_generators import ( + _block_persistent_crypticities, + lookahead_generator, + reduce_decomposition, + separating_decomposition, + support_bound_states, + theorem_generator, +) _MAX_RECTANGLES = 7 _FLOW_THRESHOLDS = ((0.6,), (0.55, 0.65)) @@ -106,6 +125,12 @@ _GLOBAL_BOUND_SECONDS = 120.0 # SCIP solution states lighter than this are dropped before the belief-free polish. _GLOBAL_BOUND_MIN_WEIGHT = 1e-6 +# Seconds per SCIP run of the exact path (two settings per component with rectangles) when there is no budget. +_EXACT_PATH_SECONDS = 60.0 +# The lookahead generator runs for cryptic orders 2 .. this, on block machines with at most this many states +# (|S+| |A|^(kappa - 1) bounds them); it took at most 1.3 s on the 3-state archive. +_LOOKAHEAD_MAX_KAPPA = 3 +_LOOKAHEAD_MAX_STATES = 64 def _entropy(p: np.ndarray) -> float: @@ -141,7 +166,8 @@ class GenerativeModelResult: ``restricted_lower`` (set by the opt-in ``global_bound`` stage) bounds the state entropy of generators with at most ``restricted_states`` states only (:func:`~sofic.generators.global_bound.generator_global_bound`). It is - numerical, and it is not part of ``lower`` or ``certified``: a minimal generator might have more states. + numerical, and it is not part of ``lower`` or ``certified``, since a minimal generator might have more + states, except when the cryptic order is at most 1 and ``restricted_states`` is at least :math:`K(P)`. """ model: CoupledGenerativeModel @@ -280,6 +306,14 @@ def _wyner_information(problem: _GeneratorProblem, seed: tuple[np.ndarray, ...]) return max(0.0, _entropy(problem.p_pair) - h_given_w) +def _cryptic_orders(bidir: BidirectionalEpsilonMachine) -> tuple[int | float, int | float] | None: + """``(kappa+, kappa-)`` from the forward and reverse ε-machines, or ``None`` if either fails.""" + try: + return bidir.forward_machine.cryptic_order(), bidir.reverse_machine.cryptic_order() + except Exception: # noqa: BLE001 - only logged + return None + + def _theorem_applies(problem: _GeneratorProblem, *, atol: float = 1e-10) -> bool: f_crit, r_crit = _persistent_criteria(problem) return f_crit < atol and r_crit < atol @@ -565,7 +599,18 @@ def share(fraction: float) -> float | None: f_crit, r_crit = _persistent_criteria(problem) theorem = f_crit < 1e-10 and r_crit < 1e-10 - log.append({"stage": "persistent criteria", "value": (f_crit, r_crit), "theorem applies": theorem}) + kappa = _cryptic_orders(bidir) + log.append( + { + "stage": "persistent criteria", + "value": (f_crit, r_crit), + "theorem applies": theorem, + "cryptic orders": kappa, + "block persistent crypticities": _block_persistent_crypticities(problem), + } + ) + P_joint = np.einsum("p,pa,pb->ab", lifted.p, lifted.plus, lifted.minus) + K_P = support_bound_states(P_joint, tol=1e-12) # ---- upper search ------------------------------------------------------------------------------- candidates: list[tuple[float, str, tuple[np.ndarray, ...]]] = [] @@ -618,6 +663,66 @@ def maybe_return_early() -> GenerativeModelResult | None: if early is not None and early.certified: return _finalize_result(early) + if theorem and not wyner and "exact" in stages and not out_of_time("exact path"): + stage_deadline = share(0.3) + seconds = _EXACT_PATH_SECONDS if stage_deadline is None else 0.5 * (stage_deadline - time.monotonic()) + try: + dec = separating_decomposition(P_joint, time_limit=max(seconds, 1.0), rng=rng) + except RuntimeError as exc: + log.append({"stage": "exact path", "error": str(exc)}) + else: + A, R, _ = reduce_decomposition(P_joint, dec.pi[:, None] * dec.Q, dec.R) + pi = A.sum(axis=1) + seed = theorem_generator(problem, pi, A / pi[:, None], R) + log.append( + { + "stage": "exact path", + "value": dec.value, + "lower": dec.lower, + "exact": dec.exact, + "states": len(pi), + "support bound states": K_P, + "components": [part["method"] for part in dec.components], + } + ) + offer("theorem generator (cryptic order at most 1)", seed) + if dec.lower > lower + 1e-9: + lower = dec.lower + lower_source = "exact separating decomposition" if dec.exact else "separating global bound (numerical)" + lower_certified = dec.exact + early = maybe_return_early() + if early is not None and early.certified: + return _finalize_result(early) + + kappa_plus = kappa[0] if kappa is not None else math.inf + if ( + not wyner + and "exact" in stages + and 2 <= kappa_plus <= _LOOKAHEAD_MAX_KAPPA + and problem.n_plus * problem.n_sym ** (int(kappa_plus) - 1) <= _LOOKAHEAD_MAX_STATES + and not out_of_time("lookahead generator") + ): + stage_deadline = share(0.2) + seconds = _EXACT_PATH_SECONDS if stage_deadline is None else 0.5 * (stage_deadline - time.monotonic()) + try: + look = lookahead_generator(reference, int(kappa_plus), time_limit=max(seconds, 1.0), rng=rng) + except (StochasticValidationError, ValueError, RuntimeError) as exc: + log.append({"stage": "lookahead generator", "error": str(exc)}) + else: + log.append( + { + "stage": "lookahead generator", + "L": look.L, + "value": look.value, + "states": look.states, + "word error": look.word_error, + } + ) + index = {x: i for i, x in enumerate(look.symbols)} + k = look.kernel.shape[0] + mats = [look.kernel[:, index[x], :] if x in index else np.zeros((k, k)) for x in problem.symbols] + offer(f"lookahead generator L={look.L}", coupled_seed_from_hmm(problem, mats)) + if "exact" in stages and not out_of_time("exact common information"): best, optima = separating_optima(problem, starts=exact_starts, deadline=share(0.25), rng=rng) if np.isfinite(best): @@ -922,7 +1027,10 @@ def maybe_return_early() -> GenerativeModelResult | None: if global_bound and not wyner and not out_of_time("restricted global bound"): from sofic.generators.global_bound import _model_size, generator_global_bound - k = global_bound_states if global_bound_states is not None else min(problem.n_plus, problem.n_minus) + 1 + k = global_bound_states if global_bound_states is not None else K_P + if global_bound_states is None: + while k > 2 and _model_size(problem, k) > _GLOBAL_BOUND_MAX_VARS: + k -= 1 size = _model_size(problem, k) stage_deadline = share(0.5) limit = min((c[0] for c in candidates), default=None) @@ -948,6 +1056,12 @@ def maybe_return_early() -> GenerativeModelResult | None: "seconds": gb.seconds, } ) + if theorem and k >= K_P and gb.lower > lower + 1e-9: + lower, lower_source, lower_certified = ( + gb.lower, + "restricted global bound at K(P) (numerical)", + False, + ) if gb.seed is not None: pi, _, _, K = gb.seed keep = np.flatnonzero(pi > _GLOBAL_BOUND_MIN_WEIGHT) @@ -1194,8 +1308,10 @@ def generative_model( 1. Build a bidirectional ε-machine (preflight / optional retry ladder). 2. Certified lower bounds and persistent-crypticity test on the edge. - 3. When :math:`p.\\chi^+ \\approx p.\\chi^- \\approx 0` and some :math:`\\op{G}{S^+ : S^-}` optimum - passes the generator kernel, return that lifted / exact-CI generator (theorem path). + 3. When :math:`p.\\chi^+ \\approx p.\\chi^- \\approx 0` (cryptic order at most 1), the exact path writes down + the generator of a least-entropy separating decomposition with at most :math:`K(P)` terms + (:mod:`~sofic.generators.separating_generators`), and the search returns once some + :math:`\\op{G}{S^+ : S^-}` optimum generates (theorem path). 4. Otherwise memory lifts, lifted channels on small joints, then :func:`~sofic.generators.universal_optimizer.universal_generative_optimizer` (full coupled equations). diff --git a/sofic/generators/global_bound.py b/sofic/generators/global_bound.py index 3bdf5cc..3479619 100644 --- a/sofic/generators/global_bound.py +++ b/sofic/generators/global_bound.py @@ -23,20 +23,35 @@ 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. +vanish (cryptic order at most 1), every separating variable is a generator state, and some optimal one has at most +:math:`K(P) = \lfloor (|\mathrm{supp}\, P| + \min(|S^+|, |S^-|)) / 2 \rfloor` values +(:func:`~sofic.generators.separating_generators.support_bound_states`; Kumar, Li and El Gamal's argument +:cite:`Kumar2014`, restricted to the support, gives the support size), so ``k = K(P)`` suffices. The two-step flows, +the support bound 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 feasibility tolerances. PySCIPOpt is an optional dependency (``pip install sofic[global]``). + +:func:`separating_global_bound` is the static counterpart: the least :math:`\H{W}` over separating variables of a +joint with at most ``k`` values, which at ``k`` equal to +:func:`~sofic.generators.separating_generators.support_bound_states` is :math:`\op{G}{X : Y}` itself. + +SCIP settings matter on both models. Its presolve can declare a feasible model infeasible when every feasible +point ties the sorted weights (Kumar, Li and El Gamal's Example 2 :cite:`Kumar2014` at ``k = 2``, whose only +decomposition is :math:`W = X` at weights :math:`(1/2, 1/2)`), and its optimization-based bound tightening can cut +off the optimum (a 3 x 3 joint with 5 support cells, where ``k = 3`` returns "optimal" 1.447803 while a feasible +3-block partition has 1.343763; see ``tests/test_separating_generators.py``). ``presolve=False, obbt=False`` is the +second opinion for a decisive "infeasible" or "optimal". ``presolve=False`` also turns off symmetry handling: SCIP +still computes the symmetry group when presolving ends, and on the unreduced model of the (3, inf) run-length-limited +process at ``k = 7`` that computation ran for over two hours without checking the time limit. """ from __future__ import annotations import math import time -from collections.abc import Sequence +from collections.abc import Mapping, Sequence from dataclasses import dataclass from typing import Any @@ -45,7 +60,7 @@ from sofic.generators.bidirectional_epsilon_machine import BidirectionalEpsilonMachine from sofic.generators.coupled_generators import _GeneratorProblem -__all__ = ["GlobalBoundResult", "generator_global_bound"] +__all__ = ["GlobalBoundResult", "SeparatingBoundResult", "generator_global_bound", "separating_global_bound"] @dataclass(frozen=True) @@ -74,6 +89,28 @@ class GlobalBoundResult: two_step: bool +@dataclass(frozen=True) +class SeparatingBoundResult: + """Outcome of :func:`separating_global_bound`. + + ``lower`` bounds :math:`\\H{W}` over separating variables with at most ``k`` values: the SCIP dual bound minus + ``slack``, ``objective_limit - slack`` when SCIP proves nothing lies below the limit, and ``inf`` when no + decomposition with ``k`` terms exists. ``factors`` is SCIP's best solution ``(pi, Q, R)``, feasible only to + SCIP's tolerances; :func:`~sofic.generators.separating_generators.separating_decomposition` polishes it into + an exact decomposition. + """ + + k: int + status: str + lower: float + dual_bound: float + slack: float + primal: float | None + factors: tuple[np.ndarray, np.ndarray, np.ndarray] | None + nodes: int + seconds: float + + def _pyscipopt() -> Any: try: import pyscipopt @@ -84,6 +121,120 @@ def _pyscipopt() -> Any: return pyscipopt +def _configure(m: Any, scip: Any, presolve: bool, obbt: bool, params: Mapping[str, Any] | None) -> None: + if not presolve: + m.setPresolve(scip.SCIP_PARAMSETTING.OFF) + m.setParam("misc/usesymmetry", 0) + if not obbt: + m.setParam("propagating/obbt/freq", -1) + for key, value in (params or {}).items(): + m.setParam(key, value) + + +def _bounds(m: Any, status: str, objective_limit: float | None, slack: float) -> tuple[float, float]: + dual = float(m.getDualbound()) + dual = math.inf if dual >= m.infinity() else -math.inf if dual <= -m.infinity() else dual + if status == "infeasible": + lower = math.inf if objective_limit is None else float(objective_limit) - slack + else: + lower = (dual if objective_limit is None else min(dual, float(objective_limit))) - slack + return float(lower), dual + + +def separating_global_bound( + P: np.ndarray, + k: int, + *, + objective_limit: float | None = None, + time_limit: float | None = None, + pi_min: float = 1e-7, + presolve: bool = True, + obbt: bool = True, + params: Mapping[str, Any] | None = None, +) -> SeparatingBoundResult: + r"""Least :math:`\H{W}` over separating variables of the joint ``P`` with at most ``k`` values, by SCIP. + + A separating variable is a decomposition :math:`P = \sum_w \pi_w Q_w R_w^\top` (rows :math:`X`, columns + :math:`Y`); its entropy is minimized with SCIP's spatial branch and bound :cite:`Achterberg2009,Vigerske2018`, + the weights sorted and each entropy term evaluated at :math:`\max(\pi_w, \text{pi\_min})` (``slack`` corrects + for that), as in :func:`generator_global_bound`. At ``k`` equal to + :func:`~sofic.generators.separating_generators.support_bound_states` some optimal separating variable is + covered, so ``lower`` bounds the exact common information :math:`\op{G}{X : Y}` itself (Kumar, Li and El + Gamal's cardinality bound :cite:`Kumar2014` is :math:`|X||Y|`). ``presolve``, ``obbt`` and ``params`` set SCIP + as described in the module docstring. Numerical, not a certificate. Requires PySCIPOpt. + """ + scip = _pyscipopt() + start = time.monotonic() + P = np.asarray(P, dtype=float) + P = P / P.sum() + na, nb = P.shape + pr, pc = P.sum(axis=1), P.sum(axis=0) + W, A, B = range(k), range(na), range(nb) + quicksum = scip.quicksum + m = scip.Model() + m.hideOutput() + _configure(m, scip, presolve, obbt, params) + p = {w: m.addVar(lb=0, ub=1) for w in W} + s = {w: m.addVar(lb=pi_min, ub=1) for w in W} + e = {w: m.addVar(lb=0, ub=1 / (math.e * math.log(2)) + 1e-9) for w in W} + Q = {(w, a): m.addVar(lb=0, ub=1) for w in W for a in A} + R = {(w, b): m.addVar(lb=0, ub=1) for w in W for b in B} + Y = {(w, a): m.addVar(lb=0, ub=float(pr[a])) for w in W for a in A} + Z = {(w, b): m.addVar(lb=0, ub=float(pc[b])) for w in W for b in B} + m.addCons(quicksum(p.values()) == 1) + for w in W: + m.addCons(s[w] >= p[w]) + m.addCons(s[w] <= p[w] + pi_min) + m.addCons(e[w] >= -s[w] * scip.log(s[w]) / math.log(2)) + m.addCons(quicksum(Q[w, a] for a in A) == 1) + m.addCons(quicksum(R[w, b] for b in B) == 1) + m.addCons(quicksum(Y[w, a] for a in A) == p[w]) + m.addCons(quicksum(Z[w, b] for b in B) == p[w]) + for a in A: + m.addCons(Y[w, a] == p[w] * Q[w, a]) + for b in B: + m.addCons(Z[w, b] == p[w] * R[w, b]) + if w + 1 < k: + m.addCons(p[w] >= p[w + 1]) + for a in A: + m.addCons(quicksum(Y[w, a] for w in W) == float(pr[a])) + for b in B: + m.addCons(quicksum(Z[w, b] for w in W) == float(pc[b])) + for a in A: + for b in B: + m.addCons(quicksum(Y[w, a] * R[w, b] for w in W) == float(P[a, b])) + m.addCons(quicksum(Q[w, a] * Z[w, b] for w in W) == float(P[a, b])) + m.setObjective(quicksum(e.values()), "minimize") + if objective_limit is not None: + m.setObjlimit(float(objective_limit)) + if time_limit is not None: + m.setParam("limits/time", max(1.0, float(time_limit))) + m.optimize() + status = str(m.getStatus()) + slack = k * pi_min * math.log2(1 / pi_min) + lower, dual = _bounds(m, status, objective_limit, slack) + primal, factors = None, None + if m.getNSols() > 0: + primal = float(m.getPrimalbound()) + sol = m.getBestSol() + factors = ( + np.clip([m.getSolVal(sol, p[w]) for w in W], 0, None), + np.clip([[m.getSolVal(sol, Q[w, a]) for a in A] for w in W], 0, None), + np.clip([[m.getSolVal(sol, R[w, b]) for b in B] for w in W], 0, None), + ) + return SeparatingBoundResult( + k=k, + status=status, + lower=lower, + dual_bound=dual, + slack=slack, + primal=primal, + factors=factors, + nodes=int(m.getNNodes()), + seconds=time.monotonic() - start, + ) + + def _two_step_law(problem: _GeneratorProblem) -> np.ndarray | None: """``Pe2[x, y, a, b] = Pr(S+_0 = a, X_0 X_1 = x y, S-_2 = b)`` from the bidirectional edge chain, if known.""" lifted = problem.lifted @@ -118,6 +269,9 @@ def generator_global_bound( time_limit: float | None = None, data_tol: float = 1e-7, pi_min: float = 1e-7, + presolve: bool = True, + obbt: bool = True, + params: Mapping[str, Any] | None = None, ) -> GlobalBoundResult: r"""Lower bound on the state entropy of generators with at most ``k`` states, by SCIP global optimization. @@ -133,7 +287,9 @@ def generator_global_bound( then reports ``"infeasible"``, no generator with at most ``k`` states has entropy below ``objective_limit - slack``. ``time_limit`` (seconds) stops SCIP early; the dual bound reached is still valid. The result is numerical, not a certificate, and says nothing about generators with more than ``k`` states; - see :class:`GlobalBoundResult`. + see :class:`GlobalBoundResult`. ``presolve=False, obbt=False`` is the second opinion for a decisive + "infeasible" or "optimal" (see the module docstring); ``params`` sets further SCIP parameters, e.g. + ``{"numerics/feastol": 1e-9}``. Requires PySCIPOpt (``pip install sofic[global]``). """ @@ -152,6 +308,7 @@ def generator_global_bound( m = scip.Model() m.hideOutput() + _configure(m, scip, presolve, obbt, params) def data_eq(lhs: Any, rhs: float) -> None: m.addCons(lhs <= rhs + data_tol) @@ -247,12 +404,7 @@ def data_eq(lhs: Any, rhs: float) -> None: status = str(m.getStatus()) slack = k * pi_min * math.log2(1 / pi_min) - dual = float(m.getDualbound()) - dual = math.inf if dual >= m.infinity() else -math.inf if dual <= -m.infinity() else dual - if status == "infeasible": - lower = math.inf if objective_limit is None else float(objective_limit) - slack - else: - lower = (dual if objective_limit is None else min(dual, float(objective_limit))) - slack + lower, dual = _bounds(m, status, objective_limit, slack) primal, seed = None, None if m.getNSols() > 0: primal = float(m.getPrimalbound()) @@ -266,7 +418,7 @@ def data_eq(lhs: Any, rhs: float) -> None: return GlobalBoundResult( k=k, status=status, - lower=float(lower), + lower=lower, dual_bound=dual, slack=slack, primal=primal, diff --git a/sofic/generators/separating_generators.py b/sofic/generators/separating_generators.py new file mode 100644 index 0000000..cd99a4e --- /dev/null +++ b/sofic/generators/separating_generators.py @@ -0,0 +1,598 @@ +r"""Exact minimal generators for cryptic order at most 1, and lookahead generators above it. + +Let :math:`P` be the joint distribution of the forward and reverse causal states :math:`(S^+, S^-)` of a process. +Every generator state separates them, so :math:`C_g \ge \op{G}{S^+ : S^-}` :cite:`LohrAy2009`. The persistent +crypticity :math:`p.\chi^+ = \H{S^+_1 \mid S^-_0, X_0}` equals :math:`\H{S^+_1 \mid X_{0:}}`, because the reverse +causal state shields the future from the past, and that is :math:`\chi^+ - \H{S^+_0 \mid X_0, S^+_1}`, Mahoney, +Ellison and Crutchfield's Theorem 1 at :math:`k = 1` :cite:`Mahoney2009`. It therefore vanishes exactly when the +cryptic order is at most 1. Forward and reverse cryptic orders are equal (when :math:`\chi^+ = 0` the past depends +on the future only through :math:`S^+`, so :math:`S^-` is a relabeling of :math:`S^+`; for orders of at least 1, +apply the vanishing of the two persistent crypticities together to the block processes), the cryptic-order +counterpart of the time symmetry of the Markov order :cite:`Ellison2011`. So cryptic order at most 1 is exactly +the class where both persistent crypticities vanish. There every separating variable of :math:`P` is +a generator state, :math:`C_g = \op{G}{S^+ : S^-}`, and :func:`theorem_generator` writes the generator down +without an LP. + +A decomposition :math:`P = \sum_w A_w R_w^\top` (row masses :math:`A_w = \pi_w Q_w`, column factors :math:`R_w`) +can be brought down to at most + +.. math:: + + K(P) = \left\lfloor \frac{|\mathrm{supp}\, P| + \min(|S^+|, |S^-|)}{2} \right\rfloor + +terms without raising its entropy (:func:`reduce_decomposition`, on the side with fewer rows or columns): merge two +terms with proportional row masses or equal column factors, or, when the column factors of the terms covering a +row are linearly dependent, move mass along the dependency until one of those cells empties, at the cheaper end +(the entropy is concave along the move). At the end every row's terms have independent column factors and each row +has at most one single-row term, which caps the count at :math:`K(P)` (:func:`support_bound_states`). Kumar, Li +and El Gamal's argument gives :math:`|X||Y|` :cite:`Kumar2014`. So :math:`K(P)` states suffice for a minimal +generator when the cryptic order is at most 1, and :func:`separating_decomposition` computes +:math:`\op{G}{S^+ : S^-}` per connected component of the support: exactly when the component has no +:math:`2 \times 2` rectangle (:func:`~sofic.generators.generator_bounds.one_wide_exact_common_information`), +otherwise by SCIP at :math:`K` terms (:func:`~sofic.generators.global_bound.separating_global_bound`, default +settings and the presolve/OBBT-off second opinion), polished into an exact decomposition. + +Above cryptic order 1, :func:`lookahead_generator` builds the least-entropy generator whose state determines its +next :math:`L - 1` symbols. Such a generator is a generator of the sliding-block process +:math:`Y_t = X_{t:t+L}`, whose persistent crypticity is :math:`\H{S^+_L \mid X_{0:}}`; that vanishes exactly when +:math:`L` reaches the cryptic order, which Mahoney et al. define as the least such :math:`L` :cite:`Mahoney2011`, +and then the construction above applies to :math:`Y_L`, giving + +.. math:: + + C_g \le \H{X_{0:L-1}} + \sum_u \Pr(u)\, \op{G}{S^+_{L-1} : S^-_0 \mid X_{0:L-1} = u}. + +The support bound, the reduction, :func:`theorem_generator`'s kernel and the lookahead construction are not from +the literature, and none of :cite:`Mahoney2009,Mahoney2011,Crutchfield2009,Ellison2011` states the equality of +the cryptic orders. +""" + +from __future__ import annotations + +import itertools +import math +import time +from dataclasses import dataclass, field +from typing import Any + +import networkx as nx +import numpy as np + +from sofic.generators.bidirectional_epsilon_machine import BidirectionalEpsilonMachine +from sofic.generators.coupled_generators import _decompose, _GeneratorProblem + +__all__ = [ + "LookaheadGenerator", + "SeparatingDecomposition", + "lookahead_generator", + "reduce_decomposition", + "separating_decomposition", + "support_bound_states", + "theorem_generator", +] + +_ZERO = 1e-10 +_EXACT = 1e-12 + + +def _entropy(p: Any) -> float: + p = np.asarray(p, dtype=float).ravel() + p = p[p > 1e-300] + return float(-(p * np.log2(p)).sum()) + + +def support_bound_states(P: np.ndarray, *, tol: float = 0.0) -> int: + r""":math:`K(P) = \lfloor (|\mathrm{supp}\, P| + \min(\text{rows}, \text{columns})) / 2 \rfloor`, counting cells + above ``tol`` and rows and columns of positive mass. + + Some least-entropy separating variable of ``P`` has at most this many values (see the module docstring), so + when the cryptic order is at most 1 some minimal generator has at most :math:`K(P)` states. + """ + S = np.asarray(P, dtype=float) > tol + return int((S.sum() + min(int(S.any(axis=1).sum()), int(S.any(axis=0).sum()))) // 2) + + +def _nullvec(cols: list[np.ndarray], tol: float) -> np.ndarray | None: + M = np.array(cols, dtype=float).T + _, s, vh = np.linalg.svd(M) + rank = int(np.sum(s > tol * max(1.0, s[0] if len(s) else 0.0))) + return None if rank == M.shape[1] else vh[-1] + + +def _merge(A: list[np.ndarray], R: list[np.ndarray], tol: float) -> bool: + for u in range(len(A)): + pu = A[u].sum() + for v in range(u + 1, len(A)): + pv = A[v].sum() + if np.abs(A[u] / pu - A[v] / pv).max() <= tol: + R[u] = (pu * R[u] + pv * R[v]) / (pu + pv) + elif np.abs(R[u] - R[v]).max() > tol: + continue + A[u] = A[u] + A[v] + del A[v], R[v] + return True + return False + + +def _null_move(A: list[np.ndarray], R: list[np.ndarray], tol: float) -> bool: + for x in range(len(A[0])): + T = [w for w in range(len(A)) if A[w][x] > tol] + if len(T) < 2: + continue + c = _nullvec([R[w] for w in T], tol) + if c is None: + continue + c = np.where(np.abs(c) > 1e-14, c, 0.0) + if not ((c > 0).any() and (c < 0).any()): + continue + hi = min((A[w][x] / -ci, i) for i, (w, ci) in enumerate(zip(T, c, strict=True)) if ci < 0) + lo = max((-A[w][x] / ci, i) for i, (w, ci) in enumerate(zip(T, c, strict=True)) if ci > 0) + pi = np.array([a.sum() for a in A]) + ends = [] + for t, i in (lo, hi): + q = pi.copy() + q[T] += t * c + ends.append((_entropy(q), t, i)) + _, t, binding = min(ends) + for w, ci in zip(T, c, strict=True): + A[w][x] = max(A[w][x] + t * ci, 0.0) + A[T[binding]][x] = 0.0 + return True + return False + + +def reduce_decomposition( + P: np.ndarray, A: Any, R: Any, *, tol: float = 1e-9 +) -> tuple[np.ndarray, np.ndarray, dict[str, int]]: + """Merges and null moves on a decomposition ``P = sum_w outer(A[w], R[w])`` until neither applies. + + ``A[w]`` are row masses (weight times row belief) and ``R[w]`` column factors (distributions). The moves run on + the side with fewer rows or columns of positive mass, never raise the entropy of the weights, keep the + decomposition exact up to rounding, and end with at most :func:`support_bound_states` terms. Returns + ``(A, R, moves)`` with ``moves`` counting each kind; ``tol`` decides equal factors, positive cells and + numerical rank. + """ + P = np.asarray(P, dtype=float) + S = P > 0 + flip = int(S.any(axis=0).sum()) < int(S.any(axis=1).sum()) + terms = [(np.asarray(a, float), np.asarray(r, float)) for a, r in zip(A, R, strict=True)] + if flip: + terms = [(a.sum() * r, a / a.sum()) for a, r in terms if a.sum() > tol] + A_, R_ = [a for a, _ in terms], [r for _, r in terms] + moves = {"merge": 0, "null": 0} + while True: + keep = [w for w in range(len(A_)) if A_[w].sum() > tol] + A_, R_ = [A_[w] for w in keep], [R_[w] for w in keep] + if _merge(A_, R_, tol): + moves["merge"] += 1 + elif _null_move(A_, R_, tol): + moves["null"] += 1 + else: + break + if flip: + A_, R_ = [a.sum() * r for a, r in zip(A_, R_, strict=True)], [a / a.sum() for a in A_] + return np.array(A_), np.array(R_), moves + + +@dataclass(frozen=True) +class SeparatingDecomposition: + """A least-entropy separating variable of a joint, from :func:`separating_decomposition`. + + ``pi``, ``Q`` (row beliefs) and ``R`` (column beliefs) give ``P = sum_w pi_w outer(Q[w], R[w])`` to + ``residual``. ``value`` is its entropy, an upper bound on :math:`\\op{G}{X : Y}`; ``lower`` is a lower bound + (exact on rectangle-free components, SCIP's dual bound at :math:`K` terms otherwise, numerical), ``exact`` + says every component was solved exactly, and ``components`` records each component's method and bracket. + """ + + pi: np.ndarray + Q: np.ndarray + R: np.ndarray + value: float + lower: float + exact: bool + residual: float + components: list[dict[str, Any]] = field(default_factory=list) + + +def _components(P: np.ndarray) -> list[tuple[np.ndarray, np.ndarray]]: + g = nx.Graph() + g.add_edges_from((("r", int(a)), ("c", int(b))) for a, b in np.argwhere(P > _ZERO)) + out = [] + for nodes in nx.connected_components(g): + rows = np.array(sorted(i for t, i in nodes if t == "r")) + cols = np.array(sorted(i for t, i in nodes if t == "c")) + out.append((rows, cols)) + return sorted(out, key=lambda rc: (int(rc[0][0]), int(rc[1][0]))) + + +def _residual(P: np.ndarray, A: np.ndarray, R: np.ndarray) -> float: + return float(np.abs(np.einsum("wa,wb->ab", A, R) - P).max()) + + +def _project_exact(P: np.ndarray, A: np.ndarray, R: np.ndarray, threshold: float): + """Least-squares projection onto exact decompositions with the zero pattern of ``(A, R)`` (entries at most + ``threshold`` fixed at 0).""" + from scipy.optimize import least_squares + + live = (A.sum(axis=1) > 0) & (R.sum(axis=1) > 0) + A, R = A[live], R[live] + pi = A.sum(axis=1) + q0, r0 = A / pi[:, None], R / R.sum(axis=1, keepdims=True) + k = len(pi) + mQ, mR = q0 > threshold, r0 > threshold + nq = int(mQ.sum()) + + def unpack(x: np.ndarray): + q, r = np.zeros(q0.shape), np.zeros(r0.shape) + q[mQ], r[mR] = x[k : k + nq], x[k + nq :] + return x[:k], q, r + + def fun(x: np.ndarray) -> np.ndarray: + lam, q, r = unpack(x) + return np.concatenate([(np.einsum("w,wa,wb->ab", lam, q, r) - P).ravel(), q.sum(1) - 1, r.sum(1) - 1]) + + sol = least_squares( + fun, + np.concatenate([pi, q0[mQ], r0[mR]]), + bounds=(0.0, 1.0), + xtol=1e-15, + ftol=1e-15, + gtol=1e-15, + max_nfev=5000, + ) + lam, q, r = unpack(sol.x) + keep = lam > 1e-14 + A2 = lam[keep, None] * q[keep] + return A2, r[keep], _residual(P, A2, r[keep]) + + +def _descend(P: np.ndarray, A: np.ndarray, R: np.ndarray): + pi = A.sum(axis=1) + lam, Qp, Rp, res = _decompose(P, pi, A / pi[:, None], R) + if res <= 1e-10 and _entropy(lam) < _entropy(pi) - 1e-12: + A2, R2, res2 = _project_exact(P, lam[:, None] * np.clip(Qp, 0, None), np.clip(Rp, 0, None), 1e-13) + if res2 <= _EXACT and _entropy(A2.sum(axis=1)) < _entropy(pi): + return A2, R2, res2 + return A, R, _residual(P, A, R) + + +def _polish( + P: np.ndarray, + candidates: list[tuple[np.ndarray, np.ndarray]], + k_max: int, + starts: int, + rng: np.random.Generator, + deadline: float | None = None, +): + """The least-entropy exact decomposition from approximate ``candidates`` (reduced at their tolerance, projected, + descended) and multistart descents with 2 terms up to the most terms of a candidate (``k_max`` without + candidates); ``None`` when none is exact. Multistarts stop at ``deadline`` once some decomposition is exact.""" + exact = [] + for A, R in candidates: + A0, R0, _ = reduce_decomposition(P, A, R, tol=1e-6) + for Ai, Ri in ((A0, R0), (A, R)): + for threshold in (1e-7, 1e-5, 1e-3): + A1, R1, res1 = _project_exact(P, np.asarray(Ai, float), np.asarray(Ri, float), threshold) + if res1 <= _EXACT: + exact.append(_descend(P, A1, R1)) + break + na, nb = P.shape + if candidates: + k_max = max(len(A) for A, _ in candidates) + for k in range(2, max(2, k_max) + 1): + for _ in range(starts): + if exact and deadline is not None and time.monotonic() > deadline: + break + lam, Qd, Rd, res = _decompose( + P, rng.dirichlet(np.ones(k)), rng.dirichlet(np.ones(na), size=k), rng.dirichlet(np.ones(nb), size=k) + ) + if res <= 1e-10: + A1, R1, res1 = _project_exact(P, lam[:, None] * np.clip(Qd, 0, None), np.clip(Rd, 0, None), 1e-13) + if res1 <= _EXACT: + exact.append((A1, R1, res1)) + return min(exact, key=lambda c: _entropy(c[0].sum(axis=1))) if exact else None + + +def _scip_component(P: np.ndarray, k: int, time_limit: float) -> tuple[list, float, dict[str, Any]]: + from sofic.generators.global_bound import separating_global_bound + + runs = { + "default": separating_global_bound(P, k, time_limit=time_limit), + "second": separating_global_bound(P, k, time_limit=time_limit, presolve=False, obbt=False), + } + if runs["default"].status == "infeasible" and runs["second"].status != "infeasible": + runs["default"] = runs["second"] + candidates = [] + for res in runs.values(): + if res.factors is not None: + p, Q, R = res.factors + keep = p > 1e-9 + R = np.where(R[keep] > 1e-9, R[keep], 0.0) + candidates.append( + (p[keep, None] * np.where(Q[keep] > 1e-9, Q[keep], 0.0), R / R.sum(axis=1, keepdims=True)) + ) + lowers = [res.lower for res in runs.values() if res.status != "infeasible"] + info = {name: {"status": res.status, "primal": res.primal, "lower": res.lower} for name, res in runs.items()} + return candidates, min(lowers, default=0.0), info + + +def separating_decomposition( + P: np.ndarray, + *, + time_limit: float = 60.0, + starts: int = 6, + rng: np.random.Generator | None = None, +) -> SeparatingDecomposition: + r"""A least-entropy separating variable of the joint ``P``, solved per connected component of its support. + + A component in one row or column is a single term. A component without :math:`2 \times 2` rectangles is solved + exactly (:func:`~sofic.generators.generator_bounds.one_wide_exact_common_information`). Otherwise SCIP + minimizes the entropy over decompositions with :math:`K` terms (:func:`support_bound_states` of the component, + which covers an optimum), with default settings and with presolve and OBBT off + (:func:`~sofic.generators.global_bound.separating_global_bound`, ``time_limit`` seconds each). SCIP's + solutions are feasible only to its tolerance, so each is reduced, projected onto exact decompositions and + descended, alongside ``starts`` multistart descents per term count (for up to ``time_limit`` seconds more); + the best exact one is kept and the smaller + of the two dual bounds is the component's lower bound (an "infeasible" counts as no bound, since a + decomposition with :math:`K` terms always exists). Without PySCIPOpt the multistart descents alone give + the upper bound and the lower bound is 0. Components combine as + :math:`\H{C} + \sum_c \Pr(c)\, G_c` for the component label :math:`C`, a common function of both sides. + """ + from sofic.generators.generator_bounds import one_wide_exact_common_information + + rng = rng if rng is not None else np.random.default_rng(0) + P = np.asarray(P, dtype=float) + P = P / P.sum() + A_all, R_all, parts, masses = [], [], [], [] + lower, exact = 0.0, True + for rows, cols in _components(P): + sub = P[np.ix_(rows, cols)] + mass = float(sub.sum()) + sub = sub / mass + part: dict[str, Any] = {"rows": rows.tolist(), "cols": cols.tolist(), "K": support_bound_states(sub, tol=_ZERO)} + if min(sub.shape) == 1: + A, R = sub.sum(axis=1)[None, :], sub.sum(axis=0)[None, :] + part.update(method="trivial", lower=0.0) + else: + try: + ow = one_wide_exact_common_information(sub, atol=1e-13) + except ValueError: + ow = None + if ow is not None: + A, R = _blocks_to_terms(sub, ow.blocks) + part.update(method="one-wide", lower=ow.value) + else: + exact = False + try: + candidates, c_lower, info = _scip_component(sub, part["K"], time_limit) + part.update(method="scip", scip=info) + except ImportError: + candidates, c_lower = [], 0.0 + part.update(method="multistart") + best = _polish(sub, candidates, part["K"], starts, rng, time.monotonic() + time_limit) + if best is None: + raise RuntimeError(f"no exact decomposition found for a {sub.shape} component") + A, R, _ = best + part["lower"] = min(c_lower, _entropy(A.sum(axis=1))) + part["value"] = _entropy(A.sum(axis=1)) + lower += mass * part["lower"] + masses.append(mass) + for a, r in zip(A, R, strict=True): + a_full, r_full = np.zeros(P.shape[0]), np.zeros(P.shape[1]) + a_full[rows], r_full[cols] = mass * np.asarray(a), np.asarray(r) + A_all.append(a_full) + R_all.append(r_full) + parts.append(part) + A_full, R_full = np.array(A_all), np.array(R_all) + pi = A_full.sum(axis=1) + value = _entropy(pi) + return SeparatingDecomposition( + pi=pi, + Q=A_full / pi[:, None], + R=R_full, + value=value, + lower=min(value, lower + _entropy(masses)), + exact=exact, + residual=_residual(P, A_full, R_full), + components=parts, + ) + + +def _blocks_to_terms(P: np.ndarray, blocks: Any) -> tuple[np.ndarray, np.ndarray]: + A, R = [], [] + for block in blocks: + mass = sum(P[c] for c in block) + a, r = np.zeros(P.shape[0]), np.zeros(P.shape[1]) + rows = {c[0] for c in block} + if len(rows) == 1: + (row,) = rows + a[row] = mass + for _, b in block: + r[b] = P[row, b] / mass + else: + (col,) = {c[1] for c in block} + for x, _ in block: + a[x] = P[x, col] + r[col] = 1.0 + A.append(a) + R.append(r) + return np.array(A), np.array(R) + + +def _as_problem(bidir: BidirectionalEpsilonMachine | _GeneratorProblem) -> _GeneratorProblem: + return bidir if isinstance(bidir, _GeneratorProblem) else _GeneratorProblem(bidir) + + +def theorem_generator( + bidir: BidirectionalEpsilonMachine | _GeneratorProblem, + pi: np.ndarray, + Q: np.ndarray, + R: np.ndarray, + *, + tol: float = 1e-9, +) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + r"""The generator of a separating variable ``(pi, Q, R)`` of the causal-state joint, when :math:`p.\chi^+ = 0`. + + With the channel :math:`c(w \mid a, b) = \pi_w Q_w(a) R_w(b) / P(a, b)` the state at time 1 is drawn from + :math:`c(\cdot \mid S^+_1, S^-_1)`, and the kernel is + + .. math:: + + K(x, v \mid w) = \sum_{b, b'} R_w(b) \Pr(X_0 = x, S^-_1 = b' \mid S^-_0 = b)\, + c(v \mid \phi(b, x), b'), + + where :math:`\phi(b, x) = S^+_1` is a function of :math:`(S^-_0, X_0)` because :math:`p.\chi^+ = 0`. Returns + ``(pi, Q, R, K)`` with ``K[w, x, v]``, symbols in the problem's order; it satisfies the coupled generator + equations, and its word process is the source's. Raises ``ValueError`` when :math:`p.\chi^+ > ` ``tol``. + """ + problem = _as_problem(bidir) + lif = problem.lifted + J = np.einsum("pb,pxq,qa->bxa", lif.minus, lif.edges, lif.plus) + pchi = _entropy(J) - _entropy(J.sum(axis=2)) + if pchi > tol: + raise ValueError(f"theorem_generator needs p.chi+ = 0 (cryptic order at most 1); p.chi+ = {pchi:.3g}") + pi, Q, R = (np.asarray(t, dtype=float) for t in (pi, Q, R)) + P = np.einsum("p,pa,pb->ab", lif.p, lif.plus, lif.minus) + pa, pb = lif.plus.argmax(axis=1), lif.minus.argmax(axis=1) + c = (pi[None, :] * Q[:, pa].T * R[:, pb].T) / P[pa, pb][:, None] + T = np.einsum("pb,pxq->bxq", lif.minus, lif.edges) + K = np.einsum("wb,bxq,qv->wxv", R / problem.p_minus[None, :], T, c) + return pi, Q, R, K + + +@dataclass(frozen=True) +class LookaheadGenerator: + """The least-entropy generator whose state determines its next ``L - 1`` symbols (:func:`lookahead_generator`). + + ``model`` is a Mealy HMM for the source with ``states`` states, and ``kernel[w, x, v]`` its transition tensor + over ``symbols``; ``value`` its state entropy, an upper bound on :math:`C_g`; ``lower`` bounds ``value``'s + optimum over this class (exact when ``exact``); ``word_error`` the exact word-process deviation from the + source. + """ + + L: int + model: Any + value: float + lower: float + exact: bool + states: int + word_error: float + kernel: np.ndarray + symbols: tuple + + +def _block_machine(machine: Any, L: int) -> Any: + """The ε-machine of :math:`Y_t = X_{t:t+L}` (symbols are ``L``-tuples): states (last ``L - 1`` symbols, + :math:`S^+`).""" + from sofic.examples.epsilon_machines import from_symbol_matrices + from sofic.generators.epsilon_machine import EpsilonMachine + from sofic.generators.matrices import emission_tensors + + pi, T = emission_tensors(machine) + pi = np.asarray(pi, dtype=float) + syms = list(T) + T = {x: np.asarray(m, dtype=float) for x, m in T.items()} + states = [] + for u in itertools.product(syms, repeat=L - 1): + v = pi.copy() + for x in u: + v = v @ T[x] + states += [(u, a) for a in range(len(pi)) if v[a] > 1e-15] + index = {s: i for i, s in enumerate(states)} + mats: dict[tuple, np.ndarray] = {} + for (u, a), i in index.items(): + for x in syms: + for a2 in np.flatnonzero(T[x][a] > 0): + y = (*u, x) + j = index[(y[1:], int(a2))] + mats.setdefault(y, np.zeros((len(states), len(states))))[i, j] += T[x][a, a2] + labels = [f"{''.join(map(str, u))}|{a}" for u, a in states] + m = from_symbol_matrices(labels, sorted(mats, key=repr), mats) + return m if isinstance(m, EpsilonMachine) else EpsilonMachine.from_hmm(m) + + +def lookahead_generator( + machine: Any, + L: int | None = None, + *, + time_limit: float = 60.0, + rng: np.random.Generator | None = None, +) -> LookaheadGenerator: + r"""The least-entropy generator of ``machine``'s process whose state determines its next ``L - 1`` symbols. + + ``L`` defaults to the cryptic order (at least 1), the least ``L`` for which the sliding-block process + :math:`Y_L` has :math:`p.\chi = 0`; ``ValueError`` when the cryptic order is infinite and no ``L`` is given, or + when :math:`Y_L` still has :math:`p.\chi^+ > 0`. Builds :math:`Y_L`'s bidirectional machine, a least-entropy + separating variable of its causal states (:func:`separating_decomposition`), reduces it, writes the generator + of :func:`theorem_generator`, keeps the first symbol of each emission, and checks the word process against + ``machine`` exactly. The value is :math:`\H{X_{0:L-1}} + \sum_u \Pr(u) \op{G}{S^+_{L-1} : S^-_0 \mid u}`, an + upper bound on :math:`C_g`: on the :math:`(2, \infty)` process it is :math:`3/2 = C_g`, on the butterfly + :math:`3.1219`, above :math:`C_g = C_\mu = \log_2 5`. + """ + from sofic.generators.generative_search import resolve_bidirectional + from sofic.generators.mealy import MealyHMM + from sofic.generators.minimal_generative_model import _equivalence_error + from sofic.graph import ATTR_EMISSION, ATTR_PROB + + if L is None: + kappa = machine.cryptic_order() + if kappa == math.inf: + raise ValueError("the cryptic order is infinite; give L") + L = max(int(kappa), 1) + y_machine = _block_machine(machine, L) + problem = _GeneratorProblem(resolve_bidirectional(y_machine)[0]) + P = np.einsum("p,pa,pb->ab", problem.lifted.p, problem.lifted.plus, problem.lifted.minus) + dec = separating_decomposition(P, time_limit=time_limit, rng=rng) + A, R, _ = reduce_decomposition(P, dec.pi[:, None] * dec.Q, dec.R) + pi = A.sum(axis=1) + pi, _, _, K = theorem_generator(problem, pi, A / pi[:, None], R) + keep = np.flatnonzero(pi > 1e-14) + firsts = sorted({y[0] for y in problem.symbols}, key=repr) + KX = np.zeros((len(keep), len(firsts), len(keep))) + for yi, y in enumerate(problem.symbols): + KX[:, firsts.index(y[0]), :] += K[np.ix_(keep, [yi], keep)][:, 0, :] + KX /= KX.sum(axis=(1, 2), keepdims=True) + names = [f"G{i}" for i in range(len(keep))] + weights = pi[keep] / pi[keep].sum() + model = MealyHMM( + initial_distribution=dict(zip(names, weights.tolist(), strict=True)), observation_alphabet=frozenset(firsts) + ) + for s in names: + model.graph.add_state(s) + for w, xi, v in zip(*np.nonzero(KX > 1e-14), strict=True): + model.graph.add_transition(names[w], names[v], **{ATTR_PROB: float(KX[w, xi, v]), ATTR_EMISSION: firsts[xi]}) + return LookaheadGenerator( + L=L, + model=model, + value=_entropy(weights), + lower=dec.lower, + exact=dec.exact, + states=len(keep), + word_error=float(_equivalence_error(model, machine)), + kernel=KX, + symbols=tuple(firsts), + ) + + +def _block_persistent_crypticities(problem: _GeneratorProblem, L_max: int = 4, max_size: int = 200_000): + r"""``[(L, p.chi+, p.chi-)]`` of the block processes :math:`Y_L` for ``L = 1 .. L_max``, from the tensor + :math:`\Pr(S^-_0, X_{0:L}, S^+_L)`: :math:`p.\chi^+(Y_L) = \H{S^+_L \mid X_{0:}}` and + :math:`p.\chi^-(Y_L) = \H{S^-_0 \mid X_{:L}}`, both zero exactly from the cryptic order on. Stops once both + vanish or the tensor would exceed ``max_size`` entries.""" + lif = problem.lifted + pp = lif.p + T = lif.edges / np.where(pp > 0, pp, 1.0)[:, None, None] + cur = np.einsum("pb,pxq->bxq", lif.minus, lif.edges) + out = [] + for L in range(1, L_max + 1): + if L > 1: + if cur.size * T.shape[1] > max_size: + break + cur = np.einsum("bwq,qxr->bwxr", cur, T).reshape(cur.shape[0], -1, T.shape[-1]) + J = np.einsum("bwr,ra->bwa", cur, lif.plus) + h = _entropy(J) + plus, minus = max(0.0, h - _entropy(J.sum(axis=2))), max(0.0, h - _entropy(J.sum(axis=0))) + out.append((L, plus, minus)) + if plus < 1e-10 and minus < 1e-10: + break + return out diff --git a/tests/test_global_bound.py b/tests/test_global_bound.py index d831291..08e7d88 100644 --- a/tests/test_global_bound.py +++ b/tests/test_global_bound.py @@ -51,6 +51,15 @@ def test_golden_mean_bound_is_the_statistical_complexity(scip) -> None: assert two.lower == pytest.approx(two.dual_bound - two.slack) +@pytest.mark.parametrize("presolve", [True, False]) +def test_presolve_off_also_turns_off_symmetry(scip, presolve) -> None: + m = scip.Model() + default = m.getParam("misc/usesymmetry") + gb._configure(m, scip, presolve=presolve, obbt=True, params=None) + assert m.getParam("misc/usesymmetry") == (default if presolve else 0) + assert m.getParam("propagating/obbt/freq") != -1 + + def test_objective_limit_semantics(scip) -> None: bidir = _bidir(_two_state(*GOLDEN_MEAN)) below = gb.generator_global_bound(bidir, 2, objective_limit=C_MU_GOLDEN - 0.01) diff --git a/tests/test_separating_generators.py b/tests/test_separating_generators.py new file mode 100644 index 0000000..cedcdcb --- /dev/null +++ b/tests/test_separating_generators.py @@ -0,0 +1,263 @@ +"""Exact minimal generators for cryptic order at most 1, the support bound, and lookahead generators.""" + +from __future__ import annotations + +import sys + +import numpy as np +import pytest +from hypothesis import HealthCheck, assume, given, settings +from hypothesis import strategies as st + +from sofic.generators import separating_generators as sg + + +def _h(p): + p = np.asarray(p, float).ravel() + p = p[p > 1e-300] + return float(-(p * np.log2(p)).sum()) + + +def _problem(machine): + from sofic.generators.coupled_generators import _GeneratorProblem + from sofic.generators.generative_search import resolve_bidirectional + + return _GeneratorProblem(resolve_bidirectional(machine)[0]) + + +def _joint(problem): + lif = problem.lifted + return np.einsum("p,pa,pb->ab", lif.p, lif.plus, lif.minus) + + +def _topologies(): + from sofic.examples.epsilon_machines import even_process, golden_mean, restricted_golden_mean + from sofic.examples.processes import rip, stretched_gm + + return { + "golden mean": golden_mean(), + "even": even_process(), + "rip": rip(), + "stretched gm 2": stretched_gm(2), + "rgm 2": restricted_golden_mean(2), + } + + +def _random_machine(name: str, seed: int): + from sofic.examples.processes import uniform_mealyhmm + from sofic.generators.epsilon_machine import EpsilonMachine + from sofic.graph import ATTR_PROB + + m = uniform_mealyhmm(_topologies()[name], create_using=EpsilonMachine, prng=np.random.default_rng(seed)) + m = m if isinstance(m, EpsilonMachine) else EpsilonMachine.from_hmm(m) + # Below this the reverse ε-machine can come out non-minimal: on the (2, inf) topology a self-loop of 0.0010739 + # gives 4 reverse states, two of them predictively equivalent up to 3e-10, and a reverse cryptic order of inf. + assume(min(float(t.data[ATTR_PROB]) for t in m.transitions()) >= 0.02) + return m + + +# Kumar, Li and El Gamal's Example 2 (an erasure joint), and a 3 x 3 joint where OBBT cuts off the optimum. +KUMAR_2 = np.array([[0.05, 0.0, 0.45], [0.0, 0.05, 0.45]]) +JOINT_52 = np.array( + [ + [0.25510874950017903, 0.0, 0.18459086280725023], + [0.0, 0.0, 0.41334737027755303], + [0.0, 0.14247245903801908, 0.004480558376998535], + ] +) + + +@pytest.mark.parametrize( + ("P", "K"), + [(np.eye(3) / 3, 3), (np.full((2, 2), 0.25), 3), (KUMAR_2, 3), (JOINT_52, 4), (np.ones((1, 4)) / 4, 2)], +) +def test_support_bound_states(P, K) -> None: + assert sg.support_bound_states(P) == K + + +@st.composite +def _decompositions(draw): + rows, cols, terms = draw(st.integers(2, 4)), draw(st.integers(2, 4)), draw(st.integers(1, 8)) + rng = np.random.default_rng(draw(st.integers(0, 2**32 - 1))) + A = rng.random((terms, rows)) * (rng.random((terms, rows)) < 0.7) + A[A.sum(axis=1) == 0, rng.integers(rows)] = 1.0 + R = rng.dirichlet(np.ones(cols), size=terms) * (rng.random((terms, cols)) < 0.6) + R[R.sum(axis=1) == 0, rng.integers(cols)] = 1.0 + return A / A.sum(), R / R.sum(axis=1, keepdims=True) + + +@settings(max_examples=60, deadline=None) +@given(_decompositions()) +def test_reduction_keeps_the_joint_lowers_the_entropy_and_reaches_the_support_bound(dec) -> None: + A, R = dec + P = A.T @ R + A2, R2, moves = sg.reduce_decomposition(P, A, R) + assert np.abs(A2.T @ R2 - P).max() <= 1e-9 + assert (A2 >= 0).all() and np.allclose(R2.sum(axis=1), 1.0) + assert _h(A2.sum(axis=1)) <= _h(A.sum(axis=1)) + 1e-9 + assert len(A2) <= sg.support_bound_states(P) + assert sum(moves.values()) >= len(A) - len(A2) + + +_KAPPA_LE_1 = ("golden mean", "even", "rip", "stretched gm 2") + + +@settings(max_examples=20, deadline=None, suppress_health_check=[HealthCheck.too_slow]) +@given(st.sampled_from(sorted(_topologies())), st.integers(0, 2**32 - 1)) +def test_theorem_class_identity_and_equal_cryptic_orders(name, seed) -> None: + """p.chi+ = chi+ - H[S+_0 | X_0, S+_1], zero exactly at cryptic order at most 1; kappa+ = kappa-.""" + from sofic.generators.generative_search import _cryptic_orders, _persistent_criteria, resolve_bidirectional + + machine = _random_machine(name, seed) + bidir = resolve_bidirectional(machine)[0] + problem = _problem(machine) + lif = problem.lifted + P = _joint(problem) + chi_plus = _h(P) - _h(P.sum(axis=0)) + F = np.einsum("pa,pxq,qc->axc", lif.plus, lif.edges, lif.plus) + p_chi_plus, _ = _persistent_criteria(problem) + assert p_chi_plus == pytest.approx(chi_plus - (_h(F) - _h(F.sum(axis=0))), abs=1e-10) + kappa_plus, kappa_minus = _cryptic_orders(bidir) + assert kappa_plus == kappa_minus + assert (p_chi_plus < 1e-10) == (kappa_plus <= 1) + ladder = sg._block_persistent_crypticities(problem) + assert all((max(plus, minus) < 1e-10) == (length >= kappa_plus) for length, plus, minus in ladder) + + +@settings(max_examples=12, deadline=None, suppress_health_check=[HealthCheck.too_slow]) +@given(st.sampled_from(_KAPPA_LE_1), st.integers(0, 2**32 - 1)) +def test_theorem_generator_generates(name, seed) -> None: + from sofic.generators.coupled_generators import CoupledSearchResult, _model_from_kernel + from sofic.generators.minimal_generative_model import _equivalence_error + + machine = _random_machine(name, seed) + assume(machine.cryptic_order() <= 1) + problem = _problem(machine) + P = _joint(problem) + dec = sg.separating_decomposition(P, time_limit=20) + A, R, _ = sg.reduce_decomposition(P, dec.pi[:, None] * dec.Q, dec.R) + assert len(A) <= sg.support_bound_states(P, tol=1e-12) + pi = A.sum(axis=1) + pi, Q, R, K = sg.theorem_generator(problem, pi, A / pi[:, None], R) + assert problem.residual(pi, Q, R, K) <= 1e-9 + model = _model_from_kernel(problem, CoupledSearchResult(pi, Q, R, K, _h(pi), 0.0, "theorem"), 1e-14) + assert _equivalence_error(model, machine) <= 1e-8 + assert dec.lower <= dec.value + 1e-12 + + +def test_theorem_generator_needs_cryptic_order_at_most_1() -> None: + from sofic.examples.epsilon_machines import restricted_golden_mean + + problem = _problem(restricted_golden_mean(2)) + with pytest.raises(ValueError, match="cryptic order at most 1"): + sg.theorem_generator(problem, np.ones(1), np.ones((1, problem.n_plus)), np.ones((1, problem.n_minus))) + + +def test_rectangle_free_components_are_exact() -> None: + from sofic.generators.generator_bounds import one_wide_exact_common_information + + for P in (KUMAR_2, JOINT_52): + dec = sg.separating_decomposition(P) + value = one_wide_exact_common_information(P, atol=1e-13).value + assert dec.exact and dec.value == pytest.approx(value, abs=1e-12) and dec.lower == dec.value + assert dec.residual <= 1e-15 + + +@pytest.fixture +def scip(): + return pytest.importorskip("pyscipopt") + + +def test_scip_second_opinion(scip) -> None: + """Presolve can declare a feasible model infeasible, and OBBT can cut off the optimum; with both off SCIP is + right on these joints, and the exact path keeps the smaller lower bound.""" + from sofic.generators.generator_bounds import one_wide_exact_common_information + from sofic.generators.global_bound import separating_global_bound + + second = separating_global_bound(KUMAR_2, 2, presolve=False, obbt=False) + assert second.status == "optimal" and second.primal == pytest.approx(1.0, abs=1e-5) + assert separating_global_bound(KUMAR_2, 2).status in ("optimal", "infeasible") + _, lower, _ = sg._scip_component(KUMAR_2, 2, 60.0) + assert lower <= 1.0 + 1e-9 + + value = one_wide_exact_common_information(JOINT_52, atol=1e-13).value + second = separating_global_bound(JOINT_52, 3, presolve=False, obbt=False) + assert second.status == "optimal" and second.primal == pytest.approx(value, abs=1e-5) + assert value - 1e-4 <= second.lower <= value + candidates, lower, _ = sg._scip_component(JOINT_52, 3, 60.0) + assert lower <= value + 1e-9 + A, R, residual = sg._polish(JOINT_52, candidates, 3, 2, np.random.default_rng(0)) + assert residual <= 1e-12 and _h(A.sum(axis=1)) == pytest.approx(value, abs=1e-9) + + +def test_full_support_component_uses_scip(scip) -> None: + P = np.array([[0.261439, 0.063794], [0.088097, 0.261439]]) + P = P / P.sum() + dec = sg.separating_decomposition(P) + assert not dec.exact and [c["method"] for c in dec.components] == ["scip"] + assert dec.residual <= 1e-12 and dec.value - 1e-4 <= dec.lower <= dec.value + assert len(dec.pi) <= sg.support_bound_states(P) + + +def test_missing_pyscipopt_falls_back_to_multistart(monkeypatch) -> None: + monkeypatch.setitem(sys.modules, "pyscipopt", None) + P = np.array([[0.3, 0.1], [0.1, 0.5]]) + dec = sg.separating_decomposition(P) + assert [c["method"] for c in dec.components] == ["multistart"] + assert dec.residual <= 1e-12 and dec.lower == 0.0 and 0.0 < dec.value <= 1.0 + 1e-12 + + +def test_lookahead_generator_on_the_two_infinity_process() -> None: + """The (2, inf) run-length-limited process (``restricted_golden_mean(2)``) has cryptic order 2 and + C_g = 3/2; the lookahead generator reaches it with 3 states.""" + from sofic.examples.epsilon_machines import restricted_golden_mean + + machine = restricted_golden_mean(2) + look = sg.lookahead_generator(machine) + assert look.L == 2 and look.states == 3 and look.exact + assert look.value == pytest.approx(1.5, abs=1e-12) and look.lower == pytest.approx(1.5, abs=1e-12) + assert look.word_error <= 1e-12 + with pytest.raises(ValueError, match="p.chi"): + sg.lookahead_generator(machine, 1) + + +# A 2-state binary process of cryptic order 1 with a full-support causal-state joint, where C_mu = 0.930387 > G +# and the support-type bounds are far below G. +SCIP_KAPPA_1 = { + 0: [[0.8620162340426342, 0.0], [0.26088622236842307, 0.0]], + 1: [[0.0, 0.1379837659573659], [0.0, 0.7391137776315769]], +} +SCIP_KAPPA_1_G = 0.7970965391094695 + + +def test_pipeline_exact_path_with_a_scip_component(scip) -> None: + from sofic.examples.epsilon_machines import from_symbol_matrices + from sofic.generators.epsilon_machine import EpsilonMachine + from sofic.generators.generative_search import generative_model + + m = from_symbol_matrices((0, 1), (0, 1), {x: np.array(M) for x, M in SCIP_KAPPA_1.items()}) + machine = m if isinstance(m, EpsilonMachine) else EpsilonMachine.from_hmm(m) + numerical = generative_model(machine, coverage="off", rng=np.random.default_rng(0)) + stages = {s["stage"]: s for s in numerical.stages} + assert stages["exact path"]["components"] == ["scip"] and stages["exact path"]["states"] == 2 + assert numerical.lower_source == "separating global bound (numerical)" and not numerical.lower_certified + assert numerical.upper == pytest.approx(SCIP_KAPPA_1_G, abs=1e-7) + assert numerical.upper - 1e-4 <= numerical.lower <= numerical.upper + certified = generative_model(machine, rng=np.random.default_rng(0)) + assert certified.certified and certified.lower_certified + assert certified.upper == pytest.approx(SCIP_KAPPA_1_G, abs=1e-7) + + +@pytest.mark.parametrize("name", ["golden mean", "rip", "stretched gm 2"]) +def test_pipeline_certifies_the_theorem_class(name) -> None: + from sofic.generators.generative_search import generative_model + + machine = _topologies()[name] + value = sg.separating_decomposition(_joint(_problem(machine))).value + result = generative_model(machine, coverage="off", generator_heaviest_term=False, rng=np.random.default_rng(0)) + stages = {s["stage"]: s for s in result.stages} + assert result.persistent_crypticity_theorem_applies and result.certified and result.lower_certified + assert stages["persistent criteria"]["cryptic orders"][0] <= 1 + assert result.upper == pytest.approx(value, abs=1e-9) + if "exact path" in stages: + assert stages["exact path"]["states"] <= stages["exact path"]["support bound states"]