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

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

Move all scripts to the same dir to use common configuration files

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