__init__.py 2.32 KB
Newer Older
1
2
3
4
5
6
from abc import ABCMeta, abstractmethod

"""A basic abstract automaton model"""
class Automaton(metaclass=ABCMeta):
   def __init__(self, states, state_to_trans):
      super().__init__()
7
8
      self._states = states
      self._state_to_trans = state_to_trans
9

10
   def start_state(self):
11
      return self._states[0]
12
13

   def states(self):
14
      return list(self._states)
15
16
17

   def transitions(self, state, label=None):
      if label is None:
18
         return list(self._state_to_trans[state])
19
      else:
20
         return list([trans for trans in self._state_to_trans[state] if trans.start_label == label])
21
22
23
24
25

   @abstractmethod
   def state(self, trace):
       pass

26
27
28
29
30
31
32
33
34
35
   def __str__(self):
       str_rep = ""
       for state in self.states():
           str_rep += str(state) + "\n"
           for tran in self.transitions(state):
               str_rep += "\t"+tran.__str__(shortened=True) + "\n"

       return str_rep


36
37
38
"""An automaton model that generates output"""
class Transducer(Automaton, metaclass=ABCMeta):
    def __init__(self, states, state_to_trans):
39
        super().__init__(states, state_to_trans)
40
41
42
43
44
45
46
47

    @abstractmethod
    def outputs(self, trace):
        pass

"""An automaton model whose states are accepting/rejecting"""
class Acceptor(Automaton, metaclass=ABCMeta):
    def __init__(self, states, state_to_trans, state_to_acc):
48
        super().__init__(states, state_to_trans)
49
        self._state_to_acc = state_to_acc
50
51

    def is_accepting(self, state):
52
        return self._state_to_acc[state]
53
54

    def accepts(self, trace):
55
56
57
        state = self.state(trace)
        is_acc = self.is_accepting(state)
        return is_acc
58

59
"""The most basic transition class available"""
60
61
62
63
class Transition():
    def __init__(self, start_state, start_label, end_state):
        self.start_state = start_state
        self.start_label = start_label
64
        self.end_state = end_state
65

66
67
68
69
70
    def __str__(self, shortened=False):
        if not shortened:
            return "{0} {1} -> {2}".format(self.start_state, self.start_label, self.end_state)
        else:
            "{1} -> {2}".format(self.start_label, self.end_state)
71

72
"""Exception raised when no transition can be fired"""
73
74
75
class NoTransitionFired(Exception):
   pass

76
77
"""Exception raised when several transitions can be fired in a deterministic machine"""
class MultipleTransitionsFired(Exception):
78
79
    pass