diff --git a/CHANGELOG.md b/CHANGELOG.md index ab897ef..0b87fe6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,23 @@ brute-force reference or a closed-form value and has a regression test. 9 reverse-machine "explosions" are now 3-state reverse ε-machines, and finite/infinite now agrees with `reverse_epsilon_machine_is_finite` on every topology. +### Canonical NFAs as generators and presentations + +- `canonical_rfsa_hmm`, `maximized_prime_atomaton_hmm` and `atomaton_hmm` (new module + `sofic.generators.canonical_generators`; also `EpsilonMachine` / `BidirectionalEpsilonMachine` methods) build the + stochastic analogues of the canonical RFSA, the maximized prime átomaton and the átomaton as generators of a + process with a finite bidirectional machine. The RFSA analogue's states are the forward causal states whose + reverse beliefs are vertices of their convex hull (future morphs that are not mixtures of the others); the + prime-átomaton analogue is the same construction in reverse time on the forward beliefs of the reverse causal + states, time-reversed back. Both are linear programs and generally non-unifilar. +- `generative_model` offers both as candidates (`canonical RFSA generator`, `maximized prime átomaton + generator`) and `coupled_search` starts from them. On the binary 3-state dataset the prime-átomaton analogue + compresses the reverse machine on 112 of 620 processes and is the best generator known on 14, lowering the + best upper bound on `C_g` on three (e.g. 1.2809 to 1.0994). +- `SoficShift.canonical_rfsa_presentation`, `maximized_prime_atomaton_presentation` and `atomaton_presentation` + (new module `sofic.shifts.canonical_presentations`) present a sofic shift by the canonical NFAs of its factor + language, trimmed to the essential states. + ### Generator verification - `GenerativeModelResult` records the returned generator's word-process deviation from the source diff --git a/docs/generators/canonical_generators.rst b/docs/generators/canonical_generators.rst new file mode 100644 index 0000000..4157ecd --- /dev/null +++ b/docs/generators/canonical_generators.rst @@ -0,0 +1,48 @@ +Canonical NFAs as generators +============================ + +.. currentmodule:: sofic.generators.canonical_generators + +A regular language has several canonical automata :cite:`Myers2015`: the minimal DFA, the átomaton +:cite:`BrzozowskiTamm2014`, the canonical residual finite-state automaton (RFSA) :cite:`Denis2002`, and the +maximized prime átomaton :cite:`MaarandTamm2022`. For a stationary process with a finite bidirectional +ε-machine :cite:`Ellison2009`, each has a stochastic analogue that generates the process: + +============================== ===================================================== ====================== +canonical NFA generator states +============================== ===================================================== ====================== +minimal DFA forward ε-machine :math:`S^+` +átomaton reverse ε-machine run forward (:func:`atomaton_hmm`) :math:`S^-` +canonical RFSA :func:`canonical_rfsa_hmm` at most :math:`|S^+|` +maximized prime átomaton :func:`maximized_prime_atomaton_hmm` at most :math:`|S^-|` +============================== ===================================================== ====================== + +A forward causal state's future morph is a mixture of the futures given the reverse causal states, which have +disjoint supports, with weights :math:`R_{s^+} = \Pr(S^- \mid S^+ = s^+)`. A morph that is not a mixture of the +other morphs -- the convex analogue of a prime residual, as in probabilistic residual automata +:cite:`Esposito2002` -- is therefore a vertex of :math:`\operatorname{conv}\{R_{s^+}\}`. The canonical-RFSA +analogue is the generator on those vertices: every causal state is a mixture of them, and the vertices' +transitions follow. The maximized-prime-átomaton analogue is the same construction applied to the reversed +process, on the vertices of the forward beliefs :math:`\operatorname{conv}\{Q_{s^-}\}`, time-reversed back. Both +are linear programs; both are in general not unifilar. The identification with the canonical NFAs is an +analogy and is not from the literature. + +They are generators, so their state entropies are upper bounds on the generative complexity :cite:`LohrAy2009`, +and :func:`~sofic.generators.generative_search.generative_model` offers them as candidates and as starts of +its coupled search. For random-parameter ε-machines the RFSA analogue rarely differs from the ε-machine +(it needs the process rank to fall below :math:`|S^+|`); the prime-átomaton analogue often compresses a large +reverse machine to a few vertices, and on binary three-state ε-machines it is sometimes the smallest generator +known. + +.. code-block:: python + + from sofic.generators import maximized_prime_atomaton_hmm + + prime = maximized_prime_atomaton_hmm(machine) # a MealyHMM on the extreme reverse causal states + prime.to_sofic_shift() # its support presents the same shift + +The topological counterparts for sofic shifts are in :mod:`sofic.shifts.canonical_presentations`. + +.. autofunction:: canonical_rfsa_hmm +.. autofunction:: maximized_prime_atomaton_hmm +.. autofunction:: atomaton_hmm diff --git a/docs/generators/generators.rst b/docs/generators/generators.rst index ccffc3a..ac53bc8 100644 --- a/docs/generators/generators.rst +++ b/docs/generators/generators.rst @@ -43,6 +43,7 @@ Computational mechanics predictive_rate_distortion symbolic_hmm generative_models + canonical_generators directional_flow alternative_complexity wheeler_epsilon diff --git a/docs/references.bib b/docs/references.bib index 7befadb..4288b57 100644 --- a/docs/references.bib +++ b/docs/references.bib @@ -1703,3 +1703,25 @@ @article{mccormick1976computability year = {1976}, doi = {10.1007/BF01580665}, } + +@inproceedings{Esposito2002, + author = {Esposito, Yann and Lemay, Aur{\'e}lien and Denis, Fran{\c{c}}ois and Dupont, Pierre}, + title = {Learning Probabilistic Residual Finite State Automata}, + booktitle = {Grammatical Inference: Algorithms and Applications (ICGI 2002)}, + series = {Lecture Notes in Computer Science}, + volume = {2484}, + pages = {77--91}, + publisher = {Springer}, + year = {2002}, + doi = {10.1007/3-540-45790-9_7}, +} + +@article{Myers2015, + author = {Myers, Robert S. R. and Ad{\'a}mek, Ji{\v r}{\'\i} and Milius, Stefan and Urbat, Henning}, + title = {Coalgebraic Constructions of Canonical Nondeterministic Automata}, + journal = {Theoretical Computer Science}, + volume = {604}, + pages = {81--101}, + year = {2015}, + doi = {10.1016/j.tcs.2015.03.035}, +} diff --git a/docs/shifts/canonical_presentations.rst b/docs/shifts/canonical_presentations.rst new file mode 100644 index 0000000..ce770ea --- /dev/null +++ b/docs/shifts/canonical_presentations.rst @@ -0,0 +1,26 @@ +Canonical NFA presentations +=========================== + +.. currentmodule:: sofic.shifts.canonical_presentations + +A sofic shift is determined by its factor language, which is factorial and extendable :cite:`LindMarcus1995`. +Any automaton for that language with every state accepting presents the shift once trimmed to the states on +bi-infinite paths, so the canonical NFAs of the factor language -- the átomaton :cite:`BrzozowskiTamm2014`, the +canonical residual finite-state automaton :cite:`Denis2002` and the maximized prime átomaton +:cite:`MaarandTamm2022` -- give canonical, generally non-resolving presentations beside the Fischer and Krieger +covers. The residual-side states are follower sets that are not unions of other follower sets. + +.. code-block:: python + + shift = machine.to_sofic_shift() + shift.canonical_rfsa_presentation() + shift.maximized_prime_atomaton_presentation() + shift.atomaton_presentation() + +The stochastic analogues, which replace unions of residuals by mixtures of future morphs, are in +:mod:`sofic.generators.canonical_generators`. + +.. autofunction:: canonical_rfsa_presentation +.. autofunction:: maximized_prime_atomaton_presentation +.. autofunction:: atomaton_presentation +.. autofunction:: factor_language_nfa diff --git a/docs/shifts/shifts.rst b/docs/shifts/shifts.rst index 8279236..9c5da1e 100644 --- a/docs/shifts/shifts.rst +++ b/docs/shifts/shifts.rst @@ -24,4 +24,5 @@ type, Sofic shifts, Dyck shifts, topological Markov chains, and covers textile dyck_enumeration covers + canonical_presentations wheeler diff --git a/sofic/generators/__init__.py b/sofic/generators/__init__.py index 914d1dc..b8e5d6b 100644 --- a/sofic/generators/__init__.py +++ b/sofic/generators/__init__.py @@ -4,6 +4,7 @@ from sofic.generators.bidirectional_epsilon_machine import BidirectionalEpsilonMachine from sofic.generators.block_convergence import BlockConvergenceDiagram, BlockConvergenceEstimates from sofic.generators.block_entropy import BlockEntropyDiagram, BlockEntropyEstimates +from sofic.generators.canonical_generators import atomaton_hmm, canonical_rfsa_hmm, maximized_prime_atomaton_hmm from sofic.generators.channel_coding import FiniteStateChannel from sofic.generators.channel_measures import ( channel_statistical_complexity, @@ -89,6 +90,9 @@ "generative_model", "generative_model_from_bidirectional", "minimal_functional_generator", + "atomaton_hmm", + "canonical_rfsa_hmm", + "maximized_prime_atomaton_hmm", "minimal_wyner_model", "ultimate_generative_model", "mu1_brute_2x2", diff --git a/sofic/generators/bidirectional_epsilon_machine.py b/sofic/generators/bidirectional_epsilon_machine.py index 891c3dd..d27d363 100644 --- a/sofic/generators/bidirectional_epsilon_machine.py +++ b/sofic/generators/bidirectional_epsilon_machine.py @@ -635,6 +635,24 @@ def minimal_functional_generator(self, **kwargs: Any) -> Any: return minimal_functional_generator(self, **kwargs) + def canonical_rfsa_hmm(self, **kwargs: Any) -> Any: + """Canonical-RFSA analogue; see :func:`~sofic.generators.canonical_generators.canonical_rfsa_hmm`.""" + from sofic.generators.canonical_generators import canonical_rfsa_hmm + + return canonical_rfsa_hmm(self, **kwargs) + + def maximized_prime_atomaton_hmm(self, **kwargs: Any) -> Any: + """Prime-átomaton analogue; see :func:`~sofic.generators.canonical_generators.maximized_prime_atomaton_hmm`.""" + from sofic.generators.canonical_generators import maximized_prime_atomaton_hmm + + return maximized_prime_atomaton_hmm(self, **kwargs) + + def atomaton_hmm(self, **kwargs: Any) -> Any: + """Átomaton analogue (reverse ε-machine run forward); see :func:`~sofic.generators.canonical_generators.atomaton_hmm`.""" + from sofic.generators.canonical_generators import atomaton_hmm + + return atomaton_hmm(self, **kwargs) + def wyner_common_information(self, **kwargs: Any) -> float: """Wyner common information C[S+ : S-] = C[past : future] (no generator requirement).""" from sofic.generators.minimal_generative_model import wyner_common_information diff --git a/sofic/generators/canonical_generators.py b/sofic/generators/canonical_generators.py new file mode 100644 index 0000000..43bc234 --- /dev/null +++ b/sofic/generators/canonical_generators.py @@ -0,0 +1,111 @@ +r"""Stochastic analogues of the canonical NFAs of a regular language, as generators of a process. + +Regular languages have several canonical automata :cite:`Myers2015`: the minimal DFA, the átomaton +:cite:`BrzozowskiTamm2014`, the canonical residual finite-state automaton (RFSA) :cite:`Denis2002`, and its dual, +the maximized prime átomaton :cite:`MaarandTamm2022`. For a stationary process with a finite bidirectional +ε-machine :cite:`Ellison2009` the first two have standard analogues, and the last two have analogues built from +extreme points of belief polytopes: + +* minimal DFA -- the forward ε-machine, states :math:`S^+`; +* átomaton (reverse of the minimal DFA of the reverse language) -- the reverse ε-machine run forward, + states :math:`S^-` (:func:`atomaton_hmm`); +* canonical RFSA (prime residuals) -- the forward causal states whose future morph is not a mixture of the + others' (:func:`canonical_rfsa_hmm`); +* maximized prime átomaton (reverse of the canonical RFSA of the reverse language) -- the same construction in + reverse time, reversed back (:func:`maximized_prime_atomaton_hmm`). + +A forward causal state :math:`s^+` has future morph :math:`\sum_b R_{s^+}(b) \Pr(\text{future} \mid S^- = b)` +with :math:`R_{s^+} = \Pr(S^- \mid S^+ = s^+)`, and the futures given distinct reverse causal states have +disjoint supports. So the morph of :math:`s^+` is not a nonnegative combination of the other morphs exactly when +:math:`R_{s^+}` is a vertex of :math:`\operatorname{conv}\{R_{s^+}\}`: this is the convex analogue of a prime +residual, as in probabilistic residual automata :cite:`Esposito2002`. Writing every row as +:math:`R_t = \sum_e C_{te} R_e`, the HMM on the vertices with joint transition matrices :math:`(T^{(x)} C)_{E, +\cdot}` emits the future morph of each vertex, so it generates the process with at most :math:`|S^+|` states. It +is in general not unifilar. The prime-átomaton analogue uses the forward beliefs +:math:`Q_{s^-} = \Pr(S^+ \mid S^- = s^-)` of the reverse causal states instead: it is a generator of the +reversed process, time-reversed with its stationary law, with at most :math:`|S^-|` states. + +These are generators, so their state entropies bound the generative complexity :math:`C_g` of +:cite:`LohrAy2009` from above; no minimality is claimed. Identifying them with the canonical NFAs is an analogy +(extreme points of a cone in place of prime residuals) and is not from the literature. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import numpy as np + +from sofic.generators.mealy import MealyHMM + +if TYPE_CHECKING: + from sofic.generators.bidirectional_epsilon_machine import BidirectionalEpsilonMachine + from sofic.generators.coupled_generators import _GeneratorProblem + +__all__ = ["atomaton_hmm", "canonical_rfsa_hmm", "maximized_prime_atomaton_hmm"] + + +def _problem(machine: Any) -> _GeneratorProblem: + from sofic.generators.bidirectional_epsilon_machine import BidirectionalEpsilonMachine + from sofic.generators.coupled_generators import _GeneratorProblem + from sofic.generators.epsilon_machine import EpsilonMachine + + if not isinstance(machine, BidirectionalEpsilonMachine): + forward = machine if isinstance(machine, EpsilonMachine) else EpsilonMachine.from_hmm(machine) + machine = BidirectionalEpsilonMachine.from_forward(forward) + return _GeneratorProblem(machine) + + +def _labels(problem: _GeneratorProblem, side: int) -> list[Any]: + return sorted({pair[side] for pair in problem.lifted.pairs}, key=repr) + + +def _as_hmm(problem: _GeneratorProblem, pi: np.ndarray, K: np.ndarray, names: list[Any], cutoff: float) -> MealyHMM: + hmm = MealyHMM(observation_alphabet=frozenset(problem.symbols)) + for name in names: + hmm.graph.add_state(name) + for w, x, v in zip(*np.nonzero(cutoff < K), strict=True): + hmm.add_transition(names[w], names[v], problem.symbols[x], float(K[w, x, v])) + total = float(pi.sum()) + hmm.initial_distribution = {name: float(p) / total for name, p in zip(names, pi, strict=True)} + hmm.validate_stochastic() + return hmm + + +def canonical_rfsa_hmm( + machine: EpsilonMachine | BidirectionalEpsilonMachine, *, tol: float = 1e-7, cutoff: float = 1e-13 +) -> MealyHMM: + """Canonical-RFSA analogue: the generator on the forward causal states with extreme future morphs. + + States are named by those causal states; the initial distribution is stationary. ``tol`` is the L1 + tolerance of the extreme-point linear programs. See the module docstring. + """ + problem = _problem(machine) + (pi, _, _, K), E = problem.residual_seed(tol=tol) + names = _labels(problem, 0) + return _as_hmm(problem, pi, K, [names[e] for e in E], cutoff) + + +def maximized_prime_atomaton_hmm( + machine: EpsilonMachine | BidirectionalEpsilonMachine, *, tol: float = 1e-7, cutoff: float = 1e-13 +) -> MealyHMM: + """Maximized-prime-átomaton analogue: the generator on the reverse causal states with extreme past morphs. + + States are named by those reverse causal states; the initial distribution is stationary. See the module + docstring. + """ + problem = _problem(machine) + (pi, _, _, K), E = problem.prime_atomaton_seed(tol=tol) + names = _labels(problem, 1) + return _as_hmm(problem, pi, K, [names[e] for e in E], cutoff) + + +def atomaton_hmm(machine: EpsilonMachine | BidirectionalEpsilonMachine, *, cutoff: float = 1e-13) -> MealyHMM: + """Átomaton analogue: the reverse ε-machine run forward in time (a co-unifilar generator on :math:`S^-`).""" + problem = _problem(machine) + pi, _, _, K = problem.reverse_seed() + return _as_hmm(problem, pi, K, _labels(problem, 1), cutoff) + + +if TYPE_CHECKING: + from sofic.generators.epsilon_machine import EpsilonMachine diff --git a/sofic/generators/coupled_generators.py b/sofic/generators/coupled_generators.py index 22cb2fb..650674f 100644 --- a/sofic/generators/coupled_generators.py +++ b/sofic/generators/coupled_generators.py @@ -362,6 +362,40 @@ def pair_seed(self) -> tuple[np.ndarray, ...]: """W = (S+, S-): the bidirectional machine.""" return self.channel_seed(np.eye(len(self.p_pair))) + def residual_seed(self, *, tol: float = 1e-7) -> tuple[tuple[np.ndarray, ...], list[int]]: + """Canonical-RFSA analogue: forward causal states whose reverse beliefs are vertices of their hull. + + A causal state's future morph is ``sum_b R[s+](b) Pr(future | S- = b)``, and those conditional futures + have disjoint supports, so a morph is not a mixture of other morphs exactly when ``R[s+]`` is a vertex + of ``conv{R[s+]}``. With every row written as ``R[t] = sum_e C[t, e] R[e]``, the HMM on the vertices + with kernel ``K[E] C`` emits the same futures (:func:`canonical_rfsa_hmm`). Returns the seed + ``(pi, Q, R, K)``, ``Q`` completed by the forward stationarity fixed point, and the vertex indices. + """ + pa, _, R, K = self.epsilon_seed() + E, C = _extreme_rows(R, tol) + pi = pa @ C + Ks = np.einsum("rxt,te->rxe", K[E], C) + Q = _complete_forward_beliefs(self, pi, np.eye(self.n_plus)[E], Ks) + return (pi, Q, R[E], Ks), E + + def prime_atomaton_seed(self, *, tol: float = 1e-7) -> tuple[tuple[np.ndarray, ...], list[int]]: + """Maximized-prime-átomaton analogue: :meth:`residual_seed` of the reversed process, reversed back. + + The states are the reverse causal states whose forward beliefs ``Q[s-]`` are vertices of + ``conv{Q[s-]}`` (their past morphs are not mixtures of the others). The generator is built in reverse + time and reversed with its stationary law (:func:`maximized_prime_atomaton_hmm`). Returns the seed, its + ``R`` completed by the future-side fixed point, and the vertex indices. + """ + pb, Q, _, K = self.reverse_seed() + E, D = _extreme_rows(Q, tol) + J = pb[:, None, None] * K # J[b, x, c] = Pr(S-_0 = b, X_0 = x, S-_1 = c) + backward = J.transpose(2, 1, 0) / np.maximum(pb[:, None, None], 1e-300) # from S-_1 = c emit x to S-_0 = b + reverse_kernel = np.einsum("cxb,be->cxe", backward[E], D) + rho = pb @ D + Kf = np.einsum("e,exf->fxe", rho, reverse_kernel) / np.maximum(rho[:, None, None], 1e-300) + R = _complete_reverse_beliefs(self, np.eye(self.n_minus)[E], Kf) + return (rho, Q[E], R, Kf), E + def channel_seed(self, c: np.ndarray) -> tuple[np.ndarray, ...]: """The lift of a channel ``c[pair, w]`` (e.g. a lifted or unconstrained optimum).""" lifted = self.lifted @@ -966,6 +1000,78 @@ def entropy(y: np.ndarray) -> float: return entropy(z), z +def _conic_residual(target: np.ndarray, generators: np.ndarray) -> tuple[float, np.ndarray]: + """L1 distance from ``target`` to the cone of the columns of ``generators``, and the coefficients.""" + from scipy.optimize import linprog + + rows, cols = generators.shape + if cols == 0: + return float(np.abs(target).sum()), np.zeros(0) + eye = np.eye(rows) + res = linprog( + np.concatenate([np.zeros(cols), np.ones(2 * rows)]), + A_eq=np.hstack([generators, eye, -eye]), + b_eq=target, + bounds=(0, None), + method="highs", + ) + return float(res.fun), res.x[:cols] + + +def _extreme_rows(M: np.ndarray, tol: float) -> tuple[list[int], np.ndarray]: + """Rows of a row-stochastic ``M`` that are vertices of the rows' convex hull, and every row's weights on them. + + Rows within ``tol`` (L1) of an earlier row are merged first. Returns the vertex indices ``E`` and ``C`` + with ``M = C @ M[E]``, ``C`` row-stochastic. + """ + representatives: list[int] = [] + for i in range(len(M)): + if not any(np.abs(M[i] - M[j]).sum() <= tol for j in representatives): + representatives.append(i) + E = [i for i in representatives if _conic_residual(M[i], M[[j for j in representatives if j != i]].T)[0] > tol] + C = np.zeros((len(M), len(E))) + for t in range(len(M)): + if t in E: + C[t, E.index(t)] = 1.0 + else: + c = _conic_residual(M[t], M[E].T)[1] + C[t] = c / c.sum() + return E, C + + +def _complete_forward_beliefs( + problem: _GeneratorProblem, + pi: np.ndarray, + Q: np.ndarray, + K: np.ndarray, + *, + atol: float = 1e-14, + max_iter: int = 100_000, +) -> np.ndarray: + """Forward beliefs of a generator: the fixed point of ``A' = sum A[w, a] K[w, x, v] F[a, x, c]``, ``A = pi Q``.""" + A = pi[:, None] * Q + for _ in range(max_iter): + nxt = np.einsum("wa,wxv,axc->vc", A, K, problem.F) + if np.abs(nxt - A).max() <= atol: + A = nxt + break + A = nxt + return A / np.maximum(A.sum(axis=1, keepdims=True), 1e-300) + + +def _complete_reverse_beliefs( + problem: _GeneratorProblem, R: np.ndarray, K: np.ndarray, *, atol: float = 1e-14, max_iter: int = 100_000 +) -> np.ndarray: + """Reverse beliefs of a generator: the fixed point of ``R[w, b] = sum K[w, x, v] R[v, c] G[x, c, b]``.""" + for _ in range(max_iter): + nxt = np.einsum("wxv,vc,xcb->wb", K, R, problem.G) + nxt = nxt / np.maximum(nxt.sum(axis=1, keepdims=True), 1e-300) + if np.abs(nxt - R).max() <= atol: + return nxt + R = nxt + return R + + def _pad(seed: Seed, k: int, rng: np.random.Generator, noise: float) -> Seed: """Fit a seed with fewer or more states into ``k`` states, adding small mass to empty states.""" pi, Q, R, K = seed @@ -1133,7 +1239,13 @@ def coupled_search( """ rng = rng or np.random.default_rng() problem = _GeneratorProblem(bidir) - named = [("eps", problem.epsilon_seed()), ("reverse", problem.reverse_seed()), ("bidir", problem.pair_seed())] + named = [ + ("eps", problem.epsilon_seed()), + ("reverse", problem.reverse_seed()), + ("bidir", problem.pair_seed()), + ("rfsa", problem.residual_seed()[0]), + ("prime", problem.prime_atomaton_seed()[0]), + ] named += list(extra) thetas = [(name, problem.logits(*_pad(cast(Seed, seed), k, rng, 1e-3))) for name, seed in named] thetas += [ diff --git a/sofic/generators/epsilon_machine.py b/sofic/generators/epsilon_machine.py index a765363..1e836df 100644 --- a/sofic/generators/epsilon_machine.py +++ b/sofic/generators/epsilon_machine.py @@ -384,6 +384,24 @@ def minimal_functional_generator(self, **kwargs: Any) -> Any: return minimal_functional_generator(self, **kwargs) + def canonical_rfsa_hmm(self, **kwargs: Any) -> Any: + """Canonical-RFSA analogue; see :func:`~sofic.generators.canonical_generators.canonical_rfsa_hmm`.""" + from sofic.generators.canonical_generators import canonical_rfsa_hmm + + return canonical_rfsa_hmm(self, **kwargs) + + def maximized_prime_atomaton_hmm(self, **kwargs: Any) -> Any: + """Prime-átomaton analogue; see :func:`~sofic.generators.canonical_generators.maximized_prime_atomaton_hmm`.""" + from sofic.generators.canonical_generators import maximized_prime_atomaton_hmm + + return maximized_prime_atomaton_hmm(self, **kwargs) + + def atomaton_hmm(self, **kwargs: Any) -> Any: + """Átomaton analogue (reverse ε-machine run forward); see :func:`~sofic.generators.canonical_generators.atomaton_hmm`.""" + from sofic.generators.canonical_generators import atomaton_hmm + + return atomaton_hmm(self, **kwargs) + def crypticity(self) -> float: """χ = C_μ − E (forward statistical complexity minus excess entropy).""" return self.statistical_complexity() - self.excess_entropy() diff --git a/sofic/generators/generative_search.py b/sofic/generators/generative_search.py index cf61817..85e79f7 100644 --- a/sofic/generators/generative_search.py +++ b/sofic/generators/generative_search.py @@ -539,6 +539,8 @@ def maybe_return_early() -> GenerativeModelResult | None: offer("epsilon machine", problem.epsilon_seed()) offer("reverse epsilon machine", problem.reverse_seed()) offer("bidirectional machine", problem.pair_seed()) + offer("canonical RFSA generator", problem.residual_seed()[0]) + offer("maximized prime átomaton generator", problem.prime_atomaton_seed()[0]) early = maybe_return_early() if early is not None and early.certified: return _finalize_result(early) diff --git a/sofic/shifts/__init__.py b/sofic/shifts/__init__.py index a7bec3f..73ad93d 100644 --- a/sofic/shifts/__init__.py +++ b/sofic/shifts/__init__.py @@ -2,6 +2,12 @@ from sofic.shifts.algorithms import periodic_points, zeta_function from sofic.shifts.base import SymbolicModel +from sofic.shifts.canonical_presentations import ( + atomaton_presentation, + canonical_rfsa_presentation, + factor_language_nfa, + maximized_prime_atomaton_presentation, +) from sofic.shifts.covers import ( LeftFischerCover, LeftKriegerCover, @@ -52,6 +58,10 @@ ) __all__ = [ + "atomaton_presentation", + "canonical_rfsa_presentation", + "factor_language_nfa", + "maximized_prime_atomaton_presentation", "BowenFranksGroup", "bowen_franks_group", "in_amalgamate", diff --git a/sofic/shifts/canonical_presentations.py b/sofic/shifts/canonical_presentations.py new file mode 100644 index 0000000..b19d4a2 --- /dev/null +++ b/sofic/shifts/canonical_presentations.py @@ -0,0 +1,77 @@ +r"""Canonical NFAs of a sofic shift's language, as presentations of the shift. + +A sofic shift :math:`X` is determined by its factor language :math:`L(X)`, which is factorial and extendable +:cite:`LindMarcus1995`. Any automaton for :math:`L(X)` whose states are all accepting presents :math:`X` once +trimmed to the states on bi-infinite paths: every path reads a word of :math:`L(X)` (residuals of a factorial +language are factorial), and every word of :math:`L(X)` labels a path. The canonical NFAs of :math:`L(X)` -- +the átomaton :cite:`BrzozowskiTamm2014`, the canonical residual finite-state automaton :cite:`Denis2002` and the +maximized prime átomaton :cite:`MaarandTamm2022` -- therefore give canonical, generally non-resolving +presentations, beside the right-resolving Fischer and Krieger covers. On the residual side the states are +follower sets that are not unions of other follower sets. + +These are the topological shadows of the stochastic analogues in +:mod:`sofic.generators.canonical_generators`, which replace unions of residuals by mixtures of future morphs. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from sofic.graph import ATTR_SYMBOL, TransitionGraph + +if TYPE_CHECKING: + from sofic.automata.nfa import NFA + from sofic.shifts.sofic import SoficShift + +__all__ = [ + "atomaton_presentation", + "canonical_rfsa_presentation", + "factor_language_nfa", + "maximized_prime_atomaton_presentation", +] + + +def factor_language_nfa(shift: SoficShift) -> NFA: + """The trimmed presentation read as an NFA with every state initial and accepting: it accepts :math:`L(X)`.""" + from sofic.automata.nfa import NFA + + trimmed = shift.trim_transient() + states = frozenset(trimmed.states()) + return NFA( + graph=trimmed.graph.copy(), + input_alphabet=frozenset(shift.symbol_alphabet), + initial_states=states, + accepting_states=states, + ) + + +def _presentation(shift: SoficShift, automaton: Any) -> SoficShift: + from sofic.shifts.sofic import SoficShift + + graph = TransitionGraph() + for state in automaton.states(): + graph.add_state(state) + for transition in automaton.transitions(): + graph.add_transition(transition.source, transition.target, **{ATTR_SYMBOL: transition.data[ATTR_SYMBOL]}) + return SoficShift(graph=graph, symbol_alphabet=frozenset(shift.symbol_alphabet)).trim_transient() + + +def canonical_rfsa_presentation(shift: SoficShift) -> SoficShift: + """Presentation of ``shift`` by the canonical RFSA of its factor language (prime follower sets).""" + from sofic.automata.canonical.residual import canonical_rfsa_from_language + + return _presentation(shift, canonical_rfsa_from_language(factor_language_nfa(shift))) + + +def maximized_prime_atomaton_presentation(shift: SoficShift) -> SoficShift: + """Presentation of ``shift`` by the maximized prime átomaton of its factor language (prime predecessor sets).""" + from sofic.automata.canonical.residual import maximized_prime_atomaton_from_language + + return _presentation(shift, maximized_prime_atomaton_from_language(factor_language_nfa(shift))) + + +def atomaton_presentation(shift: SoficShift) -> SoficShift: + """Presentation of ``shift`` by the átomaton of its factor language (reverse of the minimal DFA of the reverse).""" + from sofic.automata.canonical.residual import atomaton_from_language + + return _presentation(shift, atomaton_from_language(factor_language_nfa(shift))) diff --git a/sofic/shifts/sofic.py b/sofic/shifts/sofic.py index 34af6fa..0bf2b91 100644 --- a/sofic/shifts/sofic.py +++ b/sofic/shifts/sofic.py @@ -76,6 +76,33 @@ def transition_semigroup(self, **kwargs: Any) -> TransformationSemigroup: return transformation_semigroup(self, **kwargs) + def canonical_rfsa_presentation(self) -> SoficShift: + """Presentation by the canonical RFSA of the factor language. + + See :func:`~sofic.shifts.canonical_presentations.canonical_rfsa_presentation`. + """ + from sofic.shifts.canonical_presentations import canonical_rfsa_presentation + + return canonical_rfsa_presentation(self) + + def maximized_prime_atomaton_presentation(self) -> SoficShift: + """Presentation by the maximized prime átomaton of the factor language. + + See :func:`~sofic.shifts.canonical_presentations.maximized_prime_atomaton_presentation`. + """ + from sofic.shifts.canonical_presentations import maximized_prime_atomaton_presentation + + return maximized_prime_atomaton_presentation(self) + + def atomaton_presentation(self) -> SoficShift: + """Presentation by the átomaton of the factor language. + + See :func:`~sofic.shifts.canonical_presentations.atomaton_presentation`. + """ + from sofic.shifts.canonical_presentations import atomaton_presentation + + return atomaton_presentation(self) + def krohn_rhodes_complexity(self) -> ComplexityBounds: """Krohn-Rhodes complexity bounds of the factor language's syntactic monoid. diff --git a/tests/test_canonical_generators.py b/tests/test_canonical_generators.py new file mode 100644 index 0000000..8136bab --- /dev/null +++ b/tests/test_canonical_generators.py @@ -0,0 +1,114 @@ +"""Stochastic analogues of canonical NFAs as generators, and canonical NFA presentations of sofic shifts.""" + +from __future__ import annotations + +import numpy as np +import pytest +from hypothesis import given, settings + +from sofic.automata.algorithms import equivalent +from sofic.examples import even_process, golden_mean +from sofic.examples.epsilon_machines import from_symbol_matrices +from sofic.generators.canonical_generators import atomaton_hmm, canonical_rfsa_hmm, maximized_prime_atomaton_hmm +from sofic.generators.epsilon_machine import EpsilonMachine +from sofic.generators.mealy import MealyHMM +from sofic.generators.minimal_generative_model import _equivalence_error +from sofic.shifts.canonical_presentations import ( + atomaton_presentation, + canonical_rfsa_presentation, + factor_language_nfa, + maximized_prime_atomaton_presentation, +) +from sofic.testing.strategies import sofic_shifts + + +def _state_entropy(hmm: MealyHMM) -> float: + p = np.array([v for v in hmm.initial_distribution.values() if v > 0]) + return float(-(p * np.log2(p)).sum()) + + +def _reset_mixture() -> EpsilonMachine: + """Two hidden states, three causal states (process rank 2); symbols 2 and 3 reset, 1 is emitted only from a.""" + hmm = MealyHMM(observation_alphabet=frozenset("0123")) + for s, t, x, p in [ + ("a", "a", "0", 0.3), ("a", "a", "1", 0.2), ("a", "b", "1", 0.2), ("a", "a", "2", 0.06), ("a", "b", "3", 0.24), + ("b", "b", "0", 0.3), ("b", "a", "2", 0.35), ("b", "b", "3", 0.35), + ]: # fmt: skip + hmm.graph.add_state(s) + hmm.graph.add_state(t) + hmm.add_transition(s, t, x, p) + hmm.initial_distribution = dict(zip(hmm.reindex().states, map(float, hmm.stationary_distribution()), strict=True)) + return EpsilonMachine.from_hmm(hmm) + + +def _paired_reverse_compression() -> EpsilonMachine: + """A 3-state ε-machine whose reverse machine has 7 states, 3 of them extreme (dataset process n3-t088-d4).""" + a, b, c = 0.7353692009410088, 0.03138587493847493, 0.145902298340887 # code ((0,1),(2,2),(0,2)) + mats = {0: np.array([[a, 0, 0], [0, 0, b], [c, 0, 0]]), 1: np.array([[0, 1 - a, 0], [0, 0, 1 - b], [0, 0, 1 - c]])} + machine = from_symbol_matrices((0, 1, 2), (0, 1), mats) + return machine if isinstance(machine, EpsilonMachine) else EpsilonMachine.from_hmm(machine) + + +@pytest.mark.parametrize("build", [canonical_rfsa_hmm, maximized_prime_atomaton_hmm, atomaton_hmm]) +@pytest.mark.parametrize("machine", [golden_mean(0.4), even_process(), _reset_mixture()]) +def test_canonical_generators_generate_the_process(build, machine) -> None: + hmm = build(machine) + assert _equivalence_error(hmm, machine) < 1e-10 + + +def test_two_state_epsilon_machines_are_fixed_points() -> None: + gm = golden_mean(0.4) + assert len(list(canonical_rfsa_hmm(gm).states())) == 2 + assert _state_entropy(canonical_rfsa_hmm(gm)) == pytest.approx(float(gm.statistical_complexity())) + + +def test_rfsa_analogue_drops_the_mixture_causal_state() -> None: + machine = _reset_mixture() + rfsa = canonical_rfsa_hmm(machine) + assert len(list(machine.states())) == 3 + assert len(list(rfsa.states())) == 2 + assert not rfsa.is_unifilar() + assert _state_entropy(rfsa) < float(machine.statistical_complexity()) + + +def test_prime_atomaton_analogue_compresses_the_reverse_machine() -> None: + machine = _paired_reverse_compression() + prime = maximized_prime_atomaton_hmm(machine) + atom = atomaton_hmm(machine) + assert len(list(atom.states())) > len(list(prime.states())) == 3 + assert _equivalence_error(prime, machine) < 1e-10 + assert _state_entropy(prime) < float(machine.statistical_complexity()) - 0.15 # 1.0994 against C_mu = 1.2809 + + +def test_generator_search_starts_from_the_prime_atomaton_analogue() -> None: + from sofic.generators.bidirectional_epsilon_machine import BidirectionalEpsilonMachine + from sofic.generators.generative_search import generative_model_from_bidirectional + + bidir = BidirectionalEpsilonMachine.from_forward(_paired_reverse_compression()) + result = generative_model_from_bidirectional( + bidir, stages=("machines",), coverage="off", generator_caps=0, rng=np.random.default_rng(0) + ) + assert result.upper_source == "maximized prime átomaton generator" + assert result.upper == pytest.approx(_state_entropy(maximized_prime_atomaton_hmm(bidir)), abs=1e-9) + assert result.reproduction_error < 1e-10 + + +@pytest.mark.parametrize( + "present", [canonical_rfsa_presentation, maximized_prime_atomaton_presentation, atomaton_presentation] +) +@settings(max_examples=25, deadline=None, derandomize=True) +@given(shift=sofic_shifts(max_states=3)) +def test_canonical_presentations_present_the_same_shift(present, shift) -> None: + presented = present(shift) + assert equivalent(factor_language_nfa(shift), factor_language_nfa(presented)) + assert len(list(presented.states())) <= 2 ** len(list(shift.trim_transient().states())) + + +def test_shift_methods_and_supports() -> None: + shift = even_process().to_sofic_shift() + assert equivalent(factor_language_nfa(shift), factor_language_nfa(shift.canonical_rfsa_presentation())) + assert equivalent(factor_language_nfa(shift), factor_language_nfa(shift.maximized_prime_atomaton_presentation())) + # the support of each stochastic analogue presents the same shift + for build in (canonical_rfsa_hmm, maximized_prime_atomaton_hmm, atomaton_hmm): + support = build(_reset_mixture()).to_sofic_shift() + assert equivalent(factor_language_nfa(_reset_mixture().to_sofic_shift()), factor_language_nfa(support)) diff --git a/tests/test_generative_model.py b/tests/test_generative_model.py index 62c797a..3bf2d1a 100644 --- a/tests/test_generative_model.py +++ b/tests/test_generative_model.py @@ -82,7 +82,14 @@ def test_zero_time_budget_returns_a_valid_bracket_from_the_machines() -> None: result = generative_model_from_bidirectional(_survey_machine(), time_budget=0.0, rng=np.random.default_rng(0)) assert result.budget_exhausted - assert result.upper_source == "epsilon machine" or result.upper_source.endswith("epsilon machine") + machines = { + "epsilon machine", + "reverse epsilon machine", + "bidirectional machine", + "canonical RFSA generator", + "maximized prime átomaton generator", + } + assert result.upper_source in machines assert result.lower <= result.upper + 1e-9 skipped = {s["stage"] for s in result.stages if s.get("skipped") == "time budget exhausted"} assert {"generator coverage bound", "exact common information", "coupled search"} <= skipped