utm.html
001| '''Universal Turing Machine (software model).
001|
001| Classes:
001| TuringTape (blank)
001| TuringMachine (pgm, max, blank, start)
001|
001| Functions:
001| compile_tm_statements (statements)
001|
001| Commands:
001| TM do_turing_machine - Run TM using prgm.in
001| pgms do_list_programs - List all the built-in programs
001| list do_program_listing - List a given built-in program
001| test do_test - Run TM with built-in program
001|
001| TODO: Generate diagrammed output. Need to modify TuringMachine.run method.
001| '''
002|
003| from sys import argv, stdout, exc_info
004| from traceback import extract_tb
005| from os import path
006| from logger import logger,info,debug,trace, LogFilenameTimestamp
007| from goodies import KWARG, typename
008| from files import linefile
009|
010| BasePath = r'C:\CJS\prj\Python\app\sims\utm'
011| Log = logger('UTM')
012|
013| CMND = ''
014| ARGS = {
015|
016|
017|
018|
019| 'fpath': BasePath,
020| }
021|
022| X_TH = (-1,0)
023| X_TT = (-2,0)
024| X_TX = (-3,0)
025|
026| ErrVar = lambda var:(var,typename(var))
027|
028|
029| '''Dictionary of built-in Turing programs for TuringMachine instances.
029| Programs are keyed by their names. (The 'pgms' command lists these names.)
029| '''
030| Programs = {
031| 'nop': {
032| (0,0):(0, +1, 0),
033| },
034| 'oop': {
035| (0,0):(1, +1, 0),
036| },
037| 'jitter': {
038| (0,0):(1, +1, 1),
039| (0,1):(0, +1, 1),
040| (1,0):(1, -1, 0),
041| (1,1):(0, -1, 0),
042| },
043| '1020': {
044| (0,0):(1, +1, 1),
045| (1,0):(0, +1, 2),
046| (2,0):(2, +1, 3),
047| (3,0):(0, +1, 0),
048| },
049| 'BB': {
050| (0,0):(1, +1, 1),
051| (0,1):(1, -1, 2),
052| (1,0):(1, -1, 0),
053| (1,1):(1, +1, 1),
054| (2,0):(1, -1, 1),
055| (2,1):(1, 0,-1),
056| },
057| 'five': {
058| (0,0):(0, +1, 1),
059| (1,0):(1, -1, 2),
060| (1,1):(1, -1, 2),
061| (2,0):(0, -1, 3),
062| (3,0):(1, +1, 4),
063| (3,1):(1, +1, 4),
064| (4,0):(0, +1, 1),
065| },
066| 'tri': {
067| (0,0):(1, +1, 1),
068| (1,0):(1, -1, 2),
069| (1,1):(1, +1, 1),
070| (2,0):(1, +1, 1),
071| (2,1):(1, -1, 2),
072| },
073| 'exp': {
074| (0,0):(1, +1, 1),
075| (1,0):(0, +1, 2),
076| (2,0):(1, -1, 3),
077| (3,0):(0, -1, 3),
078| (3,1):(0, -1, 4),
079| (4,0):(1, +1, 5),
080| (5,0):(0, +1, 5),
081| (5,1):(0, +1, 6),
082| (6,0):(1, -1, 3),
083| },
084| 'exp/r': {
085| (0,0):(1, -1, 1),
086| (1,0):(0, -1, 2),
087| (2,0):(1, +1, 3),
088| (3,0):(0, +1, 3),
089| (3,1):(0, +1, 4),
090| (4,0):(1, -1, 5),
091| (5,0):(0, -1, 5),
092| (5,1):(1, +1, 3),
093| },
094| 'exp/l': {
095| (0,0):(1, +1, 1),
096| (1,0):(0, +1, 2),
097| (2,0):(1, -1, 3),
098| (3,0):(0, -1, 3),
099| (3,1):(0, -1, 4),
100| (4,0):(1, +1, 5),
101| (5,0):(0, +1, 5),
102| (5,1):(1, -1, 3),
103| },
104| }
105|
106|
107|
108| class TuringTape (object):
109| '''"Infinite" Tape for the Turing Machine.
109|
109| The "Tape" is a dictionary with integer keys that index "cells" on the Tape.
109| The cell indexes need not be contiguous; the Tape creates new cells as needed.
109| Each cell has a value and a counter of times written. Each new cell starts
109| with a configurable "blank" value, by default zero.
109| '''
110|
111| def __init__ (self, blank=0, head=None, tape=None, tx=None):
112| '''Initialize a new Tape instance.
112|
112| Arguments (all optional):
112| blank - value to use for new cells (default 0)
112| head - initial index for the Tape head (default 0)
112| tape - list of initial cell values (default none)
112| tx - index of the first initialize cell (default 0)
112| '''
113| self.blank = blank
114| self.initial = (tape, tx, head)
115| self.reset()
116|
117| def reset (self):
118| '''Reset the Tape to starting condition (incl. initialized cells).'''
119| self.tape = {0:[self.blank, 0]}
120| self.head = 0
121|
122| if self.initial[0]:
123| if self.initial[1]:
124|
125| tx = self.initial[1]
126| self.tape = {ix+tx:[n,0] for ix,n in enumerate(self.initial[0])}
127| else:
128|
129| self.tape = {ix:[n,0] for ix,n in enumerate(self.initial[0])}
130|
131| if self.initial[2]:
132| self.head = self.initial[2]
133|
134| if self.head not in self.tape:
135| self.tape[self.head] = [self.blank, 0]
136|
137| @property
138| def curr (self):
139| '''Value of current cell (head doesn't move).'''
140|
141| if self.head not in self.tape:
142| self.tape[self.head] = [self.blank, 0]
143|
144| return self.tape[self.head][0]
145|
146| @property
147| def left (self):
148| '''Left-most index of the Tape.'''
149| return min(self.tape.keys())
150|
151| @property
152| def right (self):
153| '''Right-most index of the Tape.'''
154| return max(self.tape.keys())
155|
156| @property
157| def keys (self):
158| '''List of Tape indexes (sorted; may not be contiguous).'''
159| return list(sorted(self.tape.keys()))
160|
161| @property
162| def items (self):
163| '''List of Tape Cells (sorted by index; may not be contiguous).'''
164| return [(ix,*self[ix]) for ix in self.keys]
165|
166| @property
167| def values (self):
168| '''List of Tape Values (sorted by index; may not be contiguous).'''
169| return [self[ix][0] for ix in self.keys]
170|
171| @property
172| def counts (self):
173| '''List of Tape Counts (sorted by index; may not be contiguous).'''
174| return [self[ix][1] for ix in self.keys]
175|
176| def __call__ (self, cell_value, move_to):
177| '''Write to the tape and move the head -1, 0, or +1.'''
178| assert isinstance(cell_value, int), ValueError('Cell value must be an integer. (%s:%s)' % ErrVar(cell_value))
179| assert isinstance(move_to, int), ValueError('Move-To value must be an integer. (%s:%s)' % ErrVar(move_to))
180| assert (-1 <= move_to <= +1)
181| Log.trace('tape(%d,%d)' % (cell_value,move_to))
182|
183| self.tape[self.head][0] = cell_value
184| self.tape[self.head][1] += 1
185|
186| if 0 < move_to:
187| self.head += 1
188|
189| if self.head not in self.tape:
190| self.tape[self.head] = [self.blank,0]
191| return
192|
193| if move_to < 0:
194| self.head -= 1
195|
196| if self.head not in self.tape:
197| self.tape[self.head] = [self.blank,0]
198| return
199|
200| return
201|
202| def __iter__ (self):
203| '''Return an iterator of Tape indexes. Indexes may not be contiguous.'''
204| return iter(sorted(self.tape.keys()))
205|
206| def __len__ (self):
207| '''Return (virtual!) length of Tape.'''
208| return ((self.right - self.left) + 1)
209|
210| def __getitem__ (self, tape_index):
211| '''Get (existing) Cell value.'''
212| assert isinstance(tape_index, int), ValueError('Tape index must be an integer. (%s:%s)' % ErrVar(tape_index))
213| assert tape_index in self.tape, ValueError('Invalid Tape index: No cell. (%d)' % tape_index)
214| return self.tape[tape_index]
215|
216| def __setitem__ (self, tape_index, cell_value):
217| '''Set Cell value. Create Cell if it doesn't exist.'''
218| assert isinstance(tape_index, int), ValueError('Tape index must be an integer. (%s:%s)' % ErrVar(tape_index))
219| assert isinstance(cell_value, int), ValueError('Cell value must be an integer. (%s:%s)' % ErrVar(cell_value))
220| if tape_index in self.tape:
221| self.tape[tape_index][0] = cell_value
222| self.tape[tape_index][1] += 1
223| else:
224| self.tape[tape_index] = [self.blank,1]
225|
226| def __delitem__ (self, tape_index):
227| '''Delete (existing) Cell. Actually: KEEP Cell, but set to blank.'''
228| assert isinstance(tape_index, int), ValueError('Tape index must be an integer. (%s:%s)' % ErrVar(tape_index))
229| assert tape_index in self.tape, ValueError('Invalid Tape index: No cell. (%d)' % tape_index)
230| self.tape[tape_index] = [self.blank,0]
231|
232| def __str__ (self):
233| return ' '.join([str(self.tape[k][0]) for k in sorted(self.tape)])
234|
235| def __repr__ (self):
236| vs = ','.join(['%d' % v for v in self.values])
237| ks = ','.join(['%+d' % k for k in self.keys])
238| t = (typename(self), self.left, self.right, self.head, vs, ks)
239| s = '{%s:{left:%d, right:%d, head:%d, tape:[%s], indexes:[%s]}}'
240| return s % t
241|
242|
243| class TuringMachine (object):
244| '''Universal Turing Machine. (v2)
244|
244| Executes a Turing program using a TuringTape instance. The program is a
244| dictionary of 3-ples indexed by 2-ples (in both cases, tuple instances).
244|
244| The entry key is a 2-ple (state, value) that indexes a program state and
244| value (of the Tape). The entry is selected when in the indexed state plus
244| the current Tape value matches the indexed value.
244|
244| Each entry is a 3-ple (value, move, next) that specifies what new value to
244| write to the current Tape cell; whether to move left, right, or stay (the
244| last one is rare); and what the next state is.
244|
244| States and cell values can be any integer, but the Machine treats any
244| negative state as a HALT state.
244|
244| Three special indexes: (-1,0), (-2,0), (-3,0). These allow setting the
244| TuringTape head, tape, and tx parameters, respectively.
244| '''
245| def __init__ (self, program, max_steps=32, blank=0, start_state=0):
246| '''Initialize a new Turing Machine instance.
246|
246| Contains an instance of TuringTape.
246|
246| Arguments (most optional):
246| program - the Turing program to run
246| max_steps - limits how long the Machine can run (default 32 steps)
246| blank - default blank value for Tape (default 0)
246| start_state - initial program state (default 0)
246|
246| (Use the special program keys to set Tape Head and initial Tape.)
246| '''
247| self.program = program
248| self.max_steps = max_steps
249| self.blank = blank
250| self.state = start_state
251| self.watchdog = 1
252| th = None
253| tt = None
254| tx = None
255|
256| if X_TH in program:
257|
258| th = program[X_TH]
259| del program[X_TH]
260| if X_TT in program:
261|
262| tt = program[X_TT]
263| del program[X_TT]
264| if X_TX in program:
265|
266| tx = program[X_TX]
267| del program[X_TX]
268| self.tape = TuringTape(blank=blank, head=th, tape=tt, tx=tx)
269|
270| def reset (self):
271| '''Reset machine to initial state.'''
272| self.state = 0
273| self.watchdog = 1
274| self.tape.reset()
275|
276| def run (self):
277| '''Run the machine! (Until max-steps or a negative state)'''
278|
279| while 0 <= self.state:
280|
281| pkey = (self.state, self.tape.curr)
282| if pkey not in self.program:
283| raise RuntimeError('Illegal state! state=%s, tape=%s' % pkey)
284| valu,move,goto = self.program[pkey]
285|
286| s1 = ('<' if move<0 else ('>' if 0<move else '-'))
287| s2 = ('HALT' if goto<0 else ('%02d' % goto))
288| tt = self.tape
289| t = (self.watchdog, pkey[0],pkey[1], valu,s1, s2, tt.left,tt,tt.right)
290| s = '%3d: [%02d](%d) {%d,%s} [%s] %+d|%s|%+d'
291| Log.info(s % t)
292|
293| self.tape(valu, move)
294| self.state = goto
295| self.watchdog += 1
296| if self.max_steps < self.watchdog:
297| break
298| Log.info()
299|
300|
301| final = 'HALT' if self.state < 0 else ('S%d' % self.state)
302| th = self.tape.head
303| nc = len(self.tape)
304| lt = self.tape.left
305| cells = str(self.tape)
306| rt = self.tape.right
307| prn = '%s @ %d (%d) [%+d|%s|%+d]' % (final,th, nc, lt,cells,rt)
308| print(prn)
309| print()
310| Log.info(prn)
311| Log.info()
312|
313| return self.state
314|
315| def dump (self, stream=stdout):
316| '''Dump the Tape to a stream.'''
317| for cell in self.tape:
318| val,cnt = self.tape[cell]
319| prn = '%+3d: %d (%3d)' % (cell, val, cnt)
320| print(prn, file=stream)
321| Log.info(prn)
322| print(file=stream)
323| Log.info()
324|
325| def __str__ (self):
326| return 'Turing Machine (v2)'
327|
328| def __repr__ (self):
329| t = (typename(self), self.state, self.watchdog, self.max_steps)
330| s = '{%s:{state:%d, wdog:%d, max:%d}}'
331| return s%t
332|
333| def _find_pgm_entry (self):
334| for pe in self.program:
335| if (pe.name==self.state) and (pe.curr==self.tape.curr):
336| return pe
337| raise KeyError('No Program Entry!')
338|
339|
340| def compile_tm_statements (statements):
341| '''\
341| Compile a list of text TM statements for a program.
341|
341| Format:
341| ; Turing Machine Program
341| ; (comments begin with a semicolon)
341|
341| ; [optional] Initial Tape Values
341| [1 1 1 1 0 1 1 1 0 1 1 0 0 0]
341|
341| ; [optional] Inital Head Index
341| ; (negative values indexes from end)
341| @-1
341|
341| ; Statements...
341| ; Format:
341| ; state,curr: cell, move, goto
341| ;
341| 0,0: 1 +1 1 ; start
341| 1,0: 1 +1 2
341|
341| '''
342| def compile_tm_stmt (txt):
343| Log.trace('statement: "%s"' % txt)
344| ss = txt.replace(',', ' ').replace(':',' ').split()
345| tt = [int(n) for n in ss]
346| assert len(tt)==5, ValueError('Invalid statement: "%s""' % txt)
347| return (tuple(tt[0:2]), tuple(tt[2:]))
348|
349| prgm = {}
350| for stmt in statements:
351| s = stmt.strip()
352| if s == '':
353| continue
354| if s.startswith(';'):
355| continue
356| if ';' in s:
357| s = s[0:s.index(';')].strip()
358| if s.startswith('[') and s.endswith(']'):
359| s = s[1:-1].replace(',', ' ')
360| if ':' in s:
361| cp = s.index(':')
362| tx = int(s[0:cp].rstrip())
363| s = s[cp+1:]
364| prgm[X_TX] = tx
365| ss = s.split()
366| tt = [int(n) for n in ss]
367| prgm[X_TT] = tt
368| continue
369| if s.startswith('@'):
370| th = int(s[1:].strip())
371| prgm[X_TH] = th
372| continue
373| k,b = compile_tm_stmt(s)
374| prgm[k] = b
375|
376| Log.debug('Compiled Program:')
377| Log.debug('=================')
378| for k in sorted(prgm):
379| Log.debug('%s: %s' % (k,prgm[k]))
380| Log.debug()
381| return prgm
382|
383|
384|
385| def do_turing_machine (**kwargs):
386| """CMND: Create a TuringMachine instance and run a program from a file."""
387| fpath = KWARG('fpath', BasePath, str, kwargs)
388| fname = KWARG('fname', 'program.in', str, kwargs)
389| limit = KWARG('max', 32, int, kwargs)
390| start = KWARG('start', 0, int, kwargs)
391| blank = KWARG('zero', 0, int, kwargs)
392| Log.info('test:: %s' % str(list(kwargs.keys())))
393| Log.debug('fpath="%s"' % fpath)
394| Log.debug('fname="%s"' % fname)
395| Log.debug('limit=%d' % limit)
396| Log.debug('start=%d' % start)
397| Log.debug('blank=(%s)' % blank)
398| Log.info()
399|
400| fn = path.join(fpath, fname) if fpath else fname
401| fo = linefile(fn)
402| fo.load()
403|
404| program = compile_tm_statements(fo.data)
405|
406| tm = TuringMachine(program, max_steps=limit, blank=blank, start_state=start)
407| tm.run()
408| tm.dump()
409|
410| Log.info()
411| return 'Done'
412|
413|
414| def do_list_programs (**kwargs):
415| """CMND: List all the built-in programs."""
416| fpath = KWARG('fpath', BasePath, str, kwargs)
417| fname = KWARG('fname', 'programs.list', str, kwargs)
418| Log.info('list-programs:: %s' % str(list(kwargs.keys())))
419| Log.debug('fpath="%s"' % fpath)
420| Log.debug('fname="%s"' % fname)
421| Log.info()
422| print()
423|
424| for pname in sorted(Programs):
425| prn = '%-16s (%d rows)' % (pname, len(Programs[pname]))
426| print(prn)
427| Log.info(prn)
428|
429| print()
430| Log.info()
431| return 'Done'
432|
433|
434| def do_program_listing (**kwargs):
435| """CMND: List a built-in program."""
436| fpath = KWARG('fpath', BasePath, str, kwargs)
437| fname = KWARG('fname', 'programs.list', str, kwargs)
438| pname = KWARG('pgm', '1', str, kwargs)
439| Log.info('program-listing:: %s' % str(list(kwargs.keys())))
440| Log.debug('fpath="%s"' % fpath)
441| Log.debug('fname="%s"' % fname)
442| Log.info()
443| print()
444|
445| pgm = Programs[pname]
446|
447| for k in sorted(pgm):
448| prn = '%2d (%d) [%d %+d %2d]' % (*k, *pgm[k])
449| print(prn)
450| Log.info(prn)
451|
452| print()
453| Log.info()
454| return 'Done'
455|
456|
457| def do_test (**kwargs):
458| """CMND: Do a test."""
459| fpath = KWARG('fpath', BasePath, str, kwargs)
460| fname = KWARG('fname', 'test.out', str, kwargs)
461| pname = KWARG('pgm', '1', str, kwargs)
462| limit = KWARG('max', 32, int, kwargs)
463| start = KWARG('start', 0, int, kwargs)
464| blank = KWARG('zero', 0, int, kwargs)
465| Log.info('test:: %s' % str(list(kwargs.keys())))
466| Log.debug('fpath="%s"' % fpath)
467| Log.debug('fname="%s"' % fname)
468| Log.debug('pname="%s"' % pname)
469| Log.debug('limit=%d' % limit)
470| Log.debug('start=%d' % start)
471| Log.debug('blank=(%s)' % blank)
472| Log.info()
473|
474| pgm = Programs[pname]
475|
476| tm = TuringMachine(pgm, max_steps=limit, blank=blank, start_state=start)
477| tm.run()
478| tm.dump()
479|
480| Log.info()
481| return 'Done'
482|
483| def dispatch (cmd, **kwargs):
484| """Dispatch to a module function based on CMD."""
485| Log.info('CMD: %s' % cmd)
486| for kw in kwargs:
487| Log.debug('argument[%s]: %s' % (kw,kwargs[kw]))
488| Log.info()
489| if cmd == 'TM': return do_turing_machine(**kwargs)
490| if cmd == 'list': return do_program_listing(**kwargs)
491| if cmd == 'pgms': return do_list_programs(**kwargs)
492| if cmd == 'test': return do_test(**kwargs)
493| return 'Nothing to do!'
494|
495| if __name__ == '__main__':
496| print('autorun: %s' % argv[0])
497|
498| Log.start(path.join(BasePath,'utm.log'))
499| Log.level(info())
500| Log.info(argv[0])
501| Log.info()
502| cmd = argv[1] if 1 < len(argv) else CMND
503| kwargs = ARGS
504| for a in argv[2:]:
505| nv = a.split('=', 1)
506| kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
507| Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
508| try:
509| print('CMD: %s' % cmd)
510| print()
511| obj = dispatch(cmd, **kwargs)
512| print()
513| print(obj)
514| Log.info()
515| Log.info(obj)
516| except:
517| etype, evalue, tb = exc_info()
518| ts = extract_tb(tb)
519| Log.error()
520| Log.error('%s: %s' % (etype.__name__,str(evalue)))
521| Log.error()
522| for t in ts[-5:]:
523| Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
524| Log.error(' %s' % t[3])
525| Log.error()
526| raise
527| finally:
528| Log.end()
529|
530| '''eof'''
531|