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

Last change on this file since 2850 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
RevLine 
[2411]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
[2413]8import socket
[2411]9import os
10import os.path
11import glob
[2421]12import shutil
[2437]13import subprocess
[2411]14import datetime as dt
15import numpy as np
[2460]16import ConfigParser as cp
[2411]17
[2421]18# Application library imports
[2411]19
[2421]20
[2411]21########################################
[2460]22def dods_cp(filein, DIR):
[2421]23  """
24  """
25  if not DIR["DODS"]:
26    print("DODS directory not defined")
27    return
28
[2437]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
[2421]35  shutil.copy(filein, fileout)
36
[2437]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
[2421]45  return
46
47
48########################################
[2460]49def parse_config(filename):
50
51  DIR = {}
52  OUT = {}
53
[2464]54  config = cp.ConfigParser(allow_no_value=True)
[2460]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):
[2464]73    DIR[option] = config.get(section, option)
[2460]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########################################
[2411]92def string_to_percent(x):
93  """
94  """
95  return float(x.strip("%"))/100.
96
97
98########################################
99def string_to_size_unit(x):
100  """
101  """
[2842]102  if x == "None":
103    x = "0o"
104
[2428]105  if unicode(x).isdecimal():
106    x = x + "o"
107
[2411]108  (size, unit) = (float(x[:-1]), x[-1])
[2428]109
[2411]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
[2431]127########################################
128def string_to_datetime(string, fmt="%Y-%m-%d-%H:%M"):
129  """
130  """
131  return dt.datetime.strptime(string, fmt)
132
133
[2411]134# ########################################
135# def date_to_string(dtdate, fmt="%Y-%m-%d"):
136#   """
137#   """
138#   return dt.datetime.strftime(dtdate, fmt)
139
140
141########################################
[2413]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########################################
[2411]156def get_last_file(dir_data, pattern):
157  """
158  """
159  current_dir = os.getcwd()
160  os.chdir(dir_data)
161  filename = pattern + "*"
[2413]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
[2411]167  os.chdir(current_dir)
[2413]168  return res
[2411]169
170
171########################################
[2717]172def get_input_files(dir_data, file_list, date=None):
[2427]173  """
174  """
175  res = []
176
[2717]177  for filebase in file_list:
178    if date:
179      filename = "_".join((filebase, date))
180    else:
181      filename = filebase
182
[2427]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########################################
[2460]195def plot_save(img_in, img_out, title, DIR):
[2427]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########################################
[2411]224class Project(object):
225
226  #---------------------------------------
[2464]227  def __init__(self, project_name):
228    self.project   = project_name
[2411]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,
[2463]246      converters={
247        0: string_to_date,
248        1: string_to_percent,
249      },
[2411]250      missing_values="nan",
251    )
252    dates, utheos = zip(*data)
253
[2717]254    x2 = len(utheos) - 1
[2842]255    x1 = x2
[2717]256    for nb, elem in enumerate(utheos[-2::-1]):
257      if elem >= utheos[x2]:
258        break
259      x1 = x2 - nb + 1
[2411]260
261    m = np.array([[x1, 1.], [x2, 1.]])
262    n = np.array([utheos[x1], utheos[x2]])
263
[2517]264    poly_ok = True
[2413]265    try:
[2517]266      polynome = np.poly1d(np.linalg.solve(m, n))
[2413]267    except np.linalg.linalg.LinAlgError:
[2517]268      poly_ok = False
[2411]269
[2517]270    if poly_ok:
[2717]271      delta = x1 - int(round(polynome.r[0]))
272      d1 = dates[x1]
273      self.date_init = d1 - dt.timedelta(days=delta)
[2413]274    else:
275      self.date_init = dt.datetime(self.deadline.year, 1, 1)
[2411]276
[2433]277    delta = self.deadline - self.date_init
278    self.days = delta.days + 1
[2411]279
[2433]280
[2411]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    """
[2428]296    prefixes = ["o", "K", "M", "G", "T", "P", "H"]
[2411]297
298    if not self.size or \
[2842]299      self.unit == unit_out:
[2411]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
[2433]317
Note: See TracBrowser for help on using the repository browser.