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 | from dateutil.relativedelta import relativedelta |
---|
13 | import numpy as np |
---|
14 | |
---|
15 | # Application library imports |
---|
16 | from libconso import * |
---|
17 | |
---|
18 | |
---|
19 | ######################################## |
---|
20 | class 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 | |
---|
155 | class 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.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 | ######################################## |
---|
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 | ######################################## |
---|
194 | def plot_data(ax_conso, ax_theo, xcoord, dates, |
---|
195 | consos, theo_uses, real_uses, theo_equs, theo_delay, |
---|
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( |
---|
207 | xcoord, consos, width=1, align="center", color="linen", |
---|
208 | linewidth=line_width, label="conso (heures)" |
---|
209 | ) |
---|
210 | |
---|
211 | ax_theo.plot( |
---|
212 | xcoord, real_uses, line_style, |
---|
213 | color="forestgreen", linewidth=1, markersize=8, |
---|
214 | solid_capstyle="round", solid_joinstyle="round", |
---|
215 | label="conso\nréelle (%)" |
---|
216 | ) |
---|
217 | ax_theo.plot( |
---|
218 | xcoord, theo_equs, "--", |
---|
219 | color="firebrick", linewidth=0.5, |
---|
220 | solid_capstyle="round", solid_joinstyle="round" |
---|
221 | ) |
---|
222 | ax_theo.plot( |
---|
223 | xcoord, theo_uses, line_style, |
---|
224 | color="firebrick", linewidth=1, markersize=8, |
---|
225 | solid_capstyle="round", solid_joinstyle="round", |
---|
226 | label="conso\nthéorique (%)" |
---|
227 | ) |
---|
228 | ax_theo.plot( |
---|
229 | xcoord, theo_delay, ":", |
---|
230 | color="firebrick", linewidth=0.5, |
---|
231 | solid_capstyle="round", solid_joinstyle="round", |
---|
232 | label="retard de\ndeux mois (%)" |
---|
233 | ) |
---|
234 | |
---|
235 | |
---|
236 | ######################################## |
---|
237 | def plot_config(fig, ax_conso, ax_theo, xcoord, dates, title, |
---|
238 | conso_per_day): |
---|
239 | """ |
---|
240 | """ |
---|
241 | # ... Config axes ... |
---|
242 | # ------------------- |
---|
243 | # 1) Range |
---|
244 | conso_max = np.nanmax(consos) |
---|
245 | if args.max: |
---|
246 | ymax = conso_max # + conso_max*.1 |
---|
247 | else: |
---|
248 | ymax = 2. * conso_per_day |
---|
249 | |
---|
250 | if conso_max > ymax: |
---|
251 | ax_conso.annotate( |
---|
252 | "{:.2e} heures".format(conso_max), |
---|
253 | ha="left", |
---|
254 | va="top", |
---|
255 | fontsize="xx-small", |
---|
256 | bbox=dict(boxstyle="round", fc="w", ec="0.5", color="gray",), |
---|
257 | xy=(np.nanargmax(consos)+1.2, ymax), |
---|
258 | textcoords="axes fraction", |
---|
259 | xytext=(0.01, 0.9), |
---|
260 | arrowprops=dict( |
---|
261 | arrowstyle="->", |
---|
262 | shrinkA=0, |
---|
263 | shrinkB=0, |
---|
264 | color="gray", |
---|
265 | ), |
---|
266 | ) |
---|
267 | |
---|
268 | xmin, xmax = xcoord[0]-1, xcoord[-1]+1 |
---|
269 | ax_conso.set_xlim(xmin, xmax) |
---|
270 | ax_conso.set_ylim(0., ymax) |
---|
271 | ax_theo.set_ylim(0., 100) |
---|
272 | |
---|
273 | # 2) Ticks labels |
---|
274 | (date_beg, date_end) = (dates[0], dates[-1]) |
---|
275 | date_fmt = "{:%d-%m}" |
---|
276 | |
---|
277 | if date_end - date_beg > dt.timedelta(weeks=9): |
---|
278 | maj_xticks = [x for x, d in zip(xcoord, dates) |
---|
279 | if d.weekday() == 0] |
---|
280 | maj_xlabs = [date_fmt.format(d) for d in dates |
---|
281 | if d.weekday() == 0] |
---|
282 | else: |
---|
283 | maj_xticks = [x for x, d in zip(xcoord, dates)] |
---|
284 | maj_xlabs = [date_fmt.format(d) for d in dates] |
---|
285 | |
---|
286 | ax_conso.ticklabel_format(axis="y", style="sci", scilimits=(0, 0)) |
---|
287 | |
---|
288 | ax_conso.set_xticks(xcoord, minor=True) |
---|
289 | ax_conso.set_xticks(maj_xticks, minor=False) |
---|
290 | ax_conso.set_xticklabels( |
---|
291 | maj_xlabs, rotation="vertical", size="x-small" |
---|
292 | ) |
---|
293 | |
---|
294 | yticks = list(ax_conso.get_yticks()) |
---|
295 | yticks.append(conso_per_day) |
---|
296 | ax_conso.set_yticks(yticks) |
---|
297 | |
---|
298 | ax_theo.spines["right"].set_color("firebrick") |
---|
299 | ax_theo.tick_params(colors="firebrick") |
---|
300 | ax_theo.yaxis.label.set_color("firebrick") |
---|
301 | |
---|
302 | ax_conso.axhline(y=conso_per_day, color="blue", alpha=0.5, |
---|
303 | label="conso journaliÚre\nidéale (heures)") |
---|
304 | |
---|
305 | for x, d in zip(xcoord, dates): |
---|
306 | if d.weekday() == 0 and d.hour == 0: |
---|
307 | ax_conso.axvline(x=x, color="black", alpha=0.5, |
---|
308 | linewidth=0.5, linestyle=":") |
---|
309 | |
---|
310 | # 3) Define axes title |
---|
311 | for ax, label in ( |
---|
312 | (ax_conso, "heures"), |
---|
313 | (ax_theo, "%"), |
---|
314 | ): |
---|
315 | ax.set_ylabel(label, fontweight="bold") |
---|
316 | ax.tick_params(axis="y", labelsize="small") |
---|
317 | |
---|
318 | # 4) Define plot size |
---|
319 | fig.subplots_adjust( |
---|
320 | left=0.08, |
---|
321 | bottom=0.09, |
---|
322 | right=0.93, |
---|
323 | top=0.93, |
---|
324 | ) |
---|
325 | |
---|
326 | # ... Main title and legend ... |
---|
327 | # ----------------------------- |
---|
328 | fig.suptitle(title, fontweight="bold", size="large") |
---|
329 | for ax, loc in ( |
---|
330 | (ax_conso, "upper left"), |
---|
331 | (ax_theo, "upper right"), |
---|
332 | ): |
---|
333 | ax.legend(loc=loc, fontsize="x-small", frameon=False) |
---|
334 | |
---|
335 | |
---|
336 | ######################################## |
---|
337 | def get_arguments(): |
---|
338 | parser = ArgumentParser() |
---|
339 | parser.add_argument("-v", "--verbose", action="store_true", |
---|
340 | help="verbose mode") |
---|
341 | parser.add_argument("-f", "--full", action="store_true", |
---|
342 | help="plot the whole period") |
---|
343 | parser.add_argument("-i", "--increment", action="store", |
---|
344 | type=int, default=1, dest="inc", |
---|
345 | help="sampling increment") |
---|
346 | parser.add_argument("-r", "--range", action="store", nargs=2, |
---|
347 | type=string_to_date, |
---|
348 | help="date range: ssaa-mm-jj ssaa-mm-jj") |
---|
349 | parser.add_argument("-m", "--max", action="store_true", |
---|
350 | help="plot with y_max = allocation") |
---|
351 | parser.add_argument("-s", "--show", action="store_true", |
---|
352 | help="interactive mode") |
---|
353 | parser.add_argument("-d", "--dods", action="store_true", |
---|
354 | help="copy output on dods") |
---|
355 | |
---|
356 | return parser.parse_args() |
---|
357 | |
---|
358 | |
---|
359 | ######################################## |
---|
360 | if __name__ == '__main__': |
---|
361 | |
---|
362 | # .. Initialization .. |
---|
363 | # ==================== |
---|
364 | # ... Command line arguments ... |
---|
365 | # ------------------------------ |
---|
366 | args = get_arguments() |
---|
367 | if args.verbose: |
---|
368 | print(args) |
---|
369 | |
---|
370 | # ... Turn interactive mode off ... |
---|
371 | # --------------------------------- |
---|
372 | if not args.show: |
---|
373 | import matplotlib |
---|
374 | matplotlib.use('Agg') |
---|
375 | |
---|
376 | import matplotlib.pyplot as plt |
---|
377 | # from matplotlib.backends.backend_pdf import PdfPages |
---|
378 | |
---|
379 | if not args.show: |
---|
380 | plt.ioff() |
---|
381 | |
---|
382 | # ... Files and directories ... |
---|
383 | # ----------------------------- |
---|
384 | project_name, DIR, OUT = parse_config("bin/config.ini") |
---|
385 | |
---|
386 | (file_param, file_utheo, file_data) = \ |
---|
387 | get_input_files(DIR["SAVEDATA"], |
---|
388 | [OUT["PARAM"], OUT["UTHEO"], OUT["BILAN"]]) |
---|
389 | |
---|
390 | img_name = "bilan" |
---|
391 | today = os.path.basename(file_param).strip(OUT["PARAM"]) |
---|
392 | |
---|
393 | if args.verbose: |
---|
394 | print(file_param) |
---|
395 | print(file_utheo) |
---|
396 | print(file_data) |
---|
397 | print(img_name) |
---|
398 | print(today) |
---|
399 | |
---|
400 | # .. Get project info .. |
---|
401 | # ====================== |
---|
402 | projet = Project(project_name) |
---|
403 | projet.fill_data(file_param) |
---|
404 | projet.get_date_init(file_utheo) |
---|
405 | |
---|
406 | # .. Fill in data .. |
---|
407 | # ================== |
---|
408 | # ... Initialization ... |
---|
409 | # ---------------------- |
---|
410 | bilan = DataDict() |
---|
411 | bilan.init_range(projet.date_init, projet.deadline) |
---|
412 | # ... Extract data from file ... |
---|
413 | # ------------------------------ |
---|
414 | bilan.fill_data(file_data) |
---|
415 | # ... Compute theoratical use from known data ... |
---|
416 | # ------------------------------------------------ |
---|
417 | bilan.theo_equation() |
---|
418 | |
---|
419 | # .. Extract data depending on C.L. arguments .. |
---|
420 | # ============================================== |
---|
421 | if args.full: |
---|
422 | selected_items = bilan.get_items_in_full_range(args.inc) |
---|
423 | elif args.range: |
---|
424 | selected_items = bilan.get_items_in_range( |
---|
425 | args.range[0], args.range[1], args.inc |
---|
426 | ) |
---|
427 | else: |
---|
428 | selected_items = bilan.get_items(args.inc) |
---|
429 | |
---|
430 | # .. Compute data to be plotted .. |
---|
431 | # ================================ |
---|
432 | nb_items = len(selected_items) |
---|
433 | |
---|
434 | xcoord = np.linspace(1, nb_items, num=nb_items) |
---|
435 | dates = [item.date for item in selected_items] |
---|
436 | |
---|
437 | cumul = np.array([item.conso for item in selected_items], |
---|
438 | dtype=float) |
---|
439 | consos = [] |
---|
440 | consos.append(cumul[0]) |
---|
441 | consos[1:nb_items] = cumul[1:nb_items] - cumul[0:nb_items-1] |
---|
442 | consos = np.array(consos, dtype=float) |
---|
443 | |
---|
444 | conso_per_day = projet.alloc / projet.days |
---|
445 | |
---|
446 | theo_uses = np.array( |
---|
447 | [100.*item.theo_use for item in selected_items], |
---|
448 | dtype=float |
---|
449 | ) |
---|
450 | |
---|
451 | real_uses = np.array( |
---|
452 | [100.*item.real_use for item in selected_items], |
---|
453 | dtype=float |
---|
454 | ) |
---|
455 | theo_equs = np.array( |
---|
456 | [100. * bilan.poly_theo(date.timetuple().tm_yday) |
---|
457 | for date in dates], |
---|
458 | dtype=float |
---|
459 | ) |
---|
460 | theo_delay = np.array( |
---|
461 | [100. * bilan.poly_delay(date.timetuple().tm_yday) |
---|
462 | for date in dates], |
---|
463 | dtype=float |
---|
464 | ) |
---|
465 | |
---|
466 | run_mean = np.array([item.run_mean for item in selected_items], |
---|
467 | dtype=float) |
---|
468 | pen_mean = np.array([item.pen_mean for item in selected_items], |
---|
469 | dtype=float) |
---|
470 | run_std = np.array([item.run_std for item in selected_items], |
---|
471 | dtype=float) |
---|
472 | pen_std = np.array([item.pen_std for item in selected_items], |
---|
473 | dtype=float) |
---|
474 | |
---|
475 | # .. Plot stuff .. |
---|
476 | # ================ |
---|
477 | # ... Initialize figure ... |
---|
478 | # ------------------------- |
---|
479 | (fig, ax_conso, ax_theo) = plot_init() |
---|
480 | |
---|
481 | # ... Plot data ... |
---|
482 | # ----------------- |
---|
483 | plot_data(ax_conso, ax_theo, xcoord, dates, |
---|
484 | consos, theo_uses, real_uses, theo_equs, theo_delay, |
---|
485 | run_mean, pen_mean, run_std, pen_std) |
---|
486 | |
---|
487 | # ... Tweak figure ... |
---|
488 | # -------------------- |
---|
489 | title = "Consommation {}\n({:%d/%m/%Y} - {:%d/%m/%Y})".format( |
---|
490 | projet.project.upper(), |
---|
491 | projet.date_init, |
---|
492 | projet.deadline |
---|
493 | ) |
---|
494 | |
---|
495 | plot_config( |
---|
496 | fig, ax_conso, ax_theo, xcoord, dates, title, conso_per_day |
---|
497 | ) |
---|
498 | |
---|
499 | # ... Save figure ... |
---|
500 | # ------------------- |
---|
501 | img_in = os.path.join(DIR["PLOT"], "{}.pdf".format(img_name)) |
---|
502 | img_out = os.path.join(DIR["SAVEPLOT"], |
---|
503 | "{}_{}.pdf".format(img_name, today)) |
---|
504 | |
---|
505 | plot_save(img_in, img_out, title, DIR) |
---|
506 | |
---|
507 | # ... Publish figure on dods ... |
---|
508 | # ------------------------------ |
---|
509 | if args.dods: |
---|
510 | dods_cp(img_in, DIR) |
---|
511 | |
---|
512 | if args.show: |
---|
513 | plt.show() |
---|
514 | |
---|
515 | exit(0) |
---|