Skip to content
Closed
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
187 changes: 187 additions & 0 deletions project/adjacency_matrix_fa.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
from collections import defaultdict
from collections.abc import Iterable

from pyformlang.finite_automaton import NondeterministicFiniteAutomaton, State, Symbol
from scipy.sparse import csr_matrix, eye, kron


class AdjacencyMatrixFA:
"""
Finite automaton represented by a boolean sparse matrix for each symbol.

Attributes:
states: Original states in matrix row and column order, including isolated states.
start_states: Indices of initial states in states.
final_states: Indices of accepting states in states.
matrices: Symbol-to-matrix mapping. Entry (i, j) is true when the automaton
has a transition from states[i] to states[j] on that symbol.
"""

def __init__(self, automaton: NondeterministicFiniteAutomaton) -> None:
"""
Build a matrix representation of a DFA or an NFA without epsilon transitions.

Args:
automaton: Automaton to convert. Its states and transitions are copied.
"""
states = tuple(automaton.states)
indices = {state: index for index, state in enumerate(states)}
start_states = {indices[state] for state in automaton.start_states}
final_states = {indices[state] for state in automaton.final_states}

transitions = defaultdict(list)
for source, symbol, target in automaton:
transitions[symbol].append((indices[source], indices[target]))

matrices = {}
for symbol, edges in transitions.items():
rows, columns = zip(*edges)
matrices[symbol] = csr_matrix(
([True] * len(edges), (rows, columns)),
shape=(len(states), len(states)),
dtype=bool,
)

self._initialize(states, start_states, final_states, matrices)

def _initialize(
self,
states: tuple[State, ...],
start_states: set[int],
final_states: set[int],
matrices: dict[Symbol, csr_matrix],
) -> None:
"""Store components using one common ordering of states."""
self.states = states
self.start_states = start_states
self.final_states = final_states
self.matrices = matrices

@classmethod
def _from_matrices(
cls,
states: tuple[State, ...],
start_states: set[int],
final_states: set[int],
matrices: dict[Symbol, csr_matrix],
) -> "AdjacencyMatrixFA":
"""Build from already computed boolean CSR matrices and matching indices."""
automaton = cls.__new__(cls)
automaton._initialize(states, start_states, final_states, matrices)
return automaton

@property
def num_states(self) -> int:
"""Number of states, including isolated states."""
return len(self.states)

def accepts(self, word: Iterable[Symbol]) -> bool:
"""
Check whether the automaton accepts a word.

Args:
word: Iterable of symbols or their raw values. A multicharacter label
is one symbol; an empty iterable represents the empty word.

Returns:
bool: Whether the word leads from an initial state to an accepting state.
"""
current = csr_matrix(
(
[True] * len(self.start_states),
([0] * len(self.start_states), list(self.start_states)),
),
shape=(1, self.num_states),
dtype=bool,
)
for symbol in word:
if not isinstance(symbol, Symbol):
symbol = Symbol(symbol)
matrix = self.matrices.get(symbol)
if matrix is None:
return False
current = current @ matrix
if current.nnz == 0:
return False

return bool(self.final_states.intersection(current.indices))

def transitive_closure(self) -> csr_matrix:
"""
Compute reachability between all pairs of states, ignoring transition labels.

Note:
The closure is reflexive: every state reaches itself via the empty path.
Repeated boolean squaring doubles the maximum path length each round.

Returns:
csr_matrix: Boolean matrix in the same state order as the transition matrices.
"""
closure = eye(self.num_states, format="csr", dtype=bool)
for matrix in self.matrices.values():
closure = closure + matrix

while True:
expanded = closure + closure @ closure
if expanded.nnz == closure.nnz:
return expanded
closure = expanded

def is_empty(self) -> bool:
"""
Check whether the language of the automaton is empty.

Returns:
bool: True if no accepting state is reachable from any initial state,
including paths of length zero.
"""
if not self.start_states or not self.final_states:
return True
if self.start_states & self.final_states:
return False
closure = self.transitive_closure()
return closure[list(self.start_states)][:, list(self.final_states)].nnz == 0


def intersect_automata(
automaton1: AdjacencyMatrixFA, automaton2: AdjacencyMatrixFA
) -> AdjacencyMatrixFA:
"""
Intersect two automata using the Kronecker product of their transition matrices.

Note:
Only transitions with the same symbol are synchronized. Product state (i, j)
has index i * automaton2.num_states + j, matching scipy.sparse.kron.

Args:
automaton1: First automaton. It is not modified.
automaton2: Second automaton. It is not modified.

Returns:
AdjacencyMatrixFA: Automaton accepting exactly the words accepted by both
inputs. Each state value is a pair of the corresponding input state values.
"""
states = tuple(
State((left.value, right.value))
for left in automaton1.states
for right in automaton2.states
)
start_states = {
left * automaton2.num_states + right
for left in automaton1.start_states
for right in automaton2.start_states
}
final_states = {
left * automaton2.num_states + right
for left in automaton1.final_states
for right in automaton2.final_states
}
matrices = {
symbol: kron(
automaton1.matrices[symbol], automaton2.matrices[symbol], format="csr"
)
for symbol in automaton1.matrices.keys() & automaton2.matrices.keys()
}
return AdjacencyMatrixFA._from_matrices(
states, start_states, final_states, matrices
)
57 changes: 57 additions & 0 deletions project/automata_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
from networkx import MultiDiGraph
from pyformlang.finite_automaton import (
DeterministicFiniteAutomaton,
NondeterministicFiniteAutomaton,
)
from pyformlang.regular_expression import Regex


def regex_to_dfa(regex: str) -> DeterministicFiniteAutomaton:
"""
Build a minimal DFA for a regular expression.

Args:
regex: Expression using | for union, a space or . for concatenation,
* for repetition and epsilon for the empty word.

Returns:
DeterministicFiniteAutomaton: Minimal DFA accepting the expression's language.
"""
return Regex(regex).to_epsilon_nfa().to_deterministic().minimize()


def graph_to_nfa(
graph: MultiDiGraph, start_states: set[int], final_states: set[int]
) -> NondeterministicFiniteAutomaton:
"""
Convert graph vertices to NFA states and labeled edges to transitions.

Args:
graph: Directed multigraph with edge symbols in the label attribute.
start_states: Initial vertices; an empty set means all graph vertices.
final_states: Accepting vertices; an empty set independently means all vertices.

Returns:
NondeterministicFiniteAutomaton: NFA accepting labels of paths from
initial to accepting vertices.

Raises:
ValueError: A specified initial or accepting vertex is absent from the graph.
"""
nodes = set(graph.nodes)
if not start_states.issubset(nodes) or not final_states.issubset(nodes):
raise ValueError("Start and final states must be vertices of the graph")

nfa = NondeterministicFiniteAutomaton(states=nodes)

for vertex in graph:
if not start_states or vertex in start_states:
nfa.add_start_state(vertex)

if not final_states or vertex in final_states:
nfa.add_final_state(vertex)

for source, target, data in graph.out_edges(vertex, data=True):
nfa.add_transition(source, data["label"], target)

return nfa
151 changes: 151 additions & 0 deletions project/graph_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
from dataclasses import dataclass
from pathlib import Path

import cfpq_data
import pydot
from networkx import MultiDiGraph


@dataclass
class GraphInfo:
"""Node and edge counts and unique edge labels of a graph."""

num_nodes: int
num_edges: int
labels: set[str]


def load_graph(graph_name: str) -> MultiDiGraph:
"""
Load a graph from CFPQ_Data and return it.

Args:
graph_name: Name of the graph in the CFPQ_Data.

Returns:
MultiDiGraph: Graph loaded via name from CFPQ_Data.

Raises:
FileNotFoundError: The graph name is not in the CFPQ_Data dataset.
"""

graph_path = cfpq_data.download(graph_name)
return cfpq_data.graph_from_csv(graph_path)


def load_graph_info(graph_name: str) -> GraphInfo:
"""
Load a graph from CFPQ_Data and return its basic information.

Args:
graph_name: Name of the graph in the CFPQ_Data.

Returns:
GraphInfo with node and edge counts and set of unique edge labels.

Raises:
FileNotFoundError: The graph name is not in the CFPQ_Data dataset.
"""
graph = load_graph(graph_name)

return GraphInfo(
num_nodes=graph.number_of_nodes(),
num_edges=graph.number_of_edges(),
labels={data["label"] for _, _, data in graph.edges(data=True)},
)


def create_two_cycles_graph(
num_first_cycle_nodes: int,
first_cycle_label: str,
num_second_cycle_nodes: int,
second_cycle_label: str,
) -> MultiDiGraph:
"""
Create a graph with two cycles sharing a node.

Note:
Cycle sizes exclude the shared node. A zero-sized cycle is represented by a self-loop.

Args:
num_first_cycle_nodes: Number of nodes in the first cycle, excluding the shared node.
first_cycle_label: Label on edges of first cycle in the final graph.

num_second_cycle_nodes: Number of nodes in the second cycle, excluding the shared node.
second_cycle_label: Label on edges of second cycle in the final graph.

Returns:
MultiDiGraph: Final two cycles labeled graph.

Raises:
ValueError: Negative cycle size.
"""

if num_first_cycle_nodes < 0 or num_second_cycle_nodes < 0:
raise ValueError("Cycle sizes must be non-negative")

if num_first_cycle_nodes == 0:
graph = cfpq_data.labeled_cycle_graph(
num_second_cycle_nodes + 1,
label=second_cycle_label,
)
graph.add_edge(0, 0, label=first_cycle_label)
elif num_second_cycle_nodes == 0:
graph = cfpq_data.labeled_cycle_graph(
num_first_cycle_nodes + 1,
label=first_cycle_label,
)
graph.add_edge(0, 0, label=second_cycle_label)
else:
graph = cfpq_data.labeled_two_cycles_graph(
num_first_cycle_nodes,
num_second_cycle_nodes,
labels=(first_cycle_label, second_cycle_label),
)

return graph


def save_two_cycles_graph(
num_first_cycle_nodes: int,
first_cycle_label: str,
num_second_cycle_nodes: int,
second_cycle_label: str,
output_path: str | Path,
) -> None:
"""
Create a graph with two cycles sharing a node and save it as DOT.

Note:
Cycle sizes exclude the shared node. A zero-sized cycle is represented by a self-loop.

Args:
num_first_cycle_nodes: Number of nodes in the first cycle, excluding the shared node.
first_cycle_label: Label on edges of first cycle in the final graph.

num_second_cycle_nodes: Number of nodes in the second cycle, excluding the shared node.
second_cycle_label: Label on edges of second cycle in the final graph.

output_path: Path to the output DOT file. An existing file is overwritten.

Raises:
ValueError: Negative cycle size.
"""

graph = create_two_cycles_graph(
num_first_cycle_nodes,
first_cycle_label,
num_second_cycle_nodes,
second_cycle_label,
)

dot_graph = pydot.Dot(graph_type="digraph", strict=False)
for node in graph.nodes:
dot_graph.add_node(pydot.Node(str(node)))

for source, target, data in graph.edges(data=True):
# make_quoted escapes quotes but leaves backslashes unchanged.
label = pydot.make_quoted(data["label"].replace("\\", "\\\\"))
dot_graph.add_edge(pydot.Edge(str(source), str(target), label=label))

dot_graph.write_raw(output_path, encoding="utf-8")
Loading