@tesserax.html


001| """Tesserax diagrams.
001| 
001| Package:
001|     https://apiad.github.io/tesserax/
001| 
001| pip;
001|     py -m pip install tesserax
001|     py -m pip install --upgrade tesserax
001| 
001| Commands:
001|     xb:d1       do_subscriber_picks_up_phone        ~diagram 1
001|     chess       do_chessboard                       ~draw a chessboard
001|     test        do_test                             ~test
001| 
001| """

002| ####################################################################################################
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path
006| import tesserax as tess
007| import tesserax.layout as lay
008| from logger import logger,info,debug,trace
009| from goodies import KWARG, typename, makefilename
010| ####################################################################################################
011| BasePath = r'C:\CJS\prj\Python\ws\tess'
012| Log = logger('Tesserax')
013| 
014| CMND = 'chess'
015| ARGS = {
016|     'name': 'tess',
017|     'rows': '10',
018|     'cols': '10',
019|     #'fname': 'app.dat',
020|     #'fpath': BasePath,
021| }
022| 
023| ##------------------------------------------------------------------------------------------------##
024| RowGap = 100            # width between process columns
025| ColGap =  20            # width between shapes in column
026| Margin =  30            # space around diagram
027| 
028| BoxWidth  = 100         # width of a process node
029| BoxHeight =  30         # height of a process node
030| 
031| FaintGhosts = True      # show the ghost nodes (or don't)
032| 
033| ##------------------------------------------------------------------------------------------------##
034| # Subscriber Line...
035| ProcessColumn1 = {
036|     'start':    {'$':'start'},
037|     'off-hook': {'$':'event', 'rarr':(2,'sep01')},
038|     'wait4dt':  {'$':'state', 'color':'#ff7f7f'},
039|     'sep03':    {'$':'--'},
040|     'sep04':    {'$':'--'},
041|     'sep05':    {'$':'--'},
042|     'get-pn':   {'$':'action'},
043|     'call-pn':  {'$':'event', 'rarr':(2,'sep07')},
044|     'wait4con': {'$':'state', 'color':'#ff7f7f'},
045|     'sep09':    {'$':'--'},
046|     'sep10':    {'$':'--'},
047|     'sep11':    {'$':'--'},
048|     'sep12':    {'$':'--'},
049|     'sep13':    {'$':'--'},
050|     'sep14':    {'$':'--'},
051|     'sep15':    {'$':'--'},
052|     'sep16':    {'$':'--'},
053|     'sep17':    {'$':'--'},
054|     'sep18':    {'$':'--'},
055|     'connected':{'$':'state', 'color':'#7fff7f'},
056|     'connect':  {'$':'event', 'rarr':(2,'sep20')},
057|     'talking':  {'$':'action'},
058|     'sep22':    {'$':'--'},
059|     'end':      {'$':'end'},
060| }
061| # Marker...
062| ProcessColumn2 = {
063|     'start':    {'$':'start'},
064|     'sep01':    {'$':'--'},
065|     'conn2dr':  {'$':'info'},
066|     'offhook':  {'$':'event', 'rarr':(3,'sep03')},
067|     'sep04':    {'$':'--'},
068|     'dialtone': {'$':'event', 'larr':(1,'sep05')},
069|     'sep06':    {'$':'--'},
070|     'sep07':    {'$':'--'},
071|     'call-pn':  {'$':'event', 'rarr':(3,'sep08')},
072|     'sep09':    {'$':'--'},
073|     'sep10':    {'$':'--'},
074|     'dconn-dr': {'$':'info'},
075|     'hangup':   {'$':'event', 'rarr':(3,'sep12')},
076|     'sep13':    {'$':'--'},
077|     'conn2trk': {'$':'info'},
078|     'trk-pn':   {'$':'event', 'rarr':(4,'sep15')},
079|     'sep16':    {'$':'--'},
080|     'sep17':    {'$':'--'},
081|     'connect':  {'$':'event', 'larr':(1,'sep18')},
082|     'sep19':    {'$':'--'},
083|     'sep20':    {'$':'--'},
084|     'conn-trk': {'$':'event', 'rarr':(4,'sep21')},
085|     'sep22':    {'$':'--'},
086|     'end':      {'$':'end'},
087| }
088| # Dial Register...
089| ProcessColumn3 = {
090|     'start':    {'$':'start'},
091|     'sep01':    {'$':'--'},
092|     'sep02':    {'$':'--'},
093|     'sep03':    {'$':'--'},
094|     'dialtone': {'$':'event', 'larr':(2,'sep04')},
095|     'ready':    {'$':'state', 'color':'#00ff00'},
096|     'sep06':    {'$':'--'},
097|     'sep07':    {'$':'--'},
098|     'sep08':    {'$':'--'},
099|     'decode-pn':{'$':'info'},
100|     'send-info':{'$':'event', 'larr':(2,'sep10')},
101|     'sep11':    {'$':'--'},
102|     'sep12':    {'$':'--'},
103|     'done':     {'$':'state', 'color':'#dfdfdf'},
104|     'end':      {'$':'end'},
105|     'sep15':    {'$':'--'},
106|     'sep16':    {'$':'--'},
107|     'sep17':    {'$':'--'},
108|     'sep18':    {'$':'--'},
109|     'sep19':    {'$':'--'},
110|     'sep20':    {'$':'--'},
111|     'sep21':    {'$':'--'},
112|     'sep22':    {'$':'--'},
113|     'sep23':    {'$':'--'},
114| }
115| # Trunk...
116| ProcessColumn4 = {
117|     'start':    {'$':'start'},
118|     'sep01':    {'$':'--'},
119|     'sep02':    {'$':'--'},
120|     'sep03':    {'$':'--'},
121|     'sep04':    {'$':'--'},
122|     'sep05':    {'$':'--'},
123|     'sep06':    {'$':'--'},
124|     'sep07':    {'$':'--'},
125|     'sep08':    {'$':'--'},
126|     'sep09':    {'$':'--'},
127|     'sep10':    {'$':'--'},
128|     'sep11':    {'$':'--'},
129|     'sep12':    {'$':'--'},
130|     'sep13':    {'$':'--'},
131|     'sep14':    {'$':'--'},
132|     'sep15':    {'$':'--'},
133|     'w4conn':   {'$':'action'},
134|     'connect':  {'$':'event', 'larr':(2,'sep17')},
135|     'sep18':    {'$':'--'},
136|     'sep19':    {'$':'--'},
137|     'sep20':    {'$':'--'},
138|     'sep21':    {'$':'--'},
139|     'talking':  {'$':'action'},
140|     'end':      {'$':'end'},
141| }
142| ProcessColumns = [
143|     None, ProcessColumn1, ProcessColumn2, ProcessColumn3, ProcessColumn4
144| ]
145| 
146| ##================================================================================================##
147| def create_process_column (data:dict):
148|     '''Use dictionary data to define column.'''
149| 
150|     # Use a Column Layout...
151|     with lay.Column(gap=ColGap):
152| 
153|         # Iterate through data...
154|         for item in data.values():
155| 
156|             # Create appropriate node...
157|             match item['$']:
158|                 case 'start':  item['@'] = start_node()
159|                 case 'end':    item['@'] = end_node()
160|                 case '--':     item['@'] = ghost_node()
161|                 case 'event':  item['@'] = event_node()
162|                 case 'action': item['@'] = action_node()
163|                 case 'state':  item['@'] = state_node(color=item['color'])
164|                 case 'info':   item['@'] = information_node()
165|                 case _: raise RuntimeError(f'Unexpected node type: {item["$"]}')
166| 
167| ##================================================================================================##
168| def create_process_column_down_arrows (data:dict):
169|     '''Use dictionary data to create down arrows.'''
170| 
171|     # List of Shape objects (excluding ghosts)...
172|     objs = [item['@'] for item in data.values() if item['$'] != '--']
173| 
174|     # Iterate through Shapes...
175|     obj0 = None
176|     for obj1 in objs:
177| 
178|         # If there's a Shape above us, draw an arrow...
179|         if obj0 is not None:
180|             arrow_down(obj0, obj1)
181| 
182|         # Remember this object...
183|         obj0 = obj1
184| 
185| ##================================================================================================##
186| def create_process_connection_arrows (data:dict):
187|     '''Use dictionary data to create connection arrows.'''
188| 
189|     for item in data.values():
190|         if item['$'] == 'event':
191|             obj = item['@']
192| 
193|             # Right arrow...
194|             if 'rarr' in item:
195|                 col,name = item['rarr']
196|                 other = ProcessColumns[col][name]['@']
197|                 Log.debug(f'{col=}, {name=}')
198|                 Log.debug(f'{other=}')
199|                 Log.debug()
200|                 arrow_right(obj, other)
201|                 continue
202| 
203|             # Left arrow...
204|             if 'larr' in item:
205|                 col,name = item['larr']
206|                 Log.debug(f'{col=}, {name=}')
207|                 other = ProcessColumns[col][name]['@']
208|                 Log.debug(f'{other=}')
209|                 Log.debug()
210|                 arrow_left(obj, other)
211|                 continue
212| 
213|             raise RuntimeError(f'Whoops, no arrow! ({item})')
214| 
215| 
216| ##================================================================================================##
217| def start_node (label=None):
218|     '''Draw a process diagram Start node.'''
219|     return tess.Circle(BoxHeight*(2/3), fill='#ffff7f')
220| 
221| ##================================================================================================##
222| def end_node (label=None):
223|     '''Draw an process diagram End node.'''
224|     return tess.Circle(BoxHeight*(2/3), fill='#7f7fbf')
225| 
226| ##================================================================================================##
227| def information_node (label=None):
228|     '''Draw an process diagram Information node (blue).'''
229|     return tess.Rect(BoxWidth, BoxHeight, fill='#7fbfff')
230| 
231| ##================================================================================================##
232| def event_node (label=None):
233|     '''Draw an process diagram Event node (green).'''
234|     return tess.Rect(BoxWidth, BoxHeight, fill='#7fffbf')
235| 
236| ##================================================================================================##
237| def action_node (label=None):
238|     '''Draw a process diagram Process node (orange).'''
239|     return tess.Rect(BoxWidth, BoxHeight, fill='#ffbf7f')
240| 
241| ##================================================================================================##
242| def state_node (label=None, color='#ff7f7f'):
243|     '''Draw a process diagram State node (ellipse).'''
244|     return tess.Ellipse(BoxWidth*0.5, BoxHeight*0.5, fill=color)
245| 
246| ##================================================================================================##
247| def ghost_node ():
248|     '''Draw an process diagram invisible node.'''
249|     if FaintGhosts:
250|         return tess.Rect(BoxWidth, BoxHeight, stroke='#efefef')
251|     return tess.Rect(BoxWidth, BoxHeight, stroke=None)
252| 
253| ##================================================================================================##
254| def arrow_down (from_shape, to_shape, from_dx=0, to_dx=0):
255|     '''Draw process diagram arrow from upper shape to lower shape.'''
256|     tess.Arrow(
257|         from_shape.anchor('bottom').dy(from_dx),
258|         to_shape.anchor('top').dy(to_dx)
259|     )
260| 
261| ##================================================================================================##
262| def arrow_right (from_shape, to_shape, from_dx=0, to_dx=50):
263|     '''Draw process diagram arrow from left shape to right shape.'''
264|     tess.Arrow(
265|         from_shape.anchor('right').dx(from_dx),
266|         to_shape.anchor('left').dx(to_dx)
267|     )
268| 
269| ##================================================================================================##
270| def arrow_left (from_shape, to_shape, from_dx=0, to_dx=-50):
271|     '''Draw process diagram arrow from right shape to left shape.'''
272|     tess.Arrow(
273|         from_shape.anchor('left').dx(from_dx),
274|         to_shape.anchor('right').dx(to_dx)
275|     )
276| 
277| 
278| ##================================================================================================##
279| def do_subscriber_picks_up_phone (**kwargs):
280|     '''CMND: Draw X-Bar Switch process diagram #1 .'''
281|     fpath = KWARG('fpath', BasePath, str, kwargs)
282|     fname = KWARG('fname', 'diagram-1.png', str, kwargs)
283|     Log.info(f'xbar-diagram-1:: {str(list(kwargs.keys()))}' )
284|     Log.debug(f'{fpath=}')
285|     Log.debug(f'{fname=}')
286|     Log.info()
287|     filename = makefilename(fpath,fname)
288| 
289|     # Initialize canvas...
290|     with tess.Canvas() as canvas:
291| 
292|         # Geometry...
293|         with lay.Row(gap=RowGap):
294| 
295|             create_process_column(ProcessColumn1)
296|             create_process_column(ProcessColumn2)
297|             create_process_column(ProcessColumn3)
298|             create_process_column(ProcessColumn4)
299| 
300|         # Create down arrows...
301|         create_process_column_down_arrows(ProcessColumn1)
302|         create_process_column_down_arrows(ProcessColumn2)
303|         create_process_column_down_arrows(ProcessColumn3)
304|         create_process_column_down_arrows(ProcessColumn4)
305| 
306|         # Process communication arrows...
307|         create_process_connection_arrows(ProcessColumn1)
308|         create_process_connection_arrows(ProcessColumn2)
309|         create_process_connection_arrows(ProcessColumn3)
310|         create_process_connection_arrows(ProcessColumn4)
311| 
312|     # Fit the viewport to the shapes and render
313|     canvas.fit(padding=Margin)
314|     canvas.save(filename)
315|     Log.info(f'wrote: {filename}')
316|     Log.info()
317| 
318|     return 'Done'
319| 
320| ##================================================================================================##
321| def do_chessboard (**kwargs):
322|     '''CMND: Draw a chessboard .'''
323|     fpath = KWARG('fpath', BasePath, str, kwargs)
324|     fname = KWARG('fname', 'chessboard.svg', str, kwargs)
325|     size  = KWARG('size' , 80, int, kwargs)
326|     rows  = KWARG('rows' ,  8, int, kwargs)
327|     cols  = KWARG('cols' ,  8, int, kwargs)
328|     pad   = KWARG('pad'  , 20, int, kwargs)
329|     Log.info(f'chessboard:: {str(list(kwargs.keys()))}' )
330|     Log.debug(f'{fpath=}')
331|     Log.debug(f'{fname=}')
332|     Log.debug(f'{size=}')
333|     Log.debug(f'{rows=}')
334|     Log.debug(f'{cols=}')
335|     Log.debug(f'{pad=}')
336|     Log.info()
337|     filename = makefilename(fpath,fname)
338| 
339|     # Initialize canvas...
340|     with tess.Canvas() as canvas:
341| 
342|         # One big Column of eight rows...
343|         with lay.Column(gap=0):
344| 
345|             # Top Margin...
346|             tess.Rect(size, 30, fill=None, stroke=None)
347| 
348|             # Rows...
349|             for row in range(rows):
350|                 with lay.Row(gap=0):
351| 
352|                     # Left Margin...
353|                     tess.Rect(50, size, fill=None, stroke=None)
354| 
355|                     # Columns...
356|                     for col in range(cols):
357|                         color = '#dfdfdf' if (row+col) % 2 else '#ff7f7f'
358|                         tess.Square(size, fill=color, stroke='black')
359| 
360| 
361|     # Fit the viewport to the shapes and render
362|     canvas.fit(padding=pad)
363|     canvas.save(filename)
364|     Log.info(f'wrote: {filename}')
365|     Log.info()
366| 
367|     return 'Done'
368| 
369| ##================================================================================================##
370| def do_help (**kwargs):
371|     '''CMND: Do the help command on something.'''
372|     name = KWARG('name', '', str, kwargs)
373|     Log.info(f'help:: {str(list(kwargs.keys()))}' )
374|     Log.debug(f'{name=}')
375|     Log.info()
376| 
377|     obj = eval(name)
378|     help(obj)
379|     input('Press [Enter] to continue...')
380| 
381|     Log.info()
382|     return 'Done'
383| ##================================================================================================##
384| def do_test (**kwargs):
385|     '''CMND: Do a test.'''
386|     fpath = KWARG('fpath', BasePath, str, kwargs)
387|     fname = KWARG('fname', 'test.out', str, kwargs)
388|     Log.info(f'test:: {str(list(kwargs.keys()))}' )
389|     Log.debug(f'{fpath=}')
390|     Log.debug(f'{fname=}')
391|     Log.info()
392|     Log.info()
393|     return 'Done'
394| ####################################################################################################
395| def dispatch (cmd, **kwargs):
396|     '''Dispatch to a module function based on CMD.'''
397|     Log.info(f'CMD: {cmd}')
398|     for kw in kwargs:
399|         Log.debug(f'argument[{kw}]: {kwargs[kw]}')
400|     Log.info()
401|     if cmd == 'xb:d1': return do_subscriber_picks_up_phone(**kwargs)
402|     if cmd == 'chess': return do_chessboard(**kwargs)
403|     if cmd == 'help': return do_help(**kwargs)
404|     if cmd == 'test': return do_test(**kwargs)
405|     return 'Nothing to do!'
406| ####################################################################################################
407| if __name__ == '__main__':
408|     print(f'autorun: {argv[0]}')
409|     Log.start(path.join(BasePath,'tesserax.log'))
410|     Log.level(debug())
411|     Log.info(argv[0])
412|     Log.info()
413|     cmd = argv[1] if 1 < len(argv) else CMND
414|     kwargs = ARGS
415|     for a in argv[2:]:
416|         nv = a.split('=', 1)
417|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
418|         Log.debug(f'{nv[0]}: "{kwargs[nv[0]]}"')
419|     try:
420|         print(f'CMD: {cmd}')
421|         print()
422|         obj = dispatch(cmd, **kwargs)
423|         print()
424|         print(obj)
425|         Log.info()
426|         Log.info(obj)
427|     except:
428|         etype, evalue, tb = exc_info()
429|         ts = extract_tb(tb)
430|         Log.error()
431|         Log.error(f'{etype.__name__}: {evalue!s}')
432|         Log.error()
433|         for t in ts[-5:]:
434|             Log.error(f'[{t[1]}] {t[2]} ({t[0]})')
435|             Log.error(f' {t[3]}')
436|             Log.error()
437|         raise
438|     finally:
439|         Log.end()
440| ####################################################################################################
441| '''eof'''
442|