diff --git a/README.en.md b/README.en.md index 0635b7e36..1c9158ded 100644 --- a/README.en.md +++ b/README.en.md @@ -175,7 +175,7 @@ When working with these tests, the following rules should be followed: - In these tests, usually, only one block should be modified: ```python try: - from project.task2 import regex_to_dfa, graph_to_nfa + from project.automata_construction import regex_to_dfa, graph_to_nfa except ImportError: pytestmark = pytest.mark.skip("Task 2 is not ready to test!") ``` diff --git a/README.md b/README.md index bafa1dcff..c87fc1ba3 100644 --- a/README.md +++ b/README.md @@ -157,7 +157,7 @@ - В данных тестах обычно можно изменять только одно --- блок ```python try: - from project.task2 import regex_to_dfa, graph_to_nfa + from project.automata_construction import regex_to_dfa, graph_to_nfa except ImportError: pytestmark = pytest.mark.skip("Task 2 is not ready to test!") ``` diff --git a/project/automata_construction.py b/project/automata_construction.py new file mode 100644 index 000000000..7982a5d00 --- /dev/null +++ b/project/automata_construction.py @@ -0,0 +1,42 @@ +"""Finite automata constructors for regular expressions and labeled graphs.""" + +from typing import AbstractSet + +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 the minimal DFA recognizing `regex` in pyformlang syntax.""" + return Regex(regex).to_epsilon_nfa().to_deterministic().minimize() + + +def graph_to_nfa( + graph: MultiDiGraph, + start_states: AbstractSet[int] | None = None, + final_states: AbstractSet[int] | None = None, +) -> NondeterministicFiniteAutomaton: + """Build an NFA whose states and labeled transitions come from `graph`. + + If either state set is omitted or empty, all graph vertices are used for + that set. Each graph edge must have a `label` attribute. Multiple graph + edges with the same source, label, and destination collapse into one NFA + transition, as they represent the same automaton transition. + """ + nfa = NondeterministicFiniteAutomaton() + + for source, target, edge_data in graph.edges(data=True): + nfa.add_transition(source, edge_data["label"], target) + + starts = start_states or set(graph.nodes) + finals = final_states or 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/automata_utils.py b/project/automata_utils.py new file mode 100644 index 000000000..d92a9e01e --- /dev/null +++ b/project/automata_utils.py @@ -0,0 +1,41 @@ +"""Convert regular expressions and labeled graphs to finite automata.""" + +from networkx import MultiDiGraph +from pyformlang.finite_automaton import ( + DeterministicFiniteAutomaton, + NondeterministicFiniteAutomaton, + State, +) +from pyformlang.regular_expression import Regex + + +def regex_to_dfa(regex: str) -> DeterministicFiniteAutomaton: + """Build a minimal DFA using pyformlang's regular expression syntax.""" + return Regex(regex).to_epsilon_nfa().to_deterministic().minimize() + + +def graph_to_nfa( + graph: MultiDiGraph, + start_states: set[int] | None = None, + final_states: set[int] | None = None, +) -> NondeterministicFiniteAutomaton: + """Keep graph vertices as states and edge labels as transition symbols. + + None or an empty boundary set selects all vertices, as required by the + course tests. Isolated vertices are preserved. The graph is not modified. + """ + starts = set(start_states) if start_states else set(graph.nodes) + finals = set(final_states) if final_states else set(graph.nodes) + if not (starts | finals) <= set(graph.nodes): + raise ValueError("Start and final states must be graph vertices") + + automaton = NondeterministicFiniteAutomaton( + states={State(node) for node in graph.nodes} + ) + for node in starts: + automaton.add_start_state(node) + for node in finals: + automaton.add_final_state(node) + for source, target, data in graph.edges(data=True): + automaton.add_transition(source, data["label"], target) + return automaton diff --git a/project/graph_utils.py b/project/graph_utils.py new file mode 100644 index 000000000..320668096 --- /dev/null +++ b/project/graph_utils.py @@ -0,0 +1,76 @@ +"""Load graph statistics and generate labeled graphs for path queries.""" + +from pathlib import Path + +import cfpq_data +import networkx as nx +import pydot + + +def get_graph_info(graph_name: str) -> tuple[int, int, set[str]]: + """Download a dataset graph and return its basic statistics. + + Args: + graph_name: Name of a graph in the CFPQ_Data dataset. + + Returns: + A tuple containing the number of vertices, the number of edges, + and the set of distinct edge labels. Parallel edges and self-loops + are counted individually. + + Raises: + FileNotFoundError: The graph name is unknown or its CSV file is missing. + OSError: Downloaded graph files cannot be written or read. + """ + graph = cfpq_data.graph_from_csv(cfpq_data.download(graph_name)) + labels = {data["label"] for _, _, data in graph.edges(data=True)} + return graph.number_of_nodes(), graph.number_of_edges(), labels + + +def create_two_cycles_graph( + n: int, + m: int, + labels: tuple[str, str], + output_path: str | Path, +) -> nx.MultiDiGraph: + """Create two directed cycles with a shared vertex and save them as DOT. + + Args: + n: Positive number of vertices in the first cycle, excluding the + shared vertex 0. + m: Positive number of vertices in the second cycle, excluding the + shared vertex 0. + labels: Pair of edge labels, one for each cycle. Labels may coincide. + output_path: Destination file path. Its parent directory must exist. + An existing file is overwritten using UTF-8 encoding. + + Returns: + The generated graph with n + m + 1 vertices and n + m + 2 edges. + For example, n=2 and m=3 produce cycles of lengths 3 and 4. + + Raises: + TypeError: A cycle size is not an integer, labels is a string, + or a label is not a string. + ValueError: A cycle size is not positive or labels has a length + other than two. + OSError: The output file cannot be written. + """ + if not isinstance(n, int) or not isinstance(m, int): + raise TypeError("Cycle sizes must be integers") + if n <= 0 or m <= 0: + raise ValueError("Cycle sizes must be positive") + if isinstance(labels, str): + raise TypeError("Labels must be a pair of strings") + if len(labels) != 2: + raise ValueError("Exactly two labels are required") + if not all(isinstance(label, str) for label in labels): + raise TypeError("Labels must be strings") + + graph = cfpq_data.labeled_two_cycles_graph(n, m, labels=labels) + dot = pydot.Dot(graph_type="digraph") + for node in graph.nodes: + dot.add_node(pydot.Node(str(node))) + for source, target, data in graph.edges(data=True): + dot.add_edge(pydot.Edge(str(source), str(target), label=data["label"])) + dot.write_raw(str(output_path), encoding="utf-8") + return graph diff --git a/project/hellings.py b/project/hellings.py new file mode 100644 index 000000000..17f495102 --- /dev/null +++ b/project/hellings.py @@ -0,0 +1,90 @@ +"""Context-free path queries using the Hellings algorithm. + +A fact (A, u, v) means that a path from u to v spells a word derived from A. +Initialization covers terminal edges and epsilon at every vertex. Processing +each fact composes it with both incoming and outgoing facts using binary rules. +Duplicate suppression bounds the number of pending insertions by |N'| * |V|^2, +ensuring termination on finite inputs. +""" + +from collections import defaultdict, deque + +from networkx import DiGraph +from pyformlang.cfg import CFG + +from project.automata_utils import graph_to_nfa +from project.weak_normal_form import cfg_to_weak_normal_form + + +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 allowed endpoint pairs whose path label belongs to the CFG. + + The CFG may have arbitrary productions and a custom start symbol. The + existing graph adapter supports DiGraph and MultiDiGraph with a ``label`` + on each edge. None or an empty boundary set selects every graph vertex; + unknown boundary vertices raise ValueError. All vertices remain available + as intermediate vertices. Empty paths are included when epsilon is in the + language, including at isolated vertices. Inputs are not modified. + """ + grammar = cfg_to_weak_normal_form(cfg) + automaton = graph_to_nfa(graph, start_nodes, final_nodes) + vertices = {state.value for state in automaton.states} + starts = {state.value for state in automaton.start_states} + finals = {state.value for state in automaton.final_states} + + terminal_rules = defaultdict(set) + binary_rules = defaultdict(set) + empty_rules = set() + for production in grammar.productions: + body = production.body + if not body: + empty_rules.add(production.head) + elif len(body) == 1: + terminal_rules[body[0].value].add(production.head) + else: + binary_rules[tuple(body)].add(production.head) + + discovered = set() + pending = deque() + incoming = defaultdict(set) + outgoing = defaultdict(set) + + def add_fact(variable, source, target): + fact = (variable, source, target) + if fact not in discovered: + discovered.add(fact) + pending.append(fact) + incoming[target].add((variable, source)) + outgoing[source].add((variable, target)) + + # Initialize epsilon facts and matching terminal edges. + for variable in empty_rules: + for vertex in vertices: + add_fact(variable, vertex, vertex) + for source, transitions in automaton.to_dict().items(): + for symbol, targets in transitions.items(): + for variable in terminal_rules.get(symbol.value, ()): + for target in targets: + add_fact(variable, source.value, target.value) + + while pending: + variable, source, target = pending.popleft() + # Incoming facts: A -> C B, with the pending fact labeled B. + for left, predecessor in tuple(incoming[source]): + for head in binary_rules.get((left, variable), ()): + add_fact(head, predecessor, target) + # Outgoing facts: A -> B C. Snapshots permit insertions on self-loops. + for right, successor in tuple(outgoing[target]): + for head in binary_rules.get((variable, right), ()): + add_fact(head, source, successor) + + return { + (source, target) + for variable, source, target in discovered + if variable == grammar.start_symbol and source in starts and target in finals + } diff --git a/project/matrix_automata.py b/project/matrix_automata.py new file mode 100644 index 000000000..404082e20 --- /dev/null +++ b/project/matrix_automata.py @@ -0,0 +1,152 @@ +"""Sparse-matrix finite automata and tensor-based regular path queries.""" + +from collections.abc import Iterable + +from networkx import MultiDiGraph +from pyformlang.finite_automaton import NondeterministicFiniteAutomaton, State, Symbol +from scipy.sparse import csr_matrix, eye, kron + +from project.automata_utils import graph_to_nfa, regex_to_dfa + + +class AdjacencyMatrixFA: + """Represent an epsilon-free DFA or NFA by Boolean CSR matrices. + + Each symbol has a matrix whose (i, j) entry denotes a transition from + state i to state j. Boundary sets contain matrix indices, not original + state values; ``states`` and ``state_indices`` retain the correspondence. + """ + + def __init__( + self, automaton: NondeterministicFiniteAutomaton | None = None + ) -> None: + self.states = tuple(automaton.states) if automaton is not None else () + self.state_indices = {state: i for i, state in enumerate(self.states)} + self.start_states: set[int] = set() + self.final_states: set[int] = set() + self.matrices: dict[Symbol, csr_matrix] = {} + if automaton is None: + return + + self.start_states = {self.state_indices[s] for s in automaton.start_states} + self.final_states = {self.state_indices[s] for s in automaton.final_states} + coordinates = {} + for source, transitions in automaton.to_dict().items(): + for symbol, targets in transitions.items(): + # DFA dictionaries store one state, NFA dictionaries a set. + if isinstance(targets, State): + targets = {targets} + rows, columns = coordinates.setdefault(symbol, ([], [])) + for target in targets: + rows.append(self.state_indices[source]) + columns.append(self.state_indices[target]) + for symbol, (rows, columns) in coordinates.items(): + self.matrices[symbol] = csr_matrix( + ([True] * len(rows), (rows, columns)), + shape=(self.num_states, self.num_states), + dtype=bool, + ) + + @property + def num_states(self) -> int: + """Number of states, including isolated ones.""" + return len(self.states) + + def accepts(self, word: Iterable[Symbol]) -> bool: + """Interpret a word (an iterable of symbols or their raw values).""" + starts = list(self.start_states) + current = csr_matrix( + ([True] * len(starts), ([0] * len(starts), starts)), + shape=(1, self.num_states), + 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 bool(self.final_states.intersection(current.indices)) + + def transitive_closure(self) -> csr_matrix: + """Return reflexive reachability by Boolean repeated squaring. + + Including the diagonal accounts for empty words and zero-length paths. + No dense matrices are created. + """ + closure = eye(self.num_states, format="csr", dtype=bool) + for matrix in self.matrices.values(): + closure = closure + matrix + while True: + extended = closure + closure @ closure + if extended.nnz == closure.nnz: + return extended + closure = extended + + def is_empty(self) -> bool: + """Check whether any final state is reachable from a start state.""" + if not self.start_states or not self.final_states: + return True + closure = self.transitive_closure() + return closure[list(self.start_states), :][:, list(self.final_states)].nnz == 0 + + +def intersect_automata( + automaton1: AdjacencyMatrixFA, automaton2: AdjacencyMatrixFA +) -> AdjacencyMatrixFA: + """Build the product automaton with a Kronecker product for each label.""" + result = AdjacencyMatrixFA() + result.states = tuple( + State((left, right)) + for left in automaton1.states + for right in automaton2.states + ) + result.state_indices = {state: i for i, state in enumerate(result.states)} + width = automaton2.num_states + result.start_states = { + left * width + right + for left in automaton1.start_states + for right in automaton2.start_states + } + result.final_states = { + left * width + right + for left in automaton1.final_states + for right in automaton2.final_states + } + for symbol in automaton1.matrices.keys() & automaton2.matrices.keys(): + result.matrices[symbol] = kron( + automaton1.matrices[symbol], automaton2.matrices[symbol], format="csr" + ) + return result + + +def tensor_based_rpq( + regex: str, + graph: MultiDiGraph, + start_nodes: set[int] | None = None, + final_nodes: set[int] | None = None, +) -> set[tuple[int, int]]: + """Return graph vertex pairs connected by a word matching ``regex``. + + Omitted or empty boundary sets select all vertices. Paths of length zero + are allowed when the regular expression accepts the empty word. + """ + graph_fa = AdjacencyMatrixFA(graph_to_nfa(graph, start_nodes, final_nodes)) + query_fa = AdjacencyMatrixFA(regex_to_dfa(regex)) + product = intersect_automata(graph_fa, query_fa) + if not product.start_states or not product.final_states: + return set() + closure = product.transitive_closure() + width = query_fa.num_states + result = set() + for source in product.start_states: + for target in closure.getrow(source).indices: + if target in product.final_states: + result.add( + ( + graph_fa.states[source // width].value, + graph_fa.states[target // width].value, + ) + ) + return result diff --git a/project/multiple_source_rpq.py b/project/multiple_source_rpq.py new file mode 100644 index 000000000..b8b327203 --- /dev/null +++ b/project/multiple_source_rpq.py @@ -0,0 +1,77 @@ +"""Regular path queries using sparse multiple-source breadth-first search.""" + +from networkx import MultiDiGraph +from scipy.sparse import csr_matrix, eye, kron + +from project.automata_utils import graph_to_nfa, regex_to_dfa +from project.matrix_automata import AdjacencyMatrixFA + + +def ms_bfs_based_rpq( + regex: str, + graph: MultiDiGraph, + start_nodes: set[int] | None = None, + final_nodes: set[int] | None = None, +) -> set[tuple[int, int]]: + """Return vertex pairs whose connecting path matches ``regex``. + + The Boolean CSR frontier has one row per (source, query state) pair and + one column per graph vertex. For each label, a BFS step computes + Q.T @ frontier @ G, with one query matrix Q block per source and the + graph matrix G. Visited entries are removed before the next step. + + None or an empty boundary set selects all graph vertices, following the + course convention. Zero-length paths are included if the query accepts + the empty word. Unknown boundary vertices raise ValueError. Inputs are + not modified. No graph/query product adjacency matrix or all-pairs + closure is built. + """ + graph_fa = AdjacencyMatrixFA(graph_to_nfa(graph, start_nodes, final_nodes)) + query_fa = AdjacencyMatrixFA(regex_to_dfa(regex)) + sources = sorted(graph_fa.start_states) + if not sources or not graph_fa.final_states or not query_fa.start_states: + return set() + if not query_fa.final_states: + return set() + + query_size = query_fa.num_states + shape = (len(sources) * query_size, graph_fa.num_states) + seed_rows, seed_columns = [], [] + for source_index, vertex in enumerate(sources): + for state in query_fa.start_states: + seed_rows.append(source_index * query_size + state) + seed_columns.append(vertex) + frontier = csr_matrix( + ([True] * len(seed_rows), (seed_rows, seed_columns)), + shape=shape, + dtype=bool, + ) + visited = frontier.copy() + + source_identity = eye(len(sources), format="csr", dtype=bool) + transitions = [ + ( + kron(source_identity, query_fa.matrices[symbol].T, format="csr"), + graph_fa.matrices[symbol], + ) + for symbol in query_fa.matrices.keys() & graph_fa.matrices.keys() + ] + + while frontier.nnz: + following = csr_matrix(shape, dtype=bool) + for query_transpose, graph_matrix in transitions: + following = following + query_transpose @ frontier @ graph_matrix + following = following != following.multiply(visited) + following.eliminate_zeros() + visited = visited + following + frontier = following + + rows, columns = visited.nonzero() + return { + ( + graph_fa.states[sources[row // query_size]].value, + graph_fa.states[column].value, + ) + for row, column in zip(rows, columns) + if row % query_size in query_fa.final_states and column in graph_fa.final_states + } diff --git a/project/task6.py b/project/task6.py new file mode 100644 index 000000000..c6ab11262 --- /dev/null +++ b/project/task6.py @@ -0,0 +1,6 @@ +"""Assignment entry points for weak normalization and Hellings queries.""" + +from project.hellings import hellings_based_cfpq +from project.weak_normal_form import cfg_to_weak_normal_form + +__all__ = ["cfg_to_weak_normal_form", "hellings_based_cfpq"] diff --git a/project/weak_normal_form.py b/project/weak_normal_form.py new file mode 100644 index 000000000..6ec6a148e --- /dev/null +++ b/project/weak_normal_form.py @@ -0,0 +1,64 @@ +"""Language-preserving conversion to weak Chomsky normal form.""" + +from pyformlang.cfg import CFG, Production, Terminal, Variable + + +def cfg_to_weak_normal_form(cfg: CFG) -> CFG: + """Return an independent CFG with the same language and start symbol. + + Rules have the forms A -> B C, A -> a, or A -> epsilon. Empty words and + nullable constituents are retained, including epsilon inherited through + chain rules. The supplied grammar's productions and symbol sets are + unchanged; helper variables are fresh with respect to the input symbols. + """ + occupied = {symbol.value for symbol in list(cfg.variables) + list(cfg.terminals)} + next_index = 0 + + def fresh_variable() -> Variable: + nonlocal next_index + while True: + name = f"__wcnf_{next_index}" + next_index += 1 + if name not in occupied: + occupied.add(name) + return Variable(name) + + terminal_variables = {} + productions = [] + for production in cfg.productions: + body = list(production.body) + # Replace only terminals in compound bodies. + if len(body) > 1: + for index, symbol in enumerate(body): + if isinstance(symbol, Terminal): + if symbol not in terminal_variables: + variable = fresh_variable() + terminal_variables[symbol] = variable + productions.append(Production(variable, [symbol])) + body[index] = terminal_variables[symbol] + + head = production.head + # Expand long bodies into the rightward chain of binary productions. + for symbol in body[:-2]: + following = fresh_variable() + productions.append(Production(head, [symbol, following])) + head = following + productions.append(Production(head, body[-2:])) + + # The public method implements reflexive chain-pair closure and copies + # every non-chain production, including empty bodies. + working = CFG( + variables=set(cfg.variables), + terminals=set(cfg.terminals), + start_symbol=cfg.start_symbol, + productions=productions, + ).eliminate_unit_productions() + return CFG( + variables=set(working.variables), + terminals=set(working.terminals), + start_symbol=cfg.start_symbol, + productions={ + Production(production.head, list(production.body)) + for production in working.productions + }, + ) diff --git a/tasks.en.md b/tasks.en.md index d4e823e67..791cfa72e 100644 --- a/tasks.en.md +++ b/tasks.en.md @@ -93,7 +93,7 @@ If they are not specified, assume all vertices are start and final states. > Max score: 8 -- [ ] Using [sparse matrices from sciPy](https://docs.scipy.org/doc/scipy/reference/sparse.html), implement a **function** for reachability with regular constraints for multiple start vertices (algorithm based on multiple source BFS and linear algebra). +- [x] Using [sparse matrices from sciPy](https://docs.scipy.org/doc/scipy/reference/sparse.html), implement a **function** for reachability with regular constraints for multiple start vertices (algorithm based on multiple source BFS and linear algebra). - To construct the regular query and graph, use the results from [Task 2](#task-2-constructing-a-dfa-from-a-regular-expression-and-a-nfa-from-a-graph). - Required function: ```python @@ -101,7 +101,7 @@ If they are not specified, assume all vertices are start and final states. final_nodes: set[int]) -> set[tuple[int, int]]: pass ``` -- [ ] Add your own tests as needed. +- [x] Add your own tests as needed. ## Task 5. Experimental Study of RPQ algorithms diff --git a/tasks.md b/tasks.md index 4b4fe892d..80f1e859e 100644 --- a/tasks.md +++ b/tasks.md @@ -24,24 +24,24 @@ ## Задача 1. Инициализация рабочего окружения -- [ ] Сделать `fork` данного репозитория. -- [ ] Добавить ссылку на ваш `fork` в [таблицу](https://docs.google.com/spreadsheets/d/1X7Hx6IyltD_NyTTphyzbN74Ag-G_LDzUu4OGcHoI8tg/edit?usp=sharing). -- [ ] Добавить в совладельцы форка одного из ассистентов (чтобы узнать, кого именно, нужно посмотреть в таблицу) -- [ ] Реализовать модуль, предоставляющий перечисленные ниже возможности. Для работы с графами использовать [cfpq-data](https://formallanguageconstrainedpathquerying.github.io/CFPQ_Data/tutorial.html#graphs). Данный модуль в дальнейшем будет расширяться. Функции, которые необходимо реализовать: - - [ ] По имени графа вернуть количество вершин, рёбер и перечислить различные метки, встречающиеся на рёбрах. Для получения графа по имени использовать [эту функцию](https://formallanguageconstrainedpathquerying.github.io/CFPQ_Data/tutorial.html#load-graph). - - [ ] По количеству вершин в циклах и именам меток строить [граф из двух циклов](https://formallanguageconstrainedpathquerying.github.io/CFPQ_Data/reference/graphs/generated/cfpq_data.graphs.generators.labeled_two_cycles_graph.html#cfpq_data.graphs.generators.labeled_two_cycles_graph) и сохранять его в указанный файл в формате DOT (использовать pydot). -- [ ] Добавить необходимые тесты. +- [x] Сделать `fork` данного репозитория. +- [x] Добавить ссылку на ваш `fork` в [таблицу](https://docs.google.com/spreadsheets/d/1X7Hx6IyltD_NyTTphyzbN74Ag-G_LDzUu4OGcHoI8tg/edit?usp=sharing). +- [x] Добавить в совладельцы форка одного из ассистентов (чтобы узнать, кого именно, нужно посмотреть в таблицу) +- [x] Реализовать модуль, предоставляющий перечисленные ниже возможности. Для работы с графами использовать [cfpq-data](https://formallanguageconstrainedpathquerying.github.io/CFPQ_Data/tutorial.html#graphs). Данный модуль в дальнейшем будет расширяться. Функции, которые необходимо реализовать: + - [x] По имени графа вернуть количество вершин, рёбер и перечислить различные метки, встречающиеся на рёбрах. Для получения графа по имени использовать [эту функцию](https://formallanguageconstrainedpathquerying.github.io/CFPQ_Data/tutorial.html#load-graph). + - [x] По количеству вершин в циклах и именам меток строить [граф из двух циклов](https://formallanguageconstrainedpathquerying.github.io/CFPQ_Data/reference/graphs/generated/cfpq_data.graphs.generators.labeled_two_cycles_graph.html#cfpq_data.graphs.generators.labeled_two_cycles_graph) и сохранять его в указанный файл в формате DOT (использовать pydot). +- [x] Добавить необходимые тесты. ## Задача 2. Построение детерминированного конечного автомата по регулярному выражению и недетерминированного конечного автомата по графу -- [ ] Используя возможности [pyformlang](https://pyformlang.readthedocs.io/en/latest/) реализовать **функцию** построения минимального ДКА по заданному регулярному выражению. [Формат регулярного выражения](https://pyformlang.readthedocs.io/en/latest/usage.html#regular-expression). +- [x] Используя возможности [pyformlang](https://pyformlang.readthedocs.io/en/latest/) реализовать **функцию** построения минимального ДКА по заданному регулярному выражению. [Формат регулярного выражения](https://pyformlang.readthedocs.io/en/latest/usage.html#regular-expression). - Требуемая функция: ```python def regex_to_dfa(regex: str) -> DeterministicFiniteAutomaton: pass ``` -- [ ] Используя возможности [pyformlang](https://pyformlang.readthedocs.io/en/latest/) реализовать **функцию** построения недетерминированного конечного автомата по [графу](https://networkx.org/documentation/stable/reference/classes/multidigraph.html), в том числе по любому из графов, которые можно получить, пользуясь функциональностью, реализованной в [Задаче 1](#задача-1-инициализация-рабочего-окружения) (загруженный из набора данных по имени граф, сгенерированный синтетический граф). Предусмотреть возможность указывать стартовые и финальные вершины. Если они не указаны, то считать все вершины стартовыми и финальными. +- [x] Используя возможности [pyformlang](https://pyformlang.readthedocs.io/en/latest/) реализовать **функцию** построения недетерминированного конечного автомата по [графу](https://networkx.org/documentation/stable/reference/classes/multidigraph.html), в том числе по любому из графов, которые можно получить, пользуясь функциональностью, реализованной в [Задаче 1](#задача-1-инициализация-рабочего-окружения) (загруженный из набора данных по имени граф, сгенерированный синтетический граф). Предусмотреть возможность указывать стартовые и финальные вершины. Если они не указаны, то считать все вершины стартовыми и финальными. - Требуемая функция: ```python def graph_to_nfa( @@ -49,7 +49,7 @@ ) -> NondeterministicFiniteAutomaton: pass ``` -- [ ] Добавить собственные тесты при необходимости. +- [x] Добавить собственные тесты при необходимости. ## Задача 3. Регулярные запросы для всех пар вершин @@ -83,7 +83,7 @@ ## Задача 4. Регулярные запросы для нескольких стартовых вершин -- [ ] Используя [разреженные матрицы из sciPy](https://docs.scipy.org/doc/scipy/reference/sparse.html) реализовать **функцию** достижимости с регулярными ограничениями с несколькими стартовыми вершинами (алгоритм на основе multiple source BFS через линейную алгебру). +- [x] Используя [разреженные матрицы из sciPy](https://docs.scipy.org/doc/scipy/reference/sparse.html) реализовать **функцию** достижимости с регулярными ограничениями с несколькими стартовыми вершинами (алгоритм на основе multiple source BFS через линейную алгебру). - Для конструирования регулярного запроса и графа использовать [Задачи 2](#задача-2-построение-детерминированного-конечного-автомата-по-регулярному-выражению-и-недетерминированного-конечного-автомата-по-графу). - Требуемая функция: ```python @@ -91,7 +91,7 @@ final_nodes: set[int]) -> set[tuple[int, int]]: pass ``` -- [ ] Добавить собственные тесты при необходимости. +- [x] Добавить собственные тесты при необходимости. ## Задача 5. Экспериментальное исследование алгоритмов для регулярных запросов @@ -156,12 +156,12 @@ ## Задача 6. Преобразование грамматики в ОНФХ, алгоритм Хеллингса -- [ ] Используя [возможности pyformlang для работы с контекстно-свободными грамматиками](https://pyformlang.readthedocs.io/en/latest/usage.html#context-free-grammar) реализовать **функцию** преобразования контекстно-свободной грамматики в ослабленную нормальную форму Хомского (ОНФХ). +- [x] Используя [возможности pyformlang для работы с контекстно-свободными грамматиками](https://pyformlang.readthedocs.io/en/latest/usage.html#context-free-grammar) реализовать **функцию** преобразования контекстно-свободной грамматики в ослабленную нормальную форму Хомского (ОНФХ). ```python def cfg_to_weak_normal_form(cfg: pyformlang.cfg.CFG) -> pyformlang.cfg.CFG: pass ``` -- [ ] Реализовать **функцию**, основанную на алгоритме Хеллингса, решающую задачу достижимости между всеми парами вершин для заданного графа и заданной КС грамматики (не обязательно в ОНФХ). +- [x] Реализовать **функцию**, основанную на алгоритме Хеллингса, решающую задачу достижимости между всеми парами вершин для заданного графа и заданной КС грамматики (не обязательно в ОНФХ). - Для работы с графом использовать функции из предыдущих задач. ```python def hellings_based_cfpq( @@ -172,7 +172,7 @@ ) -> set[tuple[int, int]]: pass ``` -- [ ] Добавить собственные тесты при необходимости. +- [x] Добавить собственные тесты при необходимости. ## Задача 7. Матричный алгоритм решения задачи достижимости с КС ограничениями diff --git a/tests/autotests/rpq_template_test.py b/tests/autotests/rpq_template_test.py index f57e27a2a..c70538778 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.multiple_source_rpq import ms_bfs_based_rpq except ImportError: pass 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..486c1de05 100644 --- a/tests/autotests/test_task03.py +++ b/tests/autotests/test_task03.py @@ -12,8 +12,12 @@ # 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.automata_utils import regex_to_dfa + from project.matrix_automata 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..90b244c95 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.matrix_automata import tensor_based_rpq + from project.multiple_source_rpq import ms_bfs_based_rpq except ImportError: pytestmark = pytest.mark.skip("Task 4 is not ready to test!") diff --git a/tests/test_graph_utils.py b/tests/test_graph_utils.py new file mode 100644 index 000000000..937fa709a --- /dev/null +++ b/tests/test_graph_utils.py @@ -0,0 +1,126 @@ +from unittest.mock import Mock + +import cfpq_data +import networkx as nx +import pydot +import pytest + +from project.graph_utils import create_two_cycles_graph, get_graph_info + + +@pytest.mark.parametrize( + "graph_name", + [name for name in cfpq_data.DATASET if name in {"generations", "skos"}], +) +def test_get_graph_info_from_dataset(graph_name): + """Compare statistics with independently parsed real dataset edges.""" + csv_path = cfpq_data.download(graph_name) + vertices, labels = set(), set() + edge_count = 0 + for line in csv_path.read_text(encoding="utf-8").splitlines(): + source, target, label = line.split() + vertices.update((source, target)) + labels.add(label) + edge_count += 1 + + assert get_graph_info(graph_name) == (len(vertices), edge_count, labels) + + +def test_get_graph_info_with_common_node(tmp_path, monkeypatch): + csv_path = tmp_path / "graph.csv" + csv_path.write_text("0 1 a\n1 0 a\n0 2 b\n2 0 b\n", encoding="utf-8") + monkeypatch.setattr(cfpq_data, "download", Mock(return_value=csv_path)) + + assert get_graph_info("example") == (3, 4, {"a", "b"}) + + +def test_get_graph_info_without_common_node(tmp_path, monkeypatch): + csv_path = tmp_path / "graph.csv" + csv_path.write_text("0 1 a\n1 0 a\n2 3 b\n3 2 b\n", encoding="utf-8") + monkeypatch.setattr(cfpq_data, "download", Mock(return_value=csv_path)) + + assert get_graph_info("example") == (4, 4, {"a", "b"}) + + +def test_get_graph_info_unknown_graph(): + with pytest.raises(FileNotFoundError): + get_graph_info("__missing_test_graph__") + + +def test_get_graph_info_empty_graph(tmp_path, monkeypatch): + csv_path = tmp_path / "empty.csv" + csv_path.write_text("", encoding="utf-8") + monkeypatch.setattr(cfpq_data, "download", Mock(return_value=csv_path)) + + assert get_graph_info("example") == (0, 0, set()) + + +def test_get_graph_info_parallel_edges_and_self_loop(tmp_path, monkeypatch): + csv_path = tmp_path / "graph.csv" + csv_path.write_text("0 1 a\n0 1 a\n1 1 b\n", encoding="utf-8") + monkeypatch.setattr(cfpq_data, "download", Mock(return_value=csv_path)) + + assert get_graph_info("example") == (2, 3, {"a", "b"}) + + +def test_create_two_cycles_graph(tmp_path): + graph = create_two_cycles_graph(2, 3, ("a", "b"), tmp_path / "graph.dot") + + assert graph.number_of_nodes() == 6 + assert graph.number_of_edges() == 7 + assert set(nx.get_edge_attributes(graph, "label").values()) == {"a", "b"} + cycles = list(nx.simple_cycles(graph)) + assert len(cycles) == 2 + assert sorted(map(len, cycles)) == [3, 4] + assert set(cycles[0]) & set(cycles[1]) == {0} + + +def test_create_two_cycles_saves_dot(tmp_path): + output_path = str(tmp_path / "graph.dot") + create_two_cycles_graph(1, 1, ("a", "b"), output_path) + + dot_graph = pydot.graph_from_dot_file(output_path)[0] + assert dot_graph.get_type() == "digraph" + assert {node.get_name() for node in dot_graph.get_nodes()} == {"0", "1", "2"} + assert { + (edge.get_source(), edge.get_destination(), edge.get_label()) + for edge in dot_graph.get_edges() + } == { + ("0", "1", "a"), + ("1", "0", "a"), + ("0", "2", "b"), + ("2", "0", "b"), + } + + +@pytest.mark.parametrize("n, m", [(0, 2), (2, 0), (-1, 2)]) +def test_create_two_cycles_rejects_nonpositive_size(tmp_path, n, m): + with pytest.raises(ValueError): + create_two_cycles_graph(n, m, ("a", "b"), tmp_path / "graph.dot") + + +def test_create_two_cycles_requires_two_labels(tmp_path): + with pytest.raises(ValueError): + create_two_cycles_graph(2, 3, ("a",), tmp_path / "graph.dot") + + +def test_create_two_cycles_requires_integer_sizes(tmp_path): + with pytest.raises(TypeError): + create_two_cycles_graph(1.5, 2, ("a", "b"), tmp_path / "graph.dot") + + +@pytest.mark.parametrize("labels", ["ab", ("a", None)]) +def test_create_two_cycles_rejects_invalid_label_types(tmp_path, labels): + with pytest.raises(TypeError): + create_two_cycles_graph(1, 1, labels, tmp_path / "graph.dot") + + +def test_create_two_cycles_with_same_labels(tmp_path): + output_path = str(tmp_path / "graph.dot") + graph = create_two_cycles_graph(1, 1, ("same", "same"), output_path) + + assert graph.number_of_edges() == 4 + assert set(nx.get_edge_attributes(graph, "label").values()) == {"same"} + dot_graph = pydot.graph_from_dot_file(output_path)[0] + assert len(dot_graph.get_edges()) == 4 + assert {edge.get_label() for edge in dot_graph.get_edges()} == {"same"} diff --git a/tests/test_hellings.py b/tests/test_hellings.py new file mode 100644 index 000000000..6e6d79c59 --- /dev/null +++ b/tests/test_hellings.py @@ -0,0 +1,216 @@ +"""Check context-free endpoint relations and the existing graph conventions.""" + +import random +from copy import deepcopy + +import networkx as nx +import pytest +from pyformlang.cfg import CFG, Production, Terminal, Variable + +from project.hellings import hellings_based_cfpq +from project.multiple_source_rpq import ms_bfs_based_rpq + + +@pytest.mark.parametrize("graph_type", [nx.DiGraph, nx.MultiDiGraph]) +def test_nested_language_and_custom_start(graph_type): + grammar = CFG.from_text("Q -> a Q b | epsilon", start_symbol=Variable("Q")) + graph = graph_type() + graph.add_nodes_from([10, 20, 30, 40, 50, 99]) + for source, target, label in [ + (10, 20, "a"), + (20, 30, "a"), + (30, 40, "b"), + (40, 50, "b"), + ]: + graph.add_edge(source, target, label=label) + assert hellings_based_cfpq(grammar, graph, {10}, {50}) == {(10, 50)} + assert hellings_based_cfpq(grammar, graph) == { + (10, 50), + (20, 40), + *((vertex, vertex) for vertex in graph), + } + + +@pytest.mark.parametrize("graph_type", [nx.DiGraph, nx.MultiDiGraph]) +@pytest.mark.parametrize( + "text", + [ + "S -> epsilon", + "S -> A B\nA -> epsilon\nB -> epsilon", + "S -> A\nA -> B\nB -> A | epsilon", + ], +) +def test_epsilon_only_includes_isolated_vertices(graph_type, text): + graph = graph_type() + graph.add_nodes_from([-5, 40, 99]) + graph.add_edge(-5, 40, label="a") + assert hellings_based_cfpq(CFG.from_text(text), graph) == { + (-5, -5), + (40, 40), + (99, 99), + } + + +@pytest.mark.parametrize("graph_type", [nx.DiGraph, nx.MultiDiGraph]) +@pytest.mark.parametrize("text", ["S -> epsilon", "S -> a", "S -> S"]) +def test_empty_graph(graph_type, text): + assert hellings_based_cfpq(CFG.from_text(text), graph_type()) == set() + + +@pytest.mark.parametrize("graph_type", [nx.DiGraph, nx.MultiDiGraph]) +def test_empty_language(graph_type): + graph = graph_type() + graph.add_edge(10, 20, label="a") + assert hellings_based_cfpq(CFG.from_text("S -> A\nA -> S"), graph) == set() + assert hellings_based_cfpq(CFG(start_symbol=Variable("S")), graph) == set() + + +@pytest.mark.parametrize("graph_type", [nx.DiGraph, nx.MultiDiGraph]) +def test_recursive_ambiguous_grammar_on_cycle(graph_type): + graph = graph_type() + graph.add_edge(-5, 40, label="a") + graph.add_edge(40, -5, label="a") + grammar = CFG.from_text("S -> S S | a | epsilon") + assert hellings_based_cfpq(grammar, graph) == { + (-5, -5), + (-5, 40), + (40, -5), + (40, 40), + } + + +def test_parallel_edges_keep_every_label_and_deduplicate_pairs(): + graph = nx.MultiDiGraph() + graph.add_edge(-5, 40, label="a") + graph.add_edge(-5, 40, label="b") + graph.add_edge(-5, 40, label="a") + for query in ["S -> a", "S -> b", "S -> a | b"]: + assert hellings_based_cfpq(CFG.from_text(query), graph) == {(-5, 40)} + + +def test_equal_textual_terminal_and_variable_values(): + start, variable = Variable("S"), Variable("A") + grammar = CFG( + start_symbol=start, + productions=[ + Production(start, [Terminal("A"), variable, Terminal("b")]), + Production(variable, [Terminal("c")]), + ], + ) + graph = nx.DiGraph() + for source, target, label in [(10, 20, "A"), (20, 30, "c"), (30, 40, "b")]: + graph.add_edge(source, target, label=label) + assert hellings_based_cfpq(grammar, graph) == {(10, 40)} + + +@pytest.mark.parametrize( + "starts, finals, expected", + [ + (None, None, {(10, 20), (30, 20)}), + (set(), set(), {(10, 20), (30, 20)}), + ({10}, None, {(10, 20)}), + ({10}, set(), {(10, 20)}), + (None, {20}, {(10, 20), (30, 20)}), + (set(), {30}, set()), + ], +) +def test_boundary_conventions(starts, finals, expected): + graph = nx.DiGraph() + graph.add_edge(10, 20, label="a") + graph.add_edge(30, 20, label="a") + graph.add_node(99) + assert ( + hellings_based_cfpq(CFG.from_text("S -> a"), graph, starts, finals) == expected + ) + + +def test_epsilon_is_filtered_by_both_boundaries(): + graph = nx.DiGraph() + graph.add_nodes_from([10, 20, 30, 99]) + assert hellings_based_cfpq( + CFG.from_text("S -> epsilon"), graph, {10, 20, 99}, {20, 30, 99} + ) == {(20, 20), (99, 99)} + + +@pytest.mark.parametrize("starts, finals", [({99}, None), (None, {99})]) +def test_unknown_boundary_vertices(starts, finals): + graph = nx.DiGraph() + graph.add_node(10) + with pytest.raises(ValueError, match="graph vertices"): + hellings_based_cfpq(CFG.from_text("S -> epsilon"), graph, starts, finals) + + +def test_boundaries_do_not_prune_intermediate_vertices(): + graph = nx.DiGraph() + graph.add_edge(10, 20, label="a") + graph.add_edge(20, 30, label="b") + assert hellings_based_cfpq(CFG.from_text("S -> a b"), graph, {10}, {30}) == { + (10, 30) + } + + +def test_repeated_queries_preserve_all_inputs(): + graph = nx.MultiDiGraph() + graph.add_edge(10, 20, label="a", metadata={"weight": 2}) + graph.add_edge(20, 30, label="b") + graph.add_node(99, description="isolated") + original_graph = deepcopy(graph) + grammar = CFG.from_text("S -> a A | epsilon\nA -> b") + grammar_snapshot = ( + set(grammar.productions), + set(grammar.variables), + set(grammar.terminals), + grammar.start_symbol, + ) + starts, finals = {10, 99}, {30, 99} + for _ in range(2): + assert hellings_based_cfpq(grammar, graph, starts, finals) == { + (10, 30), + (99, 99), + } + assert nx.utils.graphs_equal(graph, original_graph) + assert starts == {10, 99} + assert finals == {30, 99} + assert ( + set(grammar.productions), + set(grammar.variables), + set(grammar.terminals), + grammar.start_symbol, + ) == grammar_snapshot + + +@pytest.mark.parametrize("seed", range(4)) +@pytest.mark.parametrize( + "regex, text", + [ + ("epsilon", "S -> epsilon"), + ("a", "S -> a"), + ("a b", "S -> a b"), + ("a*", "S -> a S | epsilon"), + ("(a | b)*", "S -> A S | epsilon\nA -> a | b"), + ("a* b*", "S -> A B\nA -> a A | epsilon\nB -> b B | epsilon"), + ("(a b)*", "S -> a b S | epsilon"), + ], +) +def test_regular_grammars_match_existing_rpq(regex, text, seed): + rng = random.Random(seed) + vertices = [10, 30, 50] + graph = nx.MultiDiGraph() + graph.add_nodes_from(vertices + [99]) + for _ in range(12): + graph.add_edge( + rng.choice(vertices), rng.choice(vertices), label=rng.choice("ab") + ) + starts, finals = {10, 30, 99}, {30, 50, 99} + expected = ms_bfs_based_rpq(regex, graph, starts, finals) + assert hellings_based_cfpq(CFG.from_text(text), graph, starts, finals) == expected + + +def test_assignment_entry_points(): + from project import task6 + from project.weak_normal_form import cfg_to_weak_normal_form + + assert task6.hellings_based_cfpq is hellings_based_cfpq + assert task6.cfg_to_weak_normal_form is cfg_to_weak_normal_form + assert callable(task6.hellings_based_cfpq) + assert callable(task6.cfg_to_weak_normal_form) diff --git a/tests/test_matrix_automata.py b/tests/test_matrix_automata.py new file mode 100644 index 000000000..963e035a1 --- /dev/null +++ b/tests/test_matrix_automata.py @@ -0,0 +1,214 @@ +"""Check sparse automata against pyformlang and RPQ against explicit search.""" + +from collections import deque +from itertools import product +import random + +import networkx as nx +from pyformlang.finite_automaton import NondeterministicFiniteAutomaton, State, Symbol +import pytest +from scipy.sparse import csr_matrix + +from project.automata_utils import graph_to_nfa, regex_to_dfa +from project.matrix_automata import ( + AdjacencyMatrixFA, + intersect_automata, + tensor_based_rpq, +) + + +def words(alphabet, max_length): + for length in range(max_length + 1): + yield from product(alphabet, repeat=length) + + +@pytest.mark.parametrize("regex", ["", "epsilon", "a", "a*", "(a | b)* a b", "token"]) +def test_dfa_interpretation(regex): + dfa = regex_to_dfa(regex) + matrix_fa = AdjacencyMatrixFA(dfa) + for word in words(["a", "b", "token", "unknown"], 3): + assert matrix_fa.accepts(iter(word)) == dfa.accepts(word) + assert matrix_fa.accepts(map(Symbol, word)) == dfa.accepts(word) + assert matrix_fa.is_empty() == dfa.is_empty() + + +def test_nfa_multiple_starts_and_nondeterministic_transitions(): + nfa = NondeterministicFiniteAutomaton(states={State("isolated")}) + nfa.add_start_state("left") + nfa.add_start_state("right") + nfa.add_final_state("end") + nfa.add_transitions( + [ + ("left", "a", "dead"), + ("left", "a", "middle"), + ("middle", "b", "end"), + ("right", "b", "end"), + ] + ) + matrix_fa = AdjacencyMatrixFA(nfa) + assert matrix_fa.num_states == len(nfa.states) + for matrix in matrix_fa.matrices.values(): + assert isinstance(matrix, csr_matrix) + assert matrix.dtype == bool + assert matrix.shape == (len(nfa.states), len(nfa.states)) + for word in words("ab", 4): + assert matrix_fa.accepts(word) == nfa.accepts(word) + assert not matrix_fa.is_empty() + + +def test_empty_and_isolated_automata(): + empty = AdjacencyMatrixFA(NondeterministicFiniteAutomaton()) + assert empty.num_states == 0 + assert empty.is_empty() + assert not empty.accepts([]) + assert empty.transitive_closure().shape == (0, 0) + + nfa = NondeterministicFiniteAutomaton() + nfa.add_start_state(10) + nfa.add_final_state(20) + matrix_fa = AdjacencyMatrixFA(nfa) + assert matrix_fa.is_empty() + assert not matrix_fa.accepts([]) + nfa.add_final_state(10) + matrix_fa = AdjacencyMatrixFA(nfa) + assert not matrix_fa.is_empty() + assert matrix_fa.accepts([]) + assert not matrix_fa.accepts(["a"]) + + +def test_transitive_closure_requires_multiple_squarings(): + nfa = NondeterministicFiniteAutomaton() + nfa.add_start_state(0) + nfa.add_final_state(12) + for i in range(12): + nfa.add_transition(i, "a" if i % 2 else "b", i + 1) + matrix_fa = AdjacencyMatrixFA(nfa) + closure = matrix_fa.transitive_closure() + for source in range(13): + for target in range(13): + assert bool( + closure[ + matrix_fa.state_indices[State(source)], + matrix_fa.state_indices[State(target)], + ] + ) == (source <= target) + assert not matrix_fa.is_empty() + + +@pytest.mark.parametrize( + "left, right", + [("a*", "b*"), ("a", "b"), ("(a | b)*", "a b*"), ("epsilon", "a*"), ("a b", "b a")], +) +def test_intersection_acceptance_and_rejection(left, right): + fa1, fa2 = regex_to_dfa(left), regex_to_dfa(right) + intersection = intersect_automata(AdjacencyMatrixFA(fa1), AdjacencyMatrixFA(fa2)) + for word in words("ab", 5): + assert intersection.accepts(word) == (fa1.accepts(word) and fa2.accepts(word)) + assert intersection.is_empty() == fa1.get_intersection(fa2).is_empty() + + +def test_intersection_of_nfas_and_empty_automaton(): + nfa = NondeterministicFiniteAutomaton() + nfa.add_start_state(10) + nfa.add_start_state(20) + nfa.add_final_state(30) + nfa.add_transitions([(10, "a", 20), (10, "a", 30), (20, "b", 30)]) + matrix_fa = AdjacencyMatrixFA(nfa) + intersection = intersect_automata(matrix_fa, matrix_fa) + for word in words("ab", 4): + assert intersection.accepts(word) == nfa.accepts(word) + for left, right in [ + (AdjacencyMatrixFA(), matrix_fa), + (matrix_fa, AdjacencyMatrixFA()), + ]: + intersection = intersect_automata(left, right) + assert intersection.num_states == 0 + assert intersection.is_empty() + assert not intersection.accepts([]) + + +def test_rpq_parallel_edges_nonconsecutive_vertices_and_filters(): + graph = nx.MultiDiGraph() + graph.add_nodes_from([10, 30, 90, -5]) + graph.add_edge(10, 30, label="a") + graph.add_edge(10, 30, label="a") + graph.add_edge(10, 30, label="b") + graph.add_edge(30, 90, label="b") + graph.add_edge(90, 90, label="b") + assert tensor_based_rpq("a b*", graph) == {(10, 30), (10, 90)} + assert tensor_based_rpq("a b*", graph, {10}, {90}) == {(10, 90)} + assert tensor_based_rpq("a b*", graph, {30}, {90}) == set() + assert tensor_based_rpq("epsilon", graph) == {(v, v) for v in graph} + assert tensor_based_rpq("a*", graph, {10, -5}, {30, -5}) == {(10, 30), (-5, -5)} + assert tensor_based_rpq("missing", graph) == set() + + +@pytest.mark.parametrize("regex", ["epsilon", "a", "a*"]) +def test_rpq_empty_graph(regex): + assert tensor_based_rpq(regex, nx.MultiDiGraph()) == set() + + +def reference_rpq(regex, graph, starts, finals): + """An independent BFS over graph/DFA state pairs, without matrices.""" + dfa = regex_to_dfa(regex) + result = set() + for source in starts: + visited = {(source, state) for state in dfa.start_states} + queue = deque(visited) + while queue: + vertex, state = queue.popleft() + if vertex in finals and state in dfa.final_states: + result.add((source, vertex)) + for _, target, data in graph.out_edges(vertex, data=True): + for next_state in dfa(state, data["label"]): + pair = (target, next_state) + if pair not in visited: + visited.add(pair) + queue.append(pair) + return result + + +@pytest.mark.parametrize("seed", range(5)) +def test_rpq_matches_explicit_product_search(seed): + rng = random.Random(seed) + graph = nx.MultiDiGraph() + nodes = [-10, 20, 40, 100, 200] + graph.add_nodes_from(nodes) + for _ in range(15): + graph.add_edge( + rng.choice(nodes), rng.choice(nodes), label=rng.choice(["a", "b"]) + ) + starts, finals = set(nodes[:3]), set(nodes[2:]) + for regex in ["a", "a*", "a b", "(a | b)*", "(a b)*", "a* b a*", "epsilon"]: + assert tensor_based_rpq(regex, graph, starts, finals) == reference_rpq( + regex, graph, starts, finals + ) + + +def test_graph_conversion_preserves_isolated_vertices_and_inputs(): + graph = nx.MultiDiGraph() + graph.add_nodes_from([10, 20, 30]) + graph.add_edge(10, 20, label="a") + before = graph.copy() + starts, finals = {10, 30}, {20, 30} + nfa = graph_to_nfa(graph, starts, finals) + assert {state.value for state in nfa.states} == {10, 20, 30} + assert {state.value for state in nfa.start_states} == starts + assert {state.value for state in nfa.final_states} == finals + assert nfa.accepts([]) + assert nfa.accepts(["a"]) + assert nx.utils.graphs_equal(graph, before) + assert starts == {10, 30} and finals == {20, 30} + for boundaries in [(None, None), (set(), set())]: + nfa = graph_to_nfa(graph, *boundaries) + assert nfa.start_states == nfa.final_states == nfa.states + assert tensor_based_rpq("epsilon", graph, *boundaries) == { + (v, v) for v in graph + } + + +def test_graph_conversion_rejects_unknown_boundary_vertices(): + graph = nx.MultiDiGraph() + graph.add_node(10) + with pytest.raises(ValueError, match="graph vertices"): + graph_to_nfa(graph, {20}, {10}) diff --git a/tests/test_multiple_source_rpq.py b/tests/test_multiple_source_rpq.py new file mode 100644 index 000000000..2d321ef40 --- /dev/null +++ b/tests/test_multiple_source_rpq.py @@ -0,0 +1,160 @@ +"""Compare sparse MS-BFS with independent BFS and the tensor algorithm.""" + +from collections import deque +import random + +import cfpq_data +import networkx as nx +import pytest +from scipy.sparse import csr_matrix + +from project.automata_utils import regex_to_dfa +from project.matrix_automata import AdjacencyMatrixFA, tensor_based_rpq +from project.multiple_source_rpq import ms_bfs_based_rpq + + +def reference_rpq(regex, graph, starts, finals): + """Explicit BFS over vertex/DFA-state pairs, separately for each source.""" + dfa = regex_to_dfa(regex) + result = set() + for source in starts: + visited = {(source, state) for state in dfa.start_states} + queue = deque(visited) + while queue: + vertex, state = queue.popleft() + if vertex in finals and state in dfa.final_states: + result.add((source, vertex)) + for _, target, data in graph.out_edges(vertex, data=True): + for next_state in dfa(state, data["label"]): + pair = (target, next_state) + if pair not in visited: + visited.add(pair) + queue.append(pair) + return result + + +def test_multiple_sources_keep_separate_reachability(): + graph = nx.MultiDiGraph() + graph.add_nodes_from([10, 20, 30, 40, -5]) + graph.add_edge(10, 30, label="a") + graph.add_edge(10, 30, label="a") + graph.add_edge(20, 30, label="b") + graph.add_edge(30, 40, label="b") + graph.add_edge(40, 30, label="a") + graph.add_edge(40, 40, label="b") + starts, finals = {10, 20, 30, -5}, {30, 40, -5} + original = graph.copy() + + assert ms_bfs_based_rpq("a b*", graph, starts, finals) == {(10, 30), (10, 40)} + assert ms_bfs_based_rpq("epsilon", graph, starts, finals) == {(30, 30), (-5, -5)} + assert ms_bfs_based_rpq("a*", graph, starts, finals) == { + (10, 30), + (30, 30), + (-5, -5), + } + assert ms_bfs_based_rpq("missing", graph, starts, finals) == set() + assert nx.utils.graphs_equal(graph, original) + assert starts == {10, 20, 30, -5} + assert finals == {30, 40, -5} + + +def test_revisit_vertex_in_different_query_states(): + graph = nx.MultiDiGraph() + graph.add_edge(10, 10, label="a") + graph.add_edge(10, 20, label="b") + assert ms_bfs_based_rpq("a a b", graph, {10}, {20}) == {(10, 20)} + + +@pytest.mark.parametrize("regex", ["", "epsilon", "a", "a*", "(a | b)*"]) +def test_empty_graph(regex): + assert ms_bfs_based_rpq(regex, nx.MultiDiGraph()) == set() + + +@pytest.mark.parametrize("boundaries", [(None, None), (set(), set())]) +def test_default_boundaries_include_isolated_vertices(boundaries): + graph = nx.MultiDiGraph() + graph.add_nodes_from([10, 20, 30]) + graph.add_edge(10, 20, label="token") + assert ms_bfs_based_rpq("epsilon", graph, *boundaries) == { + (10, 10), + (20, 20), + (30, 30), + } + assert ms_bfs_based_rpq("token", graph, *boundaries) == {(10, 20)} + + +@pytest.mark.parametrize("starts, finals", [({99}, {10}), ({10}, {99})]) +def test_unknown_boundary_vertices(starts, finals): + graph = nx.MultiDiGraph() + graph.add_node(10) + with pytest.raises(ValueError, match="graph vertices"): + ms_bfs_based_rpq("epsilon", graph, starts, finals) + + +@pytest.mark.parametrize("seed", range(8)) +def test_matches_reference_and_tensor_on_random_graphs(seed): + rng = random.Random(seed) + nodes = [-10, 20, 40, 100, 200] + graph = nx.MultiDiGraph() + graph.add_nodes_from(nodes + [999]) + for _ in range(20): + graph.add_edge( + rng.choice(nodes), rng.choice(nodes), label=rng.choice(["a", "b"]) + ) + starts, finals = {-10, 40, 999}, {20, 100, 999} + queries = ["", "epsilon", "a", "a*", "a b", "(a | b)*", "(a b)*", "a* b a*"] + for regex in queries: + expected = reference_rpq(regex, graph, starts, finals) + assert ms_bfs_based_rpq(regex, graph, starts, finals) == expected + assert tensor_based_rpq(regex, graph, starts, finals) == expected + + +def test_long_chain_uses_no_dense_matrices_or_closure(monkeypatch): + graph = nx.MultiDiGraph() + for vertex in range(130): + graph.add_edge(vertex, vertex + 1, label="a") + + def forbidden(*args, **kwargs): + raise AssertionError("MS-BFS must not use dense matrices or a closure") + + monkeypatch.setattr(AdjacencyMatrixFA, "transitive_closure", forbidden) + monkeypatch.setattr(csr_matrix, "toarray", forbidden) + monkeypatch.setattr(csr_matrix, "todense", forbidden) + assert ms_bfs_based_rpq("a*", graph, {0, 65, 130}, {130}) == { + (0, 130), + (65, 130), + (130, 130), + } + + +@pytest.fixture( + scope="module", + params=[name for name in cfpq_data.DATASET if name in {"skos", "generations"}], +) +def dataset_graph(request): + """Download each small real dataset graph once for all query checks.""" + return cfpq_data.graph_from_csv(cfpq_data.download(request.param)) + + +def test_real_dataset_graphs(dataset_graph): + graph = dataset_graph + nodes = sorted(graph.nodes) + labels = sorted(nx.get_edge_attributes(graph, "label").values()) + first, last = labels[0], labels[-1] + starts, finals = set(nodes[::13]), set(nodes[::7]) + queries = ["epsilon", first, f"{first}*", f"({first} | {last})*", f"{first} {last}"] + for regex in queries: + assert ms_bfs_based_rpq(regex, graph, starts, finals) == reference_rpq( + regex, graph, starts, finals + ) + + +def test_single_label_query_on_dataset_has_exact_edge_pairs(dataset_graph): + graph = dataset_graph + label = min(nx.get_edge_attributes(graph, "label").values()) + expected = { + (source, target) + for source, target, data in graph.edges(data=True) + if data["label"] == label + } + assert ms_bfs_based_rpq(label, graph) == expected diff --git a/tests/test_task2.py b/tests/test_task2.py new file mode 100644 index 000000000..80822d0c6 --- /dev/null +++ b/tests/test_task2.py @@ -0,0 +1,80 @@ +import cfpq_data +import networkx as nx +from pyformlang.finite_automaton import DeterministicFiniteAutomaton + +from project.automata_construction import graph_to_nfa, regex_to_dfa + + +def test_regex_to_dfa_is_minimized_and_recognizes_language(): + dfa = regex_to_dfa("(a | b)* c") + + assert isinstance(dfa, DeterministicFiniteAutomaton) + assert dfa.is_deterministic() + assert len(dfa.states) == len(dfa.minimize().states) + assert dfa.accepts(["a", "b", "c"]) + assert dfa.accepts(["c"]) + assert not dfa.accepts(["c", "a"]) + assert not dfa.accepts([]) + + +def test_regex_to_dfa_minimizes_equivalent_expressions(): + first = regex_to_dfa("(a | b)*") + equivalent = regex_to_dfa("(a | b)* (a | b)*") + + assert first.is_equivalent_to(equivalent) + assert len(first.states) == len(equivalent.states) + + +def test_graph_to_nfa_handles_nondeterminism_parallel_edges_and_selected_states(): + graph = nx.MultiDiGraph() + graph.add_nodes_from([0, 1, 2, 3, 4]) + graph.add_edge(0, 1, label="a") + graph.add_edge(0, 1, label="a") + graph.add_edge(0, 2, label="a") + graph.add_edge(1, 3, label="b") + graph.add_edge(2, 3, label="c") + + nfa = graph_to_nfa(graph, {0}, {3}) + + assert nfa.accepts(["a", "b"]) + assert nfa.accepts(["a", "c"]) + assert not nfa.accepts(["a"]) + assert not nfa.accepts(["b"]) + assert graph.number_of_edges() == 5 + + +def test_graph_to_nfa_supports_cfpq_data_generated_graph(): + graph = cfpq_data.labeled_two_cycles_graph(1, 1, labels=("a", "b")) + + nfa = graph_to_nfa(graph, {0}, {0}) + + assert nfa.accepts(["a", "a"]) + assert nfa.accepts(["b", "b"]) + assert not nfa.accepts(["a", "b"]) + + +def test_graph_to_nfa_defaults_empty_state_sets_to_all_vertices(): + graph = nx.MultiDiGraph() + graph.add_edge(0, 1, label="x") + graph.add_node(2) + + nfa = graph_to_nfa(graph, set(), set()) + + assert nfa.accepts([]) + assert nfa.accepts(["x"]) + + +def test_graph_to_nfa_can_be_called_without_state_sets(): + graph = nx.MultiDiGraph() + graph.add_edge(0, 1, label="edge") + + nfa = graph_to_nfa(graph) + + assert nfa.accepts([]) + assert nfa.accepts(["edge"]) + + +def test_graph_to_nfa_empty_graph_accepts_nothing(): + nfa = graph_to_nfa(nx.MultiDiGraph()) + + assert nfa.is_empty() diff --git a/tests/test_weak_normal_form.py b/tests/test_weak_normal_form.py new file mode 100644 index 000000000..0ba7334e4 --- /dev/null +++ b/tests/test_weak_normal_form.py @@ -0,0 +1,147 @@ +"""Check weak normal form and preservation of grammar languages.""" + +from itertools import product + +import pytest +from pyformlang.cfg import CFG, Production, Terminal, Variable + +from project.weak_normal_form import cfg_to_weak_normal_form + + +def assert_weak_form(cfg): + for production in cfg.productions: + body = production.body + assert isinstance(production.head, Variable) + assert ( + not body + or (len(body) == 1 and isinstance(body[0], Terminal)) + or (len(body) == 2 and all(isinstance(symbol, Variable) for symbol in body)) + ) + + +def test_mixed_recursive_grammar_with_custom_start(): + grammar = CFG.from_text("Q -> a Q b c | epsilon", start_symbol=Variable("Q")) + normalized = cfg_to_weak_normal_form(grammar) + + assert_weak_form(normalized) + assert normalized.start_symbol == Variable("Q") + for size in range(5): + for word in product("abc", repeat=size): + expected = not word or word == ("a", "b", "c") + assert normalized.contains(word) == expected + assert normalized.contains(word) == grammar.contains(word) + assert normalized.contains(list("aabcbc")) + assert not normalized.contains(list("aabbcc")) + + +@pytest.mark.parametrize( + "text, expected", + [ + ("S -> epsilon", {()}), + ("S -> A\nA -> B\nB -> A | epsilon", {()}), + ("S -> A B\nA -> epsilon\nB -> b", {("b",)}), + ("S -> A B\nA -> epsilon\nB -> epsilon", {()}), + ("S -> A\nA -> S", set()), + ("S -> A B\nA -> a", set()), + ("S -> A\nA -> a b c", {("a", "b", "c")}), + ], +) +def test_nullable_chains_and_empty_languages(text, expected): + grammar = CFG.from_text(text) + normalized = cfg_to_weak_normal_form(grammar) + assert_weak_form(normalized) + for size in range(4): + for word in product("abc", repeat=size): + assert normalized.contains(word) == (word in expected) + assert normalized.contains(word) == grammar.contains(word) + + +def test_grammar_with_no_productions(): + grammar = CFG(start_symbol=Variable("Q")) + normalized = cfg_to_weak_normal_form(grammar) + assert_weak_form(normalized) + assert normalized.start_symbol == Variable("Q") + assert not normalized.contains([]) + assert not normalized.contains(["a"]) + + +def test_start_symbol_on_right_and_non_start_epsilon(): + grammar = CFG.from_text("S -> A S | epsilon\nA -> a | epsilon") + normalized = cfg_to_weak_normal_form(grammar) + assert_weak_form(normalized) + assert normalized.start_symbol == grammar.start_symbol + for size in range(6): + assert normalized.contains(["a"] * size) + assert not normalized.contains(["b"]) + + +def acyclic_words(grammar, variable): + """Enumerate finite derivations with explicit terminal/variable kinds.""" + words = set() + for production in grammar.productions: + if production.head != variable: + continue + choices = [ + {(symbol.value,)} + if isinstance(symbol, Terminal) + else acyclic_words(grammar, symbol) + for symbol in production.body + ] + words.update(sum(pieces, ()) for pieces in product(*choices)) + return words + + +def test_helper_names_do_not_change_original_variables_or_terminals(): + start = Variable("S") + variables = [Variable(name) for name in ("__wcnf_0", "__wcnf_1", "C#CNF#1")] + grammar = CFG( + start_symbol=start, + productions=[ + Production(start, [Terminal("a"), *variables, Terminal("__wcnf_2")]), + *(Production(variable, [Terminal("b")]) for variable in variables), + ], + ) + normalized = cfg_to_weak_normal_form(grammar) + assert_weak_form(normalized) + assert acyclic_words(normalized, start) == {("a", "b", "b", "b", "__wcnf_2")} + + +def test_terminal_and_variable_with_equal_text_remain_distinct(): + start, variable = Variable("S"), Variable("A") + grammar = CFG( + start_symbol=start, + productions=[ + Production(start, [Terminal("A"), variable, Terminal("b")]), + Production(variable, [Terminal("c")]), + ], + ) + normalized = cfg_to_weak_normal_form(grammar) + assert_weak_form(normalized) + # pyformlang's CNF membership oracle is unreliable for equal textual values. + assert acyclic_words(normalized, start) == {("A", "c", "b")} + + +def test_output_is_independent_and_input_is_unchanged(): + grammar = CFG.from_text("S -> a A b | epsilon\nA -> c") + original = ( + set(grammar.productions), + set(grammar.variables), + set(grammar.terminals), + grammar.start_symbol, + ) + bodies = [(production, list(production.body)) for production in grammar.productions] + normalized = cfg_to_weak_normal_form(grammar) + assert normalized is not grammar + assert ( + set(grammar.productions), + set(grammar.variables), + set(grammar.terminals), + grammar.start_symbol, + ) == original + for production in normalized.productions: + production.body.clear() + normalized.variables.clear() + normalized.terminals.clear() + assert all(production.body == body for production, body in bodies) + assert grammar.variables == original[1] + assert grammar.terminals == original[2]