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

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

plot_store.py : plot initial volume in addition to current volume.

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