Advertisement
Guest User

FA Machine to Dot Graphviz description

a guest
Nov 3rd, 2010
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.28 KB | None | 0 0
  1. #!/usr/bin/env python
  2. '''
  3. This simple module allow you to generate DOT graph descriptions using the
  4. fa_to_dot() function. So the function would return something like the following:
  5.  
  6. digraph fi {
  7.     "x-" -> "y" [label="a"];
  8.     "x-" -> "z+" [label="b"];
  9.     "y" -> "x-" [label="a"];
  10.     "y" -> "z+" [label="b"];
  11.     "z+" -> "z+" [label="a"];
  12.     "z+" -> "z+" [label="b"];
  13. }
  14.  
  15. Please have a look at the source of the main() function of the module to see how
  16. to use fa_to_dot().
  17. '''
  18.  
  19. def check_state(state, start_state, final_states):
  20.     '''
  21.    Return the state as a begin (-) or end (+) state if the state is a begin
  22.    or end state.
  23.    '''
  24.     result_state = state
  25.     if state == start_state:
  26.         result_state += '-'
  27.     if state in final_states:
  28.         result_state += '+'
  29.     return result_state
  30.  
  31. def fa_to_dot(states, alphabet, transistions, start_state, final_states):
  32.     '''
  33.    Builds a DOT graph description using a FA Machine.
  34.  
  35.    TODO: Check that the states and alphabet that is in use by the transistions
  36.    match the parameters.
  37.    '''
  38.     dot = 'digraph fa {\n'
  39.     for transition in transistions:
  40.         from_state, input_letter = transition
  41.         to_state = transistions[transition]
  42.         from_node = check_state(from_state, start_state, final_states)
  43.         to_node = check_state(to_state, start_state, final_states)
  44.         label = input_letter
  45.         dot += '\t"' + from_node + '" -> "' + to_node + '" [label="' \
  46.             + label + '"]\n'
  47.     dot += '}'
  48.     return dot
  49.  
  50. def main():
  51.     # S - Set of the states
  52.     states = set('xyz')
  53.     # Σ (Sigma) - Alphabet of the input letters
  54.     alphabet = set('ab')
  55.     # T: SxΣ -> S - Set of transistions
  56.     # Because we want it to resebmle a set of functions we use a dict:
  57.     # T(S,Σ) = S is (S, Σ): S
  58.     # Where (S, Σ) on the LHS is the key and S on the RHS is the value of
  59.     # the dict item
  60.     transistions = {('x', 'a'): 'y',
  61.          ('x', 'b'): 'z',
  62.          ('y', 'a'): 'x',
  63.          ('y', 'b'): 'z',
  64.          ('z', 'a'): 'z',
  65.          ('z', 'b'): 'z'}
  66.     # s0 - Start state
  67.     start_state = 'x'
  68.     # F - Set of Final States
  69.     final_states = set('z')
  70.  
  71.     print fa_to_dot(states, alphabet, transistions, start_state, final_states)
  72.  
  73. if __name__ == '__main__':
  74.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement