Changeset 2775 for TOOLS


Ignore:
Timestamp:
03/13/16 15:33:40 (8 years ago)
Author:
labetoulle
Message:

Overall cleaning and refactoring

Location:
TOOLS/ConsoGENCI/trunk
Files:
18 added
1 deleted
9 edited

Legend:

Unmodified
Added
Removed
  • TOOLS/ConsoGENCI/trunk

    • Property svn:ignore set to
      *.pdf
  • TOOLS/ConsoGENCI/trunk/bin

    • Property svn:ignore set to
      db_data.py
  • TOOLS/ConsoGENCI/trunk/bin/init_alloc_tbl.py

    r2751 r2775  
    11#!/usr/bin/env python 
    22# -*- 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# ==================================================================== # 
    311 
    412# ==================================================================== # 
     
    1725# Application library imports 
    1826import libconsodb as cdb 
     27import db_data 
    1928 
    2029 
     
    2332 
    2433  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     }, 
    5234    { 
    5335      "name": "gencmip6", 
     
    10486      "end": "2016-12-31 23:59:59", 
    10587    }, 
     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    }, 
    106115  ] 
    107116 
    108117  # 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" 
    114123 
    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  ) 
    116129 
    117130  # Build request 
  • TOOLS/ConsoGENCI/trunk/bin/init_conso_tbl.py

    r2751 r2775  
    11#!/usr/bin/env python 
    22# -*- 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# ==================================================================== # 
    311 
    412# This must come first 
     
    1523import libconso_db as cdb 
    1624import libconso_cpt as ccpt 
     25import db_data 
    1726 
    1827pp = pprint.PrettyPrinter(indent=2) 
     
    7887  if args.verbose: 
    7988    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  ) 
    8699 
    87100  # .. Extract allocation id from table .. 
  • TOOLS/ConsoGENCI/trunk/bin/libconso.py

    r2751 r2775  
    11#!/usr/bin/env python 
    22# -*- 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# ==================================================================== # 
    311 
    412# this must come first 
     
    1321import subprocess 
    1422import datetime as dt 
    15 # import numpy as np 
     23import numpy as np 
    1624import ConfigParser as cp 
    1725 
     
    1927 
    2028 
    21 ######################################## 
    22 def dods_cp(filein, DIR): 
    23   """ 
    24   """ 
    25   if not DIR["DODS"]: 
     29######################################################################## 
     30def dods_cp(img_out, img_name, DODS): 
     31  """ 
     32  """ 
     33  if not DODS["DIR"]: 
    2634    print("DODS directory not defined") 
    2735    return 
    2836 
    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] 
    3957 
    4058  try : 
     
    4361    print("Error in convert for {}:\n{}".format(fileout, rc)) 
    4462 
     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 
    4582  return 
    4683 
    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######################################################################## 
    49104def parse_config(filename): 
    50105 
    51106  DIR = {} 
    52   OUT = {} 
     107  DODS = {} 
    53108 
    54109  config = cp.ConfigParser(allow_no_value=True) 
     
    56111  config.read(filename) 
    57112 
    58   for section in ("projet", "directories", "files"): 
     113  for section in ("projet", "directories"): 
    59114    if not config.has_section(section): 
    60115      print("Missing section {} in {}, we stop".format(section, filename)) 
    61116      exit(1) 
    62117 
    63   # .. Project name .. 
    64   # ------------------ 
     118  # ... Project name ... 
     119  # -------------------- 
    65120  section = "projet" 
    66121  option  = "name" 
    67122  project_name = config.get(section, option) 
    68123 
    69   # ..Common directories .. 
    70   # ----------------------- 
     124  # ... Common directories ... 
     125  # -------------------------- 
    71126  section = "directories" 
    72127  for option in config.options(section): 
     
    80135        print("Could not create {}:\n{}".format(DIR[option], rc)) 
    81136 
    82   # ..Common files .. 
    83   # ----------------- 
    84   section = "files" 
     137  # .. DODS configuration ... 
     138  # ------------------------- 
     139  section = "dods" 
    85140  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######################################################################## 
    92147def string_to_percent(x): 
    93148  """ 
     
    96151 
    97152 
    98 ######################################## 
     153######################################################################## 
    99154def string_to_size_unit(x): 
    100155  """ 
     
    108163 
    109164 
    110 ######################################## 
     165######################################################################## 
    111166def string_to_float(x): 
    112167  """ 
     
    115170 
    116171 
    117 ######################################## 
    118 def string_to_date(ssaammjj, fmt="%Y-%m-%d"): 
    119   """ 
    120   """ 
    121   return dt.datetime.strptime(ssaammjj, fmt) 
    122  
    123  
    124 ######################################## 
     172######################################################################## 
     173def 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######################################################################## 
    125190def string_to_datetime(string, fmt="%Y-%m-%d-%H:%M"): 
    126191  """ 
     
    129194 
    130195 
    131 # ######################################## 
     196# ######################################################################## 
    132197# def date_to_string(dtdate, fmt="%Y-%m-%d"): 
    133198#   """ 
     
    136201 
    137202 
    138 ######################################## 
     203######################################################################## 
    139204def where_we_run(): 
    140205 
     
    150215 
    151216 
    152 ######################################## 
     217######################################################################## 
    153218def get_last_file(dir_data, pattern): 
    154219  """ 
     
    166231 
    167232 
    168 ######################################## 
     233######################################################################## 
    169234def get_input_files(dir_data, file_list): 
    170235  """ 
     
    184249 
    185250 
    186 ######################################## 
    187 def plot_save(img_in, img_out, title): 
     251######################################################################## 
     252def plot_save(img_out, title): 
    188253  """ 
    189254  """ 
     
    192257  dpi = 200. 
    193258 
    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: 
    196268    pdf.savefig(dpi=dpi) 
    197269 
    198     # pdf file's metadata 
     270    # ... pdf file's metadata ... 
     271    # --------------------------- 
    199272    d = pdf.infodict() 
    200273    d["Title"]   = title 
     
    206279    # d["ModDate"] = dt.datetime.today() 
    207280 
    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######################################################################## 
     283class 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 
    235302 
    236303    delta = self.end_date - self.start_date 
    237304    self.days = delta.days + 1 
    238305 
    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######################################################################## 
     319class 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######################################################################## 
    241429class SizeUnit(object): 
    242   #--------------------------------------- 
     430  #--------------------------------------------------------------------- 
    243431  def __init__(self, size, unit): 
    244432    self.size = size 
    245433    self.unit = unit 
    246434 
    247   #--------------------------------------- 
     435  #--------------------------------------------------------------------- 
    248436  def __repr__(self): 
    249437    return "{:6.2f}{}o".format(self.size, self.unit) 
    250438 
    251   #--------------------------------------- 
     439  #--------------------------------------------------------------------- 
    252440  def convert_size(self, unit_out): 
    253441    """ 
     
    271459 
    272460 
    273 ######################################## 
     461######################################################################## 
    274462if __name__ == '__main__': 
    275463  pass 
  • TOOLS/ConsoGENCI/trunk/bin/libconso_cpt.py

    r2751 r2775  
    11#!/usr/bin/env python 
    22# -*- 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# ==================================================================== # 
    311 
    412# =================================================================== # 
     
    128136def cpt_pattern(project, center): 
    129137 
    130   return "cpt_{}_{}_*.dat".format(project, center) 
     138  return "cpt_{}_{}_*.dat".format(center, project) 
    131139 
    132140 
     
    289297    res = file_list 
    290298 
    291   return set(res) 
     299  # return set(res) 
     300  return sorted(res) 
    292301 
    293302 
  • TOOLS/ConsoGENCI/trunk/bin/libconso_db.py

    r2751 r2775  
    11#!/usr/bin/env python 
    22# -*- 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# ==================================================================== # 
    311 
    412# =================================================================== # 
  • TOOLS/ConsoGENCI/trunk/bin/plot_bilan.py

    r2713 r2775  
    11#!/usr/bin/env python 
    22# -*- 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# ==================================================================== # 
    311 
    412# this must come first 
     
    1624from libconso import * 
    1725import libconsodb as cdb 
    18  
    19  
    20 ######################################## 
     26import db_data 
     27 
     28 
     29######################################################################## 
     30class 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######################################################################## 
    2141class DataDict(dict): 
    22   #--------------------------------------- 
     42  #--------------------------------------------------------------------- 
    2343  def __init__(self): 
    2444    self = {} 
    2545 
    26   #--------------------------------------- 
     46  #--------------------------------------------------------------------- 
    2747  def init_range(self, date_beg, date_end, inc=1): 
    2848    """ 
     
    3858      self.add_item(date) 
    3959 
    40   #--------------------------------------- 
     60  #--------------------------------------------------------------------- 
    4161  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 
    4576    table_name = "conso.tbl_consumption" 
    4677    request = ( 
    47       "SELECT date, total_hrs " 
     78      "SELECT date, total_hrs, allocation_id " 
    4879      "FROM " + table_name + " " 
    49       "WHERE allocation_id = '" + str(projet.id) + "'" 
    50       "  AND login IS NULL " 
     80      "WHERE login IS NULL " 
     81      "  AND " + id_condition + " " 
    5182      "ORDER BY date" 
    5283      ";" 
    5384    ) 
     85 
     86    if args.verbose: 
     87      print("Access table \"{}\"".format(table_name)) 
     88      print(request) 
    5489    cdb.select_db(cursor, request) 
    5590 
    56     for date, conso in cursor: 
     91    for date, conso, alloc_id in cursor: 
    5792      if date.date() in self: 
    58         # print(date.date(), conso) 
    59         # Days since start_date 
    6093        real_use = conso / projet.alloc 
    6194        self.add_item( 
    62           date=date, 
     95          date=date.date(), 
    6396          conso=conso, 
    6497          real_use=real_use, 
     
    6699        self[date.date()].fill() 
    67100 
    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  #--------------------------------------------------------------------- 
    104102  def add_item(self, date, conso=np.nan, 
    105103               real_use=np.nan, theo_use=np.nan, 
     
    108106    """ 
    109107    """ 
    110     self[date.date()] = Conso( 
     108    # self[date.date()] = Conso( 
     109    self[date] = Conso( 
    111110      date, conso, 
    112111      real_use, theo_use, 
     
    115114    ) 
    116115 
    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  #--------------------------------------------------------------------- 
    158117  def get_items_in_range(self, date_beg, date_end, inc=1): 
    159118    """ 
    160119    """ 
    161120    items = (item for item in self.itervalues() 
    162                    if item.date >= date_beg and 
    163                       item.date <= date_end) 
     121                   if item.date.date() >= date_beg and 
     122                      item.date.date() <= date_end) 
    164123    items = sorted(items, key=lambda item: item.date) 
    165124 
    166125    return items[::inc] 
    167126 
    168   #--------------------------------------- 
     127  #--------------------------------------------------------------------- 
    169128  def get_items_in_full_range(self, inc=1): 
    170129    """ 
    171130    """ 
     131 
    172132    items = (item for item in self.itervalues()) 
    173133    items = sorted(items, key=lambda item: item.date) 
     
    175135    return items[::inc] 
    176136 
    177   #--------------------------------------- 
     137  #--------------------------------------------------------------------- 
    178138  def get_items(self, inc=1): 
    179139    """ 
     
    187147 
    188148class Conso(object): 
    189   #--------------------------------------- 
     149  #--------------------------------------------------------------------- 
    190150  def __init__(self, date, conso=np.nan, 
    191151               real_use=np.nan, theo_use=np.nan, 
     
    204164    self.filled   = False 
    205165 
    206   #--------------------------------------- 
     166  #--------------------------------------------------------------------- 
    207167  def __repr__(self): 
    208168    return "{:.2f} ({:.2%})".format(self.conso, self.real_use) 
    209169 
    210   #--------------------------------------- 
     170  #--------------------------------------------------------------------- 
    211171  def isfilled(self): 
    212172    return self.filled 
    213173 
    214   #--------------------------------------- 
     174  #--------------------------------------------------------------------- 
    215175  def fill(self): 
    216176    self.filled = True 
    217177 
    218178 
    219 ######################################## 
     179######################################################################## 
    220180def plot_init(): 
    221181  paper_size  = np.array([29.7, 21.0]) 
     
    226186 
    227187 
    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######################################################################## 
     189def 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): 
    232194  """ 
    233195  """ 
     
    249211    label="conso\nréelle (%)" 
    250212  ) 
     213 
    251214  ax_theo.plot( 
    252     xcoord, theo_equs, "--", 
     215    xcoord, theo_uses, "--", 
    253216    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, 
    259217    solid_capstyle="round", solid_joinstyle="round", 
    260218    label="conso\nthéorique (%)" 
    261219  ) 
     220 
    262221  ax_theo.plot( 
    263     xcoord, theo_delay, ":", 
     222    xcoord, delay_uses, ":", 
    264223    color="firebrick", linewidth=0.5, 
    265224    solid_capstyle="round", solid_joinstyle="round", 
     
    267226  ) 
    268227 
    269  
    270 ######################################## 
    271 def plot_config(fig, ax_conso, ax_theo, xcoord, dates, title, 
    272                 conso_per_day, conso_per_day_2): 
     228######################################################################## 
     229def plot_config( 
     230  fig, ax_conso, ax_theo, 
     231  xcoord, dates, max_real_use, 
     232  title, projet 
     233): 
    273234  """ 
    274235  """ 
     
    282243    ymax = conso_max  # + conso_max*.1 
    283244  else: 
    284     ymax = 3. * max(conso_per_day, conso_per_day_2) 
     245    ymax = 3. * projet.max_daily_conso 
    285246 
    286247  if conso_max > ymax: 
     
    307268  ax_theo.set_ylim(0., 100) 
    308269 
    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 
    310297  (date_beg, date_end) = (dates[0], dates[-1]) 
    311298  date_fmt = "{:%d-%m}" 
     
    331318  # ax.yaxis.set_minor_locator(minor_locator) 
    332319 
    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) 
    338323 
    339324  ax_theo.spines["right"].set_color("firebrick") 
     
    341326  ax_theo.yaxis.label.set_color("firebrick") 
    342327 
    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  
    349328  for x, d in zip(xcoord, dates): 
    350329    # if d.weekday() == 0 and d.hour == 0: 
    351330    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 
    356337  for ax, label in ( 
    357338    (ax_conso, "heures"), 
     
    361342    ax.tick_params(axis="y", labelsize="small") 
    362343 
    363   # 4) Define plot size 
     344  # 5) Define plot size 
    364345  fig.subplots_adjust( 
    365346    left=0.08, 
    366347    bottom=0.09, 
    367348    right=0.93, 
    368     top=0.93, 
     349    top=0.92, 
    369350  ) 
    370351 
     
    378359    ax.legend(loc=loc, fontsize="x-small", frameon=False) 
    379360 
    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######################################################################## 
    382377def get_arguments(): 
    383378  parser = ArgumentParser() 
     
    407402 
    408403 
    409 ######################################## 
     404######################################################################## 
    410405if __name__ == '__main__': 
    411406 
     
    416411  args = get_arguments() 
    417412 
     413  print(os.getcwd()) 
     414  print(os.path.abspath(__file__)) 
     415 
    418416  # ... Turn interactive mode off ... 
    419417  # --------------------------------- 
     
    428426    plt.ioff() 
    429427 
    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) 
    433444 
    434445  # (file_param, file_utheo, file_data) = \ 
     
    436447  #                     [OUT["PARAM"], OUT["UTHEO"], OUT["BILAN"]]) 
    437448 
    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  ) 
    452465 
    453466  # 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)) 
    460474  #   print(fmt_str.format("file_param", file_param)) 
    461475  #   print(fmt_str.format("file_utheo", file_utheo)) 
    462476  #   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() 
    464498 
    465499  # .. Get project info .. 
     
    473507    "SELECT * " 
    474508    "FROM " + table_name + " " 
    475     "WHERE project = '" + args.project + "'" 
     509    "WHERE project = '" + args.project + "' " 
     510    "ORDER BY start_date" 
    476511    ";" 
    477512  ) 
     
    481516  # print(cursor.fetchall()) 
    482517 
    483   print(cursor.description) 
     518  projet = Project(args.project, args.center) 
     519  # print(cursor.description) 
    484520  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      ) 
    494536 
    495537  # .. Fill in data .. 
     
    497539  # ... Initialization ... 
    498540  # ---------------------- 
     541 
    499542  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  # ------------------------------- 
    515547  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  
    559548 
    560549  # .. Extract data depending on C.L. arguments .. 
     
    569558    selected_items = bilan.get_items(args.inc) 
    570559 
    571   print(selected_items) 
     560  last_filled_date = max([ 
     561    item.date for item in selected_items 
     562    if item.filled 
     563  ]) 
    572564 
    573565  # .. Compute data to be plotted .. 
     
    577569  xcoord = np.linspace(1, nb_items, num=nb_items) 
    578570  dates = [item.date for item in selected_items] 
     571 
     572  projet.get_theo_eq(dates) 
    579573 
    580574  cumul = np.array([item.conso for item in selected_items], 
     
    585579  consos = np.array(consos, dtype=float) 
    586580 
    587   if projet.project == "gencmip6": 
    588     alloc1 = 5.e6 
    589     alloc2 = projet.alloc - alloc1 
    590     conso_per_day   = 2 * alloc1 / projet.days 
    591     conso_per_day_2 = 2 * alloc2 / projet.days 
    592   else: 
    593     conso_per_day = projet.alloc / projet.days 
    594     conso_per_day_2 = None 
    595  
    596   theo_uses = np.array( 
    597     [100.*item.theo_use for item in selected_items], 
    598     dtype=float 
    599   ) 
    600581  real_uses = np.array( 
    601582    [100.*item.real_use for item in selected_items], 
    602583    dtype=float 
    603584  ) 
    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 
    614598 
    615599  run_mean = np.array([item.run_mean for item in selected_items], 
     
    630614  # ... Plot data ... 
    631615  # ----------------- 
    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  ) 
    635621 
    636622  # ... Tweak figure ... 
    637623  # -------------------- 
    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( 
    639630    projet.project.upper(), 
    640     projet.start_date, 
    641     projet.end_date 
     631    today, 
    642632  ) 
    643633 
    644634  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   
    648641 
    649642  # ... Save figure ... 
    650643  # ------------------- 
    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   img_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) 
    666659 
    667660  # if args.show: 
  • TOOLS/ConsoGENCI/trunk/plot

    • Property svn:ignore
      •  

        old new  
         1* 
        12*.pdf 
        23*.jpg 
Note: See TracChangeset for help on using the changeset viewer.