Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
156 changes: 156 additions & 0 deletions project/cfpq.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@

import networkx as nx
from pyformlang.cfg import CFG, Production, Terminal, Variable
from pyformlang.finite_automaton import NondeterministicFiniteAutomaton, State, Symbol
from pyformlang.rsa import Box, RecursiveAutomaton
from scipy.sparse import csr_matrix

from project.automata import (
AdjacencyMatrixFA,
graph_to_nfa,
intersect_automata,
regex_to_dfa,
)


def cfg_to_weak_normal_form(cfg: CFG) -> CFG:
Expand Down Expand Up @@ -136,3 +146,149 @@ def add(variable: Variable, source: int, target: int) -> bool:
for target in final_nodes
if (source, target) in start_relation
}


def cfg_to_rsm(cfg: CFG) -> RecursiveAutomaton:
"""Builds one box per variable, accepting its production bodies.

Each production becomes a separate NFA path; an empty body makes the
entry state final. Box construction determinizes and minimizes the NFA.
Variable transitions call other boxes, while terminals label graph edges.
No normal-form conversion or regular-expression escaping is needed.
"""
if cfg.start_symbol is None:
return RecursiveAutomaton()

variables = cfg.variables | {cfg.start_symbol}
terminal_labels = {Symbol(terminal.value) for terminal in cfg.terminals}
labels = {
variable: (
Symbol((Variable, variable.value))
if Symbol(variable.value) in terminal_labels
else Symbol(variable.value)
)
for variable in variables
}
automata = {}
for variable in variables:
automaton = NondeterministicFiniteAutomaton()
automaton.add_start_state(0)
automata[variable] = automaton

for index, production in enumerate(cfg.productions):
automaton = automata[production.head]
source = State(0)
for position, symbol in enumerate(production.body):
target = State((index, position))
label = (
labels[symbol] if isinstance(symbol, Variable) else Symbol(symbol.value)
)
automaton.add_transition(source, label, target)
source = target
automaton.add_final_state(source)

boxes = {Box(automata[variable], labels[variable]) for variable in variables}
return RecursiveAutomaton(set(labels.values()), labels[cfg.start_symbol], boxes)


def ebnf_to_rsm(ebnf: str) -> RecursiveAutomaton:
"""Builds an RSM from rules ``Head -> regex`` with start symbol ``S``.

Bodies use pyformlang regex syntax: union ``|``, concatenation, Kleene
star ``*`` and epsilon ``$``. Repeated heads are joined by union. Each
body is converted by the regex-to-DFA function from task 2; symbols
matching rule heads are recursive calls, all others are terminals.
"""
bodies: dict[str, list[str]] = {}
for line in ebnf.splitlines():
line = line.strip()
if not line:
continue
if "->" not in line:
raise ValueError("Expected an EBNF rule 'Head -> regex'")
head, body = line.split("->", 1)
head = head.strip()
if not head:
raise ValueError("An EBNF rule must have a nonempty head")
bodies.setdefault(head, []).append(f"({body.strip() or '$'})")

if "S" not in bodies:
raise ValueError("The EBNF grammar must define the start symbol S")
boxes = {Box(regex_to_dfa(" | ".join(body)), head) for head, body in bodies.items()}
return RecursiveAutomaton(set(bodies), "S", boxes)


def tensor_based_cfpq(
rsm: RecursiveAutomaton,
graph: nx.DiGraph,
start_nodes: Optional[set[int]] = None,
final_nodes: Optional[set[int]] = None,
) -> set[tuple[int, int]]:
"""Solves all-pairs CFPQ by saturating graph relations for RSM boxes.

The disjoint union of box automata is intersected with the graph using
sparse Boolean Kronecker products. Its reflexive transitive closure
yields new nonterminal edges between box entries and exits. Iteration
stops when no relation grows. The reflexive part handles nullable boxes.

As in the previous query functions, None or an empty node filter means
all graph vertices. Filters apply only to the resulting endpoint pairs.
Neither the graph nor the RSM is modified.
"""
if not graph or rsm.initial_label not in rsm.boxes:
return set()

# Qualifying states by their box prevents collisions between local IDs.
union = NondeterministicFiniteAutomaton()
for label, box in rsm.boxes.items():
for state in box.dfa.states:
union.states.add(State((label, state)))
for source, transitions in box.dfa.to_dict().items():
for symbol, target in transitions.items():
union.add_transition((label, source), symbol, (label, target))
rsm_fa = AdjacencyMatrixFA(union)
graph_fa = AdjacencyMatrixFA(graph_to_nfa(graph))
size = graph_fa.num_states
empty = csr_matrix((size, size), dtype=bool)

boundaries = {}
for label, box in rsm.boxes.items():
entries = {
rsm_fa.state_to_index[State((label, state))]
for state in box.dfa.start_states
}
exits = {
rsm_fa.state_to_index[State((label, state))]
for state in box.dfa.final_states
}
boundaries[label] = (entries, exits)
# A box label denotes a call, not a terminal present in the graph.
graph_fa.adjacency_matrices[label] = empty.copy()

changed = True
while changed:
changed = False
product = intersect_automata(rsm_fa, graph_fa)
reachability = product._reachability_matrix()
for label, (entries, exits) in boundaries.items():
relation = graph_fa.adjacency_matrices[label]
previous_size = relation.nnz
for entry in entries:
for exit_state in exits:
block = reachability[
entry * size : (entry + 1) * size,
exit_state * size : (exit_state + 1) * size,
]
relation = relation.maximum(block)
graph_fa.adjacency_matrices[label] = relation
changed |= relation.nnz > previous_size

sources = start_nodes or set(graph.nodes)
targets = final_nodes or set(graph.nodes)
rows, columns = graph_fa.adjacency_matrices[rsm.initial_label].nonzero()
return {
(source, target)
for row, column in zip(rows, columns)
if (source := graph_fa.index_to_state[row].value) in sources
and (target := graph_fa.index_to_state[column].value) in targets
}
4 changes: 2 additions & 2 deletions tasks.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@

## Задача 8. Тензорный алгоритм решения задачи достижимости с КС ограничениями

- [ ] Реализовать **функцию**, основанную на тензорном алгоритме, решающую задачу достижимости между всеми парами вершин для заданного графа и заданной КС грамматики.
- [x] Реализовать **функцию**, основанную на тензорном алгоритме, решающую задачу достижимости между всеми парами вершин для заданного графа и заданной КС грамматики.
- Для преобразования грамматики в RSM использовать результаты предыдущих работ. Явно опишите **функции** преобразования CFG -> RSM и EBNF -> RSM
- Для реализации матричных операций использовать [sciPy](https://docs.scipy.org/doc/scipy/reference/sparse.html).
- Необходимые функции:
Expand All @@ -213,7 +213,7 @@
def ebnf_to_rsm(ebnf: str) -> pyformlang.rsa.RecursiveAutomaton:
pass
```
- [ ] Добавить собственные тесты при необходимости.
- [x] Добавить собственные тесты при необходимости.

## Задача 9. Алгоритм решения задачи достижимости с КС ограничениями, основанный на GLL

Expand Down
6 changes: 3 additions & 3 deletions tests/autotests/test_task08.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@

# 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.cfpq import hellings_based_cfpq
from project.cfpq_matrix import matrix_based_cfpq
from project.cfpq import tensor_based_cfpq, cfg_to_rsm, ebnf_to_rsm
except ImportError:
pytestmark = pytest.mark.skip("Task 8 is not ready to test!")

Expand Down
149 changes: 149 additions & 0 deletions tests/test_tensor_cfpq.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
from copy import deepcopy
from random import Random

import networkx as nx
import pytest
from pyformlang.cfg import CFG, Production, Terminal, Variable
from pyformlang.rsa import RecursiveAutomaton

from project.cfpq import (
cfg_to_rsm,
ebnf_to_rsm,
hellings_based_cfpq,
tensor_based_cfpq,
)


def path_graph(labels):
graph = nx.MultiDiGraph()
graph.add_nodes_from(range(len(labels) + 1))
for index, label in enumerate(labels):
graph.add_edge(index, index + 1, label=label)
return graph


def test_cfg_to_rsm_preserves_production_bodies_and_custom_start():
cfg = CFG.from_text("Root -> a B c | $\nB -> b B | b", start_symbol="Root")
rsm = cfg_to_rsm(cfg)

assert isinstance(rsm, RecursiveAutomaton)
assert rsm.initial_label.value == "Root"
assert rsm.get_box("Root").dfa.accepts(["a", "B", "c"])
assert rsm.get_box("Root").dfa.accepts([])
assert rsm.get_box("B").dfa.accepts(["b", "B"])
assert not rsm.get_box("Root").dfa.accepts(["a", "b", "c"])
assert tensor_based_cfpq(rsm, path_graph("abbc"), {0}, {4}) == {(0, 4)}


def test_cfg_to_rsm_preserves_literal_terminals_and_name_collisions():
start, other = Variable("S"), Variable("A")
cfg = CFG(
start_symbol=start,
productions={
Production(start, [Terminal("S"), other, Terminal("|")]),
Production(other, [Terminal("a b"), Terminal("*")]),
},
)
graph = path_graph(["S", "a b", "*", "|"])
assert tensor_based_cfpq(cfg_to_rsm(cfg), graph) == {(0, 4)}


@pytest.mark.parametrize("grammar", ["S -> A", "S -> S", "S -> A\nA -> S"])
def test_unproductive_variables_do_not_match_graph_labels(grammar):
graph = path_graph(["A", "S"])
assert tensor_based_cfpq(cfg_to_rsm(CFG.from_text(grammar)), graph) == set()


@pytest.mark.parametrize("graph_type", [nx.DiGraph, nx.MultiDiGraph])
def test_tensor_cfpq_handles_recursion_isolated_nodes_and_filters(graph_type):
graph = graph_type()
graph.add_nodes_from([10, 30, 70, 90, 110, 999])
graph.add_edge(10, 30, label="a")
graph.add_edge(30, 70, label="a")
graph.add_edge(70, 90, label="b")
graph.add_edge(90, 110, label="b")
graph.add_edge(10, 110) # Unlabeled edges do not participate.
rsm = ebnf_to_rsm("S -> a S b | $")
graph_before, rsm_before = deepcopy(graph), deepcopy(rsm)
expected = {(node, node) for node in graph} | {(10, 110), (30, 90)}

assert tensor_based_cfpq(rsm, graph) == expected
assert tensor_based_cfpq(rsm, graph, set(), set()) == expected
assert tensor_based_cfpq(rsm, graph, {10, 30}, {90, 110}) == {
(10, 110),
(30, 90),
}
assert tensor_based_cfpq(rsm, graph, {10, -1}, {110, -1}) == {(10, 110)}
assert tensor_based_cfpq(rsm, graph, {-1}) == set()
assert nx.utils.graphs_equal(graph, graph_before)
assert rsm == rsm_before


def test_tensor_cfpq_handles_parallel_edges():
graph = path_graph("ab")
graph.add_edge(0, 1, label="c")
assert tensor_based_cfpq(ebnf_to_rsm("S -> (a | c) b"), graph) == {(0, 2)}


@pytest.mark.parametrize(
"grammar, expected",
[
("S -> A B\nA -> $\nB -> C\nC -> $", {(7, 7), (12, 12)}),
("S -> A B\nA -> $\nB -> A S", set()),
("S -> a", set()),
],
)
def test_tensor_cfpq_handles_nullable_chains_without_edges(grammar, expected):
graph = nx.DiGraph()
graph.add_nodes_from([7, 12])
assert tensor_based_cfpq(cfg_to_rsm(CFG.from_text(grammar)), graph) == expected


def test_tensor_cfpq_handles_empty_graph_and_grammar():
assert tensor_based_cfpq(ebnf_to_rsm("S -> $"), nx.DiGraph()) == set()
assert tensor_based_cfpq(cfg_to_rsm(CFG()), path_graph("a")) == set()


def test_ebnf_to_rsm_unites_repeated_heads_and_handles_empty_bodies():
rsm = ebnf_to_rsm("\nS -> (a | b)* T\nS -> c\nT ->\nT -> d T\n")
assert rsm.get_box("S").dfa.accepts(["a", "b", "T"])
assert rsm.get_box("S").dfa.accepts(["c"])
assert rsm.get_box("T").dfa.accepts([])
assert rsm.get_box("T").dfa.accepts(["d", "T"])
assert (0, 4) in tensor_based_cfpq(rsm, path_graph("abdd"))


@pytest.mark.parametrize("text", ["", "A -> a", "S a", "-> a"])
def test_ebnf_to_rsm_rejects_missing_start_or_malformed_rules(text):
with pytest.raises(ValueError):
ebnf_to_rsm(text)


@pytest.mark.parametrize(
"cfg_text, ebnf",
[
("S -> $ | a S", "S -> a*"),
("S -> A B\nA -> a A | $\nB -> b B | $", "S -> a* b*"),
("S -> a S b | $ | S S", "S -> (a S b)*"),
("S -> a S b | c S d | $ | S S", "S -> (a S b | c S d)*"),
("S -> a B | b B\nB -> c B | d", "S -> (a | b) c* d"),
("S -> A\nA -> B\nB -> S | a", "S -> A\nA -> B\nB -> S | a"),
],
)
def test_tensor_cfpq_matches_hellings_on_seeded_graphs(cfg_text, ebnf):
cfg = CFG.from_text(cfg_text)
from_cfg, from_ebnf = cfg_to_rsm(cfg), ebnf_to_rsm(ebnf)
random = Random(8)
for _ in range(5):
graph = nx.MultiDiGraph()
nodes = [10, 30, 50, 70, 90]
graph.add_nodes_from(nodes)
for source in nodes:
for target in nodes:
for label in "abcd":
if random.random() < 0.12:
graph.add_edge(source, target, label=label)
for starts, finals in [(None, None), ({10, 30}, {70, 90})]:
expected = hellings_based_cfpq(cfg, graph, starts, finals)
assert tensor_based_cfpq(from_cfg, graph, starts, finals) == expected
assert tensor_based_cfpq(from_ebnf, graph, starts, finals) == expected
Loading