Changeset 2775
- Timestamp:
- 03/13/16 15:33:40 (9 years ago)
- Location:
- TOOLS/ConsoGENCI/trunk
- Files:
-
- 18 added
- 1 deleted
- 9 edited
Legend:
- Unmodified
- Added
- Removed
-
TOOLS/ConsoGENCI/trunk
-
Property
svn:ignore
set to
*.pdf
-
Property
svn:ignore
set to
-
TOOLS/ConsoGENCI/trunk/bin
-
Property
svn:ignore
set to
db_data.py
-
Property
svn:ignore
set to
-
TOOLS/ConsoGENCI/trunk/bin/init_alloc_tbl.py
r2751 r2775 1 1 #!/usr/bin/env python 2 2 # -*- coding: utf-8 -*- 3 4 # ==================================================================== # 5 # Author: Sonia Labetoulle # 6 # Contact: sonia.labetoulle _at_ ipsl.jussieu.fr # 7 # Created: 2016 # 8 # History: # 9 # Modification: # 10 # ==================================================================== # 3 11 4 12 # ==================================================================== # … … 17 25 # Application library imports 18 26 import libconsodb as cdb 27 import db_data 19 28 20 29 … … 23 32 24 33 project_list = [ 25 {26 "name": "gen0826",27 "centre": "tgcc",28 "machine": "curie",29 "node": "fat/large",30 "alloc": 114000,31 "start": "2015-01-01 00:00:00",32 "end": "2015-12-31 23:59:59",33 },34 {35 "name": "gen0826",36 "centre": "tgcc",37 "machine": "curie",38 "node": "hybrid",39 "alloc": 25000,40 "start": "2015-01-01 00:00:00",41 "end": "2015-12-31 23:59:59",42 },43 {44 "name": "gen0826",45 "centre": "tgcc",46 "machine": "curie",47 "node": "thin/standard",48 "alloc": 114000,49 "start": "2015-01-01 00:00:00",50 "end": "2015-12-31 23:59:59",51 },52 34 { 53 35 "name": "gencmip6", … … 104 86 "end": "2016-12-31 23:59:59", 105 87 }, 88 { 89 "name": "gen0826", 90 "centre": "tgcc", 91 "machine": "curie", 92 "node": "fat/large", 93 "alloc": 114000, 94 "start": "2015-01-01 00:00:00", 95 "end": "2015-12-31 23:59:59", 96 }, 97 { 98 "name": "gen0826", 99 "centre": "tgcc", 100 "machine": "curie", 101 "node": "hybrid", 102 "alloc": 25000, 103 "start": "2015-01-01 00:00:00", 104 "end": "2015-12-31 23:59:59", 105 }, 106 { 107 "name": "gen0826", 108 "centre": "tgcc", 109 "machine": "curie", 110 "node": "thin/standard", 111 "alloc": 114000, 112 "start": "2015-01-01 00:00:00", 113 "end": "2015-12-31 23:59:59", 114 }, 106 115 ] 107 116 108 117 # Connection info 109 db_host = "134.157.170.104"110 # db_port = "5432"111 db_name = "prodiguer"112 db_user = "prodiguer_db_user"113 # db_pwd = "secret"118 # db_host = "134.157.170.104" 119 # # db_port = "5432" 120 # db_name = "prodiguer" 121 # db_user = "prodiguer_db_user" 122 # # db_pwd = "secret" 114 123 115 conn, cursor = cdb.connect_db(db_host, db_name, db_user) 124 conn, cursor = cdb.connect_db( 125 db_data.db_host, 126 db_data.db_name, 127 db_data.db_user 128 ) 116 129 117 130 # Build request -
TOOLS/ConsoGENCI/trunk/bin/init_conso_tbl.py
r2751 r2775 1 1 #!/usr/bin/env python 2 2 # -*- coding: utf-8 -*- 3 4 # ==================================================================== # 5 # Author: Sonia Labetoulle # 6 # Contact: sonia.labetoulle _at_ ipsl.jussieu.fr # 7 # Created: 2016 # 8 # History: # 9 # Modification: # 10 # ==================================================================== # 3 11 4 12 # This must come first … … 15 23 import libconso_db as cdb 16 24 import libconso_cpt as ccpt 25 import db_data 17 26 18 27 pp = pprint.PrettyPrinter(indent=2) … … 78 87 if args.verbose: 79 88 print("Connection to database") 80 db_host = "134.157.170.104" 81 # db_port = "5432" 82 db_name = "prodiguer" 83 db_user = "prodiguer_db_user" 84 # db_pwd = "secret" 85 conn, cursor = cdb.connect_db(db_host, db_name, db_user) 89 # db_host = "134.157.170.104" 90 # # db_port = "5432" 91 # db_name = "prodiguer" 92 # db_user = "prodiguer_db_user" 93 # # db_pwd = "secret" 94 conn, cursor = cdb.connect_db( 95 db_data.db_host, 96 db_data.db_name, 97 db_data.db_user 98 ) 86 99 87 100 # .. Extract allocation id from table .. -
TOOLS/ConsoGENCI/trunk/bin/libconso.py
r2751 r2775 1 1 #!/usr/bin/env python 2 2 # -*- coding: utf-8 -*- 3 4 # ==================================================================== # 5 # Author: Sonia Labetoulle # 6 # Contact: sonia.labetoulle _at_ ipsl.jussieu.fr # 7 # Created: 2016 # 8 # History: # 9 # Modification: # 10 # ==================================================================== # 3 11 4 12 # this must come first … … 13 21 import subprocess 14 22 import datetime as dt 15 #import numpy as np23 import numpy as np 16 24 import ConfigParser as cp 17 25 … … 19 27 20 28 21 ######################################## 22 def dods_cp( filein, DIR):23 """ 24 """ 25 if not D IR["DODS"]:29 ######################################################################## 30 def dods_cp(img_out, img_name, DODS): 31 """ 32 """ 33 if not DODS["DIR"]: 26 34 print("DODS directory not defined") 27 35 return 28 36 29 basefile = os.path.basename(filein) 30 31 fileout = os.path.join(DIR["DODS"], basefile) 32 filepng = os.path.join(DIR["DODS"], "img", basefile.split(".")[0] + ".png") 33 34 # Copy file 35 shutil.copy(filein, fileout) 36 37 # Convert it to png for web page 38 command = ["convert", "-density", "200", fileout, filepng] 37 # .. Copy pdf file to dods server .. 38 # ================================== 39 command = [ 40 "scp", 41 img_out, 42 "{}@{}:{}".format( 43 DODS["USER"], 44 DODS["SERVER"], 45 os.path.join(DODS["DIR"], "pdf", img_name + ".pdf") 46 ) 47 ] 48 try : 49 subprocess.call(command) 50 except Exception as rc : 51 print("Error in scp for {}:\n{}".format(command, rc)) 52 53 # .. Convert pdf to temporary png .. 54 # ================================== 55 img_png = img_out.replace(".pdf", ".png") 56 command = ["convert", "-density", "200", img_out, img_png] 39 57 40 58 try : … … 43 61 print("Error in convert for {}:\n{}".format(fileout, rc)) 44 62 63 # .. Copy png file to dods server .. 64 # ================================== 65 command = [ 66 "scp", 67 img_png, 68 "{}@{}:{}".format( 69 DODS["USER"], 70 DODS["SERVER"], 71 os.path.join(DODS["DIR"], "img", img_name + ".png") 72 ) 73 ] 74 try : 75 subprocess.call(command) 76 except Exception as rc : 77 print("Error in scp for {}:\n{}".format(command, rc)) 78 79 # .. Delete temporary png file .. 80 # =============================== 81 45 82 return 46 83 47 48 ######################################## 84 basefile = os.path.basename(filein) 85 86 fileout = os.path.join(DIR["DODS"], basefile) 87 filepng = os.path.join(DIR["DODS"], "img", basefile.split(".")[0] + ".png") 88 89 # Copy file 90 shutil.copy(filein, fileout) 91 92 # Convert it to png for web page 93 command = ["convert", "-density", "200", fileout, filepng] 94 95 try : 96 subprocess.call(command) 97 except Exception as rc : 98 print("Error in convert for {}:\n{}".format(fileout, rc)) 99 100 return 101 102 103 ######################################################################## 49 104 def parse_config(filename): 50 105 51 106 DIR = {} 52 OUT= {}107 DODS = {} 53 108 54 109 config = cp.ConfigParser(allow_no_value=True) … … 56 111 config.read(filename) 57 112 58 for section in ("projet", "directories" , "files"):113 for section in ("projet", "directories"): 59 114 if not config.has_section(section): 60 115 print("Missing section {} in {}, we stop".format(section, filename)) 61 116 exit(1) 62 117 63 # ..  Project name..64 # ------------------ 118 # ... Project name ... 119 # -------------------- 65 120 section = "projet" 66 121 option = "name" 67 122 project_name = config.get(section, option) 68 123 69 # .. Common directories..70 # ----------------------- 124 # ... Common directories ... 125 # -------------------------- 71 126 section = "directories" 72 127 for option in config.options(section): … … 80 135 print("Could not create {}:\n{}".format(DIR[option], rc)) 81 136 82 # .. Common files..83 # ----------------- 84 section = " files"137 # .. DODS configuration ... 138 # ------------------------- 139 section = "dods" 85 140 for option in config.options(section): 86 OUT[option] = config.get(section, option)87 88 return ( project_name, DIR, OUT)89 90 91 ######################################## 141 DODS[option] = config.get(section, option) 142 143 return (DIR, DODS) 144 145 146 ######################################################################## 92 147 def string_to_percent(x): 93 148 """ … … 96 151 97 152 98 ######################################## 153 ######################################################################## 99 154 def string_to_size_unit(x): 100 155 """ … … 108 163 109 164 110 ######################################## 165 ######################################################################## 111 166 def string_to_float(x): 112 167 """ … … 115 170 116 171 117 ######################################## 118 def string_to_date(ssaammjj, fmt="%Y-%m-%d"): 119 """ 120 """ 121 return dt.datetime.strptime(ssaammjj, fmt) 122 123 124 ######################################## 172 ######################################################################## 173 def string_to_date(ssaammjj, fmt="%Y%m%d"): 174 """ 175 """ 176 fmts = ["%Y%m%d", "%Y-%m-%d", "%Y_%m_%d"] 177 178 for fmt in fmts: 179 try: 180 res = dt.datetime.strptime(ssaammjj, fmt) 181 except Exception as rc: 182 pass 183 else: 184 break 185 186 return res.date() 187 188 189 ######################################################################## 125 190 def string_to_datetime(string, fmt="%Y-%m-%d-%H:%M"): 126 191 """ … … 129 194 130 195 131 # ######################################## 196 # ######################################################################## 132 197 # def date_to_string(dtdate, fmt="%Y-%m-%d"): 133 198 # """ … … 136 201 137 202 138 ######################################## 203 ######################################################################## 139 204 def where_we_run(): 140 205 … … 150 215 151 216 152 ######################################## 217 ######################################################################## 153 218 def get_last_file(dir_data, pattern): 154 219 """ … … 166 231 167 232 168 ######################################## 233 ######################################################################## 169 234 def get_input_files(dir_data, file_list): 170 235 """ … … 184 249 185 250 186 ######################################## 187 def plot_save(img_ in, img_out, title):251 ######################################################################## 252 def plot_save(img_out, title): 188 253 """ 189 254 """ … … 192 257 dpi = 200. 193 258 194 print(img_in) 195 with PdfPages(img_in) as pdf: 259 dirname = os.path.dirname(img_out) 260 if not os.path.isdir(dirname): 261 print("mkdir {}".format(dirname)) 262 try : 263 os.makedirs(dirname) 264 except Exception as rc : 265 print("Could not create {}:\n{}".format(dirname, rc)) 266 267 with PdfPages(img_out) as pdf: 196 268 pdf.savefig(dpi=dpi) 197 269 198 # pdf file's metadata 270 # ... pdf file's metadata ... 271 # --------------------------- 199 272 d = pdf.infodict() 200 273 d["Title"] = title … … 206 279 # d["ModDate"] = dt.datetime.today() 207 280 208 # if os.path.isdir(DIR["SAVEPLOT"]): 209 # # img_out = os.path.join(DIR["SAVEPLOT"], 210 # # "{}_{}.pdf".format(img_name, suffix)) 211 # shutil.copy(img_in, img_out) 212 213 214 ######################################## 215 class Project(object): 216 217 #--------------------------------------- 218 def __init__(self, project_name): 219 self.project = project_name 220 221 #--------------------------------------- 222 def fill_data(self, row): 223 # import json 224 # dico = json.load(open(filein, "r")) 225 # self.deadline = string_to_date(dico["deadline"]) + \ 226 # dt.timedelta(days=-1) 227 # self.alloc = dico["alloc"] 228 self.id = row["id"] 229 self.centre = row["centre"] 230 self.machine = row["machine"] 231 self.node = row["node_type"] 232 self.start_date = row["start_date"] 233 self.end_date = row["end_date"] 234 self.alloc = row["total_hrs"] 281 282 ######################################################################## 283 class AllocItem(object): 284 285 #--------------------------------------------------------------------- 286 def __init__( 287 self, 288 alloc_id, 289 machine, 290 node_type, 291 start_date, 292 end_date, 293 alloc 294 ): 295 296 self.alloc_id = alloc_id 297 self.machine = machine 298 self.node_type = node_type 299 self.start_date = start_date 300 self.end_date = end_date 301 self.alloc = alloc 235 302 236 303 delta = self.end_date - self.start_date 237 304 self.days = delta.days + 1 238 305 239 240 ######################################## 306 self.daily_conso = self.alloc / self.days 307 308 #--------------------------------------------------------------------- 309 def __repr__(self): 310 return "{} ({:%Y%m%d}/{:%Y%m%d}): {}".format( 311 self.machine, 312 self.start_date, 313 self.end_date, 314 self.alloc, 315 ) 316 317 318 ######################################################################## 319 class Project(object): 320 321 #--------------------------------------------------------------------- 322 def __init__(self, project_name, center): 323 self.project = project_name 324 self.centre = center 325 self.alloc_items = [] 326 327 #--------------------------------------------------------------------- 328 def __repr__(self): 329 return "{}/{}: {}".format( 330 self.project, 331 self.centre, 332 self.alloc_items, 333 ) 334 335 #--------------------------------------------------------------------- 336 def add_alloc( 337 self, 338 alloc_id, 339 machine, 340 node_type, 341 start_date, 342 end_date, 343 alloc 344 ): 345 346 alloc_item = AllocItem( 347 alloc_id, 348 machine, 349 node_type, 350 start_date, 351 end_date, 352 alloc 353 ) 354 355 self.alloc_items.append(alloc_item) 356 357 self.start_date = min( 358 [item.start_date for item in self.alloc_items] 359 ) 360 self.end_date = max( 361 [item.end_date for item in self.alloc_items] 362 ) 363 364 self.alloc = sum( 365 [item.alloc for item in self.alloc_items] 366 ) 367 self.max_daily_conso = max( 368 [item.daily_conso for item in self.alloc_items] 369 ) 370 371 372 self.days = sum( 373 [item.days for item in self.alloc_items] 374 ) 375 376 self.nb_alloc = len(self.alloc_items) 377 378 #--------------------------------------------------------------------- 379 def get_theo_eq(self, dates): 380 381 x0 = 0 382 y0 = 0. 383 384 for item in self.alloc_items: 385 yi = y0 386 yf = y0 + item.alloc / self.alloc 387 388 if item.start_date.date() in dates: 389 xi = dates.index(item.start_date.date()) 390 else: 391 xi = 0 392 393 if item.end_date.date() in dates: 394 xf = dates.index(item.end_date.date()) 395 else: 396 xf = len(dates) + 1 397 398 m = np.array([[xi, 1.], [xf+1, 1.]]) 399 n = np.array([yi, yf]) 400 401 try: 402 polynome = np.poly1d(np.linalg.solve(m, n)) 403 except np.linalg.linalg.LinAlgError: 404 print("error poly") 405 item.theo_eq = None 406 else: 407 item.theo_eq = polynome 408 item.xi = xi 409 item.xf = xf 410 item.yi = yi 411 item.yf = yf 412 413 y0 = yf 414 415 #--------------------------------------------------------------------- 416 def fill_data(self, row): 417 # self.id = row["id"] 418 # self.machine = row["machine"] 419 # self.node = row["node_type"] 420 # self.start_date = row["start_date"] 421 # self.end_date = row["end_date"] 422 # self.alloc = row["total_hrs"] 423 424 delta = self.end_date - self.start_date 425 self.days = delta.days + 1 426 427 428 ######################################################################## 241 429 class SizeUnit(object): 242 #--------------------------------------- 430 #--------------------------------------------------------------------- 243 431 def __init__(self, size, unit): 244 432 self.size = size 245 433 self.unit = unit 246 434 247 #--------------------------------------- 435 #--------------------------------------------------------------------- 248 436 def __repr__(self): 249 437 return "{:6.2f}{}o".format(self.size, self.unit) 250 438 251 #--------------------------------------- 439 #--------------------------------------------------------------------- 252 440 def convert_size(self, unit_out): 253 441 """ … … 271 459 272 460 273 ######################################## 461 ######################################################################## 274 462 if __name__ == '__main__': 275 463 pass -
TOOLS/ConsoGENCI/trunk/bin/libconso_cpt.py
r2751 r2775 1 1 #!/usr/bin/env python 2 2 # -*- coding: utf-8 -*- 3 4 # ==================================================================== # 5 # Author: Sonia Labetoulle # 6 # Contact: sonia.labetoulle _at_ ipsl.jussieu.fr # 7 # Created: 2016 # 8 # History: # 9 # Modification: # 10 # ==================================================================== # 3 11 4 12 # =================================================================== # … … 128 136 def cpt_pattern(project, center): 129 137 130 return "cpt_{}_{}_*.dat".format( project, center)138 return "cpt_{}_{}_*.dat".format(center, project) 131 139 132 140 … … 289 297 res = file_list 290 298 291 return set(res) 299 # return set(res) 300 return sorted(res) 292 301 293 302 -
TOOLS/ConsoGENCI/trunk/bin/libconso_db.py
r2751 r2775 1 1 #!/usr/bin/env python 2 2 # -*- coding: utf-8 -*- 3 4 # ==================================================================== # 5 # Author: Sonia Labetoulle # 6 # Contact: sonia.labetoulle _at_ ipsl.jussieu.fr # 7 # Created: 2016 # 8 # History: # 9 # Modification: # 10 # ==================================================================== # 3 11 4 12 # =================================================================== # -
TOOLS/ConsoGENCI/trunk/bin/plot_bilan.py
r2713 r2775 1 1 #!/usr/bin/env python 2 2 # -*- coding: utf-8 -*- 3 4 # ==================================================================== # 5 # Author: Sonia Labetoulle # 6 # Contact: sonia.labetoulle _at_ ipsl.jussieu.fr # 7 # Created: 2016 # 8 # History: # 9 # Modification: # 10 # ==================================================================== # 3 11 4 12 # this must come first … … 16 24 from libconso import * 17 25 import libconsodb as cdb 18 19 20 ######################################## 26 import db_data 27 28 29 ######################################################################## 30 class PlotData(object): 31 #--------------------------------------------------------------------- 32 def __init__(self, date_min, date_max): 33 self.date_min = date_min 34 self.date_max = date_max 35 36 self.data = DataDict() 37 self.data.init_range(self.date_min, self.date_max) 38 39 40 ######################################################################## 21 41 class DataDict(dict): 22 #--------------------------------------- 42 #--------------------------------------------------------------------- 23 43 def __init__(self): 24 44 self = {} 25 45 26 #--------------------------------------- 46 #--------------------------------------------------------------------- 27 47 def init_range(self, date_beg, date_end, inc=1): 28 48 """ … … 38 58 self.add_item(date) 39 59 40 #--------------------------------------- 60 #--------------------------------------------------------------------- 41 61 def fill_data(self, projet): 42 # def fill_data(self, filein): 43 """ 44 """ 62 """ 63 """ 64 65 id_condition = ( 66 "({})".format( 67 " OR ".join( 68 [ 69 "allocation_id={}".format(item.alloc_id) 70 for item in projet.alloc_items 71 ] 72 ) 73 ) 74 ) 75 45 76 table_name = "conso.tbl_consumption" 46 77 request = ( 47 "SELECT date, total_hrs "78 "SELECT date, total_hrs, allocation_id " 48 79 "FROM " + table_name + " " 49 "WHERE allocation_id = '" + str(projet.id) + "'"50 " AND login IS NULL"80 "WHERE login IS NULL " 81 " AND " + id_condition + " " 51 82 "ORDER BY date" 52 83 ";" 53 84 ) 85 86 if args.verbose: 87 print("Access table \"{}\"".format(table_name)) 88 print(request) 54 89 cdb.select_db(cursor, request) 55 90 56 for date, conso in cursor:91 for date, conso, alloc_id in cursor: 57 92 if date.date() in self: 58 # print(date.date(), conso)59 # Days since start_date60 93 real_use = conso / projet.alloc 61 94 self.add_item( 62 date=date ,95 date=date.date(), 63 96 conso=conso, 64 97 real_use=real_use, … … 66 99 self[date.date()].fill() 67 100 68 # try: 69 # data = np.genfromtxt( 70 # filein, 71 # skip_header=1, 72 # converters={ 73 # 0: string_to_date, 74 # 1: string_to_float, 75 # 2: string_to_percent, 76 # 3: string_to_percent, 77 # 4: string_to_float, 78 # 5: string_to_float, 79 # 6: string_to_float, 80 # 7: string_to_float, 81 # }, 82 # missing_values="nan", 83 # ) 84 # except Exception as rc: 85 # print("Empty file {}:\n{}".format(filein, rc)) 86 # exit(1) 87 88 # for date, conso, real_use, theo_use, \ 89 # run_mean, pen_mean, run_std, pen_std in data: 90 # if date in self: 91 # self.add_item( 92 # date, 93 # conso, 94 # real_use, 95 # theo_use, 96 # run_mean, 97 # pen_mean, 98 # run_std, 99 # pen_std, 100 # ) 101 # self[date].fill() 102 103 #--------------------------------------- 101 #--------------------------------------------------------------------- 104 102 def add_item(self, date, conso=np.nan, 105 103 real_use=np.nan, theo_use=np.nan, … … 108 106 """ 109 107 """ 110 self[date.date()] = Conso( 108 # self[date.date()] = Conso( 109 self[date] = Conso( 111 110 date, conso, 112 111 real_use, theo_use, … … 115 114 ) 116 115 117 #--------------------------------------- 118 def theo_equation(self, projet): 119 """ 120 """ 121 (dates, theo_uses) = \ 122 zip(*((item.date, item.theo_use) 123 for item in self.get_items_in_full_range())) 124 125 # (idx_min, idx_max) = \ 126 # (np.nanargmin(theo_uses), np.nanargmax(theo_uses)) 127 128 # x1 = dates[idx_min].timetuple().tm_yday 129 # x2 = dates[idx_max].timetuple().tm_yday 130 x1 = projet.start_date.timetuple().tm_yday 131 x2 = projet.end_date.timetuple().tm_yday 132 133 # y1 = theo_uses[idx_min] 134 # y2 = theo_uses[idx_max] 135 y1 = 0 136 y2 = 1 137 138 m = np.array([[x1, 1.], [x2, 1.]], dtype="float") 139 n = np.array([y1, y2], dtype="float") 140 141 poly_ok = True 142 try: 143 poly_theo = np.poly1d(np.linalg.solve(m, n)) 144 except np.linalg.linalg.LinAlgError: 145 poly_ok = False 146 147 if poly_ok: 148 delta = (dates[0] + relativedelta(months=2) - dates[0]).days 149 150 poly_delay = np.poly1d( 151 [poly_theo[1], poly_theo[0] - poly_theo[1] * delta] 152 ) 153 154 self.poly_theo = poly_theo 155 self.poly_delay = poly_delay 156 157 #--------------------------------------- 116 #--------------------------------------------------------------------- 158 117 def get_items_in_range(self, date_beg, date_end, inc=1): 159 118 """ 160 119 """ 161 120 items = (item for item in self.itervalues() 162 if item.date >= date_beg and163 item.date <= date_end)121 if item.date.date() >= date_beg and 122 item.date.date() <= date_end) 164 123 items = sorted(items, key=lambda item: item.date) 165 124 166 125 return items[::inc] 167 126 168 #--------------------------------------- 127 #--------------------------------------------------------------------- 169 128 def get_items_in_full_range(self, inc=1): 170 129 """ 171 130 """ 131 172 132 items = (item for item in self.itervalues()) 173 133 items = sorted(items, key=lambda item: item.date) … … 175 135 return items[::inc] 176 136 177 #--------------------------------------- 137 #--------------------------------------------------------------------- 178 138 def get_items(self, inc=1): 179 139 """ … … 187 147 188 148 class Conso(object): 189 #--------------------------------------- 149 #--------------------------------------------------------------------- 190 150 def __init__(self, date, conso=np.nan, 191 151 real_use=np.nan, theo_use=np.nan, … … 204 164 self.filled = False 205 165 206 #--------------------------------------- 166 #--------------------------------------------------------------------- 207 167 def __repr__(self): 208 168 return "{:.2f} ({:.2%})".format(self.conso, self.real_use) 209 169 210 #--------------------------------------- 170 #--------------------------------------------------------------------- 211 171 def isfilled(self): 212 172 return self.filled 213 173 214 #--------------------------------------- 174 #--------------------------------------------------------------------- 215 175 def fill(self): 216 176 self.filled = True 217 177 218 178 219 ######################################## 179 ######################################################################## 220 180 def plot_init(): 221 181 paper_size = np.array([29.7, 21.0]) … … 226 186 227 187 228 ######################################## 229 def plot_data(ax_conso, ax_theo, xcoord, dates, 230 consos, theo_uses, real_uses, theo_equs, theo_delay, 231 run_mean, pen_mean, run_std, pen_std): 188 ######################################################################## 189 def plot_data( 190 ax_conso, ax_theo, xcoord, dates, 191 consos, real_uses, theo_uses, delay_uses, 192 run_mean, pen_mean, run_std, pen_std 193 ): 232 194 """ 233 195 """ … … 249 211 label="conso\nréelle (%)" 250 212 ) 213 251 214 ax_theo.plot( 252 xcoord, theo_ equs, "--",215 xcoord, theo_uses, "--", 253 216 color="firebrick", linewidth=0.5, 254 solid_capstyle="round", solid_joinstyle="round"255 )256 ax_theo.plot(257 xcoord, theo_uses, line_style,258 color="firebrick", linewidth=1, markersize=8,259 217 solid_capstyle="round", solid_joinstyle="round", 260 218 label="conso\nthéorique (%)" 261 219 ) 220 262 221 ax_theo.plot( 263 xcoord, theo_delay, ":",222 xcoord, delay_uses, ":", 264 223 color="firebrick", linewidth=0.5, 265 224 solid_capstyle="round", solid_joinstyle="round", … … 267 226 ) 268 227 269 270 ######################################## 271 def plot_config(fig, ax_conso, ax_theo, xcoord, dates, title, 272 conso_per_day, conso_per_day_2): 228 ######################################################################## 229 def plot_config( 230 fig, ax_conso, ax_theo, 231 xcoord, dates, max_real_use, 232 title, projet 233 ): 273 234 """ 274 235 """ … … 282 243 ymax = conso_max # + conso_max*.1 283 244 else: 284 ymax = 3. * max(conso_per_day, conso_per_day_2)245 ymax = 3. * projet.max_daily_conso 285 246 286 247 if conso_max > ymax: … … 307 268 ax_theo.set_ylim(0., 100) 308 269 309 # 2) Ticks labels 270 # 2) Plot ideal daily consumption in hours 271 # Plot last real use value 272 x_list = [] 273 y_list = [] 274 conso_yticks = list(ax_conso.get_yticks()) 275 for item in projet.alloc_items: 276 x_list.extend([item.xi, item.xf]) 277 y_list.extend([item.daily_conso, item.daily_conso]) 278 conso_yticks.append(item.daily_conso) 279 line_alpha = 0.5 280 line_label = "conso journaliÚre\nidéale (heures)" 281 ax_conso.plot( 282 x_list, y_list, 283 color="blue", alpha=line_alpha, 284 label=line_label, 285 ) 286 287 theo_yticks = list(ax_theo.get_yticks()) 288 theo_yticks.append(max_real_use) 289 ax_theo.axhline( 290 y=max_real_use, 291 linestyle=":", linewidth=0.5, 292 color="green", alpha=line_alpha, 293 ) 294 295 296 # 3) Ticks labels 310 297 (date_beg, date_end) = (dates[0], dates[-1]) 311 298 date_fmt = "{:%d-%m}" … … 331 318 # ax.yaxis.set_minor_locator(minor_locator) 332 319 333 yticks = list(ax_conso.get_yticks()) 334 yticks.append(conso_per_day) 335 if conso_per_day_2: 336 yticks.append(conso_per_day_2) 337 ax_conso.set_yticks(yticks) 320 ax_conso.set_yticks(conso_yticks) 321 322 ax_theo.set_yticks(theo_yticks) 338 323 339 324 ax_theo.spines["right"].set_color("firebrick") … … 341 326 ax_theo.yaxis.label.set_color("firebrick") 342 327 343 ax_conso.axhline(y=conso_per_day, color="blue", alpha=0.5,344 label="conso journaliÚre\nidéale (heures)")345 346 if conso_per_day_2:347 ax_conso.axhline(y=conso_per_day_2, color="blue", alpha=0.5)348 349 328 for x, d in zip(xcoord, dates): 350 329 # if d.weekday() == 0 and d.hour == 0: 351 330 if d.weekday() == 0: 352 ax_conso.axvline(x=x, color="black", alpha=0.5, 353 linewidth=0.5, linestyle=":") 354 355 # 3) Define axes title 331 ax_conso.axvline( 332 x=x, color="black", alpha=0.5, 333 linewidth=0.5, linestyle=":" 334 ) 335 336 # 4) Define axes title 356 337 for ax, label in ( 357 338 (ax_conso, "heures"), … … 361 342 ax.tick_params(axis="y", labelsize="small") 362 343 363 # 4) Define plot size344 # 5) Define plot size 364 345 fig.subplots_adjust( 365 346 left=0.08, 366 347 bottom=0.09, 367 348 right=0.93, 368 top=0.9 3,349 top=0.92, 369 350 ) 370 351 … … 378 359 ax.legend(loc=loc, fontsize="x-small", frameon=False) 379 360 380 381 ######################################## 361 alloc_label = ( 362 "Allocation(s):\n" + 363 "\n".join([ 364 "{:%d-%m-%Y}-{:%d-%m-%Y} : {:8,.0f}h".format( 365 item.start_date, item.end_date, item.alloc 366 ) for item in projet.alloc_items 367 ]) 368 ) 369 plt.figtext( 370 x=0.92, y=0.93, s=alloc_label, 371 backgroundcolor="linen", 372 ha="right", va="bottom", fontsize="x-small" 373 ) 374 375 376 ######################################################################## 382 377 def get_arguments(): 383 378 parser = ArgumentParser() … … 407 402 408 403 409 ######################################## 404 ######################################################################## 410 405 if __name__ == '__main__': 411 406 … … 416 411 args = get_arguments() 417 412 413 print(os.getcwd()) 414 print(os.path.abspath(__file__)) 415 418 416 # ... Turn interactive mode off ... 419 417 # --------------------------------- … … 428 426 plt.ioff() 429 427 430 # # ... Files and directories ... 431 # # ----------------------------- 432 # project_name, DIR, OUT = parse_config("bin/config.ini") 428 # ... Variables and constants ... 429 # ------------------------------- 430 delay = 60 # 2 months delay 431 432 # ... Files and directories ... 433 # ----------------------------- 434 config_file = os.path.join( 435 "card", 436 "config_{}_{}.ini".format(args.center, args.project) 437 ) 438 439 if not os.path.isfile(config_file): 440 print("File {} missing ".format(config_file)) 441 exit(1) 442 443 (DIR, DODS) = parse_config(config_file) 433 444 434 445 # (file_param, file_utheo, file_data) = \ … … 436 447 # [OUT["PARAM"], OUT["UTHEO"], OUT["BILAN"]]) 437 448 438 img_name = os.path.splitext( 439 os.path.basename(__file__) 440 )[0].replace("plot_", "") 441 442 # project_name = "rgzi" 443 444 # Connection info 445 db_host = "134.157.170.104" 446 # db_port = "5432" 447 db_name = "prodiguer" 448 db_user = "prodiguer_db_user" 449 # db_pwd = "secret" 450 451 conn, cursor = cdb.connect_db(db_host, db_name, db_user) 449 img_name = "{}_{}_{}".format( 450 os.path.splitext( 451 os.path.basename(__file__) 452 )[0].replace("plot_", ""), 453 args.project, 454 args.center, 455 ) 456 457 # if args.verbose: 458 # print("Save plot as >{}<".format(img_name)) 459 460 conn, cursor = cdb.connect_db( 461 db_data.db_host, 462 db_data.db_name, 463 db_data.db_user 464 ) 452 465 453 466 # today = os.path.basename(file_param).strip(OUT["PARAM"]) 454 today = dt.date.strftime(dt.date.today(), "%Y%m%d") 455 456 # if args.verbose: 457 # fmt_str = "{:10s} : {}" 458 # print(fmt_str.format("args", args)) 459 # print(fmt_str.format("today", today)) 467 # today = dt.date.strftime(dt.date.today(), "%Y%m%d") 468 today = dt.date.today() 469 470 if args.verbose: 471 fmt_str = "{:10s} : {}" 472 print(fmt_str.format("args", args)) 473 print(fmt_str.format("today", today)) 460 474 # print(fmt_str.format("file_param", file_param)) 461 475 # print(fmt_str.format("file_utheo", file_utheo)) 462 476 # print(fmt_str.format("file_data", file_data)) 463 # print(fmt_str.format("img_name", img_name)) 477 print(fmt_str.format("img_name", img_name)) 478 print("") 479 480 # .. Range of dates .. 481 # ==================== 482 if args.full: 483 (date_min, date_max) = ( 484 dt.date(today.year, 1, 1), 485 dt.date(today.year, 12, 31), 486 ) 487 elif args.range: 488 (date_min, date_max) = (args.range) 489 else: 490 (date_min, date_max) = ( 491 dt.date(today.year, 1, 1), 492 dt.date(today.year, 12, 31), 493 ) 494 bilan_plot = PlotData(date_min, date_max) 495 496 # print(bilan_plot.__dict__) 497 # exit() 464 498 465 499 # .. Get project info .. … … 473 507 "SELECT * " 474 508 "FROM " + table_name + " " 475 "WHERE project = '" + args.project + "'" 509 "WHERE project = '" + args.project + "' " 510 "ORDER BY start_date" 476 511 ";" 477 512 ) … … 481 516 # print(cursor.fetchall()) 482 517 483 print(cursor.description) 518 projet = Project(args.project, args.center) 519 # print(cursor.description) 484 520 for row in cursor: 485 projet = Project(args.project) 486 projet.fill_data(row) 487 # print(row["project"], type(row["project"])) 488 # print(row["centre"], type(row["centre"])) 489 # print(row["machine"], type(row["machine"])) 490 # print(row["node_type"], type(row["node_type"])) 491 # print(row["start_date"], type(row["start_date"])) 492 # print(row["end_date"], type(row["end_date"])) 493 # print(row["total_hrs"], type(row["total_hrs"])) 521 # if row["start_date"].year == today.year: 522 if (bilan_plot.date_min >= row["start_date"].date() and 523 bilan_plot.date_min <= row["end_date"].date()) or \ 524 (bilan_plot.date_max >= row["start_date"].date() and 525 bilan_plot.date_max <= row["end_date"].date()) or \ 526 (bilan_plot.date_min <= row["start_date"].date() and 527 bilan_plot.date_max >= row["end_date"].date()): 528 projet.add_alloc( 529 row["id"], 530 row["machine"], 531 row["node_type"], 532 row["start_date"], 533 row["end_date"], 534 row["total_hrs"], 535 ) 494 536 495 537 # .. Fill in data .. … … 497 539 # ... Initialization ... 498 540 # ---------------------- 541 499 542 bilan = DataDict() 500 bilan.init_range(projet.start_date, projet.end_date) 501 502 # ... Extract data from file ... 503 # ------------------------------ 504 # table_name = "conso.tbl_consumption" 505 # request = ( 506 # "SELECT date, total_hrs " 507 # "FROM " + table_name + " " 508 # "WHERE allocation_id = '" + str(projet.id) + "'" 509 # " AND login IS NULL " 510 # "ORDER BY date" 511 # ";" 512 # ) 513 # cdb.select_db(cursor, request) 514 543 bilan.init_range(projet.start_date.date(), projet.end_date.date()) 544 545 # ... Extract data from table ... 546 # ------------------------------- 515 547 bilan.fill_data(projet) 516 # for item in bilan.iteritems():517 # print(item)518 # exit()519 520 # ... Compute theoratical use from known data ...521 # ------------------------------------------------522 bilan.theo_equation(projet)523 524 # print(cursor.description)525 # # for row in cursor:526 # # print(row)527 528 # consos = np.array([conso for date, conso in cursor])529 # dates = [date for date, conso in cursor]530 531 # people = ['Tom', 'Dick', 'Harry', 'Slim', 'Jim']532 # x_pos = np.arange(len(people))533 # performance = 3 + 10 * np.random.rand(len(people))534 535 # # x_pos = np.arange(len(consos))536 # print (len(x_pos), type(x_pos))537 # # print (len(people), type(people))538 # print (len(performance), type(performance))539 # print (len(consos), type(consos))540 541 # # plt.barh(x_pos, performance, align='center', alpha=0.4)542 543 # x_pos = np.arange(len(consos))544 # print (len(x_pos), type(x_pos))545 # plt.bar(x_pos, consos, align='center', alpha=0.4)546 # # plt.yticks(x_pos, dates)547 548 # # plt.barh(x_pos, conso)549 # # plt.yticks(x_pos, people)550 # # plt.xlabel('Performance')551 # # plt.title('How fast do you want to go today?')552 553 # plt.show()554 555 556 557 558 559 548 560 549 # .. Extract data depending on C.L. arguments .. … … 569 558 selected_items = bilan.get_items(args.inc) 570 559 571 print(selected_items) 560 last_filled_date = max([ 561 item.date for item in selected_items 562 if item.filled 563 ]) 572 564 573 565 # .. Compute data to be plotted .. … … 577 569 xcoord = np.linspace(1, nb_items, num=nb_items) 578 570 dates = [item.date for item in selected_items] 571 572 projet.get_theo_eq(dates) 579 573 580 574 cumul = np.array([item.conso for item in selected_items], … … 585 579 consos = np.array(consos, dtype=float) 586 580 587 if projet.project == "gencmip6":588 alloc1 = 5.e6589 alloc2 = projet.alloc - alloc1590 conso_per_day = 2 * alloc1 / projet.days591 conso_per_day_2 = 2 * alloc2 / projet.days592 else:593 conso_per_day = projet.alloc / projet.days594 conso_per_day_2 = None595 596 theo_uses = np.array(597 [100.*item.theo_use for item in selected_items],598 dtype=float599 )600 581 real_uses = np.array( 601 582 [100.*item.real_use for item in selected_items], 602 583 dtype=float 603 584 ) 604 theo_equs = np.array( 605 [100. * bilan.poly_theo(date.timetuple().tm_yday) 606 for date in dates], 607 dtype=float 608 ) 609 theo_delay = np.array( 610 [100. * bilan.poly_delay(date.timetuple().tm_yday) 611 for date in dates], 612 dtype=float 613 ) 585 586 theo_uses = [] 587 for date in dates: 588 for item in projet.alloc_items: 589 if date >= item.start_date.date() and \ 590 date <= item.end_date.date(): 591 poly_theo = item.theo_eq 592 break 593 theo_uses.append(100. * poly_theo(dates.index(date))) 594 delay_uses = delay * [0.,] + theo_uses[:-delay] 595 theo_uses = np.array(theo_uses, dtype=float) 596 delay_uses = np.array(delay_uses, dtype=float) 597 614 598 615 599 run_mean = np.array([item.run_mean for item in selected_items], … … 630 614 # ... Plot data ... 631 615 # ----------------- 632 plot_data(ax_conso, ax_theo, xcoord, dates, 633 consos, theo_uses, real_uses, theo_equs, theo_delay, 634 run_mean, pen_mean, run_std, pen_std) 616 plot_data( 617 ax_conso, ax_theo, xcoord, dates, 618 consos, real_uses, theo_uses, delay_uses, 619 run_mean, pen_mean, run_std, pen_std 620 ) 635 621 636 622 # ... Tweak figure ... 637 623 # -------------------- 638 title = "Consommation {}\n({:%d/%m/%Y} - {:%d/%m/%Y})".format( 624 # title = "Consommation {}\n({:%d/%m/%Y} - {:%d/%m/%Y})".format( 625 # projet.project.upper(), 626 # projet.start_date, 627 # projet.end_date 628 # ) 629 title = "Consommation {}\n(le {:%d/%m/%Y})".format( 639 630 projet.project.upper(), 640 projet.start_date, 641 projet.end_date 631 today, 642 632 ) 643 633 644 634 plot_config( 645 fig, ax_conso, ax_theo, xcoord, dates, title, 646 conso_per_day, conso_per_day_2 647 ) 635 fig, ax_conso, ax_theo, 636 xcoord, dates, real_uses[dates.index(last_filled_date)], 637 title, projet 638 ) 639 640 648 641 649 642 # ... Save figure ... 650 643 # ------------------- 651 # img_in = os.path.join(DIR["PLOT"], "{}.pdf".format(img_name))652 # img_out = os.path.join(DIR["SAVEPLOT"],653 # "{}_{}.pdf".format(img_name, today))654 img_in = os.path.join(".", "{}.pdf".format(img_name))655 i mg_out = os.path.join(".",656 "{}_{}.pdf".format(img_name, today))657 658 plot_save(img_ in, img_out, title)659 660 # #... Publish figure on dods ...661 # #------------------------------662 #if args.dods:663 #if args.verbose:664 #print("Publish figure on dods")665 # dods_cp(img_in, DIR)644 img_out = os.path.join( 645 DIR["PLOT"], args.center, args.project, 646 "{}_{:%Y%m%d}.pdf".format(img_name, today) 647 ) 648 if args.verbose: 649 print("Save image as {}".format(img_out)) 650 651 plot_save(img_out, title) 652 653 # ... Publish figure on dods ... 654 # ------------------------------ 655 if args.dods: 656 if args.verbose: 657 print("Publish figure on dods") 658 dods_cp(img_out, img_name, DODS) 666 659 667 660 # if args.show: -
TOOLS/ConsoGENCI/trunk/plot
- Property svn:ignore
-
old new 1 * 1 2 *.pdf 2 3 *.jpg
-
- Property svn:ignore
Note: See TracChangeset
for help on using the changeset viewer.