music_modes.html


001| """Music Modes Charts in Multiple Presentation Modes.
001| 
001| Generates the chart of the seven major modes for all twelve keys
001| (making 84 different scales total). These scales are: Lydian,
001| Ionian, Mixolydian, Dorian, Aeolian, Phrygian, and Locrian. Their
001| indexes (0 to 6) match the order just given. Notes start at A and
001| end at G#. They are indexed (0 to 11) starting with A.
001| 
001| Based on Modes, Part 7, John Baez's blog post from August 11, 2023:
001| 
001| https://johncarlosbaez.wordpress.com/2023/08/11/modes-part-7/
001| 
001| It's part of a series of posts exploring musical scales:
001| 
001| Table-1 has a column generation method that creates all 84 cells
001| for any of the seven columns. The algorithm reverses engineers the
001| column pattern without regard to how the scales are musically.
001| 
001| Table-2 has a row generation method that uses intervals of a fifth
001| to pick the notes of the scale (it moves the start point back or
001| forward from the root note to get the desired scale). The method
001| suffers from confusion between notes with identical spellings. For
001| instance, A-sharp and B-flat are the same note, but which a scale
001| uses depends on the other notes of the scale. I couldn't find a
001| generalized way to deal with the issue, so I used a table of (25!)
001| exceptions (out of 84 scales, so not good odds).
001| 
001| Table-3 has a scale generation method with a different approach.
001| The design recognizes that scale notes need to be fundamentally
001| treated in terms of their base names (A, B, C, D, E, F & G). But
001| the algorithm also needs to know about sharps and flats. So what
001| I did is use a tuple: (note, plus). The first element is the base
001| name. The second indicates flat (-n) or sharp (+n). The value is
001| expected to be 1 (flat/sharp) or 2 (double flat/sharp).
001| 
001| So: A=(0,0); A#=(0,+1); C=(2,0); Gb=(6,-1); G=(6,0); G#=(6,+1)
001| The NoteTable translates these into displayable notes.
001| 
001| Functions:
001|     table_1_display     (columns, stream)
001|     table_1_textfile    (columns, filename)
001|     table_1_webpage     (columns, filename)
001|     table_1_xml_file    (columns, filename)
001|     table_1_png_image   (columns, filename)
001| 
001|     table_2_display     (table, stream)
001|     table_2_textfile    (table, filename)
001|     table_2_webpage     (table, filename)
001|     table_2_xml_file    (table, filename)
001| 
001|     generate_column     (column_index, color_funct)
001|     generate_rows       (color_function)
001| 
001|     generate_scale_2    (note_index, mode_index)
001|     generate_section_2  (note_index)
001|     generate_table_2    ()
001|     test_scale          (note_index, mode_index)
001|     test_mode           (note_index)
001| 
001|     generate_scale_3    (first_note, mode_index)
001|     generate_section_3  (first_note)
001|     generate_table_3    ()
001| 
001| Extras:
001|     KeySig(root)        cleaned up code from something I saw on the internet
001| 
001| Commands:
001|     t3.list     do_table_3_display          Take 3
001|     t3.text     do_table_3_textfile
001|     t3.img      (not implemented yet)
001|     t3.html     do_table_3_webpage
001|     t3.xml      do_table_3_xml_file
001|     
001|     t2          do_table_2_display          Take 2
001|     
001|     t1.list     do_table_1_display          Take 1
001|     t1.text     do_table_1_textfile
001|     t1.img      do_table_1_image_file
001|     t1.html     do_table_1_webpage
001|     t1.xml      do_table_1_xml_file
001| 
001|     keysig      do_keysig_test              test KeySig class
001|     test        do_test(**kwargs)           sandbox
001| 
001| """

002| ####################################################################################################
003| from sys import argv, stdout, exc_info
004| from traceback import extract_tb
005| from os import path
006| from time import ctime
007| from PIL import Image, ImageDraw, ImageFont
008| from logger import logger,info,debug,trace, LogFilenameTimestamp
009| from goodies import KWARG
010| ####################################################################################################
011| BasePath = r'C:\CJS\prj\Python\app'
012| ImgsPath = path.join(BasePath, 'img')
013| Log = logger('Music')
014| 
015| CMND = 't2'
016| ARGS = {
017|     #'cs': '3',
018|     #'root': 'A',
019|     #'fname': 'music-modes-1-c3.html',
020|     #'fpath': BasePath,
021| }
022| 
023| ModeNames = ['Lydian', 'Ionian', 'Mixolydian', 'Dorian', 'Aeolian', 'Phrygian', 'Locrian']
024| NoteNames = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'A', 'B', 'C', 'D', 'E', 'F', 'G']
025| 
026| # Unicode Music characters...
027| MusicFlat  = '\u266d'
028| MusicSharp = '\u266f'
029| Music2Flat  = '\u266d\u266d'
030| Music2Sharp = '\u266f\u266f' #'\U0001D12a'
031| 
032| NotesSharp = ['A', 'A'+MusicSharp, 'B', 'C', 'C'+MusicSharp, 'D', 'D'+MusicSharp, 'E', 'F', 'F'+MusicSharp, 'G', 'G'+MusicSharp]
033| NotesFlat  = ['A', 'B'+MusicFlat , 'B', 'C', 'D'+MusicFlat , 'D', 'E'+MusicFlat , 'E', 'F', 'G'+MusicFlat , 'G', 'A'+MusicFlat ]
034| 
035| FMT = '%-11s| %-3s %-3s %-3s %-3s %-3s %-3s %-3s|'
036| 
037| """Note Pairs Table
037|    ----------------
037| The table uses two ways of representing the same notes. This list contains
037| both versions along with a code specifying which of the two is the primary
037| to display when the column sequence contains seven rows.
037| 
037| When the column sequence is split between the two versions, the first one
037| appears first. The column split count (1/6, 2/5, 3/4, and inverses) determines
037| how many of the first and second appear in the column.
037| """

038| NotePairs = [
039|     ('B'+Music2Flat, 'A'            , 1),   # 0 A
040|     ('B'+MusicFlat , 'A'+MusicSharp , 0),   # 1 A#
041|     ('C'+MusicFlat , 'B'            , 1),   # 2 B
042|     ('C'           , 'B'+MusicSharp , 0),   # 3 C
043|     ('D'+MusicFlat , 'C'+MusicSharp , 1),   # 4 C#
044|     ('D'           , 'C'+Music2Sharp, 0),   # 5 D
045|     ('E'+MusicFlat , 'D'+MusicSharp , 0),   # 6 D#
046|     ('F'+MusicFlat , 'E'            , 1),   # 7 E
047|     ('F'           , 'E'+MusicSharp , 0),   # 8 F
048|     ('G'+MusicFlat , 'F'+MusicSharp , 1),   # 9 F#
049|     ('G'           , 'F'+Music2Sharp, 0),   # 10 G
050|     ('A'+MusicFlat , 'G'+MusicSharp , 1),   # 11 G#
051| ]
052| BaseNotes = [note[note[2]] for note in NotePairs]
053| 
054| """Column Sequence Pattern
054|    -----------------------
054| Where in the 84-row pattern to display only the primary note versus a
054| sequence with two versions of the note. A one value means use the primary.
054| 
054| Note that the first column uses only the primary version of the notes.
054| Note also the resemblence to piano black and white keys (white=0, black=1).
054| 
054| ---Table note sequence-- C  B  Bb A  G# G  F# F  E  Eb D  C#
054| ---Note index map------- 3  2  1  0  11 10 9  8  7  6  5  4
054| ---Sharp or flat flag--- b  #  b  #  #  b  #  b  #  b  #  #
054| ---Black or White key--- C# D  D# E  F  F# G  G# A  A# B  C
054| """

055| ColumnSequencePattern = [1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0]
056| 
057| """Column Start Notes
057|    ------------------
057| Which note a column list starts with. The list contains offsets into the
057| NotePairs table. (Only seven of the possible twelve notes because the table
057| only has seven columns (because a mode scale has only seven notes).
057| (Only used by the column generator.)
057| 
057| ---Note------------ C  D  E  F  G   A  B
057| """

058| ColumnStartNotes = [3, 5, 7, 9, 10, 0, 2]
059| 
060| """ Column Dual Note Ratios
060|     -----------------------
060| When using two versions of a note in a mode column, how many of the first
060| version to use first. How many to use second is seven minus this number.
060| (Only used by the column generator.)
060| """

061| ColumnDualNoteRatios = [7, 2, 4, 6, 1, 3, 5]
062| 
063| """Column Offsets
063|    --------------
063| How much to offset each column relative to the start position. The first
063| column, obviously, is not offset at all.
063| (Only used by the column generator.)
063| """

064| ColumnOffsets = [0, 2, 4, 6, 1, 3, 5]
065| 
066| """Given a note, get the (base) note above or below."""
067| NoteAbove = lambda n:(('A') if n=='G' else chr(ord(n)+1))
068| NoteBelow = lambda n:(('G') if n=='A' else chr(ord(n)-1))
069| 
070| """Color Schemes."""
071| Colors2 = [(0x99, 0xcc, 0xff), (0x99, 0xff, 0xcc)]
072| Colors3 = [(0xf2, 0xfd, 0xff), (0x96, 0xe7, 0xfa), (0x1d, 0x89, 0xd1)]
073| Colors4 = [(0xf1, 0xee, 0xf6), (0xbd, 0xc9, 0xe1), (0x74, 0xa9, 0xcf), (0x25, 0x90, 0xd0)]
074| 
075| ##================================================================================================##
076| def get_color_scheme_1 (color_swx=3):
077|     """Returns a color scheme function."""
078|     fc2 = lambda ix:Colors2[ix % 2]
079|     fc3 = lambda ix:Colors3[ix % 3]
080|     fc4 = lambda ix:Colors4[ix % 4]
081|     if color_swx == 2: return fc2
082|     if color_swx == 3: return fc3
083|     if color_swx == 4: return fc4
084|     print('\nUnknown Color Scheme (%d)! Defaulting to 3-color.\n' % color_swx)
085|     return fc3
086| 
087| ##================================================================================================##
088| def get_color_scheme_2 (color_swx=3):
089|     """Returns a color scheme function."""
090|     fc2 = lambda cc,cx: Colors2[(cc+cx) % 2]
091|     fc3 = lambda cc,cx: Colors3[(cc+cx) % 3]
092|     fc4 = lambda cc,cx: Colors4[(cc+cx) % 4]
093|     if color_swx == 2: return fc2
094|     if color_swx == 3: return fc3
095|     if color_swx == 4: return fc4
096|     print('\nUnknown Color Scheme (%d)! Defaulting to 3-color.\n' % color_swx)
097|     return fc3
098| 
099| ##================================================================================================##
100| def generate_column (column_index, color_function):
101|     """\
101| Generate one 84-row column for the chart.
101| Requires a column index indicating which column to generate.
101| Returns a list of 84 (note, color) tuples. Color is a triplet.
101| 
101| Includes color information, which was dumb. Mixes data and presentation.
101| Would redo the whole thing, but the third approach makes this obsolete.
101| """

102|     note_index = ColumnStartNotes[column_index]
103|     note_ratio = ColumnDualNoteRatios[column_index]
104|     col_offset = ColumnOffsets[column_index]
105|     #print(column_index, note_index,note_ratio,col_offset)
106|     col = []
107|     for seq,which in enumerate(ColumnSequencePattern):
108|         bgcolor = color_function(seq)
109|         for row in range(7):
110|             # Do note version switching only if not column zero...
111|             if column_index and (which==0):
112|                 # Decide which version to use...
113|                 a_or_b = 0 if row < note_ratio else 1
114|                 note = NotePairs[note_index][a_or_b]
115|                 col.append((note,bgcolor))
116|             else:
117|                 prim = NotePairs[note_index][2]
118|                 note = NotePairs[note_index][prim]
119|                 col.append((note, bgcolor))
120|         note_index -= 1
121|         if note_index < 0: note_index = len(NotePairs)-1
122|     # Wrap the columns using their offsets...
123|     for _ in range(col_offset):
124|         col.append(col.pop(0))
125|     return col
126| 
127| ##================================================================================================##
128| def generate_rows (color_function):
129|     """Create all seven columns for the table."""
130|     cols = [generate_column(cx, color_function) for cx in range(7)]
131|     rows = zip(*cols)
132|     return list(rows)
133| 
134| ##================================================================================================##
135| def table_1_display (columns, stream=stdout):
136|     """Write table as text to a stream."""
137|     for ix,row in enumerate(columns):
138|         label = ModeNames[ix % 7]
139|         notes = [t[0] for t in row]
140|         print('%-10s| %-4s %-4s %-4s %-4s %-4s %-4s %-4s|' % (label,*notes), file=stream)
141|         if ix and (((ix+1) % 7) == 0):
142|             print(file=stream)
143|     print(file=stream)
144|     return
145| ##================================================================================================##
146| def table_2_display (table, stream=stdout):
147|     """."""
148|     for section in table:
149|         for mode,scale in section:
150|             print(FMT % (mode,*scale), file=stream)
151|         print(file=stream)
152|     print(file=stream)
153|     return
154| 
155| ##================================================================================================##
156| def table_1_textfile (columns, filename):
157|     """Write table as a text file."""
158|     fp = open(filename, mode='w', encoding='utf-8')
159|     try:
160|         table_1_display(columns, fp)
161|     except Exception as e:
162|         print()
163|         print('OOPS! Problem writing the text file!!')
164|         print(e)
165|         print()
166|     finally:
167|         fp.close()
168|         print('wrote: %s' % filename)
169|         print()
170|     return
171| ##================================================================================================##
172| def table_2_textfile (table, filename):
173|     """Write table as a text file."""
174|     fp = open(filename, mode='w', encoding='utf-8')
175|     try:
176|         table_2_display(table, fp)
177|     except Exception as e:
178|         print()
179|         print('OOPS! Problem writing the text file!!')
180|         print(e)
181|         print()
182|     finally:
183|         fp.close()
184|         print('wrote: %s' % filename)
185|         print()
186|     return
187| 
188| ##================================================================================================##
189| HtmlHead  = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">'
190| HtmlMeta  = '<meta http-equiv="Last-Modified" content="%s">'
191| HtmlTitle = '<title>Musical Modes (all 84 rows)</title>'
192| HtmlH1    = '<h1>Musical Modes (all 84 rows)</h1>'
193| HtmlTable = '<table style="border-spacing:0;border:1px solid black;"><tbody>'
194| HtmlTH    = '<tr><th style="%s">%s</th>'
195| HtmlTD    = '<td style="%s">%s</td>'
196| HtmlBlank = '<tr style="height:10px;"><td colspan="8"></td></tr>'
197| HtmlCssTH = 'text-align:left;padding:0 10px;border:1px solid black;'
198| HtmlCssTD = 'background-color:#%02x%02x%02x;padding:0 10px;border:1px solid black;'
199| HtmlError = 'OOPS! Problem writing the HTML file!!'
200| ##================================================================================================##
201| def table_1_webpage (columns, filename):
202|     """Write table as an HTML page."""
203|     fp = open(filename, mode='w', encoding='utf-8')
204|     try:
205|         print(HtmlHead, file=fp)
206|         print('<html><head>', file=fp)
207|         print(HtmlMeta % ctime(), file=fp)
208|         print(HtmlTitle, file=fp)
209|         print('</head><body>', file=fp)
210|         print(HtmlH1, file=fp)
211|         print(HtmlTable, file=fp)
212|         for ix,row in enumerate(columns):
213|             print(HtmlTH % (HtmlCssTH, ModeNames[ix % 7]), file=fp)
214|             for col in row:
215|                 css = HtmlCssTD % (col[1][0], col[1][1], col[1][2])
216|                 print(HtmlTD % (css, col[0]), file=fp)
217|             print('</tr>', file=fp)
218|             if ix and (((ix+1) % 7) == 0):
219|                 print(HtmlBlank, file=fp)
220|         print('</tbody></table>', file=fp)
221|         print('</body></html>', file=fp)
222|         print(file=fp)
223|     except Exception as e:
224|         print()
225|         print(HtmlError)
226|         print(e)
227|         print()
228|     finally:
229|         fp.close()
230|         print('wrote: %s' % filename)
231|         print()
232|     return
233| ##================================================================================================##
234| def table_2_webpage (table, filename, color_func):
235|     """Write table as an HTML page."""
236|     color_cursor = 0
237|     fp = open(filename, mode='w', encoding='utf-8')
238|     try:
239|         print(HtmlHead, file=fp)
240|         print('<html><head>', file=fp)
241|         print(HtmlMeta % ctime(), file=fp)
242|         print(HtmlTitle, file=fp)
243|         print('</head><body>', file=fp)
244|         print(HtmlH1, file=fp)
245|         print(HtmlTable, file=fp)
246|         for sx,section in enumerate(table):
247|             for mx,mode in enumerate(section):
248|                 ctab = ColorTable[mx]
249|                 name,scale = mode
250|                 print(HtmlTH % (HtmlCssTH,name), file=fp)
251|                 for note,cx in zip(scale,ctab):
252|                     css = HtmlCssTD % color_func(color_cursor,cx)
253|                     print(HtmlTD % (css,note), file=fp)
254|                 print('</tr>', file=fp)
255|             color_cursor += 1
256|             print(HtmlBlank, file=fp)
257|         print('</tbody></table>', file=fp)
258|         print('</body></html>', file=fp)
259|         print(file=fp)
260|     except Exception as e:
261|         print()
262|         print(HtmlError)
263|         print(e)
264|         print()
265|     finally:
266|         fp.close()
267|         print('wrote: %s' % filename)
268|         print()
269|     return
270| 
271| ##================================================================================================##
272| XmlHead   = '<?xml version="1.0" encoding="UTF-8"?>'
273| XmlDoc0   = '<musicmodes>'
274| XmlKey0   = '<key name="%s">'
275| XmlScale0 = ' <scale name="%s %s">'
276| XmlNotes0 = ' <notes>'
277| XmlNote   = ' <note>%s</note>'
278| XmlNotes1 = ' </notes>'
279| XmlScale1 = ' </scale>'
280| XmlKey1   = '</key>'
281| XmlDoc1   = '</musicmodes>'
282| XmlError  = 'OOPS! Problem writing the XML file!!'
283| ##================================================================================================##
284| def table_1_xml_file (columns, filename):
285|     """Write table as an XML file."""
286|     fp = open(filename, mode='w', encoding='utf-8')
287|     try:
288|         print(XmlHead, file=fp)
289|         print(XmlDoc0, file=fp)
290|         for ix,row in enumerate(columns):
291|             print(XmlScale0 % (row[0][0],ModeNames[ix % 7]), file=fp)
292|             print(XmlNotes0, file=fp)
293|             for col in row:
294|                 print(XmlNote % col[0], file=fp)
295|             print(XmlNotes1, file=fp)
296|             print(XmlScale1, file=fp)
297|         print(XmlDoc1, file=fp)
298|     except Exception as e:
299|         print()
300|         print(XmlError)
301|         print(e)
302|         print()
303|     finally:
304|         fp.close()
305|         print('wrote: %s' % filename)
306|         print()
307|     return
308| ##================================================================================================##
309| def table_2_xml_file (table, filename):
310|     """Write table as an XML file."""
311|     fp = open(filename, mode='w', encoding='utf-8')
312|     try:
313|         print(XmlHead, file=fp)
314|         print(XmlDoc0, file=fp)
315|         for sx,section in enumerate(table):
316|             print(XmlKey0 % section[0][1][0], file=fp)
317|             for mode_name,scale in section:
318|                 print(XmlScale0 % (scale[0],mode_name), file=fp)
319|                 print(XmlNotes0, file=fp)
320|                 for note in scale:
321|                     print(XmlNote % note, file=fp)
322|                 print(XmlNotes1, file=fp)
323|                 print(XmlScale1, file=fp)
324|             print(XmlKey1, file=fp)
325|         print(XmlDoc1, file=fp)
326|     except Exception as e:
327|         print()
328|         print(XmlError)
329|         print(e)
330|         print()
331|     finally:
332|         fp.close()
333|         print('wrote: %s' % filename)
334|         print()
335|     return
336| 
337| ##================================================================================================##
338| def table_1_png_image (columns, filename):
339|     """Write table as a PNG image."""
340|     row_height = 40
341|     row_margin = 5
342|     label_width = 200
343|     note_width = 70
344|     top_margin = 10
345|     left_margin = 10
346|     label_margin = 10
347|     note_margin = 8
348|     head_margin = 4
349|     title_color = (0x33, 0x66, 0x99)
350|     label_color = (0x00, 0x00, 0x00)
351|     notes_color = (0x00, 0x00, 0x00)
352| 
353|     width = left_margin + label_width + (7 * note_width) + left_margin
354|     dims = (width, 3500)
355|     im = Image.new('RGB', dims, color=(255,255,255))
356|     gi = ImageDraw.Draw(im)
357| 
358|     fnt0 = ImageFont.truetype('timesbd.ttf', size=48)
359|     fnt1 = ImageFont.truetype('timesbd.ttf', size=32)
360|     fnt2 = ImageFont.truetype('times.ttf', size=32)
361| 
362|     vcursor = top_margin
363|     left = left_margin
364|     right = left + label_width + (7 * note_width)
365| 
366|     # Title...
367|     txt = 'Musical Modes (all 84 rows)'
368|     x0,y0,x1,y1 = gi.textbbox((left,vcursor), txt, fnt0)
369|     cx = ((right-left)-(x1-x0)) // 2
370|     gi.text((left+cx,vcursor), txt, font=fnt0, fill=title_color)
371|     vcursor += y1
372| 
373|     # Draw horizontal lines...
374|     top = vcursor
375|     for section in range(12):
376|         for row in range(8):
377|             gi.line([(left,vcursor), (right,vcursor)], fill=(0,0,0), width=2)
378|             vcursor += row_height
379|         vcursor -= (row_height-row_margin)
380|     bottom = vcursor - row_margin
381|     #Draw vertical lines...
382|     gi.line([(left,top), (left,bottom)], fill=(0,0,0), width=2)
383|     gi.line([(left+label_width,top), (left+label_width,bottom)], fill=(0,0,0), width=2)
384|     gi.line([(right,top), (right,bottom)], fill=(0,0,0), width=2)
385| 
386|     # Draw the text...
387|     vcursor = top
388|     for ix,row in enumerate(columns):
389|         # Label...
390|         label = ModeNames[ix % 7]
391|         x0,y0,x1,y1 = gi.textbbox((left,vcursor), label, fnt2)
392|         gi.text((left+label_margin,vcursor+head_margin), label, font=fnt1, fill=label_color)
393|         # Notes...
394|         note_left = left+label_width
395|         for nx,note in enumerate(row):
396|             txt,clr = note
397|             # Cell square...
398|             ulx = note_left + (nx * note_width)
399|             uly = vcursor
400|             lrx = ulx + note_width
401|             lry = uly + row_height
402|             gi.rectangle([(ulx,uly), (lrx,lry)], fill=clr, outline=(0,0,0), width=2)
403|             # Note...
404|             x0,y0,x1,y1 = gi.textbbox((left,vcursor), txt, fnt2)
405|             px = note_left + note_margin + (nx * note_width)
406|             gi.text((px,vcursor+head_margin), txt, font=fnt2, fill=label_color)
407| 
408|         # Next row...
409|         if ix and (((ix+1) % 7) == 0):
410|             vcursor += (row_height+row_margin)
411|         else:
412|             vcursor += row_height
413| 
414|     im.save(filename)
415|     print('wrote: %s' % filename)
416|     print()
417|     return
418| ##================================================================================================##
419| def table_2_png_image (table, filename):
420|     """Write table as a PNG image."""
421|     return
422| 
423| 
424| ####################################################################################################
425| ## TAKE TWO...
426| ####################################################################################################
427| DupeNoteFixes = {
428|     'C Lydian':     ['C' , 'D' , 'E' , 'F♯', 'G' , 'A' , 'B' ],
429|     'B Lydian':     ['B' , 'C♯', 'D♯', 'E♯', 'F♯', 'G♯', 'A♯'],
430|     'Bâ™­ Phrygian':  ['Bâ™­', 'Câ™­', 'Dâ™­', 'Eâ™­', 'F' , 'Gâ™­', 'Aâ™­'],
431|     'Bâ™­ Locrian':   ['Bâ™­', 'Câ™­', 'Dâ™­', 'Eâ™­', 'Fâ™­', 'Gâ™­', 'Aâ™­'],
432|     'A Phrygian':   ['A' , 'Bâ™­', 'C' , 'D' , 'E' , 'F' , 'G' ],
433|     'A Locrian':    ['A' , 'Bâ™­', 'C' , 'D' , 'Eâ™­', 'F' , 'G' ],
434|     'G♯ Lydian':    ['G♯', 'A♯', 'B♯', 'C♯♯','D♯', 'E♯', 'F♯♯'],
435|     'G♯ Ionian':    ['G♯', 'A♯', 'B♯', 'C♯', 'D♯', 'E♯', 'F♯♯'],
436|     'G♯ Mixolydian':['G♯', 'A♯', 'B♯', 'C♯', 'D♯', 'E♯', 'F♯'],
437|     'G♯ Dorian':    ['G♯', 'A♯', 'B' , 'C♯', 'D♯', 'E♯', 'F♯'],
438|     'G Lydian':     ['G' , 'A' , 'B' , 'C♯', 'D' , 'E' , 'F♯'],
439|     'G Ionian':     ['G' , 'A' , 'B' , 'C' , 'D' , 'E' , 'F♯'],
440|     'F♯ Lydian':    ['F♯', 'G♯', 'A♯', 'B♯', 'C♯', 'D♯', 'E♯'],
441|     'F♯ Ionian':    ['F♯', 'G♯', 'A♯', 'B' , 'C♯', 'D♯', 'E♯'],
442|     'F Locrian':    ['F' , 'Gâ™­', 'Aâ™­', 'Bâ™­', 'Câ™­', 'Dâ™­', 'Eâ™­'],
443|     'Eâ™­ Aeolian':   ['Eâ™­', 'F' , 'Gâ™­', 'Aâ™­', 'Bâ™­', 'Câ™­', 'Dâ™­'],
444|     'Eâ™­ Phrygian':  ['Eâ™­', 'Fâ™­', 'Gâ™­', 'Aâ™­', 'Bâ™­', 'Câ™­', 'Dâ™­'],
445|     'Eâ™­ Locrian':   ['Eâ™­', 'Fâ™­', 'Gâ™­', 'Aâ™­', 'Bâ™­â™­','Câ™­', 'Dâ™­'],
446|     'E Locrian':    ['E' , 'F' , 'G' , 'A' , 'Bâ™­', 'C' , 'D' ],
447|     'D Aeolian':    ['D' , 'E' , 'F' , 'G' , 'A' , 'Bâ™­', 'C' ],
448|     'D Phrygian':   ['D' , 'Eâ™­', 'F' , 'G' , 'A' , 'Bâ™­', 'C' ],
449|     'D Locrian':    ['D' , 'Eâ™­', 'F' , 'G' , 'Aâ™­', 'Bâ™­', 'C' ],
450|     'C♯ Lydian':    ['C♯', 'D♯', 'E♯', 'F♯♯','G♯', 'A♯', 'B♯'],
451|     'C♯ Ionian':    ['C♯', 'D♯', 'E♯', 'F♯', 'G♯', 'A♯', 'B♯'],
452|     'C♯ Mixolydian':['C♯', 'D♯', 'E♯', 'F♯', 'G♯', 'A♯', 'B' ],
453| }
454| 
455| ##================================================================================================##
456| def generate_scale_2 (note_index, mode_index):
457|     """Generate a given scale in a given key."""
458|     assert 0 <= note_index < 12, ValueError('Note index must be from 0 to 11')
459|     assert 0 <= mode_index < 7, ValueError('Mode index must be from 0 to 6')
460|     note_name = BaseNotes[note_index]
461|     mode_name = ModeNames[mode_index]
462|     #print('Generate %s scale for %s' % (mode_name, note_name))
463| 
464|     def fix_duplicate_notes (notes):
465|         """Fix Duplicate Notes."""
466|         board = {note:[] for note in 'ABCDEFG'}
467|         # Plug notes into the board...
468|         for n in scale:
469|             board[n[0]].append(n)
470|         # Look for empty slots...
471|         empty = [t[0] for t in sorted(board.items()) if len(t[1])==0]
472|         if 0 < len(empty):
473|             #print('%s %s: Missing Notes: %s' % (note_name, mode_name, empty))
474|             k = '%s %s' % (note_name, mode_name)
475|             assert k in DupeNoteFixes, RuntimeError('No fix found! (%s)' % k)
476|             return DupeNoteFixes[k]
477|         # No duplicate notes, so just return input...
478|         return notes
479| 
480|     def make_scale (notes):
481|         # Start the cursor at the given index...
482|         cursor = note_index
483|         scale = []
484|         # Select scale mode by backing up...
485|         for _ in range(6-mode_index):
486|             cursor = ((cursor-5) % 12)
487|         # Pick seven notes at intevals of fifths...
488|         for scale_index in range(7):
489|             note = notes[cursor]
490|             scale.append(note)
491|             cursor = ((cursor+5) % 12)
492|         return scale
493| 
494|     # Select Sharps or Flats...
495|     ix = (((11 - note_index) + 4) % 12)
496|     note_table = NotesFlat if ColumnSequencePattern[ix] else NotesSharp
497| 
498|     # Make the scale...
499|     scale = make_scale(note_table)
500|     # Fix duplicate notes...
501|     #ATTN: UGH!!
502|     scale = fix_duplicate_notes(scale)
503|     # Sort the result...
504|     scale = sorted(scale)
505| 
506|     # Rotate notes so scale starts at the right key...
507|     key = note_table[note_index]
508|     watch_dog = 7
509|     while scale[0] != key:
510|         scale.append(scale.pop(0))
511|         watch_dog -= 1
512|         if watch_dog < 0:
513|             raise RuntimeError('Whoa! Generate-Row failed to find the first note!')
514| 
515|     # Return the scale for the given key and mode...
516|     return (mode_name, scale)
517| 
518| ##================================================================================================##
519| def generate_section_2 (note_index):
520|     """Generate the seven mode scales in a given key."""
521|     #print('Generate Modes for %s' % BaseNotes[note_index])
522|     scales = []
523|     # Loop through modes...
524|     for mode in range(7):
525|         try:
526|             scale = generate_scale_2(note_index, mode)
527|             scales.append(scale)
528|         except Exception as e:
529|             print()
530|             print(e)
531|             print()
532|     # Return the mode scales for the given key...
533|     return scales
534| 
535| ##================================================================================================##
536| def generate_table_2 ():
537|     """Generate the 84-row table of scales.
537| 
537| Table is a list of 12 sections, one for each musical key.
537| Each section is a list of 7 (mode-name, scale) tuples.
537| """

538|     return [generate_section_2(key) for key in [3,2,1,0,11,10,9,8,7,6,5,4]]
539| 
540| ##================================================================================================##
541| def test_scale (note_index=3, mode_index=6):
542|     scale = generate_scale_2(note_index, mode_index)
543|     mode,notes = scale
544|     print(FMT % (mode,*notes))
545|     return scale
546| 
547| def test_mode (note_index=3):
548|     modes = generate_section_2(note_index)
549|     print()
550|     for scale in modes:
551|         mode,notes = scale
552|         print(FMT % (mode,*notes))
553|     print()
554|     return modes
555| 
556| #scale = test_scale(note_index=3, mode_index=0)
557| #scales = test_mode(note_index=3)
558| 
559| 
560| ####################################################################################################
561| ## TAKE THREE...
562| ####################################################################################################
563| ModeIntervals = [
564|     [1, 2, 2, 2, 1, 2, 2, 1],   # Lydian C D E F# G A B
565|     [1, 2, 2, 1, 2, 2, 2, 1],   # Ionian C D E F G A B
566|     [2, 2, 2, 1, 2, 2, 1, 2],   # Mixolydian C D E F G A Bb
567|     [2, 2, 1, 2, 2, 2, 1, 2],   # Dorian C D Eb F G A Bb
568|     [2, 2, 1, 2, 2, 1, 2, 2],   # Aeolian C D Eb F G Ab Bb
569|     [2, 1, 2, 2, 2, 1, 2, 2],   # Phrygian C Db Eb F G Ab Bb
570|     [2, 1, 2, 2, 1, 2, 2, 2],   # Locrian C Db Eb F Gb Ab Bb
571| ]
572| ColorTable = [
573|     [0, 0, 0, 0, 0, 0, 0],
574|     [0, 0, 0, 1, 0, 0, 0],
575|     [0, 0, 0, 1, 0, 0, 1],
576|     [0, 0, 1, 1, 0, 0, 1],
577|     [0, 0, 1, 1, 0, 1, 1],
578|     [0, 1, 1, 1, 0, 1, 1],
579|     [0, 1, 1, 1, 1, 1, 1],
580| ]
581| NoteTable = {
582|     'A':('A'+Music2Flat, 'A'+MusicFlat, 'A', 'A'+MusicSharp, 'A'+Music2Sharp),
583|     'B':('B'+Music2Flat, 'B'+MusicFlat, 'B', 'B'+MusicSharp, 'B'+Music2Sharp),
584|     'C':('C'+Music2Flat, 'C'+MusicFlat, 'C', 'C'+MusicSharp, 'C'+Music2Sharp),
585|     'D':('D'+Music2Flat, 'D'+MusicFlat, 'D', 'D'+MusicSharp, 'D'+Music2Sharp),
586|     'E':('E'+Music2Flat, 'E'+MusicFlat, 'E', 'E'+MusicSharp, 'E'+Music2Sharp),
587|     'F':('F'+Music2Flat, 'F'+MusicFlat, 'F', 'F'+MusicSharp, 'F'+Music2Sharp),
588|     'G':('G'+Music2Flat, 'G'+MusicFlat, 'G', 'G'+MusicSharp, 'G'+Music2Sharp),
589| }
590| 
591| ##================================================================================================##
592| def Note2Str (t):
593|     base = t[0]
594|     more = 2 + t[1]
595|     return NoteTable[base][more]
596| 
597| def Str2Note (nt):
598|     base = nt[0]
599|     more = nt[1:2]
600|     if more == MusicSharp: return (base, +1)
601|     if more == MusicFlat: return (base, -1)
602|     return (base, 0)
603| 
604| ##================================================================================================##
605| def generate_scale_3 (first_note=('C',0), mode_index=0):
606|     """Generate scale given a start note and mode index."""
607|     mode = ModeIntervals[mode_index]
608|     mode_name = ModeNames[mode_index]
609|     scale = [first_note]
610| 
611|     def next_note (nt, d):
612|         """Figure out next note."""
613|         #print('next-note(%s %d)' % (nt,d))
614|         nxnt = NoteAbove(nt[0])
615|         if nt[0] in ['B', 'E']:
616|             flag = nt[1] + (d - 1)
617|         else:
618|             flag = nt[1] - (2 - d)
619|         t = (nxnt, flag)
620|         #print('next-note: %s' % str(t))
621|         return t
622| 
623|     for dist in mode[1:7]:
624|         base = scale[-1]
625|         note = next_note(base, dist)
626|         scale.append(note)
627| 
628|     # Return (mode_name, scale) tuple...
629|     return (mode_name, [Note2Str(n) for n in scale])
630| 
631| ##================================================================================================##
632| def generate_section_3 (first_note=('C',0)):
633|     """Generate the seven mode scales in a given key."""
634|     scales = []
635|     for mode in range(7):
636|         ns = generate_scale_3(mode_index=mode, first_note=first_note)
637|         scales.append(ns)
638|     return scales
639| 
640| ##================================================================================================##
641| def generate_table_3 ():
642|     """Generate the 84-row table of scales.
642| 
642| Table is a list of 12 sections, one for each musical key.
642| Each section is a list of 7 (mode-name, scale) tuples.
642| """

643|     table = []
644|     for key in [3,2,1,0,11,10,9,8,7,6,5,4]:
645|         note = Str2Note(BaseNotes[key])
646|         #print('NOTE: (%s, %d)' % note)
647|         sect = generate_section_3(first_note=note)
648|         table.append(sect)
649|     return table
650| 
651| 
652| ####################################################################################################
653| ## And now for something completely different...
654| ## ATTN: Needs work! (NOTE: TODO!)
655| ####################################################################################################
656| class KeySig:
657|     """Cleaned up code from something I saw on the internet."""
658| 
659|     tones=['A','A#','B','C','C#','D','D#','E','F','F#','G','G#',
660|            'A','A#','B','C','C#','D','D#','E','F','F#','G','G#']
661| 
662|     maj_half_steps = [0,2,4,5,7,9,11,12] # [2,2,1,2,2,2,1,1]
663|     min_half_steps = [0,2,3,5,7,8,10,12] # [2,1,2,2,1,2,2,1]
664| 
665|     def __init__ (self, root):
666|         self.keysig = root.upper()
667|         if self.keysig not in KeySig.tones:
668|             raise RuntimeError('Unknown key sig: %s' % self.keysig)
669|         self.root = KeySig.tones.index(self.keysig)
670|         self.maj_scale = [KeySig.tones[self.root+step] for step in KeySig.maj_half_steps]
671|         self.min_scale = [KeySig.tones[self.root+step] for step in KeySig.min_half_steps]
672| 
673|     def major_scale (self):
674|         return self.maj_scale
675| 
676|     def minor_scale (self):
677|         return self.min_scale
678| 
679|     def M_chords (self):
680|         self.key_chords = []
681|         self.scale=self.maj_scale+self.maj_scale[1:]
682|         for ix in range(0,7):
683|             self.chord = [self.scale[ix]]
684|             self.chord.append(self.scale[ix+2])
685|             self.chord.append(self.scale[ix+4])
686|             self.key_chords.append(tuple(self.chord))
687|         return self.key_chords
688| 
689|     def m_chords (self):
690|         self.key_chords = []
691|         self.scale=self.min_scale+self.min_scale[1:]
692|         for ix in range(0,7):
693|             self.chord = [self.scale[ix]]
694|             self.chord.append(self.scale[ix+2])
695|             self.chord.append(self.scale[ix+4])
696|             self.key_chords.append(tuple(self.chord))
697|         return self.key_chords
698| 
699| 
700| ####################################################################################################
701| ## COMMANDS
702| ##================================================================================================##
703| def do_table_1_display (**kwargs):
704|     """CMND: Generate table_1 and display it to stdout."""
705|     cs = KWARG('cs', 3, int, kwargs)
706|     Log.info('table-1-display:: %s' % str(list(kwargs.keys())))
707|     Log.debug('color-scheme="%s" (irrelevant?)' % cs)
708|     Log.info()
709|     color_scheme = get_color_scheme_1(cs)
710|     table = generate_rows(color_scheme)
711|     print()
712|     table_1_display(table)
713|     Log.info()
714|     return 'Done'
715| ##================================================================================================##
716| def do_table_1_textfile (**kwargs):
717|     """CMND: Generate table-1 and write it to a textfile."""
718|     fpath = KWARG('fpath', BasePath, str, kwargs)
719|     fname = KWARG('fname', 'music-modes-1.text', str, kwargs)
720|     cs = KWARG('cs', 3, int, kwargs)
721|     Log.info('table-1-textfile:: %s' % str(list(kwargs.keys())))
722|     Log.debug('fpath="%s"' % fpath)
723|     Log.debug('fname="%s"' % fname)
724|     Log.debug('color-scheme="%s" (irrelevant)' % cs)
725|     Log.info()
726|     filename = path.join(fpath, fname)
727|     color_scheme = get_color_scheme_1(cs)
728|     table = generate_rows(color_scheme)
729|     table_1_textfile(table, filename)
730|     Log.info()
731|     return 'Done'
732| ##================================================================================================##
733| def do_table_1_webpage (**kwargs):
734|     """CMND: Generate table-1 and create a webpage (HTML file)."""
735|     fpath = KWARG('fpath', BasePath, str, kwargs)
736|     fname = KWARG('fname', 'music-modes-1.html', str, kwargs)
737|     cs = KWARG('cs', 3, int, kwargs)
738|     Log.info('table-1-webpage:: %s' % str(list(kwargs.keys())))
739|     Log.debug('fpath="%s"' % fpath)
740|     Log.debug('fname="%s"' % fname)
741|     Log.debug('color-scheme="%s"' % cs)
742|     Log.info()
743|     filename = path.join(fpath, fname)
744|     color_scheme = get_color_scheme_1(cs)
745|     table = generate_rows(color_scheme)
746|     table_1_webpage(table, filename)
747|     Log.info()
748|     return 'Done'
749| ##================================================================================================##
750| def do_table_1_xml_file (**kwargs):
751|     """CMND: Generate table-1 and write it to an XML file."""
752|     fpath = KWARG('fpath', BasePath, str, kwargs)
753|     fname = KWARG('fname', 'music-modes-1.xml', str, kwargs)
754|     cs = KWARG('cs', 3, int, kwargs)
755|     Log.info('table-1-xmlfile:: %s' % str(list(kwargs.keys())))
756|     Log.debug('fpath="%s"' % fpath)
757|     Log.debug('fname="%s"' % fname)
758|     Log.debug('color-scheme="%s" (irrelevant)' % cs)
759|     Log.info()
760|     filename = path.join(fpath, fname)
761|     color_scheme = get_color_scheme_1(cs)
762|     table = generate_rows(color_scheme)
763|     table_1_xml_file(table, filename)
764|     Log.info()
765|     return 'Done'
766| ##================================================================================================##
767| def do_table_1_image_file (**kwargs):
768|     """CMND: Generate table-1 and write it to a PNG file."""
769|     fpath = KWARG('fpath', ImgsPath, str, kwargs)
770|     fname = KWARG('fname', 'music-modes-1.png', str, kwargs)
771|     cs = KWARG('cs', 3, int, kwargs)
772|     Log.info('table-1-png-image:: %s' % str(list(kwargs.keys())))
773|     Log.debug('fpath="%s"' % fpath)
774|     Log.debug('fname="%s"' % fname)
775|     Log.debug('color-scheme="%s"' % cs)
776|     Log.info()
777|     filename = path.join(fpath, fname)
778|     color_scheme = get_color_scheme_1(cs)
779|     table = generate_rows(color_scheme)
780|     table_1_png_image(table, filename)
781|     Log.info()
782|     return 'Done'
783| 
784| ##================================================================================================##
785| def do_table_2_display (**kwargs):
786|     """CMND: Generate table-2 (ha!)."""
787|     fpath = KWARG('fpath', BasePath, str, kwargs)
788|     fname = KWARG('fname', 'music-modes-2.text', str, kwargs)
789|     Log.info('table-2-display:: %s' % str(list(kwargs.keys())))
790|     Log.debug('fpath="%s"' % fpath)
791|     Log.debug('fname="%s"' % fname)
792|     Log.info()
793|     filename = path.join(fpath, fname)
794|     table = generate_table_2()
795|     table_2_display(table)
796|     Log.info()
797|     return 'Done'
798| 
799| ##================================================================================================##
800| def do_table_3_display (**kwargs):
801|     """CMND: Generate table-3 and display it to stdout."""
802|     Log.info('table-3-display:: %s' % str(list(kwargs.keys())))
803|     Log.info()
804|     table = generate_table_3()
805|     Log.debug(table[0])             # first section
806|     Log.debug(table[0][0])          # first scale tuple (of first section)
807|     Log.debug(table[0][0][0])       # first scale ModeName (first section)
808|     Log.debug(table[0][0][1])       # first scale of first section
809|     Log.debug(table[0][0][1][0])    # first note of first scale of first section
810|     print()
811|     table_2_display(table)
812|     Log.info()
813|     return 'Done'
814| ##================================================================================================##
815| def do_table_3_textfile (**kwargs):
816|     """CMND: Generate table-3 and write it to a textfile."""
817|     fpath = KWARG('fpath', BasePath, str, kwargs)
818|     fname = KWARG('fname', 'music-modes-3.text', str, kwargs)
819|     Log.info('table-3-textfile:: %s' % str(list(kwargs.keys())))
820|     Log.debug('fpath="%s"' % fpath)
821|     Log.debug('fname="%s"' % fname)
822|     Log.info()
823|     filename = path.join(fpath, fname)
824|     table = generate_table_3()
825|     table_2_textfile(table, filename)
826|     Log.info()
827|     return 'Done'
828| ##================================================================================================##
829| def do_table_3_webpage (**kwargs):
830|     """CMND: Generate table-3 and create a webpage (HTML file)."""
831|     fpath = KWARG('fpath', BasePath, str, kwargs)
832|     fname = KWARG('fname', 'music-modes-3.html', str, kwargs)
833|     cs = KWARG('cs', 3, int, kwargs)
834|     Log.info('table-3-webpage:: %s' % str(list(kwargs.keys())))
835|     Log.debug('fpath="%s"' % fpath)
836|     Log.debug('fname="%s"' % fname)
837|     Log.debug('color-scheme="%s"' % cs)
838|     Log.info()
839|     filename = path.join(fpath, fname)
840|     color_func = get_color_scheme_2(cs)
841|     table = generate_table_3()
842|     table_2_webpage(table, filename, color_func)
843|     Log.info()
844|     return 'Done'
845| ##================================================================================================##
846| def do_table_3_xml_file (**kwargs):
847|     """CMND: Generate table-3 and write it to an XML file."""
848|     fpath = KWARG('fpath', BasePath, str, kwargs)
849|     fname = KWARG('fname', 'music-modes-3.xml', str, kwargs)
850|     Log.info('table-3-xmlfile:: %s' % str(list(kwargs.keys())))
851|     Log.debug('fpath="%s"' % fpath)
852|     Log.debug('fname="%s"' % fname)
853|     Log.info()
854|     filename = path.join(fpath, fname)
855|     table = generate_table_3()
856|     table_2_xml_file(table, filename)
857|     Log.info()
858|     return 'Done'
859| 
860| ##================================================================================================##
861| def do_keysig_test (**kwargs):
862|     """CMND: Test the KeySig class."""
863|     root = KWARG('root', 'C', str, kwargs)
864|     Log.info('test-keysig-class:: %s' % str(list(kwargs.keys())))
865|     Log.info('root="%s"' % root)
866|     Log.info()
867|     print()
868| 
869|     k = KeySig(root=root)
870| 
871|     print("Major Scale: %s" % k.major_scale())
872|     print("Minor Scale: %s" % k.minor_scale())
873|     print()
874|     for ch in k.M_chords():
875|         print("Major Chord: %s" % str(ch))
876|     print()
877|     for ch in k.m_chords():
878|         print("Minor Chord: %s" % str(ch))
879|     print()
880| 
881|     Log.info("Major Scale: %s" % k.major_scale())
882|     Log.info("Minor Scale: %s" % k.minor_scale())
883|     Log.info()
884|     for ch in k.M_chords():
885|         Log.info("Major Chord: %s" % str(ch))
886|     Log.info()
887|     for ch in k.m_chords():
888|         Log.info("Minor Chord: %s" % str(ch))
889|     Log.info()
890|     Log.info()
891|     return 'Done'
892| 
893| ##================================================================================================##
894| def do_test (**kwargs):
895|     """Do a test."""
896|     fpath = KWARG('fpath', BasePath, str, kwargs)
897|     fname = KWARG('fname', 'test.out', str, kwargs)
898|     Log.info('test:: %s' % str(list(kwargs.keys())))
899|     Log.debug('fpath="%s"' % fpath)
900|     Log.debug('fname="%s"' % fname)
901|     Log.info()
902|     Log.info()
903|     return 'Done'
904| ####################################################################################################
905| def dispatch (cmd, **kwargs):
906|     """Dispatch to a module function based on CMD."""
907|     Log.info('CMD: %s' % cmd)
908|     for kw in kwargs:
909|         Log.debug('argument[%s]: %s' % (kw,kwargs[kw]))
910|     Log.info()
911| 
912|     if cmd == 't3.list': return do_table_3_display(**kwargs)
913|     if cmd == 't3.text': return do_table_3_textfile(**kwargs)
914|     if cmd == 't3.img' : return 'Not Implemented!'
915|     if cmd == 't3.html': return do_table_3_webpage(**kwargs)
916|     if cmd == 't3.xml' : return do_table_3_xml_file(**kwargs)
917| 
918|     if cmd == 't2' : return do_table_2_display(**kwargs)
919| 
920|     if cmd == 't1.list': return do_table_1_display(**kwargs)
921|     if cmd == 't1.text': return do_table_1_textfile(**kwargs)
922|     if cmd == 't1.img' : return do_table_1_image_file(**kwargs)
923|     if cmd == 't1.html': return do_table_1_webpage(**kwargs)
924|     if cmd == 't1.xml' : return do_table_1_xml_file(**kwargs)
925| 
926|     if cmd == 'keysig': return do_keysig_test(**kwargs)
927|     if cmd == 'test': return do_test(**kwargs)
928|     return 'Nothing to do!'
929| ####################################################################################################
930| if __name__ == '__main__':
931|     print('autorun: %s' % argv[0])
932|     #Log.start(path.join(BasePath,LogFilenameTimestamp('music-modes_%s.log')))
933|     Log.start(path.join(BasePath,'music-modes.log'))
934|     Log.level(info())
935|     Log.info(argv[0])
936|     Log.info()
937|     cmd = argv[1] if 1 < len(argv) else CMND
938|     kwargs = ARGS
939|     for a in argv[2:]:
940|         nv = a.split('=', 1)
941|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
942|         Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
943|     try:
944|         print('CMD: %s' % cmd)
945|         print()
946|         obj = dispatch(cmd, **kwargs)
947|         print()
948|         print(obj)
949|         Log.info()
950|         Log.info(obj)
951|     except:
952|         etype, evalue, tb = exc_info()
953|         ts = extract_tb(tb)
954|         Log.error()
955|         Log.error('%s: %s' % (etype.__name__,str(evalue)))
956|         Log.error()
957|         for t in ts[-5:]:
958|             Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
959|             Log.error(' %s' % t[3])
960|             Log.error()
961|         raise
962|     finally:
963|         Log.end()
964| ####################################################################################################
965| '''eof'''
966|