diff --git a/CHANGELOG.md b/CHANGELOG.md index 9db1746..b2a146d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,6 +49,26 @@ brute-force reference or a closed-form value and has a regression test. 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. +### Global bounds: bound tightening off, chords as the second opinion + +- `generator_global_bound` and `separating_global_bound` take `entropy="log"` (the default, SCIP's entropy + expression) or `entropy="chords"`. The chords replace each `-w log2 w` by its chords on a grid of masses, an SOS2 + constraint (Beale & Tomlin 1970), and solve again with the minimizer's weights added to the grids, each round + warm-started from the last, until the chords meet the entropy to `1e-9`. They lie below the entropy, so the dual + bound and an "infeasible" verdict hold for the entropy itself and `slack` is 0. Results carry `entropy`, `rounds` + and `chord_gap`. +- `obbt` now defaults to `False`. On SCIP's entropy expression, bound tightening cut the optimum off a 3 x 3 joint at + `k = 3` ("optimal" 1.447803 against a feasible 1.343763) while the entropy variables were created first, and + whether it does depends on details as small as the model's variable order. The second opinion of + `separating_decomposition` is now `entropy="chords", presolve=False` (it was `presolve=False, obbt=False`). +- Validation. On the restricted global bound at `K(P)` of 29 small processes (240 s each, about 12 runs at a time), + the chords never rose above a known generator's entropy by more than `6e-7` (SCIP's feasibility tolerance), but + they were at least 3.6 times slower than the entropy expression with bound tightening wherever both finished, and + closed 1 of the brackets it closed 6 of. With bound tightening off, the entropy expression took 1.2 to 4.4 times + as long on 9 closable brackets and did not finish 3 of them in 240 s, 2 of which it finished with bound tightening + on. On the static bound of 3 joints at `k = 5` the chords took 3 to 15 times as long, and all three settings agreed + to `1e-5`. + ### 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 7aa0d53..58ea877 100644 --- a/docs/generators/generative_models.rst +++ b/docs/generators/generative_models.rst @@ -529,8 +529,12 @@ bound is known, and :math:`\min(|S^+|, |S^-|) + 1` is not one: the skip-one chai `Supports without 2 × 2 rectangles`_) needs :math:`|S^+| + 2` states. When both persistent 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`). +works to its own tolerances, and its presolve and optimization-based bound tightening can go wrong. +Bound tightening is off by default (``obbt=True`` turns it on, which can close a bound several times +faster), and ``entropy="chords", presolve=False`` gives a second opinion: each entropy term is replaced +by its chords, an SOS2 constraint :cite:`Beale1970` refined at the minimizer, which lie below the +entropy, so the dual bound holds for the entropy itself (see :doc:`separating_generators`). SCIP takes +several times longer on the chords. :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 diff --git a/docs/generators/separating_generators.rst b/docs/generators/separating_generators.rst index 6c7865b..cf69a31 100644 --- a/docs/generators/separating_generators.rst +++ b/docs/generators/separating_generators.rst @@ -68,9 +68,12 @@ over decompositions with the component's :math:`K` terms 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 +``tests/test_separating_generators.py``, optimization-based bound tightening (OBBT) at :math:`k = 3` cut off the +optimum and SCIP reported "optimal" at :math:`1.447803`, above a feasible :math:`1.343763`. Whether it does depends +on details as small as the order in which the model's variables are created, so OBBT is off by default. The second +opinion (``entropy="chords", presolve=False``) turns presolve off and replaces SCIP's entropy expression by its +chords, an SOS2 constraint :cite:`Beale1970` refined at the minimizer; the chords lie below the entropy, so its dual +bound holds for the entropy itself. Both joints come out right under it. 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 diff --git a/sofic/generators/global_bound.py b/sofic/generators/global_bound.py index 09a9e02..62c5f64 100644 --- a/sofic/generators/global_bound.py +++ b/sofic/generators/global_bound.py @@ -17,8 +17,14 @@ marginals, and the two-step edge law :math:`\sum V\, Q_w(a) R_u(b) = \Pr(S^+_0 = a, X_0 X_1 = x y, S^-_2 = b)`. All of these are necessary for a generator, not sufficient. :func:`generator_global_bound` minimizes :math:`\H{\pi}` over them with SCIP's spatial branch and bound :cite:`Achterberg2009,Vigerske2018` through -PySCIPOpt :cite:`Maher2016`. Its dual bound therefore bounds the state entropy of every generator with at most -``k`` states from below; it says nothing about larger generators, so it is a lower bound on the generative +PySCIPOpt :cite:`Maher2016`. By default (``entropy="log"``) each term :math:`-\pi_w \log_2 \pi_w` is SCIP's own +entropy expression, evaluated at :math:`\max(\pi_w, \text{pi\_min})`. With ``entropy="chords"`` each term is +replaced by its chords on a grid of masses, an SOS2 constraint :cite:`Beale1970`, and the model is solved again with +each weight of the minimizer added to its grid until the chords meet the entropy there to ``1e-9`` in all. The +chords lie below the entropy, so every round's dual bound, and an "infeasible" verdict under an objective limit, +holds for the entropy itself; spatial branching is left to the bilinear terms. SCIP takes several times longer on +the chords, so they are the second opinion (below) rather than the default. Either way the dual bound bounds the +state entropy of every generator with at most ``k`` states from below; it says nothing about larger generators, so it is a lower bound on the generative complexity :math:`C_g` only once a bound on the number of states of a minimal generator is known. No general bound is known, and :math:`\min(|S^+|, |S^-|) + 1` is not one: a Markov chain on six symbols with :math:`|S^+| = |S^-| = 6` needs 8 states (see @@ -39,19 +45,22 @@ 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. +decomposition is :math:`W = X` at weights :math:`(1/2, 1/2)`). With ``entropy="log"``, its optimization-based bound +tightening (OBBT), together with the entropy expression and the bilinear terms, can cut off the optimum: on a 3 x 3 +joint with 5 support cells it returned "optimal" 1.447803 at ``k = 3`` while a feasible 3-block partition has +1.343763, and whether it does depends on details as small as the order in which the model's variables are created. +So OBBT is off by default; ``obbt=True`` can close a bound several times faster, at that risk. On the chords both +settings give 1.343763 there (see ``tests/test_separating_generators.py``). ``entropy="chords", presolve=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 Mapping, Sequence +from collections.abc import Callable, Mapping, Sequence from dataclasses import dataclass from typing import Any @@ -59,9 +68,13 @@ from sofic.generators.bidirectional_epsilon_machine import BidirectionalEpsilonMachine from sofic.generators.coupled_generators import _GeneratorProblem +from sofic.generators.strassen_bound import _CHORD_TOL, _GRID, _SOLVED, _entropy_term __all__ = ["GlobalBoundResult", "SeparatingBoundResult", "generator_global_bound", "separating_global_bound"] +_ENTROPY_MODELS = ("chords", "log") +_MAX_ROUNDS = 60 + @dataclass(frozen=True) class GlobalBoundResult: @@ -74,7 +87,9 @@ class GlobalBoundResult: ``K[w, x, v] = F(w, x, v) / pi_w``) describe SCIP's best solution, which solves the necessary equations only and must be verified (or polished with :func:`~sofic.generators.hmm_search.hmm_generator_search`, whose ``initial`` argument takes its symbol matrices) before it counts as a generator. ``two_step`` records whether - the two-step flows were used. + the two-step flows were used. ``entropy`` is the entropy model; on ``"chords"`` ``slack`` is 0, ``dual_bound`` is + that of the last of the ``rounds`` SCIP solves to finish, ``primal`` is the entropy of the best solution's + weights, and ``chord_gap`` is the entropy minus the chords there (at most ``1e-9`` once refinement finished). """ k: int @@ -87,6 +102,9 @@ class GlobalBoundResult: nodes: int seconds: float two_step: bool + entropy: str = "chords" + rounds: int = 1 + chord_gap: float | None = None @dataclass(frozen=True) @@ -97,7 +115,7 @@ class SeparatingBoundResult: ``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. + an exact decomposition. ``entropy``, ``rounds`` and ``chord_gap`` are as in :class:`GlobalBoundResult`. """ k: int @@ -109,6 +127,9 @@ class SeparatingBoundResult: factors: tuple[np.ndarray, np.ndarray, np.ndarray] | None nodes: int seconds: float + entropy: str = "chords" + rounds: int = 1 + chord_gap: float | None = None def _pyscipopt() -> Any: @@ -131,14 +152,118 @@ def _configure(m: Any, scip: Any, presolve: bool, obbt: bool, params: Mapping[st m.setParam(key, value) -def _bounds(m: Any, status: str, objective_limit: float | None, slack: float) -> tuple[float, float]: +def _check_entropy(entropy: str) -> None: + if entropy not in _ENTROPY_MODELS: + raise ValueError(f"entropy must be one of {_ENTROPY_MODELS}, not {entropy!r}") + + +def _entropy_terms( + m: Any, scip: Any, weights: Sequence[Any], grids: Sequence[Sequence[float]] | None, pi_min: float +) -> list[Any]: + """Objective terms for ``weights``: the chords of ``-w log2 w`` on ``grids`` (an SOS2 constraint each), or, + without grids, SCIP's entropy expression at ``max(w, pi_min)``. Must create the model's last variables: the + warm start in :func:`_solve` maps the others between rounds by position.""" + quicksum = scip.quicksum + terms = [] + for j, w in enumerate(weights): + if grids is not None: + mu = [m.addVar(lb=0, ub=1) for _ in grids[j]] + m.addCons(quicksum(mu) == 1) + m.addCons(w == quicksum(g * v for g, v in zip(grids[j], mu, strict=True))) + m.addConsSOS2(mu) + terms.append(quicksum(_entropy_term(g) * v for g, v in zip(grids[j], mu, strict=True))) + else: + s = m.addVar(lb=pi_min, ub=1) # max(w, pi_min), the argument of the entropy term + e = m.addVar(lb=0, ub=1 / (math.e * math.log(2)) + 1e-9) + m.addCons(s >= w) + m.addCons(s <= w + pi_min) + m.addCons(e >= -s * scip.log(s) / math.log(2)) + terms.append(e) + return terms + + +def _dual(m: Any) -> float: dual = float(m.getDualbound()) - dual = math.inf if dual >= m.infinity() else -math.inf if dual <= -m.infinity() else dual + return math.inf if dual >= m.infinity() else -math.inf if dual <= -m.infinity() else dual + + +def _lower(dual: float, status: str, objective_limit: float | None, slack: float) -> float: 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 + return math.inf if objective_limit is None else float(objective_limit) - slack + return float((dual if objective_limit is None else min(dual, float(objective_limit))) - slack) + + +def _solve( + build: Callable[[list[list[float]] | None], tuple[Any, list[Any], Callable[[Any], Any]]], + k: int, + entropy: str, + objective_limit: float | None, + time_limit: float | None, +) -> tuple[Any, Callable[[Any], Any], str, float, int, int, float | None]: + """Solve the model ``build(grids)`` returns (with its weight variables and a solution reader) once on + ``"log"``, or in chord rounds. + + Each chord round adds every weight of the minimizer whose chord gap exceeds ``_CHORD_TOL / k`` to its grid and + solves again from that minimizer (if below the objective limit), until the gaps sum to at most ``_CHORD_TOL``, + a round ends unsolved, without a solution or "infeasible" (final: the chords lie below the entropy), + ``_MAX_ROUNDS`` rounds pass, or the time runs out. Finer chords give a tighter relaxation, so the dual bound is + the last solved round's (earlier ones differ from it only within SCIP's tolerances), or an unsolved last + round's if that is larger. Returns the last model, its reader and status, that dual bound, the nodes and + rounds, and the chord gap at the last solution. + """ + start = time.monotonic() + grids = [list(_GRID) for _ in range(k)] if entropy == "chords" else None + dual, nodes, rounds, last, warm = -math.inf, 0, 0, None, None + while True: + m, weights, read = build(grids) + if warm is not None and (objective_limit is None or sum(map(_entropy_term, warm[1])) < objective_limit): + _warm_start(m, *warm, grids) + 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) - (time.monotonic() - start))) + m.optimize() + status, gap = str(m.getStatus()), None + if status == "infeasible" and objective_limit is None and last is not None: + # The chords change only the objective, so the equations of the earlier rounds are still feasible. + return (*last[:3], dual, nodes, rounds, last[3]) + nodes, rounds = nodes + int(m.getNNodes()), rounds + 1 + dual = _dual(m) if status in (*_SOLVED, "infeasible") else max(dual, _dual(m)) + if grids is None or status == "infeasible" or m.getNSols() == 0: + break + sol = m.getBestSol() + w = np.clip([m.getSolVal(sol, v) for v in weights], 0.0, 1.0) + gaps = [ + _entropy_term(x) - np.interp(x, g, [_entropy_term(t) for t in g]) for x, g in zip(w, grids, strict=True) + ] + gap = float(sum(gaps)) + out_of_time = time_limit is not None and time.monotonic() - start >= time_limit + if status not in _SOLVED or gap <= _CHORD_TOL or rounds >= _MAX_ROUNDS or out_of_time: + break + last = (m, read, status, gap) + variables = m.getVars() + warm = ([m.getSolVal(sol, v) for v in variables[: len(variables) - sum(map(len, grids))]], w) + for j, g in enumerate(gaps): + if g > _CHORD_TOL / k: + grids[j] = sorted({*grids[j], float(w[j])}) + return m, read, status, dual, nodes, rounds, gap + + +def _warm_start(m: Any, values: Sequence[float], weights: np.ndarray, grids: Sequence[Sequence[float]]) -> None: + """Offer SCIP the previous round's minimizer: ``values`` for the variables before the chords, and each weight + as a point on its grid (on a grid point when it was just added).""" + variables = m.getVars() + sol = m.createSol() + for v, x in zip(variables, values, strict=False): + m.setSolVal(sol, v, x) + j = len(values) + for w, grid in zip(weights, grids, strict=True): + i = min(max(int(np.searchsorted(grid, w, side="right")) - 1, 0), len(grid) - 2) + t = min(max((w - grid[i]) / (grid[i + 1] - grid[i]), 0.0), 1.0) + m.setSolVal(sol, variables[j + i], 1.0 - t) + m.setSolVal(sol, variables[j + i + 1], t) + j += len(grid) + m.addSol(sol, free=True) def separating_global_bound( @@ -149,20 +274,23 @@ def separating_global_bound( time_limit: float | None = None, pi_min: float = 1e-7, presolve: bool = True, - obbt: bool = True, + obbt: bool = False, params: Mapping[str, Any] | None = None, + entropy: str = "log", ) -> 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 + the weights sorted and each entropy term evaluated at :math:`\max(\pi_w, \text{pi\_min})` (``entropy="log"``; + ``slack`` corrects for that) or replaced by its chords, refined at the minimizer (``entropy="chords"``), 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. """ + _check_entropy(entropy) scip = _pyscipopt() start = time.monotonic() P = np.asarray(P, dtype=float) @@ -171,67 +299,67 @@ def separating_global_bound( 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]) + + def build(grids: list[list[float]] | None) -> tuple[Any, list[Any], Callable[[Any], Any]]: + m = scip.Model() + m.hideOutput() + _configure(m, scip, presolve, obbt, params) + p = {w: m.addVar(lb=0, ub=1) 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(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(Y[w, a] == p[w] * Q[w, a]) + m.addCons(quicksum(Y[w, a] for w in W) == float(pr[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) + 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])) + weights = [p[w] for w in W] + m.setObjective(quicksum(_entropy_terms(m, scip, weights, grids, pi_min)), "minimize") + + def read(sol: Any) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + return ( + 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 m, weights, read + + m, read, status, dual, nodes, rounds, gap = _solve(build, k, entropy, objective_limit, time_limit) + slack = 0.0 if entropy == "chords" else k * pi_min * math.log2(1 / pi_min) 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), - ) + factors = read(m.getBestSol()) + primal = float(m.getPrimalbound() if entropy == "log" else sum(_entropy_term(x) for x in factors[0])) return SeparatingBoundResult( k=k, status=status, - lower=lower, + lower=_lower(dual, status, objective_limit, slack), dual_bound=dual, slack=slack, primal=primal, factors=factors, - nodes=int(m.getNNodes()), + nodes=nodes, seconds=time.monotonic() - start, + entropy=entropy, + rounds=rounds, + chord_gap=gap, ) @@ -271,8 +399,9 @@ def generator_global_bound( data_tol: float = 1e-7, pi_min: float = 1e-7, presolve: bool = True, - obbt: bool = True, + obbt: bool = False, params: Mapping[str, Any] | None = None, + entropy: str = "log", ) -> GlobalBoundResult: r"""Lower bound on the state entropy of generators with at most ``k`` states, by SCIP global optimization. @@ -281,8 +410,10 @@ def generator_global_bound( with SCIP. Generators with fewer than ``k`` states are covered (their missing states get weight 0). The weights are sorted, so the optional ``caps`` (valid caps on the total weight of the ``j`` heaviest states of any generator, e.g. those of :func:`~sofic.generators.generator_caps.generator_coverage_bound`) become - linear cuts. Each entropy term is evaluated at :math:`\max(\pi_w, \text{pi\_min})`, which overestimates it by - at most :math:`\text{pi\_min} \log_2(1/\text{pi\_min})`; ``slack`` (``k`` times that) is subtracted. + linear cuts. Each entropy term is evaluated at :math:`\max(\pi_w, \text{pi\_min})`, which overestimates it by at + most :math:`\text{pi\_min} \log_2(1/\text{pi\_min})`; ``slack`` (``k`` times that) is subtracted. With + ``entropy="chords"`` it is replaced by its chords, refined at the minimizer as in the module docstring, and + ``slack`` is 0. ``weight_box`` ``(lo0, hi0, lo1, hi1)`` confines the two heaviest weights to :math:`\text{lo0} \le \pi_0 \le \text{hi0}` and :math:`\text{lo1} \le \pi_1 \le \text{hi1}`. The result then @@ -292,14 +423,16 @@ def generator_global_bound( ``objective_limit`` (e.g. the entropy of a verified generator) lets SCIP prune everything above it; when it 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. + ``objective_limit - slack``. ``time_limit`` (seconds, over all chord rounds) 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`. ``presolve=False, obbt=False`` is the second opinion for a decisive + see :class:`GlobalBoundResult`. ``entropy="chords", presolve=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]``). """ + _check_entropy(entropy) scip = _pyscipopt() start = time.monotonic() problem = bidir if isinstance(bidir, _GeneratorProblem) else _GeneratorProblem(bidir) @@ -313,131 +446,129 @@ def generator_global_bound( W, X, A, B = range(k), range(ns), range(na), range(nb) quicksum = scip.quicksum - 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) - m.addCons(lhs >= rhs - data_tol) - - pi = {w: m.addVar(lb=0, ub=1) for w in W} - s = {w: m.addVar(lb=pi_min, ub=1) for w in W} # max(pi_w, pi_min), the argument of the entropy term - 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(pp[a])) for w in W for a in A} - Z = {(w, b): m.addVar(lb=0, ub=float(pm[b])) for w in W for b in B} - F = {(w, x, v): m.addVar(lb=0, ub=1) for w in W for x in X for v in W} - FQ = {(w, x, v, a): m.addVar(lb=0, ub=1) for w in W for x in X for v in W for a in A} - - m.addCons(quicksum(pi.values()) == 1) - for w in W: - m.addCons(s[w] >= pi[w]) - m.addCons(s[w] <= pi[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) == pi[w]) - m.addCons(quicksum(Z[w, b] for b in B) == pi[w]) - for a in A: - m.addCons(Y[w, a] == pi[w] * Q[w, a]) - for b in B: - m.addCons(Z[w, b] == pi[w] * R[w, b]) - m.addCons(quicksum(F[w, x, v] for x in X for v in W) == pi[w]) - m.addCons(quicksum(F[u, x, w] for u in W for x in X) == pi[w]) - if w + 1 < k: - m.addCons(pi[w] >= pi[w + 1]) - for w in W: - for x in X: - for v in W: - m.addCons(quicksum(FQ[w, x, v, a] for a in A) == F[w, x, v]) - for a in A: - m.addCons(FQ[w, x, v, a] == F[w, x, v] * Q[w, a]) - for a in A: - data_eq(quicksum(Y[w, a] for w in W), float(pp[a])) - for b in B: - data_eq(quicksum(Z[w, b] for w in W), float(pm[b])) - for a in A: - for b in B: - data_eq(quicksum(Y[w, a] * R[w, b] for w in W), float(P[a, b])) - data_eq(quicksum(Q[w, a] * Z[w, b] for w in W), float(P[a, b])) - for a in A: - for x in X: + def build(grids: list[list[float]] | None) -> tuple[Any, list[Any], Callable[[Any], Any]]: + 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) + m.addCons(lhs >= rhs - data_tol) + + pi = {w: m.addVar(lb=0, ub=1) 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(pp[a])) for w in W for a in A} + Z = {(w, b): m.addVar(lb=0, ub=float(pm[b])) for w in W for b in B} + F = {(w, x, v): m.addVar(lb=0, ub=1) for w in W for x in X for v in W} + FQ = {(w, x, v, a): m.addVar(lb=0, ub=1) for w in W for x in X for v in W for a in A} + + m.addCons(quicksum(pi.values()) == 1) + for w in W: + 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) == pi[w]) + m.addCons(quicksum(Z[w, b] for b in B) == pi[w]) + for a in A: + m.addCons(Y[w, a] == pi[w] * Q[w, a]) for b in B: - data_eq(quicksum(FQ[w, x, v, a] * R[v, b] for w in W for v in W), float(Pe[a, x, b])) - for v in W: # forward stationarity: S+_1 is a function of (S+_0, X_0) - for a2 in A: - src = [(a, x) for a in A for x in X if fwd[a, x, a2]] - m.addCons(Y[v, a2] == quicksum(FQ[w, x, v, a] for a, x in src for w in W)) - for w in W: # reverse consistency: S-_0 is a function of (X_0, S-_1) - for b in B: - tgt = [(x, c) for x in X for c in B if rev[x, c, b]] - m.addCons(Z[w, b] == quicksum(F[w, x, v] * R[v, c] for x, c in tgt for v in W)) - for j, cap in enumerate(list(caps)[:k]): - m.addCons(quicksum(pi[w] for w in range(j + 1)) <= float(cap)) - if weight_box is not None: - lo0, hi0, lo1, hi1 = (float(t) for t in weight_box) - m.addCons(pi[0] >= lo0) - m.addCons(pi[0] <= hi0) - if k > 1: - m.addCons(pi[1] >= lo1) - m.addCons(pi[1] <= hi1) - if Pe2 is not None: - V = {(w, x, v, y, u): m.addVar(lb=0, ub=1) for w in W for x in X for v in W for y in X for u in W} - VQ = {(*key, a): m.addVar(lb=0, ub=1) for key in V for a in A} + m.addCons(Z[w, b] == pi[w] * R[w, b]) + m.addCons(quicksum(F[w, x, v] for x in X for v in W) == pi[w]) + m.addCons(quicksum(F[u, x, w] for u in W for x in X) == pi[w]) + if w + 1 < k: + m.addCons(pi[w] >= pi[w + 1]) for w in W: for x in X: for v in W: - m.addCons(quicksum(V[w, x, v, y, u] for y in X for u in W) == F[w, x, v]) - for y in X: - for u in W: - # the hidden chain is Markov: Pr(w, x, v, y, u) pi_v = Pr(w, x, v) Pr(v, y, u) - m.addCons(V[w, x, v, y, u] * pi[v] == F[w, x, v] * F[v, y, u]) - m.addCons(quicksum(VQ[w, x, v, y, u, a] for a in A) == V[w, x, v, y, u]) - for a in A: - m.addCons(VQ[w, x, v, y, u, a] == V[w, x, v, y, u] * Q[w, a]) - for v in W: - for y in X: - for u in W: - m.addCons(quicksum(V[w, x, v, y, u] for w in W for x in X) == F[v, y, u]) - for x in X: - for y in X: - for a in A: - for b in B: - data_eq( - quicksum(VQ[w, x, v, y, u, a] * R[u, b] for w in W for v in W for u in W), - float(Pe2[x, y, 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) + m.addCons(quicksum(FQ[w, x, v, a] for a in A) == F[w, x, v]) + for a in A: + m.addCons(FQ[w, x, v, a] == F[w, x, v] * Q[w, a]) + for a in A: + data_eq(quicksum(Y[w, a] for w in W), float(pp[a])) + for b in B: + data_eq(quicksum(Z[w, b] for w in W), float(pm[b])) + for a in A: + for b in B: + data_eq(quicksum(Y[w, a] * R[w, b] for w in W), float(P[a, b])) + data_eq(quicksum(Q[w, a] * Z[w, b] for w in W), float(P[a, b])) + for a in A: + for x in X: + for b in B: + data_eq(quicksum(FQ[w, x, v, a] * R[v, b] for w in W for v in W), float(Pe[a, x, b])) + for v in W: # forward stationarity: S+_1 is a function of (S+_0, X_0) + for a2 in A: + src = [(a, x) for a in A for x in X if fwd[a, x, a2]] + m.addCons(Y[v, a2] == quicksum(FQ[w, x, v, a] for a, x in src for w in W)) + for w in W: # reverse consistency: S-_0 is a function of (X_0, S-_1) + for b in B: + tgt = [(x, c) for x in X for c in B if rev[x, c, b]] + m.addCons(Z[w, b] == quicksum(F[w, x, v] * R[v, c] for x, c in tgt for v in W)) + for j, cap in enumerate(list(caps)[:k]): + m.addCons(quicksum(pi[w] for w in range(j + 1)) <= float(cap)) + if weight_box is not None: + lo0, hi0, lo1, hi1 = (float(t) for t in weight_box) + m.addCons(pi[0] >= lo0) + m.addCons(pi[0] <= hi0) + if k > 1: + m.addCons(pi[1] >= lo1) + m.addCons(pi[1] <= hi1) + if Pe2 is not None: + V = {(w, x, v, y, u): m.addVar(lb=0, ub=1) for w in W for x in X for v in W for y in X for u in W} + VQ = {(*key, a): m.addVar(lb=0, ub=1) for key in V for a in A} + for w in W: + for x in X: + for v in W: + m.addCons(quicksum(V[w, x, v, y, u] for y in X for u in W) == F[w, x, v]) + for y in X: + for u in W: + # the hidden chain is Markov: Pr(w, x, v, y, u) pi_v = Pr(w, x, v) Pr(v, y, u) + m.addCons(V[w, x, v, y, u] * pi[v] == F[w, x, v] * F[v, y, u]) + m.addCons(quicksum(VQ[w, x, v, y, u, a] for a in A) == V[w, x, v, y, u]) + for a in A: + m.addCons(VQ[w, x, v, y, u, a] == V[w, x, v, y, u] * Q[w, a]) + for v in W: + for y in X: + for u in W: + m.addCons(quicksum(V[w, x, v, y, u] for w in W for x in X) == F[v, y, u]) + for x in X: + for y in X: + for a in A: + for b in B: + data_eq( + quicksum(VQ[w, x, v, y, u, a] * R[u, b] for w in W for v in W for u in W), + float(Pe2[x, y, a, b]), + ) + weights = [pi[w] for w in W] + m.setObjective(quicksum(_entropy_terms(m, scip, weights, grids, pi_min)), "minimize") + + def read(sol: Any) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + pi_v = np.clip([m.getSolVal(sol, pi[w]) for w in W], 0, None) + Q_v = np.clip([[m.getSolVal(sol, Q[w, a]) for a in A] for w in W], 0, None) + R_v = np.clip([[m.getSolVal(sol, R[w, b]) for b in B] for w in W], 0, None) + F_v = np.clip([[[m.getSolVal(sol, F[w, x, v]) for v in W] for x in X] for w in W], 0, None) + K_v = F_v / np.maximum(F_v.sum(axis=(1, 2), keepdims=True), 1e-300) + return pi_v / pi_v.sum(), Q_v, R_v, K_v + + return m, weights, read + + m, read, status, dual, nodes, rounds, gap = _solve(build, k, entropy, objective_limit, time_limit) + slack = 0.0 if entropy == "chords" else k * pi_min * math.log2(1 / pi_min) primal, seed = None, None if m.getNSols() > 0: - primal = float(m.getPrimalbound()) - sol = m.getBestSol() - pi_v = np.clip([m.getSolVal(sol, pi[w]) for w in W], 0, None) - Q_v = np.clip([[m.getSolVal(sol, Q[w, a]) for a in A] for w in W], 0, None) - R_v = np.clip([[m.getSolVal(sol, R[w, b]) for b in B] for w in W], 0, None) - F_v = np.clip([[[m.getSolVal(sol, F[w, x, v]) for v in W] for x in X] for w in W], 0, None) - K_v = F_v / np.maximum(F_v.sum(axis=(1, 2), keepdims=True), 1e-300) - seed = (pi_v / pi_v.sum(), Q_v, R_v, K_v) + seed = read(m.getBestSol()) + primal = float(m.getPrimalbound() if entropy == "log" else sum(_entropy_term(x) for x in seed[0])) return GlobalBoundResult( k=k, status=status, - lower=lower, + lower=_lower(dual, status, objective_limit, slack), dual_bound=dual, slack=slack, primal=primal, seed=seed, - nodes=int(m.getNNodes()), + nodes=nodes, seconds=time.monotonic() - start, two_step=Pe2 is not None, + entropy=entropy, + rounds=rounds, + chord_gap=gap, ) diff --git a/sofic/generators/separating_generators.py b/sofic/generators/separating_generators.py index b20e496..42fa10c 100644 --- a/sofic/generators/separating_generators.py +++ b/sofic/generators/separating_generators.py @@ -298,7 +298,7 @@ def _scip_component(P: np.ndarray, k: int, time_limit: float) -> tuple[list, flo 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), + "second": separating_global_bound(P, k, time_limit=time_limit, entropy="chords", presolve=False), } if runs["default"].status == "infeasible" and runs["second"].status != "infeasible": runs["default"] = runs["second"] diff --git a/tests/test_global_bound.py b/tests/test_global_bound.py index d39dc78..64830a9 100644 --- a/tests/test_global_bound.py +++ b/tests/test_global_bound.py @@ -51,6 +51,19 @@ def test_golden_mean_bound_is_the_statistical_complexity(scip) -> None: assert two.lower == pytest.approx(two.dual_bound - two.slack) +def test_entropy_models(scip) -> None: + bidir = _bidir(_two_state(*GOLDEN_MEAN)) + log = gb.generator_global_bound(bidir, 2) + assert log.entropy == "log" and log.status == "optimal" and log.rounds == 1 and log.chord_gap is None + assert log.slack == pytest.approx(2 * 1e-7 * math.log2(1e7)) + chords = gb.generator_global_bound(bidir, 2, entropy="chords") + assert chords.status == "optimal" and chords.slack == 0.0 + assert chords.chord_gap <= gb._CHORD_TOL and chords.rounds < gb._MAX_ROUNDS # the refinement finished + assert C_MU_GOLDEN - 1e-4 <= chords.lower <= C_MU_GOLDEN + 1e-9 + with pytest.raises(ValueError, match="entropy"): + gb.generator_global_bound(bidir, 2, entropy="exact") + + @pytest.mark.parametrize("presolve", [True, False]) def test_presolve_off_also_turns_off_symmetry(scip, presolve) -> None: m = scip.Model() diff --git a/tests/test_separating_generators.py b/tests/test_separating_generators.py index 3aa2da4..3129626 100644 --- a/tests/test_separating_generators.py +++ b/tests/test_separating_generators.py @@ -201,11 +201,43 @@ def test_scip_second_opinion(scip) -> None: 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 + assert lower <= value + 1e-8 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_chords_keep_the_optimum_obbt_cut_off(scip) -> None: + """On SCIP's entropy expression, OBBT cut joint 52's optimum off at k = 3 ("optimal" 1.447803, when the entropy + variables were created first); the default leaves OBBT off, and the chords lie below the entropy and give the + exact common information even with OBBT on.""" + from sofic.generators.generator_bounds import one_wide_exact_common_information + from sofic.generators.global_bound import separating_global_bound + + value = one_wide_exact_common_information(JOINT_52, atol=1e-13).value + default = separating_global_bound(JOINT_52, 3) + assert default.entropy == "log" and default.status == "optimal" + assert default.primal == pytest.approx(value, abs=1e-5) and default.lower <= value + res = separating_global_bound(JOINT_52, 3, entropy="chords", obbt=True) + assert res.slack == 0.0 and res.chord_gap <= 1e-9 + assert res.status == "optimal" and res.primal == pytest.approx(value, abs=1e-6) + assert value - 1e-6 <= res.lower <= value + 1e-8 # no slack on the chords: SCIP's tolerances only + kumar = separating_global_bound(KUMAR_2, 2, entropy="chords", presolve=False) + assert kumar.status == "optimal" and 1.0 - 1e-6 <= kumar.lower <= 1.0 + 1e-8 + + +@settings(max_examples=8, deadline=None, suppress_health_check=[HealthCheck.too_slow]) +@given(st.integers(2, 3), st.integers(2, 3), st.integers(1, 3), st.integers(0, 2**32 - 1)) +def test_chord_bound_is_below_every_decomposition(rows, cols, terms, seed) -> None: + pytest.importorskip("pyscipopt") + from sofic.generators.global_bound import separating_global_bound + + rng = np.random.default_rng(seed) + A = rng.dirichlet(np.ones(terms))[:, None] * rng.dirichlet(np.ones(rows), size=terms) + R = rng.dirichlet(np.ones(cols), size=terms) + res = separating_global_bound(A.T @ R, terms, time_limit=20, entropy="chords") + assert res.lower <= _h(A.sum(axis=1)) + 1e-8 + + def test_full_support_component_uses_scip(scip) -> None: P = np.array([[0.261439, 0.063794], [0.088097, 0.261439]]) P = P / P.sum()