rewritingsystem_fsm.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. class State:
  2. '''
  3. A representation of a state managed by a ``StateMachine``.
  4. Attributes:
  5. name (instance of FreeGroupElement or string) -- State name which is also assigned to the Machine.
  6. transisitons (OrderedDict) -- Represents all the transitions of the state object.
  7. state_type (string) -- Denotes the type (accept/start/dead) of the state.
  8. rh_rule (instance of FreeGroupElement) -- right hand rule for dead state.
  9. state_machine (instance of StateMachine object) -- The finite state machine that the state belongs to.
  10. '''
  11. def __init__(self, name, state_machine, state_type=None, rh_rule=None):
  12. self.name = name
  13. self.transitions = {}
  14. self.state_machine = state_machine
  15. self.state_type = state_type[0]
  16. self.rh_rule = rh_rule
  17. def add_transition(self, letter, state):
  18. '''
  19. Add a transition from the current state to a new state.
  20. Keyword Arguments:
  21. letter -- The alphabet element the current state reads to make the state transition.
  22. state -- This will be an instance of the State object which represents a new state after in the transition after the alphabet is read.
  23. '''
  24. self.transitions[letter] = state
  25. class StateMachine:
  26. '''
  27. Representation of a finite state machine the manages the states and the transitions of the automaton.
  28. Attributes:
  29. states (dictionary) -- Collection of all registered `State` objects.
  30. name (str) -- Name of the state machine.
  31. '''
  32. def __init__(self, name, automaton_alphabet):
  33. self.name = name
  34. self.automaton_alphabet = automaton_alphabet
  35. self.states = {} # Contains all the states in the machine.
  36. self.add_state('start', state_type='s')
  37. def add_state(self, state_name, state_type=None, rh_rule=None):
  38. '''
  39. Instantiate a state object and stores it in the 'states' dictionary.
  40. Arguments:
  41. state_name (instance of FreeGroupElement or string) -- name of the new states.
  42. state_type (string) -- Denotes the type (accept/start/dead) of the state added.
  43. rh_rule (instance of FreeGroupElement) -- right hand rule for dead state.
  44. '''
  45. new_state = State(state_name, self, state_type, rh_rule)
  46. self.states[state_name] = new_state
  47. def __repr__(self):
  48. return "%s" % (self.name)