diff --git a/project/adjacency_matrix_fa.py b/project/adjacency_matrix_fa.py new file mode 100644 index 000000000..21011ce92 --- /dev/null +++ b/project/adjacency_matrix_fa.py @@ -0,0 +1,198 @@ +"""Sparse matrix representation of finite automata for regular path queries.""" + +from collections import defaultdict +from collections.abc import Iterable + +from networkx import MultiDiGraph +from pyformlang.finite_automaton import NondeterministicFiniteAutomaton, Symbol +from scipy.sparse import csr_matrix, eye, kron + +from project.task2 import graph_to_nfa, regex_to_dfa + + +class AdjacencyMatrixFA: + """An NFA represented by one sparse adjacency matrix per symbol. + + Args: + automaton: Automaton to represent. If ``None``, an empty automaton + is created; this is convenient when the fields are filled later. + """ + + def __init__( + self, automaton: NondeterministicFiniteAutomaton | None = None + ) -> None: + if automaton is None: + self.index_to_state = () + self.state_to_index = {} + self.states_count = 0 + self.start_states = set() + self.final_states = set() + self.matrices = {} + return + + self.index_to_state = tuple(automaton.states) + self.state_to_index = { + state: index for index, state in enumerate(self.index_to_state) + } + self.states_count = len(self.index_to_state) + self.start_states = { + self.state_to_index[state] for state in automaton.start_states + } + self.final_states = { + self.state_to_index[state] for state in automaton.final_states + } + + edges = defaultdict(lambda: ([], [])) + for source, symbol, target in automaton: + sources, targets = edges[symbol] + sources.append(self.state_to_index[source]) + targets.append(self.state_to_index[target]) + + self.matrices = { + symbol: csr_matrix( + ( + [True] * len(sources), + (sources, targets), + ), # (data, (row_ind, col_ind)) + shape=(self.states_count, self.states_count), + dtype=bool, + ) + for symbol, (sources, targets) in edges.items() + } + + def adjacency_matrix(self) -> csr_matrix: + """Return the boolean union of the per-symbol matrices.""" + + adjacency = csr_matrix((self.states_count, self.states_count), dtype=bool) + for matrix in self.matrices.values(): + adjacency = adjacency + matrix + return adjacency + + def transitive_closure(self) -> csr_matrix: + """Return the reflexive-transitive closure of the adjacency matrix.""" + + reachable = eye(self.states_count, format="csr", dtype=bool) + for matrix in self.matrices.values(): + reachable = reachable + matrix + while True: + expanded = reachable + reachable @ reachable + if expanded.nnz == reachable.nnz: + return expanded + reachable = expanded + + def accepts(self, word: Iterable[Symbol]) -> bool: + """Check whether the automaton accepts ``word``. + + The vector of current states is multiplied by the matrix of the next + symbol on every step; the word is accepted when the final vector + reaches at least one final state. + """ + + if not self.start_states or not self.final_states: + return False + + start_states = list(self.start_states) + current = csr_matrix( + ( + [True] * len(start_states), + ([0] * len(start_states), start_states), + ), + shape=(1, self.states_count), + dtype=bool, + ) + + for symbol in word: + matrix = self.matrices.get(Symbol(symbol)) + if matrix is None: + return False + current = current @ matrix + if current.nnz == 0: + return False + return any(node in self.final_states for node in current.indices) + + def is_empty(self) -> bool: + """Return whether no final state is reachable from a start state. + + Reachability is computed by multiplying the start vector by the + transitive closure of the adjacency matrix, so paths of length zero + are taken into account as well. + """ + + if not self.start_states or not self.final_states: + return True + + start_states = list(self.start_states) + starts = csr_matrix( + ( + [True] * len(start_states), + ([0] * len(start_states), start_states), + ), + shape=(1, self.states_count), + dtype=bool, + ) + reachable = starts @ self.transitive_closure() + return not any(node in self.final_states for node in reachable.indices) + + +def intersect_automata( + automaton1: AdjacencyMatrixFA, automaton2: AdjacencyMatrixFA +) -> AdjacencyMatrixFA: + """Build the synchronous product using a Kronecker matrix per label.""" + + product = AdjacencyMatrixFA() + width = automaton2.states_count + product.index_to_state = tuple( + (first, second) + for first in automaton1.index_to_state + for second in automaton2.index_to_state + ) + product.state_to_index = { + state: index for index, state in enumerate(product.index_to_state) + } + product.states_count = automaton1.states_count * width + # State (first, second) is stored at first * width + second, matching kron. + product.start_states = { + first * width + second + for first in automaton1.start_states + for second in automaton2.start_states + } + product.final_states = { + first * width + second + for first in automaton1.final_states + for second in automaton2.final_states + } + product.matrices = { + symbol: kron(matrix, automaton2.matrices[symbol], format="csr") + for symbol, matrix in automaton1.matrices.items() + if symbol in automaton2.matrices + } + return product + + +def tensor_based_rpq( + regex: str, graph: MultiDiGraph, start_nodes: set[int], final_nodes: set[int] +) -> set[tuple[int, int]]: + """Find graph node pairs joined by a path accepted by ``regex``. + + The pairs are extracted from the transitive closure of the tensor product + of the automata for ``regex`` and ``graph``: every closure row of a + product start state gives the reachable product states, and every reached + final state produces a pair of graph nodes. + """ + + regex_matrix = AdjacencyMatrixFA(regex_to_dfa(regex)) + graph_matrix = AdjacencyMatrixFA(graph_to_nfa(graph, start_nodes, final_nodes)) + product = intersect_automata(regex_matrix, graph_matrix) + closure = product.transitive_closure() + + result = set() + for source in product.start_states: + for target in closure.getrow(source).indices: + if target in product.final_states: + result.add( + ( + product.index_to_state[source][1].value, + product.index_to_state[target][1].value, + ) + ) + return result diff --git a/project/graph_lib.py b/project/graph_lib.py new file mode 100644 index 000000000..a5ec15568 --- /dev/null +++ b/project/graph_lib.py @@ -0,0 +1,41 @@ +import pathlib +from typing import Any, NamedTuple + +import cfpq_data +import networkx as nx +import pydot + + +class GraphInfo(NamedTuple): + """Graph statistics with named fields and tuple unpacking support.""" + + number_of_vertices: int + number_of_edges: int + labels: set[str] + + +def get_graph_info(graph_name: str) -> GraphInfo: + graph = cfpq_data.graph_from_csv(cfpq_data.download(graph_name)) + labels = set(nx.get_edge_attributes(graph, "label").values()) + return GraphInfo(graph.number_of_nodes(), graph.number_of_edges(), labels) + + +def save_two_cycles_graph( + n: int, + m: int, + common_node: Any, + labels: tuple[str, str], + path: str | pathlib.Path, +) -> nx.MultiDiGraph: + graph = cfpq_data.labeled_two_cycles_graph( + n, m, common_node=common_node, labels=labels + ) + + dot_graph = pydot.Dot(graph_type="digraph") + for node in graph.nodes: + dot_graph.add_node(pydot.Node(str(node))) + for source, target, label in graph.edges(data="label"): + dot_graph.add_edge(pydot.Edge(str(source), str(target), label=label)) + + dot_graph.write_raw(str(path)) + return graph diff --git a/project/hellings.py b/project/hellings.py new file mode 100644 index 000000000..40caaee72 --- /dev/null +++ b/project/hellings.py @@ -0,0 +1,65 @@ +"""Hellings' algorithm for context-free path queries.""" + +from networkx import DiGraph +from pyformlang.cfg import CFG, Terminal + +from project.task2 import graph_to_nfa +from project.weak_normal_form import cfg_to_weak_normal_form + +__all__ = ["hellings_based_cfpq"] + + +def hellings_based_cfpq( + cfg: CFG, + graph: DiGraph, + start_nodes: set[int] | None = None, + final_nodes: set[int] | None = None, +) -> set[tuple[int, int]]: + """Return pairs connected by a path in the language of ``cfg``. + + The grammar need not be in weak Chomsky normal form. Both directed + graphs and directed multigraphs are supported; edge labels are stored + in the ``label`` attribute. Input objects are not modified. + """ + normalized = cfg_to_weak_normal_form(cfg) + automaton = graph_to_nfa(graph, start_nodes, final_nodes) + + triples = { + (state, variable, state) + for state in automaton.states + for variable in normalized.get_nullable_symbols() + } + for source, symbol, target in automaton: + for production in normalized.productions: + if ( + len(production.body) == 1 + and isinstance(production.body[0], Terminal) + and production.body[0].value == symbol.value + ): + triples.add((source, production.head, target)) + + while True: + new_triples = set() + for source, left, middle in triples: + for right_source, right, target in triples: + if middle != right_source: + continue + for production in normalized.productions: + if ( + len(production.body) == 2 + and production.body[0] == left + and production.body[1] == right + ): + new_triples.add((source, production.head, target)) + new_triples.difference_update(triples) + if not new_triples: + break + triples.update(new_triples) + + return { + (source.value, target.value) + for source, variable, target in triples + if variable == normalized.start_symbol + and source in automaton.start_states + and target in automaton.final_states + } diff --git a/project/msbfs_rpq.py b/project/msbfs_rpq.py new file mode 100644 index 000000000..a71e11fa5 --- /dev/null +++ b/project/msbfs_rpq.py @@ -0,0 +1,92 @@ +"""Multiple-source BFS-based regular path queries.""" + +from networkx import MultiDiGraph +from scipy.sparse import block_diag, csr_matrix + +from project.adjacency_matrix_fa import AdjacencyMatrixFA +from project.task2 import graph_to_nfa, regex_to_dfa + +__all__: list[str] = ["ms_bfs_based_rpq"] + + +def ms_bfs_based_rpq( + regex: str, + graph: MultiDiGraph, + start_nodes: set[int], + final_nodes: set[int], +) -> set[tuple[int, int]]: + """Return all ``(start, final)`` pairs accepted by ``regex``. + + A multiple-source BFS advances all start nodes simultaneously. + Every BFS layer is computed with sparse Boolean matrix products: + for a symbol the frontier is shifted along the graph edges with + that label and, inside each block, advanced by the DFA transition matrix + of the symbol (enlarged to all blocks at once with ``block_diag``). + """ + + regex_matrix = AdjacencyMatrixFA(regex_to_dfa(regex)) + graph_matrix = AdjacencyMatrixFA(graph_to_nfa(graph, start_nodes, final_nodes)) + + width: int = regex_matrix.states_count + start_indices: list[int] = sorted(graph_matrix.start_states) + blocks: int = len(start_indices) + if not blocks: + return set() + + row_indices: list[int] = [] + column_indices: list[int] = [] + for block, start in enumerate(start_indices): + for dfa_start in regex_matrix.start_states: + row_indices.append(block * width + dfa_start) + column_indices.append(start) + front = csr_matrix( + ([True] * len(row_indices), (row_indices, column_indices)), + shape=(blocks * width, graph_matrix.states_count), + dtype=bool, + ) + visited = front.copy() + + dfa_steps = { + symbol: block_diag([matrix.transpose()] * blocks, format="csr") + for symbol, matrix in regex_matrix.matrices.items() + if symbol in graph_matrix.matrices + } + + while front.nnz: + new_front = None + for symbol, dfa_step in dfa_steps.items(): + # Shift along the graph edges, then advance the DFA in each block. + moved = dfa_step @ (front @ graph_matrix.matrices[symbol]) + new_front = moved if new_front is None else new_front + moved + if new_front is None: + break + new_front = new_front.tocsr() + # Keep only the states that have not been reached before. + front = new_front - new_front.multiply(visited) + front.eliminate_zeros() + visited = visited + new_front + + if not regex_matrix.final_states: + return set() + + selector_rows: list[int] = [] + selector_columns: list[int] = [] + for block in range(blocks): + for dfa_final in regex_matrix.final_states: + selector_rows.append(block) + selector_columns.append(block * width + dfa_final) + selector = csr_matrix( + ([True] * len(selector_rows), (selector_rows, selector_columns)), + shape=(blocks, blocks * width), + dtype=bool, + ) + reached = selector @ visited + + result: set[tuple[int, int]] = set() + for block, start in enumerate(start_indices): + start_value = graph_matrix.index_to_state[start].value + for node in reached.getrow(block).indices: + if node in graph_matrix.final_states: + result.add((start_value, graph_matrix.index_to_state[node].value)) + + return result diff --git a/project/task2.py b/project/task2.py new file mode 100644 index 000000000..3461db2d8 --- /dev/null +++ b/project/task2.py @@ -0,0 +1,119 @@ +"""Task 2: finite automata construction. + +Two conversions are provided: + +* :func:`regex_to_dfa` --- builds a *minimal* deterministic finite automaton + (DFA) that accepts exactly the language described by a regular expression. +* :func:`graph_to_nfa` --- builds a nondeterministic finite automaton (NFA) + from a labeled directed multigraph, where the graph nodes are the automaton + states and the edge labels are the input symbols. + +""" + +from typing import Set + +from networkx import MultiDiGraph +from pyformlang.finite_automaton import ( + DeterministicFiniteAutomaton, + NondeterministicFiniteAutomaton, + Symbol, +) +from pyformlang.regular_expression import Regex + +__all__ = ["graph_to_nfa", "regex_to_dfa"] + +#: Name of the edge attribute that stores the label (input symbol) of an edge. +LABEL_ATTRIBUTE = "label" + + +def regex_to_dfa(regex: str) -> DeterministicFiniteAutomaton: + """Build a minimal DFA that accepts the language of ``regex``. + + The syntax is the one of :class:`pyformlang.regular_expression.Regex`: + ``|`` is union, ``*`` is the Kleene star, juxtaposition is concatenation, + parentheses group sub-expressions, and whitespace between the tokens is + ignored. + Symbols are arbitrary strings, so multi-character symbols such as + ``"a1"`` are allowed. + + Args: + regex: A regular expression, for example ``"(a | b)*c"``. + + Returns: + :class:`~pyformlang.finite_automaton.DeterministicFiniteAutomaton` + that accepts exactly the words described by ``regex``. The automaton + is deterministic and minimal; in particular it accepts the empty word + exactly when ``regex`` does. + + Raises: + MisformedRegexError: If ``regex`` cannot be parsed. The exception is defined in + :mod:`pyformlang.regular_expression`. + + Examples: + >>> dfa = regex_to_dfa("a (b | c)*") + >>> dfa.accepts(["a", "b", "c"]) + True + >>> dfa.accepts(["a", "d"]) + False + >>> dfa.is_deterministic() + True + """ + + epsilon_nfa = Regex(regex).to_epsilon_nfa() + return epsilon_nfa.minimize() + + +def graph_to_nfa( + graph: MultiDiGraph, + start_states: Set[int], + final_states: Set[int], +) -> NondeterministicFiniteAutomaton: + """Build an NFA from a labeled directed multigraph. + + The graph is used as is: every node becomes an automaton state, and every + edge ``u --label--> v`` becomes a transition that reads the symbol + ``label`` and goes from ``u`` to ``v``. + + Args: + graph: A :class:`networkx.MultiDiGraph` whose edges carry the + :data:`LABEL_ATTRIBUTE` (``"label"``) attribute with the input + symbol. Nodes can be of any hashable type, but the types used in + the tests are integers and strings. + start_states: Nodes that become the start states of the automaton. An + empty set means "all nodes of ``graph`` are start states". + final_states: Nodes that become the final states of the automaton. An + empty set means "all nodes of ``graph`` are final states". + + Returns: + :class:`~pyformlang.finite_automaton.NondeterministicFiniteAutomaton` + whose states are the nodes of ``graph`` and whose transitions are the + edges of ``graph``. + + Examples: + >>> import networkx as nx + >>> graph = nx.MultiDiGraph() + >>> _ = graph.add_edges_from([(0, 1), (1, 2)], label="a") + >>> nfa = graph_to_nfa(graph, {0}, {2}) + >>> nfa.accepts(["a", "a"]) + True + >>> nfa.accepts(["a"]) + False + """ + + nodes = set(graph.nodes) + + starts = set(start_states) if start_states else nodes + finals = set(final_states) if final_states else nodes + + nfa = NondeterministicFiniteAutomaton( + states=nodes, + start_state=starts, + final_states=finals, + ) + + nfa.add_transitions( + (source, Symbol(label), target) + for source, target, label in graph.edges(data=LABEL_ATTRIBUTE) + ) + + return nfa diff --git a/project/weak_normal_form.py b/project/weak_normal_form.py new file mode 100644 index 000000000..6cebf86ed --- /dev/null +++ b/project/weak_normal_form.py @@ -0,0 +1,21 @@ +"""Conversion of context-free grammars to weak Chomsky normal form.""" + +from pyformlang.cfg import CFG, Production + +__all__ = ["cfg_to_weak_normal_form"] + + +def cfg_to_weak_normal_form(cfg: CFG) -> CFG: + """Return an equivalent grammar with rules ``A -> BC | a | epsilon``. + + Restore nullable variables' epsilon rules after pyformlang's conversion + to Chomsky normal form, then remove useless symbols. + """ + normal_form_cfg = cfg.to_normal_form() + nullable = cfg.get_nullable_symbols() + + productions = set(normal_form_cfg.productions) + productions.update(Production(variable, []) for variable in nullable) + + weak_normal_form_cfg = CFG(start_symbol=cfg.start_symbol, productions=productions) + return weak_normal_form_cfg.remove_useless_symbols() diff --git a/tests/autotests/rpq_template_test.py b/tests/autotests/rpq_template_test.py index f57e27a2a..0303b72fb 100644 --- a/tests/autotests/rpq_template_test.py +++ b/tests/autotests/rpq_template_test.py @@ -6,7 +6,7 @@ from typing import Callable, Iterable try: - from project.task4 import ms_bfs_based_rpq + from project.msbfs_rpq import ms_bfs_based_rpq except ImportError: pass diff --git a/tests/autotests/test_task03.py b/tests/autotests/test_task03.py index 321d73494..54b1e7e36 100644 --- a/tests/autotests/test_task03.py +++ b/tests/autotests/test_task03.py @@ -13,7 +13,11 @@ # 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 ( + intersect_automata, + AdjacencyMatrixFA, + tensor_based_rpq, + ) except ImportError: pytestmark = pytest.mark.skip("Task 3 is not ready to test!") diff --git a/tests/autotests/test_task04.py b/tests/autotests/test_task04.py index 7169dee43..961fd5dcf 100644 --- a/tests/autotests/test_task04.py +++ b/tests/autotests/test_task04.py @@ -11,8 +11,8 @@ # Fix import statements in try block to run tests try: - from project.task3 import tensor_based_rpq - from project.task4 import ms_bfs_based_rpq + from project.adjacency_matrix_fa import tensor_based_rpq + from project.msbfs_rpq import ms_bfs_based_rpq except ImportError: pytestmark = pytest.mark.skip("Task 4 is not ready to test!") diff --git a/tests/autotests/test_task06.py b/tests/autotests/test_task06.py index 01b5339f5..c1ba74e1a 100644 --- a/tests/autotests/test_task06.py +++ b/tests/autotests/test_task06.py @@ -9,7 +9,7 @@ # Fix import statements in try block to run tests try: - from project.task6 import hellings_based_cfpq + from project.hellings import hellings_based_cfpq except ImportError: pytestmark = pytest.mark.skip("Task 6 is not ready to test!") @@ -30,8 +30,8 @@ def test_different_grammars_hellings(self, graph, eq_grammars): def test_cfg_to_weak_normal_form_exists(): try: - import project.task6 + import project.weak_normal_form - assert "cfg_to_weak_normal_form" in dir(project.task6) + assert "cfg_to_weak_normal_form" in dir(project.weak_normal_form) except NameError: assert False diff --git a/tests/test_adjacency_matrix_fa.py b/tests/test_adjacency_matrix_fa.py new file mode 100644 index 000000000..454722132 --- /dev/null +++ b/tests/test_adjacency_matrix_fa.py @@ -0,0 +1,62 @@ +"""Behavioral tests for the sparse automata and tensor RPQ implementation.""" + +from networkx import MultiDiGraph +from pyformlang.finite_automaton import NondeterministicFiniteAutomaton + +from project.adjacency_matrix_fa import ( + AdjacencyMatrixFA, + intersect_automata, + tensor_based_rpq, +) +from project.task2 import regex_to_dfa + + +def test_adjacency_matrix_nfa_accepts_nondeterministic_paths() -> None: + automaton = NondeterministicFiniteAutomaton() + automaton.add_start_state("start") + automaton.add_final_state("end") + automaton.add_transition("start", "a", "dead") + automaton.add_transition("start", "a", "middle") + automaton.add_transition("middle", "b", "end") + + matrix_automaton = AdjacencyMatrixFA(automaton) + + assert matrix_automaton.accepts(iter(["a", "b"])) + assert not matrix_automaton.accepts(["a"]) + assert not matrix_automaton.accepts(["a", "c"]) + + +def test_is_empty_includes_zero_length_paths_and_ignores_dead_cycles() -> None: + automaton = NondeterministicFiniteAutomaton() + automaton.add_start_state(10) + automaton.add_final_state(20) + automaton.add_transition(10, "a", 10) + + assert AdjacencyMatrixFA(automaton).is_empty() + + automaton.add_final_state(10) + assert not AdjacencyMatrixFA(automaton).is_empty() + + +def test_intersection_synchronizes_labels() -> None: + first = AdjacencyMatrixFA(regex_to_dfa("a (b | c)")) + second = AdjacencyMatrixFA(regex_to_dfa("a b")) + + intersection = intersect_automata(first, second) + + assert intersection.accepts(["a", "b"]) + assert not intersection.accepts(["a", "c"]) + assert not intersection.is_empty() + + +def test_tensor_rpq_tracks_each_start_node_separately() -> None: + graph = MultiDiGraph() + graph.add_edge(10, 30, label="a") + graph.add_edge(20, 30, label="a") + graph.add_edge(30, 40, label="b") + graph.add_edge(10, 40, label="b") + + assert tensor_based_rpq("a b", graph, {10, 20}, {40}) == { + (10, 40), + (20, 40), + } diff --git a/tests/test_graph_lib.py b/tests/test_graph_lib.py new file mode 100644 index 000000000..b36757511 --- /dev/null +++ b/tests/test_graph_lib.py @@ -0,0 +1,115 @@ +from collections import Counter + +import networkx as nx +import pydot +import pytest + +from project import graph_lib + + +def test_get_graph_info(): + info = graph_lib.get_graph_info("generations") + number_of_vertices, number_of_edges, labels = info + + assert isinstance(info, graph_lib.GraphInfo) + assert number_of_vertices == 129 + assert number_of_edges == 273 + assert labels == { + "equivalentClass", + "first", + "hasChild", + "hasParent", + "hasSex", + "hasSibling", + "hasValue", + "intersectionOf", + "inverseOf", + "onProperty", + "oneOf", + "range", + "rest", + "sameAs", + "someValuesFrom", + "type", + "versionInfo", + } + + +def test_get_graph_info_unknown_graph(): + with pytest.raises(FileNotFoundError): + graph_lib.get_graph_info("no_such_graph") + + +def test_save_two_cycles_graph_round_trip(tmp_path): + path = tmp_path / "two_cycles_graph.dot" + + graph = graph_lib.save_two_cycles_graph(3, 2, 42, ("x", "y"), path) + + expected_nodes = {1, 2, 3, 4, 5, 42} + expected_edges = { + (42, 1, "x"), + (1, 2, "x"), + (2, 3, "x"), + (3, 42, "x"), + (42, 4, "y"), + (4, 5, "y"), + (5, 42, "y"), + } + + assert set(graph.nodes) == expected_nodes + assert graph.number_of_edges() == len(expected_edges) + assert set(graph.edges(data="label")) == expected_edges + + (dot_graph,) = pydot.graph_from_dot_file(str(path)) + + assert dot_graph.get_type() == "digraph" + assert {int(node.get_name()) for node in dot_graph.get_nodes()} == expected_nodes + assert len(dot_graph.get_edges()) == len(expected_edges) + assert { + (edge.get_source(), edge.get_destination(), edge.get_attributes()["label"]) + for edge in dot_graph.get_edges() + } == {(str(u), str(v), c) for u, v, c in expected_edges} + + +def test_save_two_cycles_graph_negative_size_preserves_file(tmp_path): + path = tmp_path / "existing.dot" + original_content = b"digraph { original; }\n" + path.write_bytes(original_content) + + with pytest.raises(nx.NetworkXError): + graph_lib.save_two_cycles_graph(-1, 2, 0, ("a", "b"), path) + + assert path.read_bytes() == original_content + + +def test_save_two_cycles_graph_parallel_edges_round_trip(tmp_path): + path = tmp_path / "parallel_edges.dot" + + graph = graph_lib.save_two_cycles_graph(1, 1, 1, ("a", "b"), path) + (restored,) = pydot.graph_from_dot_file(str(path)) + + assert set(graph.nodes) == {1, 2} + assert restored.get_type() == "digraph" + assert not path.read_text().startswith("strict") + assert {node.get_name() for node in restored.get_nodes()} == {"1", "2"} + expected_edges = Counter( + {("1", "1", "a"): 2, ("1", "2", "b"): 1, ("2", "1", "b"): 1} + ) + assert ( + Counter( + (str(source), str(target), label) + for source, target, label in graph.edges(data="label") + ) + == expected_edges + ) + assert ( + Counter( + ( + edge.get_source(), + edge.get_destination(), + edge.get_attributes()["label"], + ) + for edge in restored.get_edges() + ) + == expected_edges + ) diff --git a/tests/test_hellings.py b/tests/test_hellings.py new file mode 100644 index 000000000..889630fbb --- /dev/null +++ b/tests/test_hellings.py @@ -0,0 +1,68 @@ +"""Context-free path query cases not covered by the course autotests.""" + +import networkx as nx +import pytest +from pyformlang.cfg import CFG, Variable + +from project.hellings import hellings_based_cfpq + + +def test_hellings_on_digraph_with_nonconsecutive_vertices() -> None: + graph = nx.DiGraph() + graph.add_edges_from([(10, 20), (20, 30)], label="a") + graph.add_edges_from([(30, 40), (40, 50), (50, 60)], label="b") + cfg = CFG.from_text("S -> a S b | a b") + + assert hellings_based_cfpq(cfg, graph) == {(20, 40), (10, 50)} + assert hellings_based_cfpq(cfg, graph, {10}, {50}) == {(10, 50)} + + +@pytest.mark.parametrize("nodes", [None, set()]) +def test_hellings_uses_all_vertices_for_default_filters(nodes) -> None: + graph = nx.MultiDiGraph() + graph.add_edges_from([(10, 20), (20, 30)], label="a") + + assert hellings_based_cfpq(CFG.from_text("S -> a"), graph, nodes, nodes) == { + (10, 20), + (20, 30), + } + + +def test_hellings_handles_parallel_edges_and_multicharacter_labels() -> None: + graph = nx.MultiDiGraph() + graph.add_edge(0, 1, label="ignored") + graph.add_edge(0, 1, label="left") + graph.add_edge(0, 1, label="left") + graph.add_edge(1, 2, label="right") + cfg = CFG.from_text("S -> left right") + + assert hellings_based_cfpq(cfg, graph) == {(0, 2)} + + +def test_hellings_uses_the_grammar_start_symbol() -> None: + graph = nx.MultiDiGraph() + graph.add_edge(0, 1, label="a") + graph.add_edge(1, 2, label="b") + cfg = CFG.from_text("Query -> a\nS -> b", start_symbol=Variable("Query")) + + assert hellings_based_cfpq(cfg, graph) == {(0, 1)} + + +def test_hellings_on_an_empty_graph() -> None: + cfg = CFG.from_text("S -> a | $") + assert hellings_based_cfpq(cfg, nx.MultiDiGraph()) == set() + + +def test_hellings_on_an_empty_grammar() -> None: + graph = nx.MultiDiGraph() + graph.add_edge(0, 1, label="a") + + assert hellings_based_cfpq(CFG(start_symbol=Variable("S")), graph) == set() + + +def test_hellings_treats_explicit_absent_vertices_as_isolated_states() -> None: + graph = nx.MultiDiGraph() + graph.add_edge(0, 1, label="a") + cfg = CFG.from_text("S -> a | $") + + assert hellings_based_cfpq(cfg, graph, {0, 99}, {1, 99}) == {(0, 1), (99, 99)} diff --git a/tests/test_msbfs_rpq.py b/tests/test_msbfs_rpq.py new file mode 100644 index 000000000..3820b9467 --- /dev/null +++ b/tests/test_msbfs_rpq.py @@ -0,0 +1,37 @@ +"""Direct unit tests for the multiple-source RPQ solver.""" + +from networkx import MultiDiGraph + +from project.msbfs_rpq import ms_bfs_based_rpq + + +def test_ms_bfs_based_rpq_matches_expected_pairs() -> None: + graph = MultiDiGraph() + graph.add_edge(0, 1, label="a") + graph.add_edge(1, 3, label="b") + graph.add_edge(0, 2, label="a") + graph.add_edge(2, 3, label="b") + graph.add_edge(4, 5, label="a") + graph.add_edge(5, 7, label="b") + + assert ms_bfs_based_rpq("a b", graph, {0, 4}, {3, 7}) == { + (0, 3), + (4, 7), + } + + +def test_ms_bfs_based_rpq_uses_all_nodes_when_start_and_final_are_empty() -> None: + graph = MultiDiGraph() + graph.add_edge(0, 1, label="a") + graph.add_edge(1, 2, label="b") + + assert ms_bfs_based_rpq("a", graph, set(), set()) == {(0, 1)} + + +def test_ms_bfs_based_rpq_treats_absent_vertices_as_isolated_states() -> None: + graph = MultiDiGraph() + graph.add_edge(0, 1, label="a") + graph.add_edge(1, 2, label="b") + + assert ms_bfs_based_rpq("a b", graph, {0, 99}, {2, 42}) == {(0, 2)} + assert ms_bfs_based_rpq("a*", graph, {99}, {99}) == {(99, 99)} diff --git a/tests/test_task2.py b/tests/test_task2.py new file mode 100644 index 000000000..0a292d0ea --- /dev/null +++ b/tests/test_task2.py @@ -0,0 +1,160 @@ +"""Tests for the Task 2 module: ``regex_to_dfa`` and ``graph_to_nfa``.""" + +import pytest +from networkx import MultiDiGraph +from pyformlang.finite_automaton import NondeterministicFiniteAutomaton + +from project import graph_lib +from project.task2 import graph_to_nfa, regex_to_dfa + +MINIMAL_DFA_REGRESSIONS = [ + "a", + "a b", + "a*", + "a b c*", + "(a | b)*c", + "a*a*b", + "(a | b | c)*(d | e | f)*", + "((a | b)*c)*((d | e)*f)*", + "(a b d) | (a b c)", + "a b c*", +] + + +class TestRegexToDfa: + @pytest.mark.parametrize("regex", MINIMAL_DFA_REGRESSIONS) + def test_regex_to_dfa_is_deterministic_and_minimal(self, regex: str) -> None: + dfa = regex_to_dfa(regex) + minimized = dfa.minimize() + + assert dfa.is_deterministic() + assert dfa.is_equivalent_to(minimized) + assert len(minimized.states) == len(dfa.states) + + @pytest.mark.parametrize( + ("regex", "accepted", "rejected"), + [ + ("a", [["a"]], [[], ["b"], ["a", "a"]]), + ("a b", [["a", "b"]], [["b", "a"], ["a"], ["b"]]), + ("a*", [[], ["a"], ["a", "a"], ["a"] * 5], [["b"]]), + ("a b c*", [["a", "b"], ["a", "b", "c"]], [["a"], ["b", "c"], ["a", "c"]]), + ( + "(a | b)*c", + [["c"], ["a", "c"], ["b", "b", "a", "c"]], + [[], ["a"], ["c", "a"], ["a", "b"]], + ), + ( + "(a b) | (a c)", + [["a", "b"], ["a", "c"]], + [["a"], ["b"], ["a", "b", "c"]], + ), + ], + ) + def test_regex_to_dfa_accepts_its_language( + self, regex: str, accepted: list[list[str]], rejected: list[list[str]] + ) -> None: + dfa = regex_to_dfa(regex) + + for word in accepted: + assert dfa.accepts(word), f"{regex} must accept {word}" + + for word in rejected: + assert not dfa.accepts(word), f"{regex} must reject {word}" + + +def _two_cycles_graph() -> MultiDiGraph: + """A graph with two cycles sharing the node ``c``: 0->1->c->0 and c->2->3->c.""" + graph = MultiDiGraph() + graph.add_edge(0, 1, label="a") + graph.add_edge(1, "c", label="a") + graph.add_edge("c", 0, label="a") + graph.add_edge("c", 2, label="b") + graph.add_edge(2, 3, label="b") + graph.add_edge(3, "c", label="b") + return graph + + +class TestGraphToNfa: + def test_graph_to_nfa_accepts_words_from_graph(self) -> None: + graph = MultiDiGraph() + graph.add_edge(0, 1, label="a") + graph.add_edge(1, 2, label="b") + graph.add_edge(2, 3, label="c") + graph.add_edge(3, 4, label="d") + graph.add_edge(4, 5, label="e") + + nfa = graph_to_nfa(graph, {0}, {5}) + + assert nfa.accepts(["a", "b", "c", "d", "e"]) + assert not nfa.accepts(["a", "b", "c", "d"]) + assert not nfa.accepts(["b", "c", "d", "e"]) + + def test_graph_to_nfa_empty_start_and_final_sets_mean_all_nodes(self) -> None: + graph = _two_cycles_graph() + nfa = graph_to_nfa(graph.copy(), set(), set()) + + assert {state.value for state in nfa.start_states} == set(graph.nodes) + assert {state.value for state in nfa.final_states} == set(graph.nodes) + + def test_graph_to_nfa_explicit_start_and_final_states(self) -> None: + graph = _two_cycles_graph() + nfa = graph_to_nfa(graph.copy(), {0}, {0}) + + assert nfa.accepts([]) # 0 is both start and final + assert nfa.accepts(["a", "a", "a"]) # one full loop over the "a" cycle + assert nfa.accepts(["a", "a", "a"] * 3) + # 0 -> 1 -> c -> 2 -> 3 -> c -> 0, i.e. a lap over the "b" cycle + assert nfa.accepts(["a", "a", "b", "b", "b", "a"]) + + assert not nfa.accepts(["a"]) + assert not nfa.accepts(["a", "a"]) + assert not nfa.accepts(["b"]) + assert not nfa.accepts(["a", "a", "a", "b"]) + + def test_graph_to_nfa_with_one_start_and_one_final_state(self) -> None: + graph = _two_cycles_graph() + nfa = graph_to_nfa(graph.copy(), {0}, {2}) + + assert nfa.accepts(["a", "a", "b"]) # 0 -> 1 -> c -> 2 + assert nfa.accepts(["a", "a", "a", "a", "a", "b"]) # one lap over "a" first + assert nfa.accepts( + ["a", "a", "b", "b", "b", "a", "a", "a", "b"] + ) # over "b" first + + assert not nfa.accepts([]) + assert not nfa.accepts(["a"]) + assert not nfa.accepts(["a", "a"]) + assert not nfa.accepts(["b"]) + + def test_graph_to_nfa_keeps_parallel_edges(self) -> None: + graph = MultiDiGraph() + graph.add_edge(0, 1, label="a") + graph.add_edge(0, 1, label="b") + + nfa = graph_to_nfa(graph, {0}, {1}) + + assert nfa.accepts(["a"]) + assert nfa.accepts(["b"]) + assert not nfa.accepts(["a", "b"]) + + def test_graph_to_nfa_on_empty_graph(self) -> None: + nfa = graph_to_nfa(MultiDiGraph(), set(), set()) + + assert isinstance(nfa, NondeterministicFiniteAutomaton) + assert nfa.is_empty() + + def test_graph_to_nfa_integration_with_task1_graph(self, tmp_path) -> None: + path = tmp_path / "two_cycles.dot" + graph = graph_lib.save_two_cycles_graph( + 3, 2, common_node=42, labels=("x", "y"), path=path + ) + + nfa = graph_to_nfa(graph, {42}, {42}) + + # loop around the "x" cycle: 42 -> 1 -> 2 -> 3 -> 42 + assert nfa.accepts(["x", "x", "x", "x"]) + # loop around the "y" cycle: 42 -> 4 -> 5 -> 42 + assert nfa.accepts(["y", "y", "y"]) + # a mixed walk is not a valid path from 42 back to 42 + assert not nfa.accepts(["x", "x"]) + assert not nfa.accepts(["x", "y"]) diff --git a/tests/test_weak_normal_form.py b/tests/test_weak_normal_form.py new file mode 100644 index 000000000..02b2f49d5 --- /dev/null +++ b/tests/test_weak_normal_form.py @@ -0,0 +1,61 @@ +"""Language preservation and production shapes of weak Chomsky normal form.""" + +import pytest +from pyformlang.cfg import CFG, Production, Terminal, Variable + +from project.weak_normal_form import cfg_to_weak_normal_form + + +@pytest.mark.parametrize( + "grammar, accepted_words, rejected_words", + [ + ( + "S -> A B\nA -> C\nC -> $ | a\nB -> b | $", + [(), ("a",), ("b",), ("a", "b")], + [("b", "a"), ("a", "a"), ("b", "b")], + ), + ( + "S -> a S b c | $", + [(), ("a", "b", "c"), ("a", "a", "b", "c", "b", "c")], + [("a", "b"), ("a", "b", "c", "c"), ("a", "b", "c", "a", "b", "c")], + ), + ], +) +def test_conversion_preserves_language_and_weak_normal_form( + grammar: str, accepted_words, rejected_words +) -> None: + cfg = CFG.from_text(grammar) + + normalized = cfg_to_weak_normal_form(cfg) + + assert normalized.start_symbol == cfg.start_symbol + for production in normalized.productions: + body = production.body + assert ( + not body + or (len(body) == 1 and isinstance(body[0], Terminal)) + or (len(body) == 2 and all(isinstance(s, Variable) for s in body)) + ) + for word in accepted_words: + assert normalized.contains(word), word + for word in rejected_words: + assert not normalized.contains(word), word + + +def test_conversion_removes_unreachable_symbols() -> None: + cfg = CFG.from_text("S -> a\nUnused -> b | $") + + normalized = cfg_to_weak_normal_form(cfg) + + assert normalized.variables == {Variable("S")} + assert normalized.terminals == {Terminal("a")} + assert set(normalized.productions) == {Production(Variable("S"), [Terminal("a")])} + + +def test_conversion_of_empty_grammar() -> None: + start_symbol = Variable("S") + normalized = cfg_to_weak_normal_form(CFG(start_symbol=start_symbol)) + + assert normalized.start_symbol == start_symbol + assert not normalized.productions + assert not normalized.contains([])