Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2017
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. """Generate 1-dimensional automata based on various rules"""
  3.  
  4. from itertools import product
  5.  
  6. def ngrams(iterable, n=1):
  7. """Generate ngrams from an iterable"""
  8. return zip(*(iterable[i:] for i in range(n)))
  9.  
  10. def states(state, rule, left_pad='0', right_pad='0'):
  11. """Generate a stream of states from an initial state and a rule"""
  12. next_state = ''.join(rule[''.join(window)] for window in ngrams(state, 3))
  13. padding = '{}{}{}'
  14. yield state, states(padding.format(left_pad, next_state, right_pad), rule)
  15.  
  16. def automata(state, rule, n):
  17. """Generate n generations given an initial state and a rule"""
  18. tail = states(state, rule)
  19. for _ in range(n):
  20. head, tail = next(tail)
  21. yield head
  22.  
  23. if __name__ == '__main__':
  24. SYMBOLS = '01'
  25. WIDTH = 80
  26. LEFT, RIGHT = (SYMBOLS[0] * (WIDTH // 2),) * 2
  27. GENERATIONS = 30
  28. # generate all possible 3 bit windows/keys
  29. keys = ['{:0>3b}'.format(i) for i in range(8)]
  30. # generate all possible bytes
  31. bytes_ = list(product(SYMBOLS, repeat=8))
  32. # construct all 256 possible rule mappings of 3-bit keys to 1-bit values
  33. rules = [dict(zip(keys, bytes_[i])) for i in range(len(bytes_))]
  34. # define the seed state with a single bit activated in the middle
  35. initial_state = LEFT + SYMBOLS[1] + RIGHT
  36. # show the first 30 generations for each of the 256 rules
  37. label = 'rule #{}: {}'
  38. for i, rule in enumerate(rules, 1):
  39. print(label.format(i, rule))
  40. for state in automata(initial_state, rule, GENERATIONS):
  41. print(state)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement