2025-05-12_cellular-automaton-redux.html


001| #:name::Cellular Automaton Redux
002| #:link::https://thehardcorecoder.com/2025/05/12/cellular-automaton-redux/
003| #:date::2025-05-12
004| #:code::
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|     # Ensure we got a valid rule number...
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|     # Convert number to an eight-bit string...
014|     sbits = f'{rule:08b}'
015| 
016|     # Convert bits string to a list of zeros and ones...
017|     bits = [1 if b=='1' else 0 for b in sbits]
018| 
019|     # Generate and return the rule dictionary...
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| #:code::
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|     # Initial row must be twice the numbers of rows generated...
040|     need = size * 2
041| 
042|     # If the starting row's length is long enough, use it as is...
043|     if need <= len(start):
044|         return list(start)
045| 
046|     # Calculate amount of padding needed...
047|     padding = (need - len(start)) // 2
048| 
049|     # Build the starting row...
050|     row = ([0]*padding) + start + ([0]*padding)
051| 
052|     # Compensate for round-off...
053|     while len(row) < need:
054|         # This should happen only once (if at all)...
055|         row.append(0)
056| 
057|     # Return the row...
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| #:code::
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|     # Create the initial row...
080|     row = initial_row(size, start)
081| 
082|     # Generated rows appended to this list...
083|     rows = [row]
084| 
085|     # Get the rule for this run...
086|     current_rule = generate_rule(rule)
087| 
088|     # Iterations of rule...
089|     for rx in range(size):
090|         # Create new row of all blanks...
091|         new_row = [0]*len(row)
092| 
093|         # For each triplet in the current row...
094|         for ix in range(len(row)):
095| 
096|             # Convert the triplet to a key...
097|             if ix == 0:
098|                 # Edge case: first triplet extends beyond start of row...
099|                 key = make_key(row[0:1] + row[0:2])
100|             elif ix == len(row)-1:
101|                 # Edge case: last triplet extends beyond end of row...
102|                 key = make_key(row[ix-1:ix+1] + row[ix:ix+1])
103|             else:
104|                 # The usual case...
105|                 key = make_key(row[ix-1:ix+2])
106| 
107|             # Get the value per the rule...
108|             val = current_rule[key]
109| 
110|             # And put it in the new row...
111|             new_row[ix] = val
112| 
113|         # Make the new row the current row...
114|         row = new_row
115| 
116|         # Append the (new) row to the output list...
117|         rows.append(row)
118| 
119|     # We'll default to the display...
120|     sout = stdout
121|     # But if a filename is supplied, open a file...
122|     if fname:
123|         # Include the rule ID in the filename (optional)...
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|     # For the display, convert 0s and 1s to something printable...
131|     output = [''.join('#' if c else ' ' for c in row) for row in rows]
132| 
133|     # Display (or write to file) the output...
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|     # Return the list of generated rows...
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| #:code::
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      # background (nominally white)
174|     fg_color = ImageForeground      # cells (nominally black)
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 pixel if cell is nonblank...
192|             if cell:
193|                 px = cx + margin
194|                 py = rx + margin
195|                 draw.point((px, py), fill=fg_color)
196| 
197|     # Place rule number in upper-left corner (optional)...
198|     if NumberImage:
199|         fnt = ImageFont.truetype(NumberFont, size=NumberSize)
200|         draw.text((0,0), str(rule), font=fnt, fill=NumberColor)
201| 
202|     # Include the rule ID in the filename (optional)...
203|     if '%s' in fname:
204|         fname = fname % f'{rule:03d}'
205| 
206|     # We want a complete filename for the image...
207|     filename = path.join(fpath,fname) if fpath else fname
208| 
209|     # Save the image...
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|     # Run the automaton...
220|     rows = run_automaton(rule, size, fpath=r'C:\demo\hcc\python')
221| 
222|     # Generate an image file...
223|     make_automaton_bitmap(rule, rows, fpath=r'C:\demo\hcc\python')
224| 
225| #:end:code::
226|