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

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

typo

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