source: TOOLS/ConsoGENCMIP6/bin/plot_jobs.py @ 2844

Last change on this file since 2844 was 2717, checked in by labetoulle, 8 years ago

allow two sub-allocation periods, part 1

  • Property svn:executable set to *
File size: 13.4 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 libconso import *
16
17
18########################################
19class DataDict(dict):
20  #---------------------------------------
21  def __init__(self):
22    self = {}
23
24  #---------------------------------------
25  def init_range(self, date_beg, date_end, inc=1):
26    """
27    """
28    delta = date_end - date_beg + dt.timedelta(days=1)
29
30    (deb, fin) = (0, int(delta.total_seconds() / 3600))
31
32    dates = (date_beg + dt.timedelta(hours=i)
33             for i in xrange(deb, fin, inc))
34
35    for date in dates:
36      self.add_item(date)
37
38  #---------------------------------------
39  def fill_data(self, file_list):
40    """
41    """
42    for filein in sorted(file_list):
43      try:
44        data = np.genfromtxt(
45          filein,
46          skip_header=1,
47          converters={
48            0: string_to_datetime,
49            1: float,
50            2: float,
51          },
52          missing_values="nan",
53        )
54      except Exception as rc:
55        print("Problem with file {} :\n{}".format(filein, rc))
56        exit(1)
57
58      if len(data) == 24:
59        run_mean = np.nanmean(
60            np.array([run for _, run, _ in data])
61        )
62        pen_mean = np.nanmean(
63            np.array([pen for _, _, pen in data])
64        )
65        run_std = np.nanstd(
66            np.array([run for _, run, _ in data])
67        )
68        pen_std = np.nanstd(
69            np.array([pen for _, _, pen in data])
70        )
71      else:
72        run_mean = np.nan
73        pen_mean = np.nan
74        run_std  = np.nan
75        pen_std  = np.nan
76
77      for date, run, pen in data:
78        if date.hour == 0:
79          self.add_item(
80            date,
81            run,
82            pen,
83            run_mean,
84            pen_mean,
85            run_std,
86            pen_std
87          )
88        else:
89          self.add_item(date, run, pen)
90        self[date].fill()
91
92  #---------------------------------------
93  def add_item(self, date, run=np.nan, pen=np.nan,
94               run_mean=np.nan, pen_mean=np.nan,
95               run_std=np.nan, pen_std=np.nan):
96    """
97    """
98    self[date] = Conso(
99      date,
100      run,
101      pen,
102      run_mean,
103      pen_mean,
104      run_std,
105      pen_std
106    )
107
108  #---------------------------------------
109  def get_items_in_range(self, date_beg, date_end, inc=1):
110    """
111    """
112    items = (item for item in self.itervalues()
113                   if item.date >= date_beg and
114                      item.date <= date_end)
115    items = sorted(items, key=lambda item: item.date)
116
117    return items[::inc]
118
119  #---------------------------------------
120  def get_items_in_full_range(self, inc=1):
121    """
122    """
123    items = (item for item in self.itervalues()
124                   if item.date >= projet.date_init and
125                      item.date <= projet.deadline  and
126                      item.date.hour == 0)
127    items = sorted(items, key=lambda item: item.date)
128
129    return items[::inc]
130
131  #---------------------------------------
132  def get_items(self, inc=1):
133    """
134    """
135    items = (item for item in self.itervalues()
136                   if item.isfilled())
137    items = sorted(items, key=lambda item: item.date)
138
139    return items[::inc]
140
141
142class Conso(object):
143  #---------------------------------------
144  def __init__(self, date, run=np.nan, pen=np.nan,
145               run_mean=np.nan, pen_mean=np.nan,
146               run_std=np.nan, pen_std=np.nan):
147
148    self.date     = date
149    self.run      = run
150    self.pen      = pen
151    self.run_mean = run_mean
152    self.pen_mean = pen_mean
153    self.run_std  = run_std
154    self.pen_std  = pen_std
155    self.filled   = False
156
157  #---------------------------------------
158  def __repr__(self):
159    return "R{:.0f} ({:.0f}/{:.0f}) P{:.0f} ({:.0f}/{:.0f})".format(
160      self.run,
161      self.run_mean,
162      self.run_std,
163      self.pen,
164      self.pen_mean,
165      self.pen_std,
166    )
167
168  #---------------------------------------
169  def isfilled(self):
170    return self.filled
171
172  #---------------------------------------
173  def fill(self):
174    self.filled = True
175
176
177########################################
178def plot_init():
179  paper_size  = np.array([29.7, 21.0])
180  fig, ax = plt.subplots(figsize=(paper_size/2.54))
181
182  return fig, ax
183
184
185########################################
186def plot_data(ax, xcoord, dates, run_jobs, pen_jobs, run_std, pen_std):
187  """
188  """
189  line_width = 0.
190  width = 1.05
191
192  ax.bar(
193    xcoord, run_jobs, width=width, yerr=run_std/2.,
194    linewidth=line_width, align="center",
195    color="lightgreen", ecolor="green", antialiased=True,
196    label="jobs running"
197  )
198  ax.bar(
199    xcoord, pen_jobs, bottom=run_jobs, width=width,
200    linewidth=line_width, align="center",
201    color="firebrick", antialiased=True,
202    label="jobs pending"
203  )
204  # ax.step(
205  #   xcoord, run_jobs, where="mid",
206  #   linewidth=1, color="black", label="jobs running"
207  # )
208  # ax.step(
209  #   xcoord, pen_jobs+run_jobs, where="mid",
210  #   linewidth=1, color="black", label="jobs running"
211  # )
212
213
214########################################
215def plot_config(
216  fig, ax, xcoord, dates, title, conso_per_day, conso_per_day_2
217):
218  """
219  """
220  from matplotlib.ticker import AutoMinorLocator
221
222  # ... Compute useful stuff ...
223  # ----------------------------
224  multialloc = False
225  if conso_per_day_2:
226    date_inter = projet.date_init + dt.timedelta(days=projet.days//2)
227    if projet.date_init in dates:
228      xi = dates.index(projet.date_init)
229    else:
230      xi = 0
231
232    if projet.deadline in dates:
233      xf = dates.index(projet.deadline)
234    else:
235      xf = len(dates)
236
237    if date_inter in dates:
238      xn = dates.index(date_inter)
239      yi = conso_per_day
240      yf = conso_per_day_2
241      multialloc = True
242    else:
243      if dates[-1] < date_inter:
244        xn = xf
245        yi = conso_per_day
246        yf = conso_per_day
247      elif dates[0] > date_inter:
248        xn = xi
249        yi = conso_per_day_2
250        yf = conso_per_day_2
251
252  # ... Config axes ...
253  # -------------------
254  # 1) Range
255  xmin, xmax = xcoord[0]-1, xcoord[-1]+1
256  if multialloc:
257    ymax = 4. * max(yi, yf)
258  else:
259    ymax = 4. * yi
260  ax.set_xlim(xmin, xmax)
261  ax.set_ylim(0, ymax)
262
263  # 2) Plot ideal daily consumption
264  line_color = "blue"
265  line_alpha = 0.5
266  line_label = "conso journaliÚre idéale"
267  ax.plot(
268    [xi, xn, xn, xf], [yi, yi, yf, yf],
269    color=line_color, alpha=line_alpha, label=line_label,
270  )
271
272  # 3) Ticks labels
273  (date_beg, date_end) = (dates[0], dates[-1])
274
275  if date_end - date_beg > dt.timedelta(weeks=9):
276    date_fmt = "{:%d-%m}"
277    maj_xticks = [x for x, d in zip(xcoord, dates)
278                     if d.weekday() == 0 and d.hour == 0]
279    maj_xlabs  = [date_fmt.format(d) for d in dates
280                     if d.weekday() == 0 and d.hour == 0]
281  else:
282    date_fmt = "{:%d-%m %Hh}"
283    maj_xticks = [x for x, d in zip(xcoord, dates)
284                     if d.hour == 0 or d.hour == 12]
285    maj_xlabs  = [date_fmt.format(d) for d in dates
286                     if d.hour == 0 or d.hour == 12]
287
288  ax.set_xticks(xcoord, minor=True)
289  ax.set_xticks(maj_xticks, minor=False)
290  ax.set_xticklabels(maj_xlabs, rotation="vertical", size="x-small")
291
292  minor_locator = AutoMinorLocator()
293  ax.yaxis.set_minor_locator(minor_locator)
294
295  yticks = list(ax.get_yticks())
296  yticks.append(conso_per_day)
297  if multialloc:
298    yticks.append(conso_per_day_2)
299  ax.set_yticks(yticks)
300
301
302  for x, d in zip(xcoord, dates):
303    if d.weekday() == 0 and d.hour == 0:
304      ax.axvline(x=x, color="black", linewidth=1., linestyle=":")
305
306  # 4) Define axes title
307  ax.set_ylabel("cœurs", fontweight="bold")
308  ax.tick_params(axis="y", labelsize="small")
309
310  # 5) Define plot size
311  fig.subplots_adjust(
312    left=0.08,
313    bottom=0.09,
314    right=0.93,
315    top=0.93,
316  )
317
318  # ... Main title and legend ...
319  # -----------------------------
320  fig.suptitle(title, fontweight="bold", size="large")
321  ax.legend(loc="upper right", fontsize="x-small", frameon=False)
322
323
324########################################
325def get_arguments():
326  parser = ArgumentParser()
327  parser.add_argument("-v", "--verbose", action="store_true",
328                      help="verbose mode")
329  parser.add_argument("-f", "--full", action="store_true",
330                      help="plot the whole period")
331  parser.add_argument("-i", "--increment", action="store",
332                      type=int, default=1, dest="inc",
333                      help="sampling increment")
334  parser.add_argument("-r", "--range", action="store", nargs=2,
335                      type=string_to_date,
336                      help="date range: ssaa-mm-jj ssaa-mm-jj")
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
354  # ... Constants ...
355  # -----------------
356  WEEK_NB = 3
357
358  # ... Turn interactive mode off ...
359  # ---------------------------------
360  if not args.show:
361    import matplotlib
362    matplotlib.use('Agg')
363
364  import matplotlib.pyplot as plt
365  # from matplotlib.backends.backend_pdf import PdfPages
366
367  if not args.show:
368    plt.ioff()
369
370  # ... Files and directories ...
371  # -----------------------------
372  project_name, DIR, OUT = parse_config("bin/config.ini")
373
374  (file_param, file_utheo) = \
375      get_input_files(DIR["SAVEDATA"], [OUT["PARAM"], OUT["UTHEO"]])
376
377  file_list = glob.glob(os.path.join(DIR["SAVEDATA"],
378                                     "OUT_JOBS_PENDING_*"))
379
380  img_name = "jobs"
381
382  today   = dt.datetime.today()
383  weeknum = today.isocalendar()[1]
384
385  if args.verbose:
386    fmt_str = "{:10s} : {}"
387    print(fmt_str.format("args", args))
388    print(fmt_str.format("today", today))
389    print(fmt_str.format("file_param", file_param))
390    print(fmt_str.format("file_utheo", file_utheo))
391    print(fmt_str.format("file_list", file_list))
392    print(fmt_str.format("img_name", img_name))
393
394  # .. Get project info ..
395  # ======================
396  projet = Project(project_name)
397  projet.fill_data(file_param)
398  projet.get_date_init(file_utheo)
399
400  # .. Fill in data ..
401  # ==================
402  # ... Initialization ...
403  # ----------------------
404  bilan = DataDict()
405  bilan.init_range(projet.date_init, projet.deadline)
406  # ... Extract data from file ...
407  # ------------------------------
408  bilan.fill_data(file_list)
409
410  # .. Extract data depending on C.L. arguments ..
411  # ==============================================
412  if args.full:
413    selected_items = bilan.get_items_in_full_range(args.inc)
414  elif args.range:
415    selected_items = bilan.get_items_in_range(
416      args.range[0], args.range[1], args.inc
417    )
418  else:
419    range_end   = today
420    range_start = (
421      range_end + dt.timedelta(weeks=-WEEK_NB) - dt.timedelta(days=1)
422    )
423    selected_items = bilan.get_items_in_range(
424      range_start, range_end, args.inc
425    )
426
427  # .. Compute data to be plotted ..
428  # ================================
429  nb_items = len(selected_items)
430
431  xcoord   = np.linspace(1, nb_items, num=nb_items)
432  dates  = [item.date for item in selected_items]
433
434  if args.full:
435    run_jobs = np.array([item.run_mean for item in selected_items],
436                         dtype=float)
437    pen_jobs = np.array([item.pen_mean for item in selected_items],
438                         dtype=float)
439    run_std  = np.array([item.run_std for item in selected_items],
440                         dtype=float)
441    pen_std  = np.array([item.pen_std for item in selected_items],
442                         dtype=float)
443  else:
444    run_jobs = np.array([item.run for item in selected_items],
445                         dtype=float)
446    pen_jobs = np.array([item.pen for item in selected_items],
447                         dtype=float)
448    run_std  = np.nan
449    pen_std  = np.nan
450
451  if args.verbose:
452    for i in selected_items:
453      if not np.isnan(i.run_mean):
454        print(
455          "{} {:13.2f} {:13.2f} {:13.2f} {:13.2f}".format(
456           i.date,
457           i.run_mean, i.pen_mean,
458           i.run_std, i.pen_std
459          )
460        )
461
462  if projet.project == "gencmip6":
463    alloc1 = (1 * projet.alloc) / 3
464    alloc2 = (2 * projet.alloc) / 3
465    conso_per_day   = 2 * alloc1 / (projet.days * 24.)
466    conso_per_day_2 = 2 * alloc2 / (projet.days * 24.)
467  else:
468    conso_per_day = projet.alloc / (projet.days * 24.)
469    conso_per_day_2 = None
470
471  # .. Plot stuff ..
472  # ================
473  # ... Initialize figure ...
474  # -------------------------
475  (fig, ax) = plot_init()
476
477  # ... Plot data ...
478  # -----------------
479  plot_data(ax, xcoord, dates, run_jobs, pen_jobs, run_std, pen_std)
480
481  # ... Tweak figure ...
482  # --------------------
483  title = "Suivi des jobs {}\n({:%d/%m/%Y} - {:%d/%m/%Y})".format(
484    projet.project.upper(),
485    projet.date_init,
486    projet.deadline
487  )
488
489  plot_config(
490    fig, ax, xcoord, dates, title, conso_per_day, conso_per_day_2
491  )
492
493  # ... Save figure ...
494  # -------------------
495  img_in  = os.path.join(DIR["PLOT"], "{}.pdf".format(img_name))
496  img_out = os.path.join(DIR["SAVEPLOT"],
497                         "{}_w{:02d}.pdf".format(img_name, weeknum))
498
499  plot_save(img_in, img_out, title, DIR)
500
501  # ... Publish figure on dods ...
502  # ------------------------------
503  if args.dods:
504    dods_cp(img_in, DIR)
505
506  if args.show:
507    plt.show()
508
509  exit(0)
Note: See TracBrowser for help on using the repository browser.