diff --git a/project/task1.py b/project/task1.py new file mode 100644 index 000000000..d268bc53c --- /dev/null +++ b/project/task1.py @@ -0,0 +1,79 @@ +from dataclasses import dataclass +from pathlib import Path + +import cfpq_data +from networkx import MultiDiGraph +from networkx.drawing.nx_pydot import to_pydot + + +@dataclass(frozen=True) +class GraphInfo: + """Aggregated information about a graph. + + Attributes: + nodes_count : int + The number of nodes in the graph. + edges_count : int + The number of edges in the graph. + labels : set[str] + The set of distinct labels that occur on the graph edges. + """ + + nodes_count: int + edges_count: int + labels: set[str] + + +def get_graph_info(name: str) -> GraphInfo: + """Return aggregated information about a graph loaded by name. + + The graph is loaded from the CFPQ_Data dataset by its name. + + Parameters: + name : str + The name of the graph from the dataset. + + Returns: + GraphInfo + The number of nodes, the number of edges and the set of distinct + edge labels of the graph. + """ + graph = cfpq_data.graph_from_csv(cfpq_data.download(name)) + labels = {data["label"] for _, _, data in graph.edges(data=True)} + + return GraphInfo( + nodes_count=graph.number_of_nodes(), + edges_count=graph.number_of_edges(), + labels=labels, + ) + + +def create_two_cycles_graph( + first_cycle_nodes: int, + second_cycle_nodes: int, + labels: tuple[str, str], + path: str | Path, +) -> MultiDiGraph: + """Build a two-cycles graph and save it to a file in the DOT format. + + Parameters: + first_cycle_nodes : int + The number of nodes in the first cycle, excluding the common node. + second_cycle_nodes : int + The number of nodes in the second cycle, excluding the common node. + labels : tuple[str, str] + Two labels used to mark the edges of the first and the second cycle. + path : str | Path + The path to the file where the graph is saved in the DOT format. + + Returns: + graph : MultiDiGraph + The constructed two-cycles graph. + """ + graph = cfpq_data.labeled_two_cycles_graph( + first_cycle_nodes, second_cycle_nodes, labels=labels + ) + + to_pydot(graph).write(str(path)) + + return graph diff --git a/project/task2.py b/project/task2.py new file mode 100644 index 000000000..7a6289b8a --- /dev/null +++ b/project/task2.py @@ -0,0 +1,33 @@ +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 that accepts the language of a regular expression.""" + return Regex(regex).to_epsilon_nfa().minimize() + + +def graph_to_nfa( + graph: MultiDiGraph, start_states: set[int], final_states: set[int] +) -> NondeterministicFiniteAutomaton: + """Build an NFA from a labeled graph. + + Every edge becomes a transition labelled by the edge's ``"label"`` + attribute. Empty ``start_states`` or ``final_states`` mean all graph + nodes are start or final states respectively. + """ + nfa = NondeterministicFiniteAutomaton.from_networkx(graph) + + starts = start_states if start_states else set(graph.nodes) + finals = final_states if final_states else set(graph.nodes) + + for state in starts: + nfa.add_start_state(state) + for state in finals: + nfa.add_final_state(state) + + return nfa diff --git a/project/task3.py b/project/task3.py new file mode 100644 index 000000000..15f0cf681 --- /dev/null +++ b/project/task3.py @@ -0,0 +1,201 @@ +from typing import Iterable + +import scipy.sparse as sp +from networkx import MultiDiGraph +from pyformlang.finite_automaton import ( + NondeterministicFiniteAutomaton, + State, + Symbol, +) + +from project.task2 import graph_to_nfa, regex_to_dfa + + +class AdjacencyMatrixFA: + """Finite automaton represented as a sparse boolean adjacency matrix.""" + + def __init__(self, automaton: NondeterministicFiniteAutomaton | None = None): + self._states_count = 0 + self._state_to_index = {} + self._index_to_state = [] + self._start_states = set() + self._final_states = set() + self._bool_matrices = {} + if automaton is not None: + self._init_from_automaton(automaton) + + @classmethod + def from_components( + cls, + states_count: int, + bool_matrices: dict[Symbol, sp.csr_matrix], + start_states: set[int], + final_states: set[int], + ) -> "AdjacencyMatrixFA": + """Build an automaton from sparse boolean matrices and state sets.""" + fa = cls() + fa._states_count = states_count + fa._bool_matrices = bool_matrices + fa._start_states = start_states + fa._final_states = final_states + return fa + + @property + def states_count(self) -> int: + return self._states_count + + @property + def start_states(self) -> set[int]: + return self._start_states + + @property + def final_states(self) -> set[int]: + return self._final_states + + @property + def bool_matrices(self) -> dict[Symbol, sp.csr_matrix]: + return self._bool_matrices + + @property + def index_to_state(self) -> list[State]: + return self._index_to_state + + def _init_from_automaton(self, automaton: NondeterministicFiniteAutomaton): + states = set(automaton.states) + states.update(automaton.start_states) + states.update(automaton.final_states) + + self._index_to_state = list(states) + self._state_to_index = { + state: index for index, state in enumerate(self._index_to_state) + } + self._states_count = len(states) + + self._start_states = {self._state_to_index[s] for s in automaton.start_states} + self._final_states = {self._state_to_index[s] for s in automaton.final_states} + + matrices = {} + for state_from, transitions in automaton.to_dict().items(): + index_from = self._state_to_index[state_from] + for symbol, state_tos in transitions.items(): + if isinstance(state_tos, State): + state_tos = {state_tos} + matrix = matrices.setdefault( + symbol, + sp.lil_matrix((self._states_count, self._states_count), dtype=bool), + ) + for state_to in state_tos: + matrix[index_from, self._state_to_index[state_to]] = True + + self._bool_matrices = { + symbol: matrix.tocsr() for symbol, matrix in matrices.items() + } + + def accepts(self, word: Iterable[Symbol]) -> bool: + """Return ``True`` if the automaton accepts the given word.""" + current = sp.lil_matrix((1, self._states_count), dtype=bool) + for index in self._start_states: + current[0, index] = True + current = current.tocsr() + + for symbol in word: + symbol = symbol if isinstance(symbol, Symbol) else Symbol(symbol) + matrix = self._bool_matrices.get(symbol) + if matrix is None: + return False + current = current @ matrix + + return any(current[0, index] for index in self._final_states) + + def _reachability_matrix(self) -> sp.csr_matrix: + """Reflexive transitive closure of the adjacency matrix.""" + adjacency = sp.csr_matrix((self._states_count, self._states_count), dtype=bool) + for matrix in self._bool_matrices.values(): + adjacency = adjacency + matrix + + reach = sp.identity(self._states_count, dtype=bool, format="csr") + adjacency + while True: + new_reach = (reach + reach @ adjacency).astype(bool) + if (new_reach != reach).nnz == 0: + break + reach = new_reach + + return reach + + def is_empty(self) -> bool: + """Return ``True`` if the language of the automaton is empty.""" + reach = self._reachability_matrix() + return not any( + reach[start, final] + for start in self._start_states + for final in self._final_states + ) + + +def intersect_automata( + automaton1: AdjacencyMatrixFA, + automaton2: AdjacencyMatrixFA, +) -> AdjacencyMatrixFA: + """Return the intersection of two automata built via the tensor product.""" + states_count1 = automaton1.states_count + states_count2 = automaton2.states_count + + common_symbols = set(automaton1.bool_matrices) & set(automaton2.bool_matrices) + + bool_matrices = { + symbol: sp.kron( + automaton1.bool_matrices[symbol], + automaton2.bool_matrices[symbol], + format="csr", + ) + for symbol in common_symbols + } + + start_states = { + start1 * states_count2 + start2 + for start1 in automaton1.start_states + for start2 in automaton2.start_states + } + + final_states = { + final1 * states_count2 + final2 + for final1 in automaton1.final_states + for final2 in automaton2.final_states + } + + return AdjacencyMatrixFA.from_components( + states_count1 * states_count2, + bool_matrices, + start_states, + final_states, + ) + + +def tensor_based_rpq( + regex: str, + graph: MultiDiGraph, + start_nodes: set[int], + final_nodes: set[int], +) -> set[tuple[int, int]]: + """Return pairs of start/final nodes connected by a path in the regex language.""" + graph_fa = AdjacencyMatrixFA(graph_to_nfa(graph, start_nodes, final_nodes)) + regex_fa = AdjacencyMatrixFA(regex_to_dfa(regex)) + + intersection = intersect_automata(graph_fa, regex_fa) + reach = intersection._reachability_matrix() + + n_dfa = regex_fa.states_count + + result = set() + for start_index in graph_fa.start_states: + start_vertex = graph_fa.index_to_state[start_index].value + for final_index in graph_fa.final_states: + final_vertex = graph_fa.index_to_state[final_index].value + if any( + reach[start_index * n_dfa + dfa_start, final_index * n_dfa + dfa_final] + for dfa_start in regex_fa.start_states + for dfa_final in regex_fa.final_states + ): + result.add((start_vertex, final_vertex)) + + return result diff --git a/tests/test_task1.py b/tests/test_task1.py new file mode 100644 index 000000000..49c791072 --- /dev/null +++ b/tests/test_task1.py @@ -0,0 +1,156 @@ +from collections import Counter + +import pydot +import pytest +from networkx import MultiDiGraph, NetworkXError + +from project.task1 import create_two_cycles_graph, get_graph_info + +TWO_CYCLES_CASES = [ + (2, 3, ("a", "b")), + (3, 2, ("x", "y")), + (5, 5, ("first", "second")), + (1, 1, ("p", "q")), +] + + +@pytest.mark.parametrize( + ("graph_name", "nodes_count", "edges_count", "labels"), + [ + ( + "biomedical", + 341, + 459, + { + "type", + "label", + "subClassOf", + "comment", + "versionInfo", + "title", + "language", + "publisher", + "description", + "creator", + }, + ), + ( + "generations", + 129, + 273, + { + "type", + "first", + "rest", + "onProperty", + "intersectionOf", + "equivalentClass", + "someValuesFrom", + "hasValue", + "hasSex", + "hasChild", + "hasParent", + "inverseOf", + "sameAs", + "hasSibling", + "oneOf", + "range", + "versionInfo", + }, + ), + ("bzip", 632, 556, {"a", "d"}), + ("wc", 332, 269, {"a", "d"}), + ], +) +def test_get_graph_info(graph_name, nodes_count, edges_count, labels): + """``get_graph_info`` returns stats of a graph loaded from the dataset. + + The test loads real graphs from the CFPQ_Data collection over the network, + so it requires an internet connection. + """ + info = get_graph_info(graph_name) + + assert info.nodes_count == nodes_count + assert info.edges_count == edges_count + assert info.labels == labels + + +def test_get_graph_info_unknown_graph(): + """``get_graph_info`` raises ``FileNotFoundError`` for an unknown name.""" + with pytest.raises(FileNotFoundError): + get_graph_info("no such graph") + + +@pytest.mark.parametrize( + ("first_cycle_nodes", "second_cycle_nodes", "labels"), + TWO_CYCLES_CASES, +) +def test_create_two_cycles_graph_structure( + tmp_path, first_cycle_nodes, second_cycle_nodes, labels +): + """The built two-cycles graph has the expected size and edge labels.""" + graph = create_two_cycles_graph( + first_cycle_nodes, second_cycle_nodes, labels, tmp_path / "graph.dot" + ) + + assert isinstance(graph, MultiDiGraph) + assert graph.number_of_nodes() == first_cycle_nodes + second_cycle_nodes + 1 + assert graph.number_of_edges() == first_cycle_nodes + second_cycle_nodes + 2 + + label_counts = Counter(data["label"] for _, _, data in graph.edges(data=True)) + assert label_counts[labels[0]] == first_cycle_nodes + 1 + assert label_counts[labels[1]] == second_cycle_nodes + 1 + + +@pytest.mark.parametrize( + ("first_cycle_nodes", "second_cycle_nodes", "labels"), + TWO_CYCLES_CASES, +) +def test_create_two_cycles_graph_saves_dot( + tmp_path, first_cycle_nodes, second_cycle_nodes, labels +): + """The graph is saved to the given path as a valid DOT file.""" + path = tmp_path / "graph.dot" + + create_two_cycles_graph(first_cycle_nodes, second_cycle_nodes, labels, path) + + assert path.exists() + assert path.read_text().strip() + + (loaded_graph,) = pydot.graph_from_dot_file(str(path)) + + expected_nodes = first_cycle_nodes + second_cycle_nodes + 1 + expected_edges = first_cycle_nodes + second_cycle_nodes + 2 + + assert loaded_graph.get_type() == "digraph" + assert len(loaded_graph.get_nodes()) == expected_nodes + assert len(loaded_graph.get_edges()) == expected_edges + + edge_labels = {edge.get_attributes()["label"] for edge in loaded_graph.get_edges()} + assert edge_labels == set(labels) + + +@pytest.mark.parametrize( + ("first_cycle_nodes", "second_cycle_nodes"), + [(0, 0), (1, 0), (0, 1)], +) +def test_create_two_cycles_graph_zero_sized_cycle( + tmp_path, first_cycle_nodes, second_cycle_nodes +): + """A zero-sized cycle is rejected with ``IndexError``.""" + with pytest.raises(IndexError): + create_two_cycles_graph( + first_cycle_nodes, second_cycle_nodes, ("a", "b"), tmp_path / "graph.dot" + ) + + +def test_create_two_cycles_graph_negative_size_preserves_file(tmp_path): + """A failed build must not overwrite an existing file.""" + path = tmp_path / "graph.dot" + original_content = "digraph { original; }\n" + path.write_text(original_content) + + with pytest.raises(NetworkXError): + create_two_cycles_graph(-1, 2, ("a", "b"), path) + + assert path.read_text() == original_content