summary.html


001| ####################################################################################################
002| from sys import argv
003| from os import path, listdir
004| from matplotlib import pyplot as plt
005| from matplotlib.ticker import NullLocator, FixedLocator, MultipleLocator
006| from matplotlib.ticker import NullFormatter, FixedFormatter, FormatStrFormatter
007| from goodies import typename, KWARG, divisions, intervals
008| from files import textfile, linefile, csvfile, tabfile
009| from webpage import WebPage
010| ####################################################################################################
011| BasePath = r'C:\CJS\prj\Python\blog\substack\ESC'
012| ImgsPath = path.join(BasePath, 'img')
013| 
014| CMD = 'list'
015| ETC = ['xf']
016| 
017| 
018| ##------------------------------------------------------------------------------------------------##
019| TabFileHeaders = ['filename', 'max-size', 'min-size (AC)' ,'SS' ,'EF' ,'ESC']
020| 
021| ##------------------------------------------------------------------------------------------------##
022| style_sheets = [
023|     'http://localhost/basic.css'
024| ]
025| 
026| ##------------------------------------------------------------------------------------------------##
027| style_text = """\
027| table {
027|     background-color: #7f7f7f;
027|     color: #000000;
027|     font-family: sans-serif;
027|     font-size: 13px;
027|     border-spacing: 5px 3px;
027|     padding: 0;
027|     border: 1px solid black;
027|     margin: 15px 30px;
027| }
027| table thead td {
027|     background-color: #000000;
027|     color: #ffff00;
027|     font-weight: bold;
027|     text-align: center;
027|     padding: 3px 7px 5px 7px;
027| }
027| table thead th {
027|     background-color: #000000;
027|     color: #ffffff;
027|     font-weight: bold;
027|     text-align: center;
027|     padding: 3px 7px 5px 7px;
027| }
027| table tbody th {
027|     background-color: #333333;
027|     color: #ffff7f;
027|     font-family: monospace;
027|     font-weight: bold;
027|     text-align: right;
027|     padding: 2px 5px 3px 5px;
027| }
027| table tbody td {
027|     background-color: #ffffff;
027|     color: #000000;
027|     text-align: right;
027|     padding: 2px 5px 3px 19px;
027| }
027| table tbody td.filename {
027|     font-weight: bold;
027|     text-align: left;
027|     padding-right: 25px;
027|     padding-left: 7px;
027| }
027| table tbody td.number {
027|     font-size: 15px;
027| }
027| table tbody td.tint1 {background-color: #efffef;}
027| table tbody td.tint2 {background-color: #ffffff;}
027| """

028| 
029| ##------------------------------------------------------------------------------------------------##
030| x_meta = [
031|     ('X-Signature', 'lux et veritas; sapere aude'),
032|     ('X-Best-Sport', 'Baseball'),
033|     ('X-A-Great-Dog', 'Bentley'),
034|     ('X-Clacks-Overhead', 'Samantha the Black Lab'),
035|     ('X-Clacks-Overhead', 'Sir Terry Pratchett'),
036|     ('X-Clacks-Overhead', 'Carl Sagan'),
037|     ('X-Ultimate-Answer', '42'),
038| ]
039| 
040| 
041| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
042| class Summary (tabfile):
043|     tab_filename = path.join(BasePath, 'summary.tab')
044|     html_filename = path.join(BasePath, 'summary.html')
045| 
046|     def __init__ (self):
047|         super().__init__(self.tab_filename)
048|         self.load()
049| 
050|     def load (self):
051|         super().load()
052|         print(f'loaded: {self.tab_filename} ({len(self)} rows)')
053|         print()
054| 
055|         self.xs = list(range(len(self)))
056|         self.fnames = [row[0] for row in self]
057|         self.top = [int(row[1]) for row in self]
058|         self.ac  = [int(row[2]) for row in self]
059|         self.ss  = [float(row[3]) for row in self]
060|         self.ef  = [float(row[4]) for row in self]
061|         self.esc = [float(row[5]) for row in self]
062| 
063|         self.top_min = min(self.top)
064|         self.top_max = max(self.top)
065|         self.ac_min  = min(self.ac)
066|         self.ac_max  = max(self.ac)
067|         self.ss_min  = min(self.ss)
068|         self.ss_max  = max(self.ss)
069|         self.ef_min  = min(self.ef)
070|         self.ef_max  = max(self.ef)
071|         self.esc_min = min(self.esc)
072|         self.esc_max = max(self.esc)
073| 
074|     def fields (self):
075|         return zip(self.xs, self.fnames, self.top,self.ac, self.ss,self.ef, self.esc)
076| 
077|     def __repr__ (self):
078|         return f'<{typename(self)} @{id(self):08x}>'
079| 
080| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
081| class SummaryMX (Summary):
082|     tab_filename = path.join(BasePath, 'summary-mx.tab')
083|     html_filename = path.join(BasePath, 'summary-mx.html')
084| 
085|     def __init__ (self):
086|         super().__init__()
087| 
088|     def load (self):
089|         super().load()
090|         self.fnames = [fname[0:-1] for fname in self.fnames]
091| 
092| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
093| class SummaryXF (Summary):
094|     tab_filename = path.join(BasePath, 'summary-xf.tab')
095|     html_filename = path.join(BasePath, 'summary-xf.html')
096| 
097|     def __init__ (self):
098|         super().__init__()
099| 
100|     def load (self):
101|         super().load()
102|         self.fnames = [fname.replace('img_','') for fname in self.fnames]
103| 
104| ##================================================================================================##
105| def get_summary_instance (which):
106|     '''Return Summary instance for a given summary group.'''
107| 
108|     # Modes series...
109|     if which == 'mx': return SummaryMX()
110| 
111|     # Crossfade series...
112|     if which == 'xf': return SummaryXF()
113| 
114|     # Default...
115|     if which == 'root': return Summary()
116| 
117|     raise IndexError(f'Unknown summary key: "{which}"')
118| 
119| 
120| ##================================================================================================##
121| def do_generate_summary (*args):
122| 
123|     which = args[0] if 0<len(args) else '<null>'
124|     fpath = args[1] if 1<len(args) else ImgsPath
125|     print(f'{which=}')
126|     print(f'{fpath=}')
127| 
128|     summ = get_summary_instance(which)
129| 
130|     tab_filename = summ.tab_filename
131|     html_filename = summ.html_filename
132|     print(f'{tab_filename=}')
133|     print(f'{html_filename=}')
134|     print()
135| 
136|     fnames = listdir(fpath)
137|     buf = []
138| 
139|     for fname in fnames:
140|         filename = path.join(fpath, fname)
141|         if fname.endswith('-ESC.out'):
142|             print(filename)
143|             fin = linefile(filename)
144|             fin.load()
145| 
146|             if not fin[0].startswith('File: '):
147|                 print('Unexpected first line:')
148|                 print(fin[0])
149|                 print()
150|                 continue
151| 
152|             line = fin[1].replace('.zip', '')
153|             cols = line.split()
154|             buf.append(cols)
155|     print()
156|     if len(buf) == 0:
157|         print('No ESC files found.')
158|         return (fnames, [])
159| 
160|     sfmt = '{0:2d}: {1:<{W1}s} {2:>{W2}s} {3:>{W3}s} {4:>{W4}s} {5:>{W5}s} {6:>{W6}s}'
161|     col_widths = [0]*len(buf[0])
162| 
163|     for ix,row in enumerate(buf, start=1):
164|         for cx in range(len(row)):
165|             this_width = len(row[cx])
166|             if col_widths[cx] < this_width:
167|                 col_widths[cx] = this_width
168|     widths = {f'W{ix}':width for ix,width in enumerate(col_widths, start=1)}
169| 
170|     for ix,row in enumerate(buf, start=1):
171|         pout = sfmt.format(ix, *row, **widths)
172|         print(pout)
173|     print()
174| 
175|     fout = tabfile(tab_filename)
176|     fout.hdrs = TabFileHeaders
177|     fout.data = [[col.replace(',','') for col in row] for row in buf]
178|     fout.save()
179|     print(f'wrote: {tab_filename}')
180| 
181|     props = dict(meta=x_meta, css=style_sheets, csstxt=style_text)
182|     pag = WebPage('ESC Summary', **props)
183| 
184|     pag.add('<table>')
185|     pag.add('<thead>')
186|     pag.add('<tr>')
187|     pag.add(f'<td>#</td>')
188|     for hdr in TabFileHeaders:
189|         pag.add(f'<th>{hdr}</th>')
190|     pag.add('</tr>')
191|     pag.add('</thead>')
192|     pag.add('<tbody>')
193| 
194|     nametrim = lambda s: s[:-3]
195|     tint = 1
196|     groupname = nametrim(buf[0][0])
197| 
198|     for ix,row in enumerate(buf, start=1):
199|         gn = nametrim(row[0])
200|         if gn != groupname:
201|             tint = 2 if tint==1 else 1
202|             groupname = gn
203| 
204|         pag.add('<tr>')
205|         pag.add(f'<th>{ix}</th>')
206|         pag.add(f'<td class="tint{tint} filename">{row[0]}</td>')
207|         for col in row[1:]:
208|             pag.add(f'<td class="tint{tint} number">{col}</td>')
209|         pag.add('</tr>')
210| 
211|     pag.add('</tbody>')
212|     pag.add('</table>')
213| 
214|     pag.save(html_filename)
215|     print(f'wrote: {html_filename}')
216| 
217|     return (fnames, buf)
218| 
219| ##================================================================================================##
220| def do_chart_mx (*args):
221| 
222|     # ignore args[0]
223|     fname = args[1] if 1<len(args) else 'summary-mx.png'
224|     fpath = args[2] if 2<len(args) else BasePath
225| 
226|     summ = SummaryMX()
227| 
228|     print(f'minimum-SS: {summ.ss_min}')
229|     print(f'maximum-SS: {summ.ss_max}')
230|     print()
231|     print(f'minimum-EF: {summ.ef_min}')
232|     print(f'maximum-EF: {summ.ef_max}')
233|     print()
234|     print(f'minimum-ESC: {summ.esc_min}')
235|     print(f'maximum-ESC: {summ.esc_max}')
236|     print()
237| 
238|     curr_name = None
239|     curr_state = 0
240|     curr_color = lambda: '#3366cc' if curr_state else '#cc6633'
241| 
242|     def color_function (n):
243|         nonlocal curr_name, curr_state
244| 
245|         if n[0:-3] == curr_name:
246|             return curr_color()
247| 
248|         # Change name group...
249|         curr_name = n[0:-3]
250|         curr_state = 1 if curr_state==0 else 0
251|         return curr_color()
252| 
253|     ys = [x+1 for x in summ.xs]
254|     ynames = summ.fnames
255|     xs1 = summ.ss
256|     xs2 = summ.ef
257|     cs  = [color_function(name) for name in ynames]
258|     xmax = 5.0
259| 
260|     fig, ax = plt.subplots()
261|     fig.set_figwidth(9.0)
262|     fig.set_figheight(16.0)
263|     fig.subplots_adjust(left=0.190, right=0.985, bottom=0.032, top=0.98)
264|     fig.suptitle('MX Emergence Factor & Structural Spread', y=0.997, fontsize='17', fontweight='bold')
265| 
266|     ax.set_xlabel('EF (large bars) & SS (small gray bars)', fontweight='bold')
267|     ax.set_xlim(0.0, xmax)
268|     ax.xaxis.set_major_locator(MultipleLocator(1))
269|     ax.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
270|     ax.xaxis.set_minor_locator(MultipleLocator(0.1))
271|     ax.xaxis.set_minor_formatter(NullFormatter())
272| 
273|     #ax.set_ylabel('File', color='#000000', fontweight='bold')
274|     ax.set_ylim(0, ys[-1]+1)
275|     ax.invert_yaxis()
276|     ax.yaxis.set_major_locator(FixedLocator(ys))
277|     ax.yaxis.set_major_formatter(FixedFormatter(ynames))
278|     ax.yaxis.set_minor_locator(NullLocator())
279|     ax.yaxis.set_minor_formatter(NullFormatter())
280| 
281|     ax.grid(which='major', axis='both', color='#cfcfcf', lw=1.4,ls='-',zorder=1, alpha=1.0)
282|     ax.grid(which='minor', axis='both', color='#cfcfcf', lw=0.5,ls='-',zorder=0, alpha=1.0)
283|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
284|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
285| 
286|     for tick in ax.xaxis.get_major_ticks():
287|         tick.label1.set_rotation('vertical')
288|         tick.label1.set_size(9)
289| 
290|     for tick in ax.yaxis.get_major_ticks():
291|         tick.label1.set_size(8.0)
292| 
293|     ax.barh(ys, xs2, height=0.8, color=cs       , edgecolor='#000000', linewidth=0.5, zorder=11)
294|     ax.barh(ys, xs1, height=0.3, color='#bfbfbf', edgecolor='#000000', linewidth=0.4, zorder=12)
295| 
296|     bbox = {'boxstyle':'Round,pad=0.05', 'facecolor':'#ffff00', 'edgecolor':'#000000', 'lw':0.5}
297|     props = {'color':'#000000', 'fontsize':7.5, 'zorder':51, 'alpha':0.75, 'bbox':bbox}
298|     for ix,ef_val in enumerate(summ.ef):
299|         if ef_val <= xmax:
300|             continue
301|         ax.text(xmax-0.30, ix+1.25, f'{ef_val:.3f}', **props)
302| 
303|     # Save the chart...
304|     fn = path.join(fpath,fname) if fpath else fname
305|     plt.savefig(fn)
306|     plt.close(fig)
307|     print(f'wrote: {fn}')
308|     print()
309|     return summ
310| 
311| ##================================================================================================##
312| def do_chart_xf (*args):
313|     # ignore args[0]
314|     fname = args[1] if 1<len(args) else 'summary-xf.png'
315|     fpath = args[2] if 2<len(args) else BasePath
316| 
317|     summ = SummaryXF()
318| 
319|     print(f'minimum-SS: {summ.ss_min}')
320|     print(f'maximum-SS: {summ.ss_max}')
321|     print()
322|     print(f'minimum-EF: {summ.ef_min}')
323|     print(f'maximum-EF: {summ.ef_max}')
324|     print()
325|     print(f'minimum-ESC: {summ.esc_min}')
326|     print(f'maximum-ESC: {summ.esc_max}')
327|     print()
328| 
329|     curr_name = None
330|     curr_state = 0
331|     curr_color = lambda: '#3366cc' if curr_state else '#cc6633'
332| 
333|     def color_function (n):
334|         nonlocal curr_name, curr_state
335| 
336|         if n[0:-3] == curr_name:
337|             return curr_color()
338| 
339|         # Change name group...
340|         curr_name = n[0:-3]
341|         curr_state = 1 if curr_state==0 else 0
342|         return curr_color()
343| 
344|     ys = [x+1 for x in summ.xs]
345|     ynames = summ.fnames
346|     xs1 = [n/1e4 for n in summ.esc]
347|     xs2 = summ.ef
348|     cs  = [color_function(name) for name in ynames]
349|     xmax = 6.0
350| 
351|     fig, ax = plt.subplots()
352|     fig.set_figwidth(6.0)
353|     fig.set_figheight(9.0)
354|     fig.subplots_adjust(left=0.260, right=0.985, bottom=0.060, top=0.97)
355|     fig.suptitle('XF Emergence Factor and ESC', y=0.997, fontsize='13', fontweight='bold')
356| 
357|     ax.set_xlabel('EF (large bars) & ESCĂ·10,000 (small bars)', fontweight='bold')
358|     ax.set_xlim(0.0, xmax)
359|     ax.xaxis.set_major_locator(MultipleLocator(1))
360|     ax.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
361|     ax.xaxis.set_minor_locator(MultipleLocator(0.1))
362|     ax.xaxis.set_minor_formatter(NullFormatter())
363| 
364|     #ax.set_ylabel('File', color='#000000', fontweight='bold')
365|     ax.set_ylim(0, ys[-1]+1)
366|     ax.invert_yaxis()
367|     ax.yaxis.set_major_locator(FixedLocator(ys))
368|     ax.yaxis.set_major_formatter(FixedFormatter(ynames))
369|     ax.yaxis.set_minor_locator(NullLocator())
370|     ax.yaxis.set_minor_formatter(NullFormatter())
371| 
372|     ax.grid(which='major', axis='both', color='#cfcfcf', lw=1.4,ls='-',zorder=1, alpha=1.0)
373|     ax.grid(which='minor', axis='both', color='#cfcfcf', lw=0.5,ls='-',zorder=0, alpha=1.0)
374|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
375|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
376| 
377|     for tick in ax.xaxis.get_major_ticks():
378|         tick.label1.set_rotation('vertical')
379|         tick.label1.set_size(9)
380| 
381|     for tick in ax.yaxis.get_major_ticks():
382|         tick.label1.set_size(8.0)
383| 
384|     ax.barh(ys, xs2, height=0.8, color=cs       , edgecolor='#000000', linewidth=0.5, zorder=11)
385|     ax.barh(ys, xs1, height=0.3, color='#3f3f3f', edgecolor='#000000', linewidth=0.4, zorder=12)
386| 
387|     bbox = {'boxstyle':'Round,pad=0.2', 'facecolor':'#ffff00', 'edgecolor':'#000000', 'lw':0.5}
388|     toobig = [(ix,v) for ix,v in enumerate(xs1) if xmax < v]
389|     props = {'color':'#000000', 'backgroundcolor':'#ffff00', 'fontsize':8.5, 'zorder':51, 'alpha':0.75, 'bbox':bbox}
390|     for ix,val in toobig:
391|         ax.text(xmax-0.70, ix+0.75, f'{val*1e4:,.0f}', **props)
392| 
393|     #bbox = {'boxstyle':'Round,pad=0.05', 'facecolor':'#ffff00', 'edgecolor':'#000000', 'lw':0.5}
394|     #props = {'color':'#000000', 'fontsize':8.5, 'zorder':51, 'alpha':0.75, 'bbox':bbox}
395|     #for ix,ef_val in enumerate(summ.ef):
396|     # if ef_val <= xmax:
397|     # continue
398|     # ax.text(xmax-0.35, ix+1.15, f'{ef_val:.3f}', **props)
399| 
400|     # Save the chart...
401|     fn = path.join(fpath,fname) if fpath else fname
402|     plt.savefig(fn)
403|     plt.close(fig)
404|     print(f'wrote: {fn}')
405|     print()
406|     return summ
407| 
408| ##================================================================================================##
409| def do_list_summary (*args):
410| 
411|     which = args[0] if 0<len(args) else 'default'
412| 
413|     summ = get_summary_instance(which)
414| 
415|     fwid = max(len(fname) for fname in summ.fnames)
416| 
417|     print(f'minimum-SS: {summ.ss_min}')
418|     print(f'maximum-SS: {summ.ss_max}')
419|     print()
420|     print(f'minimum-EF: {summ.ef_min}')
421|     print(f'maximum-EF: {summ.ef_max}')
422|     print()
423|     print(f'minimum-ESC: {summ.esc_min}')
424|     print(f'maximum-ESC: {summ.esc_max}')
425|     print()
426| 
427|     print('DATA:')
428|     for ix,fn,sz,ac,ss,ef,esc in summ.fields():
429|         s_sz = f'{sz:,}'
430|         s_ac = f'{ac:,}'
431|         s_esc = f'{esc:,.0f}'
432|         print(f'{fn:<{fwid}} {s_sz:>10s} {s_ac:>10s} {ss:5.3f} {ef:6.3f} {s_esc:>10s}')
433|     print()
434| 
435|     print()
436|     return ()
437| 
438| ##================================================================================================##
439| def do_test (*args):
440| 
441|     which = args[0] if 0<len(args) else 'default'
442| 
443|     summ = get_summary_instance(which)
444| 
445|     print(f'minimum-SS: {summ.ss_min}')
446|     print(f'maximum-SS: {summ.ss_max}')
447|     print()
448|     print(f'minimum-EF: {summ.ef_min}')
449|     print(f'maximum-EF: {summ.ef_max}')
450|     print()
451|     print(f'minimum-ESC: {summ.esc_min}')
452|     print(f'maximum-ESC: {summ.esc_max}')
453|     #print(f'{}')
454|     print()
455| 
456|     print()
457|     return ()
458| 
459| 
460| ##================================================================================================##
461| def main (cmd, *args):
462|     print(f'command: "{cmd}"')
463|     print()
464|     if cmd == 'make': return do_generate_summary(*args)
465|     if cmd == 'c:mx': return do_chart_mx(*args)
466|     if cmd == 'c:xf': return do_chart_xf(*args)
467|     if cmd == 'list': return do_list_summary(*args)
468|     if cmd == 'test': return do_test(*args)
469|     return rv
470| ####################################################################################################
471| if __name__ == '__main__':
472|     print(argv[0])
473|     print()
474|     cmd = argv[1] if 1<len(argv) else CMD
475|     etc = argv[2:] if 2<len(argv) else ETC
476|     rv = main(cmd, *etc)
477|     print()
478| ####################################################################################################
479| '''eof'''
480|