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

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

Update title for jobs plot

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