[2411] | 1 | #!/usr/bin/env python |
---|
| 2 | # -*- coding: utf-8 -*- |
---|
| 3 | |
---|
| 4 | # this must come first |
---|
| 5 | from __future__ import print_function, unicode_literals, division |
---|
| 6 | |
---|
| 7 | # standard library imports |
---|
| 8 | from argparse import ArgumentParser |
---|
| 9 | import os |
---|
| 10 | import os.path |
---|
| 11 | import datetime as dt |
---|
| 12 | import numpy as np |
---|
| 13 | |
---|
[2413] | 14 | # Application library imports |
---|
[2411] | 15 | from gencmip6 import * |
---|
[2413] | 16 | from gencmip6_path import * |
---|
[2411] | 17 | |
---|
| 18 | |
---|
| 19 | ######################################## |
---|
[2437] | 20 | class DataDict(dict): |
---|
[2411] | 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): |
---|
[2427] | 41 | """ |
---|
| 42 | """ |
---|
| 43 | try: |
---|
| 44 | data = np.genfromtxt( |
---|
| 45 | filein, |
---|
| 46 | skip_header=1, |
---|
[2437] | 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 | }, |
---|
[2427] | 57 | missing_values="nan", |
---|
| 58 | ) |
---|
[2437] | 59 | except Exception as rc: |
---|
| 60 | print("Empty file {}:\n{}".format(filein, rc)) |
---|
[2427] | 61 | exit(1) |
---|
[2411] | 62 | |
---|
[2437] | 63 | for date, conso, real_use, theo_use, \ |
---|
| 64 | run_mean, pen_mean, run_std, pen_std in data: |
---|
[2411] | 65 | if date in self: |
---|
[2437] | 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 | ) |
---|
[2411] | 76 | self[date].fill() |
---|
| 77 | |
---|
| 78 | #--------------------------------------- |
---|
| 79 | def add_item(self, date, conso=np.nan, |
---|
[2437] | 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): |
---|
[2411] | 83 | """ |
---|
| 84 | """ |
---|
[2437] | 85 | self[date] = Conso(date, conso, real_use, theo_use, |
---|
| 86 | run_mean, pen_mean, run_std, pen_std) |
---|
[2411] | 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 | |
---|
| 154 | class Conso(object): |
---|
| 155 | #--------------------------------------- |
---|
| 156 | def __init__(self, date, conso=np.nan, |
---|
[2437] | 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): |
---|
[2411] | 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 |
---|
[2437] | 165 | self.run_mean = run_mean |
---|
| 166 | self.pen_mean = pen_mean |
---|
| 167 | self.run_std = run_std |
---|
| 168 | self.pen_std = pen_std |
---|
[2411] | 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 | ######################################## |
---|
| 185 | def 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 | ######################################## |
---|
[2437] | 194 | def 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): |
---|
[2411] | 197 | """ |
---|
| 198 | """ |
---|
[2437] | 199 | line_style = "-" |
---|
[2411] | 200 | if args.full: |
---|
[2437] | 201 | line_width = 0.05 |
---|
| 202 | else: |
---|
| 203 | # line_style = "+-" |
---|
[2413] | 204 | line_width = 0.1 |
---|
[2411] | 205 | |
---|
[2437] | 206 | ax_conso.bar(xcoord, consos, width=1, align="center", color="linen", |
---|
[2413] | 207 | linewidth=line_width, label="conso (heures)") |
---|
[2411] | 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, |
---|
[2437] | 214 | solid_capstyle="round", solid_joinstyle="round", |
---|
[2443] | 215 | label="conso\nthéorique (%)") |
---|
[2411] | 216 | ax_theo.plot(xcoord, real_uses, line_style, color="forestgreen", |
---|
| 217 | linewidth=1, markersize=8, |
---|
[2437] | 218 | solid_capstyle="round", solid_joinstyle="round", |
---|
[2443] | 219 | label="conso\nréelle (%)") |
---|
[2411] | 220 | |
---|
| 221 | |
---|
| 222 | ######################################## |
---|
[2437] | 223 | def plot_config(fig, ax_conso, ax_theo, xcoord, dates, title, conso_per_day): |
---|
[2411] | 224 | """ |
---|
| 225 | """ |
---|
| 226 | # ... Config axes ... |
---|
| 227 | # ------------------- |
---|
| 228 | # 1) Range |
---|
[2443] | 229 | conso_max = np.nanmax(consos) |
---|
[2437] | 230 | if args.max: |
---|
[2443] | 231 | ymax = np.nanmax(consos) # + np.nanmax(consos)*.1 |
---|
[2437] | 232 | else: |
---|
[2443] | 233 | ymax = 2. * conso_per_day |
---|
[2437] | 234 | |
---|
[2443] | 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 | |
---|
[2411] | 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 |
---|
[2437] | 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 | |
---|
[2411] | 271 | ax_conso.ticklabel_format(axis="y", style="sci", scilimits=(0, 0)) |
---|
[2437] | 272 | |
---|
[2411] | 273 | ax_conso.set_xticks(xcoord, minor=True) |
---|
[2437] | 274 | ax_conso.set_xticks(maj_xticks, minor=False) |
---|
| 275 | ax_conso.set_xticklabels(maj_xlabs, rotation="vertical", size="x-small") |
---|
[2411] | 276 | |
---|
[2434] | 277 | yticks = list(ax_conso.get_yticks()) |
---|
| 278 | yticks.append(conso_per_day) |
---|
| 279 | ax_conso.set_yticks(yticks) |
---|
| 280 | |
---|
[2443] | 281 | ax_theo.spines["right"].set_color("indianred") |
---|
| 282 | ax_theo.tick_params(colors="indianred") |
---|
| 283 | ax_theo.yaxis.label.set_color("indianred") |
---|
| 284 | |
---|
[2437] | 285 | ax_conso.axhline(y=conso_per_day, color="blue", alpha=0.5, |
---|
[2443] | 286 | label="conso journaliÚre\nidéale (heures)") |
---|
[2437] | 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 | |
---|
[2411] | 293 | # 3) Define axes title |
---|
[2437] | 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") |
---|
[2411] | 300 | |
---|
[2437] | 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 | |
---|
[2411] | 309 | # ... Main title and legend ... |
---|
| 310 | # ----------------------------- |
---|
[2437] | 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) |
---|
[2411] | 317 | |
---|
| 318 | |
---|
| 319 | ######################################## |
---|
| 320 | def get_arguments(): |
---|
| 321 | parser = ArgumentParser() |
---|
| 322 | parser.add_argument("-v", "--verbose", action="store_true", |
---|
[2421] | 323 | help="verbose mode") |
---|
[2411] | 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") |
---|
[2421] | 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") |
---|
[2411] | 338 | |
---|
| 339 | return parser.parse_args() |
---|
| 340 | |
---|
| 341 | |
---|
| 342 | ######################################## |
---|
| 343 | if __name__ == '__main__': |
---|
| 344 | |
---|
| 345 | # .. Initialization .. |
---|
| 346 | # ==================== |
---|
| 347 | # ... Command line arguments ... |
---|
| 348 | # ------------------------------ |
---|
| 349 | args = get_arguments() |
---|
[2425] | 350 | if args.verbose: |
---|
| 351 | print(args) |
---|
[2411] | 352 | |
---|
[2421] | 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 |
---|
[2427] | 360 | # from matplotlib.backends.backend_pdf import PdfPages |
---|
[2421] | 361 | |
---|
| 362 | if not args.show: |
---|
| 363 | plt.ioff() |
---|
| 364 | |
---|
[2411] | 365 | # ... Files and directories ... |
---|
| 366 | # ----------------------------- |
---|
[2427] | 367 | (file_param, file_utheo, file_data) = \ |
---|
| 368 | get_input_files(DIR["SAVEDATA"], |
---|
| 369 | [OUT["PARAM"], OUT["UTHEO"], OUT["BILAN"]]) |
---|
[2426] | 370 | |
---|
[2425] | 371 | img_name = "bilan" |
---|
| 372 | today = os.path.basename(file_param).strip(OUT["PARAM"]) |
---|
| 373 | |
---|
[2411] | 374 | if args.verbose: |
---|
| 375 | print(file_param) |
---|
| 376 | print(file_utheo) |
---|
[2427] | 377 | print(file_data) |
---|
[2417] | 378 | print(img_name) |
---|
[2425] | 379 | print(today) |
---|
[2411] | 380 | |
---|
| 381 | # .. Get project info .. |
---|
| 382 | # ====================== |
---|
| 383 | gencmip6 = Project() |
---|
| 384 | gencmip6.fill_data(file_param) |
---|
| 385 | gencmip6.get_date_init(file_utheo) |
---|
| 386 | |
---|
[2437] | 387 | # .. Fill in data .. |
---|
| 388 | # ================== |
---|
[2411] | 389 | # ... Initialization ... |
---|
| 390 | # ---------------------- |
---|
[2437] | 391 | bilan = DataDict() |
---|
[2411] | 392 | bilan.init_range(gencmip6.date_init, gencmip6.deadline) |
---|
| 393 | # ... Extract data from file ... |
---|
| 394 | # ------------------------------ |
---|
[2427] | 395 | bilan.fill_data(file_data) |
---|
[2411] | 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) |
---|
[2437] | 416 | dates = [item.date for item in selected_items] |
---|
| 417 | |
---|
[2420] | 418 | cumul = np.array([item.conso for item in selected_items], |
---|
[2411] | 419 | dtype=float) |
---|
[2420] | 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 | |
---|
[2433] | 425 | conso_per_day = gencmip6.alloc / gencmip6.days |
---|
[2420] | 426 | |
---|
[2411] | 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 | |
---|
[2437] | 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 | |
---|
[2411] | 443 | # .. Plot stuff .. |
---|
| 444 | # ================ |
---|
| 445 | # ... Initialize figure ... |
---|
| 446 | # ------------------------- |
---|
| 447 | (fig, ax_conso, ax_theo) = plot_init() |
---|
| 448 | |
---|
| 449 | # ... Plot data ... |
---|
| 450 | # ----------------- |
---|
[2437] | 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) |
---|
[2411] | 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 | |
---|
[2437] | 463 | plot_config(fig, ax_conso, ax_theo, xcoord, dates, title, conso_per_day) |
---|
[2411] | 464 | |
---|
| 465 | # ... Save figure ... |
---|
| 466 | # ------------------- |
---|
[2425] | 467 | img_in = os.path.join(DIR["PLOT"], "{}.pdf".format(img_name)) |
---|
[2427] | 468 | img_out = os.path.join(DIR["SAVEPLOT"], |
---|
| 469 | "{}_{}.pdf".format(img_name, today)) |
---|
[2411] | 470 | |
---|
[2430] | 471 | plot_save(img_in, img_out, title) |
---|
[2427] | 472 | |
---|
[2421] | 473 | # ... Publish figure on dods ... |
---|
| 474 | # ------------------------------ |
---|
| 475 | if args.dods: |
---|
[2425] | 476 | dods_cp(img_in) |
---|
[2421] | 477 | |
---|
| 478 | if args.show: |
---|
| 479 | plt.show() |
---|
[2425] | 480 | |
---|
[2426] | 481 | exit(0) |
---|
[2433] | 482 | |
---|