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

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

put all path definitions in a seperate file

  • Property svn:executable set to *
File size: 5.8 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
12import matplotlib.pyplot as plt
13from 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
150  return parser.parse_args()
151
152
153########################################
154if __name__ == '__main__':
155
156  # .. Initialization ..
157  # ====================
158  # ... Command line arguments ...
159  # ------------------------------
160  args = get_arguments()
161
162  # ... Files and directories ...
163  # -----------------------------
164  file_param = get_last_file(DIR["DATA"], OUT["PARAM"])
165  file_utheo = get_last_file(DIR["DATA"], OUT["UTHEO"])
166  file_login = get_last_file(DIR["DATA"], OUT["LOGIN"])
167  img_name = "bilan.pdf"
168
169  if args.verbose:
170    print(file_param)
171    print(file_utheo)
172    print(file_login)
173    print(img_name)
174
175  # .. Get project info ..
176  # ======================
177  gencmip6 = Project()
178  gencmip6.fill_data(file_param)
179  gencmip6.get_date_init(file_utheo)
180
181  # .. Fill in data dict ..
182  # =======================
183  # ... Initialization ...
184  # ----------------------
185  logins = LoginDict()
186  logins.fill_data(file_login)
187
188  # .. Extract data depending on C.L. arguments ..
189  # ==============================================
190  if args.full:
191    selected_items = logins.get_items()
192  else:
193    selected_items = logins.get_items_not_null()
194
195  if args.verbose:
196    for login in selected_items:
197      print(login)
198
199  # .. Compute data to be plotted ..
200  # ================================
201  nb_items = len(selected_items)
202
203  ycoord  = np.linspace(1, nb_items, num=nb_items)
204  ylabels = [item.login for item in selected_items]
205  consos  = np.array([item.conso for item in selected_items],
206                      dtype=float)
207  date = selected_items[0].date
208
209  # .. Plot stuff ..
210  # ================
211  # ... Initialize figure ...
212  # -------------------------
213  (fig, ax) = plot_init()
214
215  # ... Plot data ...
216  # -----------------
217  plot_data(ax, ycoord, ylabels, consos)
218
219  # ... Tweak figure ...
220  # --------------------
221  title = "Consommation {} par login\n{:%d/%m/%Y}".format(
222    gencmip6.project.upper(),
223    date
224  )
225  plot_config(ax, ycoord, ylabels, title)
226
227  # ... Save figure ...
228  # -------------------
229  plot_save(os.path.join(DIR["PLOT"], img_name))
230
231  plt.show()
232  exit()
Note: See TracBrowser for help on using the repository browser.