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

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

allow two sub-allocation periods, part 1

  • 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 unicode(x).isdecimal():
103    x = x + "o"
104
105  (size, unit) = (float(x[:-1]), x[-1])
106
107  return SizeUnit(size, unit)
108
109
110########################################
111def string_to_float(x):
112  """
113  """
114  return float(x.strip("h"))
115
116
117########################################
118def string_to_date(ssaammjj, fmt="%Y-%m-%d"):
119  """
120  """
121  return dt.datetime.strptime(ssaammjj, fmt)
122
123
124########################################
125def string_to_datetime(string, fmt="%Y-%m-%d-%H:%M"):
126  """
127  """
128  return dt.datetime.strptime(string, fmt)
129
130
131# ########################################
132# def date_to_string(dtdate, fmt="%Y-%m-%d"):
133#   """
134#   """
135#   return dt.datetime.strftime(dtdate, fmt)
136
137
138########################################
139def where_we_run():
140
141  res = ""
142  if "curie" in socket.getfqdn():
143    res = "curie"
144  elif "ipsl" in socket.getfqdn():
145    res = "ipsl"
146  else:
147    res = "default"
148
149  return res
150
151
152########################################
153def get_last_file(dir_data, pattern):
154  """
155  """
156  current_dir = os.getcwd()
157  os.chdir(dir_data)
158  filename = pattern + "*"
159  file_list = glob.glob(os.path.join(dir_data, filename))
160  if file_list:
161    res = sorted(file_list)[-1]
162  else:
163    res = None
164  os.chdir(current_dir)
165  return res
166
167
168########################################
169def get_input_files(dir_data, file_list, date=None):
170  """
171  """
172  res = []
173
174  for filebase in file_list:
175    if date:
176      filename = "_".join((filebase, date))
177    else:
178      filename = filebase
179
180    res.append(get_last_file(dir_data, filename))
181
182  if None in res:
183    print("\nMissing one or more input files, we stop.")
184    for f_in, f_out in zip(file_list, res):
185      print("=> {}: {}".format(f_in, f_out))
186    exit(1)
187
188  return res
189
190
191########################################
192def plot_save(img_in, img_out, title, DIR):
193  """
194  """
195  from matplotlib.backends.backend_pdf import PdfPages
196
197  dpi = 200.
198
199  # img_in  = os.path.join(DIR["PLOT"], "{}.pdf".format(img_name))
200
201  with PdfPages(img_in) as pdf:
202    pdf.savefig(dpi=dpi)
203
204    # pdf file's metadata
205    d = pdf.infodict()
206    d["Title"]   = title
207    d["Author"]  = os.path.basename(__file__)
208    # d["Subject"] = "Time spent over specific commands during create_ts \
209    #                 jobs at IDRIS and four configurations at TGCC"
210    # d["Keywords"] = "bench create_ts TGCC IDRIS ncrcat"
211    # d["CreationDate"] = dt.datetime(2009, 11, 13)
212    # d["ModDate"] = dt.datetime.today()
213
214  if os.path.isdir(DIR["SAVEPLOT"]):
215    # img_out = os.path.join(DIR["SAVEPLOT"],
216    #                        "{}_{}.pdf".format(img_name, suffix))
217    shutil.copy(img_in, img_out)
218
219
220########################################
221class Project(object):
222
223  #---------------------------------------
224  def __init__(self, project_name):
225    self.project   = project_name
226    self.date_init = ""
227    self.deadline  = ""
228    self.alloc     = 0
229
230  #---------------------------------------
231  def fill_data(self, filein):
232    import json
233    dico = json.load(open(filein, "r"))
234    self.deadline = string_to_date(dico["deadline"]) + \
235                    dt.timedelta(days=-1)
236    self.alloc = dico["alloc"]
237
238  #---------------------------------------
239  def get_date_init(self, filein):
240    data = np.genfromtxt(
241      filein,
242      skip_header=1,
243      converters={
244        0: string_to_date,
245        1: string_to_percent,
246      },
247      missing_values="nan",
248    )
249    dates, utheos = zip(*data)
250
251    x2 = len(utheos) - 1
252    for nb, elem in enumerate(utheos[-2::-1]):
253      if elem >= utheos[x2]:
254        break
255      x1 = x2 - nb + 1
256
257    m = np.array([[x1, 1.], [x2, 1.]])
258    n = np.array([utheos[x1], utheos[x2]])
259
260    poly_ok = True
261    try:
262      polynome = np.poly1d(np.linalg.solve(m, n))
263    except np.linalg.linalg.LinAlgError:
264      poly_ok = False
265
266    if poly_ok:
267      delta = x1 - int(round(polynome.r[0]))
268      d1 = dates[x1]
269      self.date_init = d1 - dt.timedelta(days=delta)
270    else:
271      self.date_init = dt.datetime(self.deadline.year, 1, 1)
272
273    delta = self.deadline - self.date_init
274    self.days = delta.days + 1
275
276
277########################################
278class SizeUnit(object):
279  #---------------------------------------
280  def __init__(self, size, unit):
281    self.size = size
282    self.unit = unit
283
284  #---------------------------------------
285  def __repr__(self):
286    return "{:6.2f}{}o".format(self.size, self.unit)
287
288  #---------------------------------------
289  def convert_size(self, unit_out):
290    """
291    """
292    prefixes = ["o", "K", "M", "G", "T", "P", "H"]
293
294    if not self.size or \
295       self.unit == unit_out:
296      size_out = self.size
297    else:
298      idx_deb = prefixes.index(self.unit)
299      idx_fin = prefixes.index(unit_out)
300      size_out = self.size
301      for i in xrange(abs(idx_fin-idx_deb)):
302        if idx_fin > idx_deb:
303          size_out = size_out / 1024
304        else:
305          size_out = size_out * 1024
306
307    return SizeUnit(size_out, unit_out)
308
309
310########################################
311if __name__ == '__main__':
312  pass
313
Note: See TracBrowser for help on using the repository browser.