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

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