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

Last change on this file since 2460 was 2460, checked in by labetoulle, 9 years ago
  • Use an INI config file
  • reaname "gencmip6" variables
  • Property svn:executable set to *
File size: 6.1 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={0: string_to_date,
32                    1: str},
33        missing_values="nan",
34      )
35    except:
36      print("Empty file {}".format(filein))
37      exit(1)
38
39    for date, login, conso in data:
40      self.add_item(date, login, conso)
41
42  #---------------------------------------
43  def add_item(self, date, login, conso):
44    """
45    """
46    self[login] = Login(date, login, conso)
47
48  #---------------------------------------
49  def get_items(self):
50    """
51    """
52    items = (item for item in self.itervalues())
53    items = sorted(items, key=lambda item: item.login)
54
55    return items
56
57  #---------------------------------------
58  def get_items_not_null(self):
59    """
60    """
61    items = (item for item in self.itervalues()
62                   if item.conso > 0.)
63    items = sorted(items, key=lambda item: item.login)
64
65    return items
66
67
68class Login(object):
69  #---------------------------------------
70  def __init__(self, date, login, conso):
71    self.date  = date
72    self.login = login
73    self.conso = conso
74
75  #---------------------------------------
76  def __repr__(self):
77    return "{} ({:.2}h)".format(self.login, self.conso)
78
79
80########################################
81def plot_init():
82  paper_size  = np.array([29.7, 21.0])
83  fig, ax = plt.subplots(figsize=(paper_size/2.54))
84
85  return fig, ax
86
87
88########################################
89def plot_data(ax, ycoord, ylabels, consos):
90  """
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 get_arguments():
123  parser = ArgumentParser()
124  parser.add_argument("-v", "--verbose", action="store_true",
125                      help="Verbose mode")
126  parser.add_argument("-f", "--full", action="store_true",
127                      help="plot all the logins" +
128                           " (default: plot only non-zero)")
129  parser.add_argument("-s", "--show", action="store_true",
130                      help="interactive mode")
131  parser.add_argument("-d", "--dods", action="store_true",
132                      help="copy output on dods")
133
134  return parser.parse_args()
135
136
137########################################
138if __name__ == '__main__':
139
140  # .. Initialization ..
141  # ====================
142  # ... Command line arguments ...
143  # ------------------------------
144  args = get_arguments()
145  if args.verbose:
146    print(args)
147
148  # ... Turn interactive mode off ...
149  # ---------------------------------
150  if not args.show:
151    import matplotlib
152    matplotlib.use('Agg')
153
154  import matplotlib.pyplot as plt
155  # from matplotlib.backends.backend_pdf import PdfPages
156
157  if not args.show:
158    plt.ioff()
159
160  # ... Files and directories ...
161  # -----------------------------
162  project_name, DIR, OUT = parse_config("bin/config.ini")
163
164  (file_param, file_utheo, file_data) = \
165      get_input_files(DIR["SAVEDATA"],
166                      [OUT["PARAM"], OUT["UTHEO"], OUT["LOGIN"]])
167
168  img_name = "login"
169  today = os.path.basename(file_param).strip(OUT["PARAM"])
170
171  if args.verbose:
172    print(file_param)
173    print(file_utheo)
174    print(file_data)
175    print(img_name)
176    print(today)
177
178  # .. Get project info ..
179  # ======================
180  projet = Project()
181  projet.fill_data(file_param)
182  projet.get_date_init(file_utheo)
183
184  # .. Fill in data dict ..
185  # =======================
186  # ... Initialization ...
187  # ----------------------
188  logins = LoginDict()
189  logins.fill_data(file_data)
190
191  # .. Extract data depending on C.L. arguments ..
192  # ==============================================
193  if args.full:
194    selected_items = logins.get_items()
195  else:
196    selected_items = logins.get_items_not_null()
197
198  if args.verbose:
199    for login in selected_items:
200      print(login)
201
202  # .. Compute data to be plotted ..
203  # ================================
204  nb_items = len(selected_items)
205
206  ycoord  = np.linspace(1, nb_items, num=nb_items)
207  ylabels = [item.login for item in selected_items]
208  consos  = np.array([item.conso for item in selected_items],
209                      dtype=float)
210  date = selected_items[0].date
211
212  # .. Plot stuff ..
213  # ================
214  # ... Initialize figure ...
215  # -------------------------
216  (fig, ax) = plot_init()
217
218  # ... Plot data ...
219  # -----------------
220  plot_data(ax, ycoord, ylabels, consos)
221
222  # ... Tweak figure ...
223  # --------------------
224  title = "Consommation {} par login\n{:%d/%m/%Y}".format(
225    projet.project.upper(),
226    date
227  )
228  plot_config(ax, ycoord, ylabels, title)
229
230  # ... Save figure ...
231  # -------------------
232  img_in  = os.path.join(DIR["PLOT"], "{}.pdf".format(img_name))
233  img_out = os.path.join(DIR["SAVEPLOT"],
234                         "{}_{}.pdf".format(img_name, today))
235
236  plot_save(img_in, img_out, title, DIR)
237
238  # ... Publish figure on dods ...
239  # ------------------------------
240  if args.dods:
241    dods_cp(img_in, DIR)
242
243  if args.show:
244    plt.show()
245
246  exit(0)
247
Note: See TracBrowser for help on using the repository browser.