diff --git a/project/adjacency_matrix_fa.py b/project/adjacency_matrix_fa.py new file mode 100644 index 000000000..fc1a511fd --- /dev/null +++ b/project/adjacency_matrix_fa.py @@ -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 + ) diff --git a/project/automata_utils.py b/project/automata_utils.py new file mode 100644 index 000000000..2a4fd5ca1 --- /dev/null +++ b/project/automata_utils.py @@ -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 diff --git a/project/graph_utils.py b/project/graph_utils.py new file mode 100644 index 000000000..ba9b456d4 --- /dev/null +++ b/project/graph_utils.py @@ -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") diff --git a/project/rpq.py b/project/rpq.py new file mode 100644 index 000000000..ead81e8e8 --- /dev/null +++ b/project/rpq.py @@ -0,0 +1,46 @@ +from networkx import MultiDiGraph + +from project.adjacency_matrix_fa import AdjacencyMatrixFA, intersect_automata +from project.automata_utils import graph_to_nfa, regex_to_dfa + + +def tensor_based_rpq( + regex: str, graph: MultiDiGraph, start_nodes: set[int], final_nodes: set[int] +) -> set[tuple[int, int]]: + """ + Find vertex pairs connected by a path matching a regular expression. + + Note: + Paths of length zero are included if the expression accepts the empty word. + + Args: + regex: Regular expression in the format accepted by regex_to_dfa. + graph: Directed multigraph with edge symbols in the label attribute. + start_nodes: Initial vertices; an empty set means all graph vertices. + final_nodes: Accepting vertices; an empty set independently means all vertices. + + Returns: + set[tuple[int, int]]: Matching pairs of original graph vertex identifiers. + + Raises: + ValueError: A specified initial or accepting vertex is absent from the graph. + """ + graph_fa = AdjacencyMatrixFA( + graph_to_nfa(graph, set(start_nodes), set(final_nodes)) + ) + regex_fa = AdjacencyMatrixFA(regex_to_dfa(regex)) + product = intersect_automata(graph_fa, regex_fa) + if not product.start_states or not product.final_states: + return set() + + start_states = list(product.start_states) + final_states = list(product.final_states) + reachable = product.transitive_closure()[start_states][:, final_states].tocoo() + + result = set() + for row, column in zip(reachable.row, reachable.col): + source, _ = product.states[start_states[row]].value + target, _ = product.states[final_states[column]].value + result.add((source, target)) + + return result diff --git a/tests/autotests/test_task02.py b/tests/autotests/test_task02.py index 67ae5cc14..c498b9805 100644 --- a/tests/autotests/test_task02.py +++ b/tests/autotests/test_task02.py @@ -14,7 +14,7 @@ # Fix import statements in try block to run tests try: - from project.task2 import regex_to_dfa, graph_to_nfa + from project.automata_utils import regex_to_dfa, graph_to_nfa except ImportError: pytestmark = pytest.mark.skip("Task 2 is not ready to test!") diff --git a/tests/autotests/test_task03.py b/tests/autotests/test_task03.py index 321d73494..9775ed3cd 100644 --- a/tests/autotests/test_task03.py +++ b/tests/autotests/test_task03.py @@ -12,8 +12,9 @@ # Fix import statements in try block to run tests try: - from project.task2 import regex_to_dfa - from project.task3 import intersect_automata, AdjacencyMatrixFA, tensor_based_rpq + from project.adjacency_matrix_fa import AdjacencyMatrixFA, intersect_automata + from project.automata_utils import regex_to_dfa + from project.rpq import tensor_based_rpq except ImportError: pytestmark = pytest.mark.skip("Task 3 is not ready to test!") diff --git a/tests/data/graph_with_parallel_edges.csv b/tests/data/graph_with_parallel_edges.csv new file mode 100644 index 000000000..4913fe44b --- /dev/null +++ b/tests/data/graph_with_parallel_edges.csv @@ -0,0 +1,4 @@ +0 1 a +0 1 a +1 1 b +1 2 b diff --git a/tests/data/two_cycles_5_8.dot b/tests/data/two_cycles_5_8.dot new file mode 100644 index 000000000..7becb7fd8 --- /dev/null +++ b/tests/data/two_cycles_5_8.dot @@ -0,0 +1,18 @@ +digraph { + 0 -> 1 [label="a"]; + 1 -> 2 [label="a"]; + 2 -> 3 [label="a"]; + 3 -> 4 [label="a"]; + 4 -> 5 [label="a"]; + 5 -> 0 [label="a"]; + + 0 -> 6 [label="b"]; + 6 -> 7 [label="b"]; + 7 -> 8 [label="b"]; + 8 -> 9 [label="b"]; + 9 -> 10 [label="b"]; + 10 -> 11 [label="b"]; + 11 -> 12 [label="b"]; + 12 -> 13 [label="b"]; + 13 -> 0 [label="b"]; +} diff --git a/tests/test_adjacency_matrix_fa.py b/tests/test_adjacency_matrix_fa.py new file mode 100644 index 000000000..fc8197593 --- /dev/null +++ b/tests/test_adjacency_matrix_fa.py @@ -0,0 +1,354 @@ +from collections.abc import Hashable, Iterable +from copy import deepcopy +from itertools import product +from random import Random + +import pytest +from pyformlang.finite_automaton import NondeterministicFiniteAutomaton, State, Symbol +from scipy.sparse import issparse + +from project.adjacency_matrix_fa import AdjacencyMatrixFA, intersect_automata +from project.automata_utils import regex_to_dfa + + +def _make_nfa( + transitions: Iterable[tuple[Hashable, str, Hashable]] = (), + starts: Iterable[Hashable] = (), + finals: Iterable[Hashable] = (), + states: Iterable[Hashable] = (), +) -> NondeterministicFiniteAutomaton: + """Build an NFA with explicit transitions and endpoint sets.""" + nfa = NondeterministicFiniteAutomaton(states=set(states)) + nfa.add_transitions(transitions) + for state in starts: + nfa.add_start_state(state) + for state in finals: + nfa.add_final_state(state) + return nfa + + +def _matrix_transitions( + automaton: AdjacencyMatrixFA, +) -> set[tuple[Hashable, Hashable, Hashable]]: + """Decode transitions and check that all matrices use the declared state space.""" + transitions = set() + for symbol, matrix in automaton.matrices.items(): + assert issparse(matrix), f"Matrix for {symbol} must be sparse" + assert matrix.dtype == bool, f"Matrix for {symbol} must be boolean" + assert matrix.shape == (len(automaton.states), len(automaton.states)), symbol + for row, column in zip(*matrix.nonzero()): + transitions.add( + ( + automaton.states[row].value, + symbol.value, + automaton.states[column].value, + ) + ) + return transitions + + +@pytest.fixture +def branching_nfa(): + return _make_nfa( + [("s", "a", 10), ("s", "a", 20), (10, "b", "f"), (20, "c", "f")], + starts=["s"], + finals=["f"], + states=[("isolated", 0)], + ) + + +def test_constructor_preserves_isolated_states(branching_nfa): + matrix_fa = AdjacencyMatrixFA(branching_nfa) + + assert set(matrix_fa.states) == { + State(s) for s in ["s", 10, 20, "f", ("isolated", 0)] + } + + +def test_constructor_preserves_labeled_transitions_in_boolean_sparse_matrices( + branching_nfa, +): + matrix_fa = AdjacencyMatrixFA(branching_nfa) + + actual = _matrix_transitions(matrix_fa) + assert actual == {("s", "a", 10), ("s", "a", 20), (10, "b", "f"), (20, "c", "f")} + + +def test_constructor_language_is_independent_of_source_changes(): + nfa = _make_nfa([(0, "a", 1)], starts=[0], finals=[1]) + matrix_fa = AdjacencyMatrixFA(nfa) + + # Replace the source language {a} with b* using new states and transitions. + nfa.remove_transition(0, "a", 1) + nfa.remove_start_state(0) + nfa.remove_final_state(1) + nfa.add_transition(2, "b", 2) + nfa.add_start_state(2) + nfa.add_final_state(2) + + assert matrix_fa.accepts(["a"]) + assert not matrix_fa.accepts(["b"]) + assert not matrix_fa.accepts([]) + + +@pytest.mark.parametrize( + ("word", "expected"), + [ + pytest.param(("a", "b"), True, id="first-nondeterministic-branch"), + pytest.param(("a", "c"), True, id="second-nondeterministic-branch"), + pytest.param((), False, id="empty-word-with-distinct-endpoints"), + pytest.param(("a",), False, id="nonfinal-prefix"), + pytest.param(("a", "b", "c"), False, id="extra-symbol"), + pytest.param(("b", "a"), False, id="wrong-order"), + pytest.param(("x",), False, id="unknown-symbol"), + pytest.param(("a", "a"), False, id="known-symbol-with-no-transition"), + ], +) +def test_accepts_nondeterministic_words(branching_nfa, word, expected): + assert AdjacencyMatrixFA(branching_nfa).accepts(word) is expected + + +def test_accepts_symbol_iterator_with_multicharacter_label(): + matrix_fa = AdjacencyMatrixFA(regex_to_dfa("label other")) + + assert matrix_fa.accepts(Symbol(label) for label in ["label", "other"]) + + +def test_accepts_does_not_split_multicharacter_symbols(): + assert not AdjacencyMatrixFA(regex_to_dfa("label")).accepts("label") + + +@pytest.mark.parametrize( + ("starts", "finals", "transitions", "expected"), + [ + pytest.param([], [1], [(0, "a", 1)], True, id="no-starts"), + pytest.param([0], [], [(0, "a", 1)], True, id="no-finals"), + pytest.param([0], [1], [], True, id="disconnected-isolated-states"), + pytest.param([0], [0], [], False, id="epsilon-only"), + pytest.param([0], [1], [(0, "a", 1)], False, id="one-transition"), + pytest.param([1], [0], [(0, "a", 1)], True, id="opposite-direction"), + pytest.param( + [0], [2], [(0, "a", 1), (1, "b", 0)], True, id="nonaccepting-cycle" + ), + pytest.param([0, 1], [2, 3], [(1, "a", 3)], False, id="multiple-endpoints"), + ], +) +def test_is_empty_checks_reachability(starts, finals, transitions, expected): + matrix_fa = AdjacencyMatrixFA(_make_nfa(transitions, starts, finals)) + + assert matrix_fa.is_empty() is expected + + +def test_empty_automaton_rejects_empty_word(): + matrix_fa = AdjacencyMatrixFA(NondeterministicFiniteAutomaton()) + + assert not matrix_fa.accepts(()) + + +def test_empty_automaton_has_empty_language(): + matrix_fa = AdjacencyMatrixFA(NondeterministicFiniteAutomaton()) + + assert matrix_fa.is_empty() + + +def test_closure_of_empty_automaton(): + matrix_fa = AdjacencyMatrixFA(NondeterministicFiniteAutomaton()) + + closure = matrix_fa.transitive_closure() + + assert issparse(closure) + assert closure.dtype == bool + assert closure.shape == (0, 0) + + +def test_closure_includes_long_directed_paths_and_zero_length_paths(): + matrix_fa = AdjacencyMatrixFA(_make_nfa([(i, "a", i + 1) for i in range(9)])) + + closure = matrix_fa.transitive_closure() + reachable = { + (matrix_fa.states[i].value, matrix_fa.states[j].value) + for i, j in zip(*closure.nonzero()) + } + + assert issparse(closure) + assert closure.dtype == bool + assert reachable == {(i, j) for i in range(10) for j in range(i, 10)} + + +@pytest.mark.parametrize( + ("word", "expected"), + [ + pytest.param((), True, id="shared-empty-word"), + pytest.param(("b", "b", "b"), True, id="shared-symbol"), + pytest.param(("a",), False, id="left-only-symbol"), + pytest.param(("c",), False, id="right-only-symbol"), + pytest.param(("b", "a"), False, id="word-outside-intersection"), + ], +) +def test_intersection_language(word, expected): + left = AdjacencyMatrixFA(regex_to_dfa("(a | b)*")) + right = AdjacencyMatrixFA(regex_to_dfa("(b | c)*")) + + assert intersect_automata(left, right).accepts(word) is expected + + +@pytest.mark.parametrize( + ("left", "right", "expected"), + [ + pytest.param("a", "b", True, id="disjoint-alphabets"), + pytest.param("a b", "b a", True, id="same-alphabet-incompatible-order"), + pytest.param("epsilon", "a", True, id="only-one-accepts-empty-word"), + pytest.param("a*", "b*", False, id="only-empty-word-in-common"), + ], +) +def test_intersection_emptiness(left, right, expected): + result = intersect_automata( + AdjacencyMatrixFA(regex_to_dfa(left)), AdjacencyMatrixFA(regex_to_dfa(right)) + ) + + assert result.is_empty() is expected + + +@pytest.mark.parametrize( + "empty_first", [True, False], ids=["left-empty", "right-empty"] +) +def test_intersection_with_no_states_has_empty_language(empty_first): + empty = AdjacencyMatrixFA(NondeterministicFiniteAutomaton()) + nonempty = AdjacencyMatrixFA(regex_to_dfa("a*")) + left, right = (empty, nonempty) if empty_first else (nonempty, empty) + + result = intersect_automata(left, right) + + assert result.is_empty() + + +def test_intersection_does_not_modify_inputs(): + left = AdjacencyMatrixFA(regex_to_dfa("a b*")) + right = AdjacencyMatrixFA(regex_to_dfa("a* | b")) + before = deepcopy((left, right)) + + intersect_automata(left, right) + + for actual, expected in zip((left, right), before): + assert actual.states == expected.states + assert actual.start_states == expected.start_states + assert actual.final_states == expected.final_states + assert actual.matrices.keys() == expected.matrices.keys() + for symbol in expected.matrices: + assert (actual.matrices[symbol] != expected.matrices[symbol]).nnz == 0 + + +def test_intersection_state_pairs_match_their_transitions(): + left = AdjacencyMatrixFA( + _make_nfa([(10, "a", 20), (10, "b", 30)], starts=[10], finals=[20, 30]) + ) + right = AdjacencyMatrixFA( + _make_nfa([("s", "a", "f"), ("s", "c", "s")], starts=["s"], finals=["f"]) + ) + + intersection = intersect_automata(left, right) + + assert {intersection.states[i].value for i in intersection.start_states} == { + (10, "s") + } + assert {intersection.states[i].value for i in intersection.final_states} == { + (20, "f"), + (30, "f"), + } + assert _matrix_transitions(intersection) == {((10, "s"), "a", (20, "f"))} + + +@pytest.mark.parametrize( + ("word", "expected"), + [ + pytest.param((), False, id="rejects-empty-word"), + pytest.param(("b",), True, id="accepts-common-word"), + pytest.param(("b", "b"), False, id="rejects-repetition"), + ], +) +def test_intersection_can_be_intersected_again(word, expected): + first = intersect_automata( + AdjacencyMatrixFA(regex_to_dfa("a | b")), + AdjacencyMatrixFA(regex_to_dfa("b | c")), + ) + + result = intersect_automata(first, AdjacencyMatrixFA(regex_to_dfa("b*"))) + + assert result.accepts(word) == expected + + +def _random_nfa(rng: Random) -> NondeterministicFiniteAutomaton: + """Generate a small NFA with independently chosen transitions and endpoints.""" + states = range(rng.randrange(1, 6)) + return _make_nfa( + [ + (s, label, t) + for s, label, t in product(states, "ab", states) + if rng.random() < 0.25 + ], + starts=[s for s in states if rng.random() < 0.5], + finals=[s for s in states if rng.random() < 0.5], + states=states, + ) + + +def _describe_nfa(nfa: NondeterministicFiniteAutomaton) -> str: + """Include endpoints as well as transitions in generated test failures.""" + return ( + f"states={nfa.states}, starts={nfa.start_states}, " + f"finals={nfa.final_states}, transitions={nfa.to_dict()}" + ) + + +@pytest.mark.parametrize("seed", range(12)) +def test_matrix_acceptance_matches_nfa_on_generated_inputs(seed): + nfa = _random_nfa(Random(seed)) + matrix_fa = AdjacencyMatrixFA(nfa) + + for length in range(5): + for word in product("ab", repeat=length): + assert matrix_fa.accepts(word) == nfa.accepts(word), ( + seed, + word, + _describe_nfa(nfa), + ) + + +@pytest.mark.parametrize("seed", range(12)) +def test_matrix_emptiness_matches_nfa_on_generated_inputs(seed): + nfa = _random_nfa(Random(seed)) + + assert AdjacencyMatrixFA(nfa).is_empty() == nfa.is_empty(), ( + seed, + _describe_nfa(nfa), + ) + + +@pytest.mark.parametrize("seed", range(12)) +def test_intersection_acceptance_matches_both_nfas_on_generated_inputs(seed): + rng = Random(seed) + left, right = _random_nfa(rng), _random_nfa(rng) + result = intersect_automata(AdjacencyMatrixFA(left), AdjacencyMatrixFA(right)) + + for length in range(5): + for word in product("ab", repeat=length): + expected = left.accepts(word) and right.accepts(word) + assert result.accepts(word) == expected, ( + seed, + word, + _describe_nfa(left), + _describe_nfa(right), + ) + + +@pytest.mark.parametrize("seed", range(12)) +def test_intersection_emptiness_matches_nfas_on_generated_inputs(seed): + rng = Random(seed) + left, right = _random_nfa(rng), _random_nfa(rng) + result = intersect_automata(AdjacencyMatrixFA(left), AdjacencyMatrixFA(right)) + + assert result.is_empty() == left.get_intersection(right).is_empty(), ( + seed, + _describe_nfa(left), + _describe_nfa(right), + ) diff --git a/tests/test_automata_utils.py b/tests/test_automata_utils.py new file mode 100644 index 000000000..39894d5b2 --- /dev/null +++ b/tests/test_automata_utils.py @@ -0,0 +1,177 @@ +import pytest +from networkx import MultiDiGraph +from pyformlang.finite_automaton import State + +from project.automata_utils import graph_to_nfa, regex_to_dfa + + +@pytest.mark.parametrize( + ("regex", "word"), + [ + pytest.param("a | b", (), id="union-rejects-empty-word"), + pytest.param("a | b", ("a", "b"), id="union-is-not-concatenation"), + pytest.param("a b", ("b", "a"), id="concatenation-preserves-order"), + pytest.param("a b", ("a",), id="incomplete-word"), + pytest.param("a b", ("a", "b", "b"), id="extra-symbol"), + pytest.param("a b*", ("b",), id="star-does-not-make-prefix-optional"), + pytest.param("(a | b)* a", ("a", "b"), id="required-suffix"), + pytest.param("(a | b)*", ("c",), id="unknown-symbol"), + ], +) +def test_regex_to_dfa_rejects_words_outside_the_language(regex, word): + dfa = regex_to_dfa(regex) + + assert not dfa.accepts(word) + + +@pytest.mark.parametrize( + ("word", "expected"), + [ + pytest.param((), True, id="empty-word"), + pytest.param(("a",), False, id="nonempty-word"), + ], +) +def test_regex_to_dfa_epsilon_language(word, expected): + dfa = regex_to_dfa("epsilon") + + assert dfa.accepts(word) == expected + + +@pytest.mark.parametrize( + ("word", "expected"), + [ + pytest.param(("label",), True, id="whole-symbol"), + pytest.param(tuple("label"), False, id="separate-characters"), + ], +) +def test_regex_to_dfa_multicharacter_symbol(word, expected): + dfa = regex_to_dfa("label") + + assert dfa.accepts(word) == expected + + +@pytest.fixture +def path_graph(): + graph = MultiDiGraph() + graph.add_edge(10, 20, label="a") + graph.add_edge(20, 30, label="b") + return graph + + +@pytest.mark.parametrize( + ("starts", "finals", "word"), + [ + pytest.param({20}, {30}, ("a", "b"), id="wrong-start"), + pytest.param({10}, {20}, ("a", "b"), id="wrong-final"), + pytest.param({30}, {10}, ("b", "a"), id="reversed-edges"), + pytest.param({10}, {30}, ("a", "c"), id="missing-transition"), + ], +) +def test_graph_to_nfa_rejects_invalid_paths(path_graph, starts, finals, word): + nfa = graph_to_nfa(path_graph, starts, finals) + + assert not nfa.accepts(word) + + +@pytest.mark.parametrize( + ("starts", "finals"), + [ + pytest.param({10, 40}, {30}, id="unknown-start"), + pytest.param({10}, {30, 40}, id="unknown-final"), + ], +) +def test_graph_to_nfa_rejects_unknown_vertices(path_graph, starts, finals): + with pytest.raises(ValueError): + graph_to_nfa(path_graph, starts, finals) + + +def test_graph_to_nfa_only_starts_default_to_all_vertices(path_graph): + nfa = graph_to_nfa(path_graph, set(), {30}) + + assert nfa.start_states == {State(10), State(20), State(30)} + assert nfa.final_states == {State(30)} + + +def test_graph_to_nfa_only_finals_default_to_all_vertices(path_graph): + nfa = graph_to_nfa(path_graph, {10}, set()) + + assert nfa.start_states == {State(10)} + assert nfa.final_states == {State(10), State(20), State(30)} + + +@pytest.mark.parametrize( + "word", + [ + pytest.param(("a", "b"), id="first-branch"), + pytest.param(("a", "c"), id="second-branch"), + ], +) +def test_graph_to_nfa_preserves_both_targets_for_one_label(word): + graph = MultiDiGraph() + graph.add_edge(10, 20, label="a") + graph.add_edge(10, 30, label="a") + graph.add_edge(20, 40, label="b") + graph.add_edge(30, 40, label="c") + + nfa = graph_to_nfa(graph, {10}, {40}) + + assert nfa.accepts(word) + + +@pytest.mark.parametrize("label", ["a", "b"]) +def test_graph_to_nfa_preserves_parallel_edge_labels(label): + graph = MultiDiGraph() + graph.add_edge(10, 20, label="a") + graph.add_edge(10, 20, label="b") + + nfa = graph_to_nfa(graph, {10}, {20}) + + assert nfa.accepts([label]) + + +def test_graph_to_nfa_preserves_self_loop(): + graph = MultiDiGraph() + graph.add_edge(10, 10, label="a") + + nfa = graph_to_nfa(graph, {10}, {10}) + + assert nfa.accepts(["a", "a"]) + + +def test_graph_to_nfa_preserves_multicharacter_label(): + graph = MultiDiGraph() + graph.add_edge(10, 20, label="label") + + nfa = graph_to_nfa(graph, {10}, {20}) + + assert nfa.accepts(["label"]) + + +@pytest.mark.parametrize( + ("finals", "expected"), + [ + pytest.param({10}, True, id="shared-start-and-final"), + pytest.param({20}, False, id="disconnected-start-and-final"), + ], +) +def test_graph_to_nfa_empty_word_on_isolated_vertices(finals, expected): + graph = MultiDiGraph() + graph.add_nodes_from([10, 20]) + + nfa = graph_to_nfa(graph, {10}, finals) + + assert nfa.accepts([]) == expected + + +def test_graph_to_nfa_preserves_isolated_state(path_graph): + path_graph.add_node(40) + + nfa = graph_to_nfa(path_graph, {10}, {30}) + + assert State(40) in nfa.states + + +def test_graph_to_nfa_empty_graph_has_empty_language(): + nfa = graph_to_nfa(MultiDiGraph(), set(), set()) + + assert nfa.is_empty() diff --git a/tests/test_basic.py b/tests/test_basic.py deleted file mode 100644 index a4436c5e5..000000000 --- a/tests/test_basic.py +++ /dev/null @@ -1,18 +0,0 @@ -import pytest # noqa: F401 -import project # on import will print something from __init__ file # noqa: F401 - - -def setup_module(module): - print("basic setup module") - - -def teardown_module(module): - print("basic teardown module") - - -def test_1(): - assert 1 + 1 == 2 - - -def test_2(): - assert "1" + "1" == "11" diff --git a/tests/test_graph_utils.py b/tests/test_graph_utils.py new file mode 100644 index 000000000..9764a02e9 --- /dev/null +++ b/tests/test_graph_utils.py @@ -0,0 +1,223 @@ +from collections import Counter +from pathlib import Path +from unittest.mock import Mock, sentinel + +import networkx as nx +import pydot +import pytest + +from project import graph_utils + + +def _read_dot(path: str | Path) -> pydot.Dot: + """Read a DOT file containing exactly one directed graph.""" + parsed = pydot.graph_from_dot_file(str(path)) + assert parsed is not None + assert len(parsed) == 1 + dot_graph = parsed[0] + assert dot_graph.get_type() == "digraph" + return dot_graph + + +def _read_dot_graph(path: str | Path) -> nx.MultiDiGraph: + """Read a DOT graph into NetworkX, preserving edge labels and multiplicity.""" + dot_graph = _read_dot(path) + graph = nx.MultiDiGraph() + graph.add_nodes_from(node.get_name() for node in dot_graph.get_nodes()) + graph.add_edges_from( + (edge.get_source(), edge.get_destination(), {"label": edge.get_label()}) + for edge in dot_graph.get_edges() + ) + return graph + + +def test_load_graph_passes_downloaded_path_to_reader(monkeypatch): + download = Mock(return_value=sentinel.path) + read = Mock(return_value=sentinel.graph) + monkeypatch.setattr(graph_utils.cfpq_data, "download", download) + monkeypatch.setattr(graph_utils.cfpq_data, "graph_from_csv", read) + + graph = graph_utils.load_graph("example") + + download.assert_called_once_with("example") + read.assert_called_once_with(sentinel.path) + assert graph is sentinel.graph + + +@pytest.mark.parametrize( + ("nodes", "edges", "expected"), + [ + pytest.param([], [], graph_utils.GraphInfo(0, 0, set()), id="empty"), + pytest.param( + [0, 1, 2, 3], + [(0, 1, "a"), (0, 1, "a"), (1, 1, "b")], + graph_utils.GraphInfo(4, 3, {"a", "b"}), + id="isolated-nodes-and-repeated-labels", + ), + ], +) +def test_load_graph_info(monkeypatch, nodes, edges, expected): + graph = nx.MultiDiGraph() + graph.add_nodes_from(nodes) + graph.add_edges_from((u, v, {"label": label}) for u, v, label in edges) + load = Mock(return_value=graph) + monkeypatch.setattr(graph_utils, "load_graph", load) + + info = graph_utils.load_graph_info("example") + + load.assert_called_once_with("example") + assert info == expected + + +def test_load_graph_info_reads_local_csv(monkeypatch): + graph_path = Path(__file__).parent / "data" / "graph_with_parallel_edges.csv" + download = Mock(return_value=str(graph_path)) + monkeypatch.setattr(graph_utils.cfpq_data, "download", download) + + info = graph_utils.load_graph_info("example") + + download.assert_called_once_with("example") + assert info == graph_utils.GraphInfo(3, 4, {"a", "b"}) + + +def test_load_graph_info_rejects_unknown_name(): + with pytest.raises(FileNotFoundError): + graph_utils.load_graph_info("__nonexistent_graph__") + + +def test_create_two_cycles_delegates_positive_sizes(monkeypatch): + generate = Mock(return_value=sentinel.graph) + monkeypatch.setattr(graph_utils.cfpq_data, "labeled_two_cycles_graph", generate) + + graph = graph_utils.create_two_cycles_graph(2, "a", 5, "b") + + generate.assert_called_once_with(2, 5, labels=("a", "b")) + assert graph is sentinel.graph + + +@pytest.mark.parametrize( + ( + "first_size", + "first_label", + "second_size", + "second_label", + "expected_nodes", + "expected_edges", + ), + [ + pytest.param( + 0, + "a", + 2, + "b", + {0, 1, 2}, + [(0, 0, "a"), (0, 1, "b"), (1, 2, "b"), (2, 0, "b")], + id="first-cycle-is-a-loop", + ), + pytest.param( + 2, + "a", + 0, + "b", + {0, 1, 2}, + [(0, 1, "a"), (1, 2, "a"), (2, 0, "a"), (0, 0, "b")], + id="second-cycle-is-a-loop", + ), + pytest.param( + 0, + "a", + 0, + "b", + {0}, + [(0, 0, "a"), (0, 0, "b")], + id="two-loops", + ), + pytest.param( + 0, + "a", + 0, + "a", + {0}, + [(0, 0, "a"), (0, 0, "a")], + id="two-identical-loops", + ), + ], +) +def test_create_two_cycles_handles_zero_sizes( + first_size, first_label, second_size, second_label, expected_nodes, expected_edges +): + graph = graph_utils.create_two_cycles_graph( + first_size, first_label, second_size, second_label + ) + + assert set(graph.nodes) == expected_nodes + assert Counter(graph.edges(data="label")) == Counter(expected_edges) + + +@pytest.mark.parametrize(("first_size", "second_size"), [(-1, 2), (2, -1)]) +def test_create_two_cycles_rejects_negative_sizes(first_size, second_size): + with pytest.raises(ValueError, match="non-negative"): + graph_utils.create_two_cycles_graph(first_size, "a", second_size, "b") + + +@pytest.mark.parametrize("path_type", [Path, str], ids=["path", "string"]) +def test_save_two_cycles_matches_golden_graph(tmp_path, path_type): + output_path = tmp_path / "graph.dot" + expected_path = Path(__file__).parent / "data" / "two_cycles_5_8.dot" + + graph_utils.save_two_cycles_graph(5, "a", 8, "b", path_type(output_path)) + + actual = _read_dot_graph(output_path) + expected = _read_dot_graph(expected_path) + + assert set(actual.nodes) == set(expected.nodes) + assert Counter(actual.edges(data="label")) == Counter(expected.edges(data="label")) + + +def test_save_two_cycles_overwrites_existing_file(tmp_path): + output_path = tmp_path / "graph.dot" + output_path.write_text("stale content\n" * 1000, encoding="utf-8") + + graph_utils.save_two_cycles_graph(0, "a", 0, "b", output_path) + + assert "stale content" not in output_path.read_text(encoding="utf-8") + _read_dot(output_path) + + +def test_save_two_cycles_preserves_identical_loops(tmp_path): + output_path = tmp_path / "graph.dot" + + graph_utils.save_two_cycles_graph(0, "a", 0, "a", output_path) + + graph = _read_dot(output_path) + assert {node.get_name() for node in graph.get_nodes()} == {"0"} + assert Counter( + (edge.get_source(), edge.get_destination(), edge.get_label()) + for edge in graph.get_edges() + ) == Counter({("0", "0", '"a"'): 2}) + + +@pytest.mark.parametrize( + ("label", "expected_dot_label"), + [ + pytest.param("a\\", r'"a\\"', id="trailing-backslash"), + pytest.param('a:\\"b', r'"a:\\\"b"', id="colon-backslash-and-quote"), + ], +) +def test_save_two_cycles_escapes_labels( + tmp_path, monkeypatch, label, expected_dot_label +): + graph = nx.MultiDiGraph() + graph.add_edge(0, 1, label=label) + graph.add_edge(1, 0, label="plain") + create = Mock(return_value=graph) + monkeypatch.setattr(graph_utils, "create_two_cycles_graph", create) + output_path = tmp_path / "graph.dot" + + graph_utils.save_two_cycles_graph(2, label, 5, "plain", output_path) + + create.assert_called_once_with(2, label, 5, "plain") + dot_graph = _read_dot(output_path) + assert Counter(edge.get_label() for edge in dot_graph.get_edges()) == Counter( + [expected_dot_label, '"plain"'] + ) diff --git a/tests/test_rpq.py b/tests/test_rpq.py new file mode 100644 index 000000000..a68b28f81 --- /dev/null +++ b/tests/test_rpq.py @@ -0,0 +1,193 @@ +from collections import deque +from random import Random + +import pytest +from networkx import MultiDiGraph +from pyformlang.regular_expression import Regex + +from project.rpq import tensor_based_rpq + + +def _rpq_by_traversal( + regex: str, graph: MultiDiGraph, starts: set[int], finals: set[int] +) -> set[tuple[int, int]]: + """Evaluate paths with BFS over pairs of graph vertices and query states.""" + query = Regex(regex).to_epsilon_nfa().to_deterministic() + allowed_starts = starts or set(graph.nodes) + allowed_finals = finals or set(graph.nodes) + result = set() + + for source in allowed_starts: + visited = {(source, state) for state in query.start_states} + queue = deque(visited) + while queue: + vertex, state = queue.popleft() + if vertex in allowed_finals and state in query.final_states: + result.add((source, vertex)) + for _, target, label in graph.out_edges(vertex, data="label"): + for next_state in query(state, label): + pair = (target, next_state) + if pair not in visited: + visited.add(pair) + queue.append(pair) + + return result + + +@pytest.fixture +def path_graph(): + graph = MultiDiGraph() + graph.add_nodes_from([100, -7, 42, 999]) + graph.add_edge(100, -7, label="a") + graph.add_edge(-7, 42, label="b") + return graph + + +@pytest.mark.parametrize( + ("regex", "starts", "finals", "expected"), + [ + pytest.param("a b", {100}, {42}, {(100, 42)}, id="original-vertex-identifiers"), + pytest.param("a b", {-7}, {42}, set(), id="start-restriction"), + pytest.param("a b", {100}, {-7}, set(), id="final-restriction"), + pytest.param("b a", {100}, {42}, set(), id="label-order"), + pytest.param("b a", {42}, {100}, set(), id="edge-direction"), + pytest.param("a | b", set(), {42}, {(-7, 42)}, id="default-starts"), + pytest.param("a | b", {100}, set(), {(100, -7)}, id="default-finals"), + pytest.param( + "a | b", set(), set(), {(100, -7), (-7, 42)}, id="default-both-endpoints" + ), + pytest.param( + "epsilon", + {100, 999}, + {42, 999}, + {(999, 999)}, + id="restricted-zero-length-paths", + ), + pytest.param( + "missing*", + {999}, + {999}, + {(999, 999)}, + id="isolated-vertex-and-absent-label", + ), + pytest.param( + "a", {999}, {999}, set(), id="isolated-vertex-rejects-nonempty-word" + ), + pytest.param("", set(), set(), set(), id="empty-language"), + ], +) +def test_tensor_rpq_paths(path_graph, regex, starts, finals, expected): + assert tensor_based_rpq(regex, path_graph, starts, finals) == expected + + +@pytest.mark.parametrize( + ("has_loop", "expected"), + [ + pytest.param(True, {(100, 42)}, id="traverses-loop"), + pytest.param(False, set(), id="rejects-shorter-path-without-loop"), + ], +) +def test_tensor_rpq_requires_loop_for_last_symbol(path_graph, has_loop, expected): + if has_loop: + path_graph.add_edge(42, 42, label="b") + + assert tensor_based_rpq("a b b", path_graph, {100}, {42}) == expected + + +@pytest.mark.parametrize("label", ["a", "b"]) +def test_tensor_rpq_preserves_parallel_edge_labels(label): + graph = MultiDiGraph() + graph.add_edge(10, 20, label="a") + graph.add_edge(10, 20, label="a") + graph.add_edge(10, 20, label="b") + + assert tensor_based_rpq(label, graph, {10}, {20}) == {(10, 20)} + + +def test_tensor_rpq_returns_all_reachable_endpoint_pairs(): + graph = MultiDiGraph() + graph.add_edge(10, 30, label="a") + graph.add_edge(20, 30, label="a") + graph.add_edge(20, 40, label="a") + + result = tensor_based_rpq("a", graph, {10, 20}, {30, 40}) + + assert result == {(10, 30), (20, 30), (20, 40)} + + +def test_tensor_rpq_uses_all_accepting_regex_states(path_graph): + result = tensor_based_rpq("a | a b", path_graph, {100}, {-7, 42}) + + assert result == {(100, -7), (100, 42)} + + +def test_tensor_rpq_empty_graph(): + assert tensor_based_rpq("a*", MultiDiGraph(), set(), set()) == set() + + +@pytest.mark.parametrize( + ("starts", "finals"), + [ + pytest.param({1234}, {42}, id="unknown-start"), + pytest.param({100}, {1234}, id="unknown-final"), + ], +) +def test_tensor_rpq_rejects_unknown_vertices(path_graph, starts, finals): + with pytest.raises(ValueError, match="vertices"): + tensor_based_rpq("a*", path_graph, starts, finals) + + +def test_tensor_rpq_multicharacter_labels(): + graph = MultiDiGraph() + graph.add_edge(10, 20, label="first") + graph.add_edge(20, 30, label="second") + + assert tensor_based_rpq("first second", graph, {10}, {30}) == {(10, 30)} + + +def test_tensor_rpq_does_not_modify_inputs(path_graph): + before = path_graph.copy() + starts, finals = {100}, {42} + + tensor_based_rpq("a b*", path_graph, starts, finals) + + assert dict(path_graph.nodes(data=True)) == dict(before.nodes(data=True)) + assert list(path_graph.edges(keys=True, data=True)) == list( + before.edges(keys=True, data=True) + ) + assert starts == {100} + assert finals == {42} + + +@pytest.mark.parametrize("seed", range(12)) +@pytest.mark.parametrize( + "regex", + [ + pytest.param("a b", id="concatenation"), + pytest.param("a | b", id="alternative"), + pytest.param("a*", id="repetition"), + pytest.param("(a b)*", id="repeated-sequence"), + pytest.param("a (b | c)*", id="alternative-in-repetition"), + ], +) +def test_tensor_rpq_matches_traversal_on_generated_graphs(seed, regex): + rng = Random(seed) + nodes = [-10, 8, 42, 100] + graph = MultiDiGraph() + graph.add_nodes_from(nodes) + for source in nodes: + for target in nodes: + for label in ["a", "b", "c"]: + if rng.random() < 0.25: + graph.add_edge(source, target, label=label) + starts = {node for node in nodes if rng.random() < 0.5} + finals = {node for node in nodes if rng.random() < 0.5} + expected = _rpq_by_traversal(regex, graph, starts, finals) + + assert tensor_based_rpq(regex, graph, starts, finals) == expected, ( + seed, + regex, + starts, + finals, + list(graph.edges(data="label")), + )