From 1dfa81c2d2649072a14891068d76014f9d733b81 Mon Sep 17 00:00:00 2001 From: Ryan James Date: Sun, 15 Nov 2026 22:09:34 -0700 Subject: [PATCH 1/7] =?UTF-8?q?Fix=20R=C3=A9nyi=20rate=20cancellation=20ne?= =?UTF-8?q?ar=20alpha=20=3D=201;=20require=20dit=202.4;=20add=20coverage?= =?UTF-8?q?=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- pyproject.toml | 4 +- sofic/generators/renyi.py | 5 +- tests/test_bayesian_inference.py | 137 +++++++++++++++++++++++ tests/test_bidirectional_construction.py | 128 +++++++++++++++++++++ tests/test_channel_coding.py | 27 +++++ tests/test_channel_feedback.py | 26 +++++ tests/test_cssr_trials.py | 62 ++++++++++ tests/test_dfasat.py | 6 + tests/test_generative_search_helpers.py | 46 ++++++++ tests/test_idfa.py | 65 +++++++++++ tests/test_languages.py | 100 +++++++++++++++++ tests/test_pfa.py | 54 +++++++++ tests/test_processes_constructors.py | 121 ++++++++++++++++++++ tests/test_renyi.py | 6 + tests/test_stack_inference.py | 62 ++++++++++ tests/test_stationary.py | 50 +++++++++ tests/test_structural_predicates.py | 135 ++++++++++++++++++++++ tests/test_transducers.py | 128 ++++++++++++++++++++- tests/test_viz.py | 71 ++++++++++++ tests/test_vpa.py | 65 +++++++++++ uv.lock | 34 +++--- 21 files changed, 1314 insertions(+), 18 deletions(-) create mode 100644 tests/test_bidirectional_construction.py create mode 100644 tests/test_generative_search_helpers.py create mode 100644 tests/test_idfa.py create mode 100644 tests/test_processes_constructors.py create mode 100644 tests/test_structural_predicates.py diff --git a/pyproject.toml b/pyproject.toml index e2ffa1f..e14ea09 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -27,7 +27,7 @@ classifiers = [ "Topic :: Scientific/Engineering :: Physics", ] dependencies = [ - "dit>=2.3", + "dit>=2.4", "networkx>=2.6", "numpy>=1.22", "pyyaml>=6.0", @@ -80,7 +80,7 @@ capacity = [ ] symbolic = [ "sympy>=1.12", - "dit[symbolic]>=2.3", + "dit[symbolic]>=2.4", ] # ── uv ────────────────────────────────────────────────────────────────── diff --git a/sofic/generators/renyi.py b/sofic/generators/renyi.py index 9f084e4..232fdbe 100644 --- a/sofic/generators/renyi.py +++ b/sofic/generators/renyi.py @@ -47,6 +47,9 @@ _TOL = 1e-12 _BETA_MAX = 64.0 +# Within this distance of alpha = 1, pressure(alpha) / (1 - alpha) loses more to rounding than h_mu +# loses to the O(|1 - alpha|) truncation, so the Shannon rate is returned instead. +_SHANNON_WINDOW = 1e-7 def _unifilar_mealy(model: HiddenMarkovModel, max_states: int) -> MealyHMM: @@ -161,7 +164,7 @@ def renyi_entropy_rate(model: HiddenMarkovModel, alpha: float, *, max_states: in spectrum = _Spectrum(model, max_states=max_states) if np.isinf(alpha): return -spectrum.mu - if alpha == 1.0: + if abs(alpha - 1.0) < _SHANNON_WINDOW: return float(spectrum.mealy.entropy_rate()) return spectrum.pressure(alpha) / (1.0 - alpha) diff --git a/tests/test_bayesian_inference.py b/tests/test_bayesian_inference.py index 9fa22e5..74243b1 100644 --- a/tests/test_bayesian_inference.py +++ b/tests/test_bayesian_inference.py @@ -7,8 +7,10 @@ from sofic.examples import even_process from sofic.examples.processes import sns +from sofic.graph import ATTR_PROB from sofic.inference.bayesian import ( BayesianInferenceError, + DirichletPriorMC, InferEM, InferMC, ModelComparisonMC, @@ -87,3 +89,138 @@ def test_markov_pymc_model_smoke(): posterior = InferMC(["0", "1"], list("01010"), order=1) model = posterior.as_pymc_model() assert isinstance(model, pm.Model) + + +def test_markov_pymc_model_likelihoods(): + pytest.importorskip("pymc") + posterior = InferMC(["0", "1"], list("01010"), order=1) + assert "sequence_loglik" in posterior.as_pymc_model().named_vars + counts = posterior.as_pymc_model(observed_as_counts=True) + assert "counts" in counts.named_vars + assert "sequence_loglik" not in counts.named_vars + + +def test_epsilon_machine_pymc_model(): + pytest.importorskip("pymc") + from sofic.inference.bayesian.pymc_backend import _safe_name + + posterior = InferEM(even_process(), list("1111101100")) + default = posterior.as_pymc_model() + explicit = posterior.as_pymc_model(start_node="B") + assert set(default.named_vars) == set(explicit.named_vars) + # Only A has a choice of edges in the even process. + assert _safe_name("theta", "A") == "theta_A" + assert {"theta_A", "sequence_loglik_A"} <= set(default.named_vars) + with pytest.raises(ValueError, match="not viable"): + posterior.as_pymc_model(start_node="A") + + +def test_dirichlet_prior_uniform_and_explicit_alphas(): + prior = DirichletPriorMC(["0", "1"], order=1) + assert prior.get_alpha(("0", "1")) == 1.0 + assert prior.get_alpha(("0", "*")) == 2.0 + assert prior.get_alpha(("0",)) is None + assert "alpha(0 -> *) = 2.0" in str(prior) + prior.set_alpha(("0", "1"), 3) + prior.set_alpha(("0", "0"), 2) + prior.set_alpha(("0", "1"), 5) + assert not prior.uniform + assert prior.get_alpha(("0", "1")) == 5.0 + assert prior.get_alpha(("0", "*")) == 7.0 + assert prior.get_alpha(("1", "0")) is None + + +def test_dirichlet_prior_random_rows_sum_to_root(): + prior = DirichletPriorMC(["0", "1", "2"], order=1) + prior.create_random_prior(1, 6, rng=np.random.default_rng(0)) + for context in "012": + cells = [prior.get_alpha((context, symbol)) for symbol in "012"] + assert all(1 <= alpha < 6 for alpha in cells) + assert prior.get_alpha((context, "*")) == sum(cells) + + +def test_markov_posterior_prior_types(): + assert not InferMC(["0", "1"], list("0101"), order=1, prior_type="random").prior.uniform + with pytest.raises(BayesianInferenceError, match="prior type"): + InferMC(["0", "1"], list("0101"), order=1, prior_type="jeffreys") + + +def test_markov_posterior_unseen_context_and_added_counts(): + posterior = InferMC(["0", "1"], list("0000"), order=1) + assert posterior.transition_probability_mle(("1",), "0") == (0.0, 0.0) + posterior.add_counts_from(list("0101")) + assert posterior.transition_probability_mle(("1",), "0")[0] == pytest.approx(1.0) + + +def test_markov_posterior_missing_alphas_raise(): + posterior = InferMC(["0", "1"], list("0101"), order=1) + posterior.prior = DirichletPriorMC(["0", "1"], order=1, uniform=False) + with pytest.raises(BayesianInferenceError): + posterior.transition_probability_pme(("0",), "1") + with pytest.raises(BayesianInferenceError): + posterior.posterior_alpha_matrix() + with pytest.raises(BayesianInferenceError): + posterior.log_evidence() + posterior.prior.set_alpha(("0", "0"), 1.0) + with pytest.raises(BayesianInferenceError): + posterior.log_evidence() + + +def test_markov_posterior_mean_matrix_matches_pme(): + posterior = InferMC(["0", "1"], list("0110100110010110"), order=2) + mean = posterior.posterior_mean_matrix() + np.testing.assert_allclose(mean.sum(axis=1), 1.0) + for i, context in enumerate(posterior.contexts): + for j, symbol in enumerate(posterior.alphabet): + assert mean[i, j] == pytest.approx(posterior.transition_probability_pme(context, symbol)[0]) + + +def test_markov_posterior_entropy_rate_concentrates_on_fair_coin(): + rng = np.random.default_rng(0) + small = InferMC(["0", "1"], list(rng.choice(["0", "1"], size=100)), order=0) + large = InferMC(["0", "1"], list(rng.choice(["0", "1"], size=10_000)), order=0) + assert large.average_relative_entropy_plus_entropy_rate() == pytest.approx(1.0, abs=1e-3) + assert ( + 0.0 < large.variance_relative_entropy_plus_entropy_rate() < small.variance_relative_entropy_plus_entropy_rate() + ) + + +def test_markov_posterior_reports(): + posterior = InferMC(["0", "1"], list("01010"), order=1) + mle = list(posterior.transition_probability_mle_iter()) + pme = list(posterior.transition_probability_pme_iter()) + assert len(mle) == len(pme) == 4 + assert ("0", "1", 1.0, 0.0) in mle + assert posterior.transition_probability_mle_string().count("Pr(") == 4 + assert posterior.transition_probability_pme_string().count("StdDev") == 4 + assert posterior.counts_string() + assert posterior.prior_string() == str(posterior.prior) + + +def test_markov_posterior_mle_machine_and_validation(): + posterior = InferMC(["0", "1"], list("0110100110010110"), order=1) + machine = posterior.generate_mealy_hmm("MLE") + machine.validate() + assert set(machine.states()) == {("0",), ("1",)} + with pytest.raises(BayesianInferenceError, match="threshold"): + posterior.generate_mealy_hmm(threshold=1.5) + with pytest.raises(BayesianInferenceError, match="method"): + posterior.generate_mealy_hmm("MAP") + + +def test_order_zero_markov_machine_has_one_state(): + machine = InferMC(["0", "1"], list("0001"), order=0).generate_mealy_hmm() + assert list(machine.states()) == ["A"] + assert {t.target for t in machine.transitions()} == {"A"} + + +def test_markov_posterior_samples_are_valid_machines(): + posterior = InferMC(["0", "1"], list("0110100110010110"), order=1) + machines = list(posterior.sample_mealy_hmms(3, rng=np.random.default_rng(1))) + assert len(machines) == 3 + for machine in machines: + machine.validate() + for state in machine.states(): + assert sum(t.data[ATTR_PROB] for t in machine.graph.out_transitions(state)) == pytest.approx(1.0) + with pytest.raises(BayesianInferenceError, match="threshold"): + next(iter(posterior.sample_mealy_hmms(threshold=-0.1))) diff --git a/tests/test_bidirectional_construction.py b/tests/test_bidirectional_construction.py new file mode 100644 index 0000000..79a80c5 --- /dev/null +++ b/tests/test_bidirectional_construction.py @@ -0,0 +1,128 @@ +"""Edge cases of the Eq. (15) helpers in :mod:`sofic.generators.bidirectional_construction`.""" + +from __future__ import annotations + +import math + +import pytest + +from sofic.examples import even_process, golden_mean +from sofic.exceptions import StochasticValidationError +from sofic.generators import bidirectional_construction as bc +from sofic.generators.bidirectional_construction import infer_reverse_epsilon_machine +from sofic.generators.epsilon_machine import EpsilonMachine +from sofic.graph import ATTR_EMISSION, ATTR_FUTURE_SYMBOL, ATTR_PROB, TransitionGraph + + +def _graph(edges) -> TransitionGraph: + graph = TransitionGraph() + for source, target, symbol, prob in edges: + graph.add_state(source) + graph.add_state(target) + graph.add_transition(source, target, **{ATTR_EMISSION: symbol, ATTR_PROB: prob}) + return graph + + +def test_mismatched_alphabets_are_rejected(): + forward = golden_mean() + other = EpsilonMachine.from_hmm(even_process()) + other.observation_alphabet = frozenset({"0", "1", "2"}) + with pytest.raises(StochasticValidationError, match="alphabets must match"): + bc.build_bidirectional_epsilon_machine(forward, other) + + +def test_graph_from_raw_aggregates_and_skips_massless_rows(): + a, b, c = ("a", "x"), ("b", "x"), ("c", "x") + raw = {a: [(b, "0", 0.25), (b, "0", 0.25), (a, "1", 0.5)], b: [], c: [(a, "0", 0.0)]} + graph = bc._graph_from_raw(raw) + assert not list(graph.out_transitions(b)) + assert not list(graph.out_transitions(c)) + probs = {(t.target, t.data[ATTR_EMISSION]): t.data[ATTR_PROB] for t in graph.out_transitions(a)} + assert probs == {(b, "0"): 0.5, (a, "1"): 0.5} + + +def test_graph_from_raw_keeps_symbolic_weights_exact(): + sp = pytest.importorskip("sympy") + p = sp.Symbol("p", positive=True) + a, b = ("a", "x"), ("b", "x") + graph = bc._graph_from_raw({a: [(a, "0", p), (b, "1", 1 - p)]}) + probs = {t.target: t.data[ATTR_PROB] for t in graph.out_transitions(a)} + assert sp.simplify(probs[a] - p) == 0 + assert sp.simplify(probs[b] - (1 - p)) == 0 + + +def test_clean_probability_rounds_only_float_noise(): + sp = pytest.importorskip("sympy") + assert bc._clean_probability(0.1 + 0.2) == 0.3 + x = sp.Symbol("x") + assert bc._clean_probability(x * 2 / 2) == x + + +def test_prune_of_an_empty_graph_is_empty(): + graph, initial = bc._prune_to_stationary_support(TransitionGraph(), golden_mean(), golden_mean()) + assert initial == {} + assert not list(graph.states()) + + +def test_future_symbol_annotations_filter_compatible_pairs(): + forward = golden_mean() + reverse = infer_reverse_epsilon_machine(forward) + states = sorted(reverse.states(), key=repr) + reverse.graph.nx.nodes[states[0]][ATTR_FUTURE_SYMBOL] = "1" + reverse.graph.nx.nodes[states[1]][ATTR_FUTURE_SYMBOL] = "9" + mapping = bc._infer_future_symbols(reverse) + assert mapping[states[0]] == "1" + pairs = bc._compatible_pairs(forward, reverse) + assert all(gamma != states[1] for _alpha, gamma in pairs) + assert all(bc._forward_emits(forward, alpha, "1") for alpha, gamma in pairs if gamma == states[0]) + + +def test_states_named_by_symbols_carry_their_future_symbol(): + machine = EpsilonMachine(observation_alphabet=frozenset({"0", "1"})) + for state in ("0", "1", "z"): + machine.graph.add_state(state) + assert bc._infer_future_symbols(machine) == {"0": "0", "1": "1"} + + +def test_joint_pi_on_pair_subset_rejects_leaky_or_empty_components(): + a, b = ("a", "x"), ("b", "x") + graph = _graph([(a, a, "0", 0.5), (a, b, "1", 0.5), (b, a, "0", 1.0)]) + assert bc._joint_pi_on_pair_subset(graph, []) is None + assert bc._joint_pi_on_pair_subset(graph, [a]) is None + joint = bc._joint_pi_on_pair_subset(graph, [a, b]) + assert joint == {a: pytest.approx(2 / 3), b: pytest.approx(1 / 3)} + + +def test_joint_pi_on_pair_subset_with_symbolic_rows(): + sp = pytest.importorskip("sympy") + p = sp.Symbol("p", positive=True) + a, b = ("a", "x"), ("b", "x") + graph = _graph([(a, a, "0", p), (a, b, "1", 1 - p), (b, a, "0", sp.Integer(1))]) + joint = bc._joint_pi_on_pair_subset(graph, [a, b]) + assert sp.simplify(joint[a] - 1 / (2 - p)) == 0 + leaky = _graph([(a, a, "0", p), (b, a, "0", sp.Integer(1))]) + assert bc._joint_pi_on_pair_subset(leaky, [a, b]) is None + + +def test_symbolic_marginal_errors(): + sp = pytest.importorskip("sympy") + p = sp.Symbol("p", positive=True) + assert bc._abs_marginal_error(0.25, 0.25) == 0.0 + assert bc._abs_marginal_error(0.25, 0.5) == 0.25 + assert bc._abs_marginal_error(sp.Rational(1, 2), sp.Rational(1, 4)) == 0.25 + assert bc._abs_marginal_error(p, sp.Rational(1, 4)) == math.inf + + +def test_symbolic_stationary_state_probabilities(): + sp = pytest.importorskip("sympy") + from sofic.examples.epsilon_machines import from_symbol_matrices + + p = sp.Symbol("p", positive=True) + one, zero = sp.Integer(1), sp.Integer(0) + machine = from_symbol_matrices( + ["A", "B"], + ("0", "1"), + {"0": [[1 - p, zero], [one, zero]], "1": [[zero, p], [zero, zero]]}, + ) + probs = bc._stationary_state_probabilities(machine) + assert sp.simplify(probs["A"] - 1 / (1 + p)) == 0 diff --git a/tests/test_channel_coding.py b/tests/test_channel_coding.py index 2319a52..369ce07 100644 --- a/tests/test_channel_coding.py +++ b/tests/test_channel_coding.py @@ -146,6 +146,33 @@ def test_capacity_gap_is_a_bracket(): assert bsc_gap <= upper + 1e-6 +def _partial_channel(): + """Input ``b`` is not admissible in state ``t``; outputs mix a string and an integer.""" + from sofic.automata.transducers import MealyMachine + + machine = MealyMachine(input_alphabet=frozenset({"a", "b"}), output_alphabet=frozenset({"x", 1})) + machine.add_transition("s", "s", "a", "x", prob=1.0) + machine.add_transition("s", "t", "b", 1, prob=1.0) + machine.add_transition("t", "s", "a", "x", prob=1.0) + machine.initial_states = frozenset({"s"}) + return FiniteStateChannel(machine) + + +def test_default_maps_keep_non_digit_and_unorderable_symbols(): + channel = _partial_channel() + assert channel.inputs == ("a", "b") + assert set(channel.outputs) == {"x", 1} + assert channel.log_likelihood(("b", "a"), (1, "x")) == pytest.approx(0.0) + assert channel.log_likelihood(("b", "b"), (1, 1)) == -np.inf + + +def test_sample_rejects_inadmissible_inputs(): + channel = _partial_channel() + assert channel.sample(("a", "b", "a"), np.random.default_rng(0)) == ("x", 1, "x") + with pytest.raises(ValueError, match="not admissible"): + channel.sample(("b", "b"), np.random.default_rng(0)) + + def test_symbol_maps(): channel = FiniteStateChannel(trapdoor(), input_map={"0": "a", "1": "b"}) assert channel.inputs == ("a", "b") diff --git a/tests/test_channel_feedback.py b/tests/test_channel_feedback.py index fcc7ee0..8993489 100644 --- a/tests/test_channel_feedback.py +++ b/tests/test_channel_feedback.py @@ -108,6 +108,32 @@ def test_trapdoor_code_is_zero_error(k): assert uses == pytest.approx(code.length + 3.5, abs=1e-6) +def test_rll_encode_rejects_out_of_range_indices(): + with pytest.raises(ValueError, match="index"): + rll_encode(3, 2) + with pytest.raises(ValueError, match="index"): + rll_encode(-1, 2) + + +def test_trapdoor_code_rejects_non_binary_channels(): + from types import SimpleNamespace + + from dit.exceptions import ditException + + code = trapdoor_code(2) + assert repr(code) == "TrapdoorCode(k=2, N=4)" + with pytest.raises(ditException, match="inputs and outputs"): + code.start(SimpleNamespace(inputs=(0, 1, 2), outputs=(0, 1))) + + +def test_trapdoor_decode_of_unused_word_and_short_state_is_all_zeros(): + code = trapdoor_code(2) + # After one flushing use, outputs 0101 decode to actions 1010, i.e. RLL word 101 of index 4 >= 2**2. + assert code.decode((1, 0, 1, 0, 1)) == (0, 0) + assert code.decode(()) == (0, 0) + assert code.decode((1, 0)) == (0, 0) + + def test_trapdoor_code_approaches_the_feedback_capacity(): code = trapdoor_code(32) pe, uses = code.performance( diff --git a/tests/test_cssr_trials.py b/tests/test_cssr_trials.py index fa69757..62737ba 100644 --- a/tests/test_cssr_trials.py +++ b/tests/test_cssr_trials.py @@ -82,3 +82,65 @@ def test_transcssr_on_trials_matches_the_unsplit_sample(): whole = learn_epsilon_transducer_cssr(xs, ys, max_history=1) split = learn_epsilon_transducer_cssr(_split(xs, 3), _split(ys, 3), max_history=1) assert len(list(split.states())) == len(list(whole.states())) == 1 + + +def test_suffix_counts_reject_empty_or_foreign_data(): + from sofic.inference.cssr.counts import SuffixCounts + + with pytest.raises(ValueError, match="non-empty"): + SuffixCounts.from_sequence([]) + with pytest.raises(ValueError, match="non-empty"): + SuffixCounts.from_sequences([(), ()]) + with pytest.raises(ValueError, match="not in alphabet"): + SuffixCounts.from_sequence("012", alphabet="01") + + +def test_suffix_count_morphs(): + from sofic.inference.cssr.counts import SuffixCounts + + counts = SuffixCounts.from_sequence("0010", alphabet="01", max_length=1) + assert counts.morph(("0",)) == {"0": 0.5, "1": 0.5} + assert counts.morph(("1",)) == {"0": 1.0, "1": 0.0} + assert counts.morph(("1",), smoothing=1.0) == {"0": pytest.approx(2 / 3), "1": pytest.approx(1 / 3)} + assert counts.morph(("1", "1")) == {"0": 0.5, "1": 0.5} + assert counts.state_morph({("0",), ("1",)}) == {"0": pytest.approx(2 / 3), "1": pytest.approx(1 / 3)} + assert counts.state_morph({("1", "1")}) == counts.morph(()) + # Pooled over every counted history: 0010 at L = 0, then 010 at L = 1. + assert counts.marginal_morph() == {"0": pytest.approx(5 / 7), "1": pytest.approx(2 / 7)} + assert SuffixCounts(alphabet=("a", "b")).marginal_morph() == {"a": 0.5, "b": 0.5} + + +def test_restricted_counts_keep_only_the_given_histories(): + from sofic.inference.cssr.counts import SuffixCounts + + counts = SuffixCounts.from_sequence("0010", alphabet="01", max_length=1) + proxy = counts.restricted_to({("0",)}) + assert set(proxy.history_counts) == {("0",)} + assert proxy.morph(("0",)) == counts.morph(("0",)) + assert proxy.morph(()) == {"0": 0.5, "1": 0.5} + + +def test_joint_suffix_counts(): + from sofic.inference.cssr.counts import JointSuffixCounts, Trials + + with pytest.raises(ValueError, match="non-empty"): + JointSuffixCounts.from_sequences([], [], max_length=1) + with pytest.raises(ValueError, match="both be Trials"): + JointSuffixCounts.from_sequences(Trials(["ab"]), "xy", max_length=1) + with pytest.raises(ValueError, match="equal length"): + JointSuffixCounts.from_sequences("ab", "x", max_length=1) + counts = JointSuffixCounts.from_sequences("abab", "xyxx", max_length=1) + assert counts.output_counts({(), (("z", "z"),)}, "b") == {"y": 1, "x": 1} + assert counts.state_morph({()}, "a") == {"x": 1.0, "y": 0.0} + assert counts.state_morph({(("z", "z"),)}, "a") == {} + + +def test_stack_suffix_counts_reject_empty_or_foreign_data(): + from sofic.automata.learning.papni import DyckAlphabet + from sofic.inference.cssr.counts import StackSuffixCounts + + alphabet = DyckAlphabet(frozenset("("), frozenset(")"), frozenset("x")) + with pytest.raises(ValueError, match="non-empty"): + StackSuffixCounts.from_sequence((), alphabet=alphabet) + with pytest.raises(ValueError, match="not in Dyck alphabet"): + StackSuffixCounts.from_sequence(("(", "y"), alphabet=alphabet) diff --git a/tests/test_dfasat.py b/tests/test_dfasat.py index 8caa61f..22c9915 100644 --- a/tests/test_dfasat.py +++ b/tests/test_dfasat.py @@ -75,6 +75,12 @@ def test_sat_upper_bound_too_small_raises(): learn_dfa_sat(positive, negative, upper_bound=1) +def test_sat_upper_bound_below_lower_bound_is_raised_to_it(): + positive, negative = _labeled(_even_a) + dfa = learn_dfa_sat(positive, negative, lower_bound=2, upper_bound=1) + assert len(list(dfa.states())) == 2 + + def test_sat_requires_samples(): with pytest.raises(ValueError): learn_dfa_sat([], []) diff --git a/tests/test_generative_search_helpers.py b/tests/test_generative_search_helpers.py new file mode 100644 index 0000000..e4d0435 --- /dev/null +++ b/tests/test_generative_search_helpers.py @@ -0,0 +1,46 @@ +"""Fast checks of the helpers around :func:`sofic.generators.generative_search.generative_model`.""" + +from __future__ import annotations + +import math + +import numpy as np +import pytest + +from sofic.examples import even_process, golden_mean +from sofic.examples.epsilon_machines import golden_mean_bidirectional +from sofic.generators import generative_search as gs +from sofic.generators.bidirectional_epsilon_machine import BidirectionalEpsilonMachine +from sofic.generators.coupled_generators import _GeneratorProblem + +DSBS = {("0", "0"): 0.4, ("0", "1"): 0.1, ("1", "0"): 0.1, ("1", "1"): 0.4} + + +def test_resolve_bidirectional_accepts_or_builds(): + given = golden_mean_bidirectional() + bidir, meta = gs.resolve_bidirectional(given) + assert bidir is given + assert meta == {"bidir_class": "finite", "source": "bidirectional input"} + built, meta = gs.resolve_bidirectional(even_process(), use_ladder=False) + assert isinstance(built, BidirectionalEpsilonMachine) + assert meta["bidir_class"] == "finite" + assert meta["reverse_recurrence_finite"] + assert "build_error" not in meta + + +def test_persistent_crypticity_theorem_applies_to_the_golden_mean(): + bidir, _meta = gs.resolve_bidirectional(golden_mean()) + assert gs._theorem_applies(_GeneratorProblem(bidir)) + + +def test_coverage_lower_bound_modes(): + rng = np.random.default_rng(0) + heuristic, meta, certified = gs._coverage_lower_bound(DSBS, rng, mu_starts=3, certified=False) + assert not certified and not meta["certified"] + assert {"mu_1", "mu_2"} <= set(meta) + skipped, meta, certified = gs._coverage_lower_bound(DSBS, rng, mu_starts=3, certified=False, certified_only=True) + assert skipped == -math.inf and meta["skipped"] and not certified + exact, meta, certified = gs._coverage_lower_bound(DSBS, rng, mu_starts=3, certified=True, certified_only=True) + assert certified and meta["certified"] + assert meta["mu_1"] == pytest.approx(0.625, abs=1e-6) + assert exact == pytest.approx(heuristic, abs=1e-4) diff --git a/tests/test_idfa.py b/tests/test_idfa.py new file mode 100644 index 0000000..5412ef3 --- /dev/null +++ b/tests/test_idfa.py @@ -0,0 +1,65 @@ +"""Incomplete accessible DFA strings (:mod:`sofic.automata.enumeration.idfa`).""" + +from __future__ import annotations + +import pytest + +from sofic.automata.enumeration import idfa +from sofic.automata.enumeration.idfa import MISSING_TRANSITION as MISSING +from sofic.automata.enumeration.idfa import IDFAEnumerationError + + +@pytest.mark.parametrize(("n", "k"), [(1, 2), (2, 2), (3, 2), (2, 3)]) +def test_enumeration_is_counted_ranked_and_bounded(n, k): + strings = list(idfa.iter_idfa_strings(k, n)) + assert len(strings) == len(set(strings)) == idfa.count_accessible_idfa(k, n) + assert strings[0] == idfa.first_idfa_string(n=n, k=k) + assert strings[-1] == idfa.last_idfa_string(n=n, k=k) + for rank in (0, len(strings) // 2, len(strings) - 1): + assert idfa.unrank_idfa_string(rank, n=n, k=k) == strings[rank] + assert idfa.rank_idfa_string(strings[rank], n=n, k=k) == rank + + +def test_unrank_rejects_out_of_range_ranks(): + with pytest.raises(IDFAEnumerationError, match="nonnegative"): + idfa.unrank_idfa_string(-1, n=2, k=2) + with pytest.raises(IDFAEnumerationError, match="out of range"): + idfa.unrank_idfa_string(4, n=1, k=2) + with pytest.raises(IDFAEnumerationError, match="out of range"): + idfa.unrank_idfa_string(idfa.count_accessible_idfa(2, 2), n=2, k=2) + + +def test_validation_rules(): + with pytest.raises(IDFAEnumerationError, match="expected length"): + idfa.validate_idfa_string((0,), n=2, k=2) + with pytest.raises(IDFAEnumerationError, match="not in"): + idfa.validate_idfa_string((1, 5, MISSING, MISSING), n=2, k=2) + with pytest.raises(IDFAEnumerationError, match="appears before"): + idfa.validate_idfa_string((2, 1, MISSING, MISSING, MISSING, MISSING), n=3, k=2) + with pytest.raises(IDFAEnumerationError, match="does not appear"): + idfa.validate_idfa_string((0, 0, 1, MISSING), n=2, k=2) + + +def test_advancing_past_the_upper_bound_is_an_error(): + assert idfa._advance_idfa_value(MISSING, -1) == (MISSING, True) + assert idfa._advance_idfa_value(MISSING, 1) == (0, False) + assert idfa._advance_idfa_value(1, 1) == (MISSING, True) + with pytest.raises(IDFAEnumerationError, match="invalid transition value"): + idfa._advance_idfa_value(3, 1) + + +def test_decoding_to_a_topological_graph(): + transitions = (1, MISSING, 0, 1) + graph = idfa.idfa_string_to_topological_graph(transitions, n=2, k=2, alphabet=("a", "b")) + assert graph.transitions == {(0, "a"): 1, (1, "a"): 0, (1, "b"): 1} + assert idfa.idfa_string_to_topological_graph(transitions, n=2, k=2).alphabet == frozenset({0, 1}) + with pytest.raises(IDFAEnumerationError, match="alphabet length"): + idfa.idfa_string_to_topological_graph(transitions, n=2, k=2, alphabet=("a",)) + + +def test_rerooting(): + rerooted = idfa.reroot_idfa_string((1, MISSING, 0, 1), new_root=1, n=2, k=2) + assert rerooted is not None + idfa.validate_idfa_string(rerooted, n=2, k=2) + # State 0 cannot be reached from state 1. + assert idfa.reroot_idfa_string((1, MISSING, MISSING, 1), new_root=1, n=2, k=2) is None diff --git a/tests/test_languages.py b/tests/test_languages.py index 68d3ce2..6c9ee97 100644 --- a/tests/test_languages.py +++ b/tests/test_languages.py @@ -182,6 +182,106 @@ def test_right_quotient_by_the_empty_word_is_identity(): assert quotient._negative == {("b",)} +def _ends_in_b() -> DFA: + dfa = DFA(input_alphabet=frozenset("ab"), initial_states=frozenset({0}), accepting_states=frozenset({1})) + for state in (0, 1): + dfa.graph.add_state(state) + dfa.add_transition(state, 0, "a") + dfa.add_transition(state, 1, "b") + return dfa + + +def test_language_operations_match_word_semantics(): + from sofic.automata.languages import operations as ops + + ends_a, ends_b = _simple_dfa(), _ends_in_b() + alphabet = frozenset("ab") + words = _brute_words("ab", 4) + in_a, in_b = (lambda w: ends_a.recognizes(w)), (lambda w: ends_b.recognizes(w)) + cases = { + "union": (ops.union(ends_a, ends_b), lambda w: in_a(w) or in_b(w)), + "intersection": (ops.intersection(ends_a, ends_b), lambda w: False), + "product": (ops.product(ends_a, ends_a), in_a), + "complement": (ops.complement(ends_a, alphabet), lambda w: not in_a(w)), + "difference": (ops.difference(ends_a, ends_b, alphabet), in_a), + "reverse": (ops.reverse(ends_a), lambda w: len(w) > 0 and w[0] == "a"), + "concat": ( + ops.concat(ends_a, ends_b), + lambda w: any(in_a(w[:i]) and in_b(w[i:]) for i in range(len(w) + 1)), + ), + "kleene_star": (ops.kleene_star(ends_a), lambda w: len(w) == 0 or in_a(w)), + } + for name, (language, expected) in cases.items(): + assert all((w in language) == expected(w) for w in words), name + + +def test_reverse_of_an_explicit_language_reverses_both_samples(): + from sofic.automata.languages.operations import reverse + + lang = ExplicitLanguage(positive={("a", "b")}, negative={("b", "b", "a")}, alphabet=frozenset("ab")) + reversed_lang = reverse(lang) + assert reversed_lang._positive == {("b", "a")} + assert reversed_lang._negative == {("a", "b", "b")} + assert reversed_lang.alphabet == frozenset("ab") + + +def test_language_operations_reject_explicit_languages(): + import pytest + + from sofic.automata.languages import operations as ops + + sample, dfa = ExplicitLanguage(positive={("a",)}), _simple_dfa() + for binary in (ops.union, ops.intersection, ops.difference, ops.concat): + with pytest.raises(TypeError, match="automaton-backed"): + binary(sample, dfa) + with pytest.raises(TypeError, match="automaton-backed"): + ops.complement(sample, frozenset("a")) + with pytest.raises(TypeError, match="automaton-backed"): + ops.kleene_star(sample) + with pytest.raises(TypeError, match="unsupported language"): + ops.reverse(frozenset()) + + +def test_prime_residuals_of_an_automaton_language(): + from sofic.automata.languages.residuals import prime_residuals + + # Residuals of "ends in a" are L and {epsilon} + L; neither is a union of residuals inside it. + primes = prime_residuals(AutomatonLanguage(_simple_dfa())) + words = _brute_words("ab", 4) + signatures = {frozenset(w for w in words if w in residual) for residual in primes} + ends_a = frozenset(w for w in words if w and w[-1] == "a") + assert signatures == {ends_a, ends_a | {()}} + + +def test_prime_residuals_of_a_sample_drop_composed_ones(): + from sofic.automata.languages.quotients import left_quotients + from sofic.automata.languages.residuals import prime_residuals + + lang = ExplicitLanguage(positive={("a", "b"), ("a", "c"), ("b", "c"), ("b", "d")}, alphabet=frozenset("abcd")) + residuals = left_quotients(lang) + primes = {frozenset(r._positive) for r in prime_residuals(lang)} + composed = {frozenset(r._positive) for r in residuals if is_composed_residual(r, residuals)} + assert composed + assert primes == {frozenset(r._positive) for r in residuals} - composed + + +def test_composed_automaton_residuals(): + from sofic.automata.languages.automaton_ops import union_nfa + + a_only, b_only = DFA(input_alphabet=frozenset("ab")), DFA(input_alphabet=frozenset("ab")) + for dfa, symbol in ((a_only, "a"), (b_only, "b")): + dfa.graph.add_state(0) + dfa.graph.add_state(1) + dfa.add_transition(0, 1, symbol) + dfa.initial_states, dfa.accepting_states = frozenset({0}), frozenset({1}) + both = AutomatonLanguage(union_nfa(a_only, b_only)) + first, second = AutomatonLanguage(a_only), AutomatonLanguage(b_only) + residuals = frozenset({first, second, both}) + assert is_composed_residual(both, residuals) + assert not is_composed_residual(first, residuals) + assert is_composed_residual(AutomatonLanguage(_empty_dfa()), frozenset({AutomatonLanguage(_empty_dfa())})) + + def test_composed_residual_ignores_non_contained_residuals(): r1 = ExplicitLanguage(positive={("a",)}) r2 = ExplicitLanguage(positive={("a",), ("b",)}) diff --git a/tests/test_pfa.py b/tests/test_pfa.py index 12207bd..89aeac7 100644 --- a/tests/test_pfa.py +++ b/tests/test_pfa.py @@ -32,3 +32,57 @@ def test_negative_probability(): pfa.add_transition("q0", "q0", "x", -0.1) with pytest.raises(StochasticValidationError): pfa.validate() + + +def _two_state() -> ProbabilisticFiniteAutomaton: + pfa = ProbabilisticFiniteAutomaton(initial_distribution={"a": 1.0}, output_alphabet=frozenset({"x", "y"})) + pfa.add_transition("a", "a", "x", 0.5) + pfa.add_transition("a", "b", "y", 0.5) + pfa.add_transition("b", "a", "x", 1.0) + return pfa + + +def test_string_probabilities_sum_over_words(): + pfa = _two_state() + assert pfa.string_probability(()) == pytest.approx(1.0) + assert pfa.string_probability(("x", "x")) == pytest.approx(0.25) + assert pfa.string_probability(("y", "x")) == pytest.approx(0.5) + assert pfa.string_probability(("y", "y")) == pytest.approx(0.0) + words = pfa.words_of_length(3) + assert sum(words.values()) == pytest.approx(1.0) + for word, prob in words.items(): + assert pfa.string_probability(word) == pytest.approx(prob) + + +def test_unifilarity_and_mealy_conversion(): + pfa = _two_state() + assert pfa.is_unifilar() + pfa.add_transition("b", "b", "x", 0.0) + assert not pfa.is_unifilar() + mealy = _two_state().to_mealy() + assert mealy.word_probability(("y", "x")) == pytest.approx(0.5) + + +def test_sample_follows_the_edges(): + import numpy as np + + pfa = _two_state() + sample = pfa.sample(200, rng=np.random.default_rng(0)) + assert len(sample) == 200 + assert "yy" not in "".join(sample) + assert ProbabilisticFiniteAutomaton(initial_distribution={}).sample(5) == [] + + +def test_sample_stops_at_dead_ends(): + import numpy as np + + pfa = ProbabilisticFiniteAutomaton(initial_distribution={"a": 1.0}, output_alphabet=frozenset({"x"})) + pfa.add_transition("a", "b", "x", 1.0) + pfa.graph.add_state("b") + assert pfa.sample(5, rng=np.random.default_rng(0)) == ["x"] + blocked = ProbabilisticFiniteAutomaton(initial_distribution={"a": 1.0}, output_alphabet=frozenset({"x"})) + blocked.add_transition("a", "a", "x", 0.0) + assert blocked.sample(5, rng=np.random.default_rng(0)) == [] + silent = ProbabilisticFiniteAutomaton(initial_distribution={"a": 1.0}, output_alphabet=frozenset({"x"})) + silent.graph.add_transition("a", "a", **{ATTR_PROB: 1.0}) + assert silent.sample(3, rng=np.random.default_rng(0)) == [] diff --git a/tests/test_processes_constructors.py b/tests/test_processes_constructors.py new file mode 100644 index 0000000..0d989d9 --- /dev/null +++ b/tests/test_processes_constructors.py @@ -0,0 +1,121 @@ +"""Variants and argument checks of the cmpy-compatible constructors in :mod:`sofic.examples.processes`.""" + +from __future__ import annotations + +import numpy as np +import pytest + +from sofic.examples import processes as pr +from sofic.generators.epsilon_machine import EpsilonMachine +from sofic.generators.mealy import MealyHMM + +VARIANTS = [ + (pr.band_merging, {"machine_type": EpsilonMachine}), + (pr.beads_on_necklace, {"beads": [(), ("a",), ("a", "b", "c")], "necklace": ("0", "1", "2"), "probs": 0.4}), + (pr.beads_on_necklace, {"beads": ("a", "b"), "necklace": ("0", "1"), "probs": [0.3, 0.6]}), + (pr.before_after, {"style": "cayley"}), + (pr.binary_markov_chain, {"p": 0.4, "q": 0.3, "machine_type": "generative"}), + (pr.binary_markov_chain, {"p": 0.4, "q": 0.3, "a": 0.1, "b": 0.8, "machine_type": "parametrized"}), + (pr.binary_markov_chain, {"p": 0.3, "machine_type": "lohr"}), + (pr.bmc_em, {"p": 0.3, "q": 0.7}), + (pr.bmc_gen, {"p": 1, "q": 1}), + (pr.bmc_gen, {"p": 0, "q": 0}), + (pr.bmc_gen, {"p": 0.7, "q": 0.6}), + (pr.bmc_gen, {"p": 0.2, "q": 0.4}), + (pr.bmc_gen, {"p": 0.4, "q": 0.2}), + (pr.coupled_gmps, {"epsilon": 0.1, "alt": False}), + (pr.coupled_gmps, {"epsilon": 0.0, "alt": False}), + (pr.coupled_gmps, {"epsilon": 0.0}), + (pr.iid, {"k": 2, "machine_type": "em"}), + (pr.iid, {"k": 2, "machine_type": "mealy"}), + (pr.iid, {"k": 2, "machine_type": "unknown"}), + (pr.iid, {"k": ("x", "y", "z"), "machine_type": MealyHMM}), + (pr.logic_machine, {"logic": "rrx"}), + (pr.logic_machine, {"logic": "rn1c", "bias": [0.3], "noise": 0.2}), + (pr.markov_skeleton, {"R": 1, "k": 11}), + (pr.markov_skeleton, {"R": 0, "k": 2}), + (pr.perturbed_coin, {"p": 0.5}), + (pr.perturbed_coin, {"p": 0.2, "machine_type": "lohr"}), + (pr.perturbed_coin, {"p": 0.2, "machine_type": "generative"}), + (pr.rip, {"reverse": True}), + (pr.rrx, {"machine_type": MealyHMM}), + (pr.stretched_gm, {"k": 3}), + (pr.rn_gm, {"R": 3, "N": 2}), + (pr.rk_gm, {"R": 2, "k": 2}), +] + + +@pytest.mark.parametrize(("factory", "kwargs"), VARIANTS, ids=lambda v: getattr(v, "__name__", None)) +def test_constructor_variants_are_valid_machines(factory, kwargs): + machine = factory(**kwargs) + machine.validate() + pi = np.asarray(machine.stationary_distribution(), dtype=float) + assert pi.sum() == pytest.approx(1.0) + + +ERRORS = [ + (pr.afc, {"n": 0}, ValueError), + (pr.afc2, {"n": 0}, ValueError), + (pr.beads_on_necklace, {"beads": (), "necklace": ("0",)}, ValueError), + (pr.beads_on_necklace, {"beads": [("a",), ("b",)], "necklace": ("0",)}, ValueError), + (pr.beads_on_necklace, {"beads": ("a",), "necklace": ("0", "1"), "probs": [0.5]}, ValueError), + (pr.beads_on_necklace, {"machine_type": EpsilonMachine}, NotImplementedError), + (pr.before_after, {"style": "fancy"}, ValueError), + (pr.binary_markov_chain, {"machine_type": "parametrized"}, ValueError), + (pr.binary_markov_chain, {"machine_type": "quantum"}, NotImplementedError), + (pr.binary_markov_chain, {"machine_type": MealyHMM}, NotImplementedError), + (pr.bmc_param, {"p": 0.4, "q": 0.3, "a": 0.9, "b": 0.8}, ValueError), + (pr.bmc_lohr, {"p": 0.6}, ValueError), + (pr.coupled_gmps, {"epsilon": -0.1}, ValueError), + (pr.uncoupled_gmps, {"p": 1.5}, ValueError), + (pr.cyclic_branching, {"num_states": 2, "num_branchings": 2}, ValueError), + (pr.flower, {"N": 1}, ValueError), + (pr.stretched_gm, {"k": 0}, ValueError), + (pr.rn_gm, {"R": 1, "N": 2}, ValueError), + (pr.rk_gm, {"R": 0, "k": 1}, ValueError), + (pr.nonunifilar_golden_mean, {"free": 0.01}, ValueError), + (pr.logic_machine, {"logic": "xor"}, NotImplementedError), + (pr.markov_skeleton, {"R": 1, "k": ("ab", "c"), "join": True}, ValueError), + (pr.perturbed_coin, {"p": 0.2, "q": 0.3, "machine_type": "lohr"}, ValueError), + (pr.perturbed_coin, {"p": 0.2, "machine_type": "quantum"}, NotImplementedError), + (pr.period16, {"machine_type": EpsilonMachine}, NotImplementedError), +] + + +@pytest.mark.parametrize(("factory", "kwargs", "error"), ERRORS, ids=lambda v: getattr(v, "__name__", None)) +def test_constructor_argument_checks(factory, kwargs, error): + with pytest.raises(error): + factory(**kwargs) + + +def test_transition_specifications_need_three_or_four_fields(): + with pytest.raises(ValueError, match="invalid transition specification"): + pr._from_string("A B; B A 1") + + +def test_ising_rejects_non_finite_probabilities(): + with np.errstate(all="ignore"), pytest.raises(FloatingPointError): + pr.ising(J=1.0, B=0.3, T=1e-3) + + +def test_markov_skeleton_with_tuple_states(): + machine = pr.markov_skeleton(2, ("a", "b"), join=False) + assert ("a", "b") in set(machine.states()) + assert len(list(machine.transitions())) == 8 + + +def test_uniform_mealyhmm_topologies(): + rng = np.random.default_rng(0) + from_machine = pr.uniform_mealyhmm(pr.even_process(), prng=rng) + assert {(t.source, t.target) for t in from_machine.transitions()} == { + (t.source, t.target) for t in pr.even_process().transitions() + } + one = np.ones((2, 2)) + from_mapping = pr.uniform_mealyhmm({"x": one, "y": np.eye(2)}, nodes=("p", "q"), prng=rng) + assert set(from_mapping.states()) == {"p", "q"} + assert from_mapping.observation_alphabet == frozenset("xy") + from_list = pr.uniform_mealyhmm([one, one], symbols=("u", "v"), prng=np.random.RandomState(0)) + assert from_list.observation_alphabet == frozenset("uv") + default_rng = pr.uniform_mealyhmm([one], prng=object()) + for machine in (from_machine, from_mapping, from_list, default_rng): + machine.validate() diff --git a/tests/test_renyi.py b/tests/test_renyi.py index 0140cc9..3b298fc 100644 --- a/tests/test_renyi.py +++ b/tests/test_renyi.py @@ -113,6 +113,12 @@ def test_rate_function_domain() -> None: assert rate_function(model, 2 / 3) == pytest.approx(0.0, abs=1e-9) +@pytest.mark.parametrize("alpha", [1.0 - 2**-53, 1.0 + 2**-52, 1.0 - 1e-12, 1.0 + 1e-9]) +def test_orders_next_to_one_match_shannon(alpha: float) -> None: + model = golden_mean(0.3) + assert renyi_entropy_rate(model, alpha) == pytest.approx(float(model.entropy_rate()), abs=1e-8) + + @settings(max_examples=40) @given(weighted_machines(), st.floats(0.05, 5.0)) def test_properties(model: EpsilonMachine, alpha: float) -> None: diff --git a/tests/test_stack_inference.py b/tests/test_stack_inference.py index 529c005..637d31b 100644 --- a/tests/test_stack_inference.py +++ b/tests/test_stack_inference.py @@ -312,3 +312,65 @@ def test_stack_mle_accounts_for_illegal_returns_on_empty_stack(): oracle_bits = np.mean([_held_out_bits_per_symbol(oracle, w) for w in windows]) fitted_bits = np.mean([_held_out_bits_per_symbol(fitted, w) for w in windows]) assert fitted_bits == pytest.approx(oracle_bits, abs=0.01) + + +def _motzkin_alphabet() -> DyckAlphabet: + return DyckAlphabet( + call_alphabet=frozenset({"("}), return_alphabet=frozenset({")"}), internal_alphabet=frozenset({"x"}) + ) + + +def test_dyck_alphabet_roles(): + from sofic.graph import KIND_CALL, KIND_INTERNAL, KIND_RETURN + + alphabet = _motzkin_alphabet() + assert alphabet.symbol_alphabet == frozenset({"(", ")", "x"}) + assert [alphabet.classify(s) for s in "()x"] == [KIND_CALL, KIND_RETURN, KIND_INTERNAL] + with pytest.raises(ValueError, match="not in Dyck alphabet"): + alphabet.classify("y") + with pytest.raises(ValueError, match="disjoint"): + DyckAlphabet(frozenset("a"), frozenset("a"), frozenset()) + + +def test_papni_encoding_rejects_unmatched_and_foreign_words(): + from sofic.automata.learning.papni import _decode_symbol, encode_dyck_samples + + alphabet = _motzkin_alphabet() + assert not is_well_matched(("(", "y", ")"), alphabet) + assert not is_well_matched(("(",), alphabet) + with pytest.raises(ValueError, match="not well-matched"): + encode_dyck_word(("(",), alphabet) + samples = [("(", "x", ")"), (")",)] + assert encode_dyck_samples(samples, alphabet) == [("(", "x", (")", "("))] + with pytest.raises(ValueError, match="not well-matched"): + encode_dyck_samples(samples, alphabet, drop_non_well_matched=False) + with pytest.raises(ValueError, match="unknown stack-aware symbol"): + _decode_symbol((")", "x"), alphabet) + + +def test_papni_with_negatives_and_without_positives(): + alphabet = _motzkin_alphabet() + positive = [("(", ")"), ("x",), ("(", "x", ")"), ("(", "(", ")", ")")] + negative = [("(", "x", "x", ")"), (")", "(")] + learned = learn_sofic_dyck_shift_papni(positive, negative, alphabet=alphabet) + assert learned.is_admissible_word(("(", "x", ")")) + with pytest.raises(ValueError, match="no well-matched positive"): + learn_sofic_dyck_shift_papni([(")",)], alphabet=alphabet) + + +def test_papni_dfa_conversion_with_and_without_traces(): + from sofic.automata.learning.papni import encode_dyck_samples, sofic_dyck_shift_from_papni_dfa + + alphabet = _motzkin_alphabet() + positive = [("(", ")"), ("x",), ("(", "x", ")")] + dfa = learn_dfa_rpni(encode_dyck_samples(positive, alphabet), []) + by_symbol = sofic_dyck_shift_from_papni_dfa(dfa, alphabet) + assert by_symbol.matched_edges + # Traces the DFA cannot follow, or that are not well matched, add no matched pairs. + traced = sofic_dyck_shift_from_papni_dfa(dfa, alphabet, positive_traces=[(")", "("), ("(", "(", "x", ")", ")")]) + assert len(traced.matched_edges) <= len(by_symbol.matched_edges) + from sofic.automata.dfa import DFA + + no_initial = DFA(input_alphabet=frozenset()) + with pytest.raises(ValueError, match="initial state"): + sofic_dyck_shift_from_papni_dfa(no_initial, alphabet) diff --git a/tests/test_stationary.py b/tests/test_stationary.py index 1f2b715..17f1267 100644 --- a/tests/test_stationary.py +++ b/tests/test_stationary.py @@ -77,3 +77,53 @@ def dense(*args, **kwargs): pi = stationary.stationary_distribution_hmm(_chain(n, edges)) expected = 0.25 * 0.75 ** np.arange(n) / (1 - 0.75**n) assert np.allclose(pi, expected, atol=1e-12) + + +def test_empty_chain_has_empty_stationary_distribution() -> None: + assert stationary.stationary_distribution_hmm(MealyHMM(observation_alphabet=frozenset({0}))).size == 0 + assert stationary_distribution_from_transition(np.zeros((0, 0))).size == 0 + + +def test_non_square_transition_matrices_are_rejected() -> None: + with pytest.raises(ValueError, match="square"): + stationary_distribution_from_transition(np.ones((2, 3)) / 3) + + +def test_sparse_stationary_skips_outside_states_and_declines_symbolic_or_non_invariant() -> None: + sp = pytest.importorskip("sympy") + hmm = _chain(3, [(0, 1, 1.0), (1, 0, 1.0), (1, 2, 0.0), (2, 2, 1.0)]) + assert np.allclose(stationary._stationary_distribution_sparse(hmm, [0, 1]), [0.5, 0.5]) + symbolic = _chain(2, [(0, 1, 1.0), (1, 0, sp.Integer(1))]) + assert stationary._stationary_distribution_sparse(symbolic, [0, 1]) is None + substochastic = _chain(2, [(0, 1, 0.5), (1, 0, 1.0)]) + assert stationary._stationary_distribution_sparse(substochastic, [0, 1]) is None + + +def test_matrices_without_a_stationary_distribution_raise() -> None: + from sofic.exceptions import StochasticValidationError + + # No eigenvalue one, so every eigenvector is skipped and the least-squares fallback is not invariant. + with pytest.raises(StochasticValidationError, match="invariant"): + stationary_distribution_from_transition(np.array([[0.5, 0.5], [0.5, 0.4]])) + # Eigenvalue one with a sign-changing eigenvector. + with pytest.raises(StochasticValidationError): + stationary_distribution_from_transition(np.array([[0.0, -1.0], [-1.0, 0.0]])) + + +def test_symbolic_stationary_distribution() -> None: + sp = pytest.importorskip("sympy") + p, q = sp.symbols("p q", positive=True) + transition = np.array([[1 - p, p], [q, 1 - q]], dtype=object) + pi = stationary_distribution_from_transition(transition) + assert sp.simplify(pi[0] - q / (p + q)) == 0 + assert sp.simplify(pi[1] - p / (p + q)) == 0 + assert stationary_distribution_from_transition(np.zeros((0, 0), dtype=object)).size == 0 + with pytest.raises(ValueError, match="square"): + stationary_distribution_from_transition(np.array([[p, 1 - p, 0]], dtype=object)) + + +def test_symbolic_stationary_distribution_of_a_periodic_chain() -> None: + sp = pytest.importorskip("sympy") + one = sp.Integer(1) + pi = stationary_distribution_from_transition(np.array([[0, one], [one, 0]], dtype=object)) + assert list(pi) == [sp.Rational(1, 2), sp.Rational(1, 2)] diff --git a/tests/test_structural_predicates.py b/tests/test_structural_predicates.py new file mode 100644 index 0000000..3b6fd30 --- /dev/null +++ b/tests/test_structural_predicates.py @@ -0,0 +1,135 @@ +"""Structural predicates in :mod:`sofic.properties`.""" + +from __future__ import annotations + +from sofic import properties as P +from sofic.automata.nfa import NFA +from sofic.automata.transducers import MealyMachine +from sofic.examples import even_process, golden_mean +from sofic.examples.processes import sns +from sofic.generators.mealy import MealyHMM +from sofic.graph import ATTR_EMISSION, EPSILON + + +def _chain(edges, initial=None) -> MealyHMM: + hmm = MealyHMM(observation_alphabet=frozenset("ab"), initial_distribution=initial or {}) + for source, target, symbol, prob in edges: + hmm.graph.add_state(source) + hmm.graph.add_state(target) + hmm.add_transition(source, target, symbol, prob) + return hmm + + +def _cycle() -> MealyHMM: + return _chain([(0, 1, "a", 1.0), (1, 2, "a", 1.0), (2, 0, "a", 1.0)], {0: 1 / 3, 1: 1 / 3, 2: 1 / 3}) + + +def _transducer(edges, initial=(0,)) -> MealyMachine: + machine = MealyMachine(initial_states=frozenset(initial)) + for source, target, symbol, output in edges: + machine.graph.add_state(source) + machine.graph.add_state(target) + machine.add_transition(source, target, symbol, output) + return machine + + +def test_unifilarity_ignores_unlabeled_and_excluded_edges(): + hmm = _chain([(0, 0, "a", 0.5), (0, 1, "b", 0.5), (1, 0, "a", 1.0)]) + hmm.graph.add_transition(0, 1, prob=0.0) + assert P.is_unifilar_emissions(hmm) + hmm.add_transition(0, 1, "a", 0.0) + assert not P.is_unifilar_emissions(hmm) + assert P.is_unifilar_labeled(hmm, label_attr=ATTR_EMISSION, exclude_labels=("a",)) + + +def test_counifilar_emissions(): + hmm = _chain([(0, 0, "a", 0.5), (0, 1, "b", 0.5), (1, 0, "b", 1.0)]) + hmm.graph.add_transition(1, 1, prob=0.0) + assert P.is_counifilar_emissions(hmm) + hmm.add_transition(1, 0, "a", 0.0) + assert not P.is_counifilar_emissions(hmm) + + +def test_deterministic_automata_need_one_initial_state_and_no_epsilon(): + nfa = NFA(input_alphabet=frozenset("a"), initial_states=frozenset({0}), accepting_states=frozenset({0})) + nfa.graph.add_state(0) + nfa.add_transition(0, 0, "a") + assert P.is_deterministic_automaton(nfa) + nfa.graph.add_state(1) + nfa.add_transition(0, 1, EPSILON) + assert not P.is_deterministic_automaton(nfa) + nfa.initial_states = frozenset({0, 1}) + assert not P.is_deterministic_automaton(nfa) + + +def test_deterministic_markov_chains(): + assert P.is_deterministic_markov(_cycle()) + assert not P.is_deterministic_markov(_chain([(0, 0, "a", 0.5), (0, 0, "b", 0.5)])) + assert not P.is_deterministic_markov(_chain([(0, 0, "a", 0.5)])) + + +def test_transducer_unifilarity_and_counifilarity_skip_epsilon(): + machine = _transducer([(0, 1, "a", "x"), (0, 0, "a", "y"), (1, 0, EPSILON, "x"), (1, 1, EPSILON, "x")]) + assert P.is_unifilar_transducer(machine) + assert P.is_counifilar_transducer(machine) + assert not P.is_deterministic_transducer(machine) + machine.add_transition(0, 0, "a", "x") + assert not P.is_unifilar_transducer(machine) + other = _transducer([(0, 1, "a", "x"), (1, 1, "a", "x")]) + assert not P.is_counifilar_transducer(other) + + +def test_sequential_and_subsequential_transducers(): + machine = _transducer([(0, 1, "a", "x"), (1, 0, "b", "y")]) + assert P.is_sequential_transducer(machine) + assert not P.is_subsequential_transducer(machine) + machine.final_output = {0: (), 1: ("z",)} + assert P.is_subsequential_transducer(machine) + assert not P.is_sequential_transducer(_transducer([(0, 1, "a", "x"), (0, 0, "a", "y")])) + assert not P.is_sequential_transducer(_transducer([(0, 1, EPSILON, "x")])) + assert not P.is_sequential_transducer(_transducer([(0, 1, "a", "x")], initial=(0, 1))) + + +def test_irreducibility_and_recurrent_states(): + assert P.is_irreducible(_chain([(0, 0, "a", 1.0)])) + assert P.is_irreducible(_cycle()) + transient = _chain([(0, 1, "a", 1.0), (1, 1, "a", 1.0)]) + assert not P.is_irreducible(transient) + assert P.recurrent_states(transient) == frozenset({1}) + + +def test_ergodicity(): + assert not P.is_ergodic(MealyHMM(observation_alphabet=frozenset("a"))) + assert P.is_ergodic(_cycle()) + assert not P.is_ergodic(_cycle(), weak=False) + assert P.is_ergodic(golden_mean(), weak=False) + split = _chain([(0, 1, "a", 0.5), (0, 2, "b", 0.5), (1, 1, "a", 1.0), (2, 2, "b", 1.0)], {0: 1.0}) + assert not P.is_ergodic(split) + assert P.is_ergodic(_chain([(0, 1, "a", 0.5), (0, 2, "b", 0.5), (1, 1, "a", 1.0), (2, 2, "b", 1.0)], {1: 1.0})) + + +def test_stationarity(): + assert P.is_stationary(golden_mean()) + assert not P.is_stationary(_chain([(0, 1, "a", 1.0), (1, 0, "a", 1.0)], {0: 1.0})) + assert not P.is_stationary(_transducer([(0, 0, "a", "x")])) + + +def test_detailed_balance(): + reversible = _chain([(0, 0, "a", 0.5), (0, 1, "a", 0.5), (1, 0, "a", 0.5), (1, 1, "a", 0.5)], {0: 0.5, 1: 0.5}) + assert P.is_detailed_balance(reversible) + assert not P.is_detailed_balance(_cycle()) + # Labeled flows: the golden mean's 1-edge A -> B has no reverse 1-edge. + assert not P.is_detailed_balance(golden_mean()) + + +def test_periodicity(): + assert not P.is_periodic(MealyHMM(observation_alphabet=frozenset("a"))) + assert P.is_periodic(_cycle()) + assert not P.is_periodic(golden_mean()) + + +def test_strictly_sofic_supports(): + assert P.is_strictly_sofic(even_process()) + assert not P.is_strictly_sofic(golden_mean()) + # The simple nonunifilar source has a non-unifilar support presentation of finite type. + assert not P.is_strictly_sofic(sns()) diff --git a/tests/test_transducers.py b/tests/test_transducers.py index f1ea9e2..86d29d9 100644 --- a/tests/test_transducers.py +++ b/tests/test_transducers.py @@ -1,9 +1,10 @@ """Tests for Mealy and Moore transducers.""" +import numpy as np import pytest from sofic.automata.transducers import MealyMachine, MooreMachine -from sofic.exceptions import InfiniteTransductionError +from sofic.exceptions import InfiniteTransductionError, SoficValidationError, StochasticValidationError from sofic.graph import ATTR_OUTPUT, ATTR_SYMBOL, EPSILON @@ -129,3 +130,128 @@ def test_transducer_yaml_round_trip_preserves_epsilon(): restored = MealyMachine.from_yaml(mealy.to_yaml()) assert restored.transduce(("a",)) == {("1",)} assert any(t.data[ATTR_SYMBOL] is EPSILON for t in restored.transitions()) + + +def _partial() -> MealyMachine: + """Stochastic two-state channel; input ``b`` is missing in state ``t``.""" + m = MealyMachine( + input_alphabet=frozenset({"a", "b"}), + output_alphabet=frozenset({"x", "y"}), + initial_states=frozenset({"s"}), + ) + m.add_transition("s", "s", "a", "x", prob=0.25) + m.add_transition("s", "t", "a", "y", prob=0.75) + m.add_transition("s", "t", "b", "y", prob=1.0) + m.add_transition("t", "s", "a", "x", prob=1.0) + return m + + +def test_alphabets_by_state_and_completeness(): + m = _partial() + inputs, outputs = m.alphabets(node=True) + assert inputs == {"s": frozenset("ab"), "t": frozenset("a")} + assert outputs == {"s": frozenset("xy"), "t": frozenset("x")} + assert not m.is_complete() + assert m.is_complete(frozenset("a")) + + +def test_complete_adds_a_reject_sink_only_when_needed(): + m = _partial() + completed = m.complete() + assert completed is not m + assert completed.is_complete() + assert "?" in set(completed.states()) and "?" in completed.output_alphabet + assert completed.transduce(("b", "b")) == {("y", "?")} + completed.validate_stochastic() + already = completed.complete(copy=False) + assert already is completed + assert len(list(already.states())) == 3 + assert MealyMachine().complete().input_alphabet == frozenset() + + +def test_input_and_output_machines(): + m = _partial() + inputs = m.input_machine() + assert inputs.observation_alphabet == frozenset("ab") + assert sum(t.data["prob"] for t in inputs.graph.out_transitions("s")) == pytest.approx(1.0) + outputs = m.output_machine() + assert outputs.observation_alphabet == frozenset("xy") + built = _mealy().output_machine(build=True) + assert len(list(built.states())) == 1 + + +def test_labeled_transition_matrices_options(): + m = _partial() + matrices = m.labeled_transition_matrices(["t", "s"]) + assert matrices[("a", "y")][1, 0] == pytest.approx(0.75) + nan = m.labeled_transition_matrices(["s", "t"], mode="nan") + assert np.isnan(nan[("b", "y")][1]).all() + assert not np.isnan(nan[("b", "y")][0]).any() + restricted = m.labeled_transition_matrices(["s"]) + assert restricted[("a", "x")][0, 0] == pytest.approx(0.25) + with pytest.raises(ValueError, match="unknown states"): + m.labeled_transition_matrices(["s", "nope"]) + with pytest.raises(ValueError, match="mode"): + m.labeled_transition_matrices(mode="inf") + + +def test_validate_stochastic_rejects_bad_rows(): + m = _partial() + m.validate_stochastic() + m.add_transition("t", "t", "a", "y", prob=0.5) + with pytest.raises(StochasticValidationError, match="sums to"): + m.validate_stochastic() + negative = _partial() + negative.add_transition("t", "t", "b", "y", prob=-1.0) + with pytest.raises(StochasticValidationError, match="negative"): + negative.validate_stochastic() + + +def test_validate_rejects_symbols_outside_the_alphabets(): + bad_output = _partial() + bad_output.add_transition("t", "t", "b", "z") + with pytest.raises(SoficValidationError, match="output 'z'"): + bad_output.validate() + bad_input = _partial() + bad_input.add_transition("t", "t", "c", "x") + with pytest.raises(SoficValidationError, match="symbol 'c'"): + bad_input.validate() + missing_initial = _partial() + missing_initial.initial_states = frozenset({"nowhere"}) + with pytest.raises(SoficValidationError, match="initial state"): + missing_initial.validate() + + +def test_moore_outputs_and_validation(): + m = MooreMachine(input_alphabet=frozenset("a"), output_alphabet=frozenset("0"), initial_states=frozenset({0})) + m.graph.add_state(0) + m.add_transition(0, 0, "a", prob=1.0) + m.set_output(0, "0") + m.validate() + assert m.transduce(("a",)) == {("0", "0")} + m.set_output(0, "9") + with pytest.raises(SoficValidationError, match="output '9'"): + m.validate() + m.set_output(0, "0") + m.add_transition(0, 0, "b") + with pytest.raises(SoficValidationError, match="symbol 'b'"): + m.validate() + + +def test_serial_composition_of_binary_channels(): + from sofic.examples.processes import binary_channel + + composed = binary_channel(0.1, 0.2).compose(binary_channel(0.1, 0.1)) + matrices, _states = composed.labeled_transition_matrices() + assert matrices[("0", "1")][0, 0] == pytest.approx(0.1 * 0.9 + 0.9 * 0.1) + assert matrices[("1", "0")][0, 0] == pytest.approx(0.8 * 0.1 + 0.2 * 0.9) + + +def test_conversions_to_other_representations(): + from sofic.examples.processes import binary_channel + + channel = binary_channel(0.1, 0.2) + assert channel.to_wfst().__class__.__name__ == "WeightedFiniteStateTransducer" + assert channel.to_textile_system().__class__.__name__ == "TextileSystem" + assert channel.to_product_alphabet_shift().__class__.__name__ == "ProductAlphabetShift" + assert channel.__dit_channel__().__class__.__name__ == "FiniteStateChannel" diff --git a/tests/test_viz.py b/tests/test_viz.py index faeca6d..2b7e4d8 100644 --- a/tests/test_viz.py +++ b/tests/test_viz.py @@ -327,3 +327,74 @@ def test_colliding_states_render_as_distinct_nodes(): tikz = model_to_tikz(shift) assert tikz.count(r"\node [state") == 2 assert len({line.split("(")[1].split(")")[0] for line in tikz.splitlines() if r"\node [state" in line}) == 2 + + +def _spec_parts(model, **data): + from sofic.viz._edge import edge_spec + + model.graph.add_state(0) + key = model.graph.add_transition(0, 0, **data) + transition = next(t for t in model.transitions() if t.key == key) + spec = edge_spec(model, transition) + return spec.style, [(part.kind, part.value) for part in spec.parts] + + +def test_edge_specs_for_each_model_family(): + from sofic.automata.transducers import MooreMachine + from sofic.base import StateMachine + from sofic.generators.base import QuasiStochasticModel + from sofic.generators.mealy import MealyHMM + from sofic.generators.moore import MooreHMM + from sofic.generators.nmachine import NMachine + from sofic.graph import ATTR_EMISSION, ATTR_QUASIPROB, ATTR_SYMBOL + + class Bare(StateMachine): + def validate(self) -> None: + pass + + assert _spec_parts(MooreMachine(), **{ATTR_SYMBOL: "a"}) == ("symbol_only", [("symbol", "a")]) + assert _spec_parts(MooreMachine()) == ("symbol_only", []) + assert _spec_parts(NMachine(), **{ATTR_EMISSION: "x", ATTR_QUASIPROB: -0.5}) == ( + "edge", + [("emission", "x"), ("quasiprob", -0.5)], + ) + assert _spec_parts(MooreHMM(), **{ATTR_PROB: 0.25}) == ("prob_only", [("prob", 0.25)]) + assert _spec_parts(MooreHMM()) == ("prob_only", []) + assert _spec_parts(MealyHMM(), **{ATTR_SYMBOL: "s", ATTR_PROB: 1.0}) == ("edge", [("symbol", "s"), ("prob", 1.0)]) + assert _spec_parts(MealyHMM()) == ("edge", []) + assert _spec_parts(QuasiStochasticModel(), **{ATTR_EMISSION: "x", ATTR_QUASIPROB: 2.0}) == ( + "edge", + [("emission", "x"), ("quasiprob", 2.0)], + ) + assert _spec_parts(QuasiStochasticModel()) == ("edge", []) + full = {ATTR_SYMBOL: "a", ATTR_EMISSION: "x", ATTR_PROB: 0.5, ATTR_QUASIPROB: 0.5} + assert _spec_parts(Bare(), **full) == ( + "fallback", + [("symbol", "a"), ("emission", "x"), ("prob", 0.5), ("quasiprob", 0.5)], + ) + assert _spec_parts(Bare()) == ("fallback", []) + + +def test_prob_part_prefers_probability_then_quasiprobability(): + from sofic.viz._edge import _primary_symbol_part, _prob_part + + assert _prob_part(0.5, 0.1).kind == "prob" + assert _prob_part(None, 0.1).kind == "quasiprob" + assert _prob_part(None, None) is None + assert _primary_symbol_part(None, "a", symbol_fallback=False) is None + + +def test_idiagram_legend_layout_helpers(): + from sofic.viz import idiagram as idg + + assert idg._legend_ncols(5.0, 0) == 1 + assert idg._legend_ncols(100.0, 3) == 3 + assert idg._legend_ncols(1.0, 3) == 1 + handles = {group: group for group in idg.GROUP_ORDER} + packed, ncol = idg._pack_legend_handles(handles, 4, empty_patch=None) + assert ncol == 4 + height = len(packed) // ncol + assert packed[:height] == ["r_mu"] + [None] * (height - 1) + assert set(idg.GROUP_ORDER) <= set(packed) + assert idg._pack_legend_handles({"structure": "s"}, 4, empty_patch=None) == (["s"], 1) + assert idg._pack_legend_handles({}, 4, empty_patch=None) == ([], 1) diff --git a/tests/test_vpa.py b/tests/test_vpa.py index 39c0150..6b87b0f 100644 --- a/tests/test_vpa.py +++ b/tests/test_vpa.py @@ -359,3 +359,68 @@ def test_no_call_canonical_vpa_matches_dfa_minimization(): assert len(list(canonical.states())) == len(list(minimized_dfa.states())) for word in [(), ("a",), ("b",), ("a", "a"), ("a", "b"), ("b", "a")]: assert canonical.recognizes(word) == minimized_dfa.recognizes(word) + + +_CDA_WORDS = [(), ("c", "r"), ("d", "r"), ("c",), ("r",), ("c", "r", "d", "r"), ("c", "d")] + + +def test_cda_minimize_preserves_the_language(): + cda = _cda() + minimized = ModularVisiblyPushdownAutomaton.minimize(cda) + minimized.validate() + assert [minimized.recognizes(w) for w in _CDA_WORDS] == [cda.recognizes(w) for w in _CDA_WORDS] + + +def test_mevpa_minimize_with_inferred_and_explicit_entries(): + cda = _cda() + inferred = MultipleEntryVisiblyPushdownAutomaton.minimize(cda) + explicit = MultipleEntryVisiblyPushdownAutomaton.minimize(cda, entry_states={"main": "m", "proc": ["e0", "e1"]}) + for machine in (inferred, explicit): + machine.validate() + assert [machine.recognizes(w) for w in _CDA_WORDS] == [cda.recognizes(w) for w in _CDA_WORDS] + + +def test_sevpa_minimize_with_explicit_entries_and_rejects_multi_entry_modules(): + sevpa = _redundant_sevpa() + minimized = SingleEntryVisiblyPushdownAutomaton.minimize(sevpa, entry_states={"proc": "p"}) + assert len(list(minimized.states())) == 2 + with pytest.raises(ValueError, match="one entry per non-base module"): + SingleEntryVisiblyPushdownAutomaton.minimize(_cda()) + + +def _source_dependent_calls() -> DeterministicVisiblyPushdownAutomaton: + vpa = DeterministicVisiblyPushdownAutomaton( + call_alphabet=frozenset({"c"}), + return_alphabet=frozenset({"r"}), + stack_alphabet=frozenset({"x", "y"}), + initial_state="m0", + accepting_states=frozenset({"m0"}), + ) + for state in ("m0", "m1", "p0", "p1"): + vpa.graph.add_state(state) + vpa.add_call_transition("m0", "p0", "c", "x") + vpa.add_call_transition("m1", "p1", "c", "y") + vpa.add_return_transition("p0", "m1", "r", "x") + vpa.add_return_transition("p1", "m0", "r", "y") + return vpa + + +def test_modular_minimize_argument_checks(): + vpa = _source_dependent_calls() + modules = {"main": {"m0", "m1"}, "proc": {"p0", "p1"}} + with pytest.raises(ValueError, match="call_partition is required"): + ModularVisiblyPushdownAutomaton.minimize(vpa, modules=modules, base_module="main") + with pytest.raises(ValueError, match="missing call symbol"): + ModularVisiblyPushdownAutomaton.minimize(vpa, modules=modules, base_module="main", call_partition={}) + with pytest.raises(ValueError, match="depends on the source state"): + ModularVisiblyPushdownAutomaton.minimize(vpa, modules=modules, base_module="main", call_partition={"c": "proc"}) + + +def test_call_entry_map_rejects_source_dependent_targets(): + cda = _cda() + cda.call_entries = {} + cda.graph.add_state("e2") + cda.modules = {**cda.modules, "proc": frozenset({"e0", "e1", "e2"})} + cda.add_call_transition("e0", "e2", "c", "m") + with pytest.raises(NonDeterministicError, match="depends on source state"): + cda.call_entry_map() diff --git a/uv.lock b/uv.lock index 6d9f486..a3a718e 100644 --- a/uv.lock +++ b/uv.lock @@ -663,7 +663,7 @@ wheels = [ [[package]] name = "dit" -version = "2.3" +version = "2.4" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "boltons" }, @@ -672,13 +672,13 @@ dependencies = [ { name = "loguru" }, { name = "networkx" }, { name = "numpy" }, - { name = "pltable" }, + { name = "prettytable" }, { name = "scipy" }, { name = "xarray" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a0/e0/626a2915f86f142e6f33a645ce36be2daf9d0ce0462972f3d8a983d581d2/dit-2.3.tar.gz", hash = "sha256:3cd12221de65ead9decadf1107d4b9b534cadf936cfc2e2293cfacc5ce99f56b", size = 593505, upload-time = "2026-09-26T23:47:53.275Z" } +sdist = { url = "https://files.pythonhosted.org/packages/54/02/870a1d15418c8ddbb13ecc8c18fcaa96f391cd01f8ac193c198b45943665/dit-2.4.tar.gz", hash = "sha256:9f9fc623985032e3ee35940066e8ab91d5a1c61f375542452e4f436186039532", size = 986282, upload-time = "2026-11-16T04:55:52.395Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/51/fc/c8a71a3786ecf945154c45e549e27cb904c51b97f95e2416d90ed93a1f25/dit-2.3-py3-none-any.whl", hash = "sha256:6e3390a9c80311f6b740ca322fbc7aff478c6e07f1039d8d2c5b43250e2bff24", size = 581256, upload-time = "2026-09-26T23:47:51.405Z" }, + { url = "https://files.pythonhosted.org/packages/05/97/f3e0e318c69c065185e29c62b791be00c30a88e33542056ee6629665281d/dit-2.4-py3-none-any.whl", hash = "sha256:3bbb4db1f031a3d185a2886762a5d3f6b33a9f178726f5fc9029bc8346ff9f5b", size = 842778, upload-time = "2026-11-16T04:55:50.411Z" }, ] [package.optional-dependencies] @@ -1768,12 +1768,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/81/e6/cd9575ac904136b3cbf7aa7ee819ef86eedb7274e46f230e94ea4342e729/platformdirs-4.10.0-py3-none-any.whl", hash = "sha256:fb516cdb12eb0d857d0cd85a7c57cea4d060bee4578d6cf5a14dfdf8cbf8784a", size = 22743, upload-time = "2026-05-28T03:32:52.175Z" }, ] -[[package]] -name = "pltable" -version = "1.1.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/53/b9/0276a2c7699255c9a8e459b093db4414162607dcf42636c0bbe4be1bf8e4/PLTable-1.1.0.tar.gz", hash = "sha256:dc8eb7cb9721a7090dc7a5976fbec7d3ef6b82a61f86c3b98700571a3f10401a", size = 17637, upload-time = "2023-11-21T22:14:43.834Z" } - [[package]] name = "pluggy" version = "1.6.0" @@ -1783,6 +1777,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, ] +[[package]] +name = "prettytable" +version = "3.18.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "wcwidth" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/81/74/ba08d81e668ccfe8658d7520a307e63c19862c08eb4ccb26f356c5239a7a/prettytable-3.18.0.tar.gz", hash = "sha256:439217116152244369caf3d9f1caf2f9fe29b03bd79e88d2928c8e718c95d680", size = 76373, upload-time = "2026-06-22T16:07:50.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fe/be/2e6798ace5cc036f5d05d36b7b2fd85346f1a708c87060890b070d0ec607/prettytable-3.18.0-py3-none-any.whl", hash = "sha256:b3346e0e6f79180833aebaac088ae926340586cf6d7d991b9eb125b65f72313a", size = 37357, upload-time = "2026-06-22T16:07:48.595Z" }, +] + [[package]] name = "prompt-toolkit" version = "3.0.52" @@ -2547,10 +2553,10 @@ requires-dist = [ { name = "arviz", marker = "extra == 'bayes'" }, { name = "cvxpy", marker = "extra == 'capacity'", specifier = ">=1.4" }, { name = "cvxpy", marker = "extra == 'dev'", specifier = ">=1.4" }, - { name = "dit", specifier = ">=2.3" }, - { name = "dit", extras = ["symbolic"], marker = "extra == 'dev'", specifier = ">=2.3" }, - { name = "dit", extras = ["symbolic"], marker = "extra == 'docs'", specifier = ">=2.3" }, - { name = "dit", extras = ["symbolic"], marker = "extra == 'symbolic'", specifier = ">=2.3" }, + { name = "dit", specifier = ">=2.4" }, + { name = "dit", extras = ["symbolic"], marker = "extra == 'dev'", specifier = ">=2.4" }, + { name = "dit", extras = ["symbolic"], marker = "extra == 'docs'", specifier = ">=2.4" }, + { name = "dit", extras = ["symbolic"], marker = "extra == 'symbolic'", specifier = ">=2.4" }, { name = "graphviz", marker = "extra == 'dev'", specifier = ">=0.20" }, { name = "graphviz", marker = "extra == 'test'", specifier = ">=0.20" }, { name = "graphviz", marker = "extra == 'viz'", specifier = ">=0.20" }, From 3f490952f27ea4fb6ea5acba6246875959574290 Mon Sep 17 00:00:00 2001 From: Ryan James Date: Sun, 15 Nov 2026 22:35:37 -0700 Subject: [PATCH 2/7] Speed up the lifted common-information problem: matrix products, cached tensors, batched entropies Co-authored-by: Cursor --- sofic/generators/lifted_common_information.py | 117 +++++++++++------- tests/oracles.py | 65 ++++++++++ tests/test_lifted_common_information.py | 27 ++++ 3 files changed, 164 insertions(+), 45 deletions(-) diff --git a/sofic/generators/lifted_common_information.py b/sofic/generators/lifted_common_information.py index 7d9ab19..eece358 100644 --- a/sofic/generators/lifted_common_information.py +++ b/sofic/generators/lifted_common_information.py @@ -64,6 +64,7 @@ import numpy as np from scipy.optimize import minimize +from scipy.special import entr from sofic.exceptions import StochasticValidationError from sofic.generators.minimal_generative_model import ( @@ -84,6 +85,8 @@ from sofic.generators.bidirectional_epsilon_machine import BidirectionalEpsilonMachine _LN2 = np.log(2.0) +# I[a : b | c] = H[a, c] + H[b, c] - H[a, b, c] - H[c] +_CMI_SIGNS = np.array([1.0, 1.0, -1.0, -1.0]) _COARSE_TOL = 5e-8 _REFINE = 5 _SUPPORT_CUTOFF = 1e-8 @@ -120,42 +123,71 @@ def __init__(self, bidir: BidirectionalEpsilonMachine, joint: dict[tuple[Hashabl transition.data.get(ATTR_PROB, 0.0) ) self.edges /= self.edges.sum() + # The edge law flattened both ways, and p(s+, s- | pair), for the matrix products below. + self._edges_rows = self.edges.reshape(n * len(symbols), n) # [(p, x), q] + self._edges_cols = self.edges.reshape(n, len(symbols) * n) # [p, (x, q)] + self._pair_labels = (self.plus[:, :, None] * self.minus[:, None, :]).reshape(n, -1) # [p, (a, b)] + self._cached: tuple[tuple[int, ...], bytes, dict[str, np.ndarray]] | None = None + + def _products(self, c: np.ndarray) -> dict[str, np.ndarray]: + """The tensors of :meth:`tensors` and the intermediate products, for the last ``c`` seen. + + SLSQP evaluates the constraints and their Jacobian at the same point, so the last one is kept. + """ + key = c.tobytes() + if self._cached is not None and self._cached[0] == c.shape and self._cached[1] == key: + return self._cached[2] + n, k = c.shape + n_plus, n_minus, n_sym = self.plus.shape[1], self.minus.shape[1], self.edges.shape[1] + plus_c = (self.plus[:, :, None] * c[:, None, :]).reshape(n, n_plus * k) # [p, (a, g)] + minus_c = (self.minus[:, :, None] * c[:, None, :]).reshape(n, n_minus * k) # [q, (s, v)] + forward = self._edges_rows @ c # [(p, x), v] + past = (plus_c.T @ forward.reshape(n, n_sym * k)).reshape(n_plus, k, n_sym * k) # [a, g, (x, v)] + products = { + "plus_c": plus_c, + "minus_c": minus_c, + "forward": forward, + # The three joints of constraint_informations, each indexed [a, b, c] for I[a : b | c]. + "screen": (self._pair_labels.T @ (self.p[:, None] * c)).reshape(n_plus, n_minus, k), + "future": (c.T @ (self._edges_rows @ minus_c).reshape(n, -1)).reshape(k * n_sym, n_minus, k), + "past": past.transpose(0, 2, 1), + } + self._cached = (c.shape, key, products) + return products def tensors(self, c: np.ndarray) -> tuple[np.ndarray, ...]: """``p(s+, s-, g)``, ``p(g_0, x_0, s-_1, g_1)`` and ``p(s+_0, g_0, x_0, g_1)``.""" - joint_g = self.p[:, None] * c - screen = np.einsum("pa,pb,pg->abg", self.plus, self.minus, joint_g) - forward = np.einsum("pxq,qv->pxv", self.edges, c) - future = np.einsum("pg,pxq,qs,qv->gxsv", c, self.edges, self.minus, c) - past = np.einsum("pa,pg,pxv->agxv", self.plus, c, forward) - return screen, future, past + products = self._products(c) + k = c.shape[1] + n_plus, n_minus, n_sym = products["screen"].shape[0], products["screen"].shape[1], self.edges.shape[1] + future = products["future"].reshape(k, n_sym, n_minus, k) + past = products["past"].transpose(0, 2, 1).reshape(n_plus, k, n_sym, k) + return products["screen"], future, past def constraint_informations(self, c: np.ndarray) -> np.ndarray: """``I[S+ : S- | G]``, ``I[G_0 X_0 : S-_1 | G_1]`` and ``I[S+_0 : X_0 G_1 | G_0]`` in bits.""" - screen, future, past = self.tensors(c) - return np.array( - [ - _conditional_mutual_information(screen), - _conditional_mutual_information(future.reshape(-1, *future.shape[2:])), - _conditional_mutual_information(np.moveaxis(past, 1, -1).reshape(past.shape[0], -1, past.shape[1])), - ] - ) + products = self._products(c) + return _conditional_mutual_informations((products["screen"], products["future"], products["past"])) def constraint_jacobian(self, c: np.ndarray) -> np.ndarray: """Gradients of :meth:`constraint_informations` in ``c``, shape ``(3, *c.shape)``.""" - screen, future, past = self.tensors(c) + products = self._products(c) + screen = products["screen"] + n, k = c.shape + n_plus, n_minus, n_sym = screen.shape[0], screen.shape[1], self.edges.shape[1] g_screen = _cmi_gradient(screen) - g_future = _cmi_gradient(future.reshape(-1, *future.shape[2:])).reshape(future.shape) - moved = np.moveaxis(past, 1, -1) - g_past = np.moveaxis(_cmi_gradient(moved.reshape(past.shape[0], -1, past.shape[1])).reshape(moved.shape), -1, 1) - jac = np.empty((3, *c.shape)) - jac[0] = self.p[:, None] * np.einsum("pa,pb,abg->pg", self.plus, self.minus, g_screen) - jac[1] = np.einsum("gxsv,pxq,qs,qv->pg", g_future, self.edges, self.minus, c) + np.einsum( - "gxsv,pg,pxq,qs->qv", g_future, c, self.edges, self.minus - ) - jac[2] = np.einsum("agxv,pa,pxq,qv->pg", g_past, self.plus, self.edges, c) + np.einsum( - "agxv,pa,pg,pxq->qv", g_past, self.plus, c, self.edges - ) + g_future = _cmi_gradient(products["future"]).reshape(k * n_sym, n_minus * k) # [(g, x), (s, v)] + g_past = _cmi_gradient(products["past"]).transpose(0, 2, 1).reshape(n_plus * k, n_sym * k) # [(a, g), (x, v)] + jac = np.empty((3, n, k)) + jac[0] = self.p[:, None] * (self._pair_labels @ g_screen.reshape(-1, k)) + # d/dc[p, g] through the c_0 factor of the future, then d/dc[q, v] through the c_1 factor. + through_target = (g_future @ products["minus_c"].T).reshape(k, n_sym * n) # [g, (x, q)] + through_source = ((c.T @ self._edges_cols).reshape(k * n_sym, n).T @ g_future).reshape(n, n_minus, k) + jac[1] = self._edges_cols @ through_target.T + np.einsum("qs,qsv->qv", self.minus, through_source) + # Likewise for the past, whose c_1 factor sits inside the forward map. + through_forward = (products["forward"].reshape(n, n_sym * k) @ g_past.T).reshape(n, n_plus, k) + through_plus = (products["plus_c"] @ g_past).reshape(n * n_sym, k) + jac[2] = np.einsum("pa,pag->pg", self.plus, through_forward) + self._edges_rows.T @ through_plus return jac def markov_residual(self, c: np.ndarray) -> float: @@ -189,19 +221,18 @@ def seeds(self, k: int) -> list[np.ndarray]: def _entropy_bits(p: np.ndarray) -> float: - p = p[p > 0.0] - return float(-(p * np.log2(p)).sum()) - - -def _conditional_mutual_information(joint: np.ndarray) -> float: - """``I[a : b | c]`` in bits for a joint indexed ``[a, b, c]``.""" - return max( - 0.0, - _entropy_bits(joint.sum(axis=1)) - + _entropy_bits(joint.sum(axis=0)) - - _entropy_bits(joint) - - _entropy_bits(joint.sum(axis=(0, 1))), - ) + return float(entr(np.maximum(p, 0.0)).sum()) / _LN2 + + +def _conditional_mutual_informations(joints: Sequence[np.ndarray]) -> np.ndarray: + """``I[a : b | c]`` in bits for each joint indexed ``[a, b, c]``, from one pass over all the entropies.""" + parts = [] + for joint in joints: + ac = joint.sum(axis=1) + parts += [ac.ravel(), joint.sum(axis=0).ravel(), joint.ravel(), ac.sum(axis=0)] + starts = np.cumsum([0] + [part.size for part in parts[:-1]]) + entropies = np.add.reduceat(entr(np.maximum(np.concatenate(parts), 0.0)), starts).reshape(-1, 4) + return np.maximum(entropies @ _CMI_SIGNS / _LN2, 0.0) def _cmi_gradient(joint: np.ndarray) -> np.ndarray: @@ -210,12 +241,8 @@ def _cmi_gradient(joint: np.ndarray) -> np.ndarray: def log(x: np.ndarray) -> np.ndarray: return np.log2(np.maximum(x, 1e-300)) - return ( - log(joint) - + log(joint.sum(axis=(0, 1)))[None, None, :] - - log(joint.sum(axis=1))[:, None, :] - - log(joint.sum(axis=0))[None, :, :] - ) + ac = joint.sum(axis=1) + return log(joint) + log(ac.sum(axis=0))[None, None, :] - log(ac)[:, None, :] - log(joint.sum(axis=0))[None, :, :] def _unconstrained_channel( diff --git a/tests/oracles.py b/tests/oracles.py index 2f3bcf5..144cb5f 100644 --- a/tests/oracles.py +++ b/tests/oracles.py @@ -394,3 +394,68 @@ def compose_relations( """Relational composition ``{x: {z : y in first[x], z in second(y)}}``.""" apply = second if callable(second) else (lambda y: second.get(y, set())) return {x: {z for y in ys for z in apply(y)} for x, ys in first.items()} + + +# --------------------------------------------------------------------------- lifted common information + + +def _cmi_bits(joint: np.ndarray) -> float: + """``I[a : b | c]`` in bits for a joint indexed ``[a, b, c]``, from the four entropies.""" + + def h(p: np.ndarray) -> float: + p = p[p > 0.0] + return float(-(p * np.log2(p)).sum()) + + return max(0.0, h(joint.sum(axis=1)) + h(joint.sum(axis=0)) - h(joint) - h(joint.sum(axis=(0, 1)))) + + +def _cmi_gradient_bits(joint: np.ndarray) -> np.ndarray: + def log(x: np.ndarray) -> np.ndarray: + return np.log2(np.maximum(x, 1e-300)) + + return ( + log(joint) + + log(joint.sum(axis=(0, 1)))[None, None, :] + - log(joint.sum(axis=1))[:, None, :] + - log(joint.sum(axis=0))[None, :, :] + ) + + +def lifted_tensors(problem: Any, c: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """``p(s+, s-, g)``, ``p(g_0, x_0, s-_1, g_1)`` and ``p(s+_0, g_0, x_0, g_1)`` by direct ``einsum``.""" + plus, minus, edges = problem.plus, problem.minus, problem.edges + screen = np.einsum("pa,pb,pg->abg", plus, minus, problem.p[:, None] * c) + future = np.einsum("pg,pxq,qs,qv->gxsv", c, edges, minus, c) + past = np.einsum("pa,pg,pxq,qv->agxv", plus, c, edges, c) + return screen, future, past + + +def lifted_constraint_informations(problem: Any, c: np.ndarray) -> np.ndarray: + screen, future, past = lifted_tensors(problem, c) + return np.array( + [ + _cmi_bits(screen), + _cmi_bits(future.reshape(-1, *future.shape[2:])), + _cmi_bits(np.moveaxis(past, 1, -1).reshape(past.shape[0], -1, past.shape[1])), + ] + ) + + +def lifted_constraint_jacobian(problem: Any, c: np.ndarray) -> np.ndarray: + plus, minus, edges = problem.plus, problem.minus, problem.edges + screen, future, past = lifted_tensors(problem, c) + g_screen = _cmi_gradient_bits(screen) + g_future = _cmi_gradient_bits(future.reshape(-1, *future.shape[2:])).reshape(future.shape) + moved = np.moveaxis(past, 1, -1) + g_past = np.moveaxis( + _cmi_gradient_bits(moved.reshape(past.shape[0], -1, past.shape[1])).reshape(moved.shape), -1, 1 + ) + jac = np.empty((3, *c.shape)) + jac[0] = problem.p[:, None] * np.einsum("pa,pb,abg->pg", plus, minus, g_screen) + jac[1] = np.einsum("gxsv,pxq,qs,qv->pg", g_future, edges, minus, c) + np.einsum( + "gxsv,pg,pxq,qs->qv", g_future, c, edges, minus + ) + jac[2] = np.einsum("agxv,pa,pxq,qv->pg", g_past, plus, edges, c) + np.einsum( + "agxv,pa,pg,pxq->qv", g_past, plus, c, edges + ) + return jac diff --git a/tests/test_lifted_common_information.py b/tests/test_lifted_common_information.py index f902b2a..ff62818 100644 --- a/tests/test_lifted_common_information.py +++ b/tests/test_lifted_common_information.py @@ -195,3 +195,30 @@ def test_binary_markov_lifted_wyner_bounds(p: float, q: float) -> None: assert excess - 1e-6 <= wyner.wyner_common_information <= float(process.statistical_complexity()) + 1e-6 assert wyner.markov_residual <= 1e-7 assert _reproduces(wyner, bidir) + + +@settings(max_examples=25, deadline=None) +@given(st.sampled_from(["golden", "odd", "rll"]), st.integers(1, 6), st.integers(0, 2**32 - 1)) +def test_lifted_tensors_and_jacobian_match_the_einsum_reference(name: str, k: int, seed: int) -> None: + from tests import oracles + + bidir = { + "golden": lambda: golden_mean_bidirectional(0.4), + "odd": lambda: BidirectionalEpsilonMachine.from_forward(odd()), + "rll": _rll_two_infinity, + }[name]() + problem = _LiftedProblem(bidir, _normalized_joint_distribution(bidir, cutoff=0.0)) + rng = np.random.default_rng(seed) + c = rng.dirichlet(np.ones(k), size=len(problem.pairs)) + c[rng.random(c.shape) < 0.2] = 0.0 + for got, expected in zip(problem.tensors(c), oracles.lifted_tensors(problem, c), strict=True): + np.testing.assert_allclose(got, expected, rtol=1e-12, atol=1e-15) + np.testing.assert_allclose( + problem.constraint_informations(c), oracles.lifted_constraint_informations(problem, c), atol=1e-12 + ) + np.testing.assert_allclose( + problem.constraint_jacobian(c), oracles.lifted_constraint_jacobian(problem, c), rtol=1e-10, atol=1e-9 + ) + # A second channel must not be served from the cache of the first. + other = rng.dirichlet(np.ones(k), size=len(problem.pairs)) + np.testing.assert_allclose(problem.tensors(other)[1], oracles.lifted_tensors(problem, other)[1], rtol=1e-12) From 30c2b1893c7174e18c04d94a326e694474f1be36 Mon Sep 17 00:00:00 2001 From: Ryan James Date: Sun, 15 Nov 2026 22:37:44 -0700 Subject: [PATCH 3/7] Vectorize the numeric belief lookup in mixed-state enumeration Co-authored-by: Cursor --- sofic/generators/mixed_state_construction.py | 51 ++++++++++++++------ sofic/generators/prob.py | 9 +++- tests/test_mixed_state_construction.py | 25 ++++++++++ 3 files changed, 68 insertions(+), 17 deletions(-) diff --git a/sofic/generators/mixed_state_construction.py b/sofic/generators/mixed_state_construction.py index bcbd327..a5b2d81 100644 --- a/sofic/generators/mixed_state_construction.py +++ b/sofic/generators/mixed_state_construction.py @@ -19,6 +19,8 @@ is_pure_mixed_state, ) from sofic.generators.prob import ( + PROBS_EQUAL_ATOL, + PROBS_EQUAL_RTOL, as_prob, is_positive_mass, is_symbolic, @@ -29,7 +31,7 @@ from sofic.graph import ATTR_EMISSION, ATTR_PROB, TransitionGraph # Covers the numeric tolerance of :func:`~sofic.generators.prob.probs_equal` -# (``atol=1e-12``, ``rtol=1e-9``) on the leading belief coordinate. +# (``PROBS_EQUAL_ATOL``, ``PROBS_EQUAL_RTOL``) on the projected belief key. _NUMERIC_WINDOW = 1e-9 @@ -95,49 +97,68 @@ def build_mixed_state_presentation( discovered: dict[MixedState, MixedState] = {} unique: list[MixedState] = [] symbolic_unique: list[MixedState] = [] + # Numeric beliefs sorted by key, with their rows in numeric_beliefs (in discovery order). numeric_keys: list[float] = [] numeric_unique: list[MixedState] = [] + numeric_rows: list[int] = [] + numeric_beliefs = np.empty((16, len(basis))) # Index numeric beliefs by a projection onto fixed positive weights summing to one. Beliefs equal # coordinatewise to within _NUMERIC_WINDOW project to within it too, and unlike a single # coordinate the projection rarely ties, so a lookup scans few candidates. weights = np.array([0.5 + (index * 0.6180339887498949) % 1.0 for index in range(len(basis))]) weights = weights / weights.sum() - def key(state: MixedState) -> float: - return float(np.dot(weights, np.asarray(state.belief, dtype=float))) - queue: deque[MixedState] = deque() - def candidates(state: MixedState) -> Sequence[MixedState]: - if any(is_symbolic(b) for b in state.belief): - return unique - lead = key(state) + def find_numeric(vector: np.ndarray, lead: float) -> MixedState | None: + """The first known numeric belief in key order equal to ``vector`` under :func:`probs_equal`.""" window = _NUMERIC_WINDOW * (1.0 + abs(lead)) low = bisect.bisect_left(numeric_keys, lead - window) high = bisect.bisect_right(numeric_keys, lead + window) - return [*numeric_unique[low:high], *symbolic_unique] + if low == high: + return None + rows = numeric_beliefs[numeric_rows[low:high]] + close = np.abs(rows - vector) <= PROBS_EQUAL_ATOL + PROBS_EQUAL_RTOL * np.abs(vector) + hits = np.flatnonzero(close.all(axis=1)) + return numeric_unique[low + int(hits[0])] if hits.size else None def register(state: MixedState) -> MixedState: + nonlocal numeric_beliefs existing = discovered.get(state) if existing is not None: return existing - for known in candidates(state): - if _beliefs_equal(known, state, constraints=constraints): - discovered[state] = known - return known + symbolic = any(is_symbolic(b) for b in state.belief) + if symbolic: + match = next((known for known in unique if _beliefs_equal(known, state, constraints=constraints)), None) + else: + vector = np.asarray(state.belief, dtype=float) + lead = float(weights @ vector) + match = find_numeric(vector, lead) + if match is None: + match = next( + (known for known in symbolic_unique if _beliefs_equal(known, state, constraints=constraints)), + None, + ) + if match is not None: + discovered[state] = match + return match if len(unique) >= max_states: raise MixedStateExplosionError( f"mixed-state presentation exceeded max_states={max_states}; the reachable belief set may be infinite" ) discovered[state] = state unique.append(state) - if any(is_symbolic(b) for b in state.belief): + if symbolic: symbolic_unique.append(state) else: - lead = key(state) + row = len(numeric_unique) + if row == len(numeric_beliefs): + numeric_beliefs = np.concatenate([numeric_beliefs, np.empty_like(numeric_beliefs)]) + numeric_beliefs[row] = vector position = bisect.bisect_right(numeric_keys, lead) numeric_keys.insert(position, lead) numeric_unique.insert(position, state) + numeric_rows.insert(position, row) graph.add_state(state) queue.append(state) return state diff --git a/sofic/generators/prob.py b/sofic/generators/prob.py index d3dbe72..e1ea4e5 100644 --- a/sofic/generators/prob.py +++ b/sofic/generators/prob.py @@ -96,12 +96,17 @@ def is_positive_mass(value: Prob, *, atol: float = 1e-15) -> bool: return float(value) > atol +#: Default tolerances of :func:`probs_equal` for numeric probabilities. +PROBS_EQUAL_RTOL = 1e-9 +PROBS_EQUAL_ATOL = 1e-12 + + def probs_equal( left: Prob, right: Prob, *, - rtol: float = 1e-9, - atol: float = 1e-12, + rtol: float = PROBS_EQUAL_RTOL, + atol: float = PROBS_EQUAL_ATOL, constraints: SymbolConstraints | None = None, ) -> bool: """Equality for probability scalars (exact sympy simplify, else numeric close). diff --git a/tests/test_mixed_state_construction.py b/tests/test_mixed_state_construction.py index e2e567b..46f58b8 100644 --- a/tests/test_mixed_state_construction.py +++ b/tests/test_mixed_state_construction.py @@ -5,11 +5,13 @@ import time import pytest +from hypothesis import given, settings from sofic.examples import golden_mean, sns from sofic.exceptions import MixedStateExplosionError from sofic.generators.epsilon_machine import EpsilonMachine from sofic.generators.mixed_state_construction import build_mixed_state_presentation +from sofic.testing.strategies import mealy_hmms def test_infinite_belief_set_hits_max_states_promptly(): @@ -52,3 +54,26 @@ def test_infinite_reverse_presentation_reaches_its_cap_quickly() -> None: with pytest.raises(MixedStateExplosionError): infer_reverse_epsilon_machine(forward, max_states=5_000) assert time.monotonic() - start < 60 + + +@settings(max_examples=40, deadline=None) +@given(mealy_hmms(max_states=3)) +def test_mixed_states_are_distinct_and_closed_under_bayes_updates(hmm) -> None: + import itertools + + import numpy as np + + from sofic.generators.prob import probs_equal + + try: + msp = build_mixed_state_presentation(hmm, max_states=60) + except MixedStateExplosionError: + return + states = list(msp.states()) + for left, right in itertools.combinations(states, 2): + assert not all(probs_equal(a, b) for a, b in zip(left.belief, right.belief, strict=True)) + registered = set(states) + for transition in msp.transitions(): + assert transition.target in registered + vectors = np.array([np.asarray(state.belief, dtype=float) for state in states]) + np.testing.assert_allclose(vectors.sum(axis=1), 1.0) From f7f8b968415cce5ee773c20334216a59ba2b23cd Mon Sep 17 00:00:00 2001 From: Ryan James Date: Sun, 15 Nov 2026 22:45:25 -0700 Subject: [PATCH 4/7] Speed up certified coverage bounds: exact fsum box tightening, single-pass tree splits in mu1_vertex, closed-form 3x3 vertex solves Co-authored-by: Cursor --- sofic/generators/coverage_bound.py | 83 +++++++++++++++----- sofic/generators/generator_caps.py | 34 +++++---- tests/oracles.py | 117 +++++++++++++++++++++++++++++ tests/test_generator_caps.py | 19 +++++ tests/test_mu_k_certified.py | 30 ++++++++ 5 files changed, 249 insertions(+), 34 deletions(-) diff --git a/sofic/generators/coverage_bound.py b/sofic/generators/coverage_bound.py index 3130600..e185421 100644 --- a/sofic/generators/coverage_bound.py +++ b/sofic/generators/coverage_bound.py @@ -158,6 +158,35 @@ def mu_k_spectral_cap(M: np.ndarray, k: int) -> float: return float(M.sum()) - max(0.0, tail - slack) +def _cross(a: np.ndarray, b: np.ndarray) -> np.ndarray: + return np.stack( + [ + a[..., 1] * b[..., 2] - a[..., 2] * b[..., 1], + a[..., 2] * b[..., 0] - a[..., 0] * b[..., 2], + a[..., 0] * b[..., 1] - a[..., 1] * b[..., 0], + ], + axis=-1, + ) + + +def _solve_square_systems(G: np.ndarray, h: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Solutions of ``G x = h`` over the leading axes, and which systems are regular (``|det G| > 1e-14``). + + The solutions of singular systems are arbitrary finite values. Systems of size three, the common case, + are solved by Cramer's rule, which beats a LAPACK call per tiny matrix. + """ + m = G.shape[-1] + if m != 3: + regular = np.abs(np.linalg.det(G)) > 1e-14 + return np.linalg.solve(np.where(regular[..., None, None], G, np.eye(m)), h[..., None])[..., 0], regular + r0, r1, r2 = G[..., 0, :], G[..., 1, :], G[..., 2, :] + c0, c1, c2 = _cross(r1, r2), _cross(r2, r0), _cross(r0, r1) + det = (r0 * c0).sum(axis=-1) + regular = np.abs(det) > 1e-14 + x = (h[..., 0, None] * c0 + h[..., 1, None] * c1 + h[..., 2, None] * c2) / np.where(regular, det, 1.0)[..., None] + return x, regular + + def _column_box_lp(U: np.ndarray, A: np.ndarray, C: np.ndarray) -> np.ndarray: """``max 1.x`` over ``0 <= x <= U[b]``, ``A[p].x <= 0``, ``C[p].x >= 0`` for every column ``b`` and pair ``p``. @@ -174,9 +203,7 @@ def _column_box_lp(U: np.ndarray, A: np.ndarray, C: np.ndarray) -> np.ndarray: G[:, :, 2 * m] = A[None] G[:, :, 2 * m + 1] = -C[None] combos = np.array(list(combinations(range(2 * m + 2), m))) - Gs, hs = G[:, :, combos], h[:, :, combos] - regular = np.abs(np.linalg.det(Gs)) > 1e-14 - x = np.linalg.solve(np.where(regular[..., None, None], Gs, np.eye(m)), hs[..., None])[..., 0] + x, regular = _solve_square_systems(G[:, :, combos], h[:, :, combos]) slack = np.einsum("bpkm,bpcm->bpck", G, x) - h[:, :, None, :] feasible = regular & (slack.max(axis=-1) <= 1e-12 * (1.0 + float(U.max()))) return np.where(feasible, x.sum(axis=-1), -np.inf).max(axis=-1) @@ -291,24 +318,41 @@ def _logsumexp(x: np.ndarray) -> float: _VERTEX_PERTURBATION = 1e-7 -def _tree_potentials(tree: frozenset, L: np.ndarray) -> tuple[np.ndarray, np.ndarray]: - """Solve ``p_a + q_b = L_ab`` on the edges of a spanning tree of ``K_{na,nb}`` with ``p_0 = 0``.""" +def _tree_walk(tree: frozenset, L: np.ndarray) -> tuple[np.ndarray, np.ndarray, list[tuple[int, int]], list[int]]: + """Solve ``p_a + q_b = L_ab`` on the edges of a spanning tree of ``K_{na,nb}`` with ``p_0 = 0``. + + Also returns the tree edges (in the tree's iteration order) and, for each edge ``(a, b)``, the bitmask + of the nodes (rows ``0..na-1``, then columns) left on row ``a``'s side when the edge is removed. + """ na, nb = L.shape adj: list[list[int]] = [[] for _ in range(na + nb)] for a, b in tree: adj[a].append(na + b) adj[na + b].append(a) - pot = np.full(na + nb, np.nan) - pot[0] = 0.0 + pot = [0.0] * (na + nb) + parent = [-1] * (na + nb) + parent[0] = 0 + order = [] stack = [0] while stack: x = stack.pop() + order.append(x) for y in adj[x]: - if np.isnan(pot[y]): + if parent[y] < 0: + parent[y] = x a, b = (x, y - na) if x < na else (y, x - na) pot[y] = L[a, b] - pot[x] stack.append(y) - return pot[:na], pot[na:] + subtree = [1 << x for x in range(na + nb)] + for x in reversed(order[1:]): + subtree[parent[x]] |= subtree[x] + full = (1 << (na + nb)) - 1 + edges, sides = [], [] + for a, b in tree: + below = subtree[na + b] if parent[na + b] == a else subtree[a] + edges.append((a, b)) + sides.append(below if below >> a & 1 else full ^ below) + return np.array(pot[:na]), np.array(pot[na:]), edges, sides def _initial_tree(L: np.ndarray) -> frozenset: @@ -369,23 +413,24 @@ def mu1_vertex(M: np.ndarray, *, max_vertices: int = 200_000) -> Mu1Result | Non seen = {start} queue = [start] best, best_pq = -np.inf, None + bits = 1 << np.arange(na + nb) while queue: tree = queue.pop() - p, q = _tree_potentials(tree, L) + p, q, edges, sides = _tree_walk(tree, L) value = _logsumexp(p) + _logsumexp(q) if value > best: best, best_pq = value, (p, q) slack = L - p[:, None] - q[None, :] - for edge in tree: - comp = _components(na, nb, tree - {edge}) - side = comp[edge[0]] - rows_out = np.array([comp[a] != side for a in range(na)]) - cols_in = np.array([comp[na + b] == side for b in range(nb)]) - if not rows_out.any() or not cols_in.any(): + # For each tree edge: rows off and columns on row a's side once it is removed, and the entering + # cell, the first slack minimum in row-major order over that rows x columns block. + on_side = (np.array(sides)[:, None] & bits) != 0 + rows_out, cols_in = ~on_side[:, :na], on_side[:, na:] + blocks = rows_out[:, :, None] & cols_in[:, None, :] + entering_cells = np.where(blocks, slack, np.inf).reshape(len(edges), -1).argmin(axis=1) + for edge, has_block, cell in zip(edges, blocks.any(axis=(1, 2)), entering_cells.tolist(), strict=True): + if not has_block: continue - sub = slack[np.ix_(rows_out, cols_in)] - i, j = np.unravel_index(int(np.argmin(sub)), sub.shape) - entering = (int(np.flatnonzero(rows_out)[i]), int(np.flatnonzero(cols_in)[j])) + entering = divmod(cell, nb) nxt = (tree - {edge}) | {entering} if nxt not in seen: if len(seen) >= max_vertices: diff --git a/sofic/generators/generator_caps.py b/sofic/generators/generator_caps.py index 287a665..518357f 100644 --- a/sofic/generators/generator_caps.py +++ b/sofic/generators/generator_caps.py @@ -242,14 +242,18 @@ def _sparse(rows: list[list[tuple[int, float]]], n: int) -> sp.csr_matrix: return sp.csr_matrix((d, (r, c)), shape=(len(rows), n)) -def _outward(value: Fraction, down: bool) -> float: - """``value`` rounded to a float in the given direction.""" - f = float(value) - if down and Fraction(f) > value: - return math.nextafter(f, -math.inf) - if not down and Fraction(f) < value: - return math.nextafter(f, math.inf) - return f +def _outward_sum(terms: list[float], *, up: bool) -> float: + """The exact sum of ``terms`` rounded up (or down) to a float. + + ``math.fsum`` rounds the exact sum to nearest, and the sign of the correctly rounded residual is exact. + """ + total = math.fsum(terms) + residual = math.fsum([*terms, -total]) + if up and residual > 0.0: + return math.nextafter(total, math.inf) + if not up and residual < 0.0: + return math.nextafter(total, -math.inf) + return total def _tighten(lo: np.ndarray, hi: np.ndarray) -> tuple[np.ndarray, np.ndarray] | None: @@ -257,14 +261,14 @@ def _tighten(lo: np.ndarray, hi: np.ndarray) -> tuple[np.ndarray, np.ndarray] | The new bounds are computed exactly and rounded outward, so no point of the simplex in the box is lost. """ + lows, highs = [float(v) for v in lo], [float(v) for v in hi] for _ in range(3): - exact_lo = [Fraction(float(v)) for v in lo] - sum_lo = sum(exact_lo, Fraction(0)) - hi = np.minimum(hi, [_outward(1 - (sum_lo - v), down=False) for v in exact_lo]) - exact_hi = [Fraction(float(v)) for v in hi] - sum_hi = sum(exact_hi, Fraction(0)) - lo = np.maximum(lo, [_outward(1 - (sum_hi - v), down=True) for v in exact_hi]) - return (lo, hi) if np.all(lo <= hi) else None + neg = [-v for v in lows] + highs = [min(h, _outward_sum([1.0, *neg[:i], *neg[i + 1 :]], up=True)) for i, h in enumerate(highs)] + neg = [-v for v in highs] + lows = [max(v, _outward_sum([1.0, *neg[:i], *neg[i + 1 :]], up=False)) for i, v in enumerate(lows)] + lo_out, hi_out = np.array(lows), np.array(highs) + return (lo_out, hi_out) if np.all(lo_out <= hi_out) else None def _branch_and_bound( diff --git a/tests/oracles.py b/tests/oracles.py index 144cb5f..28b0550 100644 --- a/tests/oracles.py +++ b/tests/oracles.py @@ -459,3 +459,120 @@ def lifted_constraint_jacobian(problem: Any, c: np.ndarray) -> np.ndarray: "agxv,pa,pg,pxq->qv", g_past, plus, c, edges ) return jac + + +# --------------------------------------------------------------------------- simplex boxes + + +def _outward(value: Any, down: bool) -> float: + """``value`` (a :class:`~fractions.Fraction`) rounded to a float in the given direction.""" + from fractions import Fraction + + f = float(value) + if down and Fraction(f) > value: + return math.nextafter(f, -math.inf) + if not down and Fraction(f) < value: + return math.nextafter(f, math.inf) + return f + + +def tighten_exact(lo: np.ndarray, hi: np.ndarray) -> tuple[np.ndarray, np.ndarray] | None: + """A box shrunk to its intersection with the probability simplex in exact rational arithmetic.""" + from fractions import Fraction + + for _ in range(3): + exact_lo = [Fraction(float(v)) for v in lo] + sum_lo = sum(exact_lo, Fraction(0)) + hi = np.minimum(hi, [_outward(1 - (sum_lo - v), down=False) for v in exact_lo]) + exact_hi = [Fraction(float(v)) for v in hi] + sum_hi = sum(exact_hi, Fraction(0)) + lo = np.maximum(lo, [_outward(1 - (sum_hi - v), down=True) for v in exact_hi]) + return (lo, hi) if np.all(lo <= hi) else None + + +# --------------------------------------------------------------------------- rank-1 coverage (mu_1) + + +def _tree_potentials(tree: frozenset, L: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + na, nb = L.shape + adj: list[list[int]] = [[] for _ in range(na + nb)] + for a, b in tree: + adj[a].append(na + b) + adj[na + b].append(a) + pot = np.full(na + nb, np.nan) + pot[0] = 0.0 + stack = [0] + while stack: + x = stack.pop() + for y in adj[x]: + if np.isnan(pot[y]): + a, b = (x, y - na) if x < na else (y, x - na) + pot[y] = L[a, b] - pot[x] + stack.append(y) + return pot[:na], pot[na:] + + +def mu1_vertex_reference(M: np.ndarray) -> tuple[float, np.ndarray, np.ndarray]: + """``mu_1`` by vertex enumeration, splitting each tree with a fresh union-find per removed edge.""" + from sofic.generators.coverage_bound import ( + _LOG_FLOOR, + _VERTEX_PERTURBATION, + _components, + _initial_tree, + _logsumexp, + ) + + M = np.asarray(M, dtype=float) + na, nb = M.shape + L = np.maximum(np.log(np.maximum(M, 1e-300)), _LOG_FLOOR) + L = L + _VERTEX_PERTURBATION * np.random.default_rng(0).random((na, nb)) + start = _initial_tree(L) + seen = {start} + queue = [start] + best, best_pq = -np.inf, None + while queue: + tree = queue.pop() + p, q = _tree_potentials(tree, L) + value = _logsumexp(p) + _logsumexp(q) + if value > best: + best, best_pq = value, (p, q) + slack = L - p[:, None] - q[None, :] + for edge in tree: + comp = _components(na, nb, tree - {edge}) + side = comp[edge[0]] + rows_out = np.array([comp[a] != side for a in range(na)]) + cols_in = np.array([comp[na + b] == side for b in range(nb)]) + if not rows_out.any() or not cols_in.any(): + continue + sub = slack[np.ix_(rows_out, cols_in)] + i, j = np.unravel_index(int(np.argmin(sub)), sub.shape) + entering = (int(np.flatnonzero(rows_out)[i]), int(np.flatnonzero(cols_in)[j])) + nxt = (tree - {edge}) | {entering} + if nxt not in seen: + seen.add(nxt) + queue.append(nxt) + p, q = best_pq + value = min(float(M.sum()), float(np.exp(best))) + return value, np.exp(p - _logsumexp(p)), np.exp(q - _logsumexp(q)) + + +def column_box_lp_reference(U: np.ndarray, A: np.ndarray, C: np.ndarray) -> np.ndarray: + """``max 1.x`` over ``0 <= x <= U[b]``, ``A[p].x <= 0``, ``C[p].x >= 0`` by LAPACK vertex enumeration.""" + from itertools import combinations + + nb, m = U.shape + npairs = A.shape[0] + G = np.zeros((nb, npairs, 2 * m + 2, m)) + h = np.zeros((nb, npairs, 2 * m + 2)) + G[:, :, :m] = -np.eye(m) + G[:, :, m : 2 * m] = np.eye(m) + h[:, :, m : 2 * m] = U[:, None, :] + G[:, :, 2 * m] = A[None] + G[:, :, 2 * m + 1] = -C[None] + combos = np.array(list(combinations(range(2 * m + 2), m))) + Gs, hs = G[:, :, combos], h[:, :, combos] + regular = np.abs(np.linalg.det(Gs)) > 1e-14 + x = np.linalg.solve(np.where(regular[..., None, None], Gs, np.eye(m)), hs[..., None])[..., 0] + slack = np.einsum("bpkm,bpcm->bpck", G, x) - h[:, :, None, :] + feasible = regular & (slack.max(axis=-1) <= 1e-12 * (1.0 + float(U.max()))) + return np.where(feasible, x.sum(axis=-1), -np.inf).max(axis=-1) diff --git a/tests/test_generator_caps.py b/tests/test_generator_caps.py index 031b98a..00b8316 100644 --- a/tests/test_generator_caps.py +++ b/tests/test_generator_caps.py @@ -7,6 +7,8 @@ import numpy as np import pytest +from hypothesis import given, settings +from hypothesis import strategies as st from sofic.examples.epsilon_machines import from_symbol_matrices, golden_mean_bidirectional from sofic.generators import coupled_generators as cg @@ -145,3 +147,20 @@ def fake(*args, options=None, **kwargs): root = relaxation.bound(gc._root(relaxation)) assert not infeasible assert max(b for b, _, _ in leaves) == pytest.approx(root) + + +@settings(max_examples=300, deadline=None) +@given(st.integers(1, 6).flatmap(lambda n: st.tuples(*[st.tuples(st.floats(0, 1), st.floats(0, 1))] * n))) +def test_tighten_matches_exact_rational_arithmetic(bounds): + from sofic.generators.generator_caps import _tighten + from tests.oracles import tighten_exact + + lo = np.array([min(a, b) for a, b in bounds]) + hi = np.array([max(a, b) for a, b in bounds]) + exact = tighten_exact(lo.copy(), hi.copy()) + fast = _tighten(lo.copy(), hi.copy()) + if exact is None: + assert fast is None + else: + np.testing.assert_array_equal(fast[0], exact[0]) + np.testing.assert_array_equal(fast[1], exact[1]) diff --git a/tests/test_mu_k_certified.py b/tests/test_mu_k_certified.py index 8556a32..a9988df 100644 --- a/tests/test_mu_k_certified.py +++ b/tests/test_mu_k_certified.py @@ -116,3 +116,33 @@ def test_coverage_exact_on_block_diagonal_support() -> None: cov = coverage_bound(m) assert cov.certified assert cov.value == pytest.approx(_h(0.4, 0.6), abs=1e-6) + + +@settings(max_examples=60, deadline=None) +@given(st.integers(1, 4), st.integers(1, 4), st.integers(0, 2**32 - 1), st.floats(0.0, 0.6)) +def test_mu1_vertex_matches_the_union_find_reference(na: int, nb: int, seed: int, sparsity: float) -> None: + from sofic.generators.coverage_bound import mu1_vertex + from tests.oracles import mu1_vertex_reference + + rng = np.random.default_rng(seed) + M = rng.random((na, nb)) * (rng.random((na, nb)) >= sparsity) + if M.sum() == 0.0: + M[0, 0] = 1.0 + M /= M.sum() + got = mu1_vertex(M) + value, u, v = mu1_vertex_reference(M) + assert got.value == value + np.testing.assert_array_equal(got.u, u) + np.testing.assert_array_equal(got.v, v) + + +@settings(max_examples=60, deadline=None) +@given(st.integers(2, 4), st.integers(1, 4), st.integers(1, 5), st.integers(0, 2**32 - 1)) +def test_column_box_lp_matches_the_lapack_reference(m: int, nb: int, npairs: int, seed: int) -> None: + from sofic.generators.coverage_bound import _column_box_lp + from tests.oracles import column_box_lp_reference + + rng = np.random.default_rng(seed) + U = rng.random((nb, m)) + A, C = rng.normal(size=(npairs, m)), rng.normal(size=(npairs, m)) + np.testing.assert_allclose(_column_box_lp(U, A, C), column_box_lp_reference(U, A, C), rtol=1e-9, atol=1e-12) From 7b3cc0ea572ab64f0b9bcf11c2806e68abfd3559 Mon Sep 17 00:00:00 2001 From: Ryan James Date: Sun, 15 Nov 2026 22:58:50 -0700 Subject: [PATCH 5/7] Schedule xdist with worksteal; tidy type narrowing in new tests Co-authored-by: Cursor --- pyproject.toml | 3 +- sofic/generators/mixed_state_construction.py | 45 +++++++++++--------- tests/test_bayesian_inference.py | 2 +- tests/test_bidirectional_construction.py | 1 + tests/test_generator_caps.py | 1 + uv.lock | 4 +- 6 files changed, 32 insertions(+), 24 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index e14ea09..8fda9fe 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -48,7 +48,7 @@ test = [ "pytest-cov", "pytest-rerunfailures", "pytest-sugar", - "pytest-xdist", + "pytest-xdist>=3.2", ] docs = [ "sphinx", @@ -111,6 +111,7 @@ addopts = [ "--cov=sofic", "--cov-report=term-missing", "--numprocesses=auto", + "--dist=worksteal", "--durations=25", "--durations-min=1.0", "--reruns=1", diff --git a/sofic/generators/mixed_state_construction.py b/sofic/generators/mixed_state_construction.py index a5b2d81..197e3aa 100644 --- a/sofic/generators/mixed_state_construction.py +++ b/sofic/generators/mixed_state_construction.py @@ -122,35 +122,19 @@ def find_numeric(vector: np.ndarray, lead: float) -> MixedState | None: hits = np.flatnonzero(close.all(axis=1)) return numeric_unique[low + int(hits[0])] if hits.size else None - def register(state: MixedState) -> MixedState: + def add(state: MixedState, numeric: tuple[np.ndarray, float] | None) -> MixedState: + """Record a new belief; ``numeric`` is its vector and key, or ``None`` for a symbolic belief.""" nonlocal numeric_beliefs - existing = discovered.get(state) - if existing is not None: - return existing - symbolic = any(is_symbolic(b) for b in state.belief) - if symbolic: - match = next((known for known in unique if _beliefs_equal(known, state, constraints=constraints)), None) - else: - vector = np.asarray(state.belief, dtype=float) - lead = float(weights @ vector) - match = find_numeric(vector, lead) - if match is None: - match = next( - (known for known in symbolic_unique if _beliefs_equal(known, state, constraints=constraints)), - None, - ) - if match is not None: - discovered[state] = match - return match if len(unique) >= max_states: raise MixedStateExplosionError( f"mixed-state presentation exceeded max_states={max_states}; the reachable belief set may be infinite" ) discovered[state] = state unique.append(state) - if symbolic: + if numeric is None: symbolic_unique.append(state) else: + vector, lead = numeric row = len(numeric_unique) if row == len(numeric_beliefs): numeric_beliefs = np.concatenate([numeric_beliefs, np.empty_like(numeric_beliefs)]) @@ -163,6 +147,27 @@ def register(state: MixedState) -> MixedState: queue.append(state) return state + def register(state: MixedState) -> MixedState: + existing = discovered.get(state) + if existing is not None: + return existing + numeric = None + if any(is_symbolic(b) for b in state.belief): + match = next((known for known in unique if _beliefs_equal(known, state, constraints=constraints)), None) + else: + vector = np.asarray(state.belief, dtype=float) + numeric = (vector, float(weights @ vector)) + match = find_numeric(*numeric) + if match is None: + match = next( + (known for known in symbolic_unique if _beliefs_equal(known, state, constraints=constraints)), + None, + ) + if match is None: + return add(state, numeric) + discovered[state] = match + return match + register(eta0) while queue: diff --git a/tests/test_bayesian_inference.py b/tests/test_bayesian_inference.py index 74243b1..469623c 100644 --- a/tests/test_bayesian_inference.py +++ b/tests/test_bayesian_inference.py @@ -135,7 +135,7 @@ def test_dirichlet_prior_random_rows_sum_to_root(): prior.create_random_prior(1, 6, rng=np.random.default_rng(0)) for context in "012": cells = [prior.get_alpha((context, symbol)) for symbol in "012"] - assert all(1 <= alpha < 6 for alpha in cells) + assert all(alpha is not None and 1 <= alpha < 6 for alpha in cells) assert prior.get_alpha((context, "*")) == sum(cells) diff --git a/tests/test_bidirectional_construction.py b/tests/test_bidirectional_construction.py index 79a80c5..54344a1 100644 --- a/tests/test_bidirectional_construction.py +++ b/tests/test_bidirectional_construction.py @@ -99,6 +99,7 @@ def test_joint_pi_on_pair_subset_with_symbolic_rows(): a, b = ("a", "x"), ("b", "x") graph = _graph([(a, a, "0", p), (a, b, "1", 1 - p), (b, a, "0", sp.Integer(1))]) joint = bc._joint_pi_on_pair_subset(graph, [a, b]) + assert joint is not None assert sp.simplify(joint[a] - 1 / (2 - p)) == 0 leaky = _graph([(a, a, "0", p), (b, a, "0", sp.Integer(1))]) assert bc._joint_pi_on_pair_subset(leaky, [a, b]) is None diff --git a/tests/test_generator_caps.py b/tests/test_generator_caps.py index 00b8316..f91bff3 100644 --- a/tests/test_generator_caps.py +++ b/tests/test_generator_caps.py @@ -162,5 +162,6 @@ def test_tighten_matches_exact_rational_arithmetic(bounds): if exact is None: assert fast is None else: + assert fast is not None np.testing.assert_array_equal(fast[0], exact[0]) np.testing.assert_array_equal(fast[1], exact[1]) diff --git a/uv.lock b/uv.lock index a3a718e..cb49f70 100644 --- a/uv.lock +++ b/uv.lock @@ -2581,8 +2581,8 @@ requires-dist = [ { name = "pytest-rerunfailures", marker = "extra == 'test'" }, { name = "pytest-sugar", marker = "extra == 'dev'" }, { name = "pytest-sugar", marker = "extra == 'test'" }, - { name = "pytest-xdist", marker = "extra == 'dev'" }, - { name = "pytest-xdist", marker = "extra == 'test'" }, + { name = "pytest-xdist", marker = "extra == 'dev'", specifier = ">=3.2" }, + { name = "pytest-xdist", marker = "extra == 'test'", specifier = ">=3.2" }, { name = "python-sat", marker = "extra == 'sat'", specifier = ">=1.8" }, { name = "pyyaml", specifier = ">=6.0" }, { name = "ruff", marker = "extra == 'dev'" }, From a504cb2e9d0b1d10538e2d0c291bf3a61cc7c482 Mon Sep 17 00:00:00 2001 From: Ryan James Date: Sun, 15 Nov 2026 23:33:53 -0700 Subject: [PATCH 6/7] Compute topological entropy per strongly connected component; pass rng= to dit 2.4 Co-authored-by: Cursor --- sofic/inference/cssr/process.py | 2 +- sofic/shifts/algorithms.py | 18 +++++++++++++++--- tests/test_channel_feedback.py | 8 ++++---- tests/test_shift_correctness.py | 21 +++++++++++++++++++++ 4 files changed, 41 insertions(+), 8 deletions(-) diff --git a/sofic/inference/cssr/process.py b/sofic/inference/cssr/process.py index 4048635..54fa464 100644 --- a/sofic/inference/cssr/process.py +++ b/sofic/inference/cssr/process.py @@ -356,7 +356,7 @@ def suggest_max_history( data: Any = DitTrials(trials) else: data = trials[0] - order = select_markov_order(data, max_order, method=method, alpha=alpha, n_surrogates=n_surrogates, prng=seed) + order = select_markov_order(data, max_order, method=method, alpha=alpha, n_surrogates=n_surrogates, rng=seed) return max(1, int(order)) diff --git a/sofic/shifts/algorithms.py b/sofic/shifts/algorithms.py index 9875ec7..ac924a3 100644 --- a/sofic/shifts/algorithms.py +++ b/sofic/shifts/algorithms.py @@ -80,11 +80,23 @@ def adjacency_matrix(model: SymbolicModel, *, multiplicity: bool = True) -> tupl def topological_entropy_from_matrix(matrix: np.ndarray) -> float: - """Return ``log2`` of the spectral radius of ``matrix`` (bits per symbol).""" + """Return ``log2`` of the spectral radius of the nonnegative ``matrix`` (bits per symbol). + + The spectral radius is the largest over the strongly connected components, whose Perron roots are + simple eigenvalues. Over the whole matrix, components joined by transient edges can make the leading + eigenvalue defective, and ``eigvals`` then resolves it only to about ``eps ** (1 / multiplicity)``. + """ if matrix.size == 0: return 0.0 - eigenvalues = np.linalg.eigvals(matrix) - spectral_radius = float(np.max(np.abs(eigenvalues))) + from scipy.sparse.csgraph import connected_components + + n_components, labels = connected_components(np.asarray(matrix != 0, dtype=int), connection="strong") + spectral_radius = 0.0 + for component in range(n_components): + members = np.flatnonzero(labels == component) + block = np.asarray(matrix[np.ix_(members, members)], dtype=float) + if block.any(): + spectral_radius = max(spectral_radius, float(np.max(np.abs(np.linalg.eigvals(block))))) if spectral_radius <= 0.0: return 0.0 return float(np.log2(spectral_radius)) diff --git a/tests/test_channel_feedback.py b/tests/test_channel_feedback.py index 8993489..4a81a94 100644 --- a/tests/test_channel_feedback.py +++ b/tests/test_channel_feedback.py @@ -58,7 +58,7 @@ def test_one_state_channel_matches_bsc_under_feedback(): def test_horstein_exact_matches_montecarlo_on_trapdoor(): code = horstein(2, n=6) exact = code.probability_of_error(trapdoor(), method="exact") - sampled = code.probability_of_error(trapdoor(), method="montecarlo", samples=6000, prng=np.random.default_rng(0)) + sampled = code.probability_of_error(trapdoor(), method="montecarlo", samples=6000, rng=np.random.default_rng(0)) assert sampled == pytest.approx(exact, abs=0.015) @@ -70,11 +70,11 @@ def test_feedback_capacity_brackets_log2_phi(): def test_horstein_beats_the_no_feedback_capacity_of_the_trapdoor(): """Feedback lifts the trapdoor's rate above every no-feedback code, but not above log2(phi).""" code = horstein(8, delta=1e-3) - pe, uses = code.performance(trapdoor(), method="montecarlo", samples=400, prng=np.random.default_rng(1)) + pe, uses = code.performance(trapdoor(), method="montecarlo", samples=400, rng=np.random.default_rng(1)) rate = 8 / uses assert pe <= 0.01 assert NO_FEEDBACK_UPPER < rate < LOG2_PHI - lower, upper = code.capacity_gap(trapdoor(), method="montecarlo", samples=100, prng=np.random.default_rng(2)) + lower, upper = code.capacity_gap(trapdoor(), method="montecarlo", samples=100, rng=np.random.default_rng(2)) assert 0 < lower <= upper @@ -137,7 +137,7 @@ def test_trapdoor_decode_of_unused_word_and_short_state_is_all_zeros(): def test_trapdoor_code_approaches_the_feedback_capacity(): code = trapdoor_code(32) pe, uses = code.performance( - trapdoor(), method="montecarlo", samples=200, prng=np.random.default_rng(3), max_uses=300 + trapdoor(), method="montecarlo", samples=200, rng=np.random.default_rng(3), max_uses=300 ) assert pe == 0.0 assert NO_FEEDBACK_UPPER < 32 / uses < LOG2_PHI diff --git a/tests/test_shift_correctness.py b/tests/test_shift_correctness.py index de7c0f3..f7b5739 100644 --- a/tests/test_shift_correctness.py +++ b/tests/test_shift_correctness.py @@ -123,3 +123,24 @@ def test_copy_preserves_epsilon_sentinel(): shift.graph.add_transition("p", "q", **{ATTR_SYMBOL: EPSILON}) clone = shift.copy() assert next(iter(clone.transitions())).data[ATTR_SYMBOL] is EPSILON + + +def test_topological_entropy_is_exact_for_chained_cycles(): + """Three unit-radius cycles joined by transient edges make eigenvalue one defective over the whole matrix.""" + from sofic.shifts.algorithms import topological_entropy_from_matrix + + chained = np.array( + [ + [0, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 0, 0], + [0, 1, 0, 0, 0, 0], + [1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 1, 0], + [0, 0, 1, 0, 0, 1], + ], + dtype=float, + ) + assert topological_entropy_from_matrix(chained) == pytest.approx(0.0, abs=1e-12) + golden = np.array([[1, 1, 0], [1, 0, 0], [1, 0, 0]], dtype=float) + assert topological_entropy_from_matrix(golden) == pytest.approx(np.log2((1 + np.sqrt(5)) / 2), abs=1e-12) + assert topological_entropy_from_matrix(np.zeros((3, 3))) == 0.0 From 173ba89bb61fd48fa14592e507667b4e94f3dcbd Mon Sep 17 00:00:00 2001 From: Ryan James Date: Mon, 16 Nov 2026 09:10:23 -0700 Subject: [PATCH 7/7] Skip sympy-only tests when sympy is missing instead of failing collection Co-authored-by: Cursor --- tests/test_active_epsilon_learning.py | 7 +++++-- tests/test_bisimulation.py | 2 +- tests/test_hmm_state_splitting.py | 6 ++++-- tests/test_minimal_quasi_realization.py | 8 ++++++-- tests/test_process_equivalence.py | 5 ++++- 5 files changed, 20 insertions(+), 8 deletions(-) diff --git a/tests/test_active_epsilon_learning.py b/tests/test_active_epsilon_learning.py index a0cead3..dd801b1 100644 --- a/tests/test_active_epsilon_learning.py +++ b/tests/test_active_epsilon_learning.py @@ -6,7 +6,6 @@ import numpy as np import pytest -import sympy as sp from hypothesis import given, settings from hypothesis import strategies as st @@ -19,7 +18,10 @@ from sofic.inference.active import ProbabilityOracle, ProcessOracle, learn_epsilon_machine_active from sofic.testing.strategies import epsilon_machines -R = sp.Rational + +def R(numerator: int, denominator: int): + """An exact sympy rational; skips the calling test without sympy.""" + return pytest.importorskip("sympy").Rational(numerator, denominator) def _n_states(machine): @@ -180,6 +182,7 @@ def test_recovers_random_strategy_epsilon_machines(topology, seed): def test_exact_sympy_oracle_gives_exact_machine(): + sp = pytest.importorskip("sympy") target = _exact_even() learned = learn_epsilon_machine_active(ProcessOracle(target), ("0", "1")) probs = sorted((t.data[ATTR_EMISSION], t.data[ATTR_PROB]) for t in learned.transitions()) diff --git a/tests/test_bisimulation.py b/tests/test_bisimulation.py index 23692df..ff89891 100644 --- a/tests/test_bisimulation.py +++ b/tests/test_bisimulation.py @@ -3,7 +3,6 @@ from fractions import Fraction import pytest -import sympy as sp from hypothesis import given, settings from hypothesis import strategies as st @@ -167,6 +166,7 @@ def test_markov_chain_quotient_type(): def test_symbolic_probabilities_compare_exactly(): + sp = pytest.importorskip("sympy") a = sp.Symbol("a", positive=True) hmm = MealyHMM(initial_distribution={0: sp.Integer(1)}) hmm.add_transition(0, 1, 0, a / 2) diff --git a/tests/test_hmm_state_splitting.py b/tests/test_hmm_state_splitting.py index 2c9d3c2..948a7fb 100644 --- a/tests/test_hmm_state_splitting.py +++ b/tests/test_hmm_state_splitting.py @@ -11,7 +11,6 @@ from typing import Any import pytest -import sympy from hypothesis import assume, given, settings from hypothesis import strategies as st @@ -193,6 +192,7 @@ def test_in_split_preserves_unifilarity(): def test_out_split_is_exact_for_symbolic_probabilities(): + sympy = pytest.importorskip("sympy") p = sympy.Symbol("p", positive=True) hmm = MealyHMM(initial_distribution={"A": 1 / (1 + p), "B": p / (1 + p)}) hmm.graph.add_state("A") @@ -212,7 +212,9 @@ def test_out_split_is_exact_for_symbolic_probabilities(): assert numeric_split.is_equal_process(numeric_hmm) -def substitute(hmm: MealyHMM, symbol: sympy.Symbol, value: Any) -> MealyHMM: +def substitute(hmm: MealyHMM, symbol: Any, value: Any) -> MealyHMM: + import sympy + numeric = MealyHMM( observation_alphabet=hmm.observation_alphabet, initial_distribution={ diff --git a/tests/test_minimal_quasi_realization.py b/tests/test_minimal_quasi_realization.py index 039fee6..a27e439 100644 --- a/tests/test_minimal_quasi_realization.py +++ b/tests/test_minimal_quasi_realization.py @@ -1,10 +1,10 @@ """Tests for Schützenberger/Fliess minimal quasi-realizations and the process rank.""" from functools import cache +from typing import Any import numpy as np import pytest -import sympy as sp from hypothesis import assume, given, settings from hypothesis import strategies as st @@ -144,6 +144,7 @@ def test_returns_quasi_realization_with_unit_final_vector(): def test_exact_rational_input_stays_exact(): + sp = pytest.importorskip("sympy") third = sp.Rational(1, 3) hmm = MealyHMM(initial_distribution={0: sp.Rational(3, 4), 1: sp.Rational(1, 4)}) hmm.add_transition(0, 0, 0, third) @@ -160,6 +161,7 @@ def test_exact_rational_input_stays_exact(): def test_symbolic_parameter(): + sp = pytest.importorskip("sympy") a = sp.Symbol("a", positive=True) hmm = MealyHMM(initial_distribution={0: sp.Integer(1)}) hmm.add_transition(0, 0, 0, a) @@ -174,7 +176,9 @@ def test_symbolic_parameter(): assert sp.simplify(result @ realization.tau - a * (1 - a)) == 0 -def _exact_word_probability(hmm: MealyHMM, word: tuple[int, ...]) -> sp.Expr: +def _exact_word_probability(hmm: MealyHMM, word: tuple[int, ...]) -> Any: + import sympy as sp + states = sorted(hmm.states()) vector = {s: sp.sympify(hmm.initial_distribution.get(s, 0)) for s in states} for symbol in word: diff --git a/tests/test_process_equivalence.py b/tests/test_process_equivalence.py index 1716e76..b7dd045 100644 --- a/tests/test_process_equivalence.py +++ b/tests/test_process_equivalence.py @@ -1,6 +1,9 @@ +import pytest + + def test_is_equal_process_accepts_sympy_probabilities(): """Regression: object-dtype symbol matrices broke ``matrix_rank``.""" - import sympy as sp + sp = pytest.importorskip("sympy") from sofic.examples import golden_mean