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

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

put all path definitions in a seperate file

  • Property svn:executable set to *
File size: 7.9 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
12import matplotlib.pyplot as plt
13from 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
197  return parser.parse_args()
198
199
200########################################
201if __name__ == '__main__':
202
203  # .. Initialization ..
204  # ====================
205  # ... Command line arguments ...
206  # ------------------------------
207  args = get_arguments()
208  if args.verbose:
209    print(args)
210
211  # ... Files and directories ...
212  # -----------------------------
213  file_param = get_last_file(DIR["DATA"], OUT["PARAM"])
214  file_utheo = get_last_file(DIR["DATA"], OUT["UTHEO"])
215  file_store = get_last_file(DIR["DATA"], OUT["STORE"])
216  img_name = "bilan.pdf"
217
218  if args.verbose:
219    print(file_param)
220    print(file_utheo)
221    print(file_store)
222    print(img_name)
223
224  # .. Get project info ..
225  # ======================
226  gencmip6 = Project()
227  gencmip6.fill_data(file_param)
228  gencmip6.get_date_init(file_utheo)
229
230  # .. Fill in data dict ..
231  # =======================
232  stores = StoreDict()
233  stores.fill_data(file_store)
234
235  # .. Extract data depending on C.L. arguments ..
236  # ==============================================
237  if args.full:
238    selected_items = stores.get_items()
239  else:
240    selected_items = stores.get_items_by_name(args.pattern)
241
242  if args.verbose:
243    for item in selected_items:
244      print(
245        "{:8s} {:%F} {} {:>18s} {} ".format(
246          item.login,
247          item.date,
248          item.dirsize,
249          item.dirsize.convert_size("K"),
250          item.dirname,
251        )
252      )
253
254  # .. Compute data to be plotted ..
255  # ================================
256  ylabels = [item.login for item in selected_items]
257  values  = np.array([item.dirsize.convert_size("T").size
258                          for item in selected_items],
259                     dtype=float)
260  dirnames = [item.dirname for item in selected_items]
261  date = selected_items[0].date
262
263  nb_items = len(ylabels)
264  coords  = np.linspace(1, nb_items, num=nb_items)
265
266  # .. Plot stuff ..
267  # ================
268  # ... Initialize figure ...
269  # -------------------------
270  (fig, ax) = plot_init()
271
272  # ... Plot data ...
273  # -----------------
274  plot_data(ax, coords, ylabels, values)
275
276  # ... Tweak figure ...
277  # --------------------
278  title = "Occupation {} de STORE par login\n{:%d/%m/%Y}".format(
279    gencmip6.project.upper(),
280    date
281  )
282  plot_config(ax, coords, ylabels, dirnames, title,
283              SizeUnit(np.sum(values), "T"))
284
285  # ... Save figure ...
286  # -------------------
287  plot_save(os.path.join(DIR["PLOT"], img_name))
288
289  plt.show()
290  exit()
Note: See TracBrowser for help on using the repository browser.