source: TOOLS/ConsoGENCMIP6/bin/plot_bilan.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: 13.3 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 datetime as dt
12import numpy as np
13
14# Application library imports
15from libconso import *
16
17
18########################################
19class DataDict(dict):
20  #---------------------------------------
21  def __init__(self):
22    self = {}
23
24  #---------------------------------------
25  def init_range(self, date_beg, date_end, inc=1):
26    """
27    """
28    delta = date_end - date_beg
29
30    (deb, fin) = (0, delta.days+1)
31
32    dates = (date_beg + dt.timedelta(days=i)
33             for i in xrange(deb, fin, inc))
34
35    for date in dates:
36      self.add_item(date)
37
38  #---------------------------------------
39  def fill_data(self, filein):
40    """
41    """
42    try:
43      data = np.genfromtxt(
44        filein,
45        skip_header=1,
46        converters={
47          0: string_to_date,
48          1: string_to_float,
49          2: string_to_percent,
50          3: string_to_percent,
51          4: string_to_float,
52          5: string_to_float,
53          6: string_to_float,
54          7: string_to_float,
55        },
56        missing_values="nan",
57      )
58    except Exception as rc:
59      print("Empty file {}:\n{}".format(filein, rc))
60      exit(1)
61
62    for date, conso, real_use, theo_use, \
63        run_mean, pen_mean, run_std, pen_std in data:
64      if date in self:
65        self.add_item(
66          date,
67          conso,
68          real_use,
69          theo_use,
70          run_mean,
71          pen_mean,
72          run_std,
73          pen_std,
74        )
75        self[date].fill()
76
77  #---------------------------------------
78  def add_item(self, date, conso=np.nan,
79               real_use=np.nan, theo_use=np.nan,
80               run_mean=np.nan, pen_mean=np.nan,
81               run_std=np.nan, pen_std=np.nan):
82    """
83    """
84    self[date] = Conso(date, conso, real_use, theo_use,
85                       run_mean, pen_mean, run_std, pen_std)
86
87  #---------------------------------------
88  def theo_equation(self):
89    """
90    """
91    (dates, theo_uses) = \
92      zip(*((item.date, item.theo_use)
93            for item in self.get_items_in_full_range()))
94
95    (idx_min, idx_max) = \
96        (np.nanargmin(theo_uses), np.nanargmax(theo_uses))
97
98    x1 = dates[idx_min].timetuple().tm_yday
99    x2 = dates[idx_max].timetuple().tm_yday
100
101    y1 = theo_uses[idx_min]
102    y2 = theo_uses[idx_max]
103
104    m = np.array([
105      [x1, 1.],
106      [x2, 1.]
107    ], dtype="float")
108    n = np.array([
109      y1,
110      y2
111    ], dtype="float")
112
113    try:
114      (a, b) = np.linalg.solve(m, n)
115    except np.linalg.linalg.LinAlgError:
116      (a, b) = (None, None)
117
118    if a and b:
119      for date in dates:
120        self[date].theo_equ = date.timetuple().tm_yday*a + b
121
122  #---------------------------------------
123  def get_items_in_range(self, date_beg, date_end, inc=1):
124    """
125    """
126    items = (item for item in self.itervalues()
127                   if item.date >= date_beg and
128                      item.date <= date_end)
129    items = sorted(items, key=lambda item: item.date)
130
131    return items[::inc]
132
133  #---------------------------------------
134  def get_items_in_full_range(self, inc=1):
135    """
136    """
137    items = (item for item in self.itervalues())
138    items = sorted(items, key=lambda item: item.date)
139
140    return items[::inc]
141
142  #---------------------------------------
143  def get_items(self, inc=1):
144    """
145    """
146    items = (item for item in self.itervalues()
147                   if item.isfilled())
148    items = sorted(items, key=lambda item: item.date)
149
150    return items[::inc]
151
152
153class Conso(object):
154  #---------------------------------------
155  def __init__(self, date, conso=np.nan,
156               real_use=np.nan, theo_use=np.nan,
157               run_mean=np.nan, pen_mean=np.nan,
158               run_std=np.nan, pen_std=np.nan):
159    self.date     = date
160    self.conso    = conso
161    self.real_use = real_use
162    self.theo_use = theo_use
163    self.theo_equ = np.nan
164    self.run_mean = run_mean
165    self.pen_mean = pen_mean
166    self.run_std  = run_std
167    self.pen_std  = pen_std
168    self.filled   = False
169
170  #---------------------------------------
171  def __repr__(self):
172    return "{:.2f} ({:.2%})".format(self.conso, self.real_use)
173
174  #---------------------------------------
175  def isfilled(self):
176    return self.filled
177
178  #---------------------------------------
179  def fill(self):
180    self.filled = True
181
182
183########################################
184def plot_init():
185  paper_size  = np.array([29.7, 21.0])
186  fig, ax_conso = plt.subplots(figsize=(paper_size/2.54))
187  ax_theo = ax_conso.twinx()
188
189  return fig, ax_conso, ax_theo
190
191
192########################################
193def plot_data(ax_conso, ax_theo, xcoord, dates,
194              consos, theo_uses, real_uses, theo_equs,
195              run_mean, pen_mean, run_std, pen_std):
196  """
197  """
198  line_style = "-"
199  if args.full:
200    line_width = 0.05
201  else:
202    # line_style = "+-"
203    line_width = 0.1
204
205  ax_conso.bar(
206    xcoord, consos, width=1, align="center", color="linen",
207    linewidth=line_width, label="conso (heures)"
208  )
209
210  ax_theo.plot(
211    xcoord, theo_equs, "--",
212    color="firebrick", linewidth=0.5,
213    solid_capstyle="round", solid_joinstyle="round"
214  )
215  ax_theo.plot(
216    xcoord, theo_uses, line_style, color="firebrick",
217    linewidth=1, markersize=8,
218    solid_capstyle="round", solid_joinstyle="round",
219    label="conso\nthéorique (%)"
220  )
221  ax_theo.plot(
222    xcoord, real_uses, line_style, color="forestgreen",
223    linewidth=1, markersize=8,
224    solid_capstyle="round", solid_joinstyle="round",
225    label="conso\nréelle (%)"
226  )
227
228
229########################################
230def plot_config(fig, ax_conso, ax_theo, xcoord, dates, title,
231                conso_per_day):
232  """
233  """
234  # ... Config axes ...
235  # -------------------
236  # 1) Range
237  conso_max = np.nanmax(consos)
238  if args.max:
239    ymax = conso_max  # + conso_max*.1
240  else:
241    ymax = 2. * conso_per_day
242
243  if conso_max > ymax:
244    ax_conso.annotate(
245      "{:.2e} heures".format(conso_max),
246      ha="left",
247      va="top",
248      fontsize="xx-small",
249      bbox=dict(boxstyle="round", fc="w", ec="0.5", color="gray",),
250      xy=(np.nanargmax(consos)+1.2, ymax),
251      textcoords="axes fraction",
252      xytext=(0.01, 0.9),
253      arrowprops=dict(
254        arrowstyle="->",
255        shrinkA=0,
256        shrinkB=0,
257        color="gray",
258      ),
259    )
260
261  xmin, xmax = xcoord[0]-1, xcoord[-1]+1
262  ax_conso.set_xlim(xmin, xmax)
263  ax_conso.set_ylim(0., ymax)
264  ax_theo.set_ylim(0., 100)
265
266  # 2) Ticks labels
267  (date_beg, date_end) = (dates[0], dates[-1])
268  date_fmt = "{:%d-%m}"
269
270  if date_end - date_beg > dt.timedelta(weeks=9):
271    maj_xticks = [x for x, d in zip(xcoord, dates)
272                     if d.weekday() == 0]
273    maj_xlabs  = [date_fmt.format(d) for d in dates
274                     if d.weekday() == 0]
275  else:
276    maj_xticks = [x for x, d in zip(xcoord, dates)]
277    maj_xlabs  = [date_fmt.format(d) for d in dates]
278
279  ax_conso.ticklabel_format(axis="y", style="sci", scilimits=(0, 0))
280
281  ax_conso.set_xticks(xcoord, minor=True)
282  ax_conso.set_xticks(maj_xticks, minor=False)
283  ax_conso.set_xticklabels(
284    maj_xlabs, rotation="vertical", size="x-small"
285  )
286
287  yticks = list(ax_conso.get_yticks())
288  yticks.append(conso_per_day)
289  ax_conso.set_yticks(yticks)
290
291  ax_theo.spines["right"].set_color("firebrick")
292  ax_theo.tick_params(colors="firebrick")
293  ax_theo.yaxis.label.set_color("firebrick")
294
295  ax_conso.axhline(y=conso_per_day, color="blue", alpha=0.5,
296                   label="conso journaliÚre\nidéale (heures)")
297
298  for x, d in zip(xcoord, dates):
299    if d.weekday() == 0 and d.hour == 0:
300      ax_conso.axvline(x=x, color="black", alpha=0.5,
301                       linewidth=0.5, linestyle=":")
302
303  # 3) Define axes title
304  for ax, label in (
305    (ax_conso, "heures"),
306    (ax_theo, "%"),
307  ):
308    ax.set_ylabel(label, fontweight="bold")
309    ax.tick_params(axis="y", labelsize="small")
310
311  # 4) Define plot size
312  fig.subplots_adjust(
313    left=0.08,
314    bottom=0.09,
315    right=0.93,
316    top=0.93,
317  )
318
319  # ... Main title and legend ...
320  # -----------------------------
321  fig.suptitle(title, fontweight="bold", size="large")
322  for ax, loc in (
323    (ax_conso, "upper left"),
324    (ax_theo, "upper right"),
325  ):
326    ax.legend(loc=loc, fontsize="x-small", frameon=False)
327
328
329########################################
330def get_arguments():
331  parser = ArgumentParser()
332  parser.add_argument("-v", "--verbose", action="store_true",
333                      help="verbose mode")
334  parser.add_argument("-f", "--full", action="store_true",
335                      help="plot the whole period")
336  parser.add_argument("-i", "--increment", action="store",
337                      type=int, default=1, dest="inc",
338                      help="sampling increment")
339  parser.add_argument("-r", "--range", action="store", nargs=2,
340                      type=string_to_date,
341                      help="date range: ssaa-mm-jj ssaa-mm-jj")
342  parser.add_argument("-m", "--max", action="store_true",
343                      help="plot with y_max = allocation")
344  parser.add_argument("-s", "--show", action="store_true",
345                      help="interactive mode")
346  parser.add_argument("-d", "--dods", action="store_true",
347                      help="copy output on dods")
348
349  return parser.parse_args()
350
351
352########################################
353if __name__ == '__main__':
354
355  # .. Initialization ..
356  # ====================
357  # ... Command line arguments ...
358  # ------------------------------
359  args = get_arguments()
360  if args.verbose:
361    print(args)
362
363  # ... Turn interactive mode off ...
364  # ---------------------------------
365  if not args.show:
366    import matplotlib
367    matplotlib.use('Agg')
368
369  import matplotlib.pyplot as plt
370  # from matplotlib.backends.backend_pdf import PdfPages
371
372  if not args.show:
373    plt.ioff()
374
375  # ... Files and directories ...
376  # -----------------------------
377  project_name, DIR, OUT = parse_config("bin/config.ini")
378
379  (file_param, file_utheo, file_data) = \
380      get_input_files(DIR["SAVEDATA"],
381                      [OUT["PARAM"], OUT["UTHEO"], OUT["BILAN"]])
382
383  img_name = "bilan"
384  today = os.path.basename(file_param).strip(OUT["PARAM"])
385
386  if args.verbose:
387    print(file_param)
388    print(file_utheo)
389    print(file_data)
390    print(img_name)
391    print(today)
392
393  # .. Get project info ..
394  # ======================
395  projet = Project()
396  projet.fill_data(file_param)
397  projet.get_date_init(file_utheo)
398
399  # .. Fill in data ..
400  # ==================
401  # ... Initialization ...
402  # ----------------------
403  bilan = DataDict()
404  bilan.init_range(projet.date_init, projet.deadline)
405  # ... Extract data from file ...
406  # ------------------------------
407  bilan.fill_data(file_data)
408  # ... Compute theoratical use from known data  ...
409  # ------------------------------------------------
410  bilan.theo_equation()
411
412  # .. Extract data depending on C.L. arguments ..
413  # ==============================================
414  if args.full:
415    selected_items = bilan.get_items_in_full_range(args.inc)
416  elif args.range:
417    selected_items = bilan.get_items_in_range(
418      args.range[0], args.range[1], args.inc
419    )
420  else:
421    selected_items = bilan.get_items(args.inc)
422
423  # .. Compute data to be plotted ..
424  # ================================
425  nb_items = len(selected_items)
426
427  xcoord    = np.linspace(1, nb_items, num=nb_items)
428  dates   = [item.date for item in selected_items]
429
430  cumul     = np.array([item.conso for item in selected_items],
431                        dtype=float)
432  consos    = []
433  consos.append(cumul[0])
434  consos[1:nb_items] = cumul[1:nb_items] - cumul[0:nb_items-1]
435  consos    = np.array(consos, dtype=float)
436
437  conso_per_day = projet.alloc / projet.days
438
439  theo_uses = np.array([100.*item.theo_use for item in selected_items],
440                       dtype=float)
441  real_uses = np.array([100.*item.real_use for item in selected_items],
442                       dtype=float)
443  theo_equs = np.array([100.*item.theo_equ for item in selected_items],
444                       dtype=float)
445
446  run_mean = np.array([item.run_mean for item in selected_items],
447                       dtype=float)
448  pen_mean = np.array([item.pen_mean for item in selected_items],
449                       dtype=float)
450  run_std  = np.array([item.run_std for item in selected_items],
451                       dtype=float)
452  pen_std  = np.array([item.pen_std for item in selected_items],
453                       dtype=float)
454
455  # .. Plot stuff ..
456  # ================
457  # ... Initialize figure ...
458  # -------------------------
459  (fig, ax_conso, ax_theo) = plot_init()
460
461  # ... Plot data ...
462  # -----------------
463  plot_data(ax_conso, ax_theo, xcoord, dates,
464            consos, theo_uses, real_uses, theo_equs,
465            run_mean, pen_mean, run_std, pen_std)
466
467  # ... Tweak figure ...
468  # --------------------
469  title = "Consommation {}\n({:%d/%m/%Y} - {:%d/%m/%Y})".format(
470    projet.project.upper(),
471    projet.date_init,
472    projet.deadline
473  )
474
475  plot_config(
476    fig, ax_conso, ax_theo, xcoord, dates, title, conso_per_day
477  )
478
479  # ... Save figure ...
480  # -------------------
481  img_in  = os.path.join(DIR["PLOT"], "{}.pdf".format(img_name))
482  img_out = os.path.join(DIR["SAVEPLOT"],
483                         "{}_{}.pdf".format(img_name, today))
484
485  plot_save(img_in, img_out, title, DIR)
486
487  # ... Publish figure on dods ...
488  # ------------------------------
489  if args.dods:
490    dods_cp(img_in, DIR)
491
492  if args.show:
493    plt.show()
494
495  exit(0)
496
Note: See TracBrowser for help on using the repository browser.