2025-04-28_elementary-cellular-automaton.html


001| #:name::Elementary Cellular Automaton
002| #:link::https://thehardcorecoder.com/2025/04/28/elementary-cellular-automaton/
003| #:date::2025-04-28
004| #:code::
005| from sys import argv
006| 
007| def display_rule (rule=110):
008|     bit_string = f'{rule:08b}'
009| 
010|     for bx,b in enumerate(reversed(bit_string)):
011|         print(f'{bx} [{bx:03b}]: {b}')
012|     print()
013| 
014|     return list(int(b) for b in bit_string)
015| 
016| if __name__ == '__main__':
017|     rule = int(argv[1]) if 1 < len(argv) else 110
018| 
019|     bit_string = display_rule(rule)
020| 
021| #:code::
022| def expand_row (row:list) -> list:
023|     '''\
023| Ensure that row has three blanks at the beginning and end.
023| 
023| Arguments:
023|     row     an automata row
023| 
023| Returns:
023|     the row (note that the passed row is altered)
023| 
023| '''

024|     prefix = [0,0,0]
025| 
026|     # Ensure the row begins with three blanks...
027|     while row[:3] != prefix:
028|         row.insert(0, 0)
029| 
030|     # Ensure the row ends with three blanks...
031|     while row[-3:] != prefix:
032|         row.append(0)
033| 
034|     # Return the row...
035|     return row
036| 
037| 
038| if __name__ == '__main__':
039|     print(expand_row([1]))
040|     print(expand_row([0,1]))
041|     print(expand_row([0,0,1]))
042|     print(expand_row([0,0,0,1]))
043|     print(expand_row([0,0,0,0,1]))
044|     print(expand_row([1,0]))
045|     print(expand_row([1,0,0]))
046|     print(expand_row([1,0,0,0]))
047|     print(expand_row([1,0,0,0,0]))
048|     print(expand_row([0,1,0]))
049|     print(expand_row([0,0,1,0,0]))
050|     print(expand_row([0,0,0,1,0,0,0]))
051|     print(expand_row([0,0,0,0,1,0,0,0,0]))
052| 
053| #:code::
054| from sys import argv
055| 
056| def generate_rule (rule=110):
057|     '''\
057| Generate a rule dictionary from a number.
057| 
057| Arguments:
057|     rule    rule number (from 0 to 255)
057| 
057| Returns:
057|     dictionary of the eight rule conditions
057|     
057| '''

058|     assert 0 <= rule <= 255, ValueError(f'Invalid rule number: {rule}')
059| 
060|     # Convert number to an eight-bit string...
061|     sbits = f'{rule:08b}'
062| 
063|     # Convert bits string to a list of zeros and ones...
064|     bits = [1 if b=='1' else 0 for b in sbits]
065| 
066|     # Generate and return the rule dictionary...
067|     return {f'{bx:03b}':b for bx,b in enumerate(reversed(bits))}
068| 
069| if __name__ == '__main__':
070|     rule = int(argv[1]) if 1 < len(argv) else 110
071| 
072|     rule_dict = generate_rule(rule)
073|     for bx,bit_patt in enumerate(rule_dict):
074|         print(f'{bx} [{bit_patt}]: {rule_dict[bit_patt]}')
075|     print()
076| 
077| #:code::
078| from sys import argv, stdout
079| from os import path
080| from examples import expand_row, generate_rule
081| 
082| def run_automata (rule, size, start=[1], fname='automata.out', fpath=''):
083|     '''\
083| Elementary cellular automata (per almost every CS course ever).
083| See: https://en.wikipedia.org/wiki/Elementary_cellular_automaton
083| 
083| Arguments:
083|     rule    -rule number, from 0 to 255
083|     size    -number of iterations
083|     start   -the initial row, typically just [1]
083|     fname   -filename for the text output (use None to use stdout)
083|     fpath   -filepath or None if fname is a full path/filename
083| 
083| Returns:
083|     list of size+1 generated rows (includes initial row)
083| 
083| '''

084|     print(f'Run automata with rule {rule} ({size} rows)')
085|     print()
086| 
087|     # Ensure the row has leading blanks so the automata always
088|     # reacts to a 0-0-0 input to start and end...
089|     row = expand_row(start)
090|     print(f'Initial row: {"".join(str(x) for x in row)}')
091|     print()
092| 
093|     # Generated rows appended to this list...
094|     rows = [row]
095| 
096|     # Get the rule for this run...
097|     current_rule = generate_rule(rule)
098| 
099|     # Iterations of rule...
100|     for rx in range(size):
101|         # The new row is same length as current row but
102|         # consists of just zeros (blanks)...
103|         new_row = [0]*len(row)
104| 
105|         # For each triplet in the current row...
106|         for ix in range(len(row)-2):
107| 
108|             # Convert the triplet to a key...
109|             key = ''.join(str(x) for x in row[ix:ix+3])
110| 
111|             # Get the value per the rule...
112|             val = current_rule[key]
113| 
114|             # And put it in the new row...
115|             new_row[ix+1] = val
116| 
117|         # Ensure the new row has prefix and suffix blanks
118|         # and make it the current row...
119|         row = expand_row(new_row)
120| 
121|         # Append the (new) row to the output list...
122|         rows.append(row)
123| 
124|     # We'll default to the display...
125|     sout = stdout
126|     # But if a filename is supplied, open a file...
127|     if fname:
128|         # Include the rule ID in the filename (if requested)...
129|         if '%s' in fname:
130|             fname = fname % f'{rule:03d}'
131| 
132|         filename = path.join(fpath,fname) if fpath else fname
133|         sout = open(filename, mode='w', encoding='utf8')
134| 
135|     # For the display, convert 0s and 1s to something printable...
136|     output = [''.join('#' if c else ' ' for c in row) for row in rows]
137| 
138|     # Display (or write to file) the output...
139|     try:
140|         for line in output:
141|             print(line, file=sout)
142| 
143|     except:
144|         raise
145| 
146|     finally:
147|         if fname:
148|             sout.close()
149|             print(f'wrote: {filename}')
150|             print()
151| 
152|     # Return the list of generated rows...
153|     return rows
154| 
155| if __name__ == '__main__':
156|     rule = int(argv[1]) if 1 < len(argv) else 110
157|     size = int(argv[2]) if 2 < len(argv) else  20
158| 
159|     rows = run_automata(rule, size, fpath=r'C:\demo\hcc\python')
160|     for row in rows:
161|         print(row)
162|     print()
163| 
164| #:code::
165| from sys import argv
166| from os import path
167| from PIL import Image, ImageDraw
168| from examples import run_automata
169| 
170| def make_automata_bitmap (rule, rows, fname='automata.png', fpath=''):
171|     '''\
171| Generate a PNG file from the automata output.
171| 
171| Arguments:
171|     rows    output from the automata
171|     rule    the rule number (for the filename)
171|     fname   filename for the image file (required)
171|     fpath   filepath or None if fname is a full path/filename
171| 
171| Returns:
171|     nothing (None)
171| 
171| '''

172|     bg_color = (255,255,255)    # white background
173|     fg_color = (0,0,0)          # black cells
174|     margin = 10                 # margin pixels all four sides
175| 
176|     # Image width is the longest row plus margins...
177|     width = len(rows[-1]) + (2 * margin)
178|     # Image height is the number of rows plus margins...
179|     height = len(rows) + (2 * margin)
180| 
181|     # Create a new image...
182|     img = Image.new('RGB', size=(width,height), color=bg_color)
183|     # And a drawing object...
184|     draw = ImageDraw.Draw(img)
185| 
186|     # For each row of output...
187|     for rx,row in enumerate(rows):
188| 
189|         # For each cell in the row...
190|         for cx,cell in enumerate(row):
191|             # Draw one black pixel if cell=1...
192|             if cell:
193|                 px = cx + margin
194|                 py = rx + margin
195|                 draw.point((px, py), fill=fg_color)
196| 
197|     # Include the rule ID in the filename (if requested)...
198|     if '%s' in fname:
199|         fname = fname % f'{rule:03d}'
200| 
201|     # We want a complete filename for the image...
202|     filename = path.join(fpath,fname) if fpath else fname
203| 
204|     # Save the image...
205|     img.save(filename)
206|     print(f'wrote: {filename}')
207|     print()
208| 
209| if __name__ == '__main__':
210|     rule = int(argv[1]) if 1 < len(argv) else 110
211|     size = int(argv[2]) if 2 < len(argv) else 500
212| 
213|     # Run the automaton...
214|     rows = run_automata(rule, size, fpath=r'C:\demo\hcc\python')
215| 
216|     # Generate an image file...
217|     make_automata_bitmap(rule, rows, fpath=r'C:\demo\hcc\python')
218| 
219| #:code::
220| from examples import BasePath, KWARG, run_automata, make_automata_bitmap
221| 
222| def do_run_rule (**kwargs):
223|     """CMND: Run the automata with a given rule."""
224|     dpath = KWARG('dpath', BasePath, str, kwargs)
225|     dname = KWARG('dname', 'automata_%s.out', str, kwargs)
226|     ipath = KWARG('ipath', BasePath, str, kwargs)
227|     iname = KWARG('iname', 'automata_%s.png', str, kwargs)
228|     rule  = KWARG('rule' , 110, int, kwargs)
229|     size  = KWARG('size' , 250, int, kwargs)
230|     inits = KWARG('inits', '1', str, kwargs)
231|     print('run-rule:: %s' % str(list(kwargs.keys())))
232|     print(f'{dpath=}')
233|     print(f'{dname=}')
234|     print(f'{ipath=}')
235|     print(f'{iname=}')
236|     print(f'{rule=}')
237|     print(f'{size=}')
238|     print(f'{inits=}')
239|     print()
240| 
241|     # Convert initialization string ("10101") to a list of bits...
242|     start = [1 if x else 0 for x in inits]
243| 
244|     # Run the automata...
245|     rows = run_automata(rule, size, fname=dname, fpath=dpath)
246| 
247|     # Make a bitmap...
248|     make_automata_bitmap(rule, rows, fname=iname, fpath=ipath)
249| 
250|     print()
251|     return 'Done!'
252| 
253| if __name__ == '__main__':
254|     kwargs = {
255|         'rule': '110',
256|         'size': '300',
257|     }
258|     do_run_rule(**kwargs)
259| 
260| #:code::
261| from os import path
262| from examples import BasePath, KWARG, run_automata, make_automata_bitmap
263| 
264| def do_run_all_rules (**kwargs):
265|     """CMND: Run the automata with all 250 rules."""
266|     dpath = KWARG('dpath', BasePath, str, kwargs)
267|     dname = KWARG('dname', 'automata_%s.out', str, kwargs)
268|     ipath = KWARG('ipath', BasePath, str, kwargs)
269|     iname = KWARG('iname', 'automata_%s.png', str, kwargs)
270|     size  = KWARG('size' , 250, int, kwargs)
271|     print('run-rule:: %s' % str(list(kwargs.keys())))
272|     print(f'{dpath=}')
273|     print(f'{dname=}')
274|     print(f'{ipath=}')
275|     print(f'{iname=}')
276|     print(f'{size=}')
277|     print()
278| 
279|     # For all possible rules...
280|     for rule in range(0,256):
281|         print(f'Rule: {rule} ({rule:08b})')
282| 
283|         # Run the automata...
284|         rows = run_automata(rule, size, fname=dname, fpath=dpath)
285| 
286|         # Make a bitmap...
287|         make_automata_bitmap(rule, rows, fname=iname, fpath=ipath)
288| 
289|     print()
290|     return 'Done!'
291| 
292| if __name__ == '__main__':
293|     kwargs = {
294|         'size': '300',
295|         'dpath': path.join(BasePath, 'dat'),
296|         'ipath': path.join(BasePath, 'img'),
297|     }
298|     do_run_all_rules(**kwargs)
299| 
300| #:code::
301| from sys import argv
302| from examples import do_run_rule, do_run_all_rules
303| 
304| def dispatch (cmd, **kwargs):
305|     """Dispatch to a module function based on CMD."""
306|     print(f'CMD: {cmd}')
307|     for kw in kwargs:
308|         print(f'argument[{kw}]: {kwargs[kw]}')
309|     print()
310| 
311|     if cmd == 'one': return do_run_rule(**kwargs)
312|     if cmd == 'all': return do_run_all_rules(**kwargs)
313|     return 'Nothing to do!'
314| 
315| if __name__ == '__main__':
316|     print('autorun: %s' % argv[0])
317|     print(argv[0])
318|     print()
319|     cmd = argv[1] if 1 < len(argv) else ''
320|     kwargs = {}
321|     for a in argv[2:]:
322|         nv = a.split('=', 2)
323|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
324|         print('%s: "%s"' % (nv[0], kwargs[nv[0]]))
325| 
326|     print()
327|     obj = dispatch(cmd, **kwargs)
328|     print()
329|     print(obj)
330|     print()
331| 
332| #:end:code::
333|