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

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

[consogencmip6] data anonymization (store & logins)

  • Property svn:executable set to *
File size: 7.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
11import numpy as np
12
13# Application library imports
14from libconso import *
15
16
17########################################
18class LoginDict(dict):
19  #---------------------------------------
20  def __init__(self):
21    self = {}
22
23  #---------------------------------------
24  def fill_data(self, filein):
25    """
26    """
27    try:
28      data = np.genfromtxt(
29        filein,
30        skip_header=1,
31        converters={
32          0: string_to_date,
33          1: str,
34        },
35        missing_values="nan",
36      )
37    except:
38      print("Empty file {}".format(filein))
39      exit(1)
40
41    for date, login, conso in data:
42      self.add_item(date, login, conso)
43
44  #---------------------------------------
45  def add_item(self, date, login, conso):
46    """
47    """
48    self[login] = Login(date, login, conso)
49
50  #---------------------------------------
51  def get_items(self):
52    """
53    """
54    items = (item for item in self.itervalues())
55    items = sorted(items, key=lambda item: item.login)
56
57    return items
58
59  #---------------------------------------
60  def get_items_not_null(self):
61    """
62    """
63    items = (item for item in self.itervalues()
64                   if item.conso > 0.)
65    items = sorted(items, key=lambda item: item.login)
66
67    return items
68
69
70class Login(object):
71  #---------------------------------------
72  def __init__(self, date, login, conso):
73    self.date  = date
74    self.login = login
75    self.conso = conso
76
77  #---------------------------------------
78  def __repr__(self):
79    return "{} ({:.2}h)".format(self.login, self.conso)
80
81
82########################################
83def get_aliases(alias_file):
84
85  res = {}
86
87  if os.path.isfile(alias_file):
88    try:
89      data = np.genfromtxt(
90        os.path.join(alias_file),
91        skip_header=2,
92        converters={
93          0: str,
94          1: str,
95          2: str,
96          3: str,
97        },
98        missing_values="",
99      )
100    except Exception as rc:
101      print("Empty file {}:\n{}".format(filein, rc))
102      exit(1)
103
104  for alias, login, _, _ in data:
105    res[login] = alias
106
107  return res
108
109
110########################################
111def plot_init():
112  paper_size  = np.array([29.7, 21.0])
113  fig, ax = plt.subplots(figsize=(paper_size/2.54))
114
115  return fig, ax
116
117
118########################################
119def plot_data(ax, ycoord, ylabels, consos):
120  """
121  """
122  ax.barh(ycoord, consos, align="center", color="linen",
123          linewidth=0.2, label="conso (heures)")
124
125
126########################################
127def plot_config(fig, ax, ycoord, ylabels, title):
128  """
129  """
130  from matplotlib.ticker import AutoMinorLocator
131
132  # ... Config axes ...
133  # -------------------
134  # 1) Range
135  ymin, ymax = ycoord[0]-1, ycoord[-1]+1
136  ax.set_ylim(ymin, ymax)
137
138  # 2) Ticks labels
139  ax.ticklabel_format(axis="x", style="sci", scilimits=(0, 0))
140  ax.set_yticks(ycoord, minor=False)
141  ax.set_yticklabels(ylabels, size="xx-small", fontweight="bold")
142  ax.invert_yaxis()
143
144  minor_locator = AutoMinorLocator()
145  ax.xaxis.set_minor_locator(minor_locator)
146
147  # 3) Define axes title
148  ax.set_xlabel("heures", fontweight="bold")
149
150  # 4) Define plot size
151  fig.subplots_adjust(
152    left=0.08,
153    bottom=0.09,
154    right=0.93,
155    top=0.93,
156  )
157
158  # ... Main title and legend ...
159  # -----------------------------
160  ax.set_title(title, fontweight="bold", size="large")
161  ax.legend(loc="best", fontsize="x-small", frameon=False)
162
163
164########################################
165def get_arguments():
166  parser = ArgumentParser()
167  parser.add_argument("-v", "--verbose", action="store_true",
168                      help="verbose mode")
169  parser.add_argument("-f", "--full", action="store_true",
170                      help="plot all the logins" +
171                           " (default: plot only non-zero)")
172  parser.add_argument("-s", "--show", action="store_true",
173                      help="interactive mode")
174  parser.add_argument("-d", "--dods", action="store_true",
175                      help="copy output on dods")
176
177  return parser.parse_args()
178
179
180########################################
181if __name__ == '__main__':
182
183  # .. Initialization ..
184  # ====================
185  # ... Command line arguments ...
186  # ------------------------------
187  args = get_arguments()
188
189  # ... Turn interactive mode off ...
190  # ---------------------------------
191  if not args.show:
192    import matplotlib
193    matplotlib.use('Agg')
194
195  import matplotlib.pyplot as plt
196  # from matplotlib.backends.backend_pdf import PdfPages
197
198  if not args.show:
199    plt.ioff()
200
201  # ... Files and directories ...
202  # -----------------------------
203  project_name, DIR, OUT = parse_config("bin/config.ini")
204
205  (file_param, file_utheo, file_data) = get_input_files(
206    DIR["SAVEDATA"],
207    [OUT["PARAM"], OUT["UTHEO"], OUT["LOGIN"]]
208  )
209
210  alias_file = os.path.join(
211    "bin",
212    "alias_catalog.dat",
213  )
214
215  img_name = os.path.splitext(
216               os.path.basename(__file__)
217             )[0].replace("plot_", "")
218
219  today = os.path.basename(file_param).strip(OUT["PARAM"])
220
221  if args.verbose:
222    fmt_str = "{:10s} : {}"
223    print(fmt_str.format("args", args))
224    print(fmt_str.format("today", today))
225    print(fmt_str.format("file_param", file_param))
226    print(fmt_str.format("file_utheo", file_utheo))
227    print(fmt_str.format("file_data", file_data))
228    print(fmt_str.format("img_name", img_name))
229
230  # .. Get alias info ..
231  # ====================
232  alias_dict = get_aliases(alias_file)
233
234  # .. Get project info ..
235  # ======================
236  projet = Project(project_name)
237  projet.fill_data(file_param)
238  projet.get_date_init(file_utheo)
239
240  # .. Fill in data ..
241  # ==================
242  logins = LoginDict()
243  logins.fill_data(file_data)
244
245  # .. Extract data depending on C.L. arguments ..
246  # ==============================================
247  if args.full:
248    selected_items = logins.get_items()
249  else:
250    selected_items = logins.get_items_not_null()
251
252  if args.verbose:
253    for login in selected_items:
254      print(login)
255
256  # .. Compute data to be plotted ..
257  # ================================
258  nb_items = len(selected_items)
259
260  ycoord  = np.linspace(1, nb_items, num=nb_items)
261  ylabels = [
262    alias_dict[item.login] 
263    if item.login in alias_dict
264    else str(hash(item.login)) 
265    for item in selected_items
266  ]
267  consos  = np.array([item.conso for item in selected_items],
268                      dtype=float)
269  date = selected_items[0].date
270
271  # .. Plot stuff ..
272  # ================
273  # ... Initialize figure ...
274  # -------------------------
275  (fig, ax) = plot_init()
276
277  # ... Plot data ...
278  # -----------------
279  plot_data(ax, ycoord, ylabels, consos)
280
281  # ... Tweak figure ...
282  # --------------------
283  title = "Consommation {} par login\n{:%d/%m/%Y}".format(
284    projet.project.upper(),
285    date
286  )
287  plot_config(fig, ax, ycoord, ylabels, title)
288
289  # ... Save figure ...
290  # -------------------
291  img_in  = os.path.join(DIR["PLOT"], "{}.pdf".format(img_name))
292  img_out = os.path.join(DIR["SAVEPLOT"],
293                         "{}_{}.pdf".format(img_name, today))
294
295  plot_save(img_in, img_out, title, DIR)
296
297  # ... Publish figure on dods ...
298  # ------------------------------
299  if args.dods:
300    if args.verbose:
301      print("Publish figure on dods")
302    dods_cp(img_in, DIR)
303
304  if args.show:
305    plt.show()
306
307  exit(0)
308
Note: See TracBrowser for help on using the repository browser.