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