diff --git a/CHANGELOG.md b/CHANGELOG.md index 7df4647..0854a59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,38 @@ A second correctness review: every fix below was reproduced against a brute-force reference or a closed-form value and has a regression test. +### Strassen bound on one-sided generators + +- New `sofic.generators.strassen_bound`: `strassen_lower_bound(bidir)` bounds from below the state entropy of every + generator that is sufficient on one side, with any number of states (optional dependency, + `pip install sofic[global]`). A reverse-sufficient generator is a law on the simplex of beliefs on the reverse + causal states that dominates its image under the belief updates in convex order (Strassen 1965), so it passes every + concave piecewise-linear cut; the bound is the least entropy over laws with the right mean that pass the cuts, found + by cutting planes from the canonical-heights cut of the side's chain. Each master puts one atom in each cell of the + cuts' common refinement and replaces `-w log2 w` by its chords, refined at the minimizer: a mixed-integer linear + program with an SOS2 constraint per cell (Beale & Tomlin 1970), solved by SCIP. Separation is the most violated + hinge on the segment, and on the triangle the most violated ridge, then the coupling LP's Farkas cut. Sides with + more than three causal states are skipped. `StrassenBoundResult.certified` says that SCIP solved the last master, + that its minimizer passed separation and the martingale-coupling LP (so it is the law of a generator), and that its + entropy is within `1e-6` of `lower`; the side's one-sided value is then in `[lower, value]`. +- `generative_model(..., strassen_bound=True)` runs it right after the simplex-chain search, seeded with its chains, + with a quarter of the remaining budget (30 s per side without one) and at most 30 cuts per side, and reports + `strassen_lower` and `strassen_certified` per side, also in the reliability summary. Neither enters `lower` or + `certified`: the bounds hold for `C_g` only if some minimal generator is one-sided, which is open. The stage is + skipped on truncated and exploding builds, for the Wyner objective, and without PySCIPOpt. +- The masters avoid SCIP's spatial branch and bound on `-w log w`, which returned bounds above the entropy of a known + generator on 13 of 406 three-state sides of binary 3-state processes (by 0.09 to 1.86 bits on 6, certifying one of + those, and by `1.8e-6` to `2.6e-5` on 7) and called the master infeasible on 3 more. A failed round, with an LP error or an "infeasible" verdict, is solved again without the linear shortcut, + then with SCIP's numerics emphasis and feasibility tolerances of `1e-8` and `1e-7`; past those the master keeps its + last solved round. Thin cells left at a vertex by creases that converge on it are kept: dropping them loses the + vertex's atom. +- Validation, 30 cuts per side. On the 406 sides, 120 s each, no bound rose above the census generator's entropy + (the largest difference is `-6e-9`); 2 sides were certified, 10 came within `1e-6`, and the median bound is 0.88 + of the value. Of 133 open `C_g` brackets of small ε-machines, both sides were bounded on 66 (63 have a side with + more than three causal states): the bound raised the lower end of 3 and closed `s3-n2-t0012-d4`, certified on + both sides, and rose above no upper end. On 30 two-state processes, 600 s per side certified 5 and came within + `1e-6` of 7. + ### Drawing from a terminal - `draw()` with no filename shows the diagram: inline in terminals that support the kitty graphics protocol (kitty, diff --git a/docs/generators/generative_models.rst b/docs/generators/generative_models.rst index dd16120..7aa0d53 100644 --- a/docs/generators/generative_models.rst +++ b/docs/generators/generative_models.rst @@ -551,6 +551,62 @@ It enters ``lower`` (as a numerical bound) only at cryptic order at most 1 with 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. +Strassen bound on one-sided generators +-------------------------------------- + +:func:`~sofic.generators.strassen_bound.strassen_lower_bound` (optional dependency PySCIPOpt, +``pip install sofic[global]``) bounds from below the state entropy of every reverse-sufficient generator, whatever +its number of states, and of every forward-sufficient one on the mirror side. Such a generator is a finite law +:math:`\mu` on :math:`\Delta(S^-)` that dominates its image :math:`\Phi(\mu)` under the belief updates in convex order +:cite:`Strassen1965` (see the simplex-chain search above). After a symbol :math:`x`, emitted with probability +:math:`m_x(y)`, a belief :math:`y` moves to :math:`f_x(y)`, so for every concave :math:`U` on the simplex, Jensen's +inequality on the split of each updated belief gives :math:`\int (\mathcal{B} U - U) \, d\mu \ge 0` with +:math:`\mathcal{B} U(y) = \sum_x m_x(y) \, U(f_x(y))`. A *cut* is a concave piecewise-linear :math:`U`, and the least +entropy over laws with mean :math:`p(S^-)` that pass a set of cuts is a lower bound. The function computes it by +cutting planes, on each side with at most three causal states, where the cells below are polygons: + +* the *master problem* puts one atom in each cell of the cuts' common refinement, on which every cut is affine. + Merging the atoms of a cell keeps every cut (:math:`\mathcal{B} U` is superadditive) and lowers the entropy, so + these laws reach the minimum. Each term :math:`-w \log_2 w` is replaced by its chords on a grid of masses, which + lie below it, so the master is a mixed-integer linear program with an SOS2 constraint per cell :cite:`Beale1970`, + solved by SCIP :cite:`Achterberg2009` through PySCIPOpt :cite:`Maher2016`. Its dual bound is a lower bound, and the + grids gain the minimizer's masses until the chords meet the entropy there (to :math:`10^{-9}` in all); +* *separation* returns a cut that the minimizer fails: on the segment (two causal states) the most violated hinge + :math:`-(y_0 - t)_+`, which decides convex order there, and on the triangle the most violated of 180 ridges + :math:`-(d \cdot y - t)_+`, then the Farkas dual of the martingale-coupling LP; +* the loop starts from the canonical-heights cut of the side's chain, which is tight at the law of a minimal chain, + and stops when the minimizer passes separation, after ``max_cuts`` cuts, or at the side's time limit. + +A minimizer that passes separation and the coupling LP is itself the law of a generator, so the bound is then the +side's one-sided value. ``certified`` also needs SCIP to have solved that master (to optimality or to its relative +gap of :math:`10^{-7}`) and the minimizer's entropy to come within :math:`10^{-6}` of the bound; a master stopped at +its time limit gives a valid bound and no certificate. The relaxation, the separation, the cell merge, the chord +refinement, the certificate and the heights cut are not from the literature. + +The masters are numerically delicate. SCIP's spatial branch and bound on the logarithm itself +:cite:`Vigerske2018` returned bounds above the entropy of a known generator on 13 of 406 three-state sides of binary +3-state processes, by 0.09 to 1.86 bits on 6 of them (certifying one) and by :math:`1.8 \times 10^{-6}` to +:math:`2.6 \times 10^{-5}` on 7, and called the master infeasible on 3 more; the chords replace it. Creases that +converge on a vertex leave cells as thin as :math:`10^{-7}` there, which are kept (without them the master loses the +vertex's atom) and on which SCIP's LP can fail. A failed round is solved again without the linear shortcut for the +cut terms, then with SCIP's numerics emphasis and the feasibility tolerance relaxed to :math:`10^{-8}` and to +:math:`10^{-7}`, which only relaxes the master; after that the master keeps its last solved round, and a master with +none stops the loop at the best bound so far. A master that SCIP calls infeasible counts as failed: the side's +ε-machine passes every valid cut. + +With 30 cuts and 120 s per side, no bound on those 406 sides rose above the entropy of the known generator (the +largest difference is :math:`-6 \cdot 10^{-9}`); 2 sides were certified, 10 came within :math:`10^{-6}`, and the +median bound is 0.88 of the value. Of 133 open brackets on :math:`C_g` of small ε-machines, 66 have at most three +causal states on both sides; there the bound raised the lower end of 3 and closed one, certified on both sides. On +30 two-state processes, 600 s per side certified 5. + +The pipeline runs it with ``strassen_bound=True``, right after the simplex-chain search and seeded with its chains, +with a quarter of the remaining budget (30 s per side without one) and at most 30 cuts per side. The bounds go to +``strassen_lower`` and ``strassen_certified`` per side and into the reliability summary, and never into ``lower``: +they bound :math:`C_g` only if some minimal generator is reverse- or forward-sufficient, which is open. The stage is +skipped, and the log says why, on truncated and exploding builds (where it would bound the truncation), for the +Wyner objective, and without PySCIPOpt. + API === @@ -580,6 +636,8 @@ Coupled generators and bounds .. autoclass:: sofic.generators.global_bound.GlobalBoundResult .. autofunction:: sofic.generators.global_bound.separating_global_bound .. autoclass:: sofic.generators.global_bound.SeparatingBoundResult +.. autofunction:: sofic.generators.strassen_bound.strassen_lower_bound +.. autoclass:: sofic.generators.strassen_bound.StrassenBoundResult .. autoclass:: sofic.generators.generative_search.GenerativeModelResult :members: certified, gap, g_optima_generate .. autofunction:: sofic.generators.coverage_bound.coverage_entropy_lower diff --git a/docs/references.bib b/docs/references.bib index 339cf00..bcf98cb 100644 --- a/docs/references.bib +++ b/docs/references.bib @@ -1955,3 +1955,14 @@ @inproceedings{Maher2016 year = {2016}, doi = {10.1007/978-3-319-42432-3_37}, } + +@inproceedings{Beale1970, + author = {Beale, E. M. L. and Tomlin, J. A.}, + title = {Special Facilities in a General Mathematical Programming System for Non-Convex Problems Using Ordered Sets of Variables}, + booktitle = {Proceedings of the Fifth International Conference on Operational Research}, + editor = {Lawrence, J.}, + pages = {447--454}, + publisher = {Tavistock Publications}, + address = {London}, + year = {1970}, +} diff --git a/sofic/generators/generative_search.py b/sofic/generators/generative_search.py index 967e99c..0f0a020 100644 --- a/sofic/generators/generative_search.py +++ b/sofic/generators/generative_search.py @@ -50,13 +50,20 @@ :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. +7. *Strassen bound* (opt-in, ``strassen_bound``; runs right after the simplex-chain search, with a quarter of the + remaining budget, or 30 s per side without one). On each side with at most three causal states, SCIP's lower + bound on the state entropy of the generators sufficient on that side, with any number of states + (:func:`~sofic.generators.strassen_bound.strassen_lower_bound`, seeded with the side's chain), is reported as + ``strassen_lower``, and ``strassen_certified`` when it meets that side's least value. It is not part of ``lower``: + it bounds :math:`C_g` only if some minimal generator is one-sided. *Truncated builds.* When the reverse ε-machine is infinite, the bidirectional machine is a finite truncation (``bidir_class`` ``"truncated"`` in the build stage, for bidirectional input as well). Its generators are word-verified against the forward machine, so ``upper`` holds for the process, but the lower bounds computed on it bound the truncation. :func:`generative_model` skips those stages (the excess entropy, stage 1, SCIP's dual bound on -the exact path, the heaviest-term bounds and the restricted global bound's) and reports the larger future-window -generator coverage bound at :math:`L = 2` and 3 (:func:`~sofic.generators.generator_problem_spec.window_spec`), a +the exact path, the heaviest-term bounds, the restricted global bound and the Strassen bound) and reports the larger +future-window generator coverage bound at :math:`L = 2` and 3 +(:func:`~sofic.generators.generator_problem_spec.window_spec`), a lower bound on :math:`C_g` :cite:`LohrAy2009` that needs only the forward machine, computed first with at most 30% of the budget. With a budget the searches then stop a fifth of it early, and a bracket still open gets a second pass with the time left: the branch and bound of the length with the larger bound resumes from its open boxes for ten @@ -125,7 +132,7 @@ support_bound_states, theorem_generator, ) -from sofic.generators.simplex_chains import simplex_chain_search +from sofic.generators.simplex_chains import SimplexChainResult, simplex_chain_search from sofic.graph import ATTR_EMISSION, ATTR_PROB, TransitionGraph _MAX_RECTANGLES = 7 @@ -184,6 +191,10 @@ # Seconds per side of the simplex-chain search when there is no budget (on the 3-state archive half the final # generators came within 0.6 s and 90% within 8 s); with one, the search gets a quarter of what is left. _SIMPLEX_CHAIN_SECONDS = 2.0 +# The Strassen bound adds at most this many cuts per side, and gets this many seconds per side when there is no +# budget; with one, it gets a quarter of what is left. +_STRASSEN_CUTS = 30 +_STRASSEN_SECONDS = 30.0 def _entropy(p: np.ndarray) -> float: @@ -221,6 +232,13 @@ class GenerativeModelResult: 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``, 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)`. + + ``strassen_lower`` (set by the opt-in ``strassen_bound`` stage) maps each side (``"reverse"``, ``"forward"``) to a + lower bound on the state entropy of the generators that are sufficient on that side, with any number of states + (:func:`~sofic.generators.strassen_bound.strassen_lower_bound`), and ``strassen_certified`` says whether the side's + bound is that side's least value (to 1e-6). Sides with more than three causal states are left out. The bounds are + numerical, and not part of ``lower`` or ``certified``: they bound :math:`C_g` only if some minimal generator is + one-sided, which is open. """ model: CoupledGenerativeModel @@ -243,6 +261,8 @@ class GenerativeModelResult: decomposition: dict[str, Any] | None = None restricted_lower: float | None = None restricted_states: int | None = None + strassen_lower: dict[str, float] | None = None + strassen_certified: dict[str, bool] | None = None @property def certified(self) -> bool: @@ -281,6 +301,8 @@ def _reliability_summary(result: GenerativeModelResult) -> dict[str, Any]: "structure": result.structure, "restricted_lower": result.restricted_lower, "restricted_states": result.restricted_states, + "strassen_lower": result.strassen_lower, + "strassen_certified": result.strassen_certified, } @@ -523,6 +545,7 @@ def _forward_only_result( hmm_search: bool, hmm_search_starts: int, global_bound: bool, + strassen_bound: bool, reproduction_atol: float, time_budget: float | None, rng: np.random.Generator | None, @@ -548,7 +571,11 @@ def _forward_only_result( ) for entry in window_log: log.append(entry) - for stage in (*_REVERSE_STAGES, *(("restricted global bound",) if global_bound else ())): + optional = ( + *(("restricted global bound",) if global_bound else ()), + *(("Strassen bound",) if strassen_bound else ()), + ) + for stage in (*_REVERSE_STAGES, *optional): log.append({"stage": stage, "skipped": "needs the reverse ε-machine"}) mats = symbol_matrices(forward.to_mealy()) @@ -747,6 +774,7 @@ def _bracket_search( simplex_chains: bool = True, global_bound: bool = False, global_bound_states: int | None = None, + strassen_bound: bool = False, generator_caps: int = 2, targeted: bool = True, entropy_sweep_starts: int = 80, @@ -1058,6 +1086,7 @@ def maybe_return_early() -> GenerativeModelResult | None: # the stages above share the whole budget; the ones from here to the final bound leave the reserve deadline = None if end is None else end - reserve + chains: list[SimplexChainResult] = [] if simplex_chains and "chains" in stages and not wyner and not out_of_time("simplex-chain search"): stage_deadline = share(0.25) chains = simplex_chain_search( @@ -1079,6 +1108,39 @@ def maybe_return_early() -> GenerativeModelResult | None: if early is not None and early.certified: return _finalize_result(early) + strassen_lower: dict[str, float] | None = None + strassen_certified: dict[str, bool] | None = None + if strassen_bound and (wyner or truncated): + reason = "it bounds the state entropy" if wyner else "the bidirectional machine is a truncation" + log.append({"stage": "Strassen bound", "skipped": reason}) + elif strassen_bound and not out_of_time("Strassen bound"): + from sofic.generators.strassen_bound import strassen_lower_bound + + stage_deadline = share(0.25) + try: + bounds = strassen_lower_bound( + problem, + chains=chains, + max_cuts=_STRASSEN_CUTS, + seconds=_STRASSEN_SECONDS if stage_deadline is None else math.inf, + deadline=stage_deadline, + ) + except ImportError as exc: + log.append({"stage": "Strassen bound", "skipped": str(exc)}) + else: + strassen_lower = {b.side: b.lower for b in bounds} + strassen_certified = {b.side: b.certified for b in bounds} + log.append( + { + "stage": "Strassen bound", + "lower": strassen_lower, + "certified": strassen_certified, + "cuts": {b.side: b.cuts for b in bounds}, + "stop": {b.side: b.stop for b in bounds}, + "skipped sides": [side for side in ("reverse", "forward") if side not in strassen_lower], + } + ) + kappa_plus = kappa[0] if kappa is not None else math.inf if ( not wyner @@ -1484,6 +1546,7 @@ def maybe_return_early() -> GenerativeModelResult | None: if result is None: raise StochasticValidationError(f"{objective} generator search: no candidate reproduced the source process") result.restricted_lower, result.restricted_states = restricted_lower, restricted_states + result.strassen_lower, result.strassen_certified = strassen_lower, strassen_certified # last, so it aims at the verified upper bound and gets the whole remaining budget deadline = end max_dims = _HEAVIEST_TERM_MAX_DIMS if deadline is None else _GENERATOR_HEAVIEST_TERM_MAX_DIMS @@ -1559,6 +1622,7 @@ def generative_model_from_bidirectional( simplex_chains: bool = True, global_bound: bool = False, global_bound_states: int | None = None, + strassen_bound: bool = False, generator_caps: int = 2, targeted: bool = True, entropy_sweep_starts: int = 80, @@ -1576,8 +1640,10 @@ def generative_model_from_bidirectional( ``global_bound`` (needs PySCIPOpt, ``pip install sofic[global]``) adds the restricted global bound for 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. The lower bounds are computed on ``bidir``, so on a truncation they - bound the truncation, not the process; :func:`generative_model` handles that case. + minimal generators can need more states. ``strassen_bound`` (also PySCIPOpt) adds the Strassen bound on + one-sided generators of every size, reported per side as ``strassen_lower`` and ``strassen_certified``. The lower + bounds are computed on ``bidir``, so on a truncation they bound the truncation, not the process; + :func:`generative_model` handles that case. """ return _bracket_search( bidir, @@ -1601,6 +1667,7 @@ def generative_model_from_bidirectional( simplex_chains=simplex_chains, global_bound=global_bound, global_bound_states=global_bound_states, + strassen_bound=strassen_bound, generator_caps=generator_caps, targeted=targeted, entropy_sweep_starts=entropy_sweep_starts, @@ -1704,6 +1771,7 @@ def generative_model( simplex_chains: bool = True, global_bound: bool = False, global_bound_states: int | None = None, + strassen_bound: bool = False, generator_caps: int = 2, targeted: bool = True, entropy_sweep_starts: int = 80, @@ -1740,7 +1808,8 @@ def generative_model( still overrun by those. The bidirectional build counts against the budget: the first build stops at half of it, which counts as an explosion, and the retry ladder stops at the end of it (see :func:`~sofic.generators.bidirectional_build.try_build_bidirectional`). - ``global_bound`` and ``global_bound_states`` are as in :func:`generative_model_from_bidirectional`. + ``global_bound``, ``global_bound_states`` and ``strassen_bound`` are as in + :func:`generative_model_from_bidirectional`. """ start = time.monotonic() try: @@ -1756,6 +1825,7 @@ def generative_model( hmm_search=hmm_search, hmm_search_starts=hmm_search_starts, global_bound=global_bound, + strassen_bound=strassen_bound, reproduction_atol=reproduction_atol, time_budget=None if time_budget is None else max(0.0, time_budget - (time.monotonic() - start)), rng=rng, @@ -1793,6 +1863,7 @@ def generative_model( simplex_chains=simplex_chains, global_bound=global_bound, global_bound_states=global_bound_states, + strassen_bound=strassen_bound, generator_caps=generator_caps, targeted=targeted, entropy_sweep_starts=entropy_sweep_starts, diff --git a/sofic/generators/strassen_bound.py b/sofic/generators/strassen_bound.py new file mode 100644 index 0000000..935de6d --- /dev/null +++ b/sofic/generators/strassen_bound.py @@ -0,0 +1,602 @@ +r"""Strassen relaxation: a lower bound on the state entropy of one-sided generators with any number of states. + +A reverse-sufficient generator is a finitely supported law :math:`\mu` on the simplex :math:`\Delta(S^-)` of beliefs +over the reverse causal states (:mod:`~sofic.generators.simplex_chains`). After a symbol :math:`x`, emitted with +probability :math:`m_x(y) = (y P_x) \mathbf{1}`, a belief :math:`y` moves to :math:`f_x(y) = y P_x / m_x(y)`, and the +generator reproduces the process exactly when each target is the barycenter of its successors. So :math:`\mu` +dominates its image :math:`\Phi(\mu) = \sum_x m_x \, (f_x)_\# \mu` in convex order, which by Strassen's theorem +:cite:`Strassen1965` is the existence of a martingale coupling of the two. For a concave :math:`U` on the simplex, +Jensen's inequality on the split of each target gives + +.. math:: + + \int (\mathcal{B} U - U) \, d\mu \ge 0, \qquad \mathcal{B} U(y) = \sum_x m_x(y) \, U(f_x(y)). + +A *cut* is a concave piecewise-linear :math:`U(y) = \min_k (A_k \cdot y + b_k)`, written in homogeneous form so that +:math:`\mathcal{B} U(y) = \sum_x U(y P_x)`. The least entropy :math:`\H{\mu}` over laws with mean :math:`p(S^-)` that +pass a set of cuts bounds from below the state entropy of every reverse-sufficient generator, whatever its number of +states. :func:`strassen_lower_bound` computes it by cutting planes: + +* the *master problem* puts one atom in each cell of the cuts' common refinement, on which every cut is affine. + Merging the atoms of a cell keeps every cut (:math:`U` is affine there and :math:`\mathcal{B} U` superadditive) and + lowers the entropy, so these laws reach the relaxation's minimum. Each atom's term :math:`-w_C \log_2 w_C` is + replaced by its chords on a grid of masses, which lie below it because it is concave, so the master is a + mixed-integer linear program with an SOS2 constraint per cell :cite:`Beale1970`; SCIP :cite:`Achterberg2009`, + through PySCIPOpt :cite:`Maher2016`, solves it, and its dual bound is a lower bound. Each cell's grid gains the + minimizer's mass until the chords meet the entropy there (to ``1e-9`` in all). SCIP's spatial branch and bound on + the logarithm itself proved optima above the relaxation's on some triangle sides; +* *separation* returns a cut that the master's minimizer fails: on the segment (two reverse causal states) the most + violated hinge :math:`-(y_0 - t)_+`, which decides convex order there; on the triangle the most violated ridge + :math:`-(d \cdot y - t)_+` over 180 directions, then the Farkas dual of the martingale-coupling LP; +* the *certificate*: a minimizer that passes separation and the coupling LP is itself the law of a generator, so the + bound is the one-sided value. ``certified`` also needs SCIP to have solved that master (to optimality or to its + relative gap limit of ``1e-7``) and the minimizer's entropy to come within ``1e-6`` of the bound; a master stopped + at its time limit still gives a valid bound, but no certificate. + +Each side starts from the canonical-heights cut of a known chain (from +:func:`~sofic.generators.simplex_chains.simplex_chain_search`), which is tight at the law of a minimal chain. +Forward-sufficient generators are the mirror image on :math:`\Delta(S^+)`, in reversed time. + +Under the one-sided reduction (every minimal generator is reverse- or forward-sufficient), the smaller of the two +sides' bounds is a lower bound on the generative complexity :math:`C_g`. The reduction is open in general, so +:func:`~sofic.generators.generative_search.generative_model` reports the bounds beside its ``lower`` and never in it. +The relaxation, the separation, the cell merge, the chord refinement, the certificate and the heights cut are not from +the literature. The cells are clipped as polygons, so sides with more than three causal states are skipped. The bound +is numerical: SCIP and HiGHS work to their own tolerances. PySCIPOpt is an optional dependency +(``pip install sofic[global]``). +""" + +from __future__ import annotations + +import math +import time +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Any + +import numpy as np +from scipy.optimize import linprog +from scipy.sparse import coo_matrix + +from sofic.generators.bidirectional_epsilon_machine import BidirectionalEpsilonMachine +from sofic.generators.coupled_generators import _GeneratorProblem +from sofic.generators.simplex_chains import SimplexChainResult, _entropy, _Side, _sides + +__all__ = ["StrassenBoundResult", "strassen_lower_bound"] + +# Sides with more causal states are skipped: the cells of the master are clipped as polygons. +_MAX_STATES = 3 +# A law fails separation when some cut's integral is below -_SEP_TOL. +_SEP_TOL = 1e-8 +# Each master's attempts after an LP error: (shortcut, SCIP's feasibility tolerance, numerics emphasis). +_ATTEMPTS = ((True, 1e-9, False), (False, 1e-9, False), (False, 1e-8, True), (False, 1e-7, True)) +# SCIP's relative gap on each master. +_GAP = 1e-7 +# The masses where each cell's chords of -w log2 w start, and how far below the entropy they may stay at the minimizer. +_GRID = (0.0, 0.01, 0.1, 0.25, 0.5, 0.75, 1.0) +_CHORD_TOL = 1e-9 +# A certified minimizer's entropy is within this of the bound, on a master SCIP solved (to its gap limit at most). +_CERT_TOL = 1e-6 +_SOLVED = ("optimal", "gaplimit") +# Ridge directions tried on the triangle before the coupling LP's Farkas cut. +_DIRECTIONS = 180 + + +@dataclass(frozen=True) +class StrassenBoundResult: + """Outcome of :func:`strassen_lower_bound` on one side. + + ``lower`` bounds the state entropy of every generator that is sufficient on ``side`` (``"reverse"``: each + generator state's future is the mixture of the reverse causal states' futures under its belief; ``"forward"``: the + mirror image), whatever its number of states. It is the best SCIP dual bound over the masters solved. + ``certified`` is set when SCIP solved the last master (status ``"optimal"``, or ``"gaplimit"`` at its relative gap + of ``1e-7``), its minimizer passed separation and the martingale-coupling LP, and the minimizer's entropy + ``value`` came within ``1e-6`` of ``lower``; the side's + one-sided value then lies in ``[lower, value]``. ``atoms`` and ``weights`` describe that minimizer (``None`` when + no master returned a solution). ``cuts`` counts the cuts in the last master, ``stop`` says why the loop ended + (``"passes separation"``, ``"cut cap"``, ``"time"``, ``"repeated cut"``, ``"SCIP error"`` or ``"no solution"``), + ``status`` is SCIP's status on the last master, and ``log`` has one entry per master. + """ + + side: str + lower: float + certified: bool + value: float | None + cuts: int + stop: str + status: str + seconds: float + atoms: np.ndarray | None + weights: np.ndarray | None + log: tuple[dict[str, Any], ...] + + +def _pyscipopt() -> Any: + try: + import pyscipopt + except ImportError as exc: + raise ImportError("strassen_lower_bound needs PySCIPOpt; install it with `pip install sofic[global]`") from exc + return pyscipopt + + +# --- cuts --------------------------------------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class _Cut: + """``U(y) = min_k (A[k] . y + b[k] (1 . y))``, concave and piecewise linear; homogeneous, so ``BU`` is a sum.""" + + A: np.ndarray + b: np.ndarray + kind: str = "lp" + + def U(self, Y: np.ndarray) -> np.ndarray: + Y = np.atleast_2d(np.asarray(Y, dtype=float)) + return np.min(Y @ self.A.T + np.outer(Y.sum(axis=1), self.b), axis=1) + + def BU(self, P: np.ndarray, Y: np.ndarray) -> np.ndarray: + Y = np.atleast_2d(np.asarray(Y, dtype=float)) + return np.sum([self.U(Y @ P[x]) for x in range(P.shape[0])], axis=0) + + def gain(self, P: np.ndarray, S: np.ndarray, w: np.ndarray) -> float: + """The integral of ``BU - U`` against the law; negative when the law fails the cut.""" + return float(np.asarray(w, dtype=float) @ (self.BU(P, S) - self.U(S))) + + +def _ridge(d: np.ndarray, t: float, kind: str = "ridge") -> _Cut: + """``U(y) = -(d . y - t)_+ = min(0, t - d . y)`` on the simplex.""" + d = np.asarray(d, dtype=float) + return _Cut(np.vstack([np.zeros_like(d), -d]), np.array([0.0, float(t)]), kind) + + +def _hinge(t: float) -> _Cut: + """The hinge with crease ``t`` on the segment: ``-(y_0 - t)_+`` for ``t >= 1/2`` and ``-(t - y_0)_+`` below. The + two differ by an affine function, which every law with the mean passes with equality, and this one keeps its terms + of size ``min(t, 1 - t)``.""" + if t >= 0.5: + return _ridge(np.array([1.0, 0.0]), t, "hinge") + return _ridge(np.array([-1.0, 0.0]), -t, "hinge") + + +def _prune(cut: _Cut, points: np.ndarray, tol: float = 1e-12) -> _Cut: + """Drop the pieces that are least at none of the points.""" + V = points @ cut.A.T + np.outer(points.sum(axis=1), cut.b) + keep = np.flatnonzero((V.min(axis=1, keepdims=True) + tol >= V).any(axis=0)) + return _Cut(cut.A[keep], cut.b[keep], cut.kind) + + +def _same_crease(a: _Cut, b: _Cut, tol: float = 1e-9) -> bool: + """Two ridges with the same crease, which a correct master never asks for twice.""" + if len(a.b) != 2 or len(b.b) != 2 or "lp" in (a.kind, b.kind) or a.A.shape != b.A.shape: + return False + return bool(np.abs(a.A - b.A).max() < tol and abs(a.b[1] - b.b[1]) < tol) + + +# --- separation --------------------------------------------------------------------------------------------------- + + +def _push(P: np.ndarray, S: np.ndarray, w: np.ndarray, tol: float = 1e-12) -> tuple[np.ndarray, np.ndarray]: + """Atoms ``(Y, nu)`` of the image law for the law with atoms ``S`` and weights ``w``.""" + Y, nu = [], [] + for s, wi in zip(S, w, strict=True): + if wi <= 0: + continue + for x in range(P.shape[0]): + z = s @ P[x] + mass = float(z.sum()) + if mass > tol: + Y.append(z / mass) + nu.append(wi * mass) + return np.array(Y, dtype=float).reshape(-1, S.shape[1]), np.array(nu, dtype=float) + + +def _coupling_feasible(P: np.ndarray, S: np.ndarray, w: np.ndarray) -> bool: + """Whether a martingale coupling carries the image law onto the law: each target split onto the atoms with the + target as its barycenter, and each atom receiving its weight.""" + Y, nu = _push(P, S, w) + K, N, m = len(Y), len(S), S.shape[1] + rows, cols, vals, rhs = [], [], [], [] + r = 0 + for k in range(K): + for c in range(-1, m): + rows += [r] * N + cols += range(k * N, (k + 1) * N) + vals += [1.0] * N if c < 0 else list(S[:, c]) + rhs.append(nu[k] if c < 0 else nu[k] * Y[k, c]) + r += 1 + for i in range(N): + rows += [r] * K + cols += range(i, K * N, N) + vals += [1.0] * K + rhs.append(float(w[i])) + r += 1 + A = coo_matrix((vals, (rows, cols)), shape=(r, K * N)).tocsr() + res = linprog(np.zeros(K * N), A_eq=A, b_eq=np.array(rhs), bounds=(0, None), method="highs") + return res.status == 0 + + +def _separate_lp(P: np.ndarray, S: np.ndarray, w: np.ndarray, tol: float = _SEP_TOL) -> _Cut | None: + """The cut from the Farkas dual of the coupling LP (one piece per target, pruned), or ``None`` if the law passes.""" + Y, nu = _push(P, S, w) + K, N, m = len(Y), len(S), S.shape[1] + n_var = K + K * m + N + c = np.concatenate([nu, (nu[:, None] * Y).ravel(), np.asarray(w, dtype=float)]) + rows, cols, vals = [], [], [] + row = 0 + for k in range(K): + for i in range(N): + rows += [row] * (m + 2) + cols += [k, *range(K + k * m, K + (k + 1) * m), K + K * m + i] + vals += [-1.0, *(-S[i]), -1.0] + row += 1 + A_ub = coo_matrix((vals, (rows, cols)), shape=(row, n_var)).tocsr() + res = linprog(c, A_ub=A_ub, b_ub=np.zeros(row), bounds=(-1, 1), method="highs") + if res.status != 0 or res.fun >= -tol: + return None + return _prune(_Cut(res.x[K : K + K * m].reshape(K, m), res.x[:K], "lp"), np.vstack([S, Y])) + + +def _projected_test(a: np.ndarray, wa: np.ndarray, b: np.ndarray, wb: np.ndarray) -> tuple[float, float]: + """The least ``D(t) = int (y - t)_+ da - int (y - t)_+ db`` over ``t`` for one-dimensional laws with equal means, + and its ``t``: ``D`` is piecewise linear with breakpoints at the atoms.""" + ts = np.unique(np.concatenate([a, b])) + D = np.maximum(a[None, :] - ts[:, None], 0.0) @ wa - np.maximum(b[None, :] - ts[:, None], 0.0) @ wb + j = int(np.argmin(D)) + return float(D[j]), float(ts[j]) + + +def _directions(m: int) -> list[np.ndarray]: + if m <= 2: + return [np.eye(m)[0]] + basis = np.linalg.svd(np.eye(m) - 1.0 / m)[0][:, : m - 1] + angles = np.linspace(0.0, 2 * np.pi, _DIRECTIONS, endpoint=False) + return [basis @ np.array([math.cos(t), math.sin(t)]) for t in angles] + + +def _separate(P: np.ndarray, S: np.ndarray, w: np.ndarray, tol: float = _SEP_TOL) -> _Cut | None: + """A cut the law fails, or ``None``: the most violated hinge on the segment, which decides convex order there; + on the triangle the most violated ridge over the sampled directions, then the coupling LP's Farkas cut.""" + Y, nu = _push(P, S, w) + m = S.shape[1] + best: tuple[float, np.ndarray | None, float] = (0.0, None, 0.0) + for d in _directions(m): + value, t = _projected_test(S @ d, np.asarray(w, dtype=float), Y @ d, nu) + if value < best[0]: + best = (value, d, t) + if best[0] < -tol and best[1] is not None: + return _hinge(best[2]) if m == 2 else _ridge(best[1], best[2]) + return None if m <= 2 else _separate_lp(P, S, w, tol) + + +def _heights_cut(P: np.ndarray, S: np.ndarray, pi: np.ndarray, T: np.ndarray) -> _Cut | None: + """The cut of the canonical heights ``h = -Z g`` of a chain (``Z`` its fundamental matrix, ``g`` the entropy's + gradient at ``pi``): the least of the planes above the lifted atoms ``(S_i, h_i)``, one supporting each atom and + each target. It is tight at ``pi`` when ``pi`` is a minimal chain's law.""" + N = len(S) + M = T.sum(axis=0) + g = -(np.log2(pi) + 1.0 / math.log(2.0)) + h = -(np.linalg.inv(np.eye(N) - M + np.outer(np.ones(N), pi)) @ g) + points = list(S) + for s in S: + for x in range(P.shape[0]): + z = s @ P[x] + if z.sum() > 1e-12: + points.append(z / z.sum()) + planes = [] + for z in points: + res = linprog(z, A_ub=-S, b_ub=-h, bounds=(None, None), method="highs") + if res.status == 0: + planes.append(res.x) + if not planes: + return None + A = np.unique(np.round(np.array(planes), 12), axis=0) + # less a linear function and scaled, the cut is the same constraint on laws with the mean; slopes of size 1 keep + # SCIP's LPs conditioned like the hinges' (the raw heights made them fail) + A = A - A.mean(axis=0) + A = A / max(float(np.abs(A).max()), 1e-12) + return _prune(_Cut(A, np.zeros(len(A)), "heights"), np.array(points), tol=1e-10) + + +# --- cells and the master problem --------------------------------------------------------------------------------- + + +def _clip(poly: np.ndarray, g: np.ndarray, tol: float = 1e-13) -> np.ndarray: + """The part of a convex polygon (vertex rows in cyclic order, points of the simplex) where ``g . y <= 0``.""" + out = [] + n = len(poly) + for i in range(n): + a, b = poly[i], poly[(i + 1) % n] + ga, gb = float(g @ a), float(g @ b) + if ga <= tol: + out.append(a) + if (ga < -tol and gb > tol) or (ga > tol and gb < -tol): + out.append(a + (b - a) * (ga / (ga - gb))) + unique: list[np.ndarray] = [] + for v in out: + if not any(np.abs(v - u).max() < 1e-12 for u in unique): + unique.append(v) + return np.array(unique).reshape(-1, poly.shape[1]) + + +def _size(poly: np.ndarray) -> float: + if len(poly) < poly.shape[1]: + return 0.0 + if poly.shape[1] == 2: + return float(poly[:, 0].max() - poly[:, 0].min()) + Q = poly[:, 1:] - poly[0, 1:] + return float(0.5 * abs(sum(Q[i, 0] * Q[i + 1, 1] - Q[i + 1, 0] * Q[i, 1] for i in range(len(Q) - 1)))) + + +def _refine( + cells: list[tuple[np.ndarray, dict[int, int]]], cut: _Cut, j: int +) -> list[tuple[np.ndarray, dict[int, int]]]: + """Split every cell (vertices, {cut index: piece}) so that cut ``j`` is affine on each part. A part is kept however + thin: a crease that passes near a vertex leaves a sliver there, and without it the master loses the vertex atom.""" + out = [] + for V, active in cells: + values = V @ cut.A.T + cut.b[None, :] + common = np.flatnonzero((values <= values.min(axis=1, keepdims=True) + 1e-13).all(axis=0)) + if len(common): + out.append((V, {**active, j: int(common[0])})) + continue + for k in range(len(cut.b)): + poly = V + for k2 in range(len(cut.b)): + if k2 != k and len(poly): + poly = _clip(poly, (cut.A[k] - cut.A[k2]) + (cut.b[k] - cut.b[k2])) + if len(poly) and _size(poly) > 0.0: + out.append((poly, {**active, j: k})) + return out + + +def _cells(m: int, cuts: Sequence[_Cut]) -> list[tuple[np.ndarray, dict[int, int]]]: + cells: list[tuple[np.ndarray, dict[int, int]]] = [(np.eye(m), {})] + for j, cut in enumerate(cuts): + cells = _refine(cells, cut, j) + return cells + + +def _entropy_term(w: float) -> float: + """``-w log2 w``, zero at zero.""" + return -w * math.log2(w) if w > 0 else 0.0 + + +def _master_model( + scip: Any, + P: np.ndarray, + p: np.ndarray, + cuts: Sequence[_Cut], + cells: list[tuple[np.ndarray, dict[int, int]]], + grids: list[list[float]], + *, + shortcut: bool, + feastol: float, + numerics: bool, + time_limit: float, +) -> tuple[Any, list[list[Any]]]: + """The master's SOS2 program on the cells, with each cell's entropy term replaced by its chords on that cell's + grid; returns the model and the weights of the cells' corners.""" + m, X = len(p), P.shape[0] + model = scip.Model() + model.hideOutput() + model.setParam("numerics/feastol", feastol) + model.setParam("limits/gap", _GAP) + model.setParam("limits/time", min(max(float(time_limit), 0.1), 1e20)) + if numerics: + model.setEmphasis(scip.SCIP_PARAMEMPHASIS.NUMERICS) + quicksum = scip.quicksum + lam = [[model.addVar(lb=0, ub=1) for _ in range(len(V))] for V, _ in cells] + for c in range(m): + mean = quicksum(float(V[r, c]) * lam[C][r] for C, (V, _) in enumerate(cells) for r in range(len(V))) + model.addCons(mean == float(p[c])) + chords = [] + for row, grid in zip(lam, grids, strict=True): + mu = [model.addVar(lb=0, ub=1) for _ in grid] + model.addCons(quicksum(mu) == 1) + model.addCons(quicksum(row) == quicksum(g * v for g, v in zip(grid, mu, strict=True))) + model.addConsSOS2(mu) + chords += [_entropy_term(g) * v for g, v in zip(grid, mu, strict=True)] + images = [[V @ P[x] for x in range(X)] for V, _ in cells] + for j, cut in enumerate(cuts): + A, b = cut.A, cut.b + big = float(np.abs(A + b[:, None]).max()) + 1e-9 + terms = [] + for C, (V, active) in enumerate(cells): + k0 = active[j] + terms.append(-quicksum((float(A[k0] @ V[r]) + float(b[k0])) * lam[C][r] for r in range(len(V)))) + for x in range(X): + Z = images[C][x] + if not Z.any(): + continue + coefs = Z @ A.T + np.outer(Z.sum(axis=1), b) + common = np.flatnonzero((coefs <= coefs.min(axis=1, keepdims=True) + 1e-13).all(axis=0)) + if shortcut and len(common): + k = int(common[0]) + terms.append(quicksum(float(coefs[r, k]) * lam[C][r] for r in range(len(V)))) + continue + t = model.addVar(lb=-big, ub=big) + for k in range(len(b)): + model.addCons(t <= quicksum(float(coefs[r, k]) * lam[C][r] for r in range(len(V)))) + terms.append(t) + model.addCons(quicksum(terms) >= 0) + model.setObjective(quicksum(chords), "minimize") + return model, lam + + +def _master( + P: np.ndarray, + p: np.ndarray, + cuts: Sequence[_Cut], + *, + time_limit: float, +) -> dict[str, Any]: + """The least entropy over laws with one atom per cell, mean ``p`` and every cut passed, by SCIP. + + Each round solves the SOS2 program on the chords and adds each cell's mass in the minimizer to its grid, until the + chords meet the entropy at the minimizer to ``_CHORD_TOL``; every round's dual bound is a lower bound. With the + shortcut, a pushforward term is one linear expression when one piece of the cut is least at the images of all the + cell's corners (then it is least on the whole image); otherwise, and always without it, a variable below every + piece. A round that fails, with an LP error or with an infeasible verdict (a numerical failure: the side's + ε-machine law passes every valid cut), is solved again in the time left with the next settings in ``_ATTEMPTS``, + which the later rounds keep: without the shortcut, then with SCIP's numerics emphasis and the feasibility + tolerance relaxed to 1e-8 and to 1e-7. When they run out, the master keeps its last solved round, if any. + """ + scip = _pyscipopt() + cells = _cells(len(p), cuts) + grids = [list(_GRID) for _ in cells] + start = time.monotonic() + out: dict[str, Any] = {"status": "unsolved", "dual": -math.inf, "cells": len(cells), "seconds": 0.0} + attempt = 0 + while True: + left = time_limit - (time.monotonic() - start) + if left <= 0 and "atoms" in out: + break + shortcut, feastol, numerics = _ATTEMPTS[attempt] + model, lam = _master_model( + scip, P, p, cuts, cells, grids, shortcut=shortcut, feastol=feastol, numerics=numerics, time_limit=left + ) + try: + model.optimize() + failure = "SCIP: the master is infeasible" if model.getStatus() in ("infeasible", "inforunbd") else None + except Exception as exc: # noqa: BLE001 - SCIP raises a plain Exception on an LP error + failure = str(exc) + if failure is not None: + if attempt + 1 < len(_ATTEMPTS) and time.monotonic() - start < time_limit: + attempt += 1 + continue + if "atoms" in out: + break + return {"status": f"error: {failure}"[:200], "dual": -math.inf, "cells": len(cells), "seconds": 0.0} + status = str(model.getStatus()) + dual = max(out["dual"], float(model.getDualbound())) + out.update(status=status, dual=dual, seconds=time.monotonic() - start) + if model.getNSols() == 0: + break + sol = model.getBestSol() + lams = [np.array([model.getSolVal(sol, v) for v in row]) for row in lam] + W = np.clip([lc.sum() for lc in lams], 0.0, 1.0) + atoms = np.array([lc @ V for lc, (V, _) in zip(lams, cells, strict=True)]) + keep = W > 1e-11 + S = np.clip(atoms[keep], 0.0, None) + S /= S.sum(axis=1, keepdims=True) + weights = W[keep] / W[keep].sum() + out.update(atoms=S, weights=weights, primal=_entropy(weights)) + gaps = [ + _entropy_term(w) - np.interp(w, g, [_entropy_term(x) for x in g]) for w, g in zip(W, grids, strict=True) + ] + if status not in _SOLVED or sum(gaps) <= _CHORD_TOL: + break + for C, gap in enumerate(gaps): + if gap > _CHORD_TOL / len(cells): + grids[C] = sorted({*grids[C], float(W[C])}) + return out + + +# --- the loop ----------------------------------------------------------------------------------------------------- + + +def _side_chain(chain: SimplexChainResult) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """``(atoms, pi, T)`` of a chain in its side's time, ``T[x, w, v] = Pr(x, v | w)``.""" + pi, K = np.asarray(chain.pi, dtype=float), np.asarray(chain.K, dtype=float) + reverse = chain.side == "reverse" + T = K.transpose(1, 0, 2) if reverse else np.einsum("w,wxv->xvw", pi, K) / pi[None, :, None] + return np.asarray(chain.atoms, dtype=float), pi, T + + +def _bound_side( + side: _Side, p: np.ndarray, seed: _Cut | None, *, max_cuts: int, deadline: float +) -> StrassenBoundResult: + start = time.monotonic() + cuts = [] if seed is None else [seed] + lower, value, certified = -math.inf, None, False + stop, status = "cut cap", "unsolved" + S = w = None + log: list[dict[str, Any]] = [] + added = 0 + while True: + left = deadline - time.monotonic() + if left <= 0: + stop = "time" + break + res = _master(side.P, p, cuts, time_limit=left) + status = res["status"] + entry = {"cuts": len(cuts), "cells": res["cells"], "status": status, "seconds": res["seconds"]} + if status.startswith("error"): + log.append(entry) + stop = "SCIP error" + break + lower = max(lower, res["dual"]) + entry["lower"] = lower + log.append(entry) + if "atoms" not in res: + stop = "no solution" + break + S, w, value = res["atoms"], res["weights"], res["primal"] + entry["value"] = value + cut = _separate(side.P, S, w) + if cut is None: + stop = "passes separation" + certified = bool( + status in _SOLVED and value - res["dual"] <= _CERT_TOL and _coupling_feasible(side.P, S, w) + ) + break + if any(_same_crease(cut, old) for old in cuts): + stop = "repeated cut" + break + if added == max_cuts: + break + cuts.append(cut) + added += 1 + return StrassenBoundResult( + side=side.name, + lower=float(lower), + certified=certified, + value=value, + cuts=len(cuts), + stop=stop, + status=status, + seconds=time.monotonic() - start, + atoms=S, + weights=w, + log=tuple(log), + ) + + +def strassen_lower_bound( + bidir: BidirectionalEpsilonMachine | _GeneratorProblem, + *, + sides: Sequence[str] = ("reverse", "forward"), + chains: Sequence[SimplexChainResult] = (), + max_cuts: int = 30, + seconds: float = 30.0, + deadline: float | None = None, +) -> list[StrassenBoundResult]: + """Lower bounds on the state entropy of one-sided generators with any number of states, one per side in + ``sides`` with at most three causal states; see the module docstring. + + Each side gets ``seconds``, or an equal share of the time left before ``deadline`` (a :func:`time.monotonic` value) + if that is less, and every SCIP master gets the time its side has left. The loop adds at most ``max_cuts`` cuts to + the side's seed, the canonical-heights cut of the chain in ``chains`` for that side (any + :class:`~sofic.generators.simplex_chains.SimplexChainResult`; without one the loop starts from no cut). On a SCIP + error the loop stops and keeps the best bound so far. Requires PySCIPOpt (``pip install sofic[global]``). + """ + _pyscipopt() + problem = bidir if isinstance(bidir, _GeneratorProblem) else _GeneratorProblem(bidir) + by_name = _sides(problem, math.inf) + lifted = problem.lifted + todo = [name for name in sides if by_name[name].n <= _MAX_STATES] + out = [] + for i, name in enumerate(todo): + side = by_name[name] + now = time.monotonic() + budget = seconds if deadline is None else min(seconds, max(0.0, deadline - now) / (len(todo) - i)) + p = np.asarray((lifted.minus if name == "reverse" else lifted.plus).T @ lifted.p, dtype=float) + seed = None + chain = next((c for c in chains if c.side == name), None) + if chain is not None: + try: + seed = _heights_cut(side.P, *_side_chain(chain)) + except np.linalg.LinAlgError: + seed = None + out.append(_bound_side(side, p, seed, max_cuts=max_cuts, deadline=now + budget)) + return out diff --git a/tests/test_strassen_bound.py b/tests/test_strassen_bound.py new file mode 100644 index 0000000..5e785ec --- /dev/null +++ b/tests/test_strassen_bound.py @@ -0,0 +1,456 @@ +"""Tests for the Strassen bound on one-sided generators with any number of states.""" + +from __future__ import annotations + +import functools +import math +import types + +import numpy as np +import pytest +from hypothesis import HealthCheck, given, settings +from hypothesis import strategies as st +from scipy.optimize import linprog + +from sofic.examples import golden_mean, golden_mean_bidirectional +from sofic.examples.epsilon_machines import from_symbol_matrices +from sofic.generators import generative_search as gs +from sofic.generators import simplex_chains as sc +from sofic.generators import strassen_bound as sb +from sofic.generators.bidirectional_epsilon_machine import BidirectionalEpsilonMachine +from sofic.generators.coupled_generators import _GeneratorProblem + +_SETTINGS = settings(max_examples=25, deadline=None, suppress_health_check=[HealthCheck.too_slow]) + +# Least entropy of the event-set chains of the two-state process at (0.836, 0.788): atoms at the two vertices and at +# y_0 = 0.13388698261099127 of the reverse segment, each target split between its neighbouring atoms. +_EVENT_ATOM, _EVENT_VALUE = 0.13388698261099127, 0.15570758855065991 + + +@pytest.fixture +def scip(): + return pytest.importorskip("pyscipopt") + + +@functools.cache +def _two_state(p: float, q: float) -> _GeneratorProblem: + """Symbol 0 leads to state 0 (with probability p from state 0, q from state 1); symbol 1 swaps the states.""" + mats = {0: np.array([[p, 0.0], [q, 0.0]]), 1: np.array([[0.0, 1 - p], [1 - q, 0.0]])} + return _GeneratorProblem(BidirectionalEpsilonMachine.from_forward(from_symbol_matrices((0, 1), (0, 1), mats))) + + +@functools.cache +def _triangle() -> _GeneratorProblem: + """Binary, cryptic order 2, three causal states on each side (as in test_simplex_chains).""" + a, b = 0.9253177336700834, 0.9575640890108456 + mats = { + 0: np.array([[0.0, 0.0, 0.0], [0.0, 0.0, a], [0.0, 0.0, b]]), + 1: np.array([[0.0, 1.0, 0.0], [0.0, 1 - a, 0.0], [1 - b, 0.0, 0.0]]), + } + return _GeneratorProblem(BidirectionalEpsilonMachine.from_forward(from_symbol_matrices((0, 1, 2), (0, 1), mats))) + + +@functools.cache +def _census_triangle() -> _GeneratorProblem: + """Binary, three causal states on each side: a census process on whose reverse side SCIP's spatial branch and + bound on the logarithm proved masters above the causal states' entropy.""" + a, b = 0.20432169731535188, 0.6090977215034284 + mats = { + 0: np.array([[0.0, 0.0, 0.0], [0.0, 0.0, a], [0.0, b, 0.0]]), + 1: np.array([[0.0, 1.0, 0.0], [1 - a, 0.0, 0.0], [1 - b, 0.0, 0.0]]), + } + return _GeneratorProblem(BidirectionalEpsilonMachine.from_forward(from_symbol_matrices((0, 1, 2), (0, 1), mats))) + + +def _side(which: str, p: float = 0.836, q: float = 0.788) -> tuple[sc._Side, np.ndarray]: + """A side (``"segment"``: the reverse side of the two-state process; ``"reverse"``, ``"forward"``: the triangle's) + and the law of its causal states.""" + problem = _two_state(round(p, 3), round(q, 3)) if which == "segment" else _triangle() + name = "forward" if which == "forward" else "reverse" + lifted = problem.lifted + return sc._sides(problem, math.inf)[name], (lifted.minus if name == "reverse" else lifted.plus).T @ lifted.p + + +def _random_cut(rng: np.random.Generator, m: int, K: int) -> sb._Cut: + return sb._Cut(rng.normal(size=(K, m)), rng.normal(size=K)) + + +def _chain_law(side: sc._Side, rng: np.random.Generator, extra: int) -> tuple[np.ndarray, np.ndarray]: + """A generator law: the vertices and random atoms, each target split onto them by an LP with a random objective.""" + S = np.vstack([np.eye(side.n), rng.dirichlet(np.ones(side.n), size=extra)]) + T = np.zeros((side.n_sym, len(S), len(S))) + for i, s in enumerate(S): + for x in range(side.n_sym): + z = s @ side.P[x] + if z.sum() <= 1e-12: + continue + res = linprog(rng.random(len(S)), A_eq=S.T, b_eq=z / z.sum(), bounds=(0, None), method="highs") + T[x, i] = z.sum() * np.clip(res.x, 0, None) + pi = max(sc._stationaries(T), key=lambda v: np.count_nonzero(v > 1e-12)) + keep = pi > 1e-12 + return S[keep], pi[keep] / pi[keep].sum() + + +def _random_law(side: sc._Side, p_own: np.ndarray, rng: np.random.Generator, n: int) -> tuple[np.ndarray, np.ndarray]: + """A law with the causal states' mean on the vertices and ``n`` random atoms.""" + S = np.vstack([np.eye(side.n), rng.dirichlet(np.ones(side.n), size=n)]) + res = linprog( + rng.random(len(S)), + A_eq=np.vstack([S.T, np.ones(len(S))]), + b_eq=np.concatenate([p_own, [1.0]]), + bounds=(0, None), + method="highs", + ) + w = np.clip(res.x, 0, None) + keep = w > 1e-12 + return S[keep], w[keep] / w[keep].sum() + + +def _event_chain() -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """The event-set chain at (0.836, 0.788) on the reverse segment: (atoms, pi, T).""" + side, _ = _side("segment") + y = np.array([1.0, _EVENT_ATOM, 0.0]) + S = np.column_stack([y, 1 - y]) + T = np.zeros((side.n_sym, 3, 3)) + for i, s in enumerate(S): + for x in range(side.n_sym): + z = s @ side.P[x] + if z.sum() <= 1e-14: + continue + t = z[0] / z.sum() + j = 0 if t >= _EVENT_ATOM else 1 # the target lies between atoms j and j + 1 (y_0 decreasing) + lam = (t - y[j + 1]) / (y[j] - y[j + 1]) + T[x, i, j], T[x, i, j + 1] = z.sum() * lam, z.sum() * (1 - lam) + (pi,) = sc._stationaries(T) + return S, pi, T + + +_sides_st = st.sampled_from(["segment", "reverse", "forward"]) +_pq = st.floats(0.05, 0.95) + + +@_SETTINGS +@given(_sides_st, _pq, _pq, st.integers(0, 2**31 - 1), st.integers(1, 4)) +def test_BU_is_the_pushforward(which, p, q, seed, K): + if which == "segment" and abs(p - q) < 0.02: + return + side, _ = _side(which, p, q) + rng = np.random.default_rng(seed) + cut = _random_cut(rng, side.n, K) + for y in rng.dirichlet(np.ones(side.n), size=5): + direct = 0.0 + for x in range(side.n_sym): + z = y @ side.P[x] + if z.sum() > 1e-12: + direct += z.sum() * cut.U(z / z.sum())[0] + assert cut.BU(side.P, y)[0] == pytest.approx(direct, abs=1e-10) + + +@_SETTINGS +@given(_sides_st, _pq, _pq, st.integers(0, 2**31 - 1), st.integers(0, 4)) +def test_generator_laws_pass_every_cut(which, p, q, seed, extra): + """Jensen on each target's split for a concave cut.""" + if which == "segment" and abs(p - q) < 0.02: + return + side, p_own = _side(which, p, q) + rng = np.random.default_rng(seed) + S, pi = _chain_law(side, rng, extra) + assert np.abs(pi @ S - p_own).max() < 1e-8 + for _ in range(10): + assert _random_cut(rng, side.n, int(rng.integers(1, 6))).gain(side.P, S, pi) >= -1e-9 + assert sb._separate(side.P, S, pi) is None + assert sb._coupling_feasible(side.P, S, pi) + + +@_SETTINGS +@given(_sides_st, _pq, _pq, st.integers(0, 2**31 - 1), st.integers(1, 5)) +def test_separation_finds_a_cut_exactly_when_no_coupling_exists(which, p, q, seed, n): + if which == "segment" and abs(p - q) < 0.02: + return + side, p_own = _side(which, p, q) + S, w = _random_law(side, p_own, np.random.default_rng(seed), n) + feasible = sb._coupling_feasible(side.P, S, w) + cut = sb._separate(side.P, S, w) + if cut is not None: + assert cut.gain(side.P, S, w) < 0 + assert not feasible or cut.gain(side.P, S, w) > -1e-6 + lp = sb._separate_lp(side.P, S, w) + if lp is not None: + assert lp.gain(side.P, S, w) < 0 + if side.n == 2: # Strassen on the line: convex order is the hinge test + assert (cut is None) == feasible or abs(_hinge_test(side, S, w)) < 1e-6 + + +def _hinge_test(side: sc._Side, S: np.ndarray, w: np.ndarray) -> float: + Y, nu = sb._push(side.P, S, w) + return sb._projected_test(S[:, 0], w, Y[:, 0], nu)[0] + + +@_SETTINGS +@given(_sides_st, _pq, _pq, st.integers(0, 2**31 - 1)) +def test_merging_the_atoms_of_a_cell_keeps_every_cut(which, p, q, seed): + """On a cell every cut is affine and its pushforward superadditive, so a merged atom passes at least as well.""" + if which == "segment" and abs(p - q) < 0.02: + return + side, _ = _side(which, p, q) + rng = np.random.default_rng(seed) + cuts = [_random_cut(rng, side.n, int(rng.integers(2, 4))) for _ in range(2)] + cells = sb._cells(side.n, cuts) + V, _ = cells[int(rng.integers(len(cells)))] + a, b = rng.dirichlet(np.ones(len(V)), size=2) @ V + wa, wb = rng.random(2) + 0.1 + merged = (wa * a + wb * b) / (wa + wb) + for cut in cuts: + before = wa * (cut.BU(side.P, a)[0] - cut.U(a)[0]) + wb * (cut.BU(side.P, b)[0] - cut.U(b)[0]) + assert (wa + wb) * (cut.BU(side.P, merged)[0] - cut.U(merged)[0]) >= before - 1e-10 + + +@_SETTINGS +@given(_sides_st, _pq, _pq, st.integers(0, 2**31 - 1)) +def test_the_cells_are_the_affine_pieces_of_the_cuts(which, p, q, seed): + if which == "segment" and abs(p - q) < 0.02: + return + side, _ = _side(which, p, q) + rng = np.random.default_rng(seed) + cuts = [_random_cut(rng, side.n, int(rng.integers(1, 4))) for _ in range(3)] + cells = sb._cells(side.n, cuts) + for y in rng.dirichlet(np.ones(side.n), size=20): + for V, active in cells: + res = linprog( + np.zeros(len(V)), + A_eq=np.vstack([V.T, np.ones(len(V))]), + b_eq=np.concatenate([y, [1.0]]), + bounds=(0, None), + method="highs", + ) + if res.status == 0: + for j, cut in enumerate(cuts): + assert cut.A[active[j]] @ y + cut.b[active[j]] <= cut.U(y)[0] + 1e-9 + break + else: + pytest.fail(f"no cell holds {y}") + + +@pytest.mark.parametrize("gap", [1e-5, 1e-7, 1e-9]) +def test_a_crease_near_a_vertex_keeps_the_sliver_at_the_vertex(gap): + """The corner a crease cuts off near a vertex is a cell however thin: it holds the vertex atom.""" + cells = sb._cells(3, [sb._ridge(np.array([0.0, 1.0, 0.0]), 1 - gap)]) + vertex = np.array([0.0, 1.0, 0.0]) + assert any(active[0] == 1 and np.abs(V - vertex).sum(axis=1).min() == 0.0 for V, active in cells) + + +@_SETTINGS +@given(_pq, _pq, st.integers(0, 2**31 - 1), st.floats(0.01, 0.99)) +def test_a_hinge_is_the_same_constraint_from_either_end(p, q, seed, t): + if abs(p - q) < 0.02: + return + side, p_own = _side("segment", p, q) + S, w = _random_law(side, p_own, np.random.default_rng(seed), 3) + plain = sb._ridge(np.array([1.0, 0.0]), t) + assert sb._hinge(t).gain(side.P, S, w) == pytest.approx(plain.gain(side.P, S, w), abs=1e-9) + + +def test_the_heights_cut_is_tight_at_a_minimal_chain(): + side, p_own = _side("segment") + S, pi, T = _event_chain() + assert sc._entropy(pi) == pytest.approx(_EVENT_VALUE, abs=1e-9) + assert pi @ S == pytest.approx(p_own, abs=1e-12) + cut = sb._heights_cut(side.P, S, pi, T) + assert cut is not None + assert abs(cut.gain(side.P, S, pi)) < 1e-9 + rng = np.random.default_rng(0) + for _ in range(20): + law = _chain_law(side, rng, 3) + assert cut.gain(side.P, *law) >= -1e-9 + + +def test_the_bound_stays_below_the_value_and_rises(scip): + (res,) = sb.strassen_lower_bound(_two_state(0.836, 0.788), sides=("reverse",), max_cuts=4, seconds=60.0) + lowers = [entry["lower"] for entry in res.log] + assert lowers == sorted(lowers) + assert res.lower <= _EVENT_VALUE + 1e-7 + assert res.cuts == 4 and res.stop == "cut cap" and not res.certified + + +@pytest.mark.slow +def test_the_seeded_bound_certifies_the_two_state_value(scip): + problem = _two_state(0.26, 0.308) + chains = sc.simplex_chain_search(problem, sides=("reverse",), seconds=2.0, rng=np.random.default_rng(0)) + (res,) = sb.strassen_lower_bound(problem, sides=("reverse",), chains=chains, max_cuts=30, seconds=120.0) + assert res.certified and res.stop == "passes separation" + assert res.lower <= chains[0].entropy + 1e-6 and res.value is not None + assert res.value - res.lower <= 1e-6 + assert res.lower == pytest.approx(0.563239272, abs=5e-7) + + +@pytest.mark.slow +def test_the_bound_stays_below_the_causal_states_entropy_on_a_census_triangle(scip): + """The causal states' own law is a generator on their side, so no bound passes its entropy, and each master's + minimizer is at least the bound before it (the masters' minima rise with the cuts).""" + problem = _census_triangle() + lifted = problem.lifted + entropy = sc._entropy(lifted.minus.T @ lifted.p) + chains = sc.simplex_chain_search(problem, sides=("reverse",), seconds=2.0, rng=np.random.default_rng(0)) + (res,) = sb.strassen_lower_bound(problem, sides=("reverse",), chains=chains, max_cuts=14, seconds=600.0) + assert -math.inf < res.lower <= min(entropy, chains[0].entropy) + 1e-7 + for before, entry in zip(res.log, res.log[1:], strict=False): + if "value" in entry: + assert entry["value"] >= before["lower"] - 1e-6 + + +def test_a_master_at_its_time_limit_certifies_nothing(scip, monkeypatch): + """A minimizer that passes separation is no certificate when SCIP stopped early (its dual may be far below).""" + side, p_own = _side("segment") + S, pi, _ = _event_chain() + stopped = {"status": "timelimit", "dual": 0.1, "cells": 1, "seconds": 0.0, "atoms": S, "weights": pi} + stopped["primal"] = sc._entropy(pi) + monkeypatch.setattr(sb, "_master", lambda *args, **kwargs: stopped) + res = sb._bound_side(side, p_own, None, max_cuts=5, deadline=math.inf) + assert res.stop == "passes separation" and not res.certified and res.lower == 0.1 + monkeypatch.setattr(sb, "_master", lambda *args, **kwargs: {**stopped, "status": "optimal"}) + assert not sb._bound_side(side, p_own, None, max_cuts=5, deadline=math.inf).certified + monkeypatch.setattr(sb, "_master", lambda *args, **kwargs: {**stopped, "status": "optimal", "dual": _EVENT_VALUE}) + assert sb._bound_side(side, p_own, None, max_cuts=5, deadline=math.inf).certified + + +def test_a_scip_error_keeps_the_best_bound(scip, monkeypatch): + side, p_own = _side("segment") + S, w = np.eye(2), p_own + first = {"status": "optimal", "dual": 0.05, "cells": 1, "seconds": 0.0, "atoms": S, "weights": w, "primal": 0.6} + replies = iter([first]) + error = {"status": "error: SCIP: error in LP solver!", "dual": -math.inf, "cells": 1, "seconds": 0.0} + monkeypatch.setattr(sb, "_master", lambda *args, **kwargs: next(replies, error)) + monkeypatch.setattr(sb, "_separate", lambda *args: sb._hinge(0.5)) + res = sb._bound_side(side, p_own, None, max_cuts=5, deadline=math.inf) + assert (res.stop, res.lower, res.certified, res.cuts) == ("SCIP error", 0.05, False, 1) + + +def _flaky(scip, tried: list[float], fails, verdict: str = "error"): + """A PySCIPOpt whose solves fail when ``fails(n)`` holds for the solve's number ``n`` (from 1): with an LP error, + or (``verdict="infeasible"``) with an infeasible status.""" + + class Model(scip.Model): + def optimize(self): + tried.append(self.getParam("numerics/feastol")) + if fails(len(tried)) and verdict == "error": + raise Exception("SCIP: error in LP solver!") + super().optimize() + + def getStatus(self): + return "infeasible" if fails(len(tried)) else super().getStatus() + + return types.SimpleNamespace( + Model=Model, quicksum=scip.quicksum, log=scip.log, SCIP_PARAMEMPHASIS=scip.SCIP_PARAMEMPHASIS + ) + + +@pytest.mark.parametrize("verdict", ["error", "infeasible"]) +def test_a_failed_master_is_solved_again_with_looser_settings(scip, monkeypatch, verdict): + """An LP error, or an infeasible verdict (the ε-machine's law passes every cut), moves down the ladder.""" + side, p_own = _side("segment") + tried: list[float] = [] + monkeypatch.setattr(sb, "_pyscipopt", lambda: _flaky(scip, tried, lambda n: n <= 2, verdict)) + res = sb._master(side.P, p_own, [sb._hinge(0.5)], time_limit=30.0) + assert tried[:3] == [1e-9, 1e-9, 1e-8] and set(tried[2:]) == {1e-8} + assert res["status"] == "optimal" and "atoms" in res + tried.clear() + monkeypatch.setattr(sb, "_pyscipopt", lambda: _flaky(scip, tried, lambda n: True, verdict)) + res = sb._master(side.P, p_own, [sb._hinge(0.5)], time_limit=30.0) + assert tried == [1e-9, 1e-9, 1e-8, 1e-7] and res["status"].startswith("error") and res["dual"] == -math.inf + + +# The first hinge the loop adds on the segment, whose master's minimizer (two atoms) takes two rounds of chords. +_FIRST_HINGE = 0.14089347079 + + +def test_a_failed_round_moves_down_the_ladder_and_then_keeps_the_last_solved_round(scip, monkeypatch): + side, p_own = _side("segment") + tried: list[float] = [] + monkeypatch.setattr(sb, "_pyscipopt", lambda: _flaky(scip, tried, lambda n: n == 2)) + res = sb._master(side.P, p_own, [sb._hinge(_FIRST_HINGE)], time_limit=30.0) + assert tried == [1e-9, 1e-9, 1e-9] and res["status"] == "optimal" and len(res["weights"]) == 2 + assert res["dual"] - 1e-12 <= res["primal"] <= res["dual"] + 1e-6 + tried.clear() + monkeypatch.setattr(sb, "_pyscipopt", lambda: _flaky(scip, tried, lambda n: n >= 2)) + res = sb._master(side.P, p_own, [sb._hinge(_FIRST_HINGE)], time_limit=30.0) + assert tried == [1e-9, 1e-9, 1e-9, 1e-8, 1e-7] and res["status"] == "optimal" and len(res["weights"]) == 2 + assert 0.0 < res["dual"] <= res["primal"] + 1e-9 + + +def test_the_chords_close_on_the_minimizer(scip): + """The rounds stop when the chords meet the entropy at the minimizer, so its entropy is the bound.""" + side, p_own = _side("segment") + res = sb._master(side.P, p_own, [sb._hinge(_FIRST_HINGE)], time_limit=30.0) + assert res["status"] in sb._SOLVED and len(res["weights"]) == 2 + assert res["dual"] - 1e-12 <= res["primal"] <= res["dual"] + 1e-6 + + +def test_a_side_out_of_time_reports_no_bound(scip): + (res,) = sb.strassen_lower_bound(_two_state(0.836, 0.788), sides=("reverse",), deadline=0.0) + assert (res.stop, res.lower, res.certified) == ("time", -math.inf, False) + + +def test_the_pipeline_reports_the_bound_per_side(scip, monkeypatch): + monkeypatch.setattr(gs, "_STRASSEN_SECONDS", 3.0) + kwargs = {"stages": ("machines", "chains"), "coverage": "off", "generator_heaviest_term": False} + bidir = _two_state(0.26, 0.308).bidir + result = gs.generative_model_from_bidirectional(bidir, strassen_bound=True, rng=np.random.default_rng(0), **kwargs) + assert result.strassen_lower is not None and result.strassen_certified is not None + assert set(result.strassen_lower) == {"reverse", "forward"} + for side, value in result.strassen_lower.items(): + assert value <= result.upper + 1e-6 + assert isinstance(result.strassen_certified[side], bool) + summary = result.stages[-1] + assert summary["stage"] == "reliability summary" + assert summary["strassen_lower"] == result.strassen_lower + assert result.lower_source != "Strassen bound" + (stage,) = [s for s in result.stages if s["stage"] == "Strassen bound"] + assert stage["skipped sides"] == [] + off = gs.generative_model_from_bidirectional(bidir, rng=np.random.default_rng(0), **kwargs) + assert off.strassen_lower is None and "Strassen bound" not in {s["stage"] for s in off.stages} + + +def test_the_stage_is_skipped_on_a_truncation_and_for_the_wyner_objective(): + for objective, window, reason in ( + ("entropy", (0.5, "a bound"), "the bidirectional machine is a truncation"), + ("wyner", None, "it bounds the state entropy"), + ): + result = gs._bracket_search( + golden_mean_bidirectional(), + objective=objective, + stages=("machines",), + strassen_bound=True, + window_lower=window, + rng=np.random.default_rng(0), + ) + (stage,) = [s for s in result.stages if s["stage"] == "Strassen bound"] + assert stage["skipped"] == reason and result.strassen_lower is None + + +def test_the_stage_is_skipped_without_pyscipopt(monkeypatch): + def missing(): + raise ImportError("strassen_lower_bound needs PySCIPOpt") + + monkeypatch.setattr(sb, "_pyscipopt", missing) + result = gs._bracket_search( + _two_state(0.26, 0.308).bidir, + objective="entropy", + stages=("machines",), + coverage="off", + generator_heaviest_term=False, + strassen_bound=True, + rng=np.random.default_rng(0), + ) + (stage,) = [s for s in result.stages if s["stage"] == "Strassen bound"] + assert stage["skipped"] == "strassen_lower_bound needs PySCIPOpt" and result.strassen_lower is None + + +def test_the_stage_is_skipped_on_an_exploding_build(monkeypatch): + from sofic.generators import bidirectional_build as bb + + failed = bb.BidirBuildResult(None, bb.BidirPreflightResult("explosion", reverse_max_states=10_000, error="test")) + monkeypatch.setattr(bb, "try_build_bidirectional", lambda forward, **kwargs: failed) + monkeypatch.setattr(gs, "_future_window_bound", lambda forward, **kwargs: (0.5, "a bound", [], {})) + result = gs.generative_model(golden_mean(0.5), hmm_search=False, strassen_bound=True, rng=np.random.default_rng(0)) + skipped = [s["stage"] for s in result.stages if s.get("skipped") == "needs the reverse ε-machine"] + assert skipped[-1] == "Strassen bound" and result.strassen_lower is None