Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,19 @@ brute-force reference or a closed-form value and has a regression test.
paper; it is Chaos 28, 033116 (2018).
- `automaton_to_regex` was ambiguous for multi-character symbols (`ab` vs `a`,
`b`); such symbols are now quoted (`'ab'`), and `ε`, `∅` and `'` are escaped.
- `HiddenMarkovModel.to_support_dfa` accepted only terminal recurrent subsets,
so it rejected words of positive probability (e.g. `1` for the even process);
every non-empty subset now accepts.
- `entropy_rate` and `state_entropy` no longer raise `TypeError` when state
labels mix types (e.g. `0` and `(1, 0)` after a split).
- `is_equal_process` works on sympy-valued HMMs (object-dtype matrices broke
`matrix_rank`).
- `DFA.add_transition` adds a missing source state, as `NFA.add_transition`
does.
- `EpsilonMachine.from_hmm` split causal states that differed only by
floating-point round-off from belief updates (a fair-coin HMM gave 33 states
and C_mu ≈ 2.46); numeric transition probabilities are now compared within the
mixed-state tolerance.

### New

Expand Down Expand Up @@ -553,6 +566,42 @@ brute-force reference or a closed-form value and has a regression test.
Sierpinski (log₂ 3) examples.
- `EpsilonMachine.from_hmm(hmm, max_states=...)` caps the mixed-state
enumeration (it silently ignored keyword arguments).
- `minimal_quasi_realization` and `process_rank` (plus
`HiddenMarkovModel.process_rank`): Schützenberger/Fliess minimization of an
HMM's linear representation to a minimal-dimension `QuasiRealization` whose
dimension is the process rank; exact for sympy input.
- `bisimulation_partition` and `coarsest_lumping`: the coarsest strongly
lumpable partition (Larsen–Skou probabilistic bisimulation) by splitter-based
refinement; `lump(model)` and the `lump` methods accept `partition=None` to
mean the coarsest partition.
- `SlidingBlockCode.apply_to_process` and `factor_codes.image_process`: the
image process of a sliding block code; `HiddenMarkovModel.higher_block(k)` for
k-block presentations. Excess entropy and statistical complexity are not
conjugacy invariants (`E(β_k X) = E(X) + (k − 1) h_μ`); only `h_μ` is.
- `sofic.generators.state_splitting`: process-preserving out- and in-splitting
(`split_state`) and `amalgamate`.
- `sofic.generators.support`: `support_nfa`, `support_includes`,
`is_absolutely_continuous`, `support_equal` (stationary support;
finite-cylinder absolute continuity), with matching `HiddenMarkovModel`
methods.
- `condition_on_language`: conditions an HMM on a prefix-closed regular
constraint by the Doob h-transform; the uniform i.i.d. process conditioned on
an irreducible SFT is its Parry measure.
- `omega_probability` for deterministic Büchi properties of HMM output (bottom
strongly connected components of the product chain; Baier & Katoen 2008) and
`regular_language_probability` for exact `P(X_{0:n} ∈ L)`.
- `sofic.inference.learn_epsilon_machine_active` and `ProcessOracle`: an
L*-style active learner for ε-machines from probability and equivalence
queries; exact for finite, exactly synchronizable ε-machines, with `history`
seeding for infinite transients.
- `renyi_entropy_rate`, `pressure` and `rate_function`
(`sofic.generators.renyi`): Rényi entropy rates for α ∈ [0, ∞] (topological,
Shannon and min-entropy rates as special cases) and the large-deviation rate
function of −(1/n) log₂ P(X_{0:n}) by Legendre transform of the pressure.
- Experimental `canonical_residual_hmm` (`sofic.generators.canonical_residual`,
requires `experimental=True`): a generator whose states are the extreme future
morphs of a finite ε-machine, the process analogue of the canonical RFSA; it
can be strictly smaller than the ε-machine.

## 0.3.0

Expand Down
69 changes: 69 additions & 0 deletions docs/generators/bisimulation.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
.. bisimulation.rst

**************************
Probabilistic Bisimulation
**************************

:doc:`Lumping <lumping>` aggregates states along a *given* partition. The
coarsest partition that can be lumped is found automatically by computing
**probabilistic bisimulation** :cite:`LarsenSkou1991`: an equivalence relation
on states under which equivalent states send equal probability mass, for every
emitted symbol, into every equivalence class. For a
:class:`~sofic.generators.mealy.MealyHMM` with joint edge law
:math:`P(t, o \mid s)`, states :math:`s \sim s'` are bisimilar when

.. math::

\sum_{t \in B} P(t, o \mid s) = \sum_{t \in B} P(t, o \mid s')
\qquad \text{for every class } B \text{ and every symbol } o.

This is exactly the strong lumpability condition of Kemeny & Snell
:cite:`KemenySnell1976`, so the bisimulation classes form the coarsest strongly
lumpable partition: every lumpable partition refines it, and the lumped model
generates the same observed process. A :class:`~sofic.generators.moore.MooreHMM`
additionally requires equal state emission laws. A
:class:`~sofic.generators.markov.MarkovChain` has no edge labels, so its coarsest
lumpable partition is a single block unless an ``initial`` partition (for
example, the level sets of an observation function of the state) is supplied
to be refined.

:func:`~sofic.generators.lumping.bisimulation_partition` computes the classes
by splitter-driven partition refinement in the style of Hopcroft and
Paige--Tarjan: each splitter set divides every block by the per-symbol mass its
states send into the splitter, and once a block that has already served as a
splitter breaks up, all of its pieces but the largest are queued as new
splitters. Probabilities that are all exact (sympy expressions,
:class:`~fractions.Fraction`, or integers) are compared exactly; floating-point
masses are grouped when they lie within ``tol`` of their sorted neighbors.
:func:`~sofic.generators.lumping.coarsest_lumping` returns the quotient model,
and :func:`~sofic.generators.lumping.lump` with ``partition=None`` uses the
coarsest partition.

For a unifilar presentation whose states are all recurrent, bisimulation
minimization coincides with ε-machine minimization, so the quotient has as many
states as :meth:`EpsilonMachine.from_hmm
<sofic.generators.epsilon_machine.EpsilonMachine.from_hmm>`; an ε-machine is
already bisimulation-minimal. For non-unifilar presentations the quotient is
generally not unifilar and can be far smaller than the ε-machine.

.. ipython::

In [1]: from sofic.generators.mealy import MealyHMM

In [2]: from sofic.generators.lumping import bisimulation_partition, coarsest_lumping

In [3]: hmm = MealyHMM(initial_distribution={0: 1.0})

In [4]: _ = hmm.add_transition(0, 0, "a", 0.5), hmm.add_transition(0, 1, "b", 0.25), hmm.add_transition(0, 2, "b", 0.25)

In [5]: _ = hmm.add_transition(1, 0, "a", 1.0), hmm.add_transition(2, 0, "a", 1.0)

In [6]: bisimulation_partition(hmm)

In [7]: sorted(coarsest_lumping(hmm).states(), key=str)

API
===

.. autofunction:: sofic.generators.lumping.bisimulation_partition
.. autofunction:: sofic.generators.lumping.coarsest_lumping
81 changes: 81 additions & 0 deletions docs/generators/canonical_residual_hmm.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
.. canonical_residual_hmm.rst
.. py:module:: sofic.generators.canonical_residual

**********************
Canonical Residual HMM
**********************

.. warning::

Experimental. :func:`canonical_residual_hmm` raises :class:`RuntimeError`
unless called with ``experimental=True``. The construction has no published
reference. Its correctness is checked against brute-force word
distributions in the test suite.

The canonical residual finite-state automaton (RFSA) of a regular language has
the *prime* residual languages as its states. A residual is prime when it is not
the union of other residuals :cite:`Denis2002`; see :cite:`MaarandTamm2022` for
its dual, the átomaton. Its stochastic analogue for a process with a finite
ε-machine replaces residual languages by future morphs
:math:`f_s(w) = P(w \mid s)` of the causal states, and unions by nonnegative
combinations. Every morph has :math:`f_s(\lambda) = 1`, so nonnegative
combinations of morphs are convex combinations.

Construction
============

1. Each causal state :math:`s` of positive stationary probability is
represented by its probabilities :math:`P(w_j \mid s)` on a basis of test
words. The test words are found breadth first: keep :math:`w` when
:math:`T^{(w)} \mathbf{1}` is linearly independent of the vectors already
kept. Linear relations among these coordinates are then exactly linear
relations among the morphs.
2. A morph is *extreme* when it is not a nonnegative combination of the other
morphs. This is decided by a linear program
(:func:`scipy.optimize.linprog`). The extreme morphs form the state set
:math:`R`.
3. Every morph is written as :math:`f_t = \sum_{r \in R} c_{t r} f_r` with
:math:`c \ge 0`, again by a linear program.
4. Since :math:`f_r(x w) = \sum_t T^{(x)}_{r t} f_t(w)`, the generator on
:math:`R` with joint transition matrices :math:`(T^{(x)} C)_{R,\cdot}` and
initial law :math:`\pi C` emits the future :math:`f_r` from state
:math:`r`. This follows by induction on word length. The generator
therefore produces the same process.

The result is a :class:`~sofic.generators.mealy.MealyHMM`. It is in general not
unifilar, and it has at most as many states as the ε-machine. When the morphs
are affinely independent, every morph is extreme and the result is the
ε-machine itself. This holds for every two-state ε-machine, such as the golden
mean and even processes.

A strictly smaller example
==========================

Take two hidden states ``a`` and ``b``. Symbols ``2`` and ``3`` lead to ``a`` and
``b`` from either state. Symbol ``0`` is emitted with the same probability from
both states and keeps the state. Symbol ``1`` is emitted only by ``a`` and moves
to ``a`` or ``b`` with probabilities in the ratio ``split : 1 - split``. The
recurrent beliefs are ``a``, ``b`` and the mixture ``(split, 1 - split)``, so
the ε-machine has three causal states. The third morph is a convex combination
of the other two, and the canonical residual HMM has two states. With the
defaults used in the tests (``split = 1/2``) the ε-machine has statistical
complexity 1.55 bits and the canonical residual HMM has state entropy 0.99
bits.

Relation to generative complexity
=================================

Löhr and Ay :cite:`LohrAy2009` distinguish prescient models, whose minimal
member is the ε-machine, from generative HMMs, which can be much smaller. Their
Example 3.6 is a two-state HMM with infinitely many causal states. For that
example :func:`canonical_residual_hmm` raises
:class:`~sofic.exceptions.MixedStateExplosionError`, because it needs a finite
ε-machine. The canonical residual HMM is a generator, so its state count and
its state entropy are upper bounds on the minimal generator size and the
minimal generator state entropy. Nothing else is computed. In particular, no
minimality among generators is claimed.

API
===

.. autofunction:: canonical_residual_hmm
95 changes: 95 additions & 0 deletions docs/generators/conditioning.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
.. conditioning.rst
.. py:module:: sofic.generators.conditioning

**************************************
Conditioning on a regular constraint
**************************************

:func:`condition_on_language` conditions a stationary HMM on its output staying
inside the language of a DFA forever: the limit, as :math:`n \to \infty`, of
the process conditioned on every prefix of :math:`X_{0:n}` being accepted.

Construction
============

With symbol matrices :math:`T^{(x)}` and DFA transition function
:math:`\delta`, the product of HMM states with *accepting* DFA states carries
the substochastic matrices

.. math::

M^{(x)}_{(i, q), (j, \delta(q, x))} = T^{(x)}_{ij}
\quad \text{whenever } \delta(q, x) \text{ is accepting.}

The DFA is completed first, so a missing transition is a move to a rejecting
trap. Only states reached from the stationary-positive HMM states paired with
the DFA's initial state are kept.

Surviving paths of length :math:`n` have mass of order :math:`\lambda^n`, where
:math:`\lambda` is the largest Perron root among the strongly connected
components of :math:`M = \sum_x M^{(x)}`, and they spend all but a bounded
number of steps in the component attaining it. That component must be unique;
otherwise the limit depends on how the constraint is entered and a
``ValueError`` is raised. On it, with right and left Perron eigenvectors
:math:`h` and :math:`u`, the conditioned process is the Doob
:math:`h`-transform

.. math::

P'(x, j \mid i) = \frac{M^{(x)}_{ij} h_j}{\lambda h_i},
\qquad \pi'_i \propto u_i h_i,

started in its stationary law :math:`\pi'`. For a 0-1 matrix this is Parry's
measure of maximal entropy :cite:`Parry1964` (:cite:`LindMarcus1995`, §13.3).
States of the result are pairs ``(hmm state, dfa state)``.

Which constraints
=================

The conditioning event is that the DFA run never leaves its accepting states,
i.e. every prefix is accepted. For a prefix-closed language this is just
:math:`X_{0:n} \in L`. For a factorial language, such as the language of a
shift of finite type or sofic shift, the event is also shift invariant, and the
result is the limit of the law of windows :math:`X_{k:k+m}` given
:math:`X_{0:n} \in L` with both :math:`k` and :math:`n - k` large (in the
Cesàro sense when the component is periodic). A language that is not
prefix-closed is effectively replaced by its largest prefix-closed sublanguage.

Example: the Parry measure
==========================

Conditioning the fair coin on the golden mean shift (forbid ``11``) gives the
golden mean process at :math:`p = 1/\varphi`, its measure of maximal entropy,
whose entropy rate is the topological entropy :math:`\log_2 \varphi`. The DFA of
the shift's language is obtained by determinizing its presentation with every
state initial and accepting.

.. ipython::

In [1]: from sofic.automata.nfa import NFA

In [2]: from sofic.examples import bernoulli

In [3]: from sofic.generators.conditioning import condition_on_language

In [4]: from sofic.shifts.sft import ShiftOfFiniteType

In [5]: shift = ShiftOfFiniteType.from_forbidden_words({("1", "1")}, frozenset("01"))

In [6]: states = frozenset(shift.states())

In [7]: dfa = NFA(graph=shift.graph.copy(), input_alphabet=shift.symbol_alphabet,
...: initial_states=states, accepting_states=states).determinize()

@doctest float
In [8]: condition_on_language(bernoulli(), dfa).entropy_rate()
Out[8]: 0.6942419136306173

@doctest float
In [9]: shift.topological_entropy()
Out[9]: 0.6942419136306162

API
===

.. autofunction:: condition_on_language
Loading
Loading