diff --git a/CHANGELOG.md b/CHANGELOG.md index 1899aa5..7df4647 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,6 +49,41 @@ brute-force reference or a closed-form value and has a regression test. 1,000 states, a 60 s run with `reverse_max_states=1000` and no ladder returns [0.8827307, 1.0795992]. Other failed builds still raise, as do `minimal_wyner_model` and `minimal_functional_generator`. +### Time budgets kept + +- With `time_budget`, `generative_model`'s first bidirectional build stops at half the budget. The mixed-state + enumeration, the ε-machine minimization and the bidirectional construction check a deadline (new `deadline` + keyword on `build_mixed_state_presentation`, `MealyHMM.mixed_state_presentation`, `EpsilonMachine.from_hmm`, + `infer_reverse_epsilon_machine` and `build_bidirectional_epsilon_machine`) and raise `MixedStateDeadlineError`, a + `MixedStateExplosionError`, so a stopped build is classed as an explosion with `budget_exhausted` set, and the + forward-only bracket gets the rest of the budget. The retry ladder skips the caps up to one that has exploded + (it built at 10,000 reverse states again) and forecasts from that build's time. On a binary 3-state process whose + default build is a truncation with 1,261 reverse states, the build took 46.6 s of a 60 s budget (16.4 s + minimizing, 23.3 s building the bidirectional machine) and `generative_model` 72 to 78 s; it now takes 60.0 s and + returns [0.8827307, 1.0795992]. +- The cryptic orders and the block persistent crypticities take a deadline (`cryptic_order`, + `cryptic_order_from_graph` and `power_automaton` raise `TimeoutError` past it); the pipeline gives them a tenth + of the time left, past which the cryptic orders are unknown. +- Once the budget is spent only the ε-machine is offered among the candidate machines; it always generates the + process, so the bracket keeps an upper bound. +- `separating_optima` checks its deadline before every start after the first, whether or not a start has + succeeded, and inside its SLSQP objective, so a start in progress stops at it; the first start still runs to + the end. It checked only before a start, once some start had found an exact decomposition. +- With a budget, simplex chains whose entropy is not below the forward ε-machine's are no longer offered (nor + passed on as coupled-search seeds). On the process above, lifting a 78-state reverse chain with the reverse + ε-machine's entropy took 23 s past the stage's deadline. +- The dit fallbacks of the exact stage and the dit run of the lifted channel stage stop at their deadlines (their + objective raises `TimeoutError`). Once the earlier stages kept to their shares, `minimal_wyner_model` on a 2-state + ternary truncation with a 20 s budget ran over 30 minutes in dit's Wyner basin hopping. +- With a budget, a bracket still open after the searches gets a second future-window pass with the time left: + after the HMM search on an exploding build, and on a truncated build in the fifth of the budget the searches now + leave. The branch and bound of the window length with the larger bound resumes from its open boxes for ten + times as many, so the bound only rises; resumed, it branches exactly as one longer search would. +- On six binary 3-state processes whose reverse machines explode at 1,000 states, at 300 s with the default caps + and with 1,000 reverse states, every run now ends by 310 s (up to 800 s before) and no bound is worse. One of + them certifies in both settings, in 97 s and 91 s, and nine lower bounds rise, seven through the second window + pass. + ### Coverage bound: least entropy under the caps - `coverage_entropy_lower(caps)`, the last step of `coverage_bound`, `generator_coverage_bound` and the pipeline's diff --git a/docs/core/exceptions.rst b/docs/core/exceptions.rst index 4cd759f..330200e 100644 --- a/docs/core/exceptions.rst +++ b/docs/core/exceptions.rst @@ -11,6 +11,8 @@ Exceptions * :class:`NonDeterministicError` — DFA determinism violated * :class:`StochasticValidationError` — invalid probability masses * :class:`MixedStateExplosionError` — mixed-state presentation did not close +* :class:`MixedStateDeadlineError` — mixed-state presentation did not close by its deadline (a + :class:`MixedStateExplosionError`) * :class:`UnifilarityError` — unifilarity invariant violated * :class:`QuasiStochasticValidationError` — quasi-stochastic invariant violated @@ -44,5 +46,6 @@ API .. autoclass:: NonDeterministicError .. autoclass:: StochasticValidationError .. autoclass:: MixedStateExplosionError +.. autoclass:: MixedStateDeadlineError .. autoclass:: UnifilarityError .. autoclass:: QuasiStochasticValidationError diff --git a/docs/generators/generative_models.rst b/docs/generators/generative_models.rst index 367eff8..dd16120 100644 --- a/docs/generators/generative_models.rst +++ b/docs/generators/generative_models.rst @@ -243,14 +243,24 @@ drawing its states independently at both ends of each bidirectional edge also ge coupled generators such as the interleaved product flag do not. With ``time_budget`` every stage gets a share of the time left and stops at its deadline; the stages from -the simplex-chain search on, except the final generator heaviest-term bound, stop a fifth of the budget -early, so that this bound keeps that time, and the stages before them share the whole budget. The universal -coupled search (:func:`~sofic.generators.universal_optimizer.universal_generative_optimizer`) builds no seeds -and tries no larger :math:`k` once its deadline passes; inside it, the coupled search stops every start but the -ε-machine seed at the deadline, and that seed runs to the end so that some generator can be verified. The -lifted channel stage begins no start, dit run or refinement after its deadline, and the targeted line-split -search stops its running local search there and polishes only the best decomposition it has. Those polishes, -the ε-machine seed, an optimizer iteration or a linear program can still carry a run past its budget. +the simplex-chain search on, except the final generator heaviest-term bound (on a truncated build, the second +future-window pass below), stop a fifth of the budget early, so that this bound keeps that time, and the +stages before them share the whole budget. The bidirectional build counts against the budget. The first +build stops at half of it, checked in the mixed-state enumeration, the ε-machine minimization and the +bidirectional construction; a build stopped there counts as an explosion, so the forward-only bracket below +gets the rest. The retry ladder skips the caps up to one that has exploded and stops at the end of the +budget. The persistent criteria (the cryptic orders and the block persistent crypticities) get a tenth of +the time left, past which the cryptic orders are unknown. Of the candidate machines the ε-machine is always +offered, so the bracket keeps an upper bound at any budget, and the other four only while time is left; +simplex chains no lighter than the ε-machine are not offered. The exact common information search (:func:`~sofic.generators.coupled_generators.separating_optima`) runs its +first start to the end; no later start begins after its deadline, and one in progress stops at it. The +universal coupled search (:func:`~sofic.generators.universal_optimizer.universal_generative_optimizer`) +builds no seeds and tries no larger :math:`k` once its deadline passes; inside it, the coupled search stops +every start but the ε-machine seed at the deadline, and that seed runs to the end so that some generator can +be verified. The lifted channel stage begins no start or refinement after its deadline, and its dit run stops +there, as do the dit fallbacks of the exact stage; the targeted line-split search stops its running local +search there and polishes only the best decomposition it has. Those polishes, the ε-machine seed, the first +exact start, an optimizer iteration or a linear program can still carry a run past its budget. The coupled searches parameterize states by their causal-state beliefs :math:`(Q_w, R_w)`, which favours generators whose states' pasts and futures are belief-mixtures of the causal states'. Some processes have @@ -447,16 +457,21 @@ mixed states merge within numerical tolerance, and the build is a finite truncat are verified against the forward machine's words, so the upper bound holds for the process, but the excess entropy, the support-type, flow and coverage bounds, SCIP's dual bound on the exact path, the heaviest-term bounds and the restricted global bound would bound the truncation, not the process. -:func:`~sofic.generators.generative_search.generative_model` therefore skips them, and keeps no budget for -the final heaviest-term bound. Its lower bound is the larger future-window generator coverage bound at +:func:`~sofic.generators.generative_search.generative_model` therefore skips them, including the final +heaviest-term bound. Its lower bound is the larger future-window generator coverage bound at :math:`L = 2` and 3 (1,000 and 2,000 boxes for the two explicit caps at :math:`L = 2`, 300 and 600 at -:math:`L = 3`), computed first, with at most 30% of the time budget :cite:`LohrAy2009`. +:math:`L = 3`), computed first, with at most 30% of the time budget :cite:`LohrAy2009`. With a budget the +searches stop a fifth of it early, and when the bracket is still open the time left goes to a second pass: +the branch and bound of the window length with the larger bound resumes from its open boxes, for ten times +as many, so the bound only rises. :func:`~sofic.generators.generative_search.minimal_wyner_model` reports ``lower`` 0 on a truncated build. When the reverse mixed-state presentation does not close (``bidir_class`` ``"explosion"``, after the retry -ladder), :func:`~sofic.generators.generative_search.generative_model` brackets :math:`C_g` from the forward +ladder), or with a budget the first build does not finish within half of it, +:func:`~sofic.generators.generative_search.generative_model` brackets :math:`C_g` from the forward machine alone instead of raising. The lower bound is the same future-window bound, with at most 30% of the -budget :cite:`LohrAy2009`. The upper bound is the least state entropy among the forward ε-machine and the +budget :cite:`LohrAy2009`, and the same second pass on the time the HMM search leaves when the bracket is +still open. The upper bound is the least state entropy among the forward ε-machine and the generators of the belief-free HMM search (:func:`~sofic.generators.hmm_search.hmm_generator_search`, at :math:`|S^+|` to :math:`|S^+| + 2` states with the rest of the budget split evenly between them; two state counts and two starts without a budget), each verified against the forward machine's words. The stages that need the reverse ε-machine are logged as skipped diff --git a/docs/generators/mixed_state_presentation.rst b/docs/generators/mixed_state_presentation.rst index 0c6b2b0..675fc18 100644 --- a/docs/generators/mixed_state_presentation.rst +++ b/docs/generators/mixed_state_presentation.rst @@ -11,7 +11,8 @@ mixed-state presentation used for nonunifilar hidden processes and time-symmetric computational mechanics :cite:`Ellison2009`. This constructor enumerates beliefs and raises ``MixedStateExplosionError`` -if they do not close within the state cap. Numeric equality tolerances are +if they do not close within the state cap, or ``MixedStateDeadlineError`` (an +explosion too) if they do not close by its ``deadline``. Numeric equality tolerances are not approximation-error budgets. For an opt-in finite approximation of a known positive-transition Moore HMM, see :doc:`quantized_filter` :cite:`feng2026recursive`. diff --git a/sofic/exceptions.py b/sofic/exceptions.py index 0d246c9..9990d5c 100644 --- a/sofic/exceptions.py +++ b/sofic/exceptions.py @@ -29,6 +29,15 @@ class MixedStateExplosionError(StochasticValidationError): """ +class MixedStateDeadlineError(MixedStateExplosionError): + """Raised when a mixed-state presentation, or an ε-machine or bidirectional machine built from one, reaches + its ``deadline`` before it is finished. + + Callers that handle :class:`MixedStateExplosionError` treat it as an explosion: the construction did + not finish within the time it was given. + """ + + class UnifilarityError(SoficValidationError): """Raised when a unifilarity invariant is violated.""" diff --git a/sofic/generators/bidirectional_build.py b/sofic/generators/bidirectional_build.py index 605f531..bf15f0d 100644 --- a/sofic/generators/bidirectional_build.py +++ b/sofic/generators/bidirectional_build.py @@ -3,6 +3,8 @@ When the reverse mixed-state presentation does not close at the default cap, ``build_bidirectional_with_ladder`` raises ``max_states`` until the edge tensor ``Pe`` of :class:`~sofic.generators.coupled_generators._GeneratorProblem` stabilizes. +With a time budget every build has a deadline, checked in the mixed-state enumeration and in the ε-machine and +bidirectional constructions built on it. """ from __future__ import annotations @@ -13,7 +15,7 @@ import numpy as np -from sofic.exceptions import MixedStateExplosionError, StochasticValidationError +from sofic.exceptions import MixedStateDeadlineError, MixedStateExplosionError, StochasticValidationError from sofic.generators.bidirectional_construction import ( build_bidirectional_epsilon_machine, infer_reverse_epsilon_machine, @@ -28,13 +30,17 @@ @dataclass(frozen=True) class BidirPreflightResult: - """Classification before or after attempting a bidirectional build.""" + """Classification before or after attempting a bidirectional build. + + ``deadline_reached`` marks an ``"explosion"`` that is a build stopped at its deadline, not at its cap. + """ bidir_class: BidirClass reverse_max_states: int | None = None reverse_recurrence_finite: bool | None = None reverse_twins_finite: bool | None = None error: str | None = None + deadline_reached: bool = False @dataclass(frozen=True) @@ -67,14 +73,15 @@ def preflight_bidir(forward: EpsilonMachine, *, reverse_max_states: int = 10_000 def _preflight( - forward: EpsilonMachine, reverse_max_states: int + forward: EpsilonMachine, reverse_max_states: int, deadline: float | None = None ) -> tuple[BidirPreflightResult, BidirectionalEpsilonMachine | None]: - """:func:`preflight_bidir` plus the bidirectional machine it built (``None`` unless it built).""" + """:func:`preflight_bidir` plus the bidirectional machine it built (``None`` unless it built). The build stops + at ``deadline`` (a :func:`time.monotonic` value), which counts as an explosion.""" twins = forward.reverse_is_finite() recurrence = forward.reverse_epsilon_machine_is_finite() try: - reverse = infer_reverse_epsilon_machine(forward, max_states=reverse_max_states) - bidir = build_bidirectional_epsilon_machine(forward, reverse) + reverse = infer_reverse_epsilon_machine(forward, max_states=reverse_max_states, deadline=deadline) + bidir = build_bidirectional_epsilon_machine(forward, reverse, deadline=deadline) except MixedStateExplosionError as exc: return BidirPreflightResult( "explosion", @@ -82,6 +89,7 @@ def _preflight( reverse_recurrence_finite=recurrence, reverse_twins_finite=twins, error=str(exc)[:300], + deadline_reached=isinstance(exc, MixedStateDeadlineError), ), None except (StochasticValidationError, ValueError) as exc: return BidirPreflightResult( @@ -113,24 +121,31 @@ def build_bidirectional_with_ladder( edge_tol: float = 1e-8, time_budget: float | None = None, max_reverse_states: int | None = None, + exploded: tuple[BidirPreflightResult, float] | None = None, ) -> BidirBuildResult: """Build a bidirectional machine, increasing reverse ``max_states`` until ``Pe`` stabilizes. With ``time_budget`` (seconds) the ladder stops before a cap whose forecast cost would overrun - the budget, and ``budget_exhausted`` is set on the result. A single mixed-state construction - cannot be interrupted, so the forecast scales the previous cap's time by the square of the cap - ratio (construction time grows faster than linearly in the cap); the first cap always runs. - A build whose reverse machine has more than ``max_reverse_states`` states is classified as an - explosion: such truncated machines are far too large for any generator search. + the budget, and ``budget_exhausted`` is set on the result. The forecast scales the previous cap's + time by the square of the cap ratio (construction time grows faster than linearly in the cap), and + every build stops at the end of the budget, which ends the ladder. A build whose reverse machine has + more than ``max_reverse_states`` states is classified as an explosion: such truncated machines are far + too large for any generator search. + ``exploded`` is ``(preflight, seconds)`` of a build that already exploded: caps at or below its cap are + not tried again, its time is the first forecast's, and its preflight is returned if no cap runs. """ start = time.monotonic() + end = None if time_budget is None else start + time_budget last_pe: np.ndarray | None = None last_bidir: BidirectionalEpsilonMachine | None = None - last_preflight: BidirPreflightResult | None = None - previous: tuple[int, float] | None = None + last_preflight: BidirPreflightResult | None = None if exploded is None else exploded[0] + ceiling = None if exploded is None else exploded[0].reverse_max_states + previous = None if exploded is None or ceiling is None else (ceiling, exploded[1]) exhausted = False for cap in caps: + if ceiling is not None and cap <= ceiling: + continue if time_budget is not None and previous is not None: prev_cap, prev_seconds = previous forecast = prev_seconds * (cap / prev_cap) ** 2 @@ -138,7 +153,11 @@ def build_bidirectional_with_ladder( exhausted = True break attempt = time.monotonic() - pre, bidir = _preflight(forward, cap) + pre, bidir = _preflight(forward, cap, deadline=end) + if pre.deadline_reached: + last_preflight = last_preflight if last_bidir is not None else pre + exhausted = True + break if bidir is not None and max_reverse_states is not None: size = len(list(bidir.reverse_machine.states())) if size > max_reverse_states: @@ -147,6 +166,7 @@ def build_bidirectional_with_ladder( last_preflight = pre if bidir is None: previous = (cap, time.monotonic() - attempt) + ceiling = cap if ceiling is None else max(ceiling, cap) continue pe = _edge_tensor(bidir) previous = (cap, time.monotonic() - attempt) @@ -190,14 +210,25 @@ def try_build_bidirectional( """Single-cap build, or ladder when ``use_ladder`` and the default cap explodes. ``time_budget`` (seconds, including the first preflight) and ``max_reverse_states`` are passed on - to :func:`build_bidirectional_with_ladder`. + to :func:`build_bidirectional_with_ladder`, which skips the caps up to ``reverse_max_states``. With a + budget the first build stops at half of it; a build stopped there counts as an explosion with + ``budget_exhausted`` set and gets no ladder, so the caller keeps the rest of the budget. """ start = time.monotonic() - pre, bidir = _preflight(forward, reverse_max_states) + first = None if time_budget is None else start + 0.5 * time_budget + pre, bidir = _preflight(forward, reverse_max_states, deadline=first) + if pre.deadline_reached: + return BidirBuildResult(None, pre, budget_exhausted=True) if pre.bidir_class == "explosion" and use_ladder: - remaining = None if time_budget is None else max(0.0, time_budget - (time.monotonic() - start)) + elapsed = time.monotonic() - start + remaining = None if time_budget is None else max(0.0, time_budget - elapsed) return build_bidirectional_with_ladder( - forward, caps=caps, edge_tol=edge_tol, time_budget=remaining, max_reverse_states=max_reverse_states + forward, + caps=caps, + edge_tol=edge_tol, + time_budget=remaining, + max_reverse_states=max_reverse_states, + exploded=(pre, elapsed), ) if bidir is None: return BidirBuildResult(None, pre) diff --git a/sofic/generators/bidirectional_construction.py b/sofic/generators/bidirectional_construction.py index 2203dae..5a5d5f8 100644 --- a/sofic/generators/bidirectional_construction.py +++ b/sofic/generators/bidirectional_construction.py @@ -11,6 +11,7 @@ from sofic.exceptions import StochasticValidationError from sofic.generators.bidirectional_epsilon_machine import BidirectionalEpsilonMachine from sofic.generators.epsilon_machine import EpsilonMachine +from sofic.generators.mixed_state_construction import _check_build_deadline from sofic.generators.prob import ( as_prob, has_symbolic, @@ -35,18 +36,25 @@ def build_bidirectional_epsilon_machine( forward: EpsilonMachine, reverse: EpsilonMachine, + *, + deadline: float | None = None, ) -> BidirectionalEpsilonMachine: - """Build M± from forward and reverse ε-machines via Eq. (15).""" + """Build M± from forward and reverse ε-machines via Eq. (15). + + Past ``deadline`` (a :func:`time.monotonic` value) the construction stops with + :class:`~sofic.exceptions.MixedStateDeadlineError`. + """ if forward.observation_alphabet != reverse.observation_alphabet: raise StochasticValidationError("forward and reverse observation alphabets must match") reverse = _relabel_collision_free(reverse, forward) rev_time = time_reverse_stochastic(reverse) compatible = _compatible_pairs(forward, reverse) - graph = _build_eq15_graph(forward, rev_time, sources=compatible) - graph, initial = _prune_to_stationary_support(graph, forward, reverse) + graph = _build_eq15_graph(forward, rev_time, sources=compatible, deadline=deadline) + graph, initial = _prune_to_stationary_support(graph, forward, reverse, deadline=deadline) if not initial: raise StochasticValidationError("bidirectional machine has empty joint support") + _check_build_deadline(deadline, "bidirectional construction") bidir = BidirectionalEpsilonMachine( graph=graph, @@ -66,6 +74,7 @@ def _build_eq15_graph( rev_time: EpsilonMachine, *, sources: set[tuple[Hashable, Hashable]] | None = None, + deadline: float | None = None, ) -> TransitionGraph: """Build the provisional Eq. (15) graph before pruning transient joint states.""" reverse_states = sorted(rev_time.states(), key=repr) @@ -76,6 +85,7 @@ def _build_eq15_graph( source = (alpha, gamma) if sources is not None and source not in sources: continue + _check_build_deadline(deadline, "bidirectional construction") for transition in forward.graph.out_transitions(alpha): symbol = transition.data.get(ATTR_EMISSION) prob_forward = as_prob(transition.data.get(ATTR_PROB, 0.0)) @@ -167,17 +177,20 @@ def _prune_to_stationary_support( reverse: EpsilonMachine, *, tol: float = 1e-12, + deadline: float | None = None, ) -> tuple[TransitionGraph, dict[tuple[Hashable, Hashable], Any]]: """Drop transient joint states and return a margin-matching stationary joint π.""" states = list(graph.states()) if not states: return graph, {} + _check_build_deadline(deadline, "bidirectional construction") keep = _recurrent_support(graph) or set(states) trimmed = _restrict_graph(graph, keep) # Dropping states outside the stationary support can leave others with incomplete rows, and # dropping those changes the support, so alternate the two until neither removes anything. for _ in range(len(states) + 1): + _check_build_deadline(deadline, "bidirectional construction") initial = _joint_pi_minimum_support(trimmed, forward, reverse, tol=tol) if not initial: return trimmed, {} @@ -535,14 +548,16 @@ def _validate_bidirectional_anatomy(bidir: BidirectionalEpsilonMachine, *, tol: ) -def infer_reverse_epsilon_machine(forward: EpsilonMachine, *, max_states: int = 10_000) -> EpsilonMachine: +def infer_reverse_epsilon_machine( + forward: EpsilonMachine, *, max_states: int = 10_000, deadline: float | None = None +) -> EpsilonMachine: """Infer a reverse ε-machine presentation for bidirectional construction. Time-reverses ``forward``, then builds the generator ε-machine via MSP and - probabilistic state merging (:meth:`EpsilonMachine.from_hmm`). + probabilistic state merging (:meth:`EpsilonMachine.from_hmm`, which takes ``max_states`` and ``deadline``). """ rev_hmm = time_reverse_stochastic(forward) - reverse = EpsilonMachine.from_hmm(rev_hmm, max_states=max_states) + reverse = EpsilonMachine.from_hmm(rev_hmm, max_states=max_states, deadline=deadline) warn_if_reverse_truncated(forward) return _relabel_collision_free(reverse, forward) diff --git a/sofic/generators/coupled_generators.py b/sofic/generators/coupled_generators.py index 80af736..4152af0 100644 --- a/sofic/generators/coupled_generators.py +++ b/sofic/generators/coupled_generators.py @@ -509,11 +509,17 @@ def generator_kernel(bidir: BidirectionalEpsilonMachine | _GeneratorProblem, c: def _decompose( - P: np.ndarray, lam0: np.ndarray, Q0: np.ndarray, R0: np.ndarray, maxiter: int = 500 + P: np.ndarray, + lam0: np.ndarray, + Q0: np.ndarray, + R0: np.ndarray, + maxiter: int = 500, + deadline: float | None = None, ) -> tuple[np.ndarray, np.ndarray, np.ndarray, float]: """Minimize ``H[lam]`` over exact decompositions ``P = sum_w lam_w Q_w R_w^T`` with SLSQP from ``(lam0, Q0, R0)``. Returns ``(lam, Q, R, residual)``, the residual being the largest entry of ``|sum_w lam_w Q_w R_w^T - P|``. + Past ``deadline`` (a :func:`time.monotonic` value) the objective raises :class:`_DeadlineReachedError`. """ k, na, nb = len(lam0), P.shape[0], P.shape[1] n = k + k * na + k * nb @@ -522,6 +528,8 @@ def split(x): return x[:k], x[k : k + k * na].reshape(k, na), x[k + k * na :].reshape(k, nb) def H(x): + if deadline is not None and time.monotonic() > deadline: + raise _DeadlineReachedError lam = np.maximum(x[:k], 1e-300) return float(-(lam * np.log2(lam)).sum()) @@ -612,8 +620,9 @@ def separating_optima( optimum has at most ``m`` terms, by Kumar, Li & El Gamal's argument for their bound of ``|S+| |S-|`` :cite:`Kumar2014` restricted to the support), keeps the solutions within ``atol`` of the best value, removes duplicates (equal sets of terms up to relabeling) and returns ``(best value, channels)``. The optimum need not - be unique, and only some optima may be generator states; :func:`generator_kernel` decides which. No new start - begins after ``deadline`` (a :func:`time.monotonic` value) once some decomposition has been found. + be unique, and only some optima may be generator states; :func:`generator_kernel` decides which. The first start + runs to the end; no later start begins after ``deadline`` (a :func:`time.monotonic` value), and one in progress + stops at it, adding nothing. """ problem = _as_problem(bidir) rng = rng or np.random.default_rng() @@ -621,17 +630,29 @@ def separating_optima( na, nb = P.shape sizes = sizes or range(2, min(int(np.count_nonzero(P > 1e-12)), 8) + 1) found = [] + stop = None for k in sizes: for _ in range(starts): - if deadline is not None and found and time.monotonic() > deadline: + if stop is not None and time.monotonic() > stop: break - lam, A, B, residual = _decompose( - P, rng.dirichlet(np.ones(k)), rng.dirichlet(np.ones(na), size=k), rng.dirichlet(np.ones(nb), size=k) - ) + try: + lam, A, B, residual = _decompose( + P, + rng.dirichlet(np.ones(k)), + rng.dirichlet(np.ones(na), size=k), + rng.dirichlet(np.ones(nb), size=k), + deadline=stop, + ) + except _DeadlineReachedError: + break + stop = deadline if residual <= 1e-10: live = lam > 1e-10 p = lam[live] found.append((float(-(p * np.log2(p)).sum()), lam[live], A[live], B[live])) + else: + continue + break if not found: return np.inf, [] best = min(f[0] for f in found) diff --git a/sofic/generators/epsilon_construction.py b/sofic/generators/epsilon_construction.py index 4a04ea5..26431b1 100644 --- a/sofic/generators/epsilon_construction.py +++ b/sofic/generators/epsilon_construction.py @@ -13,11 +13,12 @@ import numpy as np -from sofic.exceptions import MixedStateExplosionError, StochasticValidationError +from sofic.exceptions import MixedStateDeadlineError, MixedStateExplosionError, StochasticValidationError from sofic.generators.base import HiddenMarkovModel from sofic.generators.epsilon_machine import EpsilonMachine from sofic.generators.mealy import MealyHMM from sofic.generators.mixed_state import MixedState, MixedStatePresentation +from sofic.generators.mixed_state_construction import _check_build_deadline from sofic.generators.prob import ( array_sum, as_prob, @@ -38,32 +39,40 @@ _LIMIT_VERIFY_ATOL = 1e-9 -def build_epsilon_machine(hmm: HiddenMarkovModel, *, max_states: int = 10_000) -> EpsilonMachine: +def build_epsilon_machine( + hmm: HiddenMarkovModel, *, max_states: int = 10_000, deadline: float | None = None +) -> EpsilonMachine: + """The ε-machine of ``hmm``'s process; past ``deadline`` (a :func:`time.monotonic` value) every step stops with + :class:`~sofic.exceptions.MixedStateDeadlineError`.""" hmm = hmm.to_mealy() try: - presentation = _unifilar_presentation(hmm, max_states=max_states) + presentation = _unifilar_presentation(hmm, max_states=max_states, deadline=deadline) + except MixedStateDeadlineError: + raise except MixedStateExplosionError: - limit = _limit_machine(hmm, _filtered_belief(hmm), max_states=max(64, max_states // 10)) + limit = _limit_machine(hmm, _filtered_belief(hmm), max_states=max(64, max_states // 10), deadline=deadline) if limit is None: raise return limit - machine = _minimize(presentation, constraints=getattr(hmm, "symbol_constraints", None)) + machine = _minimize(presentation, constraints=getattr(hmm, "symbol_constraints", None), deadline=deadline) + _check_build_deadline(deadline, "ε-machine construction") seed = _boundary_belief(presentation) if seed is None: return machine - limit = _limit_machine(hmm, seed, max_states=len(list(presentation.states())) - 1) + limit = _limit_machine(hmm, seed, max_states=len(list(presentation.states())) - 1, deadline=deadline) if limit is None or len(list(limit.states())) >= len(list(machine.states())): return machine return limit -def _minimize(presentation: MealyHMM, *, constraints: Any = None) -> EpsilonMachine: +def _minimize(presentation: MealyHMM, *, constraints: Any = None, deadline: float | None = None) -> EpsilonMachine: + _check_build_deadline(deadline, "ε-machine minimization") stationary = presentation.stationary_distribution() if is_zero(array_sum(stationary)): raise StochasticValidationError("generator must have a stationary distribution") constraints = getattr(presentation, "symbol_constraints", None) or constraints - partitions = _refine_probabilistic_partitions(presentation, constraints=constraints) + partitions = _refine_probabilistic_partitions(presentation, constraints=constraints, deadline=deadline) return _quotient_machine(presentation, partitions, stationary, constraints=constraints) @@ -102,7 +111,9 @@ def _filtered_belief(hmm: MealyHMM, *, length: int = 4096) -> np.ndarray | None: return belief -def _limit_machine(hmm: MealyHMM, seed: np.ndarray | None, *, max_states: int) -> EpsilonMachine | None: +def _limit_machine( + hmm: MealyHMM, seed: np.ndarray | None, *, max_states: int, deadline: float | None = None +) -> EpsilonMachine | None: """The ε-machine generated from a limit belief, if it is finite and generates ``hmm``'s process. ``seed`` approximates a causal state of a process that synchronizes only asymptotically; entries @@ -120,21 +131,25 @@ def _limit_machine(hmm: MealyHMM, seed: np.ndarray | None, *, max_states: int) - try: limit = build_mixed_state_presentation( - hmm, initial_mixed_state=MixedState.from_vector(seed), max_states=max(1, max_states) + hmm, initial_mixed_state=MixedState.from_vector(seed), max_states=max(1, max_states), deadline=deadline ) + except MixedStateDeadlineError: + raise except MixedStateExplosionError: return None - candidate = _minimize(_unifilar_presentation(limit)) + candidate = _minimize(_unifilar_presentation(limit, deadline=deadline), deadline=deadline) + _check_build_deadline(deadline, "ε-machine construction") if _equivalence_error(candidate, hmm) > _LIMIT_VERIFY_ATOL: return None return candidate -def _unifilar_presentation(hmm: MealyHMM, *, max_states: int = 10_000) -> MealyHMM: +def _unifilar_presentation(hmm: MealyHMM, *, max_states: int = 10_000, deadline: float | None = None) -> MealyHMM: """Return a row-unifilar presentation generating the same process.""" if not hmm.is_unifilar(): - hmm = hmm.mixed_state_presentation(max_states=max_states) + hmm = hmm.mixed_state_presentation(max_states=max_states, deadline=deadline) if isinstance(hmm, MixedStatePresentation) and hmm.recurrent_states: + _check_build_deadline(deadline, "mixed-state presentation") return hmm.to_recurrent() return hmm @@ -143,6 +158,7 @@ def _refine_probabilistic_partitions( hmm: MealyHMM, *, constraints: Any = None, + deadline: float | None = None, ) -> list[set[Any]]: """Hopcroft-style refinement on probabilistic transition signatures.""" partitions: list[set[Any]] = [set(hmm.states())] @@ -152,6 +168,7 @@ def _refine_probabilistic_partitions( state_to_block = _state_to_block_index(partitions) new_partitions: list[set[Any]] = [] for block in partitions: + _check_build_deadline(deadline, "ε-machine minimization") subblocks = _split_block(hmm, block, state_to_block, constraints=constraints) if len(subblocks) > 1: changed = True diff --git a/sofic/generators/epsilon_machine.py b/sofic/generators/epsilon_machine.py index 32c3a84..b207c3c 100644 --- a/sofic/generators/epsilon_machine.py +++ b/sofic/generators/epsilon_machine.py @@ -41,12 +41,16 @@ def validate(self) -> None: self._check_unifilar() @classmethod - def from_hmm(cls, hmm: MealyHMM | MooreHMM, *, max_states: int = 10_000) -> EpsilonMachine: + def from_hmm( + cls, hmm: MealyHMM | MooreHMM, *, max_states: int = 10_000, deadline: float | None = None + ) -> EpsilonMachine: """Build the ε-machine of ``hmm``'s process. ``max_states`` caps the mixed-state enumeration used for non-unifilar input; exceeding it raises - :class:`~sofic.exceptions.MixedStateExplosionError`. + :class:`~sofic.exceptions.MixedStateExplosionError`. Past ``deadline`` (a + :func:`time.monotonic` value) the enumeration or the minimization stops with + :class:`~sofic.exceptions.MixedStateDeadlineError`, also an explosion. With floating-point probabilities, beliefs within the mixed-state tolerance (``rtol=1e-9``, ``atol=1e-12``) are merged. A belief set that @@ -56,7 +60,7 @@ def from_hmm(cls, hmm: MealyHMM | MooreHMM, *, max_states: int = 10_000) -> Epsi """ from sofic.generators.epsilon_construction import build_epsilon_machine - return build_epsilon_machine(hmm, max_states=max_states) + return build_epsilon_machine(hmm, max_states=max_states, deadline=deadline) @classmethod def from_sequence( @@ -522,16 +526,17 @@ def wheeler_statistical_complexity(self, **kwargs: Any) -> float: return wheeler_statistical_complexity(self, **kwargs) - def cryptic_order(self) -> int | float: + def cryptic_order(self, *, deadline: float | None = None) -> int | float: """Cryptic order ``k_chi``: retrodiction depth after synchronization. Distinct from :meth:`crypticity` (``χ = C_μ − E``) and from :meth:`~sofic.generators.bidirectional_epsilon_machine.BidirectionalEpsilonMachine.bidirectional_crypticity` - (``χ = C± − E``). See James et al., arXiv:1010.5545. + (``χ = C± − E``). See James et al., arXiv:1010.5545. Past ``deadline`` (a + :func:`time.monotonic` value) it raises :class:`TimeoutError`. """ from sofic.generators.synchronization import cryptic_order_from_graph, graph_from_epsilon_machine - return cryptic_order_from_graph(graph_from_epsilon_machine(self)) + return cryptic_order_from_graph(graph_from_epsilon_machine(self), deadline=deadline) def reset_threshold(self) -> int | float: """Reset threshold: shortest synchronizing (reset) word length. diff --git a/sofic/generators/generative_search.py b/sofic/generators/generative_search.py index c380a4a..967e99c 100644 --- a/sofic/generators/generative_search.py +++ b/sofic/generators/generative_search.py @@ -58,13 +58,16 @@ 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 lower bound on :math:`C_g` :cite:`LohrAy2009` that needs only the forward machine, computed first with at most 30% -of the budget. :func:`minimal_wyner_model` reports ``lower`` 0 there. +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 +times as many, so the bound only rises. :func:`minimal_wyner_model` reports ``lower`` 0 there. *Exploding builds.* When the reverse mixed-state presentation does not close (``bidir_class`` ``"explosion"``), -:func:`generative_model` brackets :math:`C_g` from the forward machine alone: ``lower`` is the same future-window -bound, and ``upper`` the least state entropy among the forward ε-machine and the belief-free HMM search's generators, -word-verified against the forward machine. The stages that need the reverse ε-machine are logged as skipped, and -``decomposition`` is ``None``. Other failed builds raise, as do :func:`minimal_wyner_model` and +or with a budget the build does not finish within half of it, :func:`generative_model` brackets :math:`C_g` from +the forward machine alone: ``lower`` is the same future-window bound (with the second pass on the time the search +leaves), and ``upper`` the least state entropy among the forward ε-machine and the belief-free HMM search's +generators, word-verified against the forward machine. The stages that need the reverse ε-machine are logged as +skipped, and ``decomposition`` is ``None``. Other failed builds raise, as do :func:`minimal_wyner_model` and :func:`~sofic.generators.functional_generators.minimal_functional_generator` on any failed build. Every candidate is word-verified. ``certified`` reports when ``lower`` meets ``upper``. @@ -145,12 +148,16 @@ # are worth it (900 s raised the bound on 3 x 5 to 3 x 11 joints of the binary 3-state dataset too). _GENERATOR_HEAVIEST_TERM_NODES = 2_000 _GENERATOR_HEAVIEST_TERM_MAX_DIMS = 14 -# Share of a time budget kept for that stage: the upper-bound searches stop this much early. +# Share of a time budget kept for that stage, or for the second future-window pass on a truncation: the upper-bound +# searches stop this much early. _GENERATOR_HEAVIEST_TERM_SHARE = 0.2 # Future-window coverage bound on truncated builds: boxes per explicit cap by window length (2 to 9 minutes per -# 3-state process without a deadline), and the share of a time budget it may use. +# 3-state process without a deadline), and the share of a time budget it may use. With a budget, a bracket still +# open after the searches gets a second pass with the time left, resuming the length with the larger bound for +# this many times its boxes. _WINDOW_NODES = {2: (1000, 2000), 3: (300, 600)} _WINDOW_SHARE = 0.3 +_WINDOW_SECOND_PASS = 10 # Stages of the bracket search that need the reverse ε-machine, skipped when its build explodes. _REVERSE_STAGES = ( "lower bounds", @@ -352,10 +359,14 @@ def _wyner_information(problem: _GeneratorProblem, seed: tuple[np.ndarray, ...]) return max(0.0, _entropy(problem.p_pair) - h_given_w) -def _cryptic_orders(bidir: BidirectionalEpsilonMachine) -> tuple[int | float, int | float] | None: - """``(kappa+, kappa-)`` from the forward and reverse ε-machines, or ``None`` if either fails.""" +def _cryptic_orders( + bidir: BidirectionalEpsilonMachine, deadline: float | None = None +) -> tuple[int | float, int | float] | None: + """``(kappa+, kappa-)`` from the forward and reverse ε-machines, or ``None`` if either fails or ``deadline`` (a + :func:`time.monotonic` value) passes first.""" try: - return bidir.forward_machine.cryptic_order(), bidir.reverse_machine.cryptic_order() + forward = bidir.forward_machine.cryptic_order(deadline=deadline) + return forward, bidir.reverse_machine.cryptic_order(deadline=deadline) except Exception: # noqa: BLE001 - only logged return None @@ -415,33 +426,61 @@ def resolve_bidirectional( return built.bidir, meta +def _window_stage(length: int) -> str: + return f"future-window generator coverage bound (L={length})" + + def _future_window_bound( forward: EpsilonMachine, *, explicit: int, k_max: int, deadline: float | None -) -> tuple[float, str, list[dict[str, Any]]]: - """The larger future-window generator coverage bound over the lengths of ``_WINDOW_NODES``, its source and - its log; a lower bound on :math:`C_g` from the forward machine alone. ``deadline`` is split evenly between - the lengths; the bounds stay valid past it, only looser.""" - from sofic.generators.generator_caps import generator_coverage_bound +) -> tuple[float, str, list[dict[str, Any]], dict[int, tuple[_GeneratorProblem, dict[int, list]]]]: + """The larger future-window generator coverage bound over the lengths of ``_WINDOW_NODES``, its source, its + log and, by length, the window problem with the open leaves of its branch and bound (for + :func:`_second_window_pass`); a lower bound on :math:`C_g` from the forward machine alone. ``deadline`` is + split evenly between the lengths; the bounds stay valid past it, only looser.""" + from sofic.generators.generator_caps import _resumable_coverage_bound from sofic.generators.generator_problem_spec import window_spec - value, source, log = 0.0, "trivial lower bound", [] + value, source, log, resume = 0.0, "trivial lower bound", [], {} for i, (length, nodes) in enumerate(_WINDOW_NODES.items()): stop = None if deadline is not None: now = time.monotonic() stop = now + max(0.0, deadline - now) / (len(_WINDOW_NODES) - i) - stage = f"future-window generator coverage bound (L={length})" - cov = generator_coverage_bound( - _GeneratorProblem.from_spec(window_spec(forward, length)), - k_max=k_max, - explicit=explicit, - max_nodes=nodes, - deadline=stop, - ) - log.append({"stage": stage, "value": cov.value, "caps": cov.caps}) + problem = _GeneratorProblem.from_spec(window_spec(forward, length)) + cov, leaves = _resumable_coverage_bound(problem, k_max=k_max, explicit=explicit, max_nodes=nodes, deadline=stop) + resume[length] = (problem, leaves) + log.append({"stage": _window_stage(length), "value": cov.value, "caps": cov.caps}) if cov.value > value: - value, source = cov.value, stage - return value, source, log + value, source = cov.value, _window_stage(length) + return value, source, log, resume + + +def _second_window_pass( + forward: EpsilonMachine, + *, + explicit: int, + k_max: int, + deadline: float, + source: str, + resume: dict[int, tuple[_GeneratorProblem, dict[int, list]]] | None, +) -> dict[str, Any]: + """Log entry of the future-window generator coverage bound continued until ``deadline`` on a bracket still open + after the searches. The branch and bound of the length that gave the first pass's bound (``source``) resumes + from its open leaves (``resume``, from :func:`_future_window_bound`) for ``_WINDOW_SECOND_PASS`` times its + boxes, so the bound only rises; without them the longest window starts afresh.""" + from sofic.generators.generator_caps import _resumable_coverage_bound + from sofic.generators.generator_problem_spec import window_spec + + length = next((L for L in _WINDOW_NODES if source == _window_stage(L)), max(_WINDOW_NODES)) + problem, leaves = (resume or {}).get(length, (None, None)) + if problem is None: + problem = _GeneratorProblem.from_spec(window_spec(forward, length)) + nodes = tuple(_WINDOW_SECOND_PASS * n for n in _WINDOW_NODES[length]) + cov, _ = _resumable_coverage_bound( + problem, k_max=k_max, explicit=explicit, max_nodes=nodes, deadline=deadline, leaves=leaves + ) + stage = f"future-window generator coverage bound (L={length}, second pass)" + return {"stage": stage, "value": cov.value, "caps": cov.caps} def _model_from_matrices( @@ -493,7 +532,8 @@ def _forward_only_result( ``lower`` is the future-window generator coverage bound, computed first with at most 30% of ``time_budget``. ``upper`` is the least state entropy among the forward ε-machine and the belief-free HMM search's generators (the rest of the budget, split evenly between the state counts), each word-verified against the forward machine. - The stages that need the reverse ε-machine are logged as skipped. + When the bracket is still open, the time the search leaves goes to a second window pass, which resumes the + first. The stages that need the reverse ε-machine are logged as skipped. """ from sofic.generators.hmm_search import _stationary from sofic.generators.matrices import emission_tensors, symbol_matrices @@ -503,7 +543,9 @@ def _forward_only_result( log.append({"stage": "bidirectional build", **build_meta}) end = None if time_budget is None else log.start + time_budget stop = None if time_budget is None else log.start + _WINDOW_SHARE * time_budget - lower, lower_source, window_log = _future_window_bound(forward, explicit=explicit, k_max=k_max, deadline=stop) + lower, lower_source, window_log, resume = _future_window_bound( + forward, explicit=explicit, k_max=k_max, deadline=stop + ) for entry in window_log: log.append(entry) for stage in (*_REVERSE_STAGES, *(("restricted global bound",) if global_bound else ())): @@ -543,6 +585,14 @@ def _forward_only_result( if float(np.abs(drift).max()) > reproduction_atol: continue upper = _entropy(start) + exhausted = end is not None and time.monotonic() >= end + if end is not None and not exhausted and upper - lower > _CERT_TOL: + entry = _second_window_pass( + forward, explicit=explicit, k_max=k_max, deadline=end, source=lower_source, resume=resume + ) + log.append(entry) + if entry["value"] > lower: + lower, lower_source = entry["value"], entry["stage"] return _finalize_result( GenerativeModelResult( model=model, @@ -553,7 +603,7 @@ def _forward_only_result( exact_common_information_estimate=None, separating_variables_generate=False, stages=log, - budget_exhausted=end is not None and time.monotonic() >= end, + budget_exhausted=exhausted, reproduction_error=error, structure={ "n_states": len(start), @@ -709,11 +759,13 @@ def _bracket_search( time_budget: float | None = None, rng: np.random.Generator | None = None, window_lower: tuple[float, str] | None = None, + window_resume: dict[int, tuple[_GeneratorProblem, dict[int, list]]] | None = None, ) -> GenerativeModelResult: """Generator search ranked by state entropy or by ``I[W : S+, S-]``; see the module docstring. ``window_lower`` is ``(value, source)`` of a lower bound on the process when ``bidir`` is a truncation; it - replaces every lower bound computed on ``bidir``. + replaces every lower bound computed on ``bidir``. ``window_resume`` is the state its second pass resumes + (from :func:`_future_window_bound`). """ from sofic.generators.functional_generators import functional_cover_search from sofic.generators.lifted_common_information import _unconstrained_channel @@ -730,13 +782,14 @@ def _bracket_search( lifted = problem.lifted log = _StageLog() end = None if time_budget is None else log.start + time_budget - reserve = ( - _GENERATOR_HEAVIEST_TERM_SHARE * time_budget - if time_budget is not None - and generator_heaviest_term - and not wyner + heaviest_last = ( + generator_heaviest_term and not truncated and problem.n_plus + problem.n_minus <= _GENERATOR_HEAVIEST_TERM_MAX_DIMS + ) + reserve = ( + _GENERATOR_HEAVIEST_TERM_SHARE * time_budget + if time_budget is not None and not wyner and (heaviest_last or truncated) else 0.0 ) deadline = end @@ -883,14 +936,15 @@ def heaviest_term(aim: float) -> None: if want_generator_coverage and not theorem and not out_of_time("generator coverage bound"): generator_coverage() - kappa = _cryptic_orders(bidir) + stage_deadline = share(0.1) + kappa = _cryptic_orders(bidir, deadline=stage_deadline) log.append( { "stage": "persistent criteria", "value": (f_crit, r_crit), "theorem applies": theorem, "cryptic orders": kappa, - "block persistent crypticities": _block_persistent_crypticities(problem), + "block persistent crypticities": _block_persistent_crypticities(problem, deadline=stage_deadline), } ) P_joint = np.einsum("p,pa,pb->ab", lifted.p, lifted.plus, lifted.minus) @@ -938,11 +992,18 @@ def maybe_return_early() -> GenerativeModelResult | None: ) if "machines" in stages: + # the ε-machine always generates the process, so the bracket keeps an upper bound at any budget offer("epsilon machine", problem.epsilon_seed()) - offer("reverse epsilon machine", problem.reverse_seed()) - offer("bidirectional machine", problem.pair_seed()) - offer("canonical RFSA generator", problem.residual_seed()[0]) - offer("maximized prime átomaton generator", problem.prime_atomaton_seed()[0]) + machines = ( + ("reverse epsilon machine", problem.reverse_seed), + ("bidirectional machine", problem.pair_seed), + ("canonical RFSA generator", lambda: problem.residual_seed()[0]), + ("maximized prime átomaton generator", lambda: problem.prime_atomaton_seed()[0]), + ) + for name, seed in machines: + if out_of_time("candidate machines"): + break + offer(name, seed()) early = maybe_return_early() if early is not None and early.certified: return _finalize_result(early) @@ -1008,8 +1069,12 @@ def maybe_return_early() -> GenerativeModelResult | None: rng=rng, ) log.append({"stage": "simplex-chain search", "values": {res.side: res.entropy for res in chains}}) + # with a budget, a chain no lighter than the ε-machine (which generates the process) cannot lower the bracket + # and a large one takes long to lift + ceiling = min((c[0] for c in candidates if c[1] == "epsilon machine"), default=math.inf) for res in chains: - offer(f"simplex chain ({res.side}, k={len(res.pi)})", coupled_seed_from_hmm(problem, res.matrices)) + if end is None or res.entropy < ceiling - 1e-9: + offer(f"simplex chain ({res.side}, k={len(res.pi)})", coupled_seed_from_hmm(problem, res.matrices)) early = maybe_return_early() if early is not None and early.certified: return _finalize_result(early) @@ -1063,6 +1128,7 @@ def maybe_return_early() -> GenerativeModelResult | None: backend="numpy", cutoff=1e-10, rng=rng, + deadline=share(0.25), ) if c is not None: c = polish_separating_channel(problem, c) @@ -1076,6 +1142,8 @@ def maybe_return_early() -> GenerativeModelResult | None: optima.append(c) except (StochasticValidationError, ImportError): pass + except TimeoutError as exc: + log.append({"stage": "dit exact common information", "error": str(exc)}) if wyner and dit_fallback and dit_small and not out_of_time("dit Wyner common information"): try: c = _unconstrained_channel( @@ -1088,9 +1156,13 @@ def maybe_return_early() -> GenerativeModelResult | None: backend="numpy", cutoff=1e-10, rng=rng, + deadline=share(0.25), ) except (StochasticValidationError, ImportError): c = None + except TimeoutError as exc: + log.append({"stage": "dit Wyner common information", "error": str(exc)}) + c = None if c is not None: violation, K = generator_kernel(problem, c) log.append( @@ -1442,6 +1514,25 @@ def maybe_return_early() -> GenerativeModelResult | None: result.lower = float(min(gtb.value, result.upper)) result.lower_source = "generator heaviest-term bound (certified)" result.lower_certified = True + if ( + truncated + and not wyner + and end is not None + and result.lower < result.upper - _CERT_TOL + and not out_of_time("future-window generator coverage bound (second pass)") + ): + entry = _second_window_pass( + reference, + explicit=generator_caps, + k_max=coverage_k_max, + deadline=end, + source=window_lower[1], + resume=window_resume, + ) + log.append(entry) + if entry["value"] > result.lower + 1e-9: + result.lower = float(min(entry["value"], result.upper)) + result.lower_source = entry["stage"] result.budget_exhausted = bool(skipped) return _finalize_result(result) @@ -1642,11 +1733,13 @@ def generative_model( The final ``stages`` entry is a **reliability summary** (``certified``, ``gap``, sources, …). With ``time_budget`` (seconds) the search becomes anytime: every stage gets a share of the time left and stops at its deadline, the stages from the simplex-chain search on stop a fifth of the budget early - so that the final generator heaviest-term bound keeps that time, and once the budget is spent the rest are - skipped and the best verified bracket so far is returned with ``budget_exhausted`` set. The coupled - search's ε-machine seed and the targeted line-split polish finish past their deadlines, so a run can - still overrun by those. The bidirectional build's retry ladder counts against the budget - (see :func:`~sofic.generators.bidirectional_build.build_bidirectional_with_ladder`). + so that the final generator heaviest-term bound (on a truncation, the second future-window pass) keeps + that time, and once the budget is spent the rest are skipped and the best verified bracket so far is + returned with ``budget_exhausted`` set. The coupled search's ε-machine seed, the first start of the exact + common information search and the targeted line-split polish finish past their deadlines, so a run can + 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`. """ start = time.monotonic() @@ -1667,12 +1760,12 @@ def generative_model( time_budget=None if time_budget is None else max(0.0, time_budget - (time.monotonic() - start)), rng=rng, ) - window_lower, window_log = None, [] + window_lower, window_log, window_resume = None, [], None if build_meta["bidir_class"] == "truncated": stop = None if time_budget is not None: stop = time.monotonic() + _WINDOW_SHARE * max(0.0, time_budget - (time.monotonic() - start)) - value, source, window_log = _future_window_bound( + value, source, window_log, window_resume = _future_window_bound( bidir.forward_machine, explicit=generator_caps, k_max=coverage_k_max, deadline=stop ) window_lower = (value, source) @@ -1712,6 +1805,7 @@ def generative_model( time_budget=time_budget, rng=rng, window_lower=window_lower, + window_resume=window_resume, ) result.stages[:0] = [{"stage": "bidirectional build", **build_meta}, *window_log] return result diff --git a/sofic/generators/generator_caps.py b/sofic/generators/generator_caps.py index 18bd104..cbc8ce6 100644 --- a/sofic/generators/generator_caps.py +++ b/sofic/generators/generator_caps.py @@ -281,7 +281,10 @@ def _tighten(lo: np.ndarray, hi: np.ndarray) -> tuple[np.ndarray, np.ndarray] | def _branch_and_bound( - relaxation: _HeaviestStatesRelaxation, max_nodes: int, deadline: float | None = None + relaxation: _HeaviestStatesRelaxation, + max_nodes: int, + deadline: float | None = None, + leaves: list[tuple[float, Boxes, Path]] | None = None, ) -> tuple[list[tuple[float, Boxes, Path]], list[tuple[Boxes, Path]]]: """Best-first branching over belief boxes. @@ -290,6 +293,9 @@ def _branch_and_bound( by :func:`_tighten` miss the simplex, so the open and infeasible leaves cover every generator. With a ``deadline`` each child LP is also limited to the time left, since a single degenerate LP can otherwise run far past it; a cut-off LP keeps its parent's bound. The root LP always runs to the end. + ``leaves``, the open leaves of an earlier call on the same relaxation, resumes that search for + ``max_nodes`` more nodes instead of starting at the root (its infeasible leaves are not returned again); + without deadlines, ``n`` nodes and then ``m`` more branch exactly as ``n + m`` nodes. """ k = relaxation.k root = _root(relaxation) @@ -297,12 +303,16 @@ def _branch_and_bound( def left() -> float | None: return None if deadline is None else deadline - time.monotonic() - first = relaxation.bound(root) - if first is None: - return [], [(root, ())] - heap: list[tuple[float, int, Boxes, Path]] = [(-first, 0, root, ())] + if leaves is None: + first = relaxation.bound(root) + if first is None: + return [], [(root, ())] + heap: list[tuple[float, int, Boxes, Path]] = [(-first, 0, root, ())] + else: + heap = [(-bound, i, boxes, path) for i, (bound, boxes, path) in enumerate(leaves)] + heapq.heapify(heap) infeasible: list[tuple[Boxes, Path]] = [] - order = itertools.count(1) + order = itertools.count(len(heap)) nodes = 0 while heap and nodes < max_nodes and (deadline is None or time.monotonic() < deadline): bound, _, boxes, path = heapq.heappop(heap) @@ -322,6 +332,8 @@ def left() -> float | None: infeasible.append((child, child_path)) else: heapq.heappush(heap, (-min(-bound, value), next(order), child, child_path)) + # in pop order, so a search resumed from these leaves breaks ties as this one would have + heap.sort(key=lambda entry: entry[:2]) return [(-b, boxes, path) for b, _, boxes, path in heap], infeasible @@ -525,22 +537,40 @@ def generator_coverage_bound( every cap stays valid, only looser. """ problem = bidir if isinstance(bidir, _GeneratorProblem) else _GeneratorProblem(bidir) + return _resumable_coverage_bound(problem, k_max=k_max, explicit=explicit, max_nodes=max_nodes, deadline=deadline)[0] + + +def _resumable_coverage_bound( + problem: _GeneratorProblem, + *, + k_max: int, + explicit: int, + max_nodes: tuple[int, ...], + deadline: float | None, + leaves: dict[int, list[tuple[float, Boxes, Path]]] | None = None, +) -> tuple[CoverageLowerResult, dict[int, list[tuple[float, Boxes, Path]]]]: + """:func:`generator_coverage_bound` with the open leaves of each explicit cap's branch and bound; ``leaves`` + from an earlier call on the same problem resumes those searches, each for its ``max_nodes`` more nodes.""" P = problem.lifted.plus.T @ (problem.p_pair[:, None] * problem.lifted.minus) k_used = max(1, min(int(k_max), *P.shape)) caps = list(mu_caps(P, k=k_used)[0]) n_explicit = min(explicit, k_used) + open_leaves: dict[int, list[tuple[float, Boxes, Path]]] = {} for j in range(1, n_explicit + 1): budget = max_nodes[min(j, len(max_nodes)) - 1] stop = None if deadline is not None: now = time.monotonic() stop = now + max(0.0, deadline - now) / (n_explicit - j + 1) - caps[j - 1] = min(caps[j - 1], generator_weight_cap(problem, j, max_nodes=budget, deadline=stop)) + resume = None if leaves is None else leaves.get(j) + open_leaves[j], _ = _branch_and_bound(_HeaviestStatesRelaxation(problem, j), budget, stop, resume) + cap = min(1.0, max((leaf[0] for leaf in open_leaves[j]), default=0.0) + _LP_SLACK) + caps[j - 1] = min(caps[j - 1], cap) for j in range(1, k_used): caps[j] = min(caps[j], caps[j - 1] + caps[0]) for j in range(k_used - 2, -1, -1): caps[j] = min(caps[j], caps[j + 1]) - return CoverageLowerResult(coverage_entropy_lower(caps), tuple(caps), True, caps[0], k_used) + return CoverageLowerResult(coverage_entropy_lower(caps), tuple(caps), True, caps[0], k_used), open_leaves __all__ = [ diff --git a/sofic/generators/lifted_common_information.py b/sofic/generators/lifted_common_information.py index 97af531..78a68b0 100644 --- a/sofic/generators/lifted_common_information.py +++ b/sofic/generators/lifted_common_information.py @@ -257,10 +257,12 @@ def _unconstrained_channel( backend: str, cutoff: float, rng: np.random.Generator, + deadline: float | None = None, ) -> np.ndarray | None: """Channel of the ordinary (dit) Wyner or exact optimum, as a start; ``None`` if that optimizer fails. - Pairs of ``problem`` that ``joint`` leaves out (below a mass cutoff) get the channel's state marginal. + Pairs of ``problem`` that ``joint`` leaves out (below a mass cutoff) get the channel's state marginal. Past + ``deadline`` (a :func:`time.monotonic` value) the optimizer stops with :class:`TimeoutError`. """ optimizer = _optimize_wyner_common_information if kind == "wyner" else _optimize_exact_common_information try: @@ -275,6 +277,7 @@ def _unconstrained_channel( backend=backend, cutoff=cutoff, rng=rng, + deadline=deadline, ) except StochasticValidationError: return None @@ -391,8 +394,9 @@ def lifted_model( ) -> WynerGenerativeModel | MinimalGenerativeModel: """Lifted Wyner (``objective="wyner"``) or exact (``"exact"``) generative model; see the module docstring. - Backs ``wyner_generative_model`` and ``minimal_generative_model``. No start, dit run or refinement begins - after ``deadline`` (:func:`time.monotonic`); the ε-machine channels always lift, so a model is still returned. + Backs ``wyner_generative_model`` and ``minimal_generative_model``. No start or refinement begins after + ``deadline`` (:func:`time.monotonic`), and the dit run stops at it; the ε-machine channels always lift, so a + model is still returned. """ if cutoff < 0.0: raise ValueError("cutoff must be nonnegative") @@ -410,21 +414,25 @@ def lifted_model( value, residual = _entropy_bits(problem.p), 0.0 else: rng = rng or np.random.default_rng() - unconstrained = ( - None - if deadline is not None and time.monotonic() >= deadline - else _unconstrained_channel( - problem, - joint, - objective, - niter=niter, - maxiter=maxiter, - polish=polish, - backend=backend, - cutoff=cutoff, - rng=rng, + try: + unconstrained = ( + None + if deadline is not None and time.monotonic() >= deadline + else _unconstrained_channel( + problem, + joint, + objective, + niter=niter, + maxiter=maxiter, + polish=polish, + backend=backend, + cutoff=cutoff, + rng=rng, + deadline=deadline, + ) ) - ) + except TimeoutError: + unconstrained = None k = int(bound) if bound is not None else len(problem.pairs) refined, candidates = _optimize( problem, objective, k, starts, maxiter, markov_atol / 2, rng, [], deadline=deadline diff --git a/sofic/generators/mealy.py b/sofic/generators/mealy.py index 8c944c1..162fe65 100644 --- a/sofic/generators/mealy.py +++ b/sofic/generators/mealy.py @@ -174,12 +174,14 @@ def mixed_state_presentation( *, initial_mixed_state: MixedState | Mapping[Hashable, float] | Sequence[float] | None = None, max_states: int = 10_000, + deadline: float | None = None, ) -> MixedStatePresentation: - """Build the mixed-state presentation (observer belief dynamics).""" + """Build the mixed-state presentation (observer belief dynamics); ``max_states`` and ``deadline`` are + as in :func:`~sofic.generators.mixed_state_construction.build_mixed_state_presentation`.""" from sofic.generators.mixed_state import MixedStatePresentation return MixedStatePresentation.from_presentation( - self, initial_mixed_state=initial_mixed_state, max_states=max_states + self, initial_mixed_state=initial_mixed_state, max_states=max_states, deadline=deadline ) def to_edge_machine(self, iterations: int = 1, style: int = 0) -> MealyHMM: diff --git a/sofic/generators/minimal_generative_model.py b/sofic/generators/minimal_generative_model.py index 4a59525..0677699 100644 --- a/sofic/generators/minimal_generative_model.py +++ b/sofic/generators/minimal_generative_model.py @@ -2,10 +2,12 @@ from __future__ import annotations +import time import warnings from collections import defaultdict from collections.abc import Hashable from dataclasses import dataclass +from types import MethodType from typing import TYPE_CHECKING, Any, cast import numpy as np @@ -671,7 +673,9 @@ def _optimized_auxiliary_joint( polish: float | bool, backend: str, rng: np.random.Generator | None, + deadline: float | None = None, ) -> tuple[Any, np.ndarray]: + timed = {} if deadline is None else {"deadline": deadline} opt = optimizer( dist, bound=bound, @@ -680,6 +684,7 @@ def _optimized_auxiliary_joint( polish=polish, backend=backend, rng=rng, + **timed, ) aux_joint = _as_numpy(opt.construct_joint(opt._optima)) @@ -734,7 +739,10 @@ def _auxiliary_state_channel( backend: str, cutoff: float, rng: np.random.Generator | None, + deadline: float | None = None, ) -> tuple[dict[tuple[Hashable, Hashable], dict[Hashable, float]], float]: + """The optimizer's generative-state channel and optimum; past ``deadline`` (a :func:`time.monotonic` value) + the optimizer stops with :class:`TimeoutError`.""" plus_states = {pair[0] for pair in joint} minus_states = {pair[1] for pair in joint} if len(plus_states) <= 1 or len(minus_states) <= 1: @@ -754,6 +762,7 @@ def _auxiliary_state_channel( polish=polish, backend=backend, rng=rng, + deadline=deadline, ) raw_channel, validation_error = _raw_channel_from_auxiliary_joint( aux_joint, @@ -776,6 +785,7 @@ def _auxiliary_state_channel( polish=False, backend=backend, rng=rng, + deadline=deadline, ) raw_channel, retry_error = _raw_channel_from_auxiliary_joint( aux_joint, @@ -836,6 +846,21 @@ def _entropy(masses: Any) -> float: return shannon_entropy(masses, atol=0.0) +def _stop_at(opt: Any, deadline: float | None) -> None: + """Make the dit optimizer ``opt`` raise :class:`TimeoutError` at its first objective evaluation past + ``deadline`` (a :func:`time.monotonic` value); dit binds its own objective only when none is set.""" + if deadline is None: + return + objective = MethodType(opt._objective(), opt) + + def timed(x: np.ndarray) -> float: + if time.monotonic() > deadline: + raise TimeoutError("dit optimization reached its deadline") + return objective(x) + + opt.objective = timed + + def _optimize_exact_common_information( dist: Any, *, @@ -845,6 +870,7 @@ def _optimize_exact_common_information( polish: float | bool, backend: str, rng: np.random.Generator | None, + deadline: float | None = None, ) -> Any: from dit.multivariate._backend import _make_backend_subclass from dit.multivariate.common_informations.exact_common_information import ExactCommonInformation @@ -854,6 +880,7 @@ def _optimize_exact_common_information( if isinstance(polish, int | float) and not isinstance(polish, bool) and polish > 0.0: options = opt._additional_options.setdefault("options", {}) options["ftol"] = min(float(polish), float(options.get("ftol", polish))) + _stop_at(opt, deadline) opt.optimize(niter=niter, maxiter=maxiter, polish=polish, rng=rng) return opt @@ -867,6 +894,7 @@ def _optimize_wyner_common_information( polish: float | bool, backend: str, rng: np.random.Generator | None, + deadline: float | None = None, ) -> Any: from dit.multivariate._backend import _make_backend_subclass from dit.multivariate.common_informations.wyner_common_information import WynerCommonInformation @@ -876,6 +904,7 @@ def _optimize_wyner_common_information( if isinstance(polish, int | float) and not isinstance(polish, bool) and polish > 0.0: options = opt._additional_options.setdefault("options", {}) options["ftol"] = min(float(polish), float(options.get("ftol", polish))) + _stop_at(opt, deadline) opt.optimize(niter=niter, maxiter=maxiter, polish=polish, rng=rng) return opt diff --git a/sofic/generators/mixed_state.py b/sofic/generators/mixed_state.py index c65805f..f0ca3b9 100644 --- a/sofic/generators/mixed_state.py +++ b/sofic/generators/mixed_state.py @@ -138,10 +138,13 @@ def from_presentation( *, initial_mixed_state: MixedState | Mapping[Hashable, float] | Sequence[float] | None = None, max_states: int = 10_000, + deadline: float | None = None, ) -> MixedStatePresentation: from sofic.generators.mixed_state_construction import build_mixed_state_presentation - return build_mixed_state_presentation(hmm, initial_mixed_state=initial_mixed_state, max_states=max_states) + return build_mixed_state_presentation( + hmm, initial_mixed_state=initial_mixed_state, max_states=max_states, deadline=deadline + ) def to_recurrent(self) -> MealyHMM: """Return the recurrent component with stationary initial weights. diff --git a/sofic/generators/mixed_state_construction.py b/sofic/generators/mixed_state_construction.py index 197e3aa..eeb95b4 100644 --- a/sofic/generators/mixed_state_construction.py +++ b/sofic/generators/mixed_state_construction.py @@ -3,13 +3,14 @@ from __future__ import annotations import bisect +import time from collections import deque from collections.abc import Hashable, Mapping, Sequence from typing import Any import numpy as np -from sofic.exceptions import MixedStateExplosionError +from sofic.exceptions import MixedStateDeadlineError, MixedStateExplosionError from sofic.generators.base import HiddenMarkovModel from sofic.generators.matrices import start_vector, symbol_matrices from sofic.generators.mealy import MealyHMM @@ -35,6 +36,13 @@ _NUMERIC_WINDOW = 1e-9 +def _check_build_deadline(deadline: float | None, what: str) -> None: + """Raise :class:`~sofic.exceptions.MixedStateDeadlineError` once ``deadline`` (a :func:`time.monotonic` value) + has passed.""" + if deadline is not None and time.monotonic() > deadline: + raise MixedStateDeadlineError(f"{what} reached its deadline") + + def _terminal_recurrent_states(graph: TransitionGraph) -> frozenset[Any]: return graph.terminal_recurrent_states() @@ -64,6 +72,7 @@ def build_mixed_state_presentation( *, initial_mixed_state: MixedState | Mapping[Hashable, Any] | Sequence[Any] | None = None, max_states: int = 10_000, + deadline: float | None = None, ) -> MixedStatePresentation: """Enumerate the mixed-state presentation of ``hmm``. @@ -79,6 +88,10 @@ def build_mixed_state_presentation( max_states Safety cap on enumerated beliefs (symbolic machines can otherwise grow without bound when successor beliefs fail to identify). + deadline + A :func:`time.monotonic` value, checked before each belief is expanded; past it the + enumeration stops with :class:`~sofic.exceptions.MixedStateDeadlineError`, a + :class:`~sofic.exceptions.MixedStateExplosionError`. """ if isinstance(hmm, MixedStatePresentation): raise TypeError("cannot build a mixed-state presentation from another mixed-state presentation") @@ -171,6 +184,10 @@ def register(state: MixedState) -> MixedState: register(eta0) while queue: + if deadline is not None and time.monotonic() > deadline: + raise MixedStateDeadlineError( + f"mixed-state presentation reached its deadline with {len(unique)} beliefs and {len(queue)} unexpanded" + ) eta = queue.popleft() row = eta.as_array() for symbol in symbols: diff --git a/sofic/generators/separating_generators.py b/sofic/generators/separating_generators.py index cd99a4e..b20e496 100644 --- a/sofic/generators/separating_generators.py +++ b/sofic/generators/separating_generators.py @@ -574,11 +574,14 @@ def lookahead_generator( ) -def _block_persistent_crypticities(problem: _GeneratorProblem, L_max: int = 4, max_size: int = 200_000): +def _block_persistent_crypticities( + problem: _GeneratorProblem, L_max: int = 4, max_size: int = 200_000, deadline: float | None = None +): r"""``[(L, p.chi+, p.chi-)]`` of the block processes :math:`Y_L` for ``L = 1 .. L_max``, from the tensor :math:`\Pr(S^-_0, X_{0:L}, S^+_L)`: :math:`p.\chi^+(Y_L) = \H{S^+_L \mid X_{0:}}` and :math:`p.\chi^-(Y_L) = \H{S^-_0 \mid X_{:L}}`, both zero exactly from the cryptic order on. Stops once both - vanish or the tensor would exceed ``max_size`` entries.""" + vanish, the tensor would exceed ``max_size`` entries, or ``deadline`` (a :func:`time.monotonic` value) has + passed before a length after the first.""" lif = problem.lifted pp = lif.p T = lif.edges / np.where(pp > 0, pp, 1.0)[:, None, None] @@ -588,6 +591,8 @@ def _block_persistent_crypticities(problem: _GeneratorProblem, L_max: int = 4, m if L > 1: if cur.size * T.shape[1] > max_size: break + if deadline is not None and time.monotonic() > deadline: + break cur = np.einsum("bwq,qxr->bwxr", cur, T).reshape(cur.shape[0], -1, T.shape[-1]) J = np.einsum("bwr,ra->bwa", cur, lif.plus) h = _entropy(J) diff --git a/sofic/generators/synchronization.py b/sofic/generators/synchronization.py index 3441d8f..81f257c 100644 --- a/sofic/generators/synchronization.py +++ b/sofic/generators/synchronization.py @@ -9,6 +9,7 @@ import bisect import math +import time from collections.abc import Hashable, Mapping from dataclasses import dataclass, field from typing import Any @@ -72,27 +73,34 @@ def labeled_graph_of(graph: TopologicalUnifilarGraph) -> LabeledGraph: ) -def power_automaton(graph: TopologicalUnifilarGraph) -> PowerAutomaton: +def power_automaton(graph: TopologicalUnifilarGraph, *, deadline: float | None = None) -> PowerAutomaton: """Build the power automaton by subset construction from the full state set. When ``graph`` is Wheeler the construction runs over co-lex *intervals* instead of arbitrary subsets. Path coherence guarantees the two agree :cite:`Gagie2017`, but the interval form visits at most ``n(n+1)/2`` states and steps in ``O(log n)`` rather than ``O(n)``, so the synchronization - orders built on top of it stay polynomial. + orders built on top of it stay polynomial. Past ``deadline`` (a + :func:`time.monotonic` value) the construction raises :class:`TimeoutError`. """ order = wheeler_order_of_graph(labeled_graph_of(graph)) if order is not None: - return _interval_power_automaton(graph, order) - return _subset_power_automaton(graph) + return _interval_power_automaton(graph, order, deadline) + return _subset_power_automaton(graph, deadline) -def _subset_power_automaton(graph: TopologicalUnifilarGraph) -> PowerAutomaton: +def _check_deadline(deadline: float | None, what: str) -> None: + if deadline is not None and time.monotonic() > deadline: + raise TimeoutError(f"{what} reached its deadline") + + +def _subset_power_automaton(graph: TopologicalUnifilarGraph, deadline: float | None = None) -> PowerAutomaton: start = frozenset(graph.states) pa = PowerAutomaton(graph=graph, start=start) queue = [start] seen = {start} while queue: + _check_deadline(deadline, "power automaton") current = queue.pop(0) pa.transitions.setdefault(current, {}) for symbol in sorted(graph.alphabet, key=repr): @@ -106,7 +114,9 @@ def _subset_power_automaton(graph: TopologicalUnifilarGraph) -> PowerAutomaton: return pa -def _interval_power_automaton(graph: TopologicalUnifilarGraph, order: WheelerOrder) -> PowerAutomaton: +def _interval_power_automaton( + graph: TopologicalUnifilarGraph, order: WheelerOrder, deadline: float | None = None +) -> PowerAutomaton: """Subset construction restricted to intervals of a Wheeler order. Axiom two makes the target rank non-decreasing in the source rank for each @@ -142,6 +152,7 @@ def as_subset(interval: tuple[int, int]) -> frozenset[Hashable]: queue = [start] seen = {start} while queue: + _check_deadline(deadline, "power automaton") current = queue.pop(0) out_map = pa.transitions.setdefault(as_subset(current), {}) for symbol in sorted(graph.alphabet, key=repr): @@ -293,7 +304,7 @@ def shortest_synchronizing_word_from_graph( return word -def _mergeable_pairs(graph: TopologicalUnifilarGraph) -> set[frozenset[Hashable]]: +def _mergeable_pairs(graph: TopologicalUnifilarGraph, deadline: float | None = None) -> set[frozenset[Hashable]]: """Return the distinct state pairs that some common word drives to one state. Seeded by pairs with a shared successor on one symbol, then closed under @@ -303,6 +314,7 @@ def _mergeable_pairs(graph: TopologicalUnifilarGraph) -> set[frozenset[Hashable] predecessors: dict[frozenset[Hashable], set[frozenset[Hashable]]] = {} mergeable: set[frozenset[Hashable]] = set() for index, left in enumerate(states): + _check_deadline(deadline, "mergeable pairs") for right in states[index + 1 :]: pair = frozenset((left, right)) for symbol in graph.alphabet: @@ -315,6 +327,7 @@ def _mergeable_pairs(graph: TopologicalUnifilarGraph) -> set[frozenset[Hashable] predecessors.setdefault(frozenset((left_next, right_next)), set()).add(pair) queue = list(mergeable) while queue: + _check_deadline(deadline, "mergeable pairs") for pair in predecessors.get(queue.pop(), ()): if pair not in mergeable: mergeable.add(pair) @@ -322,7 +335,7 @@ def _mergeable_pairs(graph: TopologicalUnifilarGraph) -> set[frozenset[Hashable] return mergeable -def cryptic_order_from_graph(graph: TopologicalUnifilarGraph) -> int | float: +def cryptic_order_from_graph(graph: TopologicalUnifilarGraph, *, deadline: float | None = None) -> int | float: """Cryptic order ``k_chi = min{k : H[S_k | X_{0:inf}] = 0}`` :cite:`James2010`. Two distinct states remain confusable given the entire future with positive @@ -333,10 +346,12 @@ def cryptic_order_from_graph(graph: TopologicalUnifilarGraph) -> int | float: ``k_chi`` is one more than the longest path from the full-support start through ambiguous states (``math.inf`` when such a path can cycle). Since every non-singleton is transient, ``k_chi`` never exceeds the Markov order. + Past ``deadline`` (a :func:`time.monotonic` value) the pair search and the + power automaton raise :class:`TimeoutError`. """ if not graph.states: return 0 - mergeable = _mergeable_pairs(graph) + mergeable = _mergeable_pairs(graph, deadline) def ambiguous(pa_state: frozenset[Hashable]) -> bool: members = sorted(pa_state, key=repr) @@ -346,7 +361,7 @@ def ambiguous(pa_state: frozenset[Hashable]) -> bool: for right in members[index + 1 :] ) - pa = power_automaton(graph) + pa = power_automaton(graph, deadline=deadline) if not ambiguous(pa.start): return 0 digraph = nx.DiGraph() diff --git a/tests/test_bidirectional_build.py b/tests/test_bidirectional_build.py index 92b1cdc..9d5d267 100644 --- a/tests/test_bidirectional_build.py +++ b/tests/test_bidirectional_build.py @@ -67,7 +67,7 @@ def test_ladder_budget_skips_caps_forecast_to_overrun(monkeypatch: pytest.Monkey clock = {"now": 0.0} attempted: list[int] = [] - def fake_preflight(forward, reverse_max_states): + def fake_preflight(forward, reverse_max_states, deadline=None): attempted.append(reverse_max_states) clock["now"] += 10.0 * (reverse_max_states / 10_000) ** 2 return bb.BidirPreflightResult("explosion", reverse_max_states=reverse_max_states), None @@ -94,7 +94,7 @@ def test_ladder_treats_an_oversized_reverse_machine_as_an_explosion(monkeypatch: huge = SimpleNamespace(reverse_machine=SimpleNamespace(states=lambda: range(5000))) - def fake_preflight(forward, reverse_max_states): + def fake_preflight(forward, reverse_max_states, deadline=None): return bb.BidirPreflightResult("truncated", reverse_max_states=reverse_max_states), huge monkeypatch.setattr(bb, "_preflight", fake_preflight) @@ -104,6 +104,81 @@ def fake_preflight(forward, reverse_max_states): assert "5000 states" in (built.preflight.error or "") +def test_the_ladder_does_not_repeat_an_exploded_cap(monkeypatch: pytest.MonkeyPatch) -> None: + """After the first build exploded at 10,000 states, the ladder used to build at 10,000 again.""" + import sofic.generators.bidirectional_build as bb + + attempted: list[int] = [] + + def fake_preflight(forward, reverse_max_states, deadline=None): + attempted.append(reverse_max_states) + return bb.BidirPreflightResult("explosion", reverse_max_states=reverse_max_states), None + + monkeypatch.setattr(bb, "_preflight", fake_preflight) + built = bb.try_build_bidirectional(None, use_ladder=True, caps=(10_000, 50_000)) + assert attempted == [10_000, 50_000] + assert built.preflight.reverse_max_states == 50_000 + + +def test_the_first_build_stops_at_half_the_budget_and_gets_no_ladder(monkeypatch: pytest.MonkeyPatch) -> None: + import sofic.generators.bidirectional_build as bb + + clock = {"now": 100.0} + calls: list[tuple[int, float | None]] = [] + + def fake_preflight(forward, reverse_max_states, deadline=None): + calls.append((reverse_max_states, deadline)) + clock["now"] = deadline + return bb.BidirPreflightResult("explosion", reverse_max_states=reverse_max_states, deadline_reached=True), None + + monkeypatch.setattr(bb, "_preflight", fake_preflight) + monkeypatch.setattr(bb.time, "monotonic", lambda: clock["now"]) + built = bb.try_build_bidirectional(None, use_ladder=True, time_budget=300.0) + assert calls == [(10_000, 250.0)] + assert built.bidir is None and built.budget_exhausted + assert built.preflight.deadline_reached + + +def test_the_ladder_forecasts_from_the_build_that_exploded(monkeypatch: pytest.MonkeyPatch) -> None: + """A first build that exploded in 40 s forecasts 1,000 s at 50,000 states, past the 60 s left.""" + import sofic.generators.bidirectional_build as bb + + clock = {"now": 0.0} + attempted: list[int] = [] + + def fake_preflight(forward, reverse_max_states, deadline=None): + attempted.append(reverse_max_states) + clock["now"] += 40.0 + return bb.BidirPreflightResult("explosion", reverse_max_states=reverse_max_states), None + + monkeypatch.setattr(bb, "_preflight", fake_preflight) + monkeypatch.setattr(bb.time, "monotonic", lambda: clock["now"]) + built = bb.try_build_bidirectional(None, use_ladder=True, caps=(10_000, 50_000), time_budget=100.0) + assert attempted == [10_000] + assert built.budget_exhausted + assert built.preflight.reverse_max_states == 10_000 + + +def test_a_build_stopped_at_its_deadline_is_an_explosion() -> None: + import time + + built = try_build_bidirectional(_exploding_forward(), time_budget=1e-9) + assert built.bidir is None and built.budget_exhausted + assert built.preflight.bidir_class == "explosion" and built.preflight.deadline_reached + start = time.monotonic() + assert try_build_bidirectional(_exploding_forward(), use_ladder=True, time_budget=1e-9).budget_exhausted + assert time.monotonic() - start < 5.0 + + +def _exploding_forward() -> EpsilonMachine: + """n3-t059-d3 of the binary 3-state dataset; its reverse mixed-state presentation passes 1,000 states.""" + mats = { + 0: np.array([[0.6326610218842386, 0.0, 0.0], [0.6594864914964855, 0.0, 0.0], [0.0, 0.04355642859348044, 0.0]]), + 1: np.array([[0.0, 0.3673389781157614, 0.0], [0.0, 0.0, 0.34051350850351453], [0.0, 0.0, 0.9564435714065196]]), + } + return from_symbol_matrices((0, 1, 2), (0, 1), mats) + + def test_truncated_reverse_machine_prunes_to_complete_rows() -> None: """Regression: dropping sub-tolerance joint states left (2, 'CE') with 86% of its outgoing mass.""" mats = {x: np.zeros((4, 4)) for x in (0, 1)} diff --git a/tests/test_coupled_generators.py b/tests/test_coupled_generators.py index 8ee9825..68589c2 100644 --- a/tests/test_coupled_generators.py +++ b/tests/test_coupled_generators.py @@ -394,16 +394,61 @@ def test_first_generating_separator_on_golden_mean() -> None: assert cg.generator_kernel(problem, hit[1])[0] <= 1e-9 -def test_separating_optima_and_bilevel_respect_an_expired_deadline() -> None: +def test_separating_optima_and_bilevel_respect_an_expired_deadline(monkeypatch: pytest.MonkeyPatch) -> None: + """Past the deadline only the first start runs, whether or not it finds an exact decomposition; the search + used to keep starting until one did, and ran 573 s of a 300 s budget on a truncated build.""" import time + deadlines: list[float | None] = [] + real = cg._decompose + + def recorded(*args, **kwargs): + deadlines.append(kwargs.get("deadline")) + return real(*args, **kwargs) + problem = cg._GeneratorProblem(_rll()) - best, optima = cg.separating_optima(problem, starts=500, deadline=time.monotonic(), rng=np.random.default_rng(0)) - assert optima and np.isfinite(best) - out = cg.bilevel_search(_rll(), optima, deadline=time.monotonic()) + monkeypatch.setattr(cg, "_decompose", recorded) + # strictly past: on Windows before Python 3.13 time.monotonic() ticks every 15.6 ms, so "now" may not have passed + expired = time.monotonic() - 1.0 + best, optima = cg.separating_optima(problem, starts=500, deadline=expired, rng=np.random.default_rng(0)) + assert deadlines == [None] + assert np.isfinite(best) == bool(optima) + monkeypatch.setattr(cg, "_decompose", real) + _, optima = cg.separating_optima(problem, starts=5, rng=np.random.default_rng(0)) + out = cg.bilevel_search(_rll(), optima, deadline=expired) assert len(out) == 1 +def test_separating_optima_stops_inside_a_start_at_the_deadline(monkeypatch: pytest.MonkeyPatch) -> None: + """SLSQP has no callback that can stop it, so the objective raises at the deadline, which ends the search.""" + clock = {"now": 0.0, "inside": False} + deadlines: list[float | None] = [] + stopped: list[int] = [] + real = cg._decompose + + def tick() -> float: + # time passes only inside the optimizer, so the deadline falls inside a start + clock["now"] += 1.0 if clock["inside"] else 0.0 + return clock["now"] + + def recorded(*args, **kwargs): + deadlines.append(kwargs.get("deadline")) + clock["inside"] = True + try: + return real(*args, **kwargs) + except cg._DeadlineReachedError: + stopped.append(len(deadlines)) + raise + finally: + clock["inside"] = False + + monkeypatch.setattr(cg.time, "monotonic", tick) + monkeypatch.setattr(cg, "_decompose", recorded) + cg.separating_optima(cg._GeneratorProblem(_rll()), starts=50, deadline=3.0, rng=np.random.default_rng(0)) + assert deadlines[0] is None and set(deadlines[1:]) == {3.0} + assert stopped == [len(deadlines)] + + def test_memory_lift_search_stops_inside_a_start_at_the_deadline(monkeypatch: pytest.MonkeyPatch) -> None: """The first start used to run all four penalty stages to the end whatever the deadline.""" clock = {"now": 0.0} @@ -485,7 +530,7 @@ def test_coupled_memory_and_targeted_searches_stop_at_an_expired_deadline() -> N bidir = _rll() problem = cg._GeneratorProblem(bidir) - # separating_optima takes no deadline; keep it out of the timed region (slow CI runners) + # separating_optima runs without a deadline here; keep it out of the timed region (slow CI runners) _best, optima = cg.separating_optima(problem, starts=10, rng=np.random.default_rng(0)) start = time.monotonic() # strictly in the past: before Python 3.13, time.monotonic() on Windows ticks every 15.6 ms diff --git a/tests/test_generative_model.py b/tests/test_generative_model.py index 5575853..41752ea 100644 --- a/tests/test_generative_model.py +++ b/tests/test_generative_model.py @@ -85,11 +85,15 @@ def _golden_mean_entropy() -> float: return float(-(1 / 3) * np.log2(1 / 3) - (2 / 3) * np.log2(2 / 3)) +def _fixed_window_bound(forward, **kwargs): + return 0.5, "a bound", [{"stage": "a bound"}], {"resume": "state"} + + def test_an_exploding_build_is_bracketed_from_the_forward_machine(monkeypatch) -> None: from sofic.generators.coupled_generators import CoupledGenerativeModel _fail_builds(monkeypatch) - monkeypatch.setattr(gs, "_future_window_bound", lambda forward, **kwargs: (0.5, "a bound", [{"stage": "a bound"}])) + monkeypatch.setattr(gs, "_future_window_bound", _fixed_window_bound) result = generative_model(golden_mean(0.5), hmm_search=False, rng=np.random.default_rng(0)) assert result.stages[0]["stage"] == "bidirectional build" assert result.stages[0]["bidir_class"] == "explosion" @@ -119,6 +123,115 @@ def test_the_forward_only_bracket_keeps_to_its_budget(monkeypatch) -> None: assert "belief-free HMM search" in {s["stage"] for s in result.stages} +def test_a_build_stopped_at_its_deadline_is_bracketed_from_the_forward_machine(monkeypatch) -> None: + from sofic.generators import bidirectional_build as bb + + seen = [] + + def stopped(forward, reverse_max_states, deadline=None): + seen.append(deadline) + error = "mixed-state presentation reached its deadline" + return bb.BidirPreflightResult( + "explosion", reverse_max_states=reverse_max_states, error=error, deadline_reached=True + ), None + + monkeypatch.setattr(bb, "_preflight", stopped) + start = time.monotonic() + result = generative_model(golden_mean(0.5), hmm_search=False, time_budget=4.0, rng=np.random.default_rng(0)) + assert time.monotonic() - start < 4.4 + assert len(seen) == 1 and seen[0] is not None + assert result.stages[0]["bidir_class"] == "explosion" and result.stages[0]["budget_exhausted"] + assert result.upper_source == "epsilon machine" + + +def _second_pass_recorder(monkeypatch, value: float) -> list[tuple[float, str, object]]: + """Replace the second window pass by one that returns ``value``; returns, per call, the time it was given and + the first pass's source and state it resumes.""" + given = [] + + def second(forward, *, explicit, k_max, deadline, source, resume): + given.append((deadline - time.monotonic(), source, resume)) + return {"stage": "second pass", "value": value, "caps": ()} + + monkeypatch.setattr(gs, "_second_window_pass", second) + return given + + +def test_the_forward_only_bracket_gives_the_time_left_to_a_second_window_pass(monkeypatch) -> None: + _fail_builds(monkeypatch) + monkeypatch.setattr(gs, "_future_window_bound", _fixed_window_bound) + given = _second_pass_recorder(monkeypatch, 0.6) + result = generative_model(golden_mean(0.5), hmm_search=False, time_budget=30.0, rng=np.random.default_rng(0)) + assert (result.lower, result.lower_source) == (0.6, "second pass") + assert [s["stage"] for s in result.stages[-2:]] == ["second pass", "reliability summary"] + assert len(given) == 1 and given[0][0] > 20.0 + assert given[0][1:] == ("a bound", {"resume": "state"}) + given.clear() + generative_model(golden_mean(0.5), hmm_search=False, rng=np.random.default_rng(0)) + assert not given + + +def test_a_truncation_gives_the_time_left_to_a_second_window_pass(monkeypatch) -> None: + given = _second_pass_recorder(monkeypatch, 0.6) + kwargs = { + "objective": "entropy", + "stages": ("machines",), + "window_lower": (0.5, "a bound"), + "window_resume": {"resume": "state"}, + } + result = gs._bracket_search(golden_mean_bidirectional(), time_budget=30.0, rng=np.random.default_rng(0), **kwargs) + assert (result.lower, result.lower_source) == (0.6, "second pass") + assert [s["stage"] for s in result.stages[-2:]] == ["second pass", "reliability summary"] + assert len(given) == 1 and given[0][0] > 20.0 + assert given[0][1:] == ("a bound", {"resume": "state"}) + given.clear() + gs._bracket_search(golden_mean_bidirectional(), rng=np.random.default_rng(0), **kwargs) + assert not given + + +def test_dit_fallbacks_stopped_at_their_deadline_are_logged(monkeypatch) -> None: + import sofic.generators.lifted_common_information as lci + + deadlines = [] + + def stopped(problem, joint, kind, *, deadline=None, **kwargs): + deadlines.append(deadline) + raise TimeoutError("dit optimization reached its deadline") + + monkeypatch.setattr(lci, "_unconstrained_channel", stopped) + kwargs = {"objective": "wyner", "stages": ("machines", "exact"), "exact_starts": 2} + result = gs._bracket_search(golden_mean_bidirectional(), time_budget=30.0, rng=np.random.default_rng(0), **kwargs) + errors = {s["stage"]: s["error"] for s in result.stages if "error" in s} + assert errors["dit exact common information"] == "dit optimization reached its deadline" + assert errors["dit Wyner common information"] == "dit optimization reached its deadline" + assert len(deadlines) == 2 and None not in deadlines + assert result.lower <= result.upper + + +def test_the_second_window_pass_resumes_the_stronger_length(monkeypatch) -> None: + import sofic.generators.generator_caps as caps + + calls = [] + + def coverage(problem, *, k_max, explicit, max_nodes, deadline, leaves=None): + calls.append((problem, max_nodes, leaves)) + return caps.CoverageLowerResult(0.7, (0.5,), True, 0.5, 1), {} + + monkeypatch.setattr(caps, "_resumable_coverage_bound", coverage) + state = {2: ("problem 2", "leaves 2"), 3: ("problem 3", "leaves 3")} + deadline = time.monotonic() + 10.0 + kwargs = {"explicit": 2, "k_max": 8, "deadline": deadline, "resume": state} + entry = gs._second_window_pass(golden_mean(0.5), source=gs._window_stage(2), **kwargs) + assert entry["stage"] == "future-window generator coverage bound (L=2, second pass)" and entry["value"] == 0.7 + assert calls == [("problem 2", (10_000, 20_000), "leaves 2")] + calls.clear() + gs._second_window_pass(golden_mean(0.5), source=gs._window_stage(3), **kwargs) + assert calls == [("problem 3", (3_000, 6_000), "leaves 3")] + calls.clear() + gs._second_window_pass(golden_mean(0.5), source="trivial lower bound", **{**kwargs, "resume": None}) + assert len(calls) == 1 and calls[0][1:] == ((3_000, 6_000), None) + + def test_other_failed_builds_and_entry_points_still_raise(monkeypatch) -> None: from sofic.exceptions import MixedStateExplosionError, StochasticValidationError from sofic.generators.functional_generators import minimal_functional_generator @@ -156,6 +269,17 @@ def test_an_exploding_build_reports_the_future_window_bound() -> None: assert result.lower < result.upper <= 1.0795992 + 1e-6 +@pytest.mark.slow +def test_the_default_build_of_an_exploding_process_keeps_to_its_budget() -> None: + """At sofic's default caps this process builds as a truncation; with 300 s it ran 814 s, 573 of them in the + exact common information multistart, which only checked its deadline once a start had succeeded.""" + start = time.monotonic() + result = generative_model(_exploding_forward(), time_budget=60.0, rng=np.random.default_rng(0)) + assert time.monotonic() - start < 66.0 + assert result.stages[0]["bidir_class"] in ("truncated", "explosion") + assert 0.0 < result.lower <= result.upper <= 1.0795992 + 1e-6 + + def test_generative_model_from_forward_epsilon_machine_certifies_golden_mean() -> None: forward = golden_mean(0.5) rng = np.random.default_rng(0) @@ -288,11 +412,30 @@ def test_zero_time_budget_returns_a_valid_bracket_from_the_machines() -> None: assert result.upper_source in machines assert result.lower <= result.upper + 1e-9 skipped = {s["stage"] for s in result.stages if s.get("skipped") == "time budget exhausted"} - assert {"generator coverage bound", "exact common information", "coupled search"} <= skipped + assert {"candidate machines", "generator coverage bound", "exact common information", "coupled search"} <= skipped assert all("elapsed" in s for s in result.stages[:-1]) assert result.stages[-1]["budget_exhausted"] is True +def test_the_persistent_criteria_get_a_tenth_of_the_time_left(monkeypatch) -> None: + given = [] + real = gs._cryptic_orders + + def recorded(bidir, deadline=None): + given.append(deadline - time.monotonic()) + return real(bidir, deadline=deadline) + + monkeypatch.setattr(gs, "_cryptic_orders", recorded) + gs._bracket_search( + golden_mean_bidirectional(), + objective="entropy", + stages=("machines",), + time_budget=10.0, + rng=np.random.default_rng(0), + ) + assert given and 0.0 < given[0] <= 1.0 + + def test_generator_heaviest_term_stage_runs_last_on_open_small_brackets() -> None: from tests.test_exact_ci_bounds import _dataset_case_t006 diff --git a/tests/test_generator_caps.py b/tests/test_generator_caps.py index 8c36808..2871244 100644 --- a/tests/test_generator_caps.py +++ b/tests/test_generator_caps.py @@ -123,6 +123,18 @@ def test_expired_deadline_still_gives_a_valid_cap() -> None: assert cov.value <= 1.5 + 1e-6 +def test_a_resumed_coverage_bound_branches_as_one_search() -> None: + from sofic.generators.generator_caps import _resumable_coverage_bound + + problem = cg._GeneratorProblem(_survey_machine()) + kwargs = {"k_max": 8, "explicit": 2, "deadline": None} + first, leaves = _resumable_coverage_bound(problem, max_nodes=(40, 80), **kwargs) + resumed, _ = _resumable_coverage_bound(problem, max_nodes=(80, 160), leaves=leaves, **kwargs) + whole = generator_coverage_bound(problem, explicit=2, max_nodes=(120, 240)) + assert first.value < resumed.value + assert resumed.caps == whole.caps and resumed.value == whole.value + + def test_child_lps_get_the_time_left_and_keep_the_parent_bound(monkeypatch: pytest.MonkeyPatch) -> None: """With a deadline, a child LP that HiGHS stops at its time limit keeps the parent's bound.""" import time diff --git a/tests/test_minimal_generative_model.py b/tests/test_minimal_generative_model.py index bbe5243..f49b547 100644 --- a/tests/test_minimal_generative_model.py +++ b/tests/test_minimal_generative_model.py @@ -4,6 +4,7 @@ import importlib import math +import time import warnings from itertools import product @@ -222,6 +223,28 @@ def optimizer(_dist, *, bound, niter, maxiter, polish, backend, rng): ) +@pytest.mark.parametrize( + "optimizer", [mgm_module._optimize_wyner_common_information, mgm_module._optimize_exact_common_information] +) +def test_a_dit_optimizer_stops_at_its_deadline(optimizer) -> None: + joint = {("A", "D"): 1 / 3, ("B", "C"): 1 / 3, ("B", "D"): 1 / 3} + kwargs = { + "optimizer": optimizer, + "optimizer_name": "test", + "bound": None, + "niter": 3, + "maxiter": 1000, + "polish": 1e-8, + "backend": "numpy", + "cutoff": 1e-10, + "rng": np.random.default_rng(0), + } + with pytest.raises(TimeoutError, match="deadline"): + _auxiliary_state_channel(joint, deadline=time.monotonic() - 1.0, **kwargs) + channel, _ = _auxiliary_state_channel(joint, deadline=time.monotonic() + 600.0, **kwargs) + assert set(channel) == set(joint) + + def test_model_from_channel_keeps_outgoing_probabilities_for_rare_active_states(): bidir = golden_mean_bidirectional(0.5) joint = dict.fromkeys((("A", "C"), ("A", "D"), ("B", "C")), 1 / 3) diff --git a/tests/test_mixed_state_construction.py b/tests/test_mixed_state_construction.py index 46f58b8..b034801 100644 --- a/tests/test_mixed_state_construction.py +++ b/tests/test_mixed_state_construction.py @@ -30,6 +30,17 @@ def test_max_states_counts_distinct_beliefs(): assert len(list(build_mixed_state_presentation(golden_mean(), max_states=3).states())) == 3 +def test_a_deadline_stops_the_enumeration_as_an_explosion(): + from sofic.exceptions import MixedStateDeadlineError + + past = time.monotonic() - 1.0 + with pytest.raises(MixedStateDeadlineError, match="deadline"): + build_mixed_state_presentation(sns(), deadline=past) + with pytest.raises(MixedStateExplosionError): + EpsilonMachine.from_hmm(sns(), deadline=past) + assert len(list(build_mixed_state_presentation(golden_mean(), deadline=time.monotonic() + 60.0).states())) == 3 + + def test_infinite_reverse_presentation_reaches_its_cap_quickly() -> None: """Regression: indexing beliefs by their first coordinate made every lookup scan all states when many beliefs share it, so this 4-state reverse inference ran for many minutes before its cap.""" diff --git a/tests/test_separating_generators.py b/tests/test_separating_generators.py index cedcdcb..3aa2da4 100644 --- a/tests/test_separating_generators.py +++ b/tests/test_separating_generators.py @@ -124,6 +124,22 @@ def test_theorem_class_identity_and_equal_cryptic_orders(name, seed) -> None: assert all((max(plus, minus) < 1e-10) == (length >= kappa_plus) for length, plus, minus in ladder) +def test_the_persistent_criteria_stop_at_an_expired_deadline() -> None: + import time + + from sofic.examples.epsilon_machines import restricted_golden_mean + from sofic.generators.generative_search import _cryptic_orders, resolve_bidirectional + + machine = restricted_golden_mean(2) + bidir = resolve_bidirectional(machine)[0] + past = time.monotonic() - 1.0 + assert _cryptic_orders(bidir, deadline=past) is None + assert _cryptic_orders(bidir, deadline=time.monotonic() + 60.0) == _cryptic_orders(bidir) == (2, 2) + problem = _problem(machine) + assert [row[0] for row in sg._block_persistent_crypticities(problem, deadline=past)] == [1] + assert [row[0] for row in sg._block_persistent_crypticities(problem)] == [1, 2] + + @settings(max_examples=12, deadline=None, suppress_health_check=[HealthCheck.too_slow]) @given(st.sampled_from(_KAPPA_LE_1), st.integers(0, 2**32 - 1)) def test_theorem_generator_generates(name, seed) -> None: diff --git a/tests/test_synchronization.py b/tests/test_synchronization.py index 6a81477..99f7f30 100644 --- a/tests/test_synchronization.py +++ b/tests/test_synchronization.py @@ -144,6 +144,15 @@ def test_restricted_golden_mean_cryptic_order(k: int): assert eps.markov_order() == k +def test_cryptic_order_stops_at_its_deadline(): + import time + + eps = restricted_golden_mean(3) + with pytest.raises(TimeoutError, match="deadline"): + eps.cryptic_order(deadline=time.monotonic() - 1.0) + assert eps.cryptic_order(deadline=time.monotonic() + 60.0) == 3 + + def test_phase_slip_backtrack_markov_order(): eps = phase_slip_backtrack() assert eps.markov_order() == math.inf