Skip to content

Automata & Formal Languages (algebrax.automata)

algebrax.automata provides transition simulation and Kleene reachability closure over state machines and formal grammars:

  • simulate_dfa / dfa_step: Evaluates Deterministic Finite Automaton paths over symbol sequences.
  • simulate_nfa / nfa_step: Evaluates Non-Deterministic, Probabilistic, and Weighted Finite Automata over arbitrary semirings (BooleanSemiring, TropicalSemiring, ViterbiSemiring, StringSemiring, or default float). Always returns a fresh copy on empty input sequences.
  • nfa_closure: Projects an NFA transition tensor into a sparse matrix and computes all-symbol (symbol=None) or single-symbol/epsilon Kleene closure via matrix_star for any StarSemiring (HasStar).

Weighted Finite Automata & Kleene Closure (simulate_nfa, nfa_closure)

Passing a semiring to nfa_step or simulate_nfa turns the same NFA transition tensor into reachability (BooleanSemiring), minimum-cost pathfinding (TropicalSemiring), most-probable path decoding (ViterbiSemiring), or formal language transduction (StringSemiring):

from algebrax.automata import nfa_closure, simulate_nfa
from algebrax.semiring import BooleanSemiring, StringSemiring, TropicalSemiring, ViterbiSemiring

# Shortest-path Weighted Finite Automaton over TropicalSemiring
trop_trans = {
    'q0': {'a': {'q1': 2.0, 'q2': 5.0}},
    'q1': {'b': {'q3': 10.0}},
    'q2': {'b': {'q3': 1.0}},
}
assert simulate_nfa({'q0': 0.0}, ['a', 'b'], trop_trans, semiring=TropicalSemiring) == {'q3': 6.0}

# All-pairs minimum-cost Kleene closure (symbol=None sums across the alphabet)
dist = nfa_closure(trop_trans, semiring=TropicalSemiring)
assert dist['q0']['q0'] == 0.0 and dist['q0']['q3'] == 6.0

# Epsilon-closure (single-symbol Kleene star over BooleanSemiring)
eps_trans = {'q0': {'eps': {'q1': True}, 'a': {'q2': True}}, 'q1': {'eps': {'q3': True}}}
eps = nfa_closure(eps_trans, symbol='eps', semiring=BooleanSemiring)
assert eps['q0']['q3'] is True and 'q2' not in eps['q0']

# Formal language transduction over StringSemiring (simulate_nfa works; nfa_closure requires HasStar)
str_trans = {'q0': {'a': {'q1': {'x'}}}, 'q1': {'b': {'q2': {'1'}}}}
assert simulate_nfa({'q0': {''}}, ['a', 'b'], str_trans, semiring=StringSemiring) == {'q2': {'x1'}}

CYK Parsing (Context-Free Grammars)

The CYK Algorithm parses a string using a Context-Free Grammar (CFG). Surprisingly, this is just Matrix Multiplication!

  • Values: Sets of Non-Terminals (e.g., {NP, VP}).
  • Add: Set Union (\(\cup\)).
  • Mul: Grammar Production Rule Application.
    • \(A \otimes B = \{C \mid C \to A B \text{ is a rule}\}\).

This allows us to parse a sentence of length \(N\) by computing the transitive closure of a chart matrix.

import algebrax as ax
from typing import Set, Dict, Tuple

# Grammar (Chomsky Normal Form)
# S -> NP VP
# NP -> 'I' | 'Python'
# VP -> V NP
# V -> 'love'
rules = {('NP', 'VP'): {'S'}, ('V', 'NP'): {'VP'}}
lexicon = {'I': {'NP'}, 'love': {'V'}, 'Python': {'NP'}}


class GrammarSemiring(ax.semiring.Semiring[Set[str]]):
    @property
    def zero(self) -> Set[str]:
        return set()

    @property
    def one(self) -> Set[str]:
        # Identity for multiplication is tricky here.
        # Ideally, a special 'Identity' non-terminal, but for CYK we usually
        # don't need the identity matrix, just the closure.
        return set()

    def add(self, a: Set[str], b: Set[str]) -> Set[str]:
        return a | b

    def mul(self, a: Set[str], b: Set[str]) -> Set[str]:
        # Apply rules: If we have non-terminals A in 'a' and B in 'b',
        # look for rules C -> A B.
        res = set()
        for lhs in a:
            for rhs in b:
                if (lhs, rhs) in rules:
                    res.update(rules[(lhs, rhs)])
        return res

    def star(self, a: Set[str]) -> Set[str]:
        # Kleene star closure: 1 | a
        return self.one | a


# Sentence: "I love Python"
sentence = ['I', 'love', 'Python']
n = len(sentence)

# Initialize Chart (Upper Triangular Matrix)
# chart[i][j] contains non-terminals spanning words i to j
# But standard matrix multiplication works on indices differently.
# CYK is usually dynamic programming.
# To do it as Matrix Mul (Valiant's Algorithm), we treat the chart as an adjacency matrix.
# Edge i->j means "span from i to j".

# Initialize spans of length 1 (Diagonal + 1)
chart = {}
for i, word in enumerate(sentence):
    if i not in chart:
        chart[i] = {}
    chart[i][i + 1] = lexicon[word]

# CYK Step: Combine spans
# Span(i, k) = Span(i, j) * Span(j, k)
# This is exactly Matrix Multiplication!
# chart = chart + chart * chart
# We iterate this n times.

semiring = GrammarSemiring()

for _ in range(n):
    # New spans = Old spans * Old spans
    new_spans = ax.matrix.dot(chart, chart, semiring=semiring)

    # Union with existing spans (Add)
    for r, row in new_spans.items():
        if r not in chart:
            chart[r] = {}
        for c, val in row.items():
            current = chart[r].get(c, set())
            chart[r][c] = current | val

# Check if 'S' spans the whole sentence (0 to n)
final_tags = chart.get(0, {}).get(n, set())
print(f'Parses as: {final_tags}')
# output: {'S'}