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

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

allow two sub-allocation periods, part 1

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