source: TOOLS/ConsoGENCMIP6/bin/plot_login.py @ 2425

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

Save daily plots on WORK

  • Property svn:executable set to *
File size: 6.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 numpy as np
12# import matplotlib.pyplot as plt
13# from matplotlib.backends.backend_pdf import PdfPages
14
15# Application library imports
16from gencmip6 import *
17from gencmip6_path import *
18
19
20########################################
21class LoginDict(dict):
22  #---------------------------------------
23  def __init__(self):
24    self = {}
25
26  #---------------------------------------
27  def fill_data(self, filein):
28    data = np.genfromtxt(
29      filein,
30      skip_header=1,
31      converters={0: string_to_date,
32                  1: str},
33      missing_values="nan",
34    )
35
36    for date, login, conso in data:
37      self.add_item(date, login, conso)
38
39  #---------------------------------------
40  def add_item(self, date, login, conso):
41    """
42    """
43    self[login] = Login(date, login, conso)
44
45  #---------------------------------------
46  def get_items(self):
47    """
48    """
49    items = (item for item in self.itervalues())
50    items = sorted(items, key=lambda item: item.login)
51
52    return items
53
54  #---------------------------------------
55  def get_items_not_null(self):
56    """
57    """
58    items = (item for item in self.itervalues()
59                   if item.conso > 0.)
60    items = sorted(items, key=lambda item: item.login)
61
62    return items
63
64
65class Login(object):
66  #---------------------------------------
67  def __init__(self, date, login, conso):
68    self.date  = date
69    self.login = login
70    self.conso = conso
71
72  #---------------------------------------
73  def __repr__(self):
74    return "{} ({:.2}h)".format(self.login, self.conso)
75
76
77########################################
78def plot_init():
79  paper_size  = np.array([29.7, 21.0])
80  fig, ax = plt.subplots(figsize=(paper_size/2.54))
81
82  return fig, ax
83
84
85########################################
86def plot_data(ax, ycoord, ylabels, consos):
87  """
88  """
89  print(ycoord)
90  print(consos)
91
92  ax.barh(ycoord, consos, align="center", color="linen",
93          linewidth=0.2, label="conso (heures)")
94
95
96########################################
97def plot_config(ax, ycoord, ylabels, title):
98  """
99  """
100  # ... Config axes ...
101  # -------------------
102  # 1) Range
103  ymin, ymax = ycoord[0]-1, ycoord[-1]+1
104  ax.set_ylim(ymin, ymax)
105
106  # 2) Ticks labels
107  ax.ticklabel_format(axis="x", style="sci", scilimits=(0, 0))
108  ax.set_yticks(ycoord, minor=False)
109  ax.set_yticklabels(ylabels, size="x-small", fontweight="bold")
110  ax.invert_yaxis()
111
112  # 3) Define axes title
113  ax.set_xlabel("heures", fontweight="bold")
114
115  # ... Main title and legend ...
116  # -----------------------------
117  ax.set_title(title, fontweight="bold", size="large")
118  ax.legend(loc="best", fontsize="x-small", frameon=False)
119
120
121########################################
122def plot_save(img_name):
123  """
124  """
125  dpi = 200.
126
127  with PdfPages(img_name) as pdf:
128    pdf.savefig(dpi=dpi)
129
130    # pdf file's metadata
131    d = pdf.infodict()
132    d["Title"]   = "Conso GENCMIP6 par login"
133    d["Author"]  = "plot_bilan.py"
134    # d["Subject"] = "Time spent over specific commands during create_ts \
135    #                 jobs at IDRIS and four configurations at TGCC"
136    # d["Keywords"] = "bench create_ts TGCC IDRIS ncrcat"
137    # d["CreationDate"] = dt.datetime(2009, 11, 13)
138    # d["ModDate"] = dt.datetime.today()
139
140
141########################################
142def get_arguments():
143  parser = ArgumentParser()
144  parser.add_argument("-v", "--verbose", action="store_true",
145                      help="Verbose mode")
146  parser.add_argument("-f", "--full", action="store_true",
147                      help="plot all the logins" +
148                           " (default: plot only non-zero)")
149  parser.add_argument("-s", "--show", action="store_true",
150                      help="interactive mode")
151  parser.add_argument("-d", "--dods", action="store_true",
152                      help="copy output on dods")
153
154  return parser.parse_args()
155
156
157########################################
158if __name__ == '__main__':
159
160  # .. Initialization ..
161  # ====================
162  # ... Command line arguments ...
163  # ------------------------------
164  args = get_arguments()
165  if args.verbose:
166    print(args)
167
168  # ... Turn interactive mode off ...
169  # ---------------------------------
170  if not args.show:
171    import matplotlib
172    matplotlib.use('Agg')
173
174  import matplotlib.pyplot as plt
175  from matplotlib.backends.backend_pdf import PdfPages
176
177  if not args.show:
178    plt.ioff()
179
180  # ... Files and directories ...
181  # -----------------------------
182  file_param = get_last_file(DIR["SAVE"], OUT["PARAM"])
183  file_utheo = get_last_file(DIR["SAVE"], OUT["UTHEO"])
184  file_login = get_last_file(DIR["SAVE"], OUT["LOGIN"])
185  img_name = "bilan.pdf"
186
187  if args.verbose:
188    print(file_param)
189    print(file_utheo)
190    print(file_login)
191    print(img_name)
192
193  # .. Get project info ..
194  # ======================
195  gencmip6 = Project()
196  gencmip6.fill_data(file_param)
197  gencmip6.get_date_init(file_utheo)
198
199  # .. Fill in data dict ..
200  # =======================
201  # ... Initialization ...
202  # ----------------------
203  logins = LoginDict()
204  logins.fill_data(file_login)
205
206  # .. Extract data depending on C.L. arguments ..
207  # ==============================================
208  if args.full:
209    selected_items = logins.get_items()
210  else:
211    selected_items = logins.get_items_not_null()
212
213  if args.verbose:
214    for login in selected_items:
215      print(login)
216
217  # .. Compute data to be plotted ..
218  # ================================
219  nb_items = len(selected_items)
220
221  ycoord  = np.linspace(1, nb_items, num=nb_items)
222  ylabels = [item.login for item in selected_items]
223  consos  = np.array([item.conso for item in selected_items],
224                      dtype=float)
225  date = selected_items[0].date
226
227  # .. Plot stuff ..
228  # ================
229  # ... Initialize figure ...
230  # -------------------------
231  (fig, ax) = plot_init()
232
233  # ... Plot data ...
234  # -----------------
235  plot_data(ax, ycoord, ylabels, consos)
236
237  # ... Tweak figure ...
238  # --------------------
239  title = "Consommation {} par login\n{:%d/%m/%Y}".format(
240    gencmip6.project.upper(),
241    date
242  )
243  plot_config(ax, ycoord, ylabels, title)
244
245  # ... Save figure ...
246  # -------------------
247  plot_save(os.path.join(DIR["PLOT"], img_name))
248
249  # ... Publish figure on dods ...
250  # ------------------------------
251  if args.dods:
252    dods_cp(os.path.join(DIR["PLOT"], img_name))
253
254  if args.show:
255    plt.show()
256
257  exit()
Note: See TracBrowser for help on using the repository browser.