automata.html


001| '''Elementary Cellular Automata.
001| 
001| Reference:
001|     https://en.wikipedia.org/wiki/Elementary_cellular_automaton
001|     https://en.wikipedia.org/wiki/Rule_110
001|     
001| Functions:
001|     generate_rule           - generate rule dictionary given the rule number
001|     initial_row             - ensure starting row is twice the height
001|     run_automata_rule       - run the automata for a given rule
001|     make_automata_bitmap    - make a PNG image of the automata output
001| 
001| Commands:
001|     list    do_list_rule        - list the conditions for a given rule
001|     one     do_run_one_rule     - run automata with a given rule
001|     rand    do_one_rule_rand    - run automata with a given rule and random start row
001|     all     do_run_all_rules    - run automata with all 256 rules
001| 
001| '''

002| ####################################################################################################
003| from sys import argv, stdout, exc_info
004| from traceback import extract_tb
005| from os import path
006| from random import random
007| from PIL import Image, ImageDraw, ImageFont
008| from logger import logger,info,debug,trace
009| from goodies import KWARG
010| ####################################################################################################
011| BasePath = r'C:\CJS\prj\Python\app\life'
012| ImgsPath = path.join(BasePath, 'img')
013| DataPath = path.join(BasePath, 'dat')
014| Log = logger('automata')
015| 
016| CMND = ''
017| ARGS = {
018|     #'rule': '110',
019|     #'size': '100',
020|     #'edge': '0',
021|     #'rpct': '0.25',
022|     #'dname': 'automata_%s.out',
023|     #'dpath': BasePath,
024|     #'iname': 'automata_%s.png',
025|     #'ipath': BasePath,
026| }
027| 
028| 
029| ##================================================================================================##
030| def generate_rule (rule=110):
031|     '''\
031| Generate a rule dictionary from a number.
031| 
031| Arguments:
031|     rule    rule number (from 0 to 255)
031| 
031| Returns:
031|     dictionary of the eight rule conditions
031|     
031| '''

032|     assert 0 <= rule <= 255, ValueError(f'Invalid rule number: {rule}')
033| 
034|     # Convert number to an eight-bit string...
035|     sbits = f'{rule:08b}'
036| 
037|     # Convert bits string to a list of zeros and ones...
038|     bits = [1 if b=='1' else 0 for b in sbits]
039| 
040|     # Generate and return the rule dictionary...
041|     return {f'{bx:03b}':b for bx,b in enumerate(reversed(bits))}
042| 
043| ##================================================================================================##
044| def initial_row (size:int, start:list) -> list:
045|     '''\
045| Create an initial row that's as wide as the number of iterations.
045| Place the starting pattern in the center of the row.
045| 
045| Arguments:
045|     size    -number of rows requested
045|     start   -starting pattern
045| 
045| Returns:
045|     the row
045| 
045| '''

046|     Log.debug(f'initial_row({size}, {start})')
047|     need = size * 2
048| 
049|     # If the starting row's length is long enough, use it as is...
050|     if need <= len(start):
051|         return list(start)
052| 
053|     # Calculate amount of padding needed...
054|     padding = (need - len(start)) // 2
055|     Log.debug(f'padding required: {padding}')
056| 
057|     row = ([0]*padding) + start + ([0]*padding)
058| 
059|     # Compensate for round-off...
060|     while len(row) < need:
061|         row.append(0)
062|         Log.debug(f'adding a blank')
063|     Log.debug()
064| 
065|     # Return the row...
066|     return row
067| 
068| ##================================================================================================##
069| def run_automata_rule (rule=110, size=200, start=[1], fname='automata_%s.out', fpath=DataPath):
070|     '''\
070| Elementary cellular automata (per almost every CS course ever).
070| See: https://en.wikipedia.org/wiki/Elementary_cellular_automaton
070| 
070| Arguments:
070|     rule    rule number, from 0 to 255
070|     size    number of iterations
070|     start   the initial row, typically just [1]
070|     fname   filename for the text output (use None to use stdout)
070|     fpath   filepath or None if fname is a full path/filename
070| 
070| Returns:
070|     list of size+1 generated rows (includes initial row)
070| 
070| '''

071|     Log.info(f'Run automata with rule {rule} ({size} rows)')
072|     Log.info()
073|     make_key = lambda xs: ''.join(str(x) for x in xs)
074| 
075|     # Create the initial row...
076|     row = initial_row(size, start)
077|     Log.trace(f'Initial row: {"".join(str(x) for x in row)}')
078|     Log.trace()
079| 
080|     # Generated rows appended to this list...
081|     rows = [row]
082| 
083|     # Get the rule for this run...
084|     current_rule = generate_rule(rule)
085| 
086|     # Iterations of rule...
087|     for rx in range(size):
088|         # Create new row of all blanks...
089|         new_row = [0]*len(row)
090| 
091|         # For each triplet in the current row...
092|         for ix in range(len(row)):
093| 
094|             # Convert the triplet to a key...
095|             if ix == 0:
096|                 # Edge case: first triplet extends beyond start of row...
097|                 key = make_key(row[0:1] + row[0:2])
098|             elif ix == len(row)-1:
099|                 # Edge case: last triplet extends beyond end of row...
100|                 key = make_key(row[ix-1:ix+1] + row[ix:ix+1])
101|             else:
102|                 # The usual case...
103|                 key = make_key(row[ix-1:ix+2])
104| 
105|             # Get the value per the rule...
106|             val = current_rule[key]
107| 
108|             # And put it in the new row...
109|             new_row[ix] = val
110| 
111|         # Make the new row the current row...
112|         row = new_row
113| 
114|         # Append the (new) row to the output list...
115|         rows.append(row)
116| 
117|     # We'll default to the display...
118|     sout = stdout
119|     # But if a filename is supplied, open a file...
120|     if fname:
121|         # Include the rule ID in the filename (optional)...
122|         if '%s' in fname:
123|             fname = fname % f'{rule:03d}'
124| 
125|         filename = path.join(fpath,fname) if fpath else fname
126|         sout = open(filename, mode='w', encoding='utf8')
127| 
128|     # For the display, convert 0s and 1s to something printable...
129|     output = [''.join('#' if c else ' ' for c in row) for row in rows]
130| 
131|     # Display (or write to file) the output...
132|     try:
133|         for line in output:
134|             print(line, file=sout)
135| 
136|     except:
137|         raise
138| 
139|     finally:
140|         if fname:
141|             sout.close()
142|             Log.info(f'wrote: {filename}')
143|             Log.info()
144| 
145|     # Return the list of generated rows...
146|     return rows
147| 
148| ##------------------------------------------------------------------------------------------------##
149| ImageBackground = (255,255,255)
150| ImageForeground = (0,0,0)
151| 
152| NumberImage = False
153| NumberSize  = 18
154| NumberColor = (255,0,0)
155| NumberFont  = 'arialbd.ttf'
156| 
157| ##================================================================================================##
158| def make_automata_bitmap (rule, rows, margin=10, fname='automata_%s.png', fpath=ImgsPath):
159|     '''\
159| Generate a PNG file from the automata output.
159| 
159| Arguments:
159|     rows    output from the automata
159|     rule    the rule number (for the filename)
159|     fname   filename for the image file (required)
159|     fpath   filepath or None if fname is a full path/filename
159| 
159| Returns:
159|     nothing (None)
159| 
159| '''

160|     bg_color = ImageBackground      # background (nominally white)
161|     fg_color = ImageForeground      # cells (nominally black)
162| 
163|     # Image width is the longest row plus margins...
164|     width = len(rows[-1]) + (2 * margin)
165|     # Image height is the number of rows plus margins...
166|     height = len(rows) + (2 * margin)
167| 
168|     # Create a new image...
169|     img = Image.new('RGB', size=(width,height), color=bg_color)
170|     # And a drawing object...
171|     draw = ImageDraw.Draw(img)
172| 
173|     # For each row of output...
174|     for rx,row in enumerate(rows):
175| 
176|         # For each cell in the row...
177|         for cx,cell in enumerate(row):
178|             # Draw one pixel if cell is nonblank...
179|             if cell:
180|                 px = cx + margin
181|                 py = rx + margin
182|                 draw.point((px, py), fill=fg_color)
183| 
184|     # Place rule number in upper-left corner (optional)...
185|     if NumberImage:
186|         fnt = ImageFont.truetype(NumberFont, size=NumberSize)
187|         draw.text((0,0), str(rule), font=fnt, fill=NumberColor)
188| 
189|     # Include the rule ID in the filename (optional)...
190|     if '%s' in fname:
191|         fname = fname % f'{rule:03d}'
192| 
193|     # We want a complete filename for the image...
194|     filename = path.join(fpath,fname) if fpath else fname
195| 
196|     # Save the image...
197|     img.save(filename)
198|     Log.info(f'wrote: {filename}')
199|     Log.info()
200| 
201| 
202| ##================================================================================================##
203| def do_run_all_rules (**kwargs):
204|     """CMND: Run the automata with all 250 rules."""
205|     dpath = KWARG('dpath', DataPath, str, kwargs)
206|     dname = KWARG('dname', 'automata_%s.out', str, kwargs)
207|     ipath = KWARG('ipath', ImgsPath, str, kwargs)
208|     iname = KWARG('iname', 'automata_%s.png', str, kwargs)
209|     size  = KWARG('size' , 250, int, kwargs)
210|     edge  = KWARG('edge' , 10, int, kwargs)
211|     Log.info('run-rule:: %s' % str(list(kwargs.keys())))
212|     Log.debug(f'{dpath=}')
213|     Log.debug(f'{dname=}')
214|     Log.debug(f'{ipath=}')
215|     Log.debug(f'{iname=}')
216|     Log.debug(f'{size=}')
217|     Log.debug(f'{edge=}')
218|     Log.info()
219| 
220|     # For all possible rules...
221|     for rule in range(0,256):
222|         print(f'Rule: {rule} ({rule:08b})')
223| 
224|         # Run the automata...
225|         rows = run_automata_rule(rule=rule, size=size, fname=dname, fpath=dpath)
226| 
227|         # Make a bitmap...
228|         make_automata_bitmap(rule, rows, margin=edge, fname=iname, fpath=ipath)
229| 
230|     Log.info()
231|     return 'Done'
232| 
233| ##================================================================================================##
234| def do_run_one_rule (**kwargs):
235|     """CMND: Run the automata with a given rule."""
236|     dpath = KWARG('dpath', DataPath, str, kwargs)
237|     dname = KWARG('dname', 'automata_%s.out', str, kwargs)
238|     ipath = KWARG('ipath', ImgsPath, str, kwargs)
239|     iname = KWARG('iname', 'automata_%s.png', str, kwargs)
240|     rule  = KWARG('rule' , 110, int, kwargs)                    # rule to run
241|     size  = KWARG('size' , 250, int, kwargs)                    # times to iterate
242|     edge  = KWARG('edge' , 10, int, kwargs)
243|     inits = KWARG('inits', '1', str, kwargs)                    # initial row
244|     Log.info('run-rule:: %s' % str(list(kwargs.keys())))
245|     Log.debug(f'{dpath=}')
246|     Log.debug(f'{dname=}')
247|     Log.debug(f'{ipath=}')
248|     Log.debug(f'{iname=}')
249|     Log.debug(f'{rule=}')
250|     Log.debug(f'{size=}')
251|     Log.debug(f'{edge=}')
252|     Log.debug(f'{inits=}')
253|     Log.info()
254| 
255|     # Convert initialization string ("10101") to a list of bits...
256|     start = [1 if x=='1' else 0 for x in inits]
257|     Log.debug(f'{start=}')
258| 
259|     # Run the automata...
260|     rows = run_automata_rule(rule=rule, size=size, start=start, fname=dname, fpath=dpath)
261| 
262|     # Make a bitmap...
263|     make_automata_bitmap(rule, rows, margin=edge, fname=iname, fpath=ipath)
264| 
265|     Log.info()
266|     return 'Done'
267| 
268| ##================================================================================================##
269| def do_one_rule_rand (**kwargs):
270|     """CMND: Run the automata with a given rule and random starting row."""
271|     dpath = KWARG('dpath', DataPath, str, kwargs)
272|     dname = KWARG('dname', 'automata_%s.out', str, kwargs)
273|     ipath = KWARG('ipath', ImgsPath, str, kwargs)
274|     iname = KWARG('iname', 'automata_%s.png', str, kwargs)
275|     rule  = KWARG('rule' , 110, int, kwargs)                    # rule to run
276|     size  = KWARG('size' , 250, int, kwargs)                    # times to iterate
277|     edge  = KWARG('edge' , 10, int, kwargs)
278|     rpct  = KWARG('rpct' , 0.333, float, kwargs)              # % of nonblanks
279|     Log.info('run-rule-random-start:: %s' % str(list(kwargs.keys())))
280|     Log.debug(f'{dpath=}')
281|     Log.debug(f'{dname=}')
282|     Log.debug(f'{ipath=}')
283|     Log.debug(f'{iname=}')
284|     Log.debug(f'{rule=}')
285|     Log.debug(f'{size=}')
286|     Log.debug(f'{edge=}')
287|     Log.debug(f'{rpct=}')
288|     Log.info()
289| 
290|     # Generate a random starting row...
291|     start = [1 if random() < rpct else 0 for ix in range(size*2)]
292|     Log.debug(f'{start=}')
293| 
294|     # Run the automata...
295|     rows = run_automata_rule(rule=rule, size=size, start=start, fname=dname, fpath=dpath)
296| 
297|     # Make a bitmap...
298|     make_automata_bitmap(rule, rows, margin=edge, fname=iname, fpath=ipath)
299| 
300|     Log.info()
301|     return 'Done'
302| 
303| ##================================================================================================##
304| def do_list_rule (**kwargs):
305|     """CMND: List a given rule's conditions."""
306|     fpath = KWARG('fpath', BasePath, str, kwargs)
307|     fname = KWARG('fname', 'rule.out', str, kwargs)
308|     rule  = KWARG('rule' , 110, int, kwargs)                    # rule to run
309|     Log.info('list-rule:: %s' % str(list(kwargs.keys())))
310|     Log.debug(f'{fpath=}')
311|     Log.debug(f'{fname=}')
312|     Log.debug(f'{rule=}')
313|     Log.info()
314| 
315|     current_rule = generate_rule(rule)
316|     for ix,key in enumerate(current_rule):
317|         Log.info(f'{ix} [{key}]: {current_rule[key]}')
318| 
319|     Log.info()
320|     return 'Done'
321| 
322| ##================================================================================================##
323| def do_test (**kwargs):
324|     """CMND: Do a test."""
325|     fpath = KWARG('fpath', BasePath, str, kwargs)
326|     fname = KWARG('fname', 'test.out', str, kwargs)
327|     dpath = KWARG('dpath', DataPath, str, kwargs)
328|     dname = KWARG('dname', 'automata_%s.out', str, kwargs)
329|     ipath = KWARG('ipath', ImgsPath, str, kwargs)
330|     iname = KWARG('iname', 'automata_%s.png', str, kwargs)
331|     Log.info('test:: %s' % str(list(kwargs.keys())))
332|     Log.debug(f'{fpath=}')
333|     Log.debug(f'{fname=}')
334|     Log.debug(f'{dpath=}')
335|     Log.debug(f'{dname=}')
336|     Log.debug(f'{ipath=}')
337|     Log.debug(f'{iname=}')
338|     Log.info()
339|     #
340|     Log.info()
341|     return 'Done'
342| ####################################################################################################
343| def dispatch (cmd, **kwargs):
344|     """Dispatch to a module function based on CMD."""
345|     Log.info(f'CMD: {cmd}')
346|     for kw in kwargs:
347|         Log.debug(f'argument[{kw}]: {kwargs[kw]}')
348|     Log.info()
349|     if cmd == 'all': return do_run_all_rules(**kwargs)
350|     if cmd == 'one': return do_run_one_rule(**kwargs)
351|     if cmd == 'rand': return do_one_rule_rand(**kwargs)
352|     if cmd == 'list': return do_list_rule(**kwargs)
353|     if cmd == 'test': return do_test(**kwargs)
354|     return 'Nothing to do!'
355| ####################################################################################################
356| if __name__ == '__main__':
357|     print('autorun: %s' % argv[0])
358|     Log.start(path.join(BasePath,'automata.log'))
359|     #Log.start(path.join(BasePath,LogFilenameTimestamp('automata_%s.log')))
360|     Log.level(debug())
361|     Log.info(argv[0])
362|     Log.info()
363|     cmd = argv[1] if 1 < len(argv) else CMND
364|     kwargs = ARGS
365|     for a in argv[2:]:
366|         nv = a.split('=', 1)
367|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
368|         Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
369|     try:
370|         print(f'CMD: {cmd}')
371|         print()
372|         obj = dispatch(cmd, **kwargs)
373|         print()
374|         print(obj)
375|         Log.info()
376|         Log.info(obj)
377|     except:
378|         etype, evalue, tb = exc_info()
379|         ts = extract_tb(tb)
380|         Log.error()
381|         Log.error('%s: %s' % (etype.__name__,str(evalue)))
382|         Log.error()
383|         for t in ts[-5:]:
384|             Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
385|             Log.error(' %s' % t[3])
386|             Log.error()
387|         raise
388|     finally:
389|         Log.end()
390| ####################################################################################################
391| '''eof'''
392|