Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
e5687a8
Задание 1. Функции получения информации о графе и сохранения в формат…
semrosin Sep 16, 2026
c72a19b
Задание 2. Функции построения минимального ДКА по регулярному выражен…
semrosin Sep 29, 2026
eea7363
Задание 3. Функции пересечения автоматов и выполнения регулярных запр…
semrosin Oct 6, 2026
ad3cb22
feat: add multiple-source RPQ solver
semrosin Oct 3, 2026
64535f2
test: add RPQ regression coverage
semrosin Oct 3, 2026
e9cfd65
test: resolve RPQ test naming collision
semrosin Oct 3, 2026
ec4e8e7
refactor: rename files
semrosin Oct 4, 2026
49e4919
refactor: use blocked Boolean matrix BFS for multiple-source RPQ
semrosin Oct 4, 2026
d3bd653
test: fix ms_bfs_based_rpq import in RPQ autotest
semrosin Oct 4, 2026
7bb3ea3
refactor: delegate start/final handling to graph_to_nfa in ms_bfs_bas…
semrosin Oct 5, 2026
856c5d6
test: rename msbfs test to reflect isolated-vertex semantics
semrosin Oct 5, 2026
d7266f9
fix: rename autotests file back
semrosin Oct 9, 2026
5dcc676
fix: switch from numpy arrays to scupy matrices
semrosin Oct 9, 2026
feca4c8
Задание 4. Функция RPQ несколько стартовых (BFS) (#4)
semrosin Oct 16, 2026
080a061
fix(task 3): использование разреженных матриц SciPy
semrosin Oct 16, 2026
d621a66
feat: convert CFGs to weak Chomsky normal form
semrosin Oct 16, 2026
b0be883
feat: add indexed Hellings context-free path queries
semrosin Oct 16, 2026
7de2f11
test: wire task 6 autotests to dedicated modules
semrosin Oct 16, 2026
7d7fb31
refactor: delegate weak normal form conversion to pyformlang
semrosin Oct 19, 2026
29cdfa7
refactor: simplify Hellings to direct fixed-point iteration
semrosin Oct 19, 2026
1b42a92
refactor: keep automaton states in Hellings triples
semrosin Oct 19, 2026
b60ff66
test: remove redundant task 6 coverage
semrosin Oct 19, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
198 changes: 198 additions & 0 deletions project/adjacency_matrix_fa.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
"""Sparse matrix representation of finite automata for regular path queries."""

from collections import defaultdict
from collections.abc import Iterable

from networkx import MultiDiGraph
from pyformlang.finite_automaton import NondeterministicFiniteAutomaton, Symbol
from scipy.sparse import csr_matrix, eye, kron

from project.task2 import graph_to_nfa, regex_to_dfa


class AdjacencyMatrixFA:
"""An NFA represented by one sparse adjacency matrix per symbol.

Args:
automaton: Automaton to represent. If ``None``, an empty automaton
is created; this is convenient when the fields are filled later.
"""

def __init__(
self, automaton: NondeterministicFiniteAutomaton | None = None
) -> None:
if automaton is None:
self.index_to_state = ()
self.state_to_index = {}
self.states_count = 0
self.start_states = set()
self.final_states = set()
self.matrices = {}
return

self.index_to_state = tuple(automaton.states)
self.state_to_index = {
state: index for index, state in enumerate(self.index_to_state)
}
self.states_count = len(self.index_to_state)
self.start_states = {
self.state_to_index[state] for state in automaton.start_states
}
self.final_states = {
self.state_to_index[state] for state in automaton.final_states
}

edges = defaultdict(lambda: ([], []))
for source, symbol, target in automaton:
sources, targets = edges[symbol]
sources.append(self.state_to_index[source])
targets.append(self.state_to_index[target])

self.matrices = {
symbol: csr_matrix(
(
[True] * len(sources),
(sources, targets),
), # (data, (row_ind, col_ind))
shape=(self.states_count, self.states_count),
dtype=bool,
)
for symbol, (sources, targets) in edges.items()
}

def adjacency_matrix(self) -> csr_matrix:
"""Return the boolean union of the per-symbol matrices."""

adjacency = csr_matrix((self.states_count, self.states_count), dtype=bool)
for matrix in self.matrices.values():
adjacency = adjacency + matrix
return adjacency

def transitive_closure(self) -> csr_matrix:
"""Return the reflexive-transitive closure of the adjacency matrix."""

reachable = eye(self.states_count, format="csr", dtype=bool)
for matrix in self.matrices.values():
reachable = reachable + matrix
while True:
expanded = reachable + reachable @ reachable
if expanded.nnz == reachable.nnz:
return expanded
reachable = expanded

def accepts(self, word: Iterable[Symbol]) -> bool:
"""Check whether the automaton accepts ``word``.

The vector of current states is multiplied by the matrix of the next
symbol on every step; the word is accepted when the final vector
reaches at least one final state.
"""

if not self.start_states or not self.final_states:
return False

start_states = list(self.start_states)
current = csr_matrix(
(
[True] * len(start_states),
([0] * len(start_states), start_states),
),
shape=(1, self.states_count),
dtype=bool,
)

for symbol in word:
matrix = self.matrices.get(Symbol(symbol))
if matrix is None:
return False
current = current @ matrix
if current.nnz == 0:
return False
return any(node in self.final_states for node in current.indices)

def is_empty(self) -> bool:
"""Return whether no final state is reachable from a start state.

Reachability is computed by multiplying the start vector by the
transitive closure of the adjacency matrix, so paths of length zero
are taken into account as well.
"""

if not self.start_states or not self.final_states:
return True

start_states = list(self.start_states)
starts = csr_matrix(
(
[True] * len(start_states),
([0] * len(start_states), start_states),
),
shape=(1, self.states_count),
dtype=bool,
)
reachable = starts @ self.transitive_closure()
return not any(node in self.final_states for node in reachable.indices)


def intersect_automata(
automaton1: AdjacencyMatrixFA, automaton2: AdjacencyMatrixFA
) -> AdjacencyMatrixFA:
"""Build the synchronous product using a Kronecker matrix per label."""

product = AdjacencyMatrixFA()
width = automaton2.states_count
product.index_to_state = tuple(
(first, second)
for first in automaton1.index_to_state
for second in automaton2.index_to_state
)
product.state_to_index = {
state: index for index, state in enumerate(product.index_to_state)
}
product.states_count = automaton1.states_count * width
# State (first, second) is stored at first * width + second, matching kron.
product.start_states = {
first * width + second
for first in automaton1.start_states
for second in automaton2.start_states
}
product.final_states = {
first * width + second
for first in automaton1.final_states
for second in automaton2.final_states
}
product.matrices = {
symbol: kron(matrix, automaton2.matrices[symbol], format="csr")
for symbol, matrix in automaton1.matrices.items()
if symbol in automaton2.matrices
}
return product


def tensor_based_rpq(
regex: str, graph: MultiDiGraph, start_nodes: set[int], final_nodes: set[int]
) -> set[tuple[int, int]]:
"""Find graph node pairs joined by a path accepted by ``regex``.

The pairs are extracted from the transitive closure of the tensor product
of the automata for ``regex`` and ``graph``: every closure row of a
product start state gives the reachable product states, and every reached
final state produces a pair of graph nodes.
"""

regex_matrix = AdjacencyMatrixFA(regex_to_dfa(regex))
graph_matrix = AdjacencyMatrixFA(graph_to_nfa(graph, start_nodes, final_nodes))
product = intersect_automata(regex_matrix, graph_matrix)
closure = product.transitive_closure()

result = set()
for source in product.start_states:
for target in closure.getrow(source).indices:
if target in product.final_states:
result.add(
(
product.index_to_state[source][1].value,
product.index_to_state[target][1].value,
)
)
return result
41 changes: 41 additions & 0 deletions project/graph_lib.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import pathlib
from typing import Any, NamedTuple

import cfpq_data
import networkx as nx
import pydot


class GraphInfo(NamedTuple):
"""Graph statistics with named fields and tuple unpacking support."""

number_of_vertices: int
number_of_edges: int
labels: set[str]


def get_graph_info(graph_name: str) -> GraphInfo:
graph = cfpq_data.graph_from_csv(cfpq_data.download(graph_name))
labels = set(nx.get_edge_attributes(graph, "label").values())
return GraphInfo(graph.number_of_nodes(), graph.number_of_edges(), labels)


def save_two_cycles_graph(
n: int,
m: int,
common_node: Any,
labels: tuple[str, str],
path: str | pathlib.Path,
) -> nx.MultiDiGraph:
graph = cfpq_data.labeled_two_cycles_graph(
n, m, common_node=common_node, labels=labels
)

dot_graph = pydot.Dot(graph_type="digraph")
for node in graph.nodes:
dot_graph.add_node(pydot.Node(str(node)))
for source, target, label in graph.edges(data="label"):
dot_graph.add_edge(pydot.Edge(str(source), str(target), label=label))

dot_graph.write_raw(str(path))
return graph
65 changes: 65 additions & 0 deletions project/hellings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""Hellings' algorithm for context-free path queries."""

from networkx import DiGraph
from pyformlang.cfg import CFG, Terminal

from project.task2 import graph_to_nfa
from project.weak_normal_form import cfg_to_weak_normal_form

__all__ = ["hellings_based_cfpq"]


def hellings_based_cfpq(
cfg: CFG,
graph: DiGraph,
start_nodes: set[int] | None = None,
final_nodes: set[int] | None = None,
) -> set[tuple[int, int]]:
"""Return pairs connected by a path in the language of ``cfg``.

The grammar need not be in weak Chomsky normal form. Both directed
graphs and directed multigraphs are supported; edge labels are stored
in the ``label`` attribute. Input objects are not modified.
"""
normalized = cfg_to_weak_normal_form(cfg)
automaton = graph_to_nfa(graph, start_nodes, final_nodes)

triples = {
(state, variable, state)
for state in automaton.states
for variable in normalized.get_nullable_symbols()
}
for source, symbol, target in automaton:
for production in normalized.productions:
if (
len(production.body) == 1
and isinstance(production.body[0], Terminal)
and production.body[0].value == symbol.value
):
triples.add((source, production.head, target))

while True:
new_triples = set()
for source, left, middle in triples:
for right_source, right, target in triples:
if middle != right_source:
continue
for production in normalized.productions:
if (
len(production.body) == 2
and production.body[0] == left
and production.body[1] == right
):
new_triples.add((source, production.head, target))
new_triples.difference_update(triples)
if not new_triples:
break
triples.update(new_triples)

return {
(source.value, target.value)
for source, variable, target in triples
if variable == normalized.start_symbol
and source in automaton.start_states
and target in automaton.final_states
}
92 changes: 92 additions & 0 deletions project/msbfs_rpq.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
"""Multiple-source BFS-based regular path queries."""

from networkx import MultiDiGraph
from scipy.sparse import block_diag, csr_matrix

from project.adjacency_matrix_fa import AdjacencyMatrixFA
from project.task2 import graph_to_nfa, regex_to_dfa

__all__: list[str] = ["ms_bfs_based_rpq"]


def ms_bfs_based_rpq(
regex: str,
graph: MultiDiGraph,
start_nodes: set[int],
final_nodes: set[int],
) -> set[tuple[int, int]]:
"""Return all ``(start, final)`` pairs accepted by ``regex``.

A multiple-source BFS advances all start nodes simultaneously.
Every BFS layer is computed with sparse Boolean matrix products:
for a symbol the frontier is shifted along the graph edges with
that label and, inside each block, advanced by the DFA transition matrix
of the symbol (enlarged to all blocks at once with ``block_diag``).
"""

regex_matrix = AdjacencyMatrixFA(regex_to_dfa(regex))
graph_matrix = AdjacencyMatrixFA(graph_to_nfa(graph, start_nodes, final_nodes))

width: int = regex_matrix.states_count
start_indices: list[int] = sorted(graph_matrix.start_states)
blocks: int = len(start_indices)
if not blocks:
return set()

row_indices: list[int] = []
column_indices: list[int] = []
for block, start in enumerate(start_indices):
for dfa_start in regex_matrix.start_states:
row_indices.append(block * width + dfa_start)
column_indices.append(start)
front = csr_matrix(
([True] * len(row_indices), (row_indices, column_indices)),
shape=(blocks * width, graph_matrix.states_count),
dtype=bool,
)
visited = front.copy()

dfa_steps = {
symbol: block_diag([matrix.transpose()] * blocks, format="csr")
for symbol, matrix in regex_matrix.matrices.items()
if symbol in graph_matrix.matrices
}

while front.nnz:
new_front = None
for symbol, dfa_step in dfa_steps.items():
# Shift along the graph edges, then advance the DFA in each block.
moved = dfa_step @ (front @ graph_matrix.matrices[symbol])
new_front = moved if new_front is None else new_front + moved
if new_front is None:
break
new_front = new_front.tocsr()
# Keep only the states that have not been reached before.
front = new_front - new_front.multiply(visited)
front.eliminate_zeros()
visited = visited + new_front

if not regex_matrix.final_states:
return set()

selector_rows: list[int] = []
selector_columns: list[int] = []
for block in range(blocks):
for dfa_final in regex_matrix.final_states:
selector_rows.append(block)
selector_columns.append(block * width + dfa_final)
selector = csr_matrix(
([True] * len(selector_rows), (selector_rows, selector_columns)),
shape=(blocks, blocks * width),
dtype=bool,
)
reached = selector @ visited

result: set[tuple[int, int]] = set()
for block, start in enumerate(start_indices):
start_value = graph_matrix.index_to_state[start].value
for node in reached.getrow(block).indices:
if node in graph_matrix.final_states:
result.add((start_value, graph_matrix.index_to_state[node].value))

return result
Loading