2025-05-12_cellular-automaton-redux.html
001|
002|
003|
004|
005| from sys import argv
006|
007| def generate_rule (rule:int=110) -> dict:
008| '''\
008| Generate a rule dictionary from a number.
008|
008| Arguments:
008| rule rule number (from 0 to 255)
008|
008| Returns:
008| dictionary of the eight rule conditions
008|
008| '''
009|
010| assert type(rule) == int, ValueError('Rule number must be an integer.')
011| assert 0 <= rule <= 255, ValueError(f'Invalid rule number: {rule}')
012|
013|
014| sbits = f'{rule:08b}'
015|
016|
017| bits = [1 if b=='1' else 0 for b in sbits]
018|
019|
020| return {f'{bx:03b}':b for bx,b in enumerate(reversed(bits))}
021|
022|
023| if __name__ == '__main__':
024| rule = int(argv[1]) if 1 < len(argv) else 110
025|
026| rule_dict = generate_rule(rule)
027| for bx,bit_patt in enumerate(rule_dict):
028| print(f'{bx} [{bit_patt}]: {rule_dict[bit_patt]}')
029| print()
030|
031|
032| from sys import argv
033|
034| def initial_row (size:int, start:list) -> list:
035| '''\
035| Create an initial row that's twice as wide as the number of iterations.
035| This allows the default start -- a single centered nonblank cell -- to
035| grow to the edge by the last row. That is, it allows a triangle from the
035| center top that grows to either or both edges at the bottom.
035|
035| Place the starting pattern in the center of the row (or use it as is
035| if it's as long as twice the row count).
035|
035| Arguments:
035| size -number of rows requested
035| start -starting pattern
035|
035| Returns:
035| the intial row
035|
035| '''
036| assert type(size) == int, ValueError('Row count must be an integer.')
037| assert type(start) == list, ValueError('Start row must be a list.')
038|
039|
040| need = size * 2
041|
042|
043| if need <= len(start):
044| return list(start)
045|
046|
047| padding = (need - len(start)) // 2
048|
049|
050| row = ([0]*padding) + start + ([0]*padding)
051|
052|
053| while len(row) < need:
054|
055| row.append(0)
056|
057|
058| return row
059|
060|
061| if __name__ == '__main__':
062| size = int(argv[1]) if 1 < len(argv) else 100
063|
064| row = initial_row(size, [1])
065| print("".join(str(cell) for cell in row))
066| print()
067|
068|
069| from sys import argv, stdout
070| from os import path
071| from examples import generate_rule, initial_row
072|
073| def run_automaton (rule, size, start=[1], fname='automaton.out', fpath=''):
074| '''\
074| Elementary cellular automata (per almost every CS course ever).
074| See: https://en.wikipedia.org/wiki/Elementary_cellular_automaton
074|
074| Arguments:
074| rule rule number, from 0 to 255
074| size number of iterations
074| start the initial row, typically just [1]
074| fname filename for the text output (use None to use stdout)
074| fpath filepath or None if fname is a full path/filename
074|
074| Returns:
074| list of size+1 generated rows (includes initial row)
074|
074| '''
075| print(f'Run automata with rule {rule} ({size} rows)')
076| print()
077| make_key = lambda xs: ''.join(str(x) for x in xs)
078|
079|
080| row = initial_row(size, start)
081|
082|
083| rows = [row]
084|
085|
086| current_rule = generate_rule(rule)
087|
088|
089| for rx in range(size):
090|
091| new_row = [0]*len(row)
092|
093|
094| for ix in range(len(row)):
095|
096|
097| if ix == 0:
098|
099| key = make_key(row[0:1] + row[0:2])
100| elif ix == len(row)-1:
101|
102| key = make_key(row[ix-1:ix+1] + row[ix:ix+1])
103| else:
104|
105| key = make_key(row[ix-1:ix+2])
106|
107|
108| val = current_rule[key]
109|
110|
111| new_row[ix] = val
112|
113|
114| row = new_row
115|
116|
117| rows.append(row)
118|
119|
120| sout = stdout
121|
122| if fname:
123|
124| if '%s' in fname:
125| fname = fname % f'{rule:03d}'
126|
127| filename = path.join(fpath,fname) if fpath else fname
128| sout = open(filename, mode='w', encoding='utf8')
129|
130|
131| output = [''.join('#' if c else ' ' for c in row) for row in rows]
132|
133|
134| try:
135| for line in output:
136| print(line, file=sout)
137|
138| except:
139| raise
140|
141| finally:
142| if fname:
143| sout.close()
144| print(f'wrote: {filename}')
145| print()
146|
147|
148| return rows
149|
150|
151| if __name__ == '__main__':
152| rule = int(argv[1]) if 1 < len(argv) else 110
153| size = int(argv[2]) if 2 < len(argv) else 200
154|
155| rows = run_automaton(rule, size, fpath=r'C:\demo\hcc\python')
156|
157|
158| from sys import argv
159| from os import path
160| from PIL import Image, ImageDraw, ImageFont
161| from examples import run_automaton
162|
163| ImageBackground = (255,255,255)
164| ImageForeground = (0,0,0)
165|
166| NumberImage = True
167| NumberSize = 18
168| NumberColor = (255,0,0)
169| NumberFont = 'arialbd.ttf'
170|
171| def make_automaton_bitmap (rule, rows, margin=10, fname='automaton.png', fpath=''):
172| '''\
172| Generate a PNG file from the automata output.
172|
172| Arguments:
172| rule the rule number (for the filename)
172| rows output from the automata
172| margin width of image border (in pixels)
172| fname filename for the image file (required)
172| fpath filepath or None if fname is a full path/filename
172|
172| Returns:
172| nothing (None)
172|
172| '''
173| bg_color = ImageBackground
174| fg_color = ImageForeground
175|
176|
177| width = len(rows[-1]) + (2 * margin)
178|
179| height = len(rows) + (2 * margin)
180|
181|
182| img = Image.new('RGB', size=(width,height), color=bg_color)
183|
184| draw = ImageDraw.Draw(img)
185|
186|
187| for rx,row in enumerate(rows):
188|
189|
190| for cx,cell in enumerate(row):
191|
192| if cell:
193| px = cx + margin
194| py = rx + margin
195| draw.point((px, py), fill=fg_color)
196|
197|
198| if NumberImage:
199| fnt = ImageFont.truetype(NumberFont, size=NumberSize)
200| draw.text((0,0), str(rule), font=fnt, fill=NumberColor)
201|
202|
203| if '%s' in fname:
204| fname = fname % f'{rule:03d}'
205|
206|
207| filename = path.join(fpath,fname) if fpath else fname
208|
209|
210| img.save(filename)
211| print(f'wrote: {filename}')
212| print()
213|
214|
215| if __name__ == '__main__':
216| rule = int(argv[1]) if 1 < len(argv) else 110
217| size = int(argv[2]) if 2 < len(argv) else 400
218|
219|
220| rows = run_automaton(rule, size, fpath=r'C:\demo\hcc\python')
221|
222|
223| make_automaton_bitmap(rule, rows, fpath=r'C:\demo\hcc\python')
224|
225|
226|