mlb.html


001| """Baseball Charts - All MLB Teams; All MLB Seasons.
001| 
001| Classes:
001|     parameters (dict)
001| 
001| Functions:
001|     make_chart (plot_function, **params)            ~generate chart
001|     dispatch (cmd, **kwargs)                        ~module dispatch
001| 
001| Commands:
001|     hr          do_mlb_seasons_homeruns_chart       ~MLB all-seasons HR chart
001|     so          do_mlb_seasons_strikeouts_chart     ~MLB all-seasons SO chart
001|     bb          do_mlb_seasons_walks_chart          ~MLB all-seasons BB chart
001|     all         do_all                              ~do all the above charts
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 matplotlib.pyplot as plt
007| import matplotlib.ticker as mltick
008| from logger import logger,info,debug,trace
009| from goodies import KWARG
010| import defs
011| ####################################################################################################
012| Log = logger('MLB')
013| 
014| CMND = ''
015| ARGS = {
016|     #'team':'twins',
017|     #'year':'2025',
018|     #'fpath': defs.BasePath,
019| }
020| 
021| 
022| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
023| class parameters (dict):
024|     '''Specialized dictionary for the chart maker.
024| 
024| New instances expect these required keyword arguments:
024|     title       ~title
024|     filename    ~filename (path and name)
024|     ylabel      ~Y-axis label
024|     ymax        ~y-axis maximum
024|     yt0, yt1    ~y-axis major and minor tick spacing
024| 
024| Once created, of course, any parameter can be changed:
024| 
024|     params = parameters(<keyword-params>)
024|     params['margin.left'] = 0.075
024|     params['margin.bottom'] = 0.15
024| 
024| '''

025|     def __init__ (self, **kwargs):
026|         '''New instance. Create required parameters.'''
027| 
028|         self['suptitle'] = kwargs['title']
029|         self['filename'] = kwargs['filename']
030|         self['width']    = 8.80
031|         self['height']   = 5.00
032| 
033|         self['xlabel'] = 'Years'
034|         self['xmin']   = 1900
035|         self['xmax']   = 2026
036|         self['xtick0'] =   10
037|         self['xtick1'] =    1
038| 
039|         self['ylabel'] = kwargs['ylabel']
040|         self['ymin']   = 0.0
041|         self['ymax']   = kwargs['ymax']
042|         self['ytick0'] = kwargs['yt0']
043|         self['ytick1'] = kwargs['yt1']
044| 
045|         self['margin.left']   = 0.08
046|         self['margin.right']  = 0.99
047|         self['margin.bottom'] = 0.13
048|         self['margin.top']    = 0.93
049| 
050| 
051| ##================================================================================================##
052| def make_chart (plot_function, **params):
053|     '''Generate the chart. All parameters are required! Returns filename.'''
054| 
055|     # Get the various chart parameters...
056|     suptitle = params['suptitle']
057|     filename = params['filename']
058| 
059|     xlabel = params['xlabel']
060|     xmin   = params['xmin']
061|     xmax   = params['xmax']
062|     xtick0 = params['xtick0']
063|     xtick1 = params['xtick1']
064| 
065|     ylabel = params['ylabel']
066|     ymin   = params['ymin']
067|     ymax   = params['ymax']
068|     ytick0 = params['ytick0']
069|     ytick1 = params['ytick1']
070| 
071|     width    = params['width']
072|     height   = params['height']
073|     margin_l = params['margin.left']
074|     margin_r = params['margin.right']
075|     margin_b = params['margin.bottom']
076|     margin_t = params['margin.top']
077| 
078|     # Create the chart...
079|     fig, ax = plt.subplots()
080| 
081|     fig.set_figwidth(width)
082|     fig.set_figheight(height)
083| 
084|     fig.subplots_adjust(left=margin_l, right=margin_r, bottom=margin_b, top=margin_t)
085| 
086|     fig.suptitle(suptitle, fontweight='bold')
087| 
088|     # Configure the X-axis...
089|     ax.set_xlabel(xlabel, fontweight='bold')
090|     ax.set_xlim(xmin, xmax)
091|     ax.xaxis.set_major_locator(mltick.MultipleLocator(xtick0))
092|     ax.xaxis.set_minor_locator(mltick.MultipleLocator(xtick1))
093|     ax.xaxis.set_major_formatter(mltick.FormatStrFormatter('%d'))
094| 
095|     for tick in ax.xaxis.get_major_ticks():
096|         tick.label1.set_rotation('vertical')
097|         tick.label1.set_size(9)
098| 
099|     # Configure the Y-axis...
100|     ax.set_ylabel(ylabel, fontweight='bold')
101|     ax.set_ylim(ymin, ymax)
102|     ax.yaxis.set_major_locator(mltick.MultipleLocator(ytick0))
103|     ax.yaxis.set_minor_locator(mltick.MultipleLocator(ytick1))
104|     ax.yaxis.set_major_formatter(mltick.FormatStrFormatter('%.1f'))
105| 
106|     # Configure the grid...
107|     ax.grid(which='major', axis='both', color='#7f7f7f', lw=1.2,ls='-',zorder=1, alpha=1.0)
108|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
109|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
110|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
111| 
112|     # Have the callback function plot the data...
113|     plot_function(ax)
114| 
115|     # Save the chart as a PNG file...
116|     fig.savefig(filename)
117|     defs.prn(f'wrote: {filename}')
118|     defs.prn()
119|     return filename
120| 
121| 
122| ##================================================================================================##
123| def do_mlb_seasons_homeruns_chart (**kwargs):
124|     '''CMND: Create all-MLB all-Seasons Home Runs chart.'''
125|     fpath = KWARG('fpath', defs.ImgsPath, str, kwargs)
126|     fname = KWARG('fname', 'baseball-hr.png', str, kwargs)
127|     Log.info(f'homeruns-chart:: {list(kwargs.keys())}')
128|     Log.debug(f'{fpath=}')
129|     Log.debug(f'{fname=}')
130|     Log.info()
131| 
132|     # Chart parameters...
133|     ps = parameters(
134|         title = 'MLB Home Runs since 1900',
135|         filename = path.join(fpath, fname) if fpath else fname,
136|         ylabel = 'Home Run % (HR/PA)',
137|         ymax = 5.0,
138|         yt0 = 1.0,
139|         yt1 = 0.1,
140|     )
141|     ps['margin.left'] = 0.07
142| 
143|     # Get MLB and Twins batting data...
144|     data1 = defs.CsvMlbSeasonsBatting()
145|     data2 = defs.CsvTeamSeasonsBatting('twins')
146| 
147|     # Extract from MLB data...
148|     yrs = data1.get_column_data('Year', reverse=True)
149|     pas = data1.get_column_data('PA', reverse=True)
150|     hrs = data1.get_column_data('HR', reverse=True)
151| 
152|     xs1 = [int(yr) for yr in yrs]
153|     ys1 = [100.0*(float(hr)/float(pa)) for pa,hr in zip(pas,hrs)]
154| 
155|     # Extract from Twins data...
156|     yrs = data2.get_column_data('Year', reverse=True)
157|     pas = data2.get_column_data('PA', reverse=True)
158|     hrs = data2.get_column_data('HR', reverse=True)
159| 
160|     xs2 = [int(yr) for yr in yrs]
161|     ys2 = [100.0*(float(hr)/float(pa)) for pa,hr in zip(pas,hrs)]
162| 
163|     def plot_function (ax):
164|         ax.plot(xs1,ys1, label='MLB', color='red' , lw=4.0, alpha=0.8, zorder=12)
165|         ax.plot(xs2,ys2, label='Min', color='blue', lw=2.0, alpha=0.8, zorder=11)
166|         ax.legend(loc='upper left', shadow=True)
167| 
168|     # Create the chart...
169|     return make_chart(plot_function, **ps)
170| 
171| ##================================================================================================##
172| def do_mlb_seasons_strikeouts_chart (**kwargs):
173|     '''CMND: Create all-MLB all-Seasons Strike Outs chart.'''
174|     fpath = KWARG('fpath', defs.ImgsPath, str, kwargs)
175|     fname = KWARG('fname', 'baseball-so.png', str, kwargs)
176|     Log.info(f'strikeouts-chart:: {list(kwargs.keys())}')
177|     Log.debug(f'{fpath=}')
178|     Log.debug(f'{fname=}')
179|     Log.info()
180| 
181|     # Chart parameters...
182|     ps = parameters(
183|         title = 'MLB Strikeouts since 1900',
184|         filename = path.join(fpath, fname) if fpath else fname,
185|         ylabel = 'Strikeout % (K/PA)',
186|         ymax = 30.0,
187|         yt0 = 5.0,
188|         yt1 = 1.0,
189|     )
190| 
191|     # Get MLB and Twins batting data...
192|     data1 = defs.CsvMlbSeasonsBatting()
193|     data2 = defs.CsvTeamSeasonsBatting('twins')
194| 
195|     # Extract from MLB data...
196|     yrs = data1.get_column_data('Year', reverse=True)
197|     pas = data1.get_column_data('PA', reverse=True)
198|     hrs = data1.get_column_data('SO', reverse=True)
199| 
200|     xs1 = [int(yr) for yr in yrs]
201|     ys1 = [100.0*(float(hr)/float(pa)) for pa,hr in zip(pas,hrs)]
202| 
203|     # Extract from Twins data...
204|     yrs = data2.get_column_data('Year', reverse=True)
205|     pas = data2.get_column_data('PA', reverse=True)
206|     hrs = data2.get_column_data('SO', reverse=True)
207| 
208|     xs2 = [int(yr) for yr in yrs]
209|     ys2 = [100.0*(float(hr)/float(pa)) for pa,hr in zip(pas,hrs)]
210| 
211|     def plot_function (ax):
212|         ax.plot(xs1,ys1, label='MLB', color='red' , lw=4.0, alpha=0.8, zorder=12)
213|         ax.plot(xs2,ys2, label='Min', color='blue', lw=2.0, alpha=0.8, zorder=11)
214|         ax.legend(loc='upper left', shadow=True)
215| 
216|     # Create the chart...
217|     return make_chart(plot_function, **ps)
218| 
219| ##================================================================================================##
220| def do_mlb_seasons_walks_chart (**kwargs):
221|     '''CMND: Create all-MLB all-Seasons Walks chart.'''
222|     fpath = KWARG('fpath', defs.ImgsPath, str, kwargs)
223|     fname = KWARG('fname', 'baseball-bb.png', str, kwargs)
224|     Log.info(f'walks-chart:: {list(kwargs.keys())}')
225|     Log.debug(f'{fpath=}')
226|     Log.debug(f'{fname=}')
227|     Log.info()
228| 
229|     # Chart parameters...
230|     ps = parameters(
231|         title = 'MLB Base-on-balls (walks) since 1900',
232|         filename = path.join(fpath, fname) if fpath else fname,
233|         ylabel = 'Walk % (BB/PA)',
234|         ymax = 12.0,
235|         yt0 = 1.0,
236|         yt1 = 0.25,
237|     )
238|     ps['ymin'] = 4.0
239| 
240|     # Get MLB and Twins batting data...
241|     data1 = defs.CsvMlbSeasonsBatting()
242|     data2 = defs.CsvTeamSeasonsBatting('twins')
243| 
244|     # Extract from MLB data...
245|     yrs = data1.get_column_data('Year', reverse=True)
246|     pas = data1.get_column_data('PA', reverse=True)
247|     hrs = data1.get_column_data('BB', reverse=True)
248| 
249|     # Extract from Twins data...
250|     xs1 = [int(yr) for yr in yrs]
251|     ys1 = [100.0*(float(hr)/float(pa)) for pa,hr in zip(pas,hrs)]
252| 
253|     yrs = data2.get_column_data('Year', reverse=True)
254|     pas = data2.get_column_data('PA', reverse=True)
255|     hrs = data2.get_column_data('BB', reverse=True)
256| 
257|     xs2 = [int(yr) for yr in yrs]
258|     ys2 = [100.0*(float(hr)/float(pa)) for pa,hr in zip(pas,hrs)]
259| 
260|     def plot_function (ax):
261|         ax.plot(xs1,ys1, label='MLB', color='red' , lw=4.0, alpha=0.8, zorder=12)
262|         ax.plot(xs2,ys2, label='Min', color='blue', lw=2.0, alpha=0.8, zorder=11)
263|         ax.legend(loc='upper left', shadow=True)
264| 
265|     # Create the chart...
266|     return make_chart(plot_function, **ps)
267| 
268| ##================================================================================================##
269| def do_all (**kwargs):
270|     '''Do all charts.'''
271|     Log.info(f'do-all:: {list(kwargs.keys())}')
272|     Log.info()
273| 
274|     rv1 = do_mlb_seasons_homeruns_chart(**kwargs)
275|     rv2 = do_mlb_seasons_strikeouts_chart(**kwargs)
276|     rv3 = do_mlb_seasons_walks_chart(**kwargs)
277| 
278|     return(rv1, rv2, rv3)
279| 
280| ##================================================================================================##
281| def do_test (**kwargs):
282|     '''CMND: Do a test.'''
283|     fpath = KWARG('fpath', defs.BasePath, str, kwargs)
284|     fname = KWARG('fname', 'test-{tcode}-{year}.png', str, kwargs)
285|     tcode = KWARG('team', defs.TwinsCode, str, kwargs)
286|     year  = KWARG('year', defs.DefaultYear, int, kwargs)
287|     team_name = defs.MlbTeams[tcode][2]
288|     file_name = path.join(fpath,fname) if fpath else fname
289|     file_name = file_name.format(**locals())
290|     Log.info(f'test:: {list(kwargs.keys())}')
291|     Log.debug(f'{fpath=}')
292|     Log.debug(f'{fname=}')
293|     Log.debug(f'{tcode=}')
294|     Log.debug(f'{year=}')
295|     Log.debug(f'{team_name=}')
296|     Log.debug(f'{file_name=}')
297|     Log.info()
298| 
299|     # Extract data from team's season...
300|     csv_data = defs.CsvTeamGames(tcode)
301| 
302|     Log.info()
303|     return file_name
304| 
305| ####################################################################################################
306| def dispatch (cmd, **kwargs):
307|     '''Dispatch to a module function based on CMD.'''
308|     Log.info(f'CMD: {cmd}')
309|     for kw in kwargs:
310|         Log.debug(f'argument[{kw}]: {kwargs[kw]}')
311|     Log.info()
312| 
313|     if cmd == 'hr': return do_mlb_seasons_homeruns_chart    (**kwargs)
314|     if cmd == 'so': return do_mlb_seasons_strikeouts_chart  (**kwargs)
315|     if cmd == 'bb': return do_mlb_seasons_walks_chart       (**kwargs)
316|     if cmd == 'all':  return do_all                         (**kwargs)
317|     if cmd == 'test': return do_test                        (**kwargs)
318| 
319|     return 'Nothing to do!'
320| ####################################################################################################
321| if __name__ == '__main__':
322|     print(f'autorun: {argv[0]}')
323|     Log.start(path.join(defs.BasePath,'mlb.log'))
324|     Log.level(trace())
325|     Log.info(argv[0])
326|     cmd = argv[1] if 1 < len(argv) else CMND
327|     kwargs = ARGS
328|     for a in argv[2:]:
329|         nv = a.split('=', 1)
330|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
331|         Log.debug(f'{nv[0]}: "{kwargs[nv[0]]}"')
332|     Log.info()
333|     try:
334|         print(f'CMD: {cmd}')
335|         print()
336|         obj = dispatch(cmd, **kwargs)
337|         print(obj)
338|         print()
339|         Log.info(obj)
340|         Log.info()
341|     except:
342|         etype, evalue, tb = exc_info()
343|         ts = extract_tb(tb)
344|         Log.error()
345|         Log.error(f'{etype.__name__}: {evalue!s}')
346|         Log.error()
347|         for t in ts[-5:]:
348|             Log.error(f'[{t[1]}] {t[2]} ({t[0]})')
349|             Log.error(f' {t[3]}')
350|             Log.error()
351|         raise
352|     finally:
353|         Log.end()
354| ####################################################################################################
355| '''eof'''
356|