diff --git a/project/cfg_lib.py b/project/cfg_lib.py new file mode 100644 index 000000000..d7fe8c10b --- /dev/null +++ b/project/cfg_lib.py @@ -0,0 +1,235 @@ +import networkx as nx + +from pyformlang.cfg import CFG, Terminal, Variable, Epsilon +from pyformlang.finite_automaton import Symbol, State +from pyformlang.rsa import RecursiveAutomaton +from scipy.sparse import csc_matrix + +from project.graph_lib import graph_to_nfa +from project.rpq_lib import AdjacencyMatrixFA, intersect_automata +from project.rsm_lib import boolean_decompress_rsm + + +def cfg_to_weak_normal_form(cfg: CFG) -> CFG: + """ + Convert a CFG to weak Chomsky normal form. + """ + if len(cfg.productions) == 0: + return cfg + + new_cfg = ( + cfg.remove_useless_symbols() + .eliminate_unit_productions() + .remove_useless_symbols() + ) + + new_productions = new_cfg._get_productions_with_only_single_terminals() + new_productions = new_cfg._decompose_productions(new_productions) + + return CFG(start_symbol=cfg.start_symbol, productions=set(new_productions)) + + +def split_productions(productions): + """ + Split WCNF productions into epsilon, terminal, and binary-non-terminal lookup structures. + """ + epsilon_prods: set[Variable] = set() # (A -> ε) + term_prods: dict[Terminal, set[Variable]] = {} # (A -> a) + nonterm_prods: dict[(Variable, Variable), set[Variable]] = {} # (A -> BC) + + for production in productions: + head, body = production.head, production.body + + if len(body) == 0 or isinstance(body[0], Epsilon): + epsilon_prods.add(head) + elif len(body) == 1 and isinstance(body[0], Terminal): + term_prods.setdefault(body[0].value, set()).add(head) + else: + nonterm_prods.setdefault((body[0], body[1]), set()).add(head) + + return epsilon_prods, term_prods, nonterm_prods + + +def hellings_based_cfpq( + cfg: CFG, + graph: nx.DiGraph, + start_nodes: set[int] = None, + final_nodes: set[int] = None, +) -> set[tuple[int, int]]: + """ + Return all (u, v) pairs connected by a path whose labels derive from the CFG start symbol, + via a Hellings-style fixed-point algorithm. + """ + cfg = cfg_to_weak_normal_form(cfg) + epsilon_prods, term_prods, nonterm_prods = split_productions(cfg.productions) + + adjacency_matrix = {(n, n, eps) for n in graph.nodes for eps in epsilon_prods} | { + (start, final, term) + for start, final, label in graph.edges.data("label") + if label in term_prods + for term in term_prods[label] + } + queue = adjacency_matrix.copy() + + while queue: + new_nonterm = set() + start1, final1, nonterm1 = queue.pop() + + for start2, final2, nonterm2 in adjacency_matrix: + if final1 == start2 and (nonterm1, nonterm2) in nonterm_prods: + for nonterm in nonterm_prods[(nonterm1, nonterm2)]: + if (start1, final2, nonterm) not in adjacency_matrix: + new_nonterm.add((start1, final2, nonterm)) + + if final2 == start1 and (nonterm2, nonterm1) in nonterm_prods: + for nonterm in nonterm_prods[(nonterm2, nonterm1)]: + if (start2, final1, nonterm) not in adjacency_matrix: + new_nonterm.add((start2, final1, nonterm)) + + queue |= new_nonterm + adjacency_matrix |= new_nonterm + + return { + (start, final) + for start, final, nonterm in adjacency_matrix + if ( + start in start_nodes + and final in final_nodes + and nonterm.value == cfg.start_symbol.value + ) + } + + +def matrix_based_cfpq( + cfg: CFG, + graph: nx.DiGraph, + start_nodes: set[int] = None, + final_nodes: set[int] = None, +) -> set[tuple[int, int]]: + """ + Return (u, v) pairs from start_nodes to final_nodes connected by a path whose labels + derive from the CFG start symbol, via matrix-based fixed-point iteration. + """ + cfg = cfg_to_weak_normal_form(cfg) + + epsilon_prods, term_prods, nonterm_prods = split_productions(cfg.productions) + node_to_idx = {n: i for i, n in enumerate(graph.nodes)} + idx_to_node = {i: n for n, i in node_to_idx.items()} + + num_nodes = graph.number_of_nodes() + adjacency_matrix: dict[Variable, csc_matrix] = { + nonterm: csc_matrix((num_nodes, num_nodes), dtype=bool) + for nonterm in cfg.variables + } + + for eps in epsilon_prods: + for n in range(num_nodes): + adjacency_matrix[eps][n, n] = True + + for s, f, lbl in graph.edges.data("label"): + if lbl in term_prods: + for term in term_prods[lbl]: + adjacency_matrix[term][node_to_idx[s], node_to_idx[f]] = True + + queue = set(cfg.variables) + while queue: + updated_var = queue.pop() + + for ( + M_B, + M_C, + ) in nonterm_prods: # M_A = M_A + M_B * M_C, if A -> BC in nonterm_prods + if updated_var != M_B and updated_var != M_C: + continue + + matrix_change = adjacency_matrix[M_B] @ adjacency_matrix[M_C] + for nonterm in nonterm_prods[(M_B, M_C)]: + old_matrix = adjacency_matrix[nonterm] + adjacency_matrix[nonterm] += matrix_change + + if (old_matrix != adjacency_matrix[nonterm]).count_nonzero() != 0: + queue.add(nonterm) + + valid_pairs: set[tuple[int, int]] = set() + for nonterm in adjacency_matrix: + if nonterm.value == cfg.start_symbol.value: + for r, c in zip(*adjacency_matrix[nonterm].nonzero()): + if idx_to_node[r] in start_nodes and idx_to_node[c] in final_nodes: + valid_pairs.add((idx_to_node[r], idx_to_node[c])) + + return valid_pairs + + +def tensor_based_cfpq( + rsm: RecursiveAutomaton, + graph: nx.DiGraph, + start_nodes: set[int] = None, + final_nodes: set[int] = None, +) -> set[tuple[int, int]]: + """ + Return (u, v) pairs from start_nodes to final_nodes connected by a path whose labels + derive from the RSM initial label, via tensor-based fixed-point iteration. + """ + rsm_m = boolean_decompress_rsm(rsm) + graph_m = AdjacencyMatrixFA( + graph_to_nfa(nx.MultiDiGraph(graph), start_nodes, final_nodes) + ) + + def delta(tc: csc_matrix) -> dict[Symbol, csc_matrix]: + """ + Project the tensor product's transitive closure onto the graph automaton: + map each complete RSM derivation of a non-terminal to a new edge labelled by that non-terminal, + skipping edges already present in graph_m. + """ + res: dict[Symbol, csc_matrix] = {} + + for i, j in zip(*tc.nonzero()): + rsm_i, rsm_j = i % rsm_m.states_count, j % rsm_m.states_count + st1, st2 = rsm_m.indexes_to_states[rsm_i], rsm_m.indexes_to_states[rsm_j] + + if st1 in rsm_m.start_states and st2 in rsm_m.final_states: + assert st1.value[0] == st2.value[0] + nonterm = st1.value[0] + + graph_i, graph_j = i // rsm_m.states_count, j // rsm_m.states_count + if ( + nonterm in graph_m.adj_matrices + and graph_m.adj_matrices[nonterm][graph_i, graph_j] + ): + continue + + if nonterm not in res: + res[nonterm] = csc_matrix( + (graph_m.states_count, graph_m.states_count), dtype=bool + ) + res[nonterm][graph_i, graph_j] = True + + return res + + while True: + transitive_closure = intersect_automata(graph_m, rsm_m).transitive_closure() + m_delta = delta(transitive_closure) + + if not m_delta: + break + + for symbol in m_delta.keys(): + if symbol not in graph_m.adj_matrices: + graph_m.adj_matrices[symbol] = m_delta[symbol] + else: + graph_m.adj_matrices[symbol] += m_delta[symbol] + + valid_pairs: set[tuple[int, int]] = set() + start_m = graph_m.adj_matrices.get(rsm.initial_label) + if start_m is None: + return valid_pairs + + for start in start_nodes: + for final in final_nodes: + if start_m[ + graph_m.states_to_indexes[State(start)], + graph_m.states_to_indexes[State(final)], + ]: + valid_pairs.add((start, final)) + + return valid_pairs diff --git a/project/graph_lib.py b/project/graph_lib.py new file mode 100644 index 000000000..ce8743b2e --- /dev/null +++ b/project/graph_lib.py @@ -0,0 +1,91 @@ +from typing import Set + +import cfpq_data +import networkx +from networkx import MultiDiGraph +from pyformlang.finite_automaton import ( + DeterministicFiniteAutomaton, + NondeterministicFiniteAutomaton, +) +from pyformlang.regular_expression import Regex + + +class GraphInformation: + """ + Class for storing some graph properties. + """ + + nodes: int + edges: int + labels: Set[str] + + def __init__(self, nodes, edges, labels): + self.nodes = nodes + self.edges = edges + self.labels = labels + + def __eq__(self, other): + result = ( + isinstance(other, GraphInformation) + and self.nodes == other.nodes + and self.edges == other.edges + and self.labels == other.labels + ) + + return result + + +def get_graph_info(graph_name): + """ + Retrieve GraphInformation by graph's name. + """ + path = cfpq_data.download(graph_name) + graph = cfpq_data.graph_from_csv(path) + + nodes_num = graph.number_of_nodes() + edges_num = graph.number_of_edges() + labels = set(cfpq_data.get_sorted_labels(graph)) + + return GraphInformation(nodes_num, edges_num, labels) + + +def generate_and_write_two_cycles_graph(num_first, num_second, labels, path): + """ + Create a two-cycle graph with numbers of nodes in cycles and given labels and save it in DOT format by given path. + """ + graph = cfpq_data.labeled_two_cycles_graph(num_first, num_second, labels=labels) + + networkx.nx_pydot.write_dot(graph, path) + + +def regex_to_dfa(regex: str) -> DeterministicFiniteAutomaton: + """ + Converts a regular expression string into a minimal deterministic finite automaton (DFA). + """ + return Regex(regex).to_epsilon_nfa().to_deterministic().minimize() + + +def graph_to_nfa( + graph: MultiDiGraph, start_states: Set[int] = None, final_states: Set[int] = None +) -> NondeterministicFiniteAutomaton: + """ + Converts a directed multi graph with labeled edges into a nondeterministic finite automaton (NFA). + """ + result_graph = NondeterministicFiniteAutomaton() + result_graph.add_transitions( + [(x, label, y) for x, y, label in graph.edges(data="label") if label] + ) + nodes = graph.nodes() + + if not start_states: + start_states = nodes + + if not final_states: + final_states = nodes + + for s in start_states: + result_graph.add_start_state(s) + for s in final_states: + result_graph.add_final_state(s) + + return result_graph diff --git a/project/rpq_lib.py b/project/rpq_lib.py new file mode 100644 index 000000000..63cfbadf6 --- /dev/null +++ b/project/rpq_lib.py @@ -0,0 +1,260 @@ +import itertools +from collections.abc import Iterable +from typing import Optional + +from networkx import MultiDiGraph +from pyformlang.finite_automaton import Symbol, NondeterministicFiniteAutomaton, State +from scipy.sparse import csc_matrix, kron, vstack + +from project.graph_lib import graph_to_nfa, regex_to_dfa + + +class AdjacencyMatrixFA: + """ + A finite automaton representation using sparse adjacency matrices. + """ + + def __init__(self, automaton: Optional[NondeterministicFiniteAutomaton]): + self.start_states = set() + self.final_states = set() + + if automaton is None: + self.states_count = 0 + self.adj_matrices = {} + self.states_to_indexes = {} + self.indexes_to_states = {} + return + + self.states_count = len(automaton.states) + self.states_to_indexes: dict[State, int] = { + state: i for i, state in enumerate(automaton.states) + } + self.indexes_to_states: dict[int, State] = { + i: state for state, i in self.states_to_indexes.items() + } + + self.start_states: set[State] = automaton.start_states + self.final_states: set[State] = automaton.final_states + self.adj_matrices: dict[Symbol, csc_matrix] = {} + + for from_st in self.states_to_indexes.keys(): + from_idx = self.states_to_indexes[from_st] + transitions: dict[Symbol, State | set[State]] = automaton.to_dict().get( + from_st + ) + + if transitions is None: + continue + + for symbol in transitions.keys(): + if symbol not in self.adj_matrices: + self.adj_matrices[symbol] = csc_matrix( + (self.states_count, self.states_count), dtype=bool + ) + + if isinstance(transitions[symbol], Iterable): + for to_st in transitions[symbol]: + to_idx = self.states_to_indexes[to_st] + self.adj_matrices[symbol][from_idx, to_idx] = True + else: + to_st: State = transitions[symbol] + to_idx = self.states_to_indexes[to_st] + self.adj_matrices[symbol][from_idx, to_idx] = True + return + + def transitive_closure(self) -> csc_matrix: + res = csc_matrix((self.states_count, self.states_count), dtype=bool) + res.setdiag(True) + + for matrix in self.adj_matrices.values(): + res += matrix + + res.astype(bool) + changed = True + + while changed: + new_res = (res @ res).astype(bool) + + if (new_res != res).nnz == 0: + changed = False + else: + res = new_res + return res + + def accepts(self, word: Iterable[Symbol]) -> bool: + """ + Check if the automaton accepts a given word. + """ + curr_cfgs: set[State] = self.start_states + + for symbol in word: + if symbol not in self.adj_matrices: + return False + + next_configs = set() + transition_matrix = self.adj_matrices[symbol] + + for curr_state in curr_cfgs: + for state in self.states_to_indexes.keys(): + if transition_matrix[ + self.states_to_indexes[curr_state], + self.states_to_indexes[state], + ]: + next_configs.add(state) + + curr_cfgs = next_configs + + return any(final_st in curr_cfgs for final_st in self.final_states) + + def is_empty(self) -> bool: + """ + Check if the language recognized by the automaton is empty. + """ + transitive_closure = self.transitive_closure() + + if transitive_closure is None: + return True + + for start_st, final_st in itertools.product( + self.start_states, self.final_states + ): + if transitive_closure[ + self.states_to_indexes[start_st], self.states_to_indexes[final_st] + ]: + return False + + return True + + +def intersect_automata( + automaton1: AdjacencyMatrixFA, automaton2: AdjacencyMatrixFA +) -> AdjacencyMatrixFA: + """ + Compute the intersection of two finite automata using tensor product. + """ + res = AdjacencyMatrixFA(None) + matrix1, matrix2 = automaton1.adj_matrices, automaton2.adj_matrices + + res.states_count = automaton1.states_count * automaton2.states_count + symbols = set(matrix1.keys()) & set(matrix2.keys()) + res.adj_matrices = {s: kron(matrix1[s], matrix2[s], format="csc") for s in symbols} + + for st1, st2 in itertools.product( + automaton1.states_to_indexes.keys(), automaton2.states_to_indexes.keys() + ): + idx1, idx2 = ( + automaton1.states_to_indexes[st1], + automaton2.states_to_indexes[st2], + ) + res_idx = idx1 * automaton2.states_count + idx2 + + res.states_to_indexes[State((st1, st2))] = res_idx + if st1 in automaton1.start_states and st2 in automaton2.start_states: + res.start_states.add(State((st1, st2))) + if st1 in automaton1.final_states and st2 in automaton2.final_states: + res.final_states.add(State((st1, st2))) + return res + + +def tensor_based_rpq( + regex: str, graph: MultiDiGraph, start_nodes: set[int], final_nodes: set[int] +) -> set[tuple[int, int]]: + """ + Perform regular path querying on a graph using tensor-based automata intersection. + """ + regex_dfa_adj_matrix = AdjacencyMatrixFA(regex_to_dfa(regex)) + graph_nfa_adj_matrix = AdjacencyMatrixFA( + graph_to_nfa(graph, start_nodes, final_nodes) + ) + + intersection_automaton = intersect_automata( + regex_dfa_adj_matrix, graph_nfa_adj_matrix + ) + result_matrix = intersection_automaton.transitive_closure() + + valid_pairs = set() + + for start_state in intersection_automaton.start_states: + for final_state in intersection_automaton.final_states: + if result_matrix[ + intersection_automaton.states_to_indexes[start_state], + intersection_automaton.states_to_indexes[final_state], + ]: + start = start_state.value[1].value + final = final_state.value[1].value + + valid_pairs.add((start, final)) + + return valid_pairs + + +def ms_bfs_based_rpq( + regex: str, graph: MultiDiGraph, start_nodes: set[int], final_nodes: set[int] +) -> set[tuple[int, int]]: + """ + Performs regular path querying on a graph using matrix-based BFS approach. + """ + dfa = AdjacencyMatrixFA(regex_to_dfa(regex)) + nfa = AdjacencyMatrixFA(graph_to_nfa(graph, start_nodes, final_nodes)) + + nfa_start_index = list(nfa.states_to_indexes[st] for st in nfa.start_states) + dfa_start = dfa.states_to_indexes[list(dfa.start_states)[0]] + front = vstack( + [ + csc_matrix( + ([True], ([dfa_start], [nfa_start])), + (dfa.states_count, nfa.states_count), + dtype=bool, + ) + for nfa_start in nfa_start_index + ] + ) + + visited = front + symbols = set(dfa.adj_matrices.keys()) & set(nfa.adj_matrices.keys()) + permutation_matrices: dict[Symbol, csc_matrix] = { + s: dfa.adj_matrices[s].transpose() for s in symbols + } + + while front.count_nonzero() != 0: + new_front = front + for s in symbols: + front_for_symbol = front @ nfa.adj_matrices[s] + front_after_permutation = vstack( + [ + permutation_matrices[s] + @ front_for_symbol[ + (i * dfa.states_count) : ((i + 1) * dfa.states_count), : + ] + for i in range(len(start_nodes)) + ] + ) + new_front += front_after_permutation + front = new_front.astype(bool) > visited + visited += front + + valid_pairs = set() + final_matrix = csc_matrix((dfa.states_count, nfa.states_count), dtype=bool) + for nfa_final in nfa.final_states: + for dfa_final in dfa.final_states: + final_matrix[ + dfa.states_to_indexes[dfa_final], nfa.states_to_indexes[nfa_final] + ] = True + + _final_state = vstack([final_matrix for _ in range(len(start_nodes))]) + final_state = vstack( + [ + csc_matrix((dfa.states_count, nfa.states_count), dtype=bool) + for _ in range(len(start_nodes)) + ] + ) + for i in range(dfa.states_count * len(start_nodes)): + for j in range(nfa.states_count): + if (_final_state[i, j]) and (visited[i, j]): + final_state[i, j] = True + + for r, c in zip(*final_state.nonzero()): + nfa_start = nfa.indexes_to_states[nfa_start_index[(r // dfa.states_count)]] + valid_pairs.add((nfa_start.value, nfa.indexes_to_states[c].value)) + + return valid_pairs diff --git a/project/rsm_lib.py b/project/rsm_lib.py new file mode 100644 index 000000000..422a7cfa0 --- /dev/null +++ b/project/rsm_lib.py @@ -0,0 +1,65 @@ +from typing import Iterable + +from pyformlang.cfg import CFG +from pyformlang.finite_automaton import ( + State, + Symbol, + NondeterministicFiniteAutomaton, + EpsilonNFA, +) +from pyformlang.rsa import RecursiveAutomaton + +from project.rpq_lib import AdjacencyMatrixFA + + +def cfg_to_rsm(cfg: CFG) -> RecursiveAutomaton: + """ + Return the RecursiveAutomaton obtained from the given CFG by reusing its textual representation. + """ + return RecursiveAutomaton.from_text(cfg.to_text()) + + +def ebnf_to_rsm(ebnf: str) -> RecursiveAutomaton: + """ + Return the RecursiveAutomaton parsed from the given EBNF text. + """ + return RecursiveAutomaton.from_text(ebnf) + + +def rsm_to_nfa(rsm: RecursiveAutomaton) -> NondeterministicFiniteAutomaton: + """ + Return an NFA whose states are (non-terminal, state) pairs of the RSM boxes and whose transitions + mirror the boxes' DFAs, with start and final states lifted from each box. + """ + nfa = NondeterministicFiniteAutomaton() + + for nonterm, box in rsm.boxes.items(): + dfa: EpsilonNFA = box.dfa + + for st in dfa.start_states: + nfa.add_start_state(State((nonterm, st.value))) + for st in dfa.final_states: + nfa.add_final_state(State((nonterm, st.value))) + + for from_st in dfa.states: + transitions: dict[Symbol, State | set[State]] = dfa.to_dict().get(from_st) + if transitions is None: + continue + + for symbol in transitions.keys(): + for to_st in ( + transitions[symbol] + if isinstance(transitions[symbol], Iterable) + else {transitions[symbol]} + ): + nfa.add_transition( + State((nonterm, from_st)), symbol, State((nonterm, to_st)) + ) + return nfa + + +def boolean_decompress_rsm(rsm: RecursiveAutomaton) -> AdjacencyMatrixFA: + """ + Return the adjacency-matrix automaton obtained by flattening the RSM into an NFA via rsm_to_nfa. + """ + return AdjacencyMatrixFA(rsm_to_nfa(rsm)) diff --git a/tests/autotests/rpq_template_test.py b/tests/autotests/rpq_template_test.py index f57e27a2a..440ffc1c5 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.rpq_lib import ms_bfs_based_rpq except ImportError: pass diff --git a/tests/autotests/test_task02.py b/tests/autotests/test_task02.py index 67ae5cc14..155ee5da5 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.graph_lib 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..cfa9ec9f2 100644 --- a/tests/autotests/test_task03.py +++ b/tests/autotests/test_task03.py @@ -12,8 +12,8 @@ # 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.graph_lib import regex_to_dfa + from project.rpq_lib 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..2ed4b9810 100644 --- a/tests/autotests/test_task04.py +++ b/tests/autotests/test_task04.py @@ -11,8 +11,7 @@ # 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.rpq_lib import tensor_based_rpq, 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..0ec49acad 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.cfg_lib 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.cfg_lib - assert "cfg_to_weak_normal_form" in dir(project.task6) + assert "cfg_to_weak_normal_form" in dir(project.cfg_lib) except NameError: assert False diff --git a/tests/autotests/test_task07.py b/tests/autotests/test_task07.py index 513ca5fe7..2f43c244d 100644 --- a/tests/autotests/test_task07.py +++ b/tests/autotests/test_task07.py @@ -11,8 +11,7 @@ # Fix import statements in try block to run tests try: - from project.task6 import hellings_based_cfpq - from project.task7 import matrix_based_cfpq + from project.cfg_lib import hellings_based_cfpq, matrix_based_cfpq except ImportError: pytestmark = pytest.mark.skip("Task 7 is not ready to test!") diff --git a/tests/autotests/test_task08.py b/tests/autotests/test_task08.py index 2ca5a31a1..4e97efbb2 100644 --- a/tests/autotests/test_task08.py +++ b/tests/autotests/test_task08.py @@ -15,9 +15,12 @@ # Fix import statements in try block to run tests try: - from project.task6 import hellings_based_cfpq - from project.task7 import matrix_based_cfpq - from project.task8 import tensor_based_cfpq, cfg_to_rsm, ebnf_to_rsm + from project.cfg_lib import ( + hellings_based_cfpq, + matrix_based_cfpq, + tensor_based_cfpq, + ) + from project.rsm_lib import cfg_to_rsm, ebnf_to_rsm except ImportError: pytestmark = pytest.mark.skip("Task 8 is not ready to test!") diff --git a/tests/files/expected.dot b/tests/files/expected.dot new file mode 100644 index 000000000..f8a8074b9 --- /dev/null +++ b/tests/files/expected.dot @@ -0,0 +1,15 @@ +digraph { +1; +2; +3; +0; +4; +5; +1 -> 2 [key=0, label=x]; +2 -> 3 [key=0, label=x]; +3 -> 0 [key=0, label=x]; +0 -> 1 [key=0, label=x]; +0 -> 4 [key=0, label=y]; +4 -> 5 [key=0, label=y]; +5 -> 0 [key=0, label=y]; +} diff --git a/tests/test_task_1.py b/tests/test_task_1.py new file mode 100644 index 000000000..510ae7c97 --- /dev/null +++ b/tests/test_task_1.py @@ -0,0 +1,70 @@ +import filecmp +import os +from pathlib import Path + +import pytest + +from project.graph_lib import ( + get_graph_info, + GraphInformation, + generate_and_write_two_cycles_graph, +) + + +def test_get_graph_info(): + actual_info = get_graph_info("people") + + expected_info = GraphInformation( + 337, + 640, + { + "allValuesFrom", + "comment", + "complementOf", + "disjointWith", + "domain", + "drives", + "equivalentClass", + "first", + "has_pet", + "intersectionOf", + "inverseOf", + "is_pet_of", + "label", + "maxCardinality", + "minCardinality", + "onProperty", + "range", + "reads", + "rest", + "service_number", + "someValuesFrom", + "subClassOf", + "subPropertyOf", + "type", + "unionOf", + }, + ) + assert actual_info == expected_info + + +def test_no_name_graph(): + with pytest.raises(Exception): + get_graph_info("this_name_surely_does_not_exist") + + +def test_generate_two_cycles_graph(): + gen_path = Path(Path(__file__).parent, "files", "generated.dot") + expect_path = Path(Path(__file__).parent, "files", "expected.dot") + + generate_and_write_two_cycles_graph(3, 2, ("x", "y"), gen_path) + + assert filecmp.cmp(expect_path, gen_path) + os.remove(gen_path) + + +def test_generate_graph_without_cycles(): + gen_path = Path(Path(__file__).parent, "files", "non_exist.dot") + + with pytest.raises(Exception): + generate_and_write_two_cycles_graph(0, 0, ("x", "y"), gen_path) diff --git a/tests/test_task_2.py b/tests/test_task_2.py new file mode 100644 index 000000000..03e3f8718 --- /dev/null +++ b/tests/test_task_2.py @@ -0,0 +1,75 @@ +import networkx +import pytest +from pyformlang.regular_expression import MisformedRegexError + +from project.graph_lib import regex_to_dfa, graph_to_nfa + + +def test_nonexistent_start(): + initial_graph = networkx.MultiDiGraph() + initial_graph.add_edge(0, 0, label="1") + initial_graph.add_edge(0, 1, label="0") + initial_graph.add_edge(1, 1, label="0") + initial_graph.add_edge(1, 0, label="1") + + graph_to_nfa(initial_graph, {42}, {0}) + graph_to_nfa(initial_graph, {0}, {42}) + + +def test_ended_by_zero(): + initial_graph = networkx.MultiDiGraph() + initial_graph.add_edge(0, 0, label="1") + initial_graph.add_edge(0, 1, label="0") + initial_graph.add_edge(1, 1, label="0") + initial_graph.add_edge(1, 0, label="1") + + final_graph = graph_to_nfa(initial_graph, {0}, {1}) + + assert final_graph.is_equivalent_to(regex_to_dfa("(0|1)* 0")) + for i in range(0, 42, 2): + assert final_graph.accepts("{0:b}".format(i)) + assert not final_graph.accepts("{0:b}".format(i + 1)) + + +def test_ended_by_banana_ananas(): + initial_graph = networkx.MultiDiGraph() + for i in range(ord("a"), ord("z") + 1): + initial_graph.add_edge(0, 0, label=chr(i)) + initial_graph.add_edge(0, 0, label=" ") + initial_graph.add_edge(0, 1, label="b") + initial_graph.add_edge(0, 2, label="a") + initial_graph.add_edge(1, 2, label="a") + initial_graph.add_edge(2, 3, label="n") + initial_graph.add_edge(3, 4, label="a") + initial_graph.add_edge(4, 5, label="n") + initial_graph.add_edge(5, 6, label="a") + initial_graph.add_edge(6, 7, label="s") + + final_graph = graph_to_nfa(initial_graph, {0}, {6, 7}) + + assert final_graph.accepts("banana") + assert final_graph.accepts("ananas") + assert final_graph.accepts(" bananas") + assert not final_graph.accepts("apple") + + +def test_wrong(): + with pytest.raises(MisformedRegexError): + regex_to_dfa("[*|.]") + + +def test_power_two(): + dfa = regex_to_dfa("1 (0)*") + assert dfa.is_deterministic + for i in range(1, 5): + assert dfa.accepts("{0:b}".format(2**i)) + assert not dfa.accepts("0") + assert not dfa.accepts("1001") + + +def test_binary_ended_by_zero(): + dfa = regex_to_dfa("(0|1)* 0") + assert dfa.is_deterministic + for i in range(0, 42, 2): + assert dfa.accepts("{0:b}".format(i)) + assert not dfa.accepts("{0:b}".format(i + 1))