-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge branch 'FormalLanguageConstrainedPathQuerying:main' into main
- Loading branch information
Showing
6 changed files
with
169 additions
and
53 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,7 @@ | ||
antlr4-python3-runtime | ||
black | ||
cfpq-data | ||
networkx==3.2.1 | ||
pre-commit | ||
pydot | ||
pytest | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,33 @@ | ||
# Задача 3. Регулярные запросы для всех пар вершин | ||
|
||
* **Мягкий дедлайн**: 25.09.2023, 23:59 | ||
* **Жёсткий дедлайн**: 28.09.2023, 23:59 | ||
* **Жёсткий дедлайн**: 06.03.2024, 23:59 | ||
* Полный балл: 5 | ||
|
||
## Задача | ||
|
||
- [ ] Реализовать тип (FiniteAutomaton), представляющий конечный автомат в виде разреженной матрицы смежности из [sciPy](https://docs.scipy.org/doc/scipy/reference/sparse.html) (или сразу её булевой декомпозиции) и информации о стартовых и финальных вершинах. У типа должны быть конструкторы от ```DeterministicFiniteAutomaton``` и ```NondeterministicFiniteAutomaton``` из [Задачи 2](https://github.com/FormalLanguageConstrainedPathQuerying/formal-lang-course/blob/main/tasks/task2.md). | ||
- [ ] Реализовать функцию-интерпретатор для типа ```FiniteAutomaton```, выясняющую, принимает ли автомат заданную строку и является ли язык, задающийся автоматом, пустым. Для реализации последней функции рекомендуется использовать транзитивное замыкание матрицы смежности. | ||
- Требуемые функции: | ||
```python | ||
def accepts(self, word: Iterable[Symbol]) -> bool: | ||
pass | ||
def is_empty(self) -> bool: | ||
pass | ||
``` | ||
- [ ] Используя [разреженные матрицы из sciPy](https://docs.scipy.org/doc/scipy/reference/sparse.html) реализовать **функцию** пересечения двух конечных автоматов через тензорное произведение. | ||
- Требуемая функция: | ||
```python | ||
def intersect_automata(automaton1: FiniteAutomaton, | ||
automaton2: FiniteAutomaton) -> FiniteAutomaton: | ||
pass | ||
``` | ||
- [ ] На основе предыдущей функции реализовать **функцию** выполнения регулярных запросов к графам: по графу с заданными стартовыми и финальными вершинами и регулярному выражению вернуть те пары вершин из заданных стартовых и финальных, которые связанны путём, формирующем слово из языка, задаваемого регулярным выражением. | ||
- Требуемая функция: | ||
```python | ||
def paths_ends(graph: MultiDiGraph, start_nodes: set[int], | ||
final_nodes: set[int], regex:str) -> list[tuple[NodeView, NodeView]]: | ||
pass | ||
``` | ||
|
||
- Для конструирования регулярного запроса и преобразований графа использовать результаты [Задачи 2](https://github.com/FormalLanguageConstrainedPathQuerying/formal-lang-course/blob/main/tasks/task2.md). | ||
- [ ] Добавить необходимые тесты. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
# This file contains test cases that you need to pass to get a grade | ||
# You MUST NOT touch anything here except ONE block below | ||
# You CAN modify this file IF AND ONLY IF you have found a bug and are willing to fix it | ||
# Otherwise, please report it | ||
import pyformlang.finite_automaton | ||
from networkx import MultiDiGraph | ||
from pyformlang.regular_expression import Regex | ||
import pytest | ||
import random | ||
import itertools | ||
import networkx as nx | ||
|
||
# Fix import statements in try block to run tests | ||
try: | ||
from project.task3 import intersect_automata, FiniteAutomaton | ||
from project.task2 import regex_to_dfa | ||
except ImportError: | ||
pytestmark = pytest.mark.skip("Task 3 is not ready to test!") | ||
|
||
REGEX_TO_TEST = [ | ||
("a", "b"), | ||
("a", "a"), | ||
("a*", "a"), | ||
("a*", "aa"), | ||
("a*", "a*"), | ||
("(aa)*", "a*"), | ||
("(a|b)*", "a*"), | ||
("(a|b)*", "b"), | ||
("(a|b)*", "bbb"), | ||
("a|b", "a"), | ||
("a|b", "a|c"), | ||
("(a|b)(c|d)", "(a|c)(b|d)"), | ||
("(a|b)*", "(a|c)*"), | ||
("a*b*", "(a|b)*"), | ||
("(ab)*", "(a|b)*"), | ||
] | ||
|
||
|
||
class TestIntersect: | ||
@pytest.mark.parametrize( | ||
"regex_str1, regex_str2", | ||
REGEX_TO_TEST, | ||
ids=lambda regex_tuple: regex_tuple, | ||
) | ||
def test(self, regex_str1: str, regex_str2: str) -> None: | ||
dfa1 = FiniteAutomaton(regex_to_dfa(regex_str1)) | ||
dfa2 = FiniteAutomaton(regex_to_dfa(regex_str2)) | ||
intersect_fa = intersect_automata(dfa1, dfa2) | ||
|
||
regex1: Regex = Regex(regex_str1) | ||
regex2: Regex = Regex(regex_str2) | ||
cfg_of_regex1: pyformlang.cfg.CFG = regex1.to_cfg() | ||
intersect_cfg: pyformlang.cfg.CFG = cfg_of_regex1.intersection(regex2) | ||
words = intersect_cfg.get_words() | ||
if intersect_cfg.is_finite(): | ||
all_word_parts = list(words) | ||
if len(all_word_parts) == 0: | ||
assert intersect_fa.is_empty() | ||
return | ||
word_parts = random.choice(all_word_parts) | ||
else: | ||
index = random.randint(0, 2**9) | ||
word_parts = next(itertools.islice(words, index, None)) | ||
|
||
word = map(lambda x: x.value, word_parts) | ||
|
||
assert intersect_fa.accepts(word) |