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

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

add minor ticks

  • Property svn:executable set to *
File size: 6.5 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 plot_init():
84  paper_size  = np.array([29.7, 21.0])
85  fig, ax = plt.subplots(figsize=(paper_size/2.54))
86
87  return fig, ax
88
89
90########################################
91def plot_data(ax, ycoord, ylabels, consos):
92  """
93  """
94  ax.barh(ycoord, consos, align="center", color="linen",
95          linewidth=0.2, label="conso (heures)")
96
97
98########################################
99def plot_config(ax, ycoord, ylabels, title):
100  """
101  """
102  from matplotlib.ticker import AutoMinorLocator
103
104  # ... Config axes ...
105  # -------------------
106  # 1) Range
107  ymin, ymax = ycoord[0]-1, ycoord[-1]+1
108  ax.set_ylim(ymin, ymax)
109
110  # 2) Ticks labels
111  ax.ticklabel_format(axis="x", style="sci", scilimits=(0, 0))
112  ax.set_yticks(ycoord, minor=False)
113  ax.set_yticklabels(ylabels, size="x-small", fontweight="bold")
114  ax.invert_yaxis()
115
116  minor_locator = AutoMinorLocator()
117  ax.xaxis.set_minor_locator(minor_locator)
118
119  # 3) Define axes title
120  ax.set_xlabel("heures", fontweight="bold")
121
122  # ... Main title and legend ...
123  # -----------------------------
124  ax.set_title(title, fontweight="bold", size="large")
125  ax.legend(loc="best", fontsize="x-small", frameon=False)
126
127
128########################################
129def get_arguments():
130  parser = ArgumentParser()
131  parser.add_argument("-v", "--verbose", action="store_true",
132                      help="verbose mode")
133  parser.add_argument("-f", "--full", action="store_true",
134                      help="plot all the logins" +
135                           " (default: plot only non-zero)")
136  parser.add_argument("-s", "--show", action="store_true",
137                      help="interactive mode")
138  parser.add_argument("-d", "--dods", action="store_true",
139                      help="copy output on dods")
140
141  return parser.parse_args()
142
143
144########################################
145if __name__ == '__main__':
146
147  # .. Initialization ..
148  # ====================
149  # ... Command line arguments ...
150  # ------------------------------
151  args = get_arguments()
152
153  # ... Turn interactive mode off ...
154  # ---------------------------------
155  if not args.show:
156    import matplotlib
157    matplotlib.use('Agg')
158
159  import matplotlib.pyplot as plt
160  # from matplotlib.backends.backend_pdf import PdfPages
161
162  if not args.show:
163    plt.ioff()
164
165  # ... Files and directories ...
166  # -----------------------------
167  project_name, DIR, OUT = parse_config("bin/config.ini")
168
169  (file_param, file_utheo, file_data) = \
170      get_input_files(DIR["SAVEDATA"],
171                      [OUT["PARAM"], OUT["UTHEO"], OUT["LOGIN"]])
172
173  img_name = os.path.splitext(
174               os.path.basename(__file__)
175             )[0].replace("plot_", "")
176
177  today = os.path.basename(file_param).strip(OUT["PARAM"])
178
179  if args.verbose:
180    fmt_str = "{:10s} : {}"
181    print(fmt_str.format("args", args))
182    print(fmt_str.format("today", today))
183    print(fmt_str.format("file_param", file_param))
184    print(fmt_str.format("file_utheo", file_utheo))
185    print(fmt_str.format("file_data", file_data))
186    print(fmt_str.format("img_name", img_name))
187
188  # .. Get project info ..
189  # ======================
190  projet = Project(project_name)
191  projet.fill_data(file_param)
192  projet.get_date_init(file_utheo)
193
194  # .. Fill in data ..
195  # ==================
196  logins = LoginDict()
197  logins.fill_data(file_data)
198
199  # .. Extract data depending on C.L. arguments ..
200  # ==============================================
201  if args.full:
202    selected_items = logins.get_items()
203  else:
204    selected_items = logins.get_items_not_null()
205
206  if args.verbose:
207    for login in selected_items:
208      print(login)
209
210  # .. Compute data to be plotted ..
211  # ================================
212  nb_items = len(selected_items)
213
214  ycoord  = np.linspace(1, nb_items, num=nb_items)
215  ylabels = [item.login for item in selected_items]
216  consos  = np.array([item.conso for item in selected_items],
217                      dtype=float)
218  date = selected_items[0].date
219
220  # .. Plot stuff ..
221  # ================
222  # ... Initialize figure ...
223  # -------------------------
224  (fig, ax) = plot_init()
225
226  # ... Plot data ...
227  # -----------------
228  plot_data(ax, ycoord, ylabels, consos)
229
230  # ... Tweak figure ...
231  # --------------------
232  title = "Consommation {} par login\n{:%d/%m/%Y}".format(
233    projet.project.upper(),
234    date
235  )
236  plot_config(ax, ycoord, ylabels, title)
237
238  # ... Save figure ...
239  # -------------------
240  img_in  = os.path.join(DIR["PLOT"], "{}.pdf".format(img_name))
241  img_out = os.path.join(DIR["SAVEPLOT"],
242                         "{}_{}.pdf".format(img_name, today))
243
244  plot_save(img_in, img_out, title, DIR)
245
246  # ... Publish figure on dods ...
247  # ------------------------------
248  if args.dods:
249    if args.verbose:
250      print("Publish figure on dods")
251    dods_cp(img_in, DIR)
252
253  if args.show:
254    plt.show()
255
256  exit(0)
257
Note: See TracBrowser for help on using the repository browser.