source: TOOLS/ConsoGENCMIP6/bin/plot_bilan_jobs.py @ 2444

Last change on this file since 2444 was 2437, checked in by labetoulle, 9 years ago

Add plot_bilan_jobs.py and do some cleaning

  • Property svn:executable set to *
File size: 13.5 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4# this must come first
5from __future__ import print_function, unicode_literals, division
6
7# standard library imports
8from argparse import ArgumentParser
9import os
10import os.path
11import datetime as dt
12import numpy as np
13
14# Application library imports
15from gencmip6 import *
16from gencmip6_path import *
17
18
19########################################
20class DataDict(dict):
21  #---------------------------------------
22  def __init__(self):
23    self = {}
24
25  #---------------------------------------
26  def init_range(self, date_beg, date_end, inc=1):
27    """
28    """
29    delta = date_end - date_beg
30
31    (deb, fin) = (0, delta.days+1)
32
33    dates = (date_beg + dt.timedelta(days=i)
34             for i in xrange(deb, fin, inc))
35
36    for date in dates:
37      self.add_item(date)
38
39  #---------------------------------------
40  def fill_data(self, filein):
41    """
42    """
43    try:
44      data = np.genfromtxt(
45        filein,
46        skip_header=1,
47        converters={
48          0: string_to_date,
49          1: string_to_float,
50          2: string_to_percent,
51          3: string_to_percent,
52          4: string_to_float,
53          5: string_to_float,
54          6: string_to_float,
55          7: string_to_float,
56        },
57        missing_values="nan",
58      )
59    except Exception as rc:
60      print("Empty file {}:\n{}".format(filein, rc))
61      exit(1)
62
63    for date, conso, real_use, theo_use, \
64        run_mean, pen_mean, run_std, pen_std in data:
65      if date in self:
66        self.add_item(
67          date,
68          conso,
69          real_use,
70          theo_use,
71          run_mean,
72          pen_mean,
73          run_std,
74          pen_std,
75        )
76        self[date].fill()
77
78  #---------------------------------------
79  def add_item(self, date, conso=np.nan,
80               real_use=np.nan, theo_use=np.nan,
81               run_mean=np.nan, pen_mean=np.nan,
82               run_std=np.nan, pen_std=np.nan):
83    """
84    """
85    self[date] = Conso(date, conso, real_use, theo_use,
86                       run_mean, pen_mean, run_std, pen_std)
87
88  #---------------------------------------
89  def theo_equation(self):
90    """
91    """
92    (dates, theo_uses) = \
93      zip(*((item.date, item.theo_use)
94            for item in self.get_items_in_full_range()))
95
96    (idx_min, idx_max) = \
97        (np.nanargmin(theo_uses), np.nanargmax(theo_uses))
98
99    x1 = dates[idx_min].timetuple().tm_yday
100    x2 = dates[idx_max].timetuple().tm_yday
101
102    y1 = theo_uses[idx_min]
103    y2 = theo_uses[idx_max]
104
105    m = np.array([
106      [x1, 1.],
107      [x2, 1.]
108    ], dtype="float")
109    n = np.array([
110      y1,
111      y2
112    ], dtype="float")
113
114    try:
115      (a, b) = np.linalg.solve(m, n)
116    except np.linalg.linalg.LinAlgError:
117      (a, b) = (None, None)
118
119    if a and b:
120      for date in dates:
121        self[date].theo_equ = date.timetuple().tm_yday*a + b
122
123  #---------------------------------------
124  def get_items_in_range(self, date_beg, date_end, inc=1):
125    """
126    """
127    items = (item for item in self.itervalues()
128                   if item.date >= date_beg and
129                      item.date <= date_end)
130    items = sorted(items, key=lambda item: item.date)
131
132    return items[::inc]
133
134  #---------------------------------------
135  def get_items_in_full_range(self, inc=1):
136    """
137    """
138    items = (item for item in self.itervalues())
139    items = sorted(items, key=lambda item: item.date)
140
141    return items[::inc]
142
143  #---------------------------------------
144  def get_items(self, inc=1):
145    """
146    """
147    items = (item for item in self.itervalues()
148                   if item.isfilled())
149    items = sorted(items, key=lambda item: item.date)
150
151    return items[::inc]
152
153
154class Conso(object):
155  #---------------------------------------
156  def __init__(self, date, conso=np.nan,
157               real_use=np.nan, theo_use=np.nan,
158               run_mean=np.nan, pen_mean=np.nan,
159               run_std=np.nan, pen_std=np.nan):
160    self.date     = date
161    self.conso    = conso
162    self.real_use = real_use
163    self.theo_use = theo_use
164    self.theo_equ = np.nan
165    self.run_mean = run_mean
166    self.pen_mean = pen_mean
167    self.run_std  = run_std
168    self.pen_std  = pen_std
169    self.filled   = False
170
171  #---------------------------------------
172  def __repr__(self):
173    return "{:.2f} ({:.2%})".format(self.conso, self.real_use)
174
175  #---------------------------------------
176  def isfilled(self):
177    return self.filled
178
179  #---------------------------------------
180  def fill(self):
181    self.filled = True
182
183
184########################################
185def plot_init():
186  paper_size  = np.array([29.7, 21.0])
187  fig, (ax_conso, ax_jobs) = plt.subplots(
188    nrows=2,
189    ncols=1,
190    sharex=True,
191    squeeze=True,
192    figsize=(paper_size/2.54)
193  )
194  ax_theo = ax_conso.twinx()
195
196  return fig, ax_conso, ax_theo, ax_jobs
197
198
199########################################
200def plot_data(ax_conso, ax_theo, ax_jobs, xcoord, dates,
201              consos, theo_uses, real_uses, theo_equs,
202              run_mean, pen_mean, run_std, pen_std):
203  """
204  """
205  line_style = "-"
206  if args.full:
207    line_width = 0.05
208  else:
209    # line_style = "+-"
210    line_width = 0.1
211
212  ax_conso.bar(xcoord, consos, width=1, align="center", color="linen",
213               linewidth=line_width, label="conso (heures)")
214
215  ax_theo.plot(xcoord, theo_equs, "--",
216               color="firebrick", linewidth=0.5,
217               solid_capstyle="round", solid_joinstyle="round")
218  ax_theo.plot(xcoord, theo_uses, line_style, color="firebrick",
219               linewidth=1, markersize=8,
220               solid_capstyle="round", solid_joinstyle="round",
221               label="conso théorique (%)")
222  ax_theo.plot(xcoord, real_uses, line_style, color="forestgreen",
223               linewidth=1, markersize=8,
224               solid_capstyle="round", solid_joinstyle="round",
225               label="conso réelle (%)")
226
227  line_width = 0.
228  width = 1.05
229
230  ax_jobs.bar(xcoord, run_mean, width=width, align="center",
231              # yerr=run_std/2, ecolor="green",
232              color="lightgreen", linewidth=line_width, antialiased=True,
233              label="jobs running")
234  ax_jobs.bar(xcoord, pen_mean, bottom=run_mean, width=width, align="center",
235              # yerr=pen_std/2, ecolor="darkred",
236              color="indianred", linewidth=line_width, antialiased=True,
237              label="jobs pending")
238
239
240########################################
241def plot_config(fig, ax_conso, ax_theo, xcoord, dates, title, conso_per_day):
242  """
243  """
244  # ... Config axes ...
245  # -------------------
246  # 1) Range
247  # if args.max:
248  #   ymax = gencmip6.alloc
249  # else:
250  #   ymax = np.nanmax(consos) + np.nanmax(consos)*.1
251
252  xmin, xmax = xcoord[0]-1, xcoord[-1]+1
253  ax_conso.set_xlim(xmin, xmax)
254  # ax_conso.set_ylim(0., ymax)
255  ax_theo.set_ylim(0., 100)
256
257  # 2) Ticks labels
258  (date_beg, date_end) = (dates[0], dates[-1])
259  date_fmt = "{:%d-%m}"
260
261  if date_end - date_beg > dt.timedelta(weeks=9):
262    maj_xticks = [x for x, d in zip(xcoord, dates)
263                     if d.weekday() == 0]
264    maj_xlabs  = [date_fmt.format(d) for d in dates
265                     if d.weekday() == 0]
266  else:
267    maj_xticks = [x for x, d in zip(xcoord, dates)]
268    maj_xlabs  = [date_fmt.format(d) for d in dates]
269
270  ax_conso.ticklabel_format(axis="y", style="sci", scilimits=(0, 0))
271
272  ax_jobs.set_xticks(xcoord, minor=True)
273  ax_jobs.set_xticks(maj_xticks, minor=False)
274  ax_jobs.set_xticklabels(maj_xlabs, rotation="vertical", size="x-small")
275
276  for ax, y, label in (
277    (ax_conso, conso_per_day, "heures"),
278    (ax_jobs, conso_per_day / 24, "cœurs"),
279  ):
280    yticks = list(ax.get_yticks())
281    yticks.append(y)
282    ax.set_yticks(yticks)
283    ax.axhline(y=y, color="blue", alpha=0.5,
284               label="conso journaliÚre\nidéale ({})".format(label))
285
286  for x, d in zip(xcoord, dates):
287    if d.weekday() == 0 and d.hour == 0:
288      for ax in (ax_conso, ax_jobs):
289        ax.axvline(x=x, color="black", alpha=0.5,
290                   linewidth=0.5, linestyle=":")
291
292  # 3) Define axes title
293  for ax, label in (
294    (ax_conso, "heures"),
295    (ax_theo, "%"),
296    (ax_jobs, "cœurs"),
297  ):
298    ax.set_ylabel(label, fontweight="bold")
299    ax.tick_params(axis="y", labelsize="small")
300
301  # 4) Define plot size
302  fig.subplots_adjust(
303    left=0.08,
304    bottom=0.09,
305    right=0.93,
306    top=0.93,
307    hspace=0.1,
308    wspace=0.1,
309  )
310
311  # ... Main title and legend ...
312  # -----------------------------
313  fig.suptitle(title, fontweight="bold", size="large")
314  for ax, loc in (
315    (ax_conso, "upper left"),
316    (ax_theo, "upper right"),
317    (ax_jobs, "upper left"),
318  ):
319    ax.legend(loc=loc, fontsize="x-small", frameon=False)
320
321
322########################################
323def get_arguments():
324  parser = ArgumentParser()
325  parser.add_argument("-v", "--verbose", action="store_true",
326                      help="verbose mode")
327  parser.add_argument("-f", "--full", action="store_true",
328                      help="plot the whole period")
329  parser.add_argument("-i", "--increment", action="store",
330                      type=int, default=1, dest="inc",
331                      help="sampling increment")
332  parser.add_argument("-r", "--range", action="store", nargs=2,
333                      type=string_to_date,
334                      help="date range: ssaa-mm-jj ssaa-mm-jj")
335  parser.add_argument("-m", "--max", action="store_true",
336                      help="plot with y_max = allocation")
337  parser.add_argument("-s", "--show", action="store_true",
338                      help="interactive mode")
339  parser.add_argument("-d", "--dods", action="store_true",
340                      help="copy output on dods")
341
342  return parser.parse_args()
343
344
345########################################
346if __name__ == '__main__':
347
348  # .. Initialization ..
349  # ====================
350  # ... Command line arguments ...
351  # ------------------------------
352  args = get_arguments()
353  if args.verbose:
354    print(args)
355
356  # ... Turn interactive mode off ...
357  # ---------------------------------
358  if not args.show:
359    import matplotlib
360    matplotlib.use('Agg')
361
362  import matplotlib.pyplot as plt
363  # from matplotlib.backends.backend_pdf import PdfPages
364
365  if not args.show:
366    plt.ioff()
367
368  # ... Files and directories ...
369  # -----------------------------
370  (file_param, file_utheo, file_data) = \
371      get_input_files(DIR["SAVEDATA"],
372                      [OUT["PARAM"], OUT["UTHEO"], OUT["BILAN"]])
373
374  img_name = "bilan_jobs"
375  today = os.path.basename(file_param).strip(OUT["PARAM"])
376
377  if args.verbose:
378    print(file_param)
379    print(file_utheo)
380    print(file_data)
381    print(img_name)
382    print(today)
383
384  # .. Get project info ..
385  # ======================
386  gencmip6 = Project()
387  gencmip6.fill_data(file_param)
388  gencmip6.get_date_init(file_utheo)
389
390  # .. Fill in data ..
391  # ==================
392  # ... Initialization ...
393  # ----------------------
394  bilan = DataDict()
395  bilan.init_range(gencmip6.date_init, gencmip6.deadline)
396  # ... Extract data from file ...
397  # ------------------------------
398  bilan.fill_data(file_data)
399  # ... Compute theoratical use from known data  ...
400  # ------------------------------------------------
401  bilan.theo_equation()
402
403  # .. Extract data depending on C.L. arguments ..
404  # ==============================================
405  if args.full:
406    selected_items = bilan.get_items_in_full_range(args.inc)
407  elif args.range:
408    selected_items = bilan.get_items_in_range(
409      args.range[0], args.range[1], args.inc
410    )
411  else:
412    selected_items = bilan.get_items(args.inc)
413
414  # .. Compute data to be plotted ..
415  # ================================
416  nb_items = len(selected_items)
417
418  xcoord    = np.linspace(1, nb_items, num=nb_items)
419  dates   = [item.date for item in selected_items]
420
421  cumul     = np.array([item.conso for item in selected_items],
422                        dtype=float)
423  consos    = []
424  consos.append(cumul[0])
425  consos[1:nb_items] = cumul[1:nb_items] - cumul[0:nb_items-1]
426  consos    = np.array(consos, dtype=float)
427
428  conso_per_day = gencmip6.alloc / gencmip6.days
429
430  theo_uses = np.array([100.*item.theo_use for item in selected_items],
431                       dtype=float)
432  real_uses = np.array([100.*item.real_use for item in selected_items],
433                       dtype=float)
434  theo_equs = np.array([100.*item.theo_equ for item in selected_items],
435                       dtype=float)
436
437  run_mean = np.array([item.run_mean for item in selected_items],
438                       dtype=float)
439  pen_mean = np.array([item.pen_mean for item in selected_items],
440                       dtype=float)
441  run_std  = np.array([item.run_std for item in selected_items],
442                       dtype=float)
443  pen_std  = np.array([item.pen_std for item in selected_items],
444                       dtype=float)
445
446  # .. Plot stuff ..
447  # ================
448  # ... Initialize figure ...
449  # -------------------------
450  (fig, ax_conso, ax_theo, ax_jobs) = plot_init()
451
452  # ... Plot data ...
453  # -----------------
454  plot_data(ax_conso, ax_theo, ax_jobs, xcoord, dates,
455            consos, theo_uses, real_uses, theo_equs,
456            run_mean, pen_mean, run_std, pen_std)
457
458  # ... Tweak figure ...
459  # --------------------
460  title = "Consommation {}\n({:%d/%m/%Y} - {:%d/%m/%Y})".format(
461    gencmip6.project.upper(),
462    gencmip6.date_init,
463    gencmip6.deadline
464  )
465
466  plot_config(fig, ax_conso, ax_theo, xcoord, dates, title, conso_per_day)
467
468  # ... Save figure ...
469  # -------------------
470  img_in  = os.path.join(DIR["PLOT"], "{}.pdf".format(img_name))
471  img_out = os.path.join(DIR["SAVEPLOT"],
472                         "{}_{}.pdf".format(img_name, today))
473
474  plot_save(img_in, img_out, title)
475
476  # ... Publish figure on dods ...
477  # ------------------------------
478  if args.dods:
479    dods_cp(img_in)
480
481  if args.show:
482    plt.show()
483
484  exit(0)
485
Note: See TracBrowser for help on using the repository browser.