source: TOOLS/ConsoGENCMIP6/bin/libconso.py @ 3734

Last change on this file since 3734 was 2842, checked in by labetoulle, 8 years ago

[concogencmip6] problem with directory size = None in store occupation analysis

  • Property svn:executable set to *
File size: 7.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
8import socket
9import os
10import os.path
11import glob
12import shutil
13import subprocess
14import datetime as dt
15import numpy as np
16import ConfigParser as cp
17
18# Application library imports
19
20
21########################################
22def dods_cp(filein, DIR):
23  """
24  """
25  if not DIR["DODS"]:
26    print("DODS directory not defined")
27    return
28
29  basefile = os.path.basename(filein)
30
31  fileout = os.path.join(DIR["DODS"], basefile)
32  filepng = os.path.join(DIR["DODS"], "img", basefile.split(".")[0] + ".png")
33
34  # Copy file
35  shutil.copy(filein, fileout)
36
37  # Convert it to png for web page
38  command = ["convert", "-density", "200", fileout, filepng]
39
40  try :
41    subprocess.call(command)
42  except Exception as rc :
43    print("Error in convert for {}:\n{}".format(fileout, rc))
44
45  return
46
47
48########################################
49def parse_config(filename):
50
51  DIR = {}
52  OUT = {}
53
54  config = cp.ConfigParser(allow_no_value=True)
55  config.optionxform = str
56  config.read(filename)
57
58  for section in ("projet", "directories", "files"):
59    if not config.has_section(section):
60      print("Missing section {} in {}, we stop".format(section, filename))
61      exit(1)
62
63  # .. Project name ..
64  # ------------------
65  section = "projet"
66  option  = "name"
67  project_name = config.get(section, option)
68
69  # ..Common directories ..
70  # -----------------------
71  section = "directories"
72  for option in config.options(section):
73    DIR[option] = config.get(section, option)
74
75    if DIR[option] and not os.path.isdir(DIR[option]):
76      print("mkdir {}".format(DIR[option]))
77      try :
78        os.makedirs(DIR[option])
79      except Exception as rc :
80        print("Could not create {}:\n{}".format(DIR[option], rc))
81
82  # ..Common files ..
83  # -----------------
84  section = "files"
85  for option in config.options(section):
86    OUT[option] = config.get(section, option)
87
88  return (project_name, DIR, OUT)
89
90
91########################################
92def string_to_percent(x):
93  """
94  """
95  return float(x.strip("%"))/100.
96
97
98########################################
99def string_to_size_unit(x):
100  """
101  """
102  if x == "None":
103    x = "0o"
104
105  if unicode(x).isdecimal():
106    x = x + "o"
107
108  (size, unit) = (float(x[:-1]), x[-1])
109
110  return SizeUnit(size, unit)
111
112
113########################################
114def string_to_float(x):
115  """
116  """
117  return float(x.strip("h"))
118
119
120########################################
121def string_to_date(ssaammjj, fmt="%Y-%m-%d"):
122  """
123  """
124  return dt.datetime.strptime(ssaammjj, fmt)
125
126
127########################################
128def string_to_datetime(string, fmt="%Y-%m-%d-%H:%M"):
129  """
130  """
131  return dt.datetime.strptime(string, fmt)
132
133
134# ########################################
135# def date_to_string(dtdate, fmt="%Y-%m-%d"):
136#   """
137#   """
138#   return dt.datetime.strftime(dtdate, fmt)
139
140
141########################################
142def where_we_run():
143
144  res = ""
145  if "curie" in socket.getfqdn():
146    res = "curie"
147  elif "ipsl" in socket.getfqdn():
148    res = "ipsl"
149  else:
150    res = "default"
151
152  return res
153
154
155########################################
156def get_last_file(dir_data, pattern):
157  """
158  """
159  current_dir = os.getcwd()
160  os.chdir(dir_data)
161  filename = pattern + "*"
162  file_list = glob.glob(os.path.join(dir_data, filename))
163  if file_list:
164    res = sorted(file_list)[-1]
165  else:
166    res = None
167  os.chdir(current_dir)
168  return res
169
170
171########################################
172def get_input_files(dir_data, file_list, date=None):
173  """
174  """
175  res = []
176
177  for filebase in file_list:
178    if date:
179      filename = "_".join((filebase, date))
180    else:
181      filename = filebase
182
183    res.append(get_last_file(dir_data, filename))
184
185  if None in res:
186    print("\nMissing one or more input files, we stop.")
187    for f_in, f_out in zip(file_list, res):
188      print("=> {}: {}".format(f_in, f_out))
189    exit(1)
190
191  return res
192
193
194########################################
195def plot_save(img_in, img_out, title, DIR):
196  """
197  """
198  from matplotlib.backends.backend_pdf import PdfPages
199
200  dpi = 200.
201
202  # img_in  = os.path.join(DIR["PLOT"], "{}.pdf".format(img_name))
203
204  with PdfPages(img_in) as pdf:
205    pdf.savefig(dpi=dpi)
206
207    # pdf file's metadata
208    d = pdf.infodict()
209    d["Title"]   = title
210    d["Author"]  = os.path.basename(__file__)
211    # d["Subject"] = "Time spent over specific commands during create_ts \
212    #                 jobs at IDRIS and four configurations at TGCC"
213    # d["Keywords"] = "bench create_ts TGCC IDRIS ncrcat"
214    # d["CreationDate"] = dt.datetime(2009, 11, 13)
215    # d["ModDate"] = dt.datetime.today()
216
217  if os.path.isdir(DIR["SAVEPLOT"]):
218    # img_out = os.path.join(DIR["SAVEPLOT"],
219    #                        "{}_{}.pdf".format(img_name, suffix))
220    shutil.copy(img_in, img_out)
221
222
223########################################
224class Project(object):
225
226  #---------------------------------------
227  def __init__(self, project_name):
228    self.project   = project_name
229    self.date_init = ""
230    self.deadline  = ""
231    self.alloc     = 0
232
233  #---------------------------------------
234  def fill_data(self, filein):
235    import json
236    dico = json.load(open(filein, "r"))
237    self.deadline = string_to_date(dico["deadline"]) + \
238                    dt.timedelta(days=-1)
239    self.alloc = dico["alloc"]
240
241  #---------------------------------------
242  def get_date_init(self, filein):
243    data = np.genfromtxt(
244      filein,
245      skip_header=1,
246      converters={
247        0: string_to_date,
248        1: string_to_percent,
249      },
250      missing_values="nan",
251    )
252    dates, utheos = zip(*data)
253
254    x2 = len(utheos) - 1
255    x1 = x2
256    for nb, elem in enumerate(utheos[-2::-1]):
257      if elem >= utheos[x2]:
258        break
259      x1 = x2 - nb + 1
260
261    m = np.array([[x1, 1.], [x2, 1.]])
262    n = np.array([utheos[x1], utheos[x2]])
263
264    poly_ok = True
265    try:
266      polynome = np.poly1d(np.linalg.solve(m, n))
267    except np.linalg.linalg.LinAlgError:
268      poly_ok = False
269
270    if poly_ok:
271      delta = x1 - int(round(polynome.r[0]))
272      d1 = dates[x1]
273      self.date_init = d1 - dt.timedelta(days=delta)
274    else:
275      self.date_init = dt.datetime(self.deadline.year, 1, 1)
276
277    delta = self.deadline - self.date_init
278    self.days = delta.days + 1
279
280
281########################################
282class SizeUnit(object):
283  #---------------------------------------
284  def __init__(self, size, unit):
285    self.size = size
286    self.unit = unit
287
288  #---------------------------------------
289  def __repr__(self):
290    return "{:6.2f}{}o".format(self.size, self.unit)
291
292  #---------------------------------------
293  def convert_size(self, unit_out):
294    """
295    """
296    prefixes = ["o", "K", "M", "G", "T", "P", "H"]
297
298    if not self.size or \
299      self.unit == unit_out:
300      size_out = self.size
301    else:
302      idx_deb = prefixes.index(self.unit)
303      idx_fin = prefixes.index(unit_out)
304      size_out = self.size
305      for i in xrange(abs(idx_fin-idx_deb)):
306        if idx_fin > idx_deb:
307          size_out = size_out / 1024
308        else:
309          size_out = size_out * 1024
310
311    return SizeUnit(size_out, unit_out)
312
313
314########################################
315if __name__ == '__main__':
316  pass
317
Note: See TracBrowser for help on using the repository browser.