Skip to content
Closed
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
2 changes: 1 addition & 1 deletion README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -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!")
```
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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!")
```
Expand Down
42 changes: 42 additions & 0 deletions project/automata_construction.py
Original file line number Diff line number Diff line change
@@ -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
41 changes: 41 additions & 0 deletions project/automata_utils.py
Original file line number Diff line number Diff line change
@@ -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
76 changes: 76 additions & 0 deletions project/graph_utils.py
Original file line number Diff line number Diff line change
@@ -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
90 changes: 90 additions & 0 deletions project/hellings.py
Original file line number Diff line number Diff line change
@@ -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
}
Loading