Skip to content

Instantly share code, notes, and snippets.

@lesguillemets
Created October 30, 2013 16:44
Show Gist options
  • Save lesguillemets/7235936 to your computer and use it in GitHub Desktop.
Save lesguillemets/7235936 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import Image
import numpy as np
class CellularAutomaton(object):
def __init__(self, elements, rulecode):
self.cells = list(elements)
self.rule = CARule(rulecode)
self.length = len(elements)
def __str__(self):
return ''.join(map(lambda x: '#' if x else '.', self.cells))
def next(self):
nextgen = [self.rule(self.cells[i:i+3]) for i in xrange(self.length-2)]
self.cells = [self.cells[0]] + nextgen + [self.cells[-1]]
class CARule(object):
def __init__(self, wfcode):
'''
wolfram code: given as an integer with base 10, not binary.
'''
self.rulenum = wfcode
self.rule = map(lambda n: bool(int(n)), "{0:08b}".format(wfcode))
self.rule.reverse()
# self.rule :: [Bool]
def __call__(self, conditions):
''' conditions : [Bool, Bool, Bool] '''
return self.rule[
sum([int(a) * 2**i for (i,a) in enumerate(conditions)])]
def __str__(self):
return "Wolfram Code {0}".format(self.rulenum)
def main():
width = 2001
gens = 2000
myca = np.zeros(width*gens, dtype=int).reshape(gens, width)
halflength = (width-1)/2
firstgen = [0]*halflength+[1]+[0]*halflength
mycell = CellularAutomaton(firstgen, 90)
for i in range(gens):
myca[i,:] = map(lambda x: 255 if x else 100, mycell.cells)
mycell.next()
img = Image.fromarray(np.uint8(myca))
img.save("./rule90_5001_6000.png")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment