MA0301/exam/python/FSA.py

80 lines
1.9 KiB
Python

from sys import argv
from pathlib import Path
import re
from common import replaceContent
placementChart = {
'a': 'above',
'b': 'below',
'l': 'left',
'r': 'right'
}
def generateEdge(inputLine):
s_src, msg, opts, s_dest = inputLine.split(' ')
out_options = []
if '(' in opts or ')' in opts:
out_options.append('bend left' if '(' in opts else 'bend right')
if any(x in opts for x in 'udlr'):
out_options.append(
'above' if 'u' in opts else \
'below' if 'd' in opts else \
'left' if 'l' in opts else \
'right' if 'r' in opts else ''
)
if s_src == 'o':
return f'\draw (s{s_dest}) edge[loop,{",".join(out_options)}] node{{{msg}}} (s{s_dest});'
else:
return f'\draw (s{s_src}) edge[{", ".join(out_options)}] node{{${msg}$}} (s{s_dest});'
def generateNode(inputLine):
s_src, opts = inputLine.split(' ')
out_opts = []
if 's' in opts:
out_opts.append('initial')
if 'f' in opts:
out_opts.append('accepting')
if place := re.search('[udlr]\d+', opts):
out_opts.append(placementChart[place.group()[0]] + ' of=s' + place.group()[1])
return f'\\node[state, {", ".join(out_opts)}] (s{s_src}) {{$s_{s_src}$}};'
def generate_latex(inputLines):
nodes, edges = inputLines.split('\n\n')
output=[]
for node in nodes.split('\n'):
output.append(generateNode(node))
output.append('')
for edge in edges.split('\n'):
output.append(generateEdge(edge))
return '\n'.join(output)
def processFileContent(raw):
content = generate_latex(raw)
return replaceContent(content, 'FSA')
if __name__ == '__main__':
pass
# filename = argv[1]
# with open(filename) as file:
# content = generate_latex(file.read())
# with open(str(Path(__file__).parent.absolute()) + '/tex_templates/FSA.tex') as template:
# with open(argv[2], 'w') as destination_file:
# destination_file.write(template.read().replace('%CONTENT', content))