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

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

cleaning

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