-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpctm.py
executable file
·157 lines (135 loc) · 5.53 KB
/
pctm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#!/usr/bin/python3
# -*- coding: utf-8 -*-
""" Command-Line interface for interacting with Turing Machines and Grammars for primality check """
import argparse
from datetime import timedelta
from timeit import default_timer as timer
from typing import Tuple, List, Union
from pyformlang import cfg
from src.context_sensitive_grammar import ContextSensitiveGrammar
from src.my_production import Production
from src.turing_machine import TuringMachine
from src.unrestricted_grammar import UnrestrictedGrammar
def print_trace(
res: Tuple[List[Production], List[Tuple[Union[cfg.Variable, cfg.Terminal], ...]]]
, grammar: Union[ContextSensitiveGrammar, UnrestrictedGrammar]
):
""" Print word output trace """
productions, sentences = res
output: List[Tuple[str, str, str]] = list()
for i in range(len(productions)):
sentence_from = list(map(lambda x: x.value, sentences[i]))
if sentence_from == [grammar.start_symbol]:
sentence_from = [grammar.start_symbol.value]
production_head = list(map(lambda x: x.value, productions[i].head))
production_body = list(map(lambda x: x.value, productions[i].body))
sentence_to = list(map(lambda x: x.value, sentences[i + 1]))
output.append(
(f'{" ".join(sentence_from)}',
f'{grammar.productions.index(productions[i]) + 1}) {" ".join(production_head)} -> {" ".join(production_body)}',
f'{" ".join(sentence_to)}')
)
formats = [-1] * 3
for s in output:
for i in range(3):
formats[i] = max(formats[i], len(s[i]) + 1)
for s in output:
print(
('{0:<' + str(formats[0]) + '}').format(s[0]) + ' : ' +
('{0:<' + str(formats[1]) + '}').format(s[1]) + ' : ' +
('{0:<' + str(formats[2]) + '}').format(s[2])
)
def main():
""" Command-Line tool for interacting with Turing Machines and Grammars for primality check """
parser = argparse.ArgumentParser(
description='Primality Check Turing Machine'
, epilog="At least one of -tm/--turing_machine, "
+ "-lba/--linear_bounded_automaton, "
+ "-csg/--context_sensitive_grammar, "
+ "-ug/--unrestricted_grammar required"
)
parser.add_argument(
'-tm'
, '--turing_machine'
, help='Check by Turing Machine'
, action='store_true'
)
parser.add_argument(
'-lba'
, '--linear_bounded_automaton'
, help='Check by Linear Bounded Automaton'
, action='store_true'
)
parser.add_argument(
'-csg'
, '--context_sensitive_grammar'
, help='Check by Context Sensitive Grammar'
, action='store_true'
)
parser.add_argument(
'-ug'
, '--unrestricted_grammar'
, help='Check by Unrestricted Grammar'
, action='store_true'
)
parser.add_argument(
'-w'
, '--word'
, help='Word to check'
, type=str
, required=True
)
args = parser.parse_args()
if args.turing_machine is False and \
args.linear_bounded_automaton is False and \
args.context_sensitive_grammar is False and \
args.unrestricted_grammar is False:
parser.error("At least one of -tm/--turing_machine, "
+ "-lba/--linear_bounded_automaton, "
+ "-csg/--context_sensitive_grammar, "
+ "-ug/--unrestricted_grammar required"
)
turing_machine = None
if args.turing_machine is True:
turing_machine = TuringMachine.from_txt('resources/primality_check_tm.txt')
linear_bounded_automaton = None
if args.linear_bounded_automaton is True:
linear_bounded_automaton = TuringMachine.from_txt('resources/primality_check_lba.txt')
context_sensitive_grammar = None
if args.context_sensitive_grammar is True:
context_sensitive_grammar = ContextSensitiveGrammar.from_txt('resources/primality_check_csg.txt')
unrestricted_grammar = None
if args.unrestricted_grammar is True:
unrestricted_grammar = UnrestrictedGrammar.from_txt('resources/primality_check_ug.txt')
if turing_machine is not None:
start = timer()
res = turing_machine.accepts(args.word)
end = timer()
result_time = timedelta(seconds=end - start)
print(f'Check by Turing Machine: {res} is done in {result_time} seconds')
if linear_bounded_automaton is not None:
start = timer()
res = linear_bounded_automaton.accepts("$" + args.word + "#")
end = timer()
result_time = timedelta(seconds=end - start)
print(f'Check by Linear Bounded Automaton: {res} is done in {result_time} seconds')
if context_sensitive_grammar is not None:
start = timer()
res = context_sensitive_grammar.accepts(args.word)
end = timer()
result = res != tuple()
result_time = timedelta(seconds=end - start)
print(f'Check by Context Sensitive Grammar: {result} is done in {result_time} seconds')
if result:
print_trace(res, context_sensitive_grammar)
if unrestricted_grammar is not None:
start = timer()
res = unrestricted_grammar.accepts(args.word)
end = timer()
result = res != tuple()
result_time = timedelta(seconds=end - start)
print(f'Check by Unrestricted Grammar: {result} is done in {result_time} seconds')
if result:
print_trace(res, unrestricted_grammar)
if __name__ == '__main__':
main()