source: TOOLS/ConsoGENCMIP6/bin/plot_store.py @ 2425

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

Save daily plots on WORK

  • Property svn:executable set to *
File size: 8.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# import matplotlib.pyplot as plt
13# from matplotlib.backends.backend_pdf import PdfPages
14
15# Application library imports
16from gencmip6 import *
17from gencmip6_path import *
18
19
20########################################
21class DirVolume(object):
22  #---------------------------------------
23  def __init__(self, date, login, dirname, size):
24    self.date  = date
25    self.login = login
26    self.dirname = dirname
27    self.dirsize = size
28
29  #---------------------------------------
30  def __repr__(self):
31    return "{}={}".format(self.dirname, self.dirsize)
32
33
34########################################
35class StoreDict(dict):
36  #---------------------------------------
37  def __init__(self):
38    self = {}
39
40  #---------------------------------------
41  def fill_data(self, filein):
42    data = np.genfromtxt(
43      filein,
44      skip_header=1,
45      converters={0: string_to_date,
46                  1: str,
47                  2: string_to_size_unit,
48                  3: str},
49      missing_values="nan",
50    )
51
52    for date, login, dirsize, dirname in data:
53      self.add_item(date, login, dirsize, dirname)
54
55  #---------------------------------------
56  def add_item(self, date, login, dirsize, dirname):
57    """
58    """
59    if login not in self:
60      self[login] = Login(date, login)
61    self[login].add_directory(date, login, dirsize, dirname)
62
63  #---------------------------------------
64  def get_items(self):
65    """
66    """
67    items = (subitem for item in self.itervalues()
68                     for subitem in item.listdir)
69    items = sorted(items, key=lambda item: item.login)
70
71    return items
72
73  #---------------------------------------
74  def get_items_by_name(self, pattern):
75    """
76    """
77    items = (subitem for item in self.itervalues()
78                     for subitem in item.listdir
79                      if pattern in subitem.dirname)
80    items = sorted(items, key=lambda item: item.login)
81
82    return items
83
84
85########################################
86class Login(object):
87  #---------------------------------------
88  def __init__(self, date, login):
89    self.date  = date
90    self.login = login
91    self.total = SizeUnit(0., "K")
92    self.listdir = []
93
94  #---------------------------------------
95  def __repr__(self):
96    return "{}/{:%F}: {}".format(self.login, self.date, self.listdir)
97
98  #---------------------------------------
99  def add_to_total(self, dirsize):
100    """
101    """
102    somme = self.total.convert_size("K").size + \
103            dirsize.convert_size("K").size
104    self.total = SizeUnit(somme, "K")
105
106  #---------------------------------------
107  def add_directory(self, date, login, dirsize, dirname):
108    """
109    """
110    self.listdir.append(DirVolume(date, login, dirname, dirsize))
111    self.add_to_total(dirsize)
112
113
114########################################
115def plot_init():
116  paper_size  = np.array([29.7, 21.0])
117  fig, ax = plt.subplots(figsize=(paper_size/2.54))
118
119  return fig, ax
120
121
122########################################
123def plot_data(ax, coords, ylabels, values):
124  """
125  """
126  ax.barh(coords, values, align="center", color="linen",
127          linewidth=0.2, label="volume sur STORE ($To$)")
128
129
130########################################
131def plot_config(ax, coords, ylabels, dirnames, title, tot_volume):
132  """
133  """
134  # ... Config axes ...
135  # -------------------
136  # 1) Range
137  ymin, ymax = coords[0]-1, coords[-1]+1
138  ax.set_ylim(ymin, ymax)
139
140  # 2) Ticks labels
141  ax.ticklabel_format(axis="x", style="sci", scilimits=(0, 0))
142  ax.set_yticks(coords, minor=False)
143  ax.set_yticklabels(ylabels, size="x-small", fontweight="bold")
144  ax.invert_yaxis()
145
146  xmin, xmax = ax.get_xlim()
147  xpos = xmin + (xmax-xmin)/50.
148  for (ypos, text) in zip(coords, dirnames):
149    ax.text(s=text, x=xpos, y=ypos, va="center", ha="left",
150                size="xx-small", color="gray", style="italic")
151
152  # 3) Define axes title
153  ax.set_xlabel("$To$", fontweight="bold")
154
155  # ... Main title and legend ...
156  # -----------------------------
157  ax.set_title(title, fontweight="bold", size="large")
158  ax.legend(loc="best", fontsize="x-small", frameon=False)
159
160  tot_label = "volume total = {}".format(tot_volume)
161  plt.figtext(x=0.95, y=0.93, s=tot_label, backgroundcolor="linen",
162              ha="right", va="bottom", fontsize="small")
163
164
165########################################
166def plot_save(img_name):
167  """
168  """
169  dpi = 200.
170
171  with PdfPages(img_name) as pdf:
172    pdf.savefig(dpi=dpi)
173
174    # pdf file's metadata
175    d = pdf.infodict()
176    d["Title"]   = "Occupation GENCMIP6 sur STORE par login"
177    d["Author"]  = "plot_bilan.py"
178    # d["Subject"] = "Time spent over specific commands during create_ts \
179    #                 jobs at IDRIS and four configurations at TGCC"
180    # d["Keywords"] = "bench create_ts TGCC IDRIS ncrcat"
181    # d["CreationDate"] = dt.datetime(2009, 11, 13)
182    # d["ModDate"] = dt.datetime.today()
183
184
185########################################
186def get_arguments():
187  parser = ArgumentParser()
188  parser.add_argument("-v", "--verbose", action="store_true",
189                      help="Verbose mode")
190  parser.add_argument("-f", "--full", action="store_true",
191                      help="plot all the directories in IGCM_OUT" +
192                           "(default: plot IPSLCM6 directories)")
193  parser.add_argument("-p", "--pattern", action="store",
194                      default="IPSLCM6",
195                      help="plot the whole period")
196  parser.add_argument("-s", "--show", action="store_true",
197                      help="interactive mode")
198  parser.add_argument("-d", "--dods", action="store_true",
199                      help="copy output on dods")
200
201  return parser.parse_args()
202
203
204########################################
205if __name__ == '__main__':
206
207  # .. Initialization ..
208  # ====================
209  # ... Command line arguments ...
210  # ------------------------------
211  args = get_arguments()
212  if args.verbose:
213    print(args)
214
215  # ... Turn interactive mode off ...
216  # ---------------------------------
217  if not args.show:
218    import matplotlib
219    matplotlib.use('Agg')
220
221  import matplotlib.pyplot as plt
222  from matplotlib.backends.backend_pdf import PdfPages
223
224  if not args.show:
225    plt.ioff()
226
227  # ... Files and directories ...
228  # -----------------------------
229  file_param = get_last_file(DIR["SAVE"], OUT["PARAM"])
230  file_utheo = get_last_file(DIR["SAVE"], OUT["UTHEO"])
231  file_store = get_last_file(DIR["SAVE"], OUT["STORE"])
232  img_name = "bilan.pdf"
233
234  if args.verbose:
235    print(file_param)
236    print(file_utheo)
237    print(file_store)
238    print(img_name)
239
240  # .. Get project info ..
241  # ======================
242  gencmip6 = Project()
243  gencmip6.fill_data(file_param)
244  gencmip6.get_date_init(file_utheo)
245
246  # .. Fill in data dict ..
247  # =======================
248  stores = StoreDict()
249  stores.fill_data(file_store)
250
251  # .. Extract data depending on C.L. arguments ..
252  # ==============================================
253  if args.full:
254    selected_items = stores.get_items()
255  else:
256    selected_items = stores.get_items_by_name(args.pattern)
257
258  if args.verbose:
259    for item in selected_items:
260      print(
261        "{:8s} {:%F} {} {:>18s} {} ".format(
262          item.login,
263          item.date,
264          item.dirsize,
265          item.dirsize.convert_size("K"),
266          item.dirname,
267        )
268      )
269
270  # .. Compute data to be plotted ..
271  # ================================
272  ylabels = [item.login for item in selected_items]
273  values  = np.array([item.dirsize.convert_size("T").size
274                          for item in selected_items],
275                     dtype=float)
276  dirnames = [item.dirname for item in selected_items]
277  date = selected_items[0].date
278
279  nb_items = len(ylabels)
280  coords  = np.linspace(1, nb_items, num=nb_items)
281
282  # .. Plot stuff ..
283  # ================
284  # ... Initialize figure ...
285  # -------------------------
286  (fig, ax) = plot_init()
287
288  # ... Plot data ...
289  # -----------------
290  plot_data(ax, coords, ylabels, values)
291
292  # ... Tweak figure ...
293  # --------------------
294  title = "Occupation {} de STORE par login\n{:%d/%m/%Y}".format(
295    gencmip6.project.upper(),
296    date
297  )
298  plot_config(ax, coords, ylabels, dirnames, title,
299              SizeUnit(np.sum(values), "T"))
300
301  # ... Save figure ...
302  # -------------------
303  plot_save(os.path.join(DIR["PLOT"], img_name))
304
305  # ... Publish figure on dods ...
306  # ------------------------------
307  if args.dods:
308    dods_cp(os.path.join(DIR["PLOT"], img_name))
309
310  if args.show:
311    plt.show()
312
313  exit()
Note: See TracBrowser for help on using the repository browser.