From d060046eb7d4d323d06c751dd6b9d5c371ac3f33 Mon Sep 17 00:00:00 2001 From: MUNET Claire Date: Tue, 23 Oct 2018 17:54:42 +0200 Subject: [PATCH] essai de renommage PSEN --- .../ExtractGeneratorLoadLineandTransfoDico.py | 391 - PSEN_Eficas/PSEN/exploit2.ows | 23 - PSEN_Eficas/PSEN_Cata.py | 2788 -------- PSEN_Eficas/PSEN_Cata_PF.py | 2446 ------- PSEN_Eficas/__init__.py | 0 PSEN_Eficas/com.py | 607 -- PSEN_Eficas/configuration_PSEN.py | 43 - PSEN_Eficas/debugPFWrapper.py | 28 - PSEN_Eficas/mesScripts.py | 35 - PSEN_Eficas/opsPSEN.py | 111 - PSEN_Eficas/opsPSEN_PF.py | 112 - PSEN_Eficas/prefs.py | 22 - PSEN_Eficas/prefs_PSEN.py | 45 - PSEN_Eficas/properties.py | 24 - PSEN_Eficas/qtEficas_PSEN.py | 44 - PSEN_Eficas/usrCmdPF.py | 29 - PSSE_PF_Eficas/PSEN | 1 - .../PSEN => PSSE_PF_Eficas/PSEN2}/OutLog.py | 0 .../PSEN2}/PFWrapper.py | 0 .../PSEN2}/PSENconfig.py | 0 .../PSEN2}/PSSEWrapper.py | 465 +- .../PSEN => PSSE_PF_Eficas/PSEN2}/__init__.py | 0 .../PSEN => PSSE_PF_Eficas/PSEN2}/comfile.py | 0 .../PSEN2}/correct_comtask.py | 0 .../PSEN => PSSE_PF_Eficas/PSEN2}/ecd.py | 0 .../PSEN2}/read_pfd_wrapper.py | 0 .../PSEN2}/run_in_PFfunction.py | 0 .../PSEN2}/runreadOPF.py | 0 .../PSEN2}/support_functions.py | 6264 ++++++++--------- .../PSEN2}/support_functionsPF.py | 0 .../PSEN => PSSE_PF_Eficas/PSEN2}/usrCmd.py | 0 .../PSEN => PSSE_PF_Eficas/PSEN2}/usrCmdPF.py | 0 32 files changed, 3324 insertions(+), 10154 deletions(-) delete mode 100755 PSEN_Eficas/ExtractGeneratorLoadLineandTransfoDico.py delete mode 100755 PSEN_Eficas/PSEN/exploit2.ows delete mode 100644 PSEN_Eficas/PSEN_Cata.py delete mode 100644 PSEN_Eficas/PSEN_Cata_PF.py delete mode 100644 PSEN_Eficas/__init__.py delete mode 100644 PSEN_Eficas/com.py delete mode 100755 PSEN_Eficas/configuration_PSEN.py delete mode 100644 PSEN_Eficas/debugPFWrapper.py delete mode 100755 PSEN_Eficas/mesScripts.py delete mode 100755 PSEN_Eficas/opsPSEN.py delete mode 100644 PSEN_Eficas/opsPSEN_PF.py delete mode 100755 PSEN_Eficas/prefs.py delete mode 100755 PSEN_Eficas/prefs_PSEN.py delete mode 100755 PSEN_Eficas/properties.py delete mode 100755 PSEN_Eficas/qtEficas_PSEN.py delete mode 100644 PSEN_Eficas/usrCmdPF.py delete mode 160000 PSSE_PF_Eficas/PSEN rename {PSEN_Eficas/PSEN => PSSE_PF_Eficas/PSEN2}/OutLog.py (100%) rename {PSEN_Eficas/PSEN => PSSE_PF_Eficas/PSEN2}/PFWrapper.py (100%) rename {PSEN_Eficas/PSEN => PSSE_PF_Eficas/PSEN2}/PSENconfig.py (100%) rename {PSEN_Eficas/PSEN => PSSE_PF_Eficas/PSEN2}/PSSEWrapper.py (85%) mode change 100755 => 100644 rename {PSEN_Eficas/PSEN => PSSE_PF_Eficas/PSEN2}/__init__.py (100%) mode change 100755 => 100644 rename {PSEN_Eficas/PSEN => PSSE_PF_Eficas/PSEN2}/comfile.py (100%) rename {PSEN_Eficas/PSEN => PSSE_PF_Eficas/PSEN2}/correct_comtask.py (100%) rename {PSEN_Eficas/PSEN => PSSE_PF_Eficas/PSEN2}/ecd.py (100%) rename {PSEN_Eficas/PSEN => PSSE_PF_Eficas/PSEN2}/read_pfd_wrapper.py (100%) rename {PSEN_Eficas/PSEN => PSSE_PF_Eficas/PSEN2}/run_in_PFfunction.py (100%) rename {PSEN_Eficas/PSEN => PSSE_PF_Eficas/PSEN2}/runreadOPF.py (100%) rename {PSEN_Eficas/PSEN => PSSE_PF_Eficas/PSEN2}/support_functions.py (97%) mode change 100755 => 100644 rename {PSEN_Eficas/PSEN => PSSE_PF_Eficas/PSEN2}/support_functionsPF.py (100%) rename {PSEN_Eficas/PSEN => PSSE_PF_Eficas/PSEN2}/usrCmd.py (100%) rename {PSEN_Eficas/PSEN => PSSE_PF_Eficas/PSEN2}/usrCmdPF.py (100%) diff --git a/PSEN_Eficas/ExtractGeneratorLoadLineandTransfoDico.py b/PSEN_Eficas/ExtractGeneratorLoadLineandTransfoDico.py deleted file mode 100755 index 73ff2a0f..00000000 --- a/PSEN_Eficas/ExtractGeneratorLoadLineandTransfoDico.py +++ /dev/null @@ -1,391 +0,0 @@ - -############################################################ -# ojectif de ce module: extraire des donnes pour afficher dans l'interface Eficas -############################################################ -NoBreakersandSwitches = True - - -def ExtractGeneratorLoadLineandTransfoDico(NetworkFile,PSSE_PATH, PSSPY_PATH): - - import os - import sys - import numpy as np - - #print NetworkFile - #print PSSE_PATH - #psspy_path34 = os.path.join("../", PSSE_PATH, "PSSPY27") - sys.path.append(PSSPY_PATH) - os.environ['PATH'] += ';' + PSSE_PATH + ';' - - import psspy - import redirect - - ###initialization PSSE - psspy.psseinit(10000) - _i=psspy.getdefaultint() - _f=psspy.getdefaultreal() - _s=psspy.getdefaultchar() - redirect.psse2py() - - # Silent execution of PSSe - islct=6 # 6=no output; 1=standard - psspy.progress_output(islct) - - #open Network File - psspy.case(NetworkFile) - - #Extract Loads - sid = -1 #all buses - flag = 1 #all in service loads/generators (4 all loads/generators) - - - string = ['NUMBER'] - ierr,iarray = psspy.aloadint(sid,flag,string) - - string = ['NAME','ID','EXNAME'] - ierr,carray = psspy.aloadchar(sid,flag,string) - - string = ['mvaact'] - ierr, xdata = psspy.aloadcplx(sid, flag, string) - - LoadDico = {} # [Bus name, load ID, extended bus name, bus number] - for i in range(len(iarray[0])): - idname = "Lo" + carray[1][i].strip() -# try: #id is an integer -# idname = "Lo" + str(int(carray[1][i])) -# except: #id is not an integer -# idname = "Lo" + carray[1][i] - loadname = carray[0][i].strip()+ "__" + idname - loadname = loadname.replace(" ","_") - loadname = loadname.replace("-","_") - loadname = loadname.replace(".","_") - loadname = loadname.replace("&","and") - loadname = loadname.replace("%","pct") - loadname = loadname.replace("=","eq") - loadname = loadname.replace("#","_") - loadname = loadname.replace("$","_") - loadname = loadname.replace("/","_") - loadname = loadname.replace("\\","_") - try: - int(loadname[0]) - loadname="_" + loadname - except: - pass - LoadDico[loadname]= {} - LoadDico[loadname]['NAME'] = carray[0][i].strip() - LoadDico[loadname]['ID'] = carray[1][i] - LoadDico[loadname]['EXNAME'] =carray[2][i] - LoadDico[loadname]['NUMBER']=iarray[0][i] - LoadDico[loadname]['P']=np.real(xdata)[0][i] - LoadDico[loadname]['Q']=np.imag(xdata)[0][i] - - #Extract Generators - sid = -1 #all buses - flag = 1 #all in service loads/generators (4 all loads/generators) - - string = ['NUMBER'] - ierr,iarray = psspy.amachint(sid,flag,string) - - string = ['NAME','ID','EXNAME'] - ierr,carray = psspy.amachchar(sid,flag,string) - - rstrings = ['pgen','qgen','mbase','pmax','qmax','pmin','qmin'] - ierr, rarray = psspy.amachreal(sid, flag, rstrings) - - MachineDico = {} # [Bus name, machine ID, extended bus name, bus number] - for i in range(len(iarray[0])): - idname = "Gr" + carray[1][i].strip() -## try: -## idname = "Gr" + str(int(carray[1][i])) -## except: -## idname = "Gr" + carray[1][i] - machinename = carray[0][i].strip()+ "__" + idname - machinename = machinename.replace(" ","_") - machinename = machinename.replace("-","_") - machinename = machinename.replace(".","_") - machinename = machinename.replace("&","and") - machinename = machinename.replace("%","pct") - machinename = machinename.replace("=","eq") - machinename = machinename.replace("#","_") - machinename = machinename.replace("$","_") - machinename = machinename.replace("/","_") - machinename = machinename.replace("\\","_") - try: - int(machinename[0]) - machinename="_" + machinename - except: - pass - MachineDico[machinename]={} - MachineDico[machinename]['NAME'] = carray[0][i].strip() - MachineDico[machinename]['ID'] = carray[1][i] - MachineDico[machinename]['EXNAME'] =carray[2][i] - MachineDico[machinename]['NUMBER']=iarray[0][i] - MachineDico[machinename]['P']=rarray[0][i] - MachineDico[machinename]['Q']=rarray[1][i] - MachineDico[machinename]['PMAX']=rarray[3][i] - MachineDico[machinename]['QMAX']=rarray[4][i] - MachineDico[machinename]['PMIN']=rarray[5][i] - MachineDico[machinename]['QMIN']=rarray[6][i] - - #Extract Motors - sid = -1 #all buses - flag = 1 #all in service loads/generators (4 all loads/generators) - - string = ['NUMBER','PSETCODE','BASECODE'] - ierr,iarray = psspy.aindmacint(sid,flag,string) - - string = ['NAME','ID','EXNAME'] - ierr,carray = psspy.aindmacchar(sid,flag,string) - - rstrings = ['psetpoint','mbase','p','q'] - ierr, rarray = psspy.aindmacreal(sid, flag, rstrings) - - - MotorDico = {} # [Bus name, machine ID, extended bus name, bus number] - for i in range(len(iarray[0])): - idname = "Mo" + carray[1][i].strip() -## try: -## idname = "Gr" + str(int(carray[1][i])) -## except: -## idname = "Gr" + carray[1][i] - motorname = carray[0][i].strip()+ "__" + idname - motorname = motorname.replace(" ","_") - motorname = motorname.replace("-","_") - motorname = motorname.replace(".","_") - motorname = motorname.replace("&","and") - motorname = motorname.replace("%","pct") - motorname = motorname.replace("=","eq") - motorname = motorname.replace("#","_") - motorname = motorname.replace("$","_") - motorname = motorname.replace("/","_") - motorname = motorname.replace("\\","_") - - try: - int(motorname[0]) - motorname="_" + motorname - except: - pass - MotorDico[motorname]={} - MotorDico[motorname]['NAME'] = carray[0][i].strip() - MotorDico[motorname]['ID'] = carray[1][i] - MotorDico[motorname]['EXNAME'] =carray[2][i] - MotorDico[motorname]['NUMBER']=iarray[0][i] - MotorDico[motorname]['PSETCODE']=iarray[1][i] - MotorDico[motorname]['BASECODE']=iarray[2][i] - MotorDico[motorname]['PSETPOINT']=rarray[0][i] - MotorDico[motorname]['MBASE']=rarray[1][i] - MotorDico[motorname]['P']=rarray[2][i] - MotorDico[motorname]['Q']=rarray[3][i] - - - #Extract Lignes - sid = -1 - owner = 1 - ties = 1 - flag = 2 #6 for two-winding transfos - entry = 1 #each branch once, not both directions - string = ['FROMNUMBER','TONUMBER'] - ierr,iarray = psspy.abrnint(sid,owner,ties,flag,entry,string) - string = ['FROMNAME','TONAME','FROMEXNAME','TOEXNAME','ID'] - ierr,carray = psspy.abrnchar(sid,owner,ties,flag,entry,string) - - LineDico = {} #[linename, Bus name 1, Bus name 2, ID, extended bus name 1, extended bus name 2, bus number 1, bus number 2] - for i in range(len(iarray[0])): - idname = carray[4][i].strip() - #idname = carray[4][i] - if '@' in idname: - idname = idname.replace('@','Br') - elif '*' in idname: - idname = idname.replace('*','Sw') - else: - try: - idname = 'Li' + str(int(idname)) - except: - idname = 'Li' + idname - linename =carray[0][i].strip() + "__" + carray[1][i].strip() + "__" + idname - linename = linename.replace(" ","_") - linename = linename.replace("-","_") - linename = linename.replace(".","_") - linename = linename.replace("&","and") - linename = linename.replace("%","pct") - linename = linename.replace("=","eq") - linename = linename.replace("#","_") - linename = linename.replace("$","_") - linename = linename.replace("/","_") - linename = linename.replace("\\","_") - try: - int(linename[0]) - linename="_" + linename - except: - pass - if NoBreakersandSwitches: - if 'Br' not in idname and 'Sw' not in idname: - LineDico[linename]={} - LineDico[linename]['FROMNAME']=carray[0][i].strip() - LineDico[linename]['TONAME']=carray[1][i].strip() - LineDico[linename]['ID']=carray[4][i] - LineDico[linename]['FROMEXNAME']=carray[2][i] - LineDico[linename]['TOEXNAME']=carray[3][i] - LineDico[linename]['FROMNUMBER']=iarray[0][i] - LineDico[linename]['TONUMBER']=iarray[1][i] - - - print "Read lines" - - #Extract Transfos - sid = -1 - owner = 1 - ties = 1 - flag = 6 #two-winding transfos - entry = 1 #each branch once, not both directions - string = ['FROMNUMBER','TONUMBER'] - ierr,iarray = psspy.abrnint(sid,owner,ties,flag,entry,string) - string = ['FROMNAME','TONAME','FROMEXNAME','TOEXNAME','ID'] - ierr,carray = psspy.abrnchar(sid,owner,ties,flag,entry,string) - - TfoDico = {} #[linename, Bus name 1, Bus name 2, machine ID, extended bus name 1, extended bus name 2, bus number 1, bus number 2] - for i in range(len(iarray[0])): - idname = 'Tr' + carray[4][i].strip() -## try: -## idname = 'Tr' + str(int(carray[4][i])) -## except: -## idname = 'Tr' + carray[4][i] - tfoname = carray[0][i].strip() + "__" + carray[1][i].strip() + "__" + idname - tfoname = tfoname.replace(" ","_") - tfoname = tfoname.replace("-","_") - tfoname = tfoname.replace(".","_") - tfoname = tfoname.replace("&","and") - tfoname = tfoname.replace("%","pct") - tfoname = tfoname.replace("=","eq") - tfoname = tfoname.replace("#","_") - tfoname = tfoname.replace("$","_") - tfoname = tfoname.replace("/","_") - tfoname = tfoname.replace("\\","_") - try: - int(tfoname[0]) - tfoname="_" + tfoname - except: - pass - TfoDico[tfoname]={} - TfoDico[tfoname]['FROMNAME']=carray[0][i].strip() - TfoDico[tfoname]['TONAME']=carray[1][i].strip() - TfoDico[tfoname]['ID']=carray[4][i] - TfoDico[tfoname]['FROMEXNAME']=carray[2][i] - TfoDico[tfoname]['TOEXNAME']=carray[3][i] - TfoDico[tfoname]['FROMNUMBER']=iarray[0][i] - TfoDico[tfoname]['TONUMBER']=iarray[1][i] - TfoDico[tfoname]['#WIND']=2 - print "Read Transfos" - - #Extract 3 winding Transfos - sid = -1 #assume a subsystem containing all buses in working case - owner_3flow = 1 #1 = use bus ownership 2 = use tfo ownership - ties_3flow = 3 #ignored bc sid is negative. 3 = interior subsystem and subsystem tie 3 winding transformers - flag=3 #all 3 winding transfo windings - string = ['wind1number','wind2number','wind3number'] - ierr,iarray = psspy.awndint(sid,owner,ties,flag,entry,string) - string = ['wind1name','wind2name','wind3name','wind1exname','wind2exname','wind3exname','id'] - ierr,carray = psspy.awndchar(sid,owner,ties,flag,entry,string) - - #[Bus name 1, Bus name 2, Bus name 3, machine ID, extended bus name 1, extended bus name 2, extended bus name 3, bus number 1, bus number 2, bus number 3] - for i in range(len(iarray[0])): - idname = 'Tr' + carray[6][i].strip() -## try: -## idname = 'Tr' + str(int(carray[4][i])) -## except: -## idname = 'Tr' + carray[4][i] - tfoname = carray[0][i].strip() + "__" + carray[1][i].strip() + "__" + carray[2][i].strip() + "__" + idname - tfoname = tfoname.replace(" ","_") - tfoname = tfoname.replace("-","_") - tfoname = tfoname.replace(".","_") - tfoname = tfoname.replace("&","and") - tfoname = tfoname.replace("%","pct") - tfoname = tfoname.replace("=","eq") - tfoname = tfoname.replace("#","_") - tfoname = tfoname.replace("$","_") - tfoname = tfoname.replace("/","_") - tfoname = tfoname.replace("\\","_") - try: - int(tfoname[0]) - tfoname="_" + tfoname - except: - pass - TfoDico[tfoname]={} - TfoDico[tfoname]['FROMNAME']=carray[0][i].strip() - TfoDico[tfoname]['TONAME']=carray[1][i].strip() - TfoDico[tfoname]['3NAME']=carray[2][i].strip() - TfoDico[tfoname]['ID']=carray[6][i] - TfoDico[tfoname]['FROMEXNAME']=carray[3][i] - TfoDico[tfoname]['TOEXNAME']=carray[4][i] - TfoDico[tfoname]['3EXNAME']=carray[5][i] - TfoDico[tfoname]['FROMNUMBER']=iarray[0][i] - TfoDico[tfoname]['TONUMBER']=iarray[1][i] - TfoDico[tfoname]['3NUMBER']=iarray[2][i] - TfoDico[tfoname]['#WIND']=3 - print "Read 3-Winding Transfos" - # path1 = os.getcwd() - # import json - # path_temp=os.path.dirname(NetworkFile) - # # filew = open(path_temp+'/temp.txt', 'w') - # json.dump(MachineDico, open("toto.txt", 'w')) - # # filew.write(MachineDico) - # # filew.close() - filew = open('temp.txt', 'w') - filew.write(NetworkFile + '\n') - filew.write(PSSE_PATH + '\n') - filew.close() - - return MachineDico, LoadDico, LineDico, TfoDico, MotorDico - - -def PFExtractGeneratorLoadLineandTransfoDico(NetworkFile, PF_PATH,Python3_path): - # PSEN sous PowerFactory Lecture les donnees de Generateur,Load,Line,Transfo - import os,pickle - import sys, subprocess - import numpy as np - path1=os.getcwd() - # path_temp=os.path.dirname(NetworkFile) - filew=open('temp.txt','w') - filew.write(NetworkFile+'\n') - filew.write(PF_PATH + '\n') - filew.write(Python3_path + '\n') - filew.close() - print('changer le chemin de Python3 executable') - lancer = [Python3_path+'/python.exe', path1+'/com.py']# changer le chemin de Python3 executable - proc = subprocess.Popen(lancer) - proc.wait() - with open('Data_for_interface', 'rb') as fichier: - mon_depickler = pickle.Unpickler(fichier) - data_file = mon_depickler.load() - - import collections - def convert(data): - if isinstance(data, basestring): - return str(data) - elif isinstance(data, collections.Mapping): - return dict(map(convert, data.iteritems())) - elif isinstance(data, collections.Iterable): - return type(data)(map(convert, data)) - else: - return data - data=convert(data_file) - MachineDico=data['MachineDico'] - LoadDico = data['LoadDico'] - LineDico = data['LineDico'] - TfoDico = data['TransfoDico'] - MotorDico = data['MotorDico'] - os.remove('Data_for_interface') - - - return MachineDico, LoadDico, LineDico, TfoDico, MotorDico - - -#NetworkFile=r"C:\Users\j15773\Documents\Projects\DEWA\Task 4\FEWA_GCCIA_SUMMAX2018_OPF_EQ2.sav" - -#PSSE_PATH=r"C:\Program Files (x86)\PTI\PSSE34\PSSBIN" -#PSSPY_PATH=r"C:\Program Files (x86)\PTI\PSSE34\PSSPY27" - -#PSSE_PATH=r"C:\Program Files (x86)\PTI\PSSE33\PSSBIN" -#PSSPY_PATH=r"C:\Program Files (x86)\PTI\PSSE33\PSSBIN" - -#MachineDico, LoadDico, LineDico, TfoDico, MotorDico = ExtractGeneratorLoadLineandTransfoDico(NetworkFile,PSSE_PATH,PSSPY_PATH) diff --git a/PSEN_Eficas/PSEN/exploit2.ows b/PSEN_Eficas/PSEN/exploit2.ows deleted file mode 100755 index 56005895..00000000 --- a/PSEN_Eficas/PSEN/exploit2.ows +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/PSEN_Eficas/PSEN_Cata.py b/PSEN_Eficas/PSEN_Cata.py deleted file mode 100644 index edee53af..00000000 --- a/PSEN_Eficas/PSEN_Cata.py +++ /dev/null @@ -1,2788 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2013 EDF R&D -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# - -# -------------------------------------------------- -# debut entete -# -------------------------------------------------- - -#from Accas import ASSD, JDC_CATA, AU_MOINS_UN, PROC, SIMP, FACT, OPER, MACRO, BLOC, A_VALIDATOR -from Accas import * -import opsPSEN - -class loi ( ASSD ) : pass -class variable ( ASSD ) : pass -class sd_charge ( ASSD ) : pass -class sd_generateur ( ASSD ) : pass -class sd_ligne ( ASSD ) : pass -class sd_transfo ( ASSD ) : pass -class sd_moteur (ASSD) : pass -#class sd_busbar ( sd_generateur,sd_charge ) : pass - -import types -class Tuple: - def __init__(self,ntuple): - self.ntuple=ntuple - - def __convert__(self,valeur): - if type(valeur) == types.StringType: - return None - if len(valeur) != self.ntuple: - return None - return valeur - - def info(self): - return "Tuple de %s elements" % self.ntuple - - __repr__=info - __str__=info - -class Matrice: - def __init__(self,nbLigs=None,nbCols=None,methodeCalculTaille=None,formatSortie="ligne",valSup=None,valMin=None,structure=None): - self.nbLigs=nbLigs - self.nbCols=nbCols - self.methodeCalculTaille=methodeCalculTaille - self.formatSortie=formatSortie - self.valSup=valSup - self.valMin=valMin - self.structure=structure - - def __convert__(self,valeur): - # Attention ne verifie pas grand chose - if type(valeur) != types.ListType : - return None - return valeur - - def info(self): - return "Matrice %s x %s" % (self.nbLigs, self.nbCols) - - __repr__=info - __str__=info - - -#CONTEXT.debug = 1 -JdC = JDC_CATA ( code = 'PSEN', - execmodul = None, - regles = ( AU_MOINS_UN ( 'PSSE_PARAMETERS' ), - AU_MOINS_UN ( 'DIRECTORY' ), - AU_MOINS_UN ( 'DISTRIBUTION' ), - AU_MOINS_UN ( 'SIMULATION' ), - AU_PLUS_UN ( 'PSSE_PARAMETERS' ), - AU_PLUS_UN ( 'DIRECTORY' ), - AU_PLUS_UN ( 'SIMULATION' ), - AU_PLUS_UN ( 'CORRELATION' ), - AU_PLUS_UN ( 'N_1_GENERATORS' ), - AU_PLUS_UN ( 'N_1_LINES' ), - AU_PLUS_UN ( 'N_1_LOADS' ), - AU_PLUS_UN ( 'N_1_MOTORS' ), - AU_PLUS_UN ( 'N_1_TRANSFORMERS' ), - - ), - ) # Fin JDC_CATA - - -# -------------------------------------------------- -# fin entete -# -------------------------------------------------- - -MONGENER = OPER ( nom = "MONGENER", - sd_prod = sd_generateur, - UIinfo = {"groupes": ("CACHE")}, - op = None, - fr = "Generateur", - ang = "Generator", - - ID = SIMP ( statut = 'o', typ = "TXM", fr = "num bus", ang = "num bus",), -) -MONMOTEUR = OPER ( nom = "MONMOTEUR", - sd_prod = sd_moteur, - UIinfo = {"groupes": ("CACHE")}, - op = None, - fr = "Moteur", - ang = "Motor", - - ID = SIMP ( statut = 'o', typ = "TXM", fr = "num bus", ang = "num bus",), -) -MACHARGE = OPER ( nom = "MACHARGE", - sd_prod = sd_charge, - UIinfo = {"groupes": ("CACHE")}, - op = None, - fr = "Charge", - ang = "Load", - - ID = SIMP ( statut = 'o', typ = "TXM", fr = "nom charge", ang = "load name",), -) -MALIGNE = OPER ( nom = "MALIGNE", - sd_prod = sd_ligne, - UIinfo = {"groupes": ("CACHE")}, - op = None, - fr = "Ligne", - ang = "Line", - - ID = SIMP ( statut = 'o', typ = "TXM", fr = "nom ligne", ang = "line name",), -) -MONTRANSFO = OPER ( nom = "MONTRANSFO", - sd_prod = sd_transfo, - UIinfo = {"groupes": ("CACHE")}, - op = None, - fr = "Transformateur", - ang = "Transformer", - - ID = SIMP ( statut = 'o', typ = "TXM", fr = "nom transformateur", ang = "transformer name",), -) - - - -PSSE_PARAMETERS = PROC ( nom = "PSSE_PARAMETERS", - op=None, - docu = "", - ALGORITHM = SIMP ( statut = "o", - typ='TXM', - into=["Optimum Power Flow","Economic Dispatch and Power Flow"], - defaut="Optimum Power Flow", - ), - I_MAX = SIMP ( statut = "o", - typ='TXM', - into=['RateA','RateB','RateC'], - defaut='RateA', - ), - LOCK_TAPS = SIMP ( statut = "o", - typ=bool, - defaut=True, - ), - - b_OPF = BLOC (condition = "ALGORITHM == 'Optimum Power Flow'", - FUEL_COST = SIMP ( statut = "o", - typ=bool, - defaut=True, - ), - LOADSHEDDING_COST = SIMP ( statut = "o", - typ=bool, - defaut=False, - ), - MVAR_COST = SIMP ( statut = "o", - typ=bool, - defaut=False, - ), - ITERATION_LIMIT = SIMP ( statut = "o", - typ = "I", - val_min=1, - defaut=20, - ), - UNIT_COMMITMENT = SIMP ( statut = "o", - typ = bool, - defaut = True, - fr = "Premiere passe de l'OPF pour determiner quels groupes doivent être connectes. Deconnecter les autres.", - ang = "First OPF to determine which units should be run; others are disconnected.", - ), - b_UnitCommitment = BLOC (condition = "UNIT_COMMITMENT == True", - SAVE_CASE_BEFORE_UNIT_COMMITMENT = SIMP ( statut = "o", - typ = bool, - defaut = False, - fr = "Sauvegarder des fichiers de cas avant d'avoir deconnecte les groupes ne produisant pas de la puissance active", - ang = "Save network case files before having disconnected groups that dont generate active power.", - ), - - SpinningReserveCorrection = FACT(statut='f', max="**", - - SpinningReserveID = SIMP ( statut = "o", - typ = "I", - val_min = 1, - val_max = 15, - defaut=1, - fr = "Numero de réserve comme definie dans PSS/E correspondant à une réserve tournante", - ang= "Period reserve constraint identifier numer as defined in PSS/E, corresponding to an online (spinning) reserve." - ), - ), - - ), - DECIMAL_SEPARATOR = SIMP(statut="o",typ='TXM',into=[',','.'],defaut='.',), - ), - - b_ECD = BLOC (condition = "ALGORITHM == 'Economic Dispatch and Power Flow'", - ecd_file=SIMP(statut="o", typ = ('Fichier', 'Economic Dispatch Files (*.ecd);;All Files (*)',),), - ), - -## P_MIN= SIMP ( statut = "o", -## typ=bool, -## defaut=True, -## ), -) - -SIMULATION = PROC ( nom = "SIMULATION", - op = None, - docu = "", - regles =(EXCLUS('NUMBER_PACKAGE','CONVERGENCE'), UN_PARMI('NUMBER_PACKAGE','CONVERGENCE'),), - - SIZE_PACKAGE = SIMP ( statut = "o", - typ = "I", - val_min=10, - defaut=100, - ), - NUMBER_PACKAGE = SIMP ( statut = "f", - typ = "I", - val_min=1, - ), - CONVERGENCE = SIMP ( statut = "f", - typ="I", - into=[1], - ), - - MAX_CORES = SIMP ( statut = "f", - typ="I", - val_min=1, - ), - -## STUDY = SIMP ( statut = "o", -## typ = "TXM", -## into = ( 'N-1', 'Load', 'Wind-1', 'Wind-2', 'PV' ), -## max=5, -## fr = "Affichage du niveau de wrapper de la bibliotheque Open TURNS", -## ang = "Open TURNS library debug level print", -## ), -) - - -#================================ -# Definition du modele physique -#================================ - - - -CORRELATION = PROC ( nom = 'CORRELATION', - op = None, - docu = "", - fr = "Correlation entre variables", - ang = "Variable correlation", - -#### Copula = SIMP ( statut = "o", -#### typ = 'TXM', -#### into = ( "Independent", "Normal" ), -#### defaut = "Independent", -#### fr = "Type de la copule", -#### ang = "Copula kind", -#### ), -## -## # Matrix = BLOC ( condition = "Copula in ( 'Normal', )", -## - CorrelationMatrix = SIMP ( statut = "o", - typ = Matrice(nbLigs=None, - nbCols=None, - methodeCalculTaille='NbDeDistributions', - structure="symetrique"), - fr = "Matrice de correlation entre les variables d'entree", - ang = "Correlation matrix for input variables", - #val_max=1.0, - #val_min=-1.0, - ), -## #), # Fin BLOC Matrix -## -## -) - -DIRECTORY = MACRO ( nom = 'DIRECTORY', - op=None, - fr = "Chargement des directoires et fichiers", - ang = "Load directories and files necessary to run PSEN", - sd_prod = opsPSEN.INCLUDE, - op_init = opsPSEN.INCLUDE_context, - #sd_prod=None, - fichier_ini = 1, - - PSSE_path=SIMP(statut="o",typ='Repertoire',defaut='C:\Program Files (x86)\PTI\PSSE34\PSSBIN'), - PSSPY_path=SIMP(statut="o",typ='Repertoire',defaut='C:\Program Files (x86)\PTI\PSSE34\PSSPY27'), - sav_file=SIMP(statut="o", typ = ('Fichier', 'Network Case Files (*.sav);;All Files (*)',),), - results_folder=SIMP(statut="o",typ='Repertoire'), - #lines_file=SIMP(statut="o" ,typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',),), - #groups_file=SIMP(statut="o", typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',),), - #generationsystem_file=SIMP(statut="o" ,typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',),), - -) -( - - -) - - -#================================ -# Importation des fichiers csv N-1 -#================================ - -N_1_LINES = PROC( nom="N_1_LINES", - op = None, - docu = "", - fr = "N-1 lignes", - ang = "N-1 lines", - Activated = SIMP ( statut='o', typ=bool, defaut=True), -## FileName = SIMP ( statut = "o", -## typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), -## fr = "chemin du fichier csv des probabilites des defauts lignes", -## ang = "csv file path with probabilities of line outages", -## ), - Probability = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Probabilite d'indisponibilite de la ligne", - ang = "Probability that the line is not available", - validators=VerifTypeTuple((sd_ligne,'R')),), - ) - -N_1_TRANSFORMERS = PROC( nom="N_1_TRANSFORMERS", - op = None, - docu = "", - fr = "N-1 transformateurs", - ang = "N-1 transformers", - Activated = SIMP ( statut='o', typ=bool, defaut=True), -## FileName = SIMP ( statut = "o", -## typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), -## fr = "chemin du fichier csv des probabilites des defauts transformateur", -## ang = "csv file path with probabilities of transformer outages", -## ), - Probability = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Probabilite d'indisponibilite de la ligne", - ang = "Probability that the line is not available", - validators=VerifTypeTuple((sd_transfo,'R')),), - ) -N_1_GENERATORS = PROC( nom="N_1_GENERATORS", - op = None, - docu = "", - fr = "N-1 generateurs", - ang = "N-1 generators", - Activated = SIMP ( statut='o', typ=bool, defaut=True), -## FileName = SIMP ( statut = "o", -## typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), -## fr = "chemin du fichier csv des probabilites des defauts generateurs", -## ang = "csv file path with probabilities of generator outages", -## ), - Probability = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Probabilite d'indisponibilite du generateur", - ang = "Probability that the generator is not available", - validators=VerifTypeTuple((sd_generateur,'R')),), - ) -N_1_MOTORS = PROC( nom="N_1_MOTORS", - op = None, - docu = "", - fr = "N-1 moteurs", - ang = "N-1 motors", - Activated = SIMP ( statut='o', typ=bool, defaut=True), -## FileName = SIMP ( statut = "o", -## typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), -## fr = "chemin du fichier csv des probabilites des defauts generateurs", -## ang = "csv file path with probabilities of generator outages", -## ), - Probability = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Probabilite d'indisponibilite du moteur", - ang = "Probability that the motor is not available", - validators=VerifTypeTuple((sd_moteur,'R')),), - ) -N_1_LOADS = PROC( nom="N_1_LOADS", - op = None, - docu = "", - fr = "N-1 charges", - ang = "N-1 loads", - Activated = SIMP ( statut='o', typ=bool, defaut=True), -## FileName = SIMP ( statut = "o", -## typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), -## fr = "chemin du fichier csv des probabilites des defauts charges", -## ang = "csv file path with probabilities of load outages", -## ), - Probability = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Probabilite d'indisponibilite du generateur", - ang = "Probability that the generator is not available", - validators=VerifTypeTuple((sd_charge,'R')),), - ) - - - - -#================================ -# Definition des LOIS -#================================ - -# Nota : les variables de type OPER doivent etre en majuscules ! -# Nota : les variables de type OPER doivent etre de premier niveau (pas imbriquees dans un autre type) -DISTRIBUTION = OPER ( nom = "DISTRIBUTION", - sd_prod = loi, - op = 68, - fr = "Definitions des lois marginales utilisees par les variables d'entree", - -#==== -# Choisir generateur ou charge -#==== - -## TypeMachine = SIMP ( statut='o', typ='TXM', -## into = ('charge','vent1','vent2','pv','N-1',), -## ), - Activated = SIMP ( statut='o', typ=bool, defaut=True), - ComponentType = SIMP (statut='o', typ='TXM', - into = ('Generator','Load','Motor','Line','Transformer', 'Reserve Constraint'),), - - b_reserve = BLOC (condition = "ComponentType == 'Reserve Constraint'", - - ReserveID = SIMP (statut= "o", typ = "I", - val_max = 15, - val_min = 1, - fr = "Numero de réserve comme definie dans PSS/E", - ang= "Period resperve constraint identifier numer as defined in PSS/E.", - defaut = 1, - ), - - Law = SIMP ( statut = "o", typ = "TXM", - into = ( "Exponential", - "Histogram", - "Normal", - #"Rayleigh", - "PDF_from_file", - "TruncatedNormal", - "TimeSeries_from_file", - "Uniform", - "UserDefined", - "Weibull", - ), - fr = "Choix du type de la loi marginale", - ang = "1D marginal distribution", - ), - - -#==== -# Definition des parametres selon le type de la loi -#==== - - - EXPONENTIAL = BLOC ( condition = " Law in ( 'Exponential', ) ", - - Lambda = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Lambda | Lambda > 0", - ang = "Lambda parameter | Lambda > 0", - ), - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - - ), # Fin BLOC EXPONENTIAL - - - HISTOGRAM = BLOC ( condition = " Law in ( 'Histogram', ) ", - - First = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du supoport de la loi", - ang = "Support lower bound", - ), - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : largeur de classe, hauteur de classe", - ang = "Class bandwidth, class height couple list", - validators=VerifTypeTuple(('R','R')), - ), - - ), # Fin BLOC HISTOGRAM - - - NORMAL = BLOC ( condition = " Law in ( 'Normal', ) ", - - Mu = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi", - ang = "Mean value", - ), - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart type de la loi", - ang = "Standard deviation", - ), - - ), # Fin BLOC NORMAL - - - RAYLEIGH = BLOC ( condition = " Law in ( 'Rayleigh', ) ", - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Parametre Sigma de la loi | Sigma > 0", - ang = "Sigma parameter | Sigma > 0", - ), - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - ), # Fin BLOC RAYLEIGH - - PDF = BLOC ( condition = " Law in ( 'PDF_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Nom du fichier .csv", - ang = ".csv file name", - ), - ), - - - - TRUNCATEDNORMAL = BLOC ( condition = " Law in ( 'TruncatedNormal', ) ", - - MuN = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi Normale non tronqu�e", - ang = "Mean value of the associated non truncated normal distribution", - ), - - SigmaN = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart-type de la loi Normale non tronqu�e", - ang = "Standard deviation of the associated non truncated normal distribution", - ), - - A = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure de la loi | A < B", - ang = "Lower bound | A < B", - ), - - B = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne superieure de la loi | A < B", - ang = "Upper bound | A < B", - ), - - ), # Fin BLOC TRUNCATEDNORMAL - - - TimeSeries = BLOC ( condition = " Law in ( 'TimeSeries_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Fichier CSV d'une serie temporelle", - ang = "CSV file of a time series", - ), - ), - - - UNIFORM = BLOC ( condition = " Law in ( 'Uniform', ) ", - - A = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi | A < B", - ang = "Support lower bound | A < B", - ), - - B = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne superieure du support de la loi | A < B", - ang = "Support upper bound | A < B", - ), - - ), # Fin BLOC UNIFORM - - - USERDEFINED = BLOC ( condition = " Law in ( 'UserDefined', ) ", - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : (valeur, prob.)", - ang = "List of pairs : (value, prob.)", - validators=VerifTypeTuple(('R','R')), - ), - - ), # Fin BLOC USERDEFINED - - - WEIBULL = BLOC ( condition = " Law in ( 'Weibull', ) ", - - Settings = SIMP ( statut = "o", - typ = "TXM", - max = 1, - into = ( "AlphaBeta", "MuSigma" ), - defaut = "AlphaBeta", - fr = "Parametrage de la loi weibull", - ang = "Weibull distribution parameter set", - ), - - AlphaBeta_Parameters = BLOC ( condition = " Settings in ( 'AlphaBeta', ) ", - - Alpha = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Alpha de la loi | Alpha > 0", - ang = "Alpha parameter | Alpha > 0", - ), - - Beta = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Beta de la loi | Beta > 0", - ang = "Beta parameter | Beta > 0", - ), - - ), # Fin BLOC AlphaBeta_Parameters - - - MuSigma_Parameters = BLOC ( condition = " Settings in ( 'MuSigma', ) ", - - Mu = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi", - ang = "Mean value", - ), - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart type de la loi", - ang = "Standard deviation", - ), - - ), # Fin BLOC MuSigma_Parameters - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - - ), # Fin BLOC WEIBULL - - ), #fin de BLOC reserve - - - - - b_gener = BLOC (condition = "ComponentType == 'Generator'", - - Type = SIMP (statut= "o", typ = "TXM", - into = ("Generator Power Level", "Generator Availability"), - fr = "Choisir si c'est le niveau de puissance ou la disponibilit� du generateur qui sera tiree", - ang= "Choose whether the power level or the availability of the generator will be set by the law", - defaut = "Generator Power Level", - ), - - Sampling = SIMP (statut= "o", typ = "TXM", - into = ("Same sample for all generators", "One sample per generator"), - fr = "Choisir si une seule tirage sera fait pour tous les generateurs ou si des tirages differents seront faits pour chaque generateur", - ang= "Choose whether one drawing/sample will be performed for all of the generators or whether a different drawing/sample will be performed for each generator.", - defaut = "Same sample for all generators", - ), - - Generator = SIMP(statut='o',typ=sd_generateur,max="**", homo="SansOrdreNiDoublon"), - -#==== -# Type de distribution -#==== - - b_gener_level = BLOC (condition= "Type == 'Generator Power Level'", - - Law = SIMP ( statut = "o", typ = "TXM", - into = ( "Exponential", - "Histogram", - "Normal", - #"Rayleigh", - "PDF_from_file", - "TruncatedNormal", - "TimeSeries_from_file", - "Uniform", - "UserDefined", - "Weibull", - ), - fr = "Choix du type de la loi marginale", - ang = "1D marginal distribution", - ), - - -#==== -# Definition des parametres selon le type de la loi -#==== - - - EXPONENTIAL = BLOC ( condition = " Law in ( 'Exponential', ) ", - - Lambda = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Lambda | Lambda > 0", - ang = "Lambda parameter | Lambda > 0", - ), - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - - ), # Fin BLOC EXPONENTIAL - - - HISTOGRAM = BLOC ( condition = " Law in ( 'Histogram', ) ", - - First = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du supoport de la loi", - ang = "Support lower bound", - ), - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : largeur de classe, hauteur de classe", - ang = "Class bandwidth, class height couple list", - validators=VerifTypeTuple(('R','R')), - ), - - ), # Fin BLOC HISTOGRAM - - - NORMAL = BLOC ( condition = " Law in ( 'Normal', ) ", - - Mu = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi", - ang = "Mean value", - ), - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart type de la loi", - ang = "Standard deviation", - ), - - ), # Fin BLOC NORMAL - - - RAYLEIGH = BLOC ( condition = " Law in ( 'Rayleigh', ) ", - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Parametre Sigma de la loi | Sigma > 0", - ang = "Sigma parameter | Sigma > 0", - ), - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - ), # Fin BLOC RAYLEIGH - - PDF = BLOC ( condition = " Law in ( 'PDF_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Nom du fichier .csv", - ang = ".csv file name", - ), - ), - - - - TRUNCATEDNORMAL = BLOC ( condition = " Law in ( 'TruncatedNormal', ) ", - - MuN = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi Normale non tronqu�e", - ang = "Mean value of the associated non truncated normal distribution", - ), - - SigmaN = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart-type de la loi Normale non tronqu�e", - ang = "Standard deviation of the associated non truncated normal distribution", - ), - - A = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure de la loi | A < B", - ang = "Lower bound | A < B", - ), - - B = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne superieure de la loi | A < B", - ang = "Upper bound | A < B", - ), - - ), # Fin BLOC TRUNCATEDNORMAL - - - TimeSeries = BLOC ( condition = " Law in ( 'TimeSeries_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Fichier CSV d'une serie temporelle", - ang = "CSV file of a time series", - ), - ), - - - UNIFORM = BLOC ( condition = " Law in ( 'Uniform', ) ", - - A = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi | A < B", - ang = "Support lower bound | A < B", - ), - - B = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne superieure du support de la loi | A < B", - ang = "Support upper bound | A < B", - ), - - ), # Fin BLOC UNIFORM - - - USERDEFINED = BLOC ( condition = " Law in ( 'UserDefined', ) ", - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : (valeur, prob.)", - ang = "List of pairs : (value, prob.)", - validators=VerifTypeTuple(('R','R')), - ), - - ), # Fin BLOC USERDEFINED - - - WEIBULL = BLOC ( condition = " Law in ( 'Weibull', ) ", - - Settings = SIMP ( statut = "o", - typ = "TXM", - max = 1, - into = ( "AlphaBeta", "MuSigma" ), - defaut = "AlphaBeta", - fr = "Parametrage de la loi weibull", - ang = "Weibull distribution parameter set", - ), - - AlphaBeta_Parameters = BLOC ( condition = " Settings in ( 'AlphaBeta', ) ", - - Alpha = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Alpha de la loi | Alpha > 0", - ang = "Alpha parameter | Alpha > 0", - ), - - Beta = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Beta de la loi | Beta > 0", - ang = "Beta parameter | Beta > 0", - ), - - ), # Fin BLOC AlphaBeta_Parameters - - - MuSigma_Parameters = BLOC ( condition = " Settings in ( 'MuSigma', ) ", - - Mu = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi", - ang = "Mean value", - ), - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart type de la loi", - ang = "Standard deviation", - ), - - ), # Fin BLOC MuSigma_Parameters - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - - ), # Fin BLOC WEIBULL - - - Transfer_Function = FACT(statut='f', - - TF_Input = SIMP ( statut='o', - typ = 'TXM', - fr = 'Entrer une fonction de transfert � partir d''un fichier .pow (vitesse de vent - puissance eolienne)\n \ - ou entrer une liste de tuples (valeur tiree - puissance normalisee)', - ang = 'Enter wind speed - turbine production transfer function as a .pow file, \n \ - or enter a generic list of (law output value, normalized power output) tuples', - into = ('.pow file', 'tuples list'), - ), - b_file = BLOC(condition = "TF_Input == '.pow file'", - File_Name = SIMP ( statut = "o", - typ = ('Fichier', 'Pow files (*.pow);;All Files (*)',), - fr = "Nom du fichier de transfer .pow", - ang = ".pow file name", - ), - Wind_Speed_Measurement_Height = SIMP ( statut = 'o', - typ = "R", - max = 1, - fr = 'Hauteur (en metres) a laquelle les mesures de vitesse du vent ont ete prises', - ang = 'Height of wind speed measurements (m)', - sug = 10, - val_min = 0, - ), - Hub_Height = SIMP (statut = 'o', - typ = "R", - fr = 'hauteur de moyeu de l''eolienne', - ang = 'wind turbine hub height', - sug = 80, - val_min = 0,), - AlphaWS = SIMP (statut = 'o', - typ = "R", - fr = 'l''alpha pour extrapoler les mesures de vitesse du vent a la hauteur du moyeu ', - ang = 'alpha used to extrapolate wind speed measurements to hub height', - defaut = 1./7, - val_min = 0, - val_max = 1, - ), - Percent_Losses = SIMP (statut = 'o', - typ = "R", - fr = 'pourcentage de pertes entre la sortie theorique d''une turbine et la sortie de la centrale', - ang = 'percent losses between theoretical power output of a single turbine and the output of the farm', - defaut = 5, - val_min = 0, - val_max = 100, - ), - ), #fin du bloc FileName - - b_tuples = BLOC(condition = "TF_Input == 'tuples list'", - - TF_Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - min = 2, - fr = "Liste de couples : valeur tiree, puissance normalisee sortie", - ang = "List of couples : value set by law, normalized power output", - validators=VerifTypeTuple(('R','R')), - ), - ), #fin du block Tuples List - - ), #fin du FACT Transfer Function - - ), #fin du bloc generator level - - - b_gener_avail = BLOC (condition= "Type == 'Generator Availability'", - - Law = SIMP ( statut = "o", typ = "TXM", - into = ( #"Exponential", - #"Histogram", - #"Normal", - #"Rayleigh", - #"PDF_from_file", - #"TruncatedNormal", - "TimeSeries_from_file", - #"Uniform", - "UserDefined", - #"Weibull", - ), - fr = "Choix du type de la loi marginale", - ang = "1D marginal distribution", - defaut="UserDefined", - ), - - -#==== -# Definition des parametres selon le type de la loi -#==== - - - TimeSeries = BLOC ( condition = " Law in ( 'TimeSeries_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Fichier CSV d'une serie temporelle", - ang = "CSV file of a time series", - ), - ), - - - USERDEFINED = BLOC ( condition = " Law in ( 'UserDefined', ) ", - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : (valeur, prob.)", - ang = "List of pairs : (value, prob.)", - validators=VerifTypeTuple(('R','R')), - defaut=((0,0.0),(1,1.0)), - ), - - ), # Fin BLOC USERDEFINED - - - ), #fin du bloc generator avail - - - ), #fin du bloc generateur - -#Bloc Charge - b_charge = BLOC (condition = "ComponentType == 'Load'", - - -#==== -# Type de distribution -#==== - - Type = SIMP (statut= "o", typ = "TXM", - into = ("Load Level", "Load Availability"), - fr = "Choisir si c'est le niveau de charge ou la disponibilit� de la charge qui sera tiree", - ang= "Choose whether the power level or the availability of the load will be set by the law", - defaut = "Load Level", - ), - - Sampling = SIMP (statut= "o", typ = "TXM", - into = ("Same sample for all loads", "One sample per load"), - fr = "Choisir si une seule tirage sera fait pour tous les charges ou si des tirages differents seront faits pour chaque charge", - ang= "Choose whether one drawing/sample will be performed for all of the loads or whether a different drawing/sample will be performed for each load.", - defaut = "Same sample for all loads", - ), - - Load = SIMP(statut='o',typ=sd_charge,max="**", homo="SansOrdreNiDoublon",), - - - b_charge_level = BLOC (condition = "Type == 'Load Level'", - - Law = SIMP ( statut = "o", typ = "TXM", - into = ( "Exponential", - "Histogram", - "Normal", - #"Rayleigh", - "PDF_from_file", - "TruncatedNormal", - "TimeSeries_from_file", - "Uniform", - "UserDefined", - "Weibull", - ), - fr = "Choix du type de la loi marginale", - ang = "1D marginal distribution", - ), - - -#==== -# Definition des parametres selon le type de la loi -#==== - - - EXPONENTIAL = BLOC ( condition = " Law in ( 'Exponential', ) ", - - Lambda = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Lambda | Lambda > 0", - ang = "Lambda parameter | Lambda > 0", - ), - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - - ), # Fin BLOC EXPONENTIAL - - - HISTOGRAM = BLOC ( condition = " Law in ( 'Histogram', ) ", - - First = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du supoport de la loi", - ang = "Support lower bound", - ), - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : largeur de classe, hauteur de classe", - ang = "Class bandwidth, class height couple list", - validators=VerifTypeTuple(('R','R')), - ), - - ), # Fin BLOC HISTOGRAM - - - NORMAL = BLOC ( condition = " Law in ( 'Normal', ) ", - - Mu = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi", - ang = "Mean value", - ), - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart type de la loi", - ang = "Standard deviation", - ), - - ), # Fin BLOC NORMAL - - - RAYLEIGH = BLOC ( condition = " Law in ( 'Rayleigh', ) ", - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Parametre Sigma de la loi | Sigma > 0", - ang = "Sigma parameter | Sigma > 0", - ), - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - ), # Fin BLOC RAYLEIGH - - PDF = BLOC ( condition = " Law in ( 'PDF_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Nom du fichier .csv", - ang = ".csv file name", - ), - ), - - - - TRUNCATEDNORMAL = BLOC ( condition = " Law in ( 'TruncatedNormal', ) ", - - MuN = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi Normale non tronqu�e", - ang = "Mean value of the associated non truncated normal distribution", - ), - - SigmaN = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart-type de la loi Normale non tronqu�e", - ang = "Standard deviation of the associated non truncated normal distribution", - ), - - A = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure de la loi | A < B", - ang = "Lower bound | A < B", - ), - - B = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne superieure de la loi | A < B", - ang = "Upper bound | A < B", - ), - - ), # Fin BLOC TRUNCATEDNORMAL - - - TimeSeries = BLOC ( condition = " Law in ( 'TimeSeries_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Fichier CSV d'une serie temporelle", - ang = "CSV file of a time series", - ), - ), - - - UNIFORM = BLOC ( condition = " Law in ( 'Uniform', ) ", - - A = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi | A < B", - ang = "Support lower bound | A < B", - ), - - B = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne superieure du support de la loi | A < B", - ang = "Support upper bound | A < B", - ), - - ), # Fin BLOC UNIFORM - - - USERDEFINED = BLOC ( condition = " Law in ( 'UserDefined', ) ", - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : (valeur, probabilite)", - ang = "List of pairs : (value, probability)", - validators=VerifTypeTuple(('R','R')), - ), - - ), # Fin BLOC USERDEFINED - - - WEIBULL = BLOC ( condition = " Law in ( 'Weibull', ) ", - - Settings = SIMP ( statut = "o", - typ = "TXM", - max = 1, - into = ( "AlphaBeta", "MuSigma" ), - defaut = "AlphaBeta", - fr = "Parametrage de la loi weibull", - ang = "Weibull distribution parameter set", - ), - - AlphaBeta_Parameters = BLOC ( condition = " Settings in ( 'AlphaBeta', ) ", - - Alpha = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Alpha de la loi | Alpha > 0", - ang = "Alpha parameter | Alpha > 0", - ), - - Beta = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Beta de la loi | Beta > 0", - ang = "Beta parameter | Beta > 0", - ), - - ), # Fin BLOC AlphaBeta_Parameters - - - MuSigma_Parameters = BLOC ( condition = " Settings in ( 'MuSigma', ) ", - - Mu = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi", - ang = "Mean value", - ), - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart type de la loi", - ang = "Standard deviation", - ), - - ), # Fin BLOC MuSigma_Parameters - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - - ), # Fin BLOC WEIBULL - - ), #fin du block Load Level - - - b_charge_avail = BLOC (condition = "Type == 'Load Availability'", - - Law = SIMP ( statut = "o", typ = "TXM", - into = ( #"Exponential", - #"Histogram", - #"Normal", - #"Rayleigh", - #"PDF_from_file", - #"TruncatedNormal", - "TimeSeries_from_file", - #"Uniform", - "UserDefined", - #"Weibull", - ), - fr = "Choix du type de la loi marginale", - ang = "1D marginal distribution", - defaut = "UserDefined", - ), - - -#==== -# Definition des parametres selon le type de la loi -#==== - - TimeSeries = BLOC ( condition = " Law in ( 'TimeSeries_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Fichier CSV d'une serie temporelle", - ang = "CSV file of a time series", - ), - ), - - - - USERDEFINED = BLOC ( condition = " Law in ( 'UserDefined', ) ", - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : (valeur, probabilite)", - ang = "List of pairs : (value, probability)", - validators=VerifTypeTuple(('R','R')), - defaut=((0,0.0),(1,1.0)), - ), - - ), # Fin BLOC USERDEFINED - - - ), #fin du block Load Avail - - - ), #fin du bloc charge - - - -#Bloc Moteur - b_moteur = BLOC (condition = "ComponentType == 'Motor'", - - -#==== -# Type de distribution -#==== - - Type = SIMP (statut= "o", typ = "TXM", - into = ("Motor Level", "Motor Availability"), - fr = "Choisir si c'est le niveau de charge du moteur ou la disponibilit� du moteur qui sera tiree", - ang= "Choose whether the power level or the availability of the motor will be set by the law", - defaut = "Motor Level", - ), - - Sampling = SIMP (statut= "o", typ = "TXM", - into = ("Same sample for all motors", "One sample per motor"), - fr = "Choisir si une seule tirage sera fait pour tous les moteurs ou si des tirages differents seront faits pour chaque moteur", - ang= "Choose whether one drawing/sample will be performed for all of the motors or whether a different drawing/sample will be performed for each motor.", - defaut = "Same sample for all motors", - ), - - Motor = SIMP(statut='o',typ=sd_moteur,max="**", homo="SansOrdreNiDoublon",), - - - b_moteur_level = BLOC (condition = "Type == 'Motor Level'", - - Law = SIMP ( statut = "o", typ = "TXM", - into = ( "Exponential", - "Histogram", - "Normal", - #"Rayleigh", - "PDF_from_file", - "TruncatedNormal", - "TimeSeries_from_file", - "Uniform", - "UserDefined", - "Weibull", - ), - fr = "Choix du type de la loi marginale", - ang = "1D marginal distribution", - ), - - -#==== -# Definition des parametres selon le type de la loi -#==== - - - EXPONENTIAL = BLOC ( condition = " Law in ( 'Exponential', ) ", - - Lambda = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Lambda | Lambda > 0", - ang = "Lambda parameter | Lambda > 0", - ), - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - - ), # Fin BLOC EXPONENTIAL - - - HISTOGRAM = BLOC ( condition = " Law in ( 'Histogram', ) ", - - First = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du supoport de la loi", - ang = "Support lower bound", - ), - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : largeur de classe, hauteur de classe", - ang = "Class bandwidth, class height couple list", - validators=VerifTypeTuple(('R','R')), - ), - - ), # Fin BLOC HISTOGRAM - - - NORMAL = BLOC ( condition = " Law in ( 'Normal', ) ", - - Mu = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi", - ang = "Mean value", - ), - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart type de la loi", - ang = "Standard deviation", - ), - - ), # Fin BLOC NORMAL - - - RAYLEIGH = BLOC ( condition = " Law in ( 'Rayleigh', ) ", - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Parametre Sigma de la loi | Sigma > 0", - ang = "Sigma parameter | Sigma > 0", - ), - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - ), # Fin BLOC RAYLEIGH - - PDF = BLOC ( condition = " Law in ( 'PDF_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Nom du fichier .csv", - ang = ".csv file name", - ), - ), - - - - TRUNCATEDNORMAL = BLOC ( condition = " Law in ( 'TruncatedNormal', ) ", - - MuN = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi Normale non tronqu�e", - ang = "Mean value of the associated non truncated normal distribution", - ), - - SigmaN = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart-type de la loi Normale non tronqu�e", - ang = "Standard deviation of the associated non truncated normal distribution", - ), - - A = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure de la loi | A < B", - ang = "Lower bound | A < B", - ), - - B = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne superieure de la loi | A < B", - ang = "Upper bound | A < B", - ), - - ), # Fin BLOC TRUNCATEDNORMAL - - - TimeSeries = BLOC ( condition = " Law in ( 'TimeSeries_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Fichier CSV d'une serie temporelle", - ang = "CSV file of a time series", - ), - ), - - - UNIFORM = BLOC ( condition = " Law in ( 'Uniform', ) ", - - A = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi | A < B", - ang = "Support lower bound | A < B", - ), - - B = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne superieure du support de la loi | A < B", - ang = "Support upper bound | A < B", - ), - - ), # Fin BLOC UNIFORM - - - USERDEFINED = BLOC ( condition = " Law in ( 'UserDefined', ) ", - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : (valeur, probabilite)", - ang = "List of pairs : (value, probability)", - validators=VerifTypeTuple(('R','R')), - ), - - ), # Fin BLOC USERDEFINED - - - WEIBULL = BLOC ( condition = " Law in ( 'Weibull', ) ", - - Settings = SIMP ( statut = "o", - typ = "TXM", - max = 1, - into = ( "AlphaBeta", "MuSigma" ), - defaut = "AlphaBeta", - fr = "Parametrage de la loi weibull", - ang = "Weibull distribution parameter set", - ), - - AlphaBeta_Parameters = BLOC ( condition = " Settings in ( 'AlphaBeta', ) ", - - Alpha = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Alpha de la loi | Alpha > 0", - ang = "Alpha parameter | Alpha > 0", - ), - - Beta = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Beta de la loi | Beta > 0", - ang = "Beta parameter | Beta > 0", - ), - - ), # Fin BLOC AlphaBeta_Parameters - - - MuSigma_Parameters = BLOC ( condition = " Settings in ( 'MuSigma', ) ", - - Mu = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi", - ang = "Mean value", - ), - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart type de la loi", - ang = "Standard deviation", - ), - - ), # Fin BLOC MuSigma_Parameters - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - - ), # Fin BLOC WEIBULL - - ), #fin du block Load Level - - - b_moteur_avail = BLOC (condition = "Type == 'Motor Availability'", - - Law = SIMP ( statut = "o", typ = "TXM", - into = ( #"Exponential", - #"Histogram", - #"Normal", - #"Rayleigh", - #"PDF_from_file", - #"TruncatedNormal", - "TimeSeries_from_file", - #"Uniform", - "UserDefined", - #"Weibull", - ), - fr = "Choix du type de la loi marginale", - ang = "1D marginal distribution", - defaut = "UserDefined", - ), - - -#==== -# Definition des parametres selon le type de la loi -#==== - - TimeSeries = BLOC ( condition = " Law in ( 'TimeSeries_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Fichier CSV d'une serie temporelle", - ang = "CSV file of a time series", - ), - ), - - - - USERDEFINED = BLOC ( condition = " Law in ( 'UserDefined', ) ", - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : (valeur, probabilite)", - ang = "List of pairs : (value, probability)", - validators=VerifTypeTuple(('R','R')), - defaut=((0,0.0),(1,1.0)), - ), - - ), # Fin BLOC USERDEFINED - - - ), #fin du block Load Avail - - - ), #fin du bloc moteur - - - b_ligne = BLOC (condition = "ComponentType == 'Line'", - - -#==== -# Type de distribution -#==== - - Type = SIMP (statut= "o", typ = "TXM", - into = ("Line Availability",), - fr = "La disponibilite de la ligne sera tiree", - ang= "Line availability will be set by the law", - defaut = "Line Availability", - ), - - Sampling = SIMP (statut= "o", typ = "TXM", - into = ("Same sample for all lines", "One sample per line"), - fr = "Choisir si une seule tirage sera fait pour tous les lignes ou si des tirages differents seront faits pour chaque ligne", - ang= "Choose whether one drawing/sample will be performed for all of the lines or whether a different drawing/sample will be performed for each line.", - defaut = "Same sample for all lines", - ), - - Line = SIMP(statut='o',typ=sd_ligne,max="**", homo="SansOrdreNiDoublon"), - - Law = SIMP ( statut = "o", typ = "TXM", - into = ( #"Exponential", - #"Histogram", - #"Normal", - #"Rayleigh", - #"PDF_from_file", - #"TruncatedNormal", - "TimeSeries_from_file", - #"Uniform", - "UserDefined", - #"Weibull", - ), - defaut = "UserDefined", - fr = "Choix du type de la loi marginale", - ang = "1D marginal distribution", - ), - - -#==== -# Definition des parametres selon le type de la loi -#==== - - - EXPONENTIAL = BLOC ( condition = " Law in ( 'Exponential', ) ", - - Lambda = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Lambda | Lambda > 0", - ang = "Lambda parameter | Lambda > 0", - ), - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - - ), # Fin BLOC EXPONENTIAL - - - HISTOGRAM = BLOC ( condition = " Law in ( 'Histogram', ) ", - - First = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du supoport de la loi", - ang = "Support lower bound", - ), - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : largeur de classe, hauteur de classe", - ang = "Class bandwidth, class height couple list", - validators=VerifTypeTuple(('R','R')), - ), - - ), # Fin BLOC HISTOGRAM - - - NORMAL = BLOC ( condition = " Law in ( 'Normal', ) ", - - Mu = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi", - ang = "Mean value", - ), - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart type de la loi", - ang = "Standard deviation", - ), - - ), # Fin BLOC NORMAL - - - RAYLEIGH = BLOC ( condition = " Law in ( 'Rayleigh', ) ", - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Parametre Sigma de la loi | Sigma > 0", - ang = "Sigma parameter | Sigma > 0", - ), - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - ), # Fin BLOC RAYLEIGH - - PDF = BLOC ( condition = " Law in ( 'PDF_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Nom du fichier .csv", - ang = ".csv file name", - ), - ), - - - - TRUNCATEDNORMAL = BLOC ( condition = " Law in ( 'TruncatedNormal', ) ", - - MuN = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi Normale non tronqu�e", - ang = "Mean value of the associated non truncated normal distribution", - ), - - SigmaN = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart-type de la loi Normale non tronqu�e", - ang = "Standard deviation of the associated non truncated normal distribution", - ), - - A = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure de la loi | A < B", - ang = "Lower bound | A < B", - ), - - B = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne superieure de la loi | A < B", - ang = "Upper bound | A < B", - ), - - ), # Fin BLOC TRUNCATEDNORMAL - - - TimeSeries = BLOC ( condition = " Law in ( 'TimeSeries_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Fichier CSV d'une serie temporelle", - ang = "CSV file of a time series", - ), - ), - - - UNIFORM = BLOC ( condition = " Law in ( 'Uniform', ) ", - - A = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi | A < B", - ang = "Support lower bound | A < B", - ), - - B = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne superieure du support de la loi | A < B", - ang = "Support upper bound | A < B", - ), - - ), # Fin BLOC UNIFORM - - - USERDEFINED = BLOC ( condition = " Law in ( 'UserDefined', ) ", - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : (valeur, probabilite)", - ang = "List of pairs : (value, probability)", - validators=VerifTypeTuple(('R','R')), - defaut=((0,0.0),(1,1.0)), - ), - - ), # Fin BLOC USERDEFINED - - - WEIBULL = BLOC ( condition = " Law in ( 'Weibull', ) ", - - Settings = SIMP ( statut = "o", - typ = "TXM", - max = 1, - into = ( "AlphaBeta", "MuSigma" ), - defaut = "AlphaBeta", - fr = "Parametrage de la loi weibull", - ang = "Weibull distribution parameter set", - ), - - AlphaBeta_Parameters = BLOC ( condition = " Settings in ( 'AlphaBeta', ) ", - - Alpha = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Alpha de la loi | Alpha > 0", - ang = "Alpha parameter | Alpha > 0", - ), - - Beta = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Beta de la loi | Beta > 0", - ang = "Beta parameter | Beta > 0", - ), - - ), # Fin BLOC AlphaBeta_Parameters - - - MuSigma_Parameters = BLOC ( condition = " Settings in ( 'MuSigma', ) ", - - Mu = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi", - ang = "Mean value", - ), - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart type de la loi", - ang = "Standard deviation", - ), - - ), # Fin BLOC MuSigma_Parameters - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - - ), # Fin BLOC WEIBULL - - ), #fin du bloc ligne - - b_transfo = BLOC (condition = "ComponentType == 'Transformer'", - - -#==== -# Type de distribution -#==== - - Type = SIMP (statut= "o", typ = "TXM", - into = ("Transformer Availability",), - fr = "La disponibilite du transformateur sera tiree", - ang= "Transformer availability will be set by the law", - defaut = "Transformer Availability" - ), - - Sampling = SIMP (statut= "o", typ = "TXM", - into = ("Same sample for all transformers", "One sample per transformer"), - fr = "Choisir si une seule tirage sera fait pour tous les transforamteurs ou si des tirages differents seront faits pour chaque transformateur", - ang= "Choose whether one drawing/sample will be performed for all of the tranformers or whether a different drawing/sample will be performed for each transformer.", - defaut = "Same sample for all transformers", - ), - - Transformer = SIMP(statut='o',typ=sd_transfo,max="**", homo="SansOrdreNiDoublon"), - - Law = SIMP ( statut = "o", typ = "TXM", - into = ( #"Beta", - #"Exponential", - #"Gamma", - #"Geometric", - #"Gumbel", - #"Histogram", - #"Laplace", - #"Logistic", - #"LogNormal", - #"MultiNomial", - #"NonCentralStudent", - #"Normal", - #"Poisson", - #"Rayleigh", - #"Student", - #"PDF_from_file", - #"Triangular", - #"TruncatedNormal", - "TimeSeries_from_file", - #"Uniform", - "UserDefined", - #"Weibull", - ), - defaut="UserDefined", - fr = "Choix du type de la loi marginale", - ang = "1D marginal distribution", - ), - - -#==== -# Definition des parametres selon le type de la loi -#==== - -## NONPARAM = BLOC ( condition = " Law in ( 'NonParametrique', ) ", -## -## FileName = SIMP ( statut = "o", -## typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), -## fr = "Nom du modele physique", -## ang = "Physical model identifier", -## ), -## ), - -# BETA = BLOC ( condition = " Law in ( 'Beta', ) ", -# -# Settings = SIMP ( statut = "o", -# typ = "TXM", -# max = 1, -# into = ( "RT", "MuSigma" ), -# defaut = "RT", -# fr = "Parametrage de la loi beta", -# ang = "Beta distribution parameter set", -# ), -# -# RT_Parameters = BLOC ( condition = " Settings in ( 'RT', ) ", -# -# R = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Parametre R de la loi | R > 0", -# ang = "R parameter | R > 0", -# ), -# -# # T > R -# T = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Parametre T de la loi | T > R", -# ang = "T parameter | T > R", -# ), -# -# ), # Fin BLOC RT_Parameters -# -# -# MuSigma_Parameters = BLOC ( condition = " Settings in ( 'MuSigma', ) ", -# -# Mu = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Moyenne de la loi", -# ang = "Mean value", -# ), -# -# Sigma = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Ecart type de la loi", -# ang = "Standard deviation", -# ), -# -# ), # Fin BLOC MuSigma_Parameters -# -# -# A = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Borne inferieure du support de la loi", -# ang = "Support lower bound", -# ), -# -# # B > A -# B = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Borne superieure du support de la loi", -# ang = "Support upper bound", -# ), -# -# ), # Fin BLOC BETA - - - - EXPONENTIAL = BLOC ( condition = " Law in ( 'Exponential', ) ", - - Lambda = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Lambda | Lambda > 0", - ang = "Lambda parameter | Lambda > 0", - ), - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - - ), # Fin BLOC EXPONENTIAL - - - -# GAMMA = BLOC ( condition = " Law in ( 'Gamma', ) ", -# -# Settings = SIMP ( statut = "o", -# typ = "TXM", -# max = 1, -# into = ( "KLambda", "MuSigma" ), -# defaut = "KLambda", -# fr = "Parametrage de la loi gamma", -# ang = "Gamma distribution parameter set", -# ), -# -# KLambda_Parameters = BLOC ( condition = " Settings in ( 'KLambda', ) ", -# -# K = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Parametre K de la loi | K > 0", -# ang = "K parameter | K > 0", -# ), -# -# Lambda = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Parametre Lambda de la loi | Lambda > 0", -# ang = "Lambda parameter | Lambda > 0", -# ), -# -# ), # Fin BLOC KLambda_Parameters -# -# -# MuSigma_Parameters = BLOC ( condition = " Settings in ( 'MuSigma', ) ", -# -# Mu = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Moyenne de la loi", -# ang = "Mean value", -# ), -# -# Sigma = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Ecart type de la loi", -# ang = "Standard deviation", -# ), -# -# ), # Fin BLOC MuSigma_Parameters -# -# Gamma = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Borne inferieure du supoport de la loi", -# ang = "Support lower bound", -# ), -# -# -# ), # Fin BLOC GAMMA - - -# -# GEOMETRIC = BLOC ( condition = " Law in ( 'Geometric', ) ", -# -# P = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# val_max = 1., -# fr = "Parametre P | 0 < P < 1", -# ang = "P parameter | 0 < P < 1", -# ), -# -# ), # Fin BLOC GEOMETRIC -# -# -# -# GUMBEL = BLOC ( condition = " Law in ( 'Gumbel', ) ", -# -# Settings = SIMP ( statut = "o", -# typ = "TXM", -# max = 1, -# into = ( "AlphaBeta", "MuSigma" ), -# defaut = "AlphaBeta", -# fr = "Parametrage de la loi gumbel", -# ang = "Gumbel distribution parameter set", -# ), -# -# AlphaBeta_Parameters = BLOC ( condition = " Settings in ( 'AlphaBeta', ) ", -# -# Alpha = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Parametre Alpha de la loi | Alpha > 0", -# ang = "Alpha parameter | Alpha > 0", -# ), -# -# Beta = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Parametre Beta de la loi", -# ang = "Beta parameter", -# ), -# -# ), # Fin BLOC AlphaBeta_Parameters -# -# -# MuSigma_Parameters = BLOC ( condition = " Settings in ( 'MuSigma', ) ", -# -# Mu = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Moyenne de la loi", -# ang = "Mean value", -# ), -# -# Sigma = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Ecart type de la loi", -# ang = "Standard deviation", -# ), -# -# ), # Fin BLOC MuSigma_Parameters -# -# ), # Fin BLOC GUMBEL - - - - HISTOGRAM = BLOC ( condition = " Law in ( 'Histogram', ) ", - - First = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du supoport de la loi", - ang = "Support lower bound", - ), - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : largeur de classe, hauteur de classe", - ang = "Class bandwidth, class height couple list", - validators=VerifTypeTuple(('R','R')), - ), - - ), # Fin BLOC HISTOGRAM - - - -# LAPLACE = BLOC ( condition = " Law in ( 'Laplace', ) ", -# -# Lambda = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Parametre Lambda | Lambda > 0", -# ang = "Lambda parameter | Lambda > 0", -# ), -# -# Mu = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Moyenne de la loi", -# ang = "Mean value", -# ), -# -# ), # Fin BLOC LAPLACE -# -# LOGNORMAL = BLOC ( condition = " Law in ( 'LogNormal', ) ", -# -# Settings = SIMP ( statut = "o", -# typ = "TXM", -# max = 1, -# into = ( "MuSigmaLog", "MuSigma", "MuSigmaOverMu" ), -# defaut = "MuSigmaLog", -# fr = "Parametrage de la loi lognormale", -# ang = "Lognormal distribution parameter set", -# ), -# -# MuSigma_Parameters = BLOC ( condition = " Settings in ( 'MuSigma', ) ", -# -# Mu = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Moyenne de la loi", -# ang = "Mean value", -# ), -# -# Sigma = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Ecart type de la loi", -# ang = "Standard deviation", -# ), -# -# ), # Fin BLOC MuSigma_Parameters -# -# MuSigmaOverMu_Parameters = BLOC ( condition = " Settings in ( 'MuSigmaOverMu', ) ", -# -# Mu = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Moyenne de la loi", -# ang = "Mean value", -# ), -# -# SigmaOverMu = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Rapport ecart type / moyenne de la loi", -# ang = "Standard deviation / mean value ratio", -# ), -# -# ), # Fin BLOC MuSigmaOverMu_Parameters -# -# MuSigmaLog_Parameters = BLOC ( condition = " Settings in ( 'MuSigmaLog', ) ", -# -# MuLog = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Moyenne du log", -# ang = "Log mean value", -# ), -# -# SigmaLog = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Ecart type du log", -# ang = "Log standard deviation", -# ), -# -# ), # Fin BLOC MuSigmaLog_Parameters -# -# Gamma = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Borne inferieure du support de la loi", -# ang = "Support lower bound", -# ), -# -# ), # Fin BLOC LOGNORMAL -# -# -# -# LOGISTIC = BLOC ( condition = " Law in ( 'Logistic', ) ", -# -# Alpha = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Borne inferieure du supoport de la loi", -# ang = "Support lower bound", -# ), -# -# Beta = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Parametre Beta de la loi | Beta > 0", -# ang = "Beta parameter | Beta > 0", -# ), -# -# ), # Fin BLOC LOGISTIC -# -# -# -# MULTINOMIAL = BLOC ( condition = " Law in ( 'MultiNomial', ) ", -# -# N = SIMP ( statut = "o", -# typ = "I", -# max = 1, -# fr = "Parametre N de la loi | N > 0", -# ang = "N parameter | N > 0", -# ), -# -# # Il faut definir une collection de couples ( x,p ) -# Values = SIMP ( statut = 'o', -# typ = "R", -# max = '**', -# fr = "Liste de probabilit�s", -# ang = "Probability list", -# validators=VerifTypeTuple(('R','R')), -# ), -# -# ), # Fin BLOC MULTINOMIAL -# -# -# NONCENTRALSTUDENT = BLOC ( condition = " Law in ( 'NonCentralStudent', ) ", -# -# Nu = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Parametre Nu de la loi | Nu > 0", -# ang = "Nu parameter | Nu > 0", -# ), -# -# Delta = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Parametre Delta de la loi | Delta > 0", -# ang = "Delta parameter | Delta > 0", -# ), -# -# Gamma = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Parametre Gamma de centrage de la loi", -# ang = "Gamma parameter", -# ), -# -# ), # Fin BLOC NONCENTRALSTUDENT - - - NORMAL = BLOC ( condition = " Law in ( 'Normal', ) ", - - Mu = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi", - ang = "Mean value", - ), - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart type de la loi", - ang = "Standard deviation", - ), - - ), # Fin BLOC NORMAL - - -# -# POISSON = BLOC ( condition = " Law in ( 'Poisson', ) ", -# -# Lambda = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Parametre Lambda de la loi | Lambda > 0", -# ang = "Lambda parameter | Lambda > 0", -# ), -# -# ), # Fin BLOC POISSON -# -# -# -# RAYLEIGH = BLOC ( condition = " Law in ( 'Rayleigh', ) ", -# -# Sigma = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Parametre Sigma de la loi | Sigma > 0", -# ang = "Sigma parameter | Sigma > 0", -# ), -# -# Gamma = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Borne inferieure du support de la loi", -# ang = "Support lower bound", -# ), -# ), # Fin BLOC RAYLEIGH - - PDF = BLOC ( condition = " Law in ( 'PDF_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Nom du fichier .csv", - ang = ".csv file name", - ), - ), - -# STUDENT = BLOC ( condition = " Law in ( 'Student', ) ", -# -# Mu = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Parametre Mu de la loi", -# ang = "Mu parameter", -# ), -# -# Nu = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 2., -# fr = "Parametre Nu de la loi | Nu > 2", -# ang = "Nu parameter | Nu > 2", -# ), -# -# Sigma = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Parametre Sigma de la loi", -# ang = "Sigma parameter", -# ), -# -# ), # Fin BLOC STUDENT -# -# -# -# TRIANGULAR = BLOC ( condition = " Law in ( 'Triangular', ) ", -# -# A = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Borne inferieure du support de la loi | A < M < B", -# ang = "Support lower bound | A < M < B", -# ), -# -# M = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Mode de la loi | A < M < B", -# ang = "Mode | A < M < B", -# ), -# -# B = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Borne superieure du support de la loi | A < M < B", -# ang = "Support upper bound | A < M < B", -# ), -# -# ), # Fin BLOC TRIANGULAR -# -# - - TRUNCATEDNORMAL = BLOC ( condition = " Law in ( 'TruncatedNormal', ) ", - - MuN = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi Normale non tronqu�e", - ang = "Mean value of the associated non truncated normal distribution", - ), - - SigmaN = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart-type de la loi Normale non tronqu�e", - ang = "Standard deviation of the associated non truncated normal distribution", - ), - - A = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure de la loi | A < B", - ang = "Lower bound | A < B", - ), - - B = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne superieure de la loi | A < B", - ang = "Upper bound | A < B", - ), - - ), # Fin BLOC TRUNCATEDNORMAL - - - TimeSeries = BLOC ( condition = " Law in ( 'TimeSeries_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Fichier CSV d'une serie temporelle", - ang = "CSV file of a time series", - ), - ), - - - UNIFORM = BLOC ( condition = " Law in ( 'Uniform', ) ", - - A = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi | A < B", - ang = "Support lower bound | A < B", - ), - - B = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne superieure du support de la loi | A < B", - ang = "Support upper bound | A < B", - ), - - ), # Fin BLOC UNIFORM - - - USERDEFINED = BLOC ( condition = " Law in ( 'UserDefined', ) ", - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : (valeur, probabilite)", - ang = "List of pairs : (value, probability)", - validators=VerifTypeTuple(('R','R')), - defaut=((0,0.0),(1,1.0)), - ), - - ), # Fin BLOC USERDEFINED - - - WEIBULL = BLOC ( condition = " Law in ( 'Weibull', ) ", - - Settings = SIMP ( statut = "o", - typ = "TXM", - max = 1, - into = ( "AlphaBeta", "MuSigma" ), - defaut = "AlphaBeta", - fr = "Parametrage de la loi weibull", - ang = "Weibull distribution parameter set", - ), - - AlphaBeta_Parameters = BLOC ( condition = " Settings in ( 'AlphaBeta', ) ", - - Alpha = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Alpha de la loi | Alpha > 0", - ang = "Alpha parameter | Alpha > 0", - ), - - Beta = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Beta de la loi | Beta > 0", - ang = "Beta parameter | Beta > 0", - ), - - ), # Fin BLOC AlphaBeta_Parameters - - - MuSigma_Parameters = BLOC ( condition = " Settings in ( 'MuSigma', ) ", - - Mu = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi", - ang = "Mean value", - ), - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart type de la loi", - ang = "Standard deviation", - ), - - ), # Fin BLOC MuSigma_Parameters - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - - ), # Fin BLOC WEIBULL - - - - ), #fin du bloc transformer - - -) - -#Classement_Commandes_Ds_Arbre=('DIRECTORY', 'DISTRIBUTION', 'CORRELATION') -Classement_Commandes_Ds_Arbre=('DIRECTORY', 'PSSE_PARAMETERS', 'SIMULATION', 'DISTRIBUTION', 'CORRELATION','N_1_GENERATORS', 'N_1_LINES', 'N_1_TRANSFORMERS', 'N_1_LOADS','N_1_MOTORS') - -Ordre_Des_Commandes = ( 'DIRECTORY', 'PSSE_PARAMETERS', 'SIMULATION', 'DISTRIBUTION', 'CORRELATION', - 'N_1_GENERATORS', 'N_1_LINES', 'N_1_TRANSFORMERS', 'N_1_LOADS','N_1_MOTORS') diff --git a/PSEN_Eficas/PSEN_Cata_PF.py b/PSEN_Eficas/PSEN_Cata_PF.py deleted file mode 100644 index 34c0482c..00000000 --- a/PSEN_Eficas/PSEN_Cata_PF.py +++ /dev/null @@ -1,2446 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2013 EDF R&D -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# - -# -------------------------------------------------- -# debut entete -# -------------------------------------------------- - -#from Accas import ASSD, JDC_CATA, AU_MOINS_UN, PROC, SIMP, FACT, OPER, MACRO, BLOC, A_VALIDATOR -from Accas import * -import opsPSEN_PF - -class loi ( ASSD ) : pass -class variable ( ASSD ) : pass -class sd_charge ( ASSD ) : pass -class sd_generateur ( ASSD ) : pass -class sd_ligne ( ASSD ) : pass -class sd_transfo ( ASSD ) : pass -class sd_moteur (ASSD) : pass -#class sd_busbar ( sd_generateur,sd_charge ) : pass - -import types -class Tuple: - def __init__(self,ntuple): - self.ntuple=ntuple - - def __convert__(self,valeur): - if type(valeur) == types.StringType: - return None - if len(valeur) != self.ntuple: - return None - return valeur - - def info(self): - return "Tuple de %s elements" % self.ntuple - - __repr__=info - __str__=info - -class Matrice: - def __init__(self,nbLigs=None,nbCols=None,methodeCalculTaille=None,formatSortie="ligne",valSup=None,valMin=None,structure=None): - self.nbLigs=nbLigs - self.nbCols=nbCols - self.methodeCalculTaille=methodeCalculTaille - self.formatSortie=formatSortie - self.valSup=valSup - self.valMin=valMin - self.structure=structure - - def __convert__(self,valeur): - # Attention ne verifie pas grand chose - if type(valeur) != types.ListType : - return None - return valeur - - def info(self): - return "Matrice %s x %s" % (self.nbLigs, self.nbCols) - - __repr__=info - __str__=info - - -#CONTEXT.debug = 1 -JdC = JDC_CATA ( code = 'PSEN', - execmodul = None, - regles = ( AU_MOINS_UN ( 'PF_PARAMETERS' ), - AU_MOINS_UN ( 'DIRECTORY' ), - AU_MOINS_UN ( 'DISTRIBUTION' ), - AU_MOINS_UN ( 'SIMULATION' ), - AU_PLUS_UN ( 'PF_PARAMETERS' ), - AU_PLUS_UN ( 'DIRECTORY' ), - AU_PLUS_UN ( 'SIMULATION' ), - AU_PLUS_UN ( 'CORRELATION' ), - AU_PLUS_UN ( 'N_1_GENERATORS' ), - AU_PLUS_UN ( 'N_1_LINES' ), - AU_PLUS_UN ( 'N_1_LOADS' ), - AU_PLUS_UN ( 'N_1_MOTORS' ), - AU_PLUS_UN ( 'N_1_TRANSFORMERS' ), - - ), - ) # Fin JDC_CATA - - -# -------------------------------------------------- -# fin entete -# -------------------------------------------------- - -MONGENER = OPER ( nom = "MONGENER", - sd_prod = sd_generateur, - UIinfo = {"groupes": ("CACHE")}, - op = None, - fr = "Generateur", - ang = "Generator", - - ID = SIMP ( statut = 'o', typ = "TXM", fr = "num bus", ang = "num bus",), -) -MONMOTEUR = OPER ( nom = "MONMOTEUR", - sd_prod = sd_moteur, - UIinfo = {"groupes": ("CACHE")}, - op = None, - fr = "Moteur", - ang = "Motor", - - ID = SIMP ( statut = 'o', typ = "TXM", fr = "num bus", ang = "num bus",), -) - -MACHARGE = OPER ( nom = "MACHARGE", - sd_prod = sd_charge, - UIinfo = {"groupes": ("CACHE")}, - op = None, - fr = "Charge", - ang = "Load", - - ID = SIMP ( statut = 'o', typ = "TXM", fr = "nom charge", ang = "load name",), -) -MALIGNE = OPER ( nom = "MALIGNE", - sd_prod = sd_ligne, - UIinfo = {"groupes": ("CACHE")}, - op = None, - fr = "Ligne", - ang = "Line", - - ID = SIMP ( statut = 'o', typ = "TXM", fr = "nom ligne", ang = "line name",), -) -MONTRANSFO = OPER ( nom = "MONTRANSFO", - sd_prod = sd_transfo, - UIinfo = {"groupes": ("CACHE")}, - op = None, - fr = "Transformateur", - ang = "Transformer", - - ID = SIMP ( statut = 'o', typ = "TXM", fr = "nom transformateur", ang = "transformer name",), -) - - - -PF_PARAMETERS = PROC ( nom = "PF_PARAMETERS", op=None, docu = "", - ALGORITHM = SIMP ( statut = "o",typ='TXM', into=["Optimum Power Flow"], defaut="Optimum Power Flow", ), - # I_MAX=SIMP(statut="o",typ='TXM',into=['RateA', 'RateB', 'RateC'],defaut='RateA',), - LOCK_TAPS = SIMP ( statut = "o", typ=bool, defaut=True, ), - b_OPF = BLOC (condition = "ALGORITHM == 'Optimum Power Flow'", - OBJECTIVE_FUNCTION=SIMP(statut="o",typ='TXM',into=['MINIMISATION_OF_COST','LOADSHEDDING_COSTS','MINIMISATION_OF_LOSSES','MAXIMISATION_MVAR_RESERVE'],defaut='MINIMISATION_OF_COST',), - ITERATION_INTERIOR = SIMP ( statut = "o",typ = "I",val_min=1,defaut=700,), - NON_COST_OPTIMAL_SOLUTION_ALLOWED=SIMP(statut="o",typ=bool,defaut=True, ), - LOAD_SHEDDING_ALLOWED=SIMP(statut="o",typ=bool,defaut=True, ), - LS_Q_CONVERGENCE_CRITERIA=SIMP(statut="o",typ=bool,defaut=False, - fr = "Determine quel critère de convergence est utilisé--celui basé sur le quantité de delestage et la puissance reactive modifiée au niveau des shunt, ou celui basé sur la tension moyenne des buses et le flux des branches.", - ang = "Determines which convergence criteria is used--one based on added load-shedding and shunt reactive power, or one based on average bus voltages and branch flows", - ), - UNIT_COMMITMENT = SIMP ( statut = "o", typ = bool,defaut = True, - fr = "Premiere passe de l'OPF pour determiner quels groupes doivent être connectes. Deconnecter les autres.", - ang = "First OPF to determine which units should be run; others are disconnected.",), - # b_UnitCommitment = BLOC (condition = "UNIT_COMMITMENT == True", - # SAVE_CASE_BEFORE_UNIT_COMMITMENT = SIMP ( statut = "o",typ = bool,defaut = False, - # fr = "Sauvegarder des fichiers de cas avant d'avoir deconnecte les groupes ne produisant pas de la puissance active", - # ang = "Save network case files before having disconnected groups that dont generate active power.",),), - ), - DECIMAL_SEPARATOR = SIMP(statut="o",typ='TXM',into=[',','.'],defaut='.',), - ) - -SIMULATION = PROC ( nom = "SIMULATION", op = None, docu = "", - regles =(EXCLUS('NUMBER_PACKAGE','CONVERGENCE'), UN_PARMI('NUMBER_PACKAGE','CONVERGENCE'),), - SIZE_PACKAGE = SIMP ( statut = "o", typ = "I", val_min=1, defaut=10, ), - NUMBER_PACKAGE = SIMP ( statut = "f",typ = "I", val_min=1, ), - CONVERGENCE = SIMP ( statut = "f", typ="I", into=[1], ),) - - -#================================ -# Definition du modele physique -#================================ - - - -CORRELATION = PROC ( nom = 'CORRELATION', - op = None, - docu = "", - fr = "Correlation entre variables", - ang = "Variable correlation", - -#### Copula = SIMP ( statut = "o", -#### typ = 'TXM', -#### into = ( "Independent", "Normal" ), -#### defaut = "Independent", -#### fr = "Type de la copule", -#### ang = "Copula kind", -#### ), -## -## # Matrix = BLOC ( condition = "Copula in ( 'Normal', )", -## - CorrelationMatrix = SIMP ( statut = "o", - typ = Matrice(nbLigs=None, - nbCols=None, - methodeCalculTaille='NbDeDistributions', - structure="symetrique"), - fr = "Matrice de correlation entre les variables d'entree", - ang = "Correlation matrix for input variables", - #val_max=1.0, - #val_min=-1.0 - ), -## #), # Fin BLOC Matrix -## -## -) - -DIRECTORY = MACRO ( nom = 'DIRECTORY', - op=None, - fr = "Chargement des directoires et fichiers", - ang = "Load directories and files necessary to run PSEN", - sd_prod = opsPSEN_PF.INCLUDE, - op_init = opsPSEN_PF.INCLUDE_context, - #sd_prod=None, - fichier_ini = 1, - - PF_path=SIMP(statut="o",typ='Repertoire',defaut=r'C:\Program Files\DIgSILENT\PowerFactory 2017 SP1\Python\3.5'), - pfd_file=SIMP(statut="o", typ = ('Fichier', 'Network Case Files (*.pfd);;All Files (*)',),), - results_folder=SIMP(statut="o",typ='Repertoire'),#,defaut=r'C:\Users\VN38270N\Documents\ResultatSim'), - Python3_path=SIMP(statut="o",typ='Repertoire',defaut=r'C:\Anaconda3'), - #lines_file=SIMP(statut="o" ,typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',),), - #groups_file=SIMP(statut="o", typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',),), - #generationsystem_file=SIMP(statut="o" ,typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',),), - -) - - - -#================================ -# Importation des fichiers csv N-1 -#================================ - -N_1_LINES = PROC( nom="N_1_LINES", - op = None, - docu = "", - fr = "N-1 lignes", - ang = "N-1 lines", - Activated = SIMP ( statut='o', typ=bool, defaut=True), -## FileName = SIMP ( statut = "o", -## typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), -## fr = "chemin du fichier csv des probabilites des defauts lignes", -## ang = "csv file path with probabilities of line outages", -## ), - Probability = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Probabilite d'indisponibilite de la ligne", - ang = "Probability that the line is not available", - validators=VerifTypeTuple((sd_ligne,'R')),), - ) - -N_1_TRANSFORMERS = PROC( nom="N_1_TRANSFORMERS", - op = None, - docu = "", - fr = "N-1 transformateurs", - ang = "N-1 transformers", - Activated = SIMP ( statut='o', typ=bool, defaut=True), -## FileName = SIMP ( statut = "o", -## typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), -## fr = "chemin du fichier csv des probabilites des defauts transformateur", -## ang = "csv file path with probabilities of transformer outages", -## ), - Probability = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Probabilite d'indisponibilite de la ligne", - ang = "Probability that the line is not available", - validators=VerifTypeTuple((sd_transfo,'R')),), - ) -N_1_GENERATORS = PROC( nom="N_1_GENERATORS", - op = None, - docu = "", - fr = "N-1 generateurs", - ang = "N-1 generators", - Activated = SIMP ( statut='o', typ=bool, defaut=True), -## FileName = SIMP ( statut = "o", -## typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), -## fr = "chemin du fichier csv des probabilites des defauts generateurs", -## ang = "csv file path with probabilities of generator outages", -## ), - Probability = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Probabilite d'indisponibilite du generateur", - ang = "Probability that the generator is not available", - validators=VerifTypeTuple((sd_generateur,'R')),), - ) -N_1_MOTORS = PROC( nom="N_1_MOTORS", - op = None, - docu = "", - fr = "N-1 moteurs", - ang = "N-1 motors", - Activated = SIMP ( statut='o', typ=bool, defaut=True), -## FileName = SIMP ( statut = "o", -## typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), -## fr = "chemin du fichier csv des probabilites des defauts generateurs", -## ang = "csv file path with probabilities of generator outages", -## ), - Probability = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Probabilite d'indisponibilite du moteur", - ang = "Probability that the motor is not available", - validators=VerifTypeTuple((sd_moteur,'R')),), - ) -N_1_LOADS = PROC( nom="N_1_LOADS", - op = None, - docu = "", - fr = "N-1 charges", - ang = "N-1 loads", - Activated = SIMP ( statut='o', typ=bool, defaut=True), -## FileName = SIMP ( statut = "o", -## typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), -## fr = "chemin du fichier csv des probabilites des defauts charges", -## ang = "csv file path with probabilities of load outages", -## ), - Probability = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Probabilite d'indisponibilite du generateur", - ang = "Probability that the generator is not available", - validators=VerifTypeTuple((sd_charge,'R')),), - ) - - - - -#================================ -# Definition des LOIS -#================================ - -# Nota : les variables de type OPER doivent etre en majuscules ! -# Nota : les variables de type OPER doivent etre de premier niveau (pas imbriquees dans un autre type) -DISTRIBUTION = OPER ( nom = "DISTRIBUTION", - sd_prod = loi, - op = 68, - fr = "Definitions des lois marginales utilisees par les variables d'entree", - -#==== -# Choisir generateur ou charge -#==== - -## TypeMachine = SIMP ( statut='o', typ='TXM', -## into = ('charge','vent1','vent2','pv','N-1',), -## ), - Activated = SIMP ( statut='o', typ=bool, defaut=True), - ComponentType = SIMP (statut='o', typ='TXM', - into = ('Generator','Load','Motor','Line','Transformer'),), - b_gener = BLOC (condition = "ComponentType == 'Generator'", - - Type = SIMP (statut= "o", typ = "TXM", - into = ("Generator Power Level", "Generator Unavailability"), - fr = "Choisir si c'est le niveau de puissance ou la indisponibilit� du generateur qui sera tiree", - ang= "Choose whether the power level or the unavailability of the generator will be set by the law", - defaut = "Generator Power Level", - ), - - Sampling = SIMP (statut= "o", typ = "TXM", - into = ("Same sample for all generators", "One sample per generator"), - fr = "Choisir si une seule tirage sera fait pour tous les generateurs ou si des tirages differents seront faits pour chaque generateur", - ang= "Choose whether one drawing/sample will be performed for all of the generators or whether a different drawing/sample will be performed for each generator.", - defaut = "Same sample for all generators", - ), - - Generator = SIMP(statut='o',typ=sd_generateur,max="**", homo="SansOrdreNiDoublon"), - -#==== -# Type de distribution -#==== - - b_gener_level = BLOC (condition= "Type == 'Generator Power Level'", - - Law = SIMP ( statut = "o", typ = "TXM", - into = ( "Exponential", - "Histogram", - "Normal", - #"Rayleigh", - "PDF_from_file", - "TruncatedNormal", - "TimeSeries_from_file", - "Uniform", - "UserDefined", - "Weibull", - ), - fr = "Choix du type de la loi marginale", - ang = "1D marginal distribution", - ), - - -#==== -# Definition des parametres selon le type de la loi -#==== - - - EXPONENTIAL = BLOC ( condition = " Law in ( 'Exponential', ) ", - - Lambda = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Lambda | Lambda > 0", - ang = "Lambda parameter | Lambda > 0", - ), - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - - ), # Fin BLOC EXPONENTIAL - - - HISTOGRAM = BLOC ( condition = " Law in ( 'Histogram', ) ", - - First = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du supoport de la loi", - ang = "Support lower bound", - ), - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : largeur de classe, hauteur de classe", - ang = "Class bandwidth, class height couple list", - validators=VerifTypeTuple(('R','R')), - ), - - ), # Fin BLOC HISTOGRAM - - - NORMAL = BLOC ( condition = " Law in ( 'Normal', ) ", - - Mu = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi", - ang = "Mean value", - ), - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart type de la loi", - ang = "Standard deviation", - ), - - ), # Fin BLOC NORMAL - - - RAYLEIGH = BLOC ( condition = " Law in ( 'Rayleigh', ) ", - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Parametre Sigma de la loi | Sigma > 0", - ang = "Sigma parameter | Sigma > 0", - ), - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - ), # Fin BLOC RAYLEIGH - - PDF = BLOC ( condition = " Law in ( 'PDF_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Nom du fichier .csv", - ang = ".csv file name", - ), - ), - - - - TRUNCATEDNORMAL = BLOC ( condition = " Law in ( 'TruncatedNormal', ) ", - - MuN = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi Normale non tronqu�e", - ang = "Mean value of the associated non truncated normal distribution", - ), - - SigmaN = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart-type de la loi Normale non tronqu�e", - ang = "Standard deviation of the associated non truncated normal distribution", - ), - - A = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure de la loi | A < B", - ang = "Lower bound | A < B", - ), - - B = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne superieure de la loi | A < B", - ang = "Upper bound | A < B", - ), - - ), # Fin BLOC TRUNCATEDNORMAL - - - TimeSeries = BLOC ( condition = " Law in ( 'TimeSeries_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Fichier CSV d'une serie temporelle", - ang = "CSV file of a time series", - ), - ), - - - UNIFORM = BLOC ( condition = " Law in ( 'Uniform', ) ", - - A = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi | A < B", - ang = "Support lower bound | A < B", - ), - - B = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne superieure du support de la loi | A < B", - ang = "Support upper bound | A < B", - ), - - ), # Fin BLOC UNIFORM - - - USERDEFINED = BLOC ( condition = " Law in ( 'UserDefined', ) ", - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : (valeur, prob.)", - ang = "List of pairs : (value, prob.)", - validators=VerifTypeTuple(('R','R')), - ), - - ), # Fin BLOC USERDEFINED - - - WEIBULL = BLOC ( condition = " Law in ( 'Weibull', ) ", - - Settings = SIMP ( statut = "o", - typ = "TXM", - max = 1, - into = ( "AlphaBeta", "MuSigma" ), - defaut = "AlphaBeta", - fr = "Parametrage de la loi weibull", - ang = "Weibull distribution parameter set", - ), - - AlphaBeta_Parameters = BLOC ( condition = " Settings in ( 'AlphaBeta', ) ", - - Alpha = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Alpha de la loi | Alpha > 0", - ang = "Alpha parameter | Alpha > 0", - ), - - Beta = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Beta de la loi | Beta > 0", - ang = "Beta parameter | Beta > 0", - ), - - ), # Fin BLOC AlphaBeta_Parameters - - - MuSigma_Parameters = BLOC ( condition = " Settings in ( 'MuSigma', ) ", - - Mu = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi", - ang = "Mean value", - ), - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart type de la loi", - ang = "Standard deviation", - ), - - ), # Fin BLOC MuSigma_Parameters - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - - ), # Fin BLOC WEIBULL - - - Transfer_Function = FACT(statut='f', - - TF_Input = SIMP ( statut='o', - typ = 'TXM', - fr = 'Entrer une fonction de transfert � partir d''un fichier .pow (vitesse de vent - puissance eolienne)\n \ - ou entrer une liste de tuples (valeur tiree - puissance normalisee)', - ang = 'Enter wind speed - turbine production transfer function as a .pow file, \n \ - or enter a generic list of (law output value, normalized power output) tuples', - into = ('.pow file', 'tuples list'), - ), - b_file = BLOC(condition = "TF_Input == '.pow file'", - File_Name = SIMP ( statut = "o", - typ = ('Fichier', 'Pow files (*.pow);;All Files (*)',), - fr = "Nom du fichier de transfer .pow", - ang = ".pow file name", - ), - Wind_Speed_Measurement_Height = SIMP ( statut = 'o', - typ = "R", - max = 1, - fr = 'Hauteur (en metres) a laquelle les mesures de vitesse du vent ont ete prises', - ang = 'Height of wind speed measurements (m)', - sug = 10, - val_min = 0, - ), - Hub_Height = SIMP (statut = 'o', - typ = "R", - fr = 'hauteur de moyeu de l''eolienne', - ang = 'wind turbine hub height', - sug = 80, - val_min = 0,), - AlphaWS = SIMP (statut = 'o', - typ = "R", - fr = 'l''alpha pour extrapoler les mesures de vitesse du vent a la hauteur du moyeu ', - ang = 'alpha used to extrapolate wind speed measurements to hub height', - defaut = 1./7, - val_min = 0, - val_max = 1, - ), - Percent_Losses = SIMP (statut = 'o', - typ = "R", - fr = 'pourcentage de pertes entre la sortie theorique d''une turbine et la sortie de la centrale', - ang = 'percent losses between theoretical power output of a single turbine and the output of the farm', - defaut = 5, - val_min = 0, - val_max = 100, - ), - ), #fin du bloc FileName - - b_tuples = BLOC(condition = "TF_Input == 'tuples list'", - - TF_Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - min = 2, - fr = "Liste de couples : valeur tiree, puissance normalisee sortie", - ang = "List of couples : value set by law, normalized power output", - validators=VerifTypeTuple(('R','R')), - ), - ), #fin du block Tuples List - - ), #fin du FACT Transfer Function - - ), #fin du bloc generator level - - - b_gener_avail = BLOC (condition= "Type == 'Generator Unavailability'", - - Law = SIMP ( statut = "o", typ = "TXM", - into = ( #"Exponential", - #"Histogram", - #"Normal", - #"Rayleigh", - #"PDF_from_file", - #"TruncatedNormal", - "TimeSeries_from_file", - #"Uniform", - "UserDefined", - #"Weibull", - ), - fr = "Choix du type de la loi marginale", - ang = "1D marginal distribution", - defaut="UserDefined", - ), - - -#==== -# Definition des parametres selon le type de la loi -#==== - - - TimeSeries = BLOC ( condition = " Law in ( 'TimeSeries_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Fichier CSV d'une serie temporelle", - ang = "CSV file of a time series", - ), - ), - - - USERDEFINED = BLOC ( condition = " Law in ( 'UserDefined', ) ", - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : (valeur, prob.)", - ang = "List of pairs : (value, prob.)", - validators=VerifTypeTuple(('R','R')), - defaut=((0,1.0),(1,0.0)), - ), - - ), # Fin BLOC USERDEFINED - - - ), #fin du bloc generator avail - - - ), #fin du bloc generateur - -#Bloc Charge - b_charge = BLOC (condition = "ComponentType == 'Load'", - - -#==== -# Type de distribution -#==== - - Type = SIMP (statut= "o", typ = "TXM", - into = ("Load Level", "Load Unavailability"), - fr = "Choisir si c'est le niveau de charge ou la indisponibilit� de la charge qui sera tiree", - ang= "Choose whether the power level or the unavailability of the load will be set by the law", - defaut = "Load Level", - ), - - Sampling = SIMP (statut= "o", typ = "TXM", - into = ("Same sample for all loads", "One sample per load"), - fr = "Choisir si une seule tirage sera fait pour tous les charges ou si des tirages differents seront faits pour chaque charge", - ang= "Choose whether one drawing/sample will be performed for all of the loads or whether a different drawing/sample will be performed for each load.", - defaut = "Same sample for all loads", - ), - - Load = SIMP(statut='o',typ=sd_charge,max="**", homo="SansOrdreNiDoublon",), - - - b_charge_level = BLOC (condition = "Type == 'Load Level'", - - Law = SIMP ( statut = "o", typ = "TXM", - into = ( "Exponential", - "Histogram", - "Normal", - #"Rayleigh", - "PDF_from_file", - "TruncatedNormal", - "TimeSeries_from_file", - "Uniform", - "UserDefined", - "Weibull", - ), - fr = "Choix du type de la loi marginale", - ang = "1D marginal distribution", - ), - - -#==== -# Definition des parametres selon le type de la loi -#==== - - - EXPONENTIAL = BLOC ( condition = " Law in ( 'Exponential', ) ", - - Lambda = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Lambda | Lambda > 0", - ang = "Lambda parameter | Lambda > 0", - ), - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - - ), # Fin BLOC EXPONENTIAL - - - HISTOGRAM = BLOC ( condition = " Law in ( 'Histogram', ) ", - - First = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du supoport de la loi", - ang = "Support lower bound", - ), - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : largeur de classe, hauteur de classe", - ang = "Class bandwidth, class height couple list", - validators=VerifTypeTuple(('R','R')), - ), - - ), # Fin BLOC HISTOGRAM - - - NORMAL = BLOC ( condition = " Law in ( 'Normal', ) ", - - Mu = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi", - ang = "Mean value", - ), - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart type de la loi", - ang = "Standard deviation", - ), - - ), # Fin BLOC NORMAL - - - RAYLEIGH = BLOC ( condition = " Law in ( 'Rayleigh', ) ", - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Parametre Sigma de la loi | Sigma > 0", - ang = "Sigma parameter | Sigma > 0", - ), - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - ), # Fin BLOC RAYLEIGH - - PDF = BLOC ( condition = " Law in ( 'PDF_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Nom du fichier .csv", - ang = ".csv file name", - ), - ), - - - - TRUNCATEDNORMAL = BLOC ( condition = " Law in ( 'TruncatedNormal', ) ", - - MuN = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi Normale non tronqu�e", - ang = "Mean value of the associated non truncated normal distribution", - ), - - SigmaN = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart-type de la loi Normale non tronqu�e", - ang = "Standard deviation of the associated non truncated normal distribution", - ), - - A = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure de la loi | A < B", - ang = "Lower bound | A < B", - ), - - B = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne superieure de la loi | A < B", - ang = "Upper bound | A < B", - ), - - ), # Fin BLOC TRUNCATEDNORMAL - - - TimeSeries = BLOC ( condition = " Law in ( 'TimeSeries_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Fichier CSV d'une serie temporelle", - ang = "CSV file of a time series", - ), - ), - - - UNIFORM = BLOC ( condition = " Law in ( 'Uniform', ) ", - - A = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi | A < B", - ang = "Support lower bound | A < B", - ), - - B = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne superieure du support de la loi | A < B", - ang = "Support upper bound | A < B", - ), - - ), # Fin BLOC UNIFORM - - - USERDEFINED = BLOC ( condition = " Law in ( 'UserDefined', ) ", - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : (valeur, probabilite)", - ang = "List of pairs : (value, probability)", - validators=VerifTypeTuple(('R','R')), - ), - - ), # Fin BLOC USERDEFINED - - - WEIBULL = BLOC ( condition = " Law in ( 'Weibull', ) ", - - Settings = SIMP ( statut = "o", - typ = "TXM", - max = 1, - into = ( "AlphaBeta", "MuSigma" ), - defaut = "AlphaBeta", - fr = "Parametrage de la loi weibull", - ang = "Weibull distribution parameter set", - ), - - AlphaBeta_Parameters = BLOC ( condition = " Settings in ( 'AlphaBeta', ) ", - - Alpha = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Alpha de la loi | Alpha > 0", - ang = "Alpha parameter | Alpha > 0", - ), - - Beta = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Beta de la loi | Beta > 0", - ang = "Beta parameter | Beta > 0", - ), - - ), # Fin BLOC AlphaBeta_Parameters - - - MuSigma_Parameters = BLOC ( condition = " Settings in ( 'MuSigma', ) ", - - Mu = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi", - ang = "Mean value", - ), - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart type de la loi", - ang = "Standard deviation", - ), - - ), # Fin BLOC MuSigma_Parameters - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - - ), # Fin BLOC WEIBULL - - ), #fin du block Load Level - - - b_charge_avail = BLOC (condition = "Type == 'Load Unavailability'", - - Law = SIMP ( statut = "o", typ = "TXM", - into = ( #"Exponential", - #"Histogram", - #"Normal", - #"Rayleigh", - #"PDF_from_file", - #"TruncatedNormal", - "TimeSeries_from_file", - #"Uniform", - "UserDefined", - #"Weibull", - ), - fr = "Choix du type de la loi marginale", - ang = "1D marginal distribution", - defaut = "UserDefined", - ), - - -#==== -# Definition des parametres selon le type de la loi -#==== - - TimeSeries = BLOC ( condition = " Law in ( 'TimeSeries_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Fichier CSV d'une serie temporelle", - ang = "CSV file of a time series", - ), - ), - - - - USERDEFINED = BLOC ( condition = " Law in ( 'UserDefined', ) ", - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : (valeur, probabilite)", - ang = "List of pairs : (value, probability)", - validators=VerifTypeTuple(('R','R')), - defaut=((0,1.0),(1,0.0)), - ), - - ), # Fin BLOC USERDEFINED - - - ), #fin du block Load Avail - - - ), #fin du bloc charge - - - -#Bloc Moteur - b_moteur = BLOC (condition = "ComponentType == 'Motor'", - - -#==== -# Type de distribution -#==== - - Type = SIMP (statut= "o", typ = "TXM", - into = ("Motor Level", "Motor Unavailability"), - fr = "Choisir si c'est le niveau de charge du moteur ou la indisponibilit� du moteur qui sera tiree", - ang= "Choose whether the power level or the unavailability of the motor will be set by the law", - defaut = "Motor Level", - ), - - Sampling = SIMP (statut= "o", typ = "TXM", - into = ("Same sample for all motors", "One sample per motor"), - fr = "Choisir si une seule tirage sera fait pour tous les moteurs ou si des tirages differents seront faits pour chaque moteur", - ang= "Choose whether one drawing/sample will be performed for all of the motors or whether a different drawing/sample will be performed for each motor.", - defaut = "Same sample for all motors", - ), - - Motor = SIMP(statut='o',typ=sd_moteur,max="**", homo="SansOrdreNiDoublon",), - - - b_moteur_level = BLOC (condition = "Type == 'Motor Level'", - - Law = SIMP ( statut = "o", typ = "TXM", - into = ( "Exponential", - "Histogram", - "Normal", - #"Rayleigh", - "PDF_from_file", - "TruncatedNormal", - "TimeSeries_from_file", - "Uniform", - "UserDefined", - "Weibull", - ), - fr = "Choix du type de la loi marginale", - ang = "1D marginal distribution", - ), - - -#==== -# Definition des parametres selon le type de la loi -#==== - - - EXPONENTIAL = BLOC ( condition = " Law in ( 'Exponential', ) ", - - Lambda = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Lambda | Lambda > 0", - ang = "Lambda parameter | Lambda > 0", - ), - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - - ), # Fin BLOC EXPONENTIAL - - - HISTOGRAM = BLOC ( condition = " Law in ( 'Histogram', ) ", - - First = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du supoport de la loi", - ang = "Support lower bound", - ), - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : largeur de classe, hauteur de classe", - ang = "Class bandwidth, class height couple list", - validators=VerifTypeTuple(('R','R')), - ), - - ), # Fin BLOC HISTOGRAM - - - NORMAL = BLOC ( condition = " Law in ( 'Normal', ) ", - - Mu = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi", - ang = "Mean value", - ), - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart type de la loi", - ang = "Standard deviation", - ), - - ), # Fin BLOC NORMAL - - - RAYLEIGH = BLOC ( condition = " Law in ( 'Rayleigh', ) ", - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Parametre Sigma de la loi | Sigma > 0", - ang = "Sigma parameter | Sigma > 0", - ), - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - ), # Fin BLOC RAYLEIGH - - PDF = BLOC ( condition = " Law in ( 'PDF_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Nom du fichier .csv", - ang = ".csv file name", - ), - ), - - - - TRUNCATEDNORMAL = BLOC ( condition = " Law in ( 'TruncatedNormal', ) ", - - MuN = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi Normale non tronqu�e", - ang = "Mean value of the associated non truncated normal distribution", - ), - - SigmaN = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart-type de la loi Normale non tronqu�e", - ang = "Standard deviation of the associated non truncated normal distribution", - ), - - A = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure de la loi | A < B", - ang = "Lower bound | A < B", - ), - - B = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne superieure de la loi | A < B", - ang = "Upper bound | A < B", - ), - - ), # Fin BLOC TRUNCATEDNORMAL - - - TimeSeries = BLOC ( condition = " Law in ( 'TimeSeries_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Fichier CSV d'une serie temporelle", - ang = "CSV file of a time series", - ), - ), - - - UNIFORM = BLOC ( condition = " Law in ( 'Uniform', ) ", - - A = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi | A < B", - ang = "Support lower bound | A < B", - ), - - B = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne superieure du support de la loi | A < B", - ang = "Support upper bound | A < B", - ), - - ), # Fin BLOC UNIFORM - - - USERDEFINED = BLOC ( condition = " Law in ( 'UserDefined', ) ", - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : (valeur, probabilite)", - ang = "List of pairs : (value, probability)", - validators=VerifTypeTuple(('R','R')), - ), - - ), # Fin BLOC USERDEFINED - - - WEIBULL = BLOC ( condition = " Law in ( 'Weibull', ) ", - - Settings = SIMP ( statut = "o", - typ = "TXM", - max = 1, - into = ( "AlphaBeta", "MuSigma" ), - defaut = "AlphaBeta", - fr = "Parametrage de la loi weibull", - ang = "Weibull distribution parameter set", - ), - - AlphaBeta_Parameters = BLOC ( condition = " Settings in ( 'AlphaBeta', ) ", - - Alpha = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Alpha de la loi | Alpha > 0", - ang = "Alpha parameter | Alpha > 0", - ), - - Beta = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Beta de la loi | Beta > 0", - ang = "Beta parameter | Beta > 0", - ), - - ), # Fin BLOC AlphaBeta_Parameters - - - MuSigma_Parameters = BLOC ( condition = " Settings in ( 'MuSigma', ) ", - - Mu = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi", - ang = "Mean value", - ), - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart type de la loi", - ang = "Standard deviation", - ), - - ), # Fin BLOC MuSigma_Parameters - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - - ), # Fin BLOC WEIBULL - - ), #fin du block Load Level - - - b_moteur_avail = BLOC (condition = "Type == 'Motor Unavailability'", - - Law = SIMP ( statut = "o", typ = "TXM", - into = ( #"Exponential", - #"Histogram", - #"Normal", - #"Rayleigh", - #"PDF_from_file", - #"TruncatedNormal", - "TimeSeries_from_file", - #"Uniform", - "UserDefined", - #"Weibull", - ), - fr = "Choix du type de la loi marginale", - ang = "1D marginal distribution", - defaut = "UserDefined", - ), - - -#==== -# Definition des parametres selon le type de la loi -#==== - - TimeSeries = BLOC ( condition = " Law in ( 'TimeSeries_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Fichier CSV d'une serie temporelle", - ang = "CSV file of a time series", - ), - ), - - - - USERDEFINED = BLOC ( condition = " Law in ( 'UserDefined', ) ", - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : (valeur, probabilite)", - ang = "List of pairs : (value, probability)", - validators=VerifTypeTuple(('R','R')), - defaut=((0,1.0),(1,0.0)), - ), - - ), # Fin BLOC USERDEFINED - - - ), #fin du block Load Avail - - - ), #fin du bloc moteur - - - b_ligne = BLOC (condition = "ComponentType == 'Line'", - - -#==== -# Type de distribution -#==== - - Type = SIMP (statut= "o", typ = "TXM", - into = ("Line Unavailability",), - fr = "L'indisponibilite de la ligne sera tiree", - ang= "Line unavailability will be set by the law", - defaut = "Line Unavailability", - ), - - Sampling = SIMP (statut= "o", typ = "TXM", - into = ("Same sample for all lines", "One sample per line"), - fr = "Choisir si une seule tirage sera fait pour tous les lignes ou si des tirages differents seront faits pour chaque ligne", - ang= "Choose whether one drawing/sample will be performed for all of the lines or whether a different drawing/sample will be performed for each line.", - defaut = "Same sample for all lines", - ), - - Line = SIMP(statut='o',typ=sd_ligne,max="**", homo="SansOrdreNiDoublon"), - - Law = SIMP ( statut = "o", typ = "TXM", - into = ( #"Exponential", - #"Histogram", - #"Normal", - #"Rayleigh", - #"PDF_from_file", - #"TruncatedNormal", - "TimeSeries_from_file", - #"Uniform", - "UserDefined", - #"Weibull", - ), - defaut = "UserDefined", - fr = "Choix du type de la loi marginale", - ang = "1D marginal distribution", - ), - - -#==== -# Definition des parametres selon le type de la loi -#==== - - - EXPONENTIAL = BLOC ( condition = " Law in ( 'Exponential', ) ", - - Lambda = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Lambda | Lambda > 0", - ang = "Lambda parameter | Lambda > 0", - ), - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - - ), # Fin BLOC EXPONENTIAL - - - HISTOGRAM = BLOC ( condition = " Law in ( 'Histogram', ) ", - - First = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du supoport de la loi", - ang = "Support lower bound", - ), - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : largeur de classe, hauteur de classe", - ang = "Class bandwidth, class height couple list", - validators=VerifTypeTuple(('R','R')), - ), - - ), # Fin BLOC HISTOGRAM - - - NORMAL = BLOC ( condition = " Law in ( 'Normal', ) ", - - Mu = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi", - ang = "Mean value", - ), - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart type de la loi", - ang = "Standard deviation", - ), - - ), # Fin BLOC NORMAL - - - RAYLEIGH = BLOC ( condition = " Law in ( 'Rayleigh', ) ", - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Parametre Sigma de la loi | Sigma > 0", - ang = "Sigma parameter | Sigma > 0", - ), - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - ), # Fin BLOC RAYLEIGH - - PDF = BLOC ( condition = " Law in ( 'PDF_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Nom du fichier .csv", - ang = ".csv file name", - ), - ), - - - - TRUNCATEDNORMAL = BLOC ( condition = " Law in ( 'TruncatedNormal', ) ", - - MuN = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi Normale non tronqu�e", - ang = "Mean value of the associated non truncated normal distribution", - ), - - SigmaN = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart-type de la loi Normale non tronqu�e", - ang = "Standard deviation of the associated non truncated normal distribution", - ), - - A = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure de la loi | A < B", - ang = "Lower bound | A < B", - ), - - B = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne superieure de la loi | A < B", - ang = "Upper bound | A < B", - ), - - ), # Fin BLOC TRUNCATEDNORMAL - - - TimeSeries = BLOC ( condition = " Law in ( 'TimeSeries_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Fichier CSV d'une serie temporelle", - ang = "CSV file of a time series", - ), - ), - - - UNIFORM = BLOC ( condition = " Law in ( 'Uniform', ) ", - - A = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi | A < B", - ang = "Support lower bound | A < B", - ), - - B = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne superieure du support de la loi | A < B", - ang = "Support upper bound | A < B", - ), - - ), # Fin BLOC UNIFORM - - - USERDEFINED = BLOC ( condition = " Law in ( 'UserDefined', ) ", - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : (valeur, probabilite)", - ang = "List of pairs : (value, probability)", - validators=VerifTypeTuple(('R','R')), - defaut=((0,1.0),(1,0.0)), - ), - - ), # Fin BLOC USERDEFINED - - - WEIBULL = BLOC ( condition = " Law in ( 'Weibull', ) ", - - Settings = SIMP ( statut = "o", - typ = "TXM", - max = 1, - into = ( "AlphaBeta", "MuSigma" ), - defaut = "AlphaBeta", - fr = "Parametrage de la loi weibull", - ang = "Weibull distribution parameter set", - ), - - AlphaBeta_Parameters = BLOC ( condition = " Settings in ( 'AlphaBeta', ) ", - - Alpha = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Alpha de la loi | Alpha > 0", - ang = "Alpha parameter | Alpha > 0", - ), - - Beta = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Beta de la loi | Beta > 0", - ang = "Beta parameter | Beta > 0", - ), - - ), # Fin BLOC AlphaBeta_Parameters - - - MuSigma_Parameters = BLOC ( condition = " Settings in ( 'MuSigma', ) ", - - Mu = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi", - ang = "Mean value", - ), - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart type de la loi", - ang = "Standard deviation", - ), - - ), # Fin BLOC MuSigma_Parameters - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - - ), # Fin BLOC WEIBULL - - ), #fin du bloc ligne - - b_transfo = BLOC (condition = "ComponentType == 'Transformer'", - - -#==== -# Type de distribution -#==== - - Type = SIMP (statut= "o", typ = "TXM", - into = ("Transformer Unavailability",), - fr = "L'indisponibilite du transformateur sera tiree", - ang= "Transformer unavailability will be set by the law", - defaut = "Transformer Unavailability" - ), - - Sampling = SIMP (statut= "o", typ = "TXM", - into = ("Same sample for all transformers", "One sample per transformer"), - fr = "Choisir si une seule tirage sera fait pour tous les transforamteurs ou si des tirages differents seront faits pour chaque transformateur", - ang= "Choose whether one drawing/sample will be performed for all of the tranformers or whether a different drawing/sample will be performed for each transformer.", - defaut = "Same sample for all transformers", - ), - - Transformer = SIMP(statut='o',typ=sd_transfo,max="**", homo="SansOrdreNiDoublon"), - - Law = SIMP ( statut = "o", typ = "TXM", - into = ( #"Beta", - #"Exponential", - #"Gamma", - #"Geometric", - #"Gumbel", - #"Histogram", - #"Laplace", - #"Logistic", - #"LogNormal", - #"MultiNomial", - #"NonCentralStudent", - #"Normal", - #"Poisson", - #"Rayleigh", - #"Student", - #"PDF_from_file", - #"Triangular", - #"TruncatedNormal", - "TimeSeries_from_file", - #"Uniform", - "UserDefined", - #"Weibull", - ), - defaut="UserDefined", - fr = "Choix du type de la loi marginale", - ang = "1D marginal distribution", - ), - - -#==== -# Definition des parametres selon le type de la loi -#==== - -## NONPARAM = BLOC ( condition = " Law in ( 'NonParametrique', ) ", -## -## FileName = SIMP ( statut = "o", -## typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), -## fr = "Nom du modele physique", -## ang = "Physical model identifier", -## ), -## ), - -# BETA = BLOC ( condition = " Law in ( 'Beta', ) ", -# -# Settings = SIMP ( statut = "o", -# typ = "TXM", -# max = 1, -# into = ( "RT", "MuSigma" ), -# defaut = "RT", -# fr = "Parametrage de la loi beta", -# ang = "Beta distribution parameter set", -# ), -# -# RT_Parameters = BLOC ( condition = " Settings in ( 'RT', ) ", -# -# R = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Parametre R de la loi | R > 0", -# ang = "R parameter | R > 0", -# ), -# -# # T > R -# T = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Parametre T de la loi | T > R", -# ang = "T parameter | T > R", -# ), -# -# ), # Fin BLOC RT_Parameters -# -# -# MuSigma_Parameters = BLOC ( condition = " Settings in ( 'MuSigma', ) ", -# -# Mu = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Moyenne de la loi", -# ang = "Mean value", -# ), -# -# Sigma = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Ecart type de la loi", -# ang = "Standard deviation", -# ), -# -# ), # Fin BLOC MuSigma_Parameters -# -# -# A = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Borne inferieure du support de la loi", -# ang = "Support lower bound", -# ), -# -# # B > A -# B = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Borne superieure du support de la loi", -# ang = "Support upper bound", -# ), -# -# ), # Fin BLOC BETA - - - - EXPONENTIAL = BLOC ( condition = " Law in ( 'Exponential', ) ", - - Lambda = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Lambda | Lambda > 0", - ang = "Lambda parameter | Lambda > 0", - ), - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - - ), # Fin BLOC EXPONENTIAL - - - -# GAMMA = BLOC ( condition = " Law in ( 'Gamma', ) ", -# -# Settings = SIMP ( statut = "o", -# typ = "TXM", -# max = 1, -# into = ( "KLambda", "MuSigma" ), -# defaut = "KLambda", -# fr = "Parametrage de la loi gamma", -# ang = "Gamma distribution parameter set", -# ), -# -# KLambda_Parameters = BLOC ( condition = " Settings in ( 'KLambda', ) ", -# -# K = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Parametre K de la loi | K > 0", -# ang = "K parameter | K > 0", -# ), -# -# Lambda = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Parametre Lambda de la loi | Lambda > 0", -# ang = "Lambda parameter | Lambda > 0", -# ), -# -# ), # Fin BLOC KLambda_Parameters -# -# -# MuSigma_Parameters = BLOC ( condition = " Settings in ( 'MuSigma', ) ", -# -# Mu = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Moyenne de la loi", -# ang = "Mean value", -# ), -# -# Sigma = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Ecart type de la loi", -# ang = "Standard deviation", -# ), -# -# ), # Fin BLOC MuSigma_Parameters -# -# Gamma = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Borne inferieure du supoport de la loi", -# ang = "Support lower bound", -# ), -# -# -# ), # Fin BLOC GAMMA - - -# -# GEOMETRIC = BLOC ( condition = " Law in ( 'Geometric', ) ", -# -# P = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# val_max = 1., -# fr = "Parametre P | 0 < P < 1", -# ang = "P parameter | 0 < P < 1", -# ), -# -# ), # Fin BLOC GEOMETRIC -# -# -# -# GUMBEL = BLOC ( condition = " Law in ( 'Gumbel', ) ", -# -# Settings = SIMP ( statut = "o", -# typ = "TXM", -# max = 1, -# into = ( "AlphaBeta", "MuSigma" ), -# defaut = "AlphaBeta", -# fr = "Parametrage de la loi gumbel", -# ang = "Gumbel distribution parameter set", -# ), -# -# AlphaBeta_Parameters = BLOC ( condition = " Settings in ( 'AlphaBeta', ) ", -# -# Alpha = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Parametre Alpha de la loi | Alpha > 0", -# ang = "Alpha parameter | Alpha > 0", -# ), -# -# Beta = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Parametre Beta de la loi", -# ang = "Beta parameter", -# ), -# -# ), # Fin BLOC AlphaBeta_Parameters -# -# -# MuSigma_Parameters = BLOC ( condition = " Settings in ( 'MuSigma', ) ", -# -# Mu = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Moyenne de la loi", -# ang = "Mean value", -# ), -# -# Sigma = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Ecart type de la loi", -# ang = "Standard deviation", -# ), -# -# ), # Fin BLOC MuSigma_Parameters -# -# ), # Fin BLOC GUMBEL - - - - HISTOGRAM = BLOC ( condition = " Law in ( 'Histogram', ) ", - - First = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du supoport de la loi", - ang = "Support lower bound", - ), - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : largeur de classe, hauteur de classe", - ang = "Class bandwidth, class height couple list", - validators=VerifTypeTuple(('R','R')), - ), - - ), # Fin BLOC HISTOGRAM - - - -# LAPLACE = BLOC ( condition = " Law in ( 'Laplace', ) ", -# -# Lambda = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Parametre Lambda | Lambda > 0", -# ang = "Lambda parameter | Lambda > 0", -# ), -# -# Mu = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Moyenne de la loi", -# ang = "Mean value", -# ), -# -# ), # Fin BLOC LAPLACE -# -# LOGNORMAL = BLOC ( condition = " Law in ( 'LogNormal', ) ", -# -# Settings = SIMP ( statut = "o", -# typ = "TXM", -# max = 1, -# into = ( "MuSigmaLog", "MuSigma", "MuSigmaOverMu" ), -# defaut = "MuSigmaLog", -# fr = "Parametrage de la loi lognormale", -# ang = "Lognormal distribution parameter set", -# ), -# -# MuSigma_Parameters = BLOC ( condition = " Settings in ( 'MuSigma', ) ", -# -# Mu = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Moyenne de la loi", -# ang = "Mean value", -# ), -# -# Sigma = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Ecart type de la loi", -# ang = "Standard deviation", -# ), -# -# ), # Fin BLOC MuSigma_Parameters -# -# MuSigmaOverMu_Parameters = BLOC ( condition = " Settings in ( 'MuSigmaOverMu', ) ", -# -# Mu = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Moyenne de la loi", -# ang = "Mean value", -# ), -# -# SigmaOverMu = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Rapport ecart type / moyenne de la loi", -# ang = "Standard deviation / mean value ratio", -# ), -# -# ), # Fin BLOC MuSigmaOverMu_Parameters -# -# MuSigmaLog_Parameters = BLOC ( condition = " Settings in ( 'MuSigmaLog', ) ", -# -# MuLog = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Moyenne du log", -# ang = "Log mean value", -# ), -# -# SigmaLog = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Ecart type du log", -# ang = "Log standard deviation", -# ), -# -# ), # Fin BLOC MuSigmaLog_Parameters -# -# Gamma = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Borne inferieure du support de la loi", -# ang = "Support lower bound", -# ), -# -# ), # Fin BLOC LOGNORMAL -# -# -# -# LOGISTIC = BLOC ( condition = " Law in ( 'Logistic', ) ", -# -# Alpha = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Borne inferieure du supoport de la loi", -# ang = "Support lower bound", -# ), -# -# Beta = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Parametre Beta de la loi | Beta > 0", -# ang = "Beta parameter | Beta > 0", -# ), -# -# ), # Fin BLOC LOGISTIC -# -# -# -# MULTINOMIAL = BLOC ( condition = " Law in ( 'MultiNomial', ) ", -# -# N = SIMP ( statut = "o", -# typ = "I", -# max = 1, -# fr = "Parametre N de la loi | N > 0", -# ang = "N parameter | N > 0", -# ), -# -# # Il faut definir une collection de couples ( x,p ) -# Values = SIMP ( statut = 'o', -# typ = "R", -# max = '**', -# fr = "Liste de probabilit�s", -# ang = "Probability list", -# validators=VerifTypeTuple(('R','R')), -# ), -# -# ), # Fin BLOC MULTINOMIAL -# -# -# NONCENTRALSTUDENT = BLOC ( condition = " Law in ( 'NonCentralStudent', ) ", -# -# Nu = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Parametre Nu de la loi | Nu > 0", -# ang = "Nu parameter | Nu > 0", -# ), -# -# Delta = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Parametre Delta de la loi | Delta > 0", -# ang = "Delta parameter | Delta > 0", -# ), -# -# Gamma = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Parametre Gamma de centrage de la loi", -# ang = "Gamma parameter", -# ), -# -# ), # Fin BLOC NONCENTRALSTUDENT - - - NORMAL = BLOC ( condition = " Law in ( 'Normal', ) ", - - Mu = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi", - ang = "Mean value", - ), - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart type de la loi", - ang = "Standard deviation", - ), - - ), # Fin BLOC NORMAL - - -# -# POISSON = BLOC ( condition = " Law in ( 'Poisson', ) ", -# -# Lambda = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 0., -# fr = "Parametre Lambda de la loi | Lambda > 0", -# ang = "Lambda parameter | Lambda > 0", -# ), -# -# ), # Fin BLOC POISSON -# -# -# -# RAYLEIGH = BLOC ( condition = " Law in ( 'Rayleigh', ) ", -# -# Sigma = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Parametre Sigma de la loi | Sigma > 0", -# ang = "Sigma parameter | Sigma > 0", -# ), -# -# Gamma = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Borne inferieure du support de la loi", -# ang = "Support lower bound", -# ), -# ), # Fin BLOC RAYLEIGH - - PDF = BLOC ( condition = " Law in ( 'PDF_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Nom du fichier .csv", - ang = ".csv file name", - ), - ), - -# STUDENT = BLOC ( condition = " Law in ( 'Student', ) ", -# -# Mu = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Parametre Mu de la loi", -# ang = "Mu parameter", -# ), -# -# Nu = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# val_min = 2., -# fr = "Parametre Nu de la loi | Nu > 2", -# ang = "Nu parameter | Nu > 2", -# ), -# -# Sigma = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Parametre Sigma de la loi", -# ang = "Sigma parameter", -# ), -# -# ), # Fin BLOC STUDENT -# -# -# -# TRIANGULAR = BLOC ( condition = " Law in ( 'Triangular', ) ", -# -# A = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Borne inferieure du support de la loi | A < M < B", -# ang = "Support lower bound | A < M < B", -# ), -# -# M = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Mode de la loi | A < M < B", -# ang = "Mode | A < M < B", -# ), -# -# B = SIMP ( statut = "o", -# typ = "R", -# max = 1, -# fr = "Borne superieure du support de la loi | A < M < B", -# ang = "Support upper bound | A < M < B", -# ), -# -# ), # Fin BLOC TRIANGULAR -# -# - - TRUNCATEDNORMAL = BLOC ( condition = " Law in ( 'TruncatedNormal', ) ", - - MuN = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi Normale non tronqu�e", - ang = "Mean value of the associated non truncated normal distribution", - ), - - SigmaN = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart-type de la loi Normale non tronqu�e", - ang = "Standard deviation of the associated non truncated normal distribution", - ), - - A = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure de la loi | A < B", - ang = "Lower bound | A < B", - ), - - B = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne superieure de la loi | A < B", - ang = "Upper bound | A < B", - ), - - ), # Fin BLOC TRUNCATEDNORMAL - - - TimeSeries = BLOC ( condition = " Law in ( 'TimeSeries_from_file', ) ", - - FileName = SIMP ( statut = "o", - typ = ('Fichier', 'Wrapper Files (*.csv);;All Files (*)',), - fr = "Fichier CSV d'une serie temporelle", - ang = "CSV file of a time series", - ), - ), - - - UNIFORM = BLOC ( condition = " Law in ( 'Uniform', ) ", - - A = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi | A < B", - ang = "Support lower bound | A < B", - ), - - B = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne superieure du support de la loi | A < B", - ang = "Support upper bound | A < B", - ), - - ), # Fin BLOC UNIFORM - - - USERDEFINED = BLOC ( condition = " Law in ( 'UserDefined', ) ", - - # Il faut definir une collection de couples ( x,p ) - Values = SIMP ( statut = 'o', - typ = Tuple(2), - max = '**', - fr = "Liste de couples : (valeur, probabilite)", - ang = "List of pairs : (value, probability)", - validators=VerifTypeTuple(('R','R')), - defaut=((0,1.0),(1,0.0)), - ), - - ), # Fin BLOC USERDEFINED - - - WEIBULL = BLOC ( condition = " Law in ( 'Weibull', ) ", - - Settings = SIMP ( statut = "o", - typ = "TXM", - max = 1, - into = ( "AlphaBeta", "MuSigma" ), - defaut = "AlphaBeta", - fr = "Parametrage de la loi weibull", - ang = "Weibull distribution parameter set", - ), - - AlphaBeta_Parameters = BLOC ( condition = " Settings in ( 'AlphaBeta', ) ", - - Alpha = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Alpha de la loi | Alpha > 0", - ang = "Alpha parameter | Alpha > 0", - ), - - Beta = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Parametre Beta de la loi | Beta > 0", - ang = "Beta parameter | Beta > 0", - ), - - ), # Fin BLOC AlphaBeta_Parameters - - - MuSigma_Parameters = BLOC ( condition = " Settings in ( 'MuSigma', ) ", - - Mu = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Moyenne de la loi", - ang = "Mean value", - ), - - Sigma = SIMP ( statut = "o", - typ = "R", - max = 1, - val_min = 0., - fr = "Ecart type de la loi", - ang = "Standard deviation", - ), - - ), # Fin BLOC MuSigma_Parameters - - Gamma = SIMP ( statut = "o", - typ = "R", - max = 1, - fr = "Borne inferieure du support de la loi", - ang = "Support lower bound", - ), - - ), # Fin BLOC WEIBULL - - - - ), #fin du bloc transformer - - -) - - - - -#Classement_Commandes_Ds_Arbre=('DIRECTORY', 'DISTRIBUTION', 'CORRELATION',) -#Classement_Commandes_Ds_Arbre=('DIRECTORY', 'PF_PARAMETERS', 'SIMULATION', 'DISTRIBUTION', 'N_1_GENERATORS', 'N_1_LINES', 'N_1_TRANSFORMERS', 'N_1_MOTORS','N_1_LOADS','CORRELATION',) -Classement_Commandes_Ds_Arbre=('DIRECTORY', 'PF_PARAMETERS', 'SIMULATION', 'DISTRIBUTION', 'CORRELATION') - -Ordre_Des_Commandes = ('DIRECTORY', 'PF_PARAMETERS', 'SIMULATION', 'DISTRIBUTION', 'N_1_GENERATORS', 'N_1_LINES', 'N_1_TRANSFORMERS', 'N_1_MOTORS','N_1_LOADS','CORRELATION') diff --git a/PSEN_Eficas/__init__.py b/PSEN_Eficas/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/PSEN_Eficas/com.py b/PSEN_Eficas/com.py deleted file mode 100644 index 77e9ec83..00000000 --- a/PSEN_Eficas/com.py +++ /dev/null @@ -1,607 +0,0 @@ -#!/usr/bin/python3 -######################################################################################################################## -# ojectif de ce module: extraire des donnes pour afficher dans l'interface Eficas. Subprocess dans la fonction PFExtractGeneratorLoadLineandTransfoDico -######################################################################################################################## -import pdb - -NoBreakersandSwitches = True - -NetworkFile = r'C:\Logiciels DER\PSEN_MERGED_V6\Example\Corse PF\Modele_Corse_PSEN_peak_good.pfd' -PF_PATH = r'C:\Program Files\DIgSILENT\PowerFactory 2016 SP2\Python\3.5' - -def PFExtractData(NetworkFile, PF_PATH): - #PSEN sous PowerFactory, extraire des donnees de Gen, Load, Bus, Branch, Transfos,Motor - import os - import sys - import numpy as np - - print (NetworkFile) - print (PF_PATH) - (filepath, filename) = os.path.split(NetworkFile) - sys.path.append(PF_PATH) - os.environ['PATH'] += ';' + os.path.dirname(os.path.dirname(PF_PATH)) + ';' - - import powerfactory - import powerfactory as pf - app = pf.GetApplication() - # app.Show() - user = app.GetCurrentUser() - ComImp = user.CreateObject('ComPFDIMPORT')# objet pour importer pfd file - - app.SetWriteCacheEnabled(1) # Disable consistency check - ComImp.g_file = NetworkFile - ComImp.g_target = user # project is imported under the user account - err = ComImp.Execute() # Execute command starts the import process - ComImp.Delete() - app.SetWriteCacheEnabled(0) # Enable consistency check - prjs = user.GetContents('*.IntPrj') - prjs.sort(key=lambda x: x.gnrl_modif, reverse=True) - #•pdb.set_trace() - prj = prjs[0] - prj.Activate() - studycase = app.GetActiveStudyCase() - grids = studycase.GetChildren(1, '*.ElmNet', 1)[0].contents - tous = [] - for grid in grids: - tous.extend(grid.obj_id.GetContents('*.ElmTerm', 1)) - bus = [] - for noeud in tous: - # if ((noeud.iUsage == 0) and (noeud.outserv == 0)): # eliminer tous les noeuds out-service - # if ((noeud.iUsage == 0)or(noeud.iUsage == 1)) : - bus.append(noeud) - noeuds = sorted(bus, key=lambda x: x.cStatName) - buses = [] - for ii in range(len(noeuds)): - busname = noeuds[ii].cStatName.replace('/','_').replace(')','_').replace('(','_').replace(" ","_").replace("-","_").replace(".","_").replace("&","and").replace("%","pct").replace("=","eq").replace("#","_").replace("$","_") - aa = [ii, noeuds[ii].uknom, busname, noeuds[ii].GetBusType()] - # [numero,nominal KV,busname] - buses.append(aa) - # ==============================================================# - # Loads data (busnumber, active, reactive, status, name, id) - tous = [] - for grid in grids: - tous.extend(grid.obj_id.GetContents( '*.ElmLod', 1)) - tous = sorted(tous, key=lambda x: x.bus1.cBusBar.cStatName) - LoadDico = {} - for bus in buses: - idload = 0 - for load in tous: - busname = load.bus1.cBusBar.cStatName - busname = busname.replace('/','_').replace(')','_').replace('(','_').replace(" ","_").replace("-","_").replace(".","_").replace("&","and").replace("%","pct").replace("=","eq").replace("#","_").replace("$","_") - if busname == bus[2]: - idload += 1 # cree id pour load - busnumber = bus[0] - loadname = busname - loadname = loadname.replace(" ", "_") - loadname = loadname.replace("-", "_") - loadname = loadname.replace(".", "_") - loadname = loadname.replace("/", "_") - loadname = loadname.replace("&", "and") - loadname = loadname.replace("%","pct") - loadname = loadname.replace("=","eq") - loadname = loadname.replace("#","_") - loadname = loadname.replace("$","_") - loadname = loadname.replace("\\","_") - loadname = loadname.replace("(","_") - loadname = loadname.replace(")","_") - try: - int(loadname[0]) - loadname = "C_" + loadname - except: - pass - loadname=loadname+'_Lo'+str(idload) - #p = load.plini #CM - #q = load.qlini #CM - p = load.plini_a - q = load.qlini_a - LoadDico[loadname] = {} - LoadDico[loadname]['NAME'] = load.loc_name.strip() - LoadDico[loadname]['ID'] = idload - LoadDico[loadname]['EXNAME'] = busname + '_' + str(bus[1])+'KV' - LoadDico[loadname]['NUMBER'] = busnumber - LoadDico[loadname]['P'] = p - LoadDico[loadname]['Q'] = q - # ==============================================================#Generator - MachineDico = {} # [Bus name, machine ID, extended bus name, bus number] - tous = [] - for grid in grids: - tous.extend(grid.obj_id.GetContents( '*.ElmSym', 1)) - - for plant in tous: - if plant.i_mot == 0: - busname = plant.bus1.cBusBar.cStatName - busname = busname.replace('/','_').replace(')','_').replace('(','_').replace(" ","_").replace("-","_").replace(".","_").replace("&","and").replace("%","pct").replace("=","eq").replace("#","_").replace("$","_") - for ii in range(len(buses)): - if busname in buses[ii]: - busnumber = ii - break - idplant = plant.loc_name#plant.ngnum -# p = plant.pgini #CM -# q = plant.qgini #CM - p = plant.pgini_a - q = plant.qgini_a - pmax = plant.Pmax_uc - pmin = plant.Pmin_uc - qmax = plant.cQ_max - qmin = plant.cQ_min - machinename = busname + '_' + 'syn_' + 'Gr_' + str(idplant) # generator synchrone - machinename = machinename.replace(" ", "_") - # machinename = machinename.replace("Generator", "gen") - machinename = machinename.replace("-", "_") - machinename = machinename.replace(".", "_") - machinename = machinename.replace("/", "_") - machinename = machinename.replace("&", "and") - machinename = machinename.replace("%","pct") - machinename = machinename.replace("=","eq") - machinename = machinename.replace("#","_") - machinename = machinename.replace("$","_") - machinename = machinename.replace("\\","_") - machinename = machinename.replace("(","_") - machinename = machinename.replace(")","_") - # machinename = machinename + '_' +'syn_' + 'Gr_' + str(idplant) # generator synchrone - try: - int(machinename[0]) - machinename = "G_" + machinename - except: - pass - - MachineDico[machinename] = {} - MachineDico[machinename]['NAME'] = plant.loc_name - MachineDico[machinename]['ID'] = idplant - MachineDico[machinename]['EXNAME'] = busname + '_' + str(bus[1])+'KV' - MachineDico[machinename]['NUMBER'] = busnumber - MachineDico[machinename]['P'] = p - MachineDico[machinename]['Q'] = q - MachineDico[machinename]['PMAX'] = pmax - MachineDico[machinename]['QMAX'] = qmax - MachineDico[machinename]['PMIN'] = pmin - MachineDico[machinename]['QMIN'] = qmin - tous = [] - for grid in grids: - tous.extend(grid.obj_id.GetContents( '*.ElmAsm', 1)) - - for plant in tous: - if plant.i_mot == 0: - busname = plant.bus1.cBusBar.cStatName - busname = busname.replace('/','_').replace(')','_').replace('(','_').replace(" ","_").replace("-","_").replace(".","_").replace("&","and").replace("%","pct").replace("=","eq").replace("#","_").replace("$","_") - for ii in range(len(buses)): - if busname in buses[ii]: - busnumber = ii - break - idplant = plant.loc_name -# p = plant.pgini #CM -# q = plant.qgini #CM - p = plant.pgini_a - q = plant.qgini_a - pmax = plant.Pmax_uc - pmin = plant.Pmin_uc - qmax = plant.cQ_max - qmin = plant.cQ_min - machinename = busname + '_' + 'asyn_' + 'Gr_' + str(idplant) # generator asynchrone - machinename = machinename.replace(" ", "_") - machinename = machinename.replace("-", "_") - machinename = machinename.replace(".", "_") - machinename = machinename.replace("/", "_") - machinename = machinename.replace("&", "and") - machinename = machinename.replace("%","pct") - machinename = machinename.replace("=","eq") - machinename = machinename.replace("#","_") - machinename = machinename.replace("$","_") - machinename = machinename.replace("\\","_") - machinename = machinename.replace("(","_") - machinename = machinename.replace(")","_") - # machinename = machinename + '_' +'asyn_' + 'Gr_' + str(idplant) # generator asynchrone - try: - int(machinename[0]) - machinename = "G_" + machinename - except: - pass - - MachineDico[machinename] = {} - MachineDico[machinename]['NAME'] = plant.loc_name - MachineDico[machinename]['ID'] = idplant - MachineDico[machinename]['EXNAME'] = busname + '_' + str(bus[1])+'KV' - MachineDico[machinename]['NUMBER'] = busnumber - MachineDico[machinename]['P'] = p - MachineDico[machinename]['Q'] = q - MachineDico[machinename]['PMAX'] = pmax - MachineDico[machinename]['QMAX'] = qmax - MachineDico[machinename]['PMIN'] = pmin - MachineDico[machinename]['QMIN'] = qmin - tous = [] - for grid in grids: - tous.extend(grid.obj_id.GetContents( '*.ElmGenstat', 1)) - for plant in tous: - busname = plant.bus1.cBusBar.cStatName - busname = busname.replace('/','_').replace(')','_').replace('(','_').replace(" ","_").replace("-","_").replace(".","_").replace("&","and").replace("%","pct").replace("=","eq").replace("#","_").replace("$","_") - for ii in range(len(buses)): - if busname in buses[ii]: - busnumber = ii - break - idplant = plant.loc_name -# p = plant.pgini #CM -# q = plant.qgini #CM - p = plant.pgini_a - q = plant.qgini_a - pmax = plant.Pmax_uc - pmin = plant.Pmin_uc - qmax = plant.cQ_max - qmin = plant.cQ_min - machinename = busname + '_' + 'genstat_' + 'Gr_' + str(idplant) # generator static - machinename = machinename.replace(" ", "_") - machinename = machinename.replace("-", "_") - machinename = machinename.replace(".", "_") - machinename = machinename.replace("/", "_") - machinename = machinename.replace("&", "and") - machinename = machinename.replace("%","pct") - machinename = machinename.replace("=","eq") - machinename = machinename.replace("#","_") - machinename = machinename.replace("$","_") - machinename = machinename.replace("\\","_") - machinename = machinename.replace("(","_") - machinename = machinename.replace(")","_") - - try: - int(machinename[0]) - machinename = "G_" + machinename - except: - pass - - MachineDico[machinename] = {} - MachineDico[machinename]['NAME'] = plant.loc_name - MachineDico[machinename]['ID'] = idplant - MachineDico[machinename]['EXNAME'] = busname + '_' + str(bus[1]) + 'KV' - MachineDico[machinename]['NUMBER'] = busnumber - MachineDico[machinename]['P'] = p - MachineDico[machinename]['Q'] = q - MachineDico[machinename]['PMAX'] = pmax - MachineDico[machinename]['QMAX'] = qmax - MachineDico[machinename]['PMIN'] = pmin - MachineDico[machinename]['QMIN'] = qmin - - tous = [] - for grid in grids: - tous.extend(grid.obj_id.GetContents( '*.ElmPvsys', 1)) - for plant in tous: - busname = plant.bus1.cBusBar.cStatName - busname = busname.replace('/','_').replace(')','_').replace('(','_').replace(" ","_").replace("-","_").replace(".","_").replace("&","and").replace("%","pct").replace("=","eq").replace("#","_").replace("$","_") - for ii in range(len(buses)): - if busname in buses[ii]: - busnumber = ii - break - idplant = plant.loc_name#plant.ngnum -# p = plant.pgini #CM -# q = plant.qgini #CM - p = plant.pgini_a - q = plant.qgini_a - pmax = plant.Pmax_uc - pmin = plant.Pmin_uc - qmax = plant.cQ_max - qmin = plant.cQ_min - machinename = busname + '_' + 'pv_' + 'Gr_' + str(idplant) # generator PV - machinename = machinename.replace(" ", "_") - machinename = machinename.replace("-", "_") - machinename = machinename.replace(".", "_") - machinename = machinename.replace("/", "_") - machinename = machinename.replace("&", "and") - machinename = machinename.replace("%","pct") - machinename = machinename.replace("=","eq") - machinename = machinename.replace("#","_") - machinename = machinename.replace("$","_") - machinename = machinename.replace("\\","_") - machinename = machinename.replace("(","_") - machinename = machinename.replace(")","_") - - try: - int(machinename[0]) - machinename = "G_" + machinename - except: - pass - - MachineDico[machinename] = {} - MachineDico[machinename]['NAME'] = plant.loc_name - MachineDico[machinename]['ID'] = idplant - MachineDico[machinename]['EXNAME'] = busname + '_' + str(bus[1]) + 'KV' - MachineDico[machinename]['NUMBER'] = busnumber - MachineDico[machinename]['P'] = p - MachineDico[machinename]['Q'] = q - MachineDico[machinename]['PMAX'] = pmax - MachineDico[machinename]['QMAX'] = qmax - MachineDico[machinename]['PMIN'] = pmin - MachineDico[machinename]['QMIN'] = qmin - # ==============================================================#Motor - - MotorDico = {} # [Bus name, machine ID, extended bus name, bus number] - tous = [] - for grid in grids: - tous.extend(grid.obj_id.GetContents( '*.ElmSym', 1)) - - for plant in tous: - if plant.i_mot == 1: - busname = plant.bus1.cBusBar.cStatName - for ii in range(len(buses)): - if busname in buses[ii]: - busnumber = ii - break - idplant = plant.loc_name#plant.ngnum -# p = plant.pgini #CM -# q = plant.qgini #CM - p = plant.pgini_a - q = plant.qgini_a - pmax = plant.Pmax_uc - pmin = plant.Pmin_uc - qmax = plant.cQ_max - qmin = plant.cQ_min - machinename = busname + '_' + 'syn_' + 'Mo_' + str(idplant) # Motor synchrone - machinename = machinename.replace(" ", "_") - machinename = machinename.replace("-", "_") - machinename = machinename.replace(".", "_") - machinename = machinename.replace("/", "_") - machinename = machinename.replace("&", "and") - machinename = machinename.replace("%","pct") - machinename = machinename.replace("=","eq") - machinename = machinename.replace("#","_") - machinename = machinename.replace("$","_") - machinename = machinename.replace("\\","_") - machinename = machinename.replace("(","_") - machinename = machinename.replace(")","_") - - try: - int(machinename[0]) - machinename = "M_" + machinename - except: - pass - MotorDico[machinename] = {} - MotorDico[machinename]['NAME'] = plant.loc_name - MotorDico[machinename]['ID'] = idplant - MotorDico[machinename]['EXNAME'] = busname + '_' + str(bus[1])+'KV' - MotorDico[machinename]['NUMBER'] = busnumber - MotorDico[machinename]['P'] = p - MotorDico[machinename]['Q'] = q - MotorDico[machinename]['PMAX'] = pmax - MotorDico[machinename]['QMAX'] = qmax - MotorDico[machinename]['PMIN'] = pmin - MotorDico[machinename]['QMIN'] = qmin - tous = [] - for grid in grids: - tous.extend(grid.obj_id.GetContents( '*.ElmAsm', 1)) - - for plant in tous: - if plant.i_mot == 1: - busname = plant.bus1.cBusBar.cStatName - busname = busname.replace('/','_').replace(')','_').replace('(','_').replace(" ","_").replace("-","_").replace(".","_").replace("&","and").replace("%","pct").replace("=","eq").replace("#","_").replace("$","_") - for ii in range(len(buses)): - if busname in buses[ii]: - busnumber = ii - break - idplant = plant.loc_name#plant.ngnum -# p = plant.pgini #CM -# q = plant.qgini #CM - p = plant.pgini_a - q = plant.qgini_a - # pmax = plant.Pmax_uc - pmax = plant.P_max - pmin = plant.Pmin_uc - qmax = plant.cQ_max - qmin = plant.cQ_min - machinename = busname + '_' + 'asyn_' + 'Mo_' + str(idplant) # moteur asynchrone - machinename = machinename.replace(" ", "_") - machinename = machinename.replace("-", "_") - machinename = machinename.replace(".", "_") - machinename = machinename.replace("/", "_") - machinename = machinename.replace("&", "and") - machinename = machinename.replace("%","pct") - machinename = machinename.replace("=","eq") - machinename = machinename.replace("#","_") - machinename = machinename.replace("$","_") - machinename = machinename.replace("\\","_") - machinename = machinename.replace("(","_") - machinename = machinename.replace(")","_") - - try: - int(machinename[0]) - machinename = "M_" + machinename - except: - pass - MotorDico[machinename] = {} - MotorDico[machinename]['NAME'] = plant.loc_name - MotorDico[machinename]['ID'] = idplant - MotorDico[machinename]['EXNAME'] = busname + '_' + str(bus[1]) + 'KV' - MotorDico[machinename]['NUMBER'] = busnumber - MotorDico[machinename]['P'] = p - MotorDico[machinename]['Q'] = q - MotorDico[machinename]['PMAX'] = pmax - MotorDico[machinename]['QMAX'] = qmax - MotorDico[machinename]['PMIN'] = pmin - MotorDico[machinename]['QMIN'] = qmin - # ==============================================================# - LineDico = {} # [linename, Bus name 1, Bus name 2, ID, extended bus name 1, extended bus name 2, bus number 1, bus number 2] - tous = [] - for grid in grids: - tous.extend(grid.obj_id.GetContents( '*.ElmLne', 1)) - for line in tous: - linename = line.loc_name - frombus_name = line.bus1.cBusBar.cStatName - frombus_name = frombus_name.replace('/','_').replace(')','_').replace('(','_').replace(" ","_").replace("-","_").replace(".","_").replace("&","and").replace("%","pct").replace("=","eq").replace("#","_").replace("$","_") - for ii in range(len(buses)): - if frombus_name in buses[ii]: - frombus_number = ii - frombus_KV=buses[ii][1] - break - tobus_name = line.bus2.cBusBar.cStatName - tobus_name = tobus_name.replace('/','_').replace(')','_').replace('(','_').replace(" ","_").replace("-","_").replace(".","_").replace("&","and").replace("%","pct").replace("=","eq").replace("#","_").replace("$","_") - for ii in range(len(buses)): - if tobus_name in buses[ii]: - tobus_number = ii - tobus_KV=buses[ii][1] - break - idline = line.loc_name#line.nlnum - linename=frombus_name+'_'+tobus_name+'_'+idline+'_Li' - linename = linename.replace(" ", "_") - linename = linename.replace("-", "_") - linename = linename.replace(".", "_") - linename = linename.replace("/", "_") - linename = linename.replace("&", "and") - linename = linename.replace("%","pct") - linename = linename.replace("=","eq") - linename = linename.replace("#","_") - linename = linename.replace("$","_") - linename = linename.replace("\\","_") - linename = linename.replace("(","_") - linename = linename.replace(")","_") - try: - int(linename[0]) - linename = "L_" + linename - except: - pass - if NoBreakersandSwitches: - LineDico[linename] = {} - LineDico[linename]['FROMNAME'] = frombus_name - LineDico[linename]['TONAME'] = tobus_name - LineDico[linename]['ID'] = idline - LineDico[linename]['FROMEXNAME'] = frombus_name+'_'+str(frombus_KV) - LineDico[linename]['TOEXNAME'] = tobus_name+'_'+str(tobus_KV) - LineDico[linename]['FROMNUMBER'] = frombus_number # il n'y a pas de bus number dans PowerFactory - LineDico[linename]['TONUMBER'] = tobus_number - - - print ("Read lines") - # Extract Transfos - TfoDico = {} # [tranlinename, Bus name 1, Bus name 2, machine ID, extended bus name 1, extended bus name 2, bus number 1, bus number 2] - tous = [] - for grid in grids: - tous.extend(grid.obj_id.GetContents( '*.ElmTr2', 1)) - - for tfo in tous: - # tfosname = tfo.loc_name - id_tfo=tfo.loc_name#tfo.ntnum - frombus_name=tfo.bushv.cBusBar.cStatName - tobus_name=tfo.buslv.cBusBar.cStatName - frombus_name = frombus_name.replace('/','_').replace(')','_').replace('(','_').replace(" ","_").replace("-","_").replace(".","_").replace("&","and").replace("%","pct").replace("=","eq").replace("#","_").replace("$","_") - tobus_name = tobus_name.replace('/','_').replace(')','_').replace('(','_').replace(" ","_").replace("-","_").replace(".","_").replace("&","and").replace("%","pct").replace("=","eq").replace("#","_").replace("$","_") - for ii in range(len(buses)): - if frombus_name in buses[ii]: - frombus_number = ii - frombus_KV=buses[ii][1] - break - for ii in range(len(buses)): - if tobus_name in buses[ii]: - tobus_number = ii - tobus_KV=buses[ii][1] - break - - tfoname = frombus_name+'_' +tobus_name+'_' + str(id_tfo)+'_'+'Tr' - tfoname = tfoname.replace(" ", "_") - tfoname = tfoname.replace("-", "_") - tfoname = tfoname.replace(".", "_") - tfoname = tfoname.replace("/", "_") - tfoname = tfoname.replace("&", "and") - tfoname = tfoname.replace("%","pct") - tfoname = tfoname.replace("=","eq") - tfoname = tfoname.replace("#","_") - tfoname = tfoname.replace("$","_") - tfoname = tfoname.replace("\\","_") - tfoname = tfoname.replace("(","_") - tfoname = tfoname.replace(")","_") - try: - int(tfoname[0]) - tfoname = "_" + tfoname - except: - pass - if NoBreakersandSwitches: - TfoDico[tfoname] = {} - TfoDico[tfoname]['FROMNAME'] = frombus_name - TfoDico[tfoname]['TONAME'] = tobus_name - TfoDico[tfoname]['ID'] = id_tfo - TfoDico[tfoname]['FROMEXNAME'] = frombus_name+'_'+str(frombus_KV) - TfoDico[tfoname]['TOEXNAME'] = tobus_name+str(tobus_KV) - TfoDico[tfoname]['FROMNUMBER'] = frombus_number # il n'y a pas de bus number dans PowerFactory - TfoDico[tfoname]['TONUMBER'] = tobus_number - TfoDico[tfoname]['#WIND'] = 2 - - # Extract 3 winding Transfos - tous = [] - for grid in grids: - tous.extend(grid.obj_id.GetContents( '*.ElmTr3', 1)) - for tfo in tous: - # tfosname = tfo.loc_name - id_tfo = tfo.loc_name#tfo.nt3nm - frombus_name = tfo.bushv.cBusBar.cStatName - tobus_name = tfo.busmv.cBusBar.cStatName - bus3 = tfo.buslv.cBusBar.cStatName - frombus_name = frombus_name.replace('/','_').replace(')','_').replace('(','_').replace(" ","_").replace("-","_").replace(".","_").replace("&","and").replace("%","pct").replace("=","eq").replace("#","_").replace("$","_") - tobus_name = tobus_name.replace('/','_').replace(')','_').replace('(','_').replace(" ","_").replace("-","_").replace(".","_").replace("&","and").replace("%","pct").replace("=","eq").replace("#","_").replace("$","_") - bus3 = bus3.replace('/','_').replace(')','_').replace('(','_').replace(" ","_").replace("-","_").replace(".","_").replace("&","and").replace("%","pct").replace("=","eq").replace("#","_").replace("$","_") - for ii in range(len(buses)): - if frombus_name in buses[ii]: - frombus_number = ii - frombus_KV=buses[ii][1] - break - for ii in range(len(buses)): - if tobus_name in buses[ii]: - tobus_number = ii - tobus_KV=buses[ii][1] - break - for ii in range(len(buses)): - if bus3 in buses[ii]: - bus3_number = ii - bus3_KV=buses[ii][1] - break - tfoname = frombus_name+ '_' + tobus_name + '_' +bus3+'_' + str(id_tfo)+'_'+ 'Tr3' - tfoname = tfoname.replace(" ", "_") - tfoname = tfoname.replace("-", "_") - tfoname = tfoname.replace(".", "_") - tfoname = tfoname.replace("/", "_") - tfoname = tfoname.replace("&", "and") - tfoname = tfoname.replace("%","pct") - tfoname = tfoname.replace("=","eq") - tfoname = tfoname.replace("#","_") - tfoname = tfoname.replace("$","_") - tfoname = tfoname.replace("\\","_") - tfoname = tfoname.replace("(","_") - tfoname = tfoname.replace(")","_") - try: - int(tfoname[0]) - tfoname = "_" + tfoname - except: - pass - if NoBreakersandSwitches: - TfoDico[tfoname] = {} - TfoDico[tfoname]['FROMNAME'] = frombus_name - TfoDico[tfoname]['TONAME'] = tobus_name - TfoDico[tfoname]['3NAME']= bus3 - TfoDico[tfoname]['ID'] = id_tfo - TfoDico[tfoname]['FROMEXNAME'] = frombus_name+'_'+str(frombus_KV) - TfoDico[tfoname]['TOEXNAME'] = tobus_name+'_'+str(tobus_KV) - TfoDico[tfoname]['3EXNAME']=bus3+'_'+str(bus3_KV) - TfoDico[tfoname]['FROMNUMBER'] = frombus_number # il n'y a pas de bus number dans PowerFactory - TfoDico[tfoname]['TONUMBER'] = tobus_number - TfoDico[tfoname]['3NUMBER'] = bus3_number - TfoDico[tfoname]['#WIND'] = 3 - - print ("Read 3-Winding Transfos") - prj.Delete() - - return MachineDico, LoadDico, LineDico, TfoDico, MotorDico -filer=open('temp.txt','r') -_path=[] -for line in filer: - _path.append(line) -filer.close() -pfd_file=_path[0].replace('\n','') -PF_path=_path[1].replace('\n','') - -MachineDico, LoadDico, LineDico, TransfoDico, MotorDico = PFExtractData(pfd_file,PF_path) -Data={} -Data['MachineDico']=MachineDico -Data['LoadDico']=LoadDico -Data['LineDico']=LineDico -Data['TransfoDico']=TransfoDico -Data['MotorDico']=MotorDico -# Data=[MachineDico, LoadDico, LineDico, TransfoDico, MotorDico] -import pickle -# print('=========='+str(pickle.HIGHEST_PROTOCOL)+'=========') -with open('Data_for_interface', 'wb') as fichier: - mon_pickler = pickle.Pickler(fichier,protocol=2) - mon_pickler.dump(Data) - diff --git a/PSEN_Eficas/configuration_PSEN.py b/PSEN_Eficas/configuration_PSEN.py deleted file mode 100755 index 4ab64b85..00000000 --- a/PSEN_Eficas/configuration_PSEN.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" - Ce module sert pour charger les paramètres de configuration d'EFICAS -""" -# Modules Python -from InterfaceQT4 import configuration -import os - - -class CONFIG(configuration.CONFIG_BASE): - - #----------------------------------- - def __init__(self,appli,repIni): - #----------------------------------- - - self.labels_user=['catalogues','lang'] - self.labels_eficas=['lang','rep_cata','catalogues'] - - configuration.CONFIG_BASE.__init__(self,appli,'.Eficas_monCode') - - -def make_config(appli,rep): - return CONFIG(appli,rep) - diff --git a/PSEN_Eficas/debugPFWrapper.py b/PSEN_Eficas/debugPFWrapper.py deleted file mode 100644 index 0712ed46..00000000 --- a/PSEN_Eficas/debugPFWrapper.py +++ /dev/null @@ -1,28 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Created on Thu Feb 9 14:57:43 2017 - -@author: j15773 -""" - -import sys,os -path1 = os.path.abspath(os.path.join(os.path.abspath(__file__), '../', '../', 'PSEN_Eficas', 'PSEN')) -sys.path.append(path1) -import PSENconfig -import subprocess -import PFWrapper - -filer = open('temp.txt', 'r') -_path = [] -for line in filer: - _path.append(line) -filer.close() - -Python3_path = _path[2].replace('\n', '') - -WrapperFilePath = os.path.join(path1, 'PFWrapper.py') -p = subprocess.Popen([Python3_path + '/python.exe', WrapperFilePath]) - -(out, err) = p.communicate() -print out -print err diff --git a/PSEN_Eficas/mesScripts.py b/PSEN_Eficas/mesScripts.py deleted file mode 100755 index 15f80ed6..00000000 --- a/PSEN_Eficas/mesScripts.py +++ /dev/null @@ -1,35 +0,0 @@ -def view_zone(listeparam) : - item=listeparam[0] - import visu_geom - visu_zone = visu_geom.VisuGeom(from_eficas=True, - eficas_item=item, - ligne_arbre=False) - visu_zone.visualize() - -def view_ligne_arbre(listeparam) : - item=listeparam[0] - import visu_geom - visu_arbre = visu_geom.VisuGeom(from_eficas=True, - eficas_item=item, - ligne_arbre=True) - visu_arbre.visualize() - -def import_zone(listeparam,appli) : - item=listeparam[0] - # simulation de la recuperation zone - #import eficasSalome - #eficasSalome.runEficas(code='MT',fichier='/home/I29518/test_zone.comm') - appli.viewmanager.handleOpen(fichier='/home/A96028/Install_EficasV1/EficasV1/MT/MT_include.comm') - -def import_zone2(listeparam,appli) : - editor=listeparam[0] - itemWidget=listeparam[1] - texte="sansnom=ZONE(NOEUDS=(_F(NOM='N1', X=0.0,), _F(NOM='N2', X=0.19,),), ELEMENTS=(_F(NOM='E1', DEBUT='N1', FIN='N2', RAFFINAGE='NON', MATERIAU=MAT_R01, SECTION_MASSE=_F(TYPE_SECTION='CONSTANTE', DIAM_EXTERN_DEBUT=0.1, DIAM_INTERN_DEBUT=0,), SECTION_RIGIDITE=_F(TYPE_SECTION='CONSTANTE', DIAM_EXTERN_DEBUT=0.1, DIAM_INTERN_DEBUT=0.0,),), _F(NOM='E2', DEBUT='N2', FIN='N3', RAFFINAGE='NON', MATERIAU=MAT_R01, SECTION_MASSE=_F(TYPE_SECTION='VARIABLE', DIAM_EXTERN_DEBUT=0.1, DIAM_INTERN_DEBUT=0, DIAM_EXTERN_SORTIE=0.2, DIAM_INTERN_SORTIE=0.0,), SECTION_RIGIDITE=_F(TYPE_SECTION='VARIABLE', DIAM_EXTERN_DEBUT=0.1, DIAM_INTERN_DEBUT=0.0, DIAM_EXTERN_SORTIE=0.2, DIAM_INTERN_SORTIE=0.0,),),),);" - editor.updateJdc(itemWidget,texte) - -def Source(): - print "jjjjjjjjjjjjjjjjjjj" - -dict_commandes={ - 'GENDOF':(Source,"Source",(),False,True,"affiche un message"), - } diff --git a/PSEN_Eficas/opsPSEN.py b/PSEN_Eficas/opsPSEN.py deleted file mode 100755 index ad26a261..00000000 --- a/PSEN_Eficas/opsPSEN.py +++ /dev/null @@ -1,111 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2013 EDF R&D -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# - -from ExtractGeneratorLoadLineandTransfoDico import ExtractGeneratorLoadLineandTransfoDico,PFExtractGeneratorLoadLineandTransfoDico -# from ExtractGeneratorLoadLineandTransfoDico import ExtractGeneratorLoadLineandTransfoDico - -def INCLUDE(self,PSSE_path,PSSPY_path,sav_file,**args): - """ - Fonction sd_prod pour la macro INCLUDE - """ - - if sav_file==None: return - reevalue=0 - listeADeTruire=[] - listeNouveau=[] - toClean=False - if hasattr(self,'fichier_ini'): - reevalue=1 - if self.fichier_ini == sav_file : return - self.fichier_ini=sav_file - if hasattr(self,'old_context_fichier_init' ): - toClean=True - for concept in self.old_context_fichier_init.values(): - #self.jdc.delete_concept(concept) - listeADeTruire.append(concept) - self.jdc_aux=None - self.contexte_fichier_init={} - #self.reevalue_sd_jdc() - self.jdc.reset_context() - - self.fichier_ini=sav_file - self.contexte_fichier_init = {} - self.fichier_unite = 999 - self.fichier_err = None - self.fichier_text="" - - unite = 999 - try : - print('before ExtractGeneratorLoadLineandTransfoDico') - MachineDico,LoadDico,LineDico,TransfoDico, MotorDico = ExtractGeneratorLoadLineandTransfoDico(sav_file,PSSE_path,PSSPY_path) - print('after extract') - except : - if self.jdc.appli is not None: - self.jdc.appli.affiche_alerte("Error", 'An error happened in ExtractGeneratorandLoadList execution ') - self.g_context = {} - self.etapes = [] - self.jdc_aux = None - self.fichier_err = str(exc) - self.contexte_fichier_init = {} - - - for nom in MachineDico.keys(): - self.fichier_text += "%s=MONGENER(ID='%s',);\n" % (nom, 'a') - listeNouveau.append(nom) - - for nom in LoadDico.keys(): - self.fichier_text += "%s=MACHARGE(ID='%s',);\n" % (nom, 'a') - listeNouveau.append(nom) - - for nom in LineDico.keys(): - self.fichier_text += "%s=MALIGNE(ID='%s',);\n" % (nom,'a') - listeNouveau.append(nom) - - for nom in TransfoDico.keys(): - self.fichier_text += "%s=MONTRANSFO(ID='%s',);\n" % (nom,'a') - listeNouveau.append(nom) - - for nom in MotorDico.keys(): - self.fichier_text += "%s=MONMOTEUR(ID='%s',);\n" % (nom,'a') - - import Extensions.jdc_include - self.JdC_aux = Extensions.jdc_include.JDC_CATA_INCLUDE(code='PSEN', execmodul=None) - self.make_contexte_include(None, self.fichier_text) - self.old_context_fichier_init = self.contexte_fichier_init - self.parent.record_unit(unite, self) - - self.jdc.MachineDico=MachineDico - self.jdc.LoadDico=LoadDico - self.jdc.LineDico=LineDico - self.jdc.TransfoDico=TransfoDico - self.jdc.MotorDico = MotorDico - - if toClean: - for concept in listeADeTruire : - if concept.nom not in listeNouveau: self.jdc.delete_concept(concept) - self.reevalue_sd_jdc() - -def INCLUDE_context(self,d): - """ - Fonction op_init pour macro INCLUDE - """ - for k,v in self.g_context.items(): - d[k]=v - diff --git a/PSEN_Eficas/opsPSEN_PF.py b/PSEN_Eficas/opsPSEN_PF.py deleted file mode 100644 index 269402b4..00000000 --- a/PSEN_Eficas/opsPSEN_PF.py +++ /dev/null @@ -1,112 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2013 EDF R&D -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# - -from ExtractGeneratorLoadLineandTransfoDico import PFExtractGeneratorLoadLineandTransfoDico - -def INCLUDE(self, PF_path, pfd_file,Python3_path, **args): - """ - Fonction sd_prod pour la macro INCLUDE - """ - - if pfd_file==None: return - reevalue=0 - listeADeTruire=[] - listeNouveau=[] - toClean=False - if hasattr(self,'fichier_ini'): - reevalue=1 - if self.fichier_ini == pfd_file : return - self.fichier_ini=pfd_file - if hasattr(self,'old_context_fichier_init' ): - toClean=True - for concept in self.old_context_fichier_init.values(): - #self.jdc.delete_concept(concept) - listeADeTruire.append(concept) - self.jdc_aux=None - self.contexte_fichier_init={} - #self.reevalue_sd_jdc() - self.jdc.reset_context() - - self.fichier_ini=pfd_file - self.contexte_fichier_init = {} - self.fichier_unite = 999 - self.fichier_err = None - self.fichier_text="" - - unite = 999 - - try: - print('before PFExtractGeneratorLoadLineandTransfoDico') - MachineDico, LoadDico, LineDico, TransfoDico, MotorDico = PFExtractGeneratorLoadLineandTransfoDico(pfd_file, PF_path,Python3_path) - - print('after extract') - except : - if self.jdc.appli is not None: - self.jdc.appli.affiche_alerte("Error", 'An error happened in ExtractGeneratorandLoadList execution ') - self.g_context = {} - self.etapes = [] - self.jdc_aux = None - self.fichier_err = str(exc) - self.contexte_fichier_init = {} - - - for nom in MachineDico.keys(): - self.fichier_text += "%s=MONGENER(ID='%s',);\n" % (nom, 'a') - listeNouveau.append(nom) - - for nom in LoadDico.keys(): - self.fichier_text += "%s=MACHARGE(ID='%s',);\n" % (nom, 'a') - listeNouveau.append(nom) - - for nom in LineDico.keys(): - self.fichier_text += "%s=MALIGNE(ID='%s',);\n" % (nom,'a') - listeNouveau.append(nom) - - for nom in TransfoDico.keys(): - self.fichier_text += "%s=MONTRANSFO(ID='%s',);\n" % (nom,'a') - listeNouveau.append(nom) - - for nom in MotorDico.keys(): - self.fichier_text += "%s=MONMOTEUR(ID='%s',);\n" % (nom,'a') - - import Extensions.jdc_include - self.JdC_aux = Extensions.jdc_include.JDC_CATA_INCLUDE(code='PSEN', execmodul=None) - self.make_contexte_include(None, self.fichier_text) - self.old_context_fichier_init = self.contexte_fichier_init - self.parent.record_unit(unite, self) - - self.jdc.MachineDico=MachineDico - self.jdc.LoadDico=LoadDico - self.jdc.LineDico=LineDico - self.jdc.TransfoDico=TransfoDico - self.jdc.MotorDico = MotorDico - - if toClean: - for concept in listeADeTruire : - if concept.nom not in listeNouveau: self.jdc.delete_concept(concept) - self.reevalue_sd_jdc() - -def INCLUDE_context(self,d): - """ - Fonction op_init pour macro INCLUDE - """ - for k,v in self.g_context.items(): - d[k]=v - diff --git a/PSEN_Eficas/prefs.py b/PSEN_Eficas/prefs.py deleted file mode 100755 index c19b171d..00000000 --- a/PSEN_Eficas/prefs.py +++ /dev/null @@ -1,22 +0,0 @@ -# Copyright (C) 2007-2012 EDF R&D -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -code="PSEN" -import sys, os -if os.path.dirname(os.path.abspath(__file__)) not in sys.path : - sys.path.insert(0,os.path.dirname(os.path.abspath(__file__))) diff --git a/PSEN_Eficas/prefs_PSEN.py b/PSEN_Eficas/prefs_PSEN.py deleted file mode 100755 index c9ab6fb0..00000000 --- a/PSEN_Eficas/prefs_PSEN.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== - -import os,sys -# repIni sert a localiser le fichier editeur.ini -# Obligatoire -repIni=os.path.dirname(os.path.abspath(__file__)) -INSTALLDIR=os.path.join(repIni,'..') -sys.path[:0]=[INSTALLDIR] - - -# lang indique la langue utilisee pour les chaines d'aide : fr ou ang -lang='en' #'fr' - -# Codage des strings qui accepte les accents (en remplacement de 'ascii') -encoding='iso-8859-1' -docPath=repIni - - -# -catalogues=( - ('PSEN', 'PSEN for PSSE', os.path.join(repIni, 'PSEN_Cata.py'), 'PSEN', 'python'), - ('PSEN','PSEN for PowerFactory',os.path.join(repIni,'PSEN_Cata_PF.py'),'PSEN','python'), - -) -#simpleClic=True -#nombreDeBoutonParLigne=2 diff --git a/PSEN_Eficas/properties.py b/PSEN_Eficas/properties.py deleted file mode 100755 index 1d328a46..00000000 --- a/PSEN_Eficas/properties.py +++ /dev/null @@ -1,24 +0,0 @@ -#@ MODIF properties Accas DATE 11/06/2008 AUTEUR aster M.ADMINISTRATEUR -# RESPONSABLE D6BHHHH J-P.LEFEBVRE -# ====================================================================== -# COPYRIGHT (C) 1991 - 2001 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# ====================================================================== -# IDENTIFICATION DU GESTIONNAIRE DE COMMANDE ACCAS A PARTIR -# DE LA VERSION DU CODE_ASTER ASSOCIE -#---------------------------------------------------------------------- -version = "1.2" -date = "25/05/2010" -exploit = False diff --git a/PSEN_Eficas/qtEficas_PSEN.py b/PSEN_Eficas/qtEficas_PSEN.py deleted file mode 100755 index a7d0489f..00000000 --- a/PSEN_Eficas/qtEficas_PSEN.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# Copyright (C) 2007-2012 EDF R&D -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -""" - Ce module sert a lancer EFICAS configure pour Code_Aster -""" -# Modules Python -# Modules Eficas - -import sys, os -# sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)),'..')) -# code="PSEN" -import sys, os -# if os.path.dirname(os.path.abspath(__file__)) not in sys.path : -# sys.path.insert(0,os.path.dirname(os.path.abspath(__file__))) -import prefs -# name='prefs_'+prefs.code -# __import__(name) -import prefs_PSEN - -#from PyQt4.QtCore import * - -from InterfaceQT4 import eficas_go - - -if __name__=='__main__': - eficas_go.lance_eficas(code=prefs.code) diff --git a/PSEN_Eficas/usrCmdPF.py b/PSEN_Eficas/usrCmdPF.py deleted file mode 100644 index cc039cd2..00000000 --- a/PSEN_Eficas/usrCmdPF.py +++ /dev/null @@ -1,29 +0,0 @@ -# -*- coding: cp1252 -*- -import sys -from tkinter import * -import os - - -def maFonction6(event): - quitting() - -def quitting(): - can1.delete(proceeding) - can1.create_text(200,50,font=('Fixedsys',12),text="If you want to quit press button again...") - Button(root,text="Stop Simulation",font=("Fixedsys"),command=really_quitting).grid(row=4,column=1,sticky=N,padx=5) - -def really_quitting(): - print ('quitting') - root.destroy() - -# création d'une instance de la classe TK, que l'on affecte à l'objet "root" -root = Tk() -root.title("PSEN - Processing...") -can1=Canvas(root,width=400,height=100,bg="light blue") -can1.grid(row=0,column=0,rowspan=10) - -proceeding=can1.create_text(200,50,font=('Fixedsys',12),text="Processing...") - -Button(root,text="Stop Simulation",font=("Fixedsys"),command=quitting).grid(row=4,column=1,sticky=N,padx=5) -root.bind("", maFonction6) # lettre q -root.mainloop() diff --git a/PSSE_PF_Eficas/PSEN b/PSSE_PF_Eficas/PSEN deleted file mode 160000 index 661f9cde..00000000 --- a/PSSE_PF_Eficas/PSEN +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 661f9cdeb9fd990499c7175cda68c99f5c4ae51e diff --git a/PSEN_Eficas/PSEN/OutLog.py b/PSSE_PF_Eficas/PSEN2/OutLog.py similarity index 100% rename from PSEN_Eficas/PSEN/OutLog.py rename to PSSE_PF_Eficas/PSEN2/OutLog.py diff --git a/PSEN_Eficas/PSEN/PFWrapper.py b/PSSE_PF_Eficas/PSEN2/PFWrapper.py similarity index 100% rename from PSEN_Eficas/PSEN/PFWrapper.py rename to PSSE_PF_Eficas/PSEN2/PFWrapper.py diff --git a/PSEN_Eficas/PSEN/PSENconfig.py b/PSSE_PF_Eficas/PSEN2/PSENconfig.py similarity index 100% rename from PSEN_Eficas/PSEN/PSENconfig.py rename to PSSE_PF_Eficas/PSEN2/PSENconfig.py diff --git a/PSEN_Eficas/PSEN/PSSEWrapper.py b/PSSE_PF_Eficas/PSEN2/PSSEWrapper.py old mode 100755 new mode 100644 similarity index 85% rename from PSEN_Eficas/PSEN/PSSEWrapper.py rename to PSSE_PF_Eficas/PSEN2/PSSEWrapper.py index 7f503a6f..590eecb7 --- a/PSEN_Eficas/PSEN/PSSEWrapper.py +++ b/PSSE_PF_Eficas/PSEN2/PSSEWrapper.py @@ -9,6 +9,7 @@ import os, random, sys import numpy as np import time #import gmtime, strftime, sleep from array import * + from support_functions import * import pdb import multiprocessing @@ -18,133 +19,125 @@ import shutil import csv InitializeDispatchGentoP0 = False -Debug = False #blocks multiprocessing - -DEWAinterfacebug = False -Year = 2030 -Version = 'V8' - -if DEWAinterfacebug: -# if Year==2026: -# import PSENconfig_Gens2026 as PSENconfig_Gens -# import PSENconfig_Loads2026 as PSENconfig_Loads -# elif Year==2030: -# import PSENconfig_Gens2030 as PSENconfig_Gens -# elif Year==2020: -# import PSENconfig_Gens2020 as PSENconfig_Gens -# elif Year==2018: -# import PSENconfig_Gens2018 as PSENconfig_Gens -# -# #→PSENconfig.Dico['SIMULATION']['MAX_CORES']=23 -# All_Gens = PSENconfig_Gens.Dico['DISTRIBUTIONGens']['Generator'] - - #add correct generators to lists - All_Gens = PSENconfig.MachineDico.keys() - DRRG1_Gens = [] - DRRG2_Gens = [] - DRRG3_Gens = [] - HCCP_Gens = [] - PV_Gens = [] - CSP_Gens = [] - for gen in All_Gens: - if gen[-2:]=='D2': - DRRG2_Gens.append(gen) - elif gen[-2:]=='D3': - DRRG3_Gens.append(gen) - elif gen[-2:]=='D1': - DRRG1_Gens.append(gen) - elif gen[0:5]=='HCCP_': - HCCP_Gens.append(gen) - elif gen.startswith('BLCK') or gen.startswith('IPP300') or gen.startswith('SOL') or gen.startswith('_200MW_'): - PV_Gens.append(gen) - elif gen.startswith('CSP_ST'): - CSP_Gens.append(gen) - - PSENconfig.Dico['DISTRIBUTIONDRRG_2']['Generator']=DRRG2_Gens - PSENconfig.Dico['DISTRIBUTIONDRRG_3']['Generator']=DRRG3_Gens - PSENconfig.Dico['DISTRIBUTIONDRRG_1']['Generator']=DRRG1_Gens - - PSENconfig.Dico['DISTRIBUTIONPV']['Generator']= PV_Gens - - if Year > 2021: - PSENconfig.Dico['DISTRIBUTIONCSP']['Generator']= CSP_Gens - - if Year > 2019: - PSENconfig.Dico['DISTRIBUTIONHCCP']['Generator']= HCCP_Gens - - if Year > 2022: - PSENconfig.Dico['DISTRIBUTIONHatta_Gen']['Generator']=['HATA_PUMP_1__GrG1', 'HATA_PUMP_2__GrG2'] - - PSENconfig.Dico['DISTRIBUTIONHatta_Pump']['Generator']=['HATA_PUMP_3__GrP1', 'HATA_PUMP_4__GrP2'] - - #add correct loads to list - All_Loads = PSENconfig.LoadDico.keys() - Loads = [] - CSP_aux_loads = [] - for load in All_Loads: - if load.endswith('__LoD'): - continue - elif load.endswith('__LoAX') and load.startswith('CSP_'): - CSP_aux_loads.append(load) - else: - Loads.append(load) - - if Year > 2021: - PSENconfig.Dico['DISTRIBUTIONCSP_AUX']['Load']= CSP_aux_loads - - PSENconfig.Dico['DISTRIBUTIONLoad']['Load']=Loads - -# PSENconfig.Dico['PSSE_PARAMETERS']['SpinningReserveID_1']= 1 -# PSENconfig.Dico['PSSE_PARAMETERS']['SpinningReserveID_2']= 2 +Debug = True #pour faire des tests +## ============================================================================================= +def function_callback(result): #define callback for a probabilistic study + output.extend(result[0]) + inputSamp.extend(result[1]) + Pmachine.extend(result[2]) +## ============================================================================================= +def callback_indices(indices): #define callback function for probabilistic study + Ind1.extend(indices[0]) + Ind2.extend(indices[1]) +## ============================================================================================= +def function_callback_psse(result): #define callback function for time study + #print(result) + output.extend(result[1]) + inputSamp.extend(result[0])#5]) + Pmachine.extend(result[2])#6]) - fileDico = os.path.join('C:\Logiciels DER','PSEN_MERGED_' + Version, 'Code\PSEN_Eficas\PSEN','PSENConfig_SAVE_' + str(Year) + '.py') - f = open( str(fileDico), 'wb') - f.write("Dico =" + str(PSENconfig.Dico) ) +def log(filename, text): + f=open(filename, 'a') + f.write(text) f.close() - - -if __name__ == '__main__': - + +## ============================================================================================= +def init_PSSEWrapper(): sys.path.append(PSENconfig.Dico['DIRECTORY']['PSSE_path']) os.environ['PATH'] = PSENconfig.Dico['DIRECTORY']['PSSE_path'] + ";"+ os.environ['PATH'] - import psspy - import pssarrays - import redirect - - -## cwd=os.getcwd() -## lastRep = cwd.split('/')[-1] -## if lastRep=='InterfaceQT4': -## cmd_Path=os.getcwd()+'..\PSEN\usrCmd.py' - - if Debug: cmd_Path=os.getcwd()+'\usrCmd.py' #lancement depuis pssewrapper.py #cmd_Path=os.getcwd()+'\PSEN\usrCmd.py' #lancement depuis qteficas_psen.py else: cmd_Path=os.path.join(os.path.dirname(os.path.abspath(__file__)),"usrCmd.py") ##cmd_Path=os.getcwd()+'\EficasV1\PSEN_Eficas\PSEN\usrCmd.py' #lancement avec le .bat + return cmd_Path +## ============================================================================================= +def init_PSSE(Paths): + ## Inititalisation de PSSE + import psspy + import pssarrays + import redirect + _i=psspy.getdefaultint() + _f=psspy.getdefaultreal() + _s=psspy.getdefaultchar() + redirect.psse2py() + psspy.psseinit(80000) + # Silent execution of PSSe + islct=6 # 6=no output; 1=standard + psspy.progress_output(islct) + + #read sav + psspy.case(Paths['sav_file']) + all_inputs_init=read_sav(Paths['sav_file']) -#=============================================================================== -# Recuperation donnees utilisateurs - User data -#=============================================================================== -# Lecture du fichier PSENConfig - > sauvegarde avec le nom en du - - - #extract laws from Eficas Output PSENconfig est le fichier qui continent le dico +## rappel sur la strucutre de item[] qui contient les elements reseau +# plants = all_inputs_init[3] +# for item in plants: +# bus = item[0] +# status = item[1] +# _id = item[2] +# pgen = item[3] +# qgen = item[4] +# mvabase = item [5] +# pmax = item[6] +# qmax = item[7] +# name = item[8] + if Debug: + print("all_inputs_init[][] = generateurs ", " init_PSSE") + for item in all_inputs_init[3]: + print(item[8]) + return all_inputs_init + +## ============================================================================================= +def read_PSENconfig(): + """" + Read the file PSENconfig + PSENconfig contains all the information about the element in the network and the user configuration + """ Paths = PSENconfig.Dico['DIRECTORY'] SimuParams = PSENconfig.Dico['SIMULATION'] PSSEParams = PSENconfig.Dico['PSSE_PARAMETERS'] + + # Probabilistic Study: central dispersion => Monte Carlo or LHS iterations + if SimuParams.has_key('NUMBER_PACKAGE'): + nb_fix = int(SimuParams['NUMBER_PACKAGE']) + elif SimuParams.has_key('CONVERGENCE'): + if SimuParams['CONVERGENCE']==1: + nb_fix=0 + else: + nb_fix=100 + print '\nALERT:\nConvergence not selected, and no number of packages chosen: default number= 100' + time.sleep(2) + #CHARGEMENT DE PSSE - LOADING OF PSSE +# pssFolder=str(Paths['PSSE_path']) ### ne semble pas etre utilise + os.environ['PATH'] += ';' + Paths['results_folder'] + os.chdir(Paths['results_folder']) + + if Debug: + print(Paths, SimuParams, PSSEParams, nb_fix, " Paths, SimuParams, PSSEParams, nb_fix", " read_PSENconfig()") + + return Paths, SimuParams, PSSEParams, nb_fix + +## ============================================================================================= +#### TEST A FAIRE : creer deux PSENConfig differents : 1 ou matrice de correlation presente et l'autre non pour voir si "Laws" correct +def read_laws(): + """ + si la loi = pdf_from_file ou time_serie_from_file : on va lire les donnees contenues dans le csv associe + et on met a jour le dictionnaire Laws[shortkey]['FileContents'] + + fonction a faire evoluer pour traiter toutes les lois de la meme maniere + """ + ## si la matrice de correlation existe, on lit l entete de la matrice et on cree une liste if PSENconfig.Dico.has_key('CORRELATION'): - LawNames = RemoveListfromString(PSENconfig.Dico['CORRELATION']['CorrelationMatrix'][0]) - - Laws = {} - NonActiveIndices = [] - TSindices = [] + LawNames = RemoveListfromString(PSENconfig.Dico['CORRELATION']['CorrelationMatrix'][0]) ## RemoveListfromString est def ds support_functions + Laws = {} ## contient l ensemble des distributions (copié depuis PSENconfig) + NonActiveIndices = [] ## comprendre ce que cela contient + TSindices = [] ## comprendre ce que cela contient for key in PSENconfig.Dico.keys(): if key[0:12] == 'DISTRIBUTION': shortkey = key[12:] @@ -174,12 +167,13 @@ if __name__ == '__main__': else: if PSENconfig.Dico.has_key('CORRELATION'): NonActiveIndices.append(LawNames.index(shortkey)) + if Debug: + print(Laws, TSindices, NonActiveIndices, LawNames) + + return Laws, TSindices, NonActiveIndices, LawNames +## ============================================================================================= - # Travail sur la Matrice de correlatin - # remplit CorrMatrix - # --> creation d un dictionnaire - # clef = matrice = la matrice entree par l utilisateur mois les laws non actives, et si timeserie on a juste 1 dans la diagonale - +def read_or_create_corrmatrix(LawNames, NonActiveIndices, TSindices): if PSENconfig.Dico.has_key('CORRELATION'): #Treat Correlation Matrix - eliminate non-activated laws CorrMatrix0 = {} @@ -197,8 +191,6 @@ if __name__ == '__main__': c2 = [] for ind, c_el in enumerate(c): if ind not in NonActiveIndices: - ## c2.append(c_el) - #if time series, don't correlate other laws with the value "1". if (ind not in TSindices) and (i not in TSindices): c2.append(c_el) @@ -207,13 +199,10 @@ if __name__ == '__main__': else: c2.append(0.) CMax.append(c2) - CorrMatrix0['matrix'] = np.array(CMax) CorrMatrix0['laws'] = LawNames2 else: #acceptable only if all active distributions are time series or if only 1 active distribution - # a supprimer - if len(Laws)==1: #create correlation matrix of 1 x 1 CorrMatrix0 = {} CorrMatrix0['matrix'] = np.array([[1]]) @@ -230,64 +219,17 @@ if __name__ == '__main__': else: print 'Error: Correlation matrix must be defined. Enter 0''s for correlations between laws and time series.' sys.exit(1) + + if Debug: + print(CorrMatrix0, " read_or_create_corrmatrix(LawNames, NonActiveIndices, TSindices)", " CorrMatrix0") + + return CorrMatrix0 - - #Duplicate Laws for cases where 1 law defined for multiple components and different sampling should be performed per component: - isDuplicateLaws = False - for law in Laws.keys(): - if Laws[law].has_key('Sampling'): #not a reserve constraint law - if 'One sample per ' in Laws[law]['Sampling']: - isDuplicateLaws = True - ComponentType = Laws[law]['ComponentType'] - ComponentList = Laws[law][ComponentType] - for component in ComponentList: - lawname = law + "_" + component - Laws[lawname]=Laws[law] #make a copy of the law - Laws[lawname][ComponentType]=[component] #apply law to only one component, not whole list - del Laws[law] - else: #one sample for all components defined by law or Reserve Constraint Law - i = CorrMatrix0['laws'].index(law) - if CorrMatrix0['matrix'][i][i] != 1: - print 'Error: Correlation must be 1 between law and itself for law with same sample for all components. (' + law + ')' - sys.exit(1) - #CorrMaxtrix0['matrix'][i][i] = 1 - - #retreat CorrelationMatrix - #if isDuplicateLaws: - # CorrMatrix = {} - # CorrMatrix['laws']=Laws.keys() - # CorrMatrix['matrix']=np.eye(len(Laws.keys())) - # for x,lawname1 in enumerate(Laws.keys()): - # for i,lawname1_0 in enumerate(CorrMatrix0['laws']): - # if lawname1_0 in lawname1: - # break - # for y, lawname2 in enumerate(Laws.keys()): - # for j,lawname2_0 in enumerate(CorrMatrix0['laws']): - # if lawname2_0 in lawname2: - # break - # if x!=y: - # CorrMatrix['matrix'][x][y] = CorrMatrix0['matrix'][i][j] - # CorrMatrix['matrix'][y][x] = CorrMatrix0['matrix'][j][i] - ## if i==j: - ## CorrMatrix['matrix'][x][y] = 0 - ## CorrMatrix['matrix'][y][x] = 0 - ## else: - ## CorrMatrix['matrix'][x][y] = CorrMatrix0['matrix'][i][j] - ## CorrMatrix['matrix'][y][x] = CorrMatrix0['matrix'][j][i] - #else: - # CorrMatrix = CorrMatrix0 - - CorrMatrix = CorrMatrix0 - - #retest for positive definiteness - #if not np.all(np.linalg.eigvals(CorrMatrix['matrix'])>0): - # print 'Error: Correlation matrix is not positive definite.' - # sys.exit(1) - - - #execution file name - exec_file="report.txt" - +## ============================================================================================= +def contingency(): + """ + utilise la fonction config_contingency() definie dans support_functions.py + """ # Treat Contingency Files enteres as CSVs LinesList = [] GeneratorsList = [] @@ -314,7 +256,6 @@ if __name__ == '__main__': try : continLines, continGroups, continTransfos, continLoads, continMotors, continVal, continProb = config_contingency(LinesList,GeneratorsList,TransformersList,LoadsList,MotorsList) except IOError : # Si le fichier n'est pas dans un bon format on traite l'exception - nb_lines=1 print 'Error with contingency input file' else : continLines, continGroups, continTransfos, continLoads, continMotors, continVal, continProb = config_contingency(LinesList,GeneratorsList,TransformersList,LoadsList,MotorsList) @@ -329,9 +270,15 @@ if __name__ == '__main__': folderN_1 = '1_' else : folderN_1 = '_' + + if Debug: + print(continLines, continGroups, continTransfos, continLoads, continMotors, continVal, continProb, N_1_fromFile, folderN_1, " continLines, continGroups, continTransfos, continLoads, continMotors, continVal, continProb, N_1_fromFile, folderN_1", " fonction : contingency()") + return continLines, continGroups, continTransfos, continLoads, continMotors, continVal, continProb, N_1_fromFile, folderN_1 +## =============================================================================================== - +def TS(CorrMatrix): # Definition des variables pour les series temporelles + # a passer en pandas ? time_serie_flag=[] time_serie_mat=[] @@ -372,80 +319,37 @@ if __name__ == '__main__': timeVect = range(1, N+1) time_serie_mat=zip(*time_serie_mat) + + if Debug: + print(time_serie_flag, time_serie_mat, time_serie_time, timeVect, " time_serie_flag, time_serie_mat, time_serie_time, timeVect", " fonction TS()") + + return time_serie_flag, time_serie_mat, time_serie_time, timeVect +## =============================================================================================== + + + +""" DEBUT DU MAIN """ +if __name__ == '__main__': -## # Probabilistic Study: central dispersion => Monte Carlo or LHS iterations -## try: -## nb_fix=int(SimuParams['NUMBER_PACKAGE']) -## if OPFParams['MVAR_COST']==False and N_1_fromFile==False and nb_fix==0: -## nb_fix=100 -## print '\nALERT:\nNo paramaters choosen to calculate convergence criteria.\nNo number of packages choosen: default number= 100' -## time.sleep(2) -## except: -## if OPFParams['MVAR_COST']==False and N_1_fromFile==False: -## nb_fix=100 -## print '\nALERT:\nNo paramaters choosen to calculate convergence criteria.\nNo number of packages choosen: default number= 100' -## time.sleep(2) -## else: -## nb_fix=0 - - - # Probabilistic Study: central dispersion => Monte Carlo or LHS iterations - if SimuParams.has_key('NUMBER_PACKAGE'): - nb_fix = int(SimuParams['NUMBER_PACKAGE']) - elif SimuParams.has_key('CONVERGENCE'): - if SimuParams['CONVERGENCE']==1: - nb_fix=0 - else: - nb_fix=100 - print '\nALERT:\nConvergence not selected, and no number of packages chosen: default number= 100' - time.sleep(2) - - - #Extension name for the folders and files - day=time.strftime("%Y%m%d", time.gmtime()) - hour=time.strftime("%Hh%Mm%S", time.gmtime()) - - #CHARGEMENT DE PSSE - LOADING OF PSSE - pssFolder=str(Paths['PSSE_path']) - os.environ['PATH'] += ';' + Paths['results_folder'] - os.chdir(Paths['results_folder']) - #os.remove('fort.2') - - _i=psspy.getdefaultint() - _f=psspy.getdefaultreal() - _s=psspy.getdefaultchar() - redirect.psse2py() - psspy.psseinit(80000) - - # Silent execution of PSSe - islct=6 # 6=no output; 1=standard - psspy.progress_output(islct) + cmd_Path = init_PSSEWrapper() + Paths, SimuParams, PSSEParams, nb_fix = read_PSENconfig() + all_inputs_init = init_PSSE(Paths) + log("report.txt", "Starting time: %f; Monte Carlo Size : %f; " % (time.clock(), SimuParams["SIZE_PACKAGE"])) + + Laws, TSindices, NonActiveIndices, LawNames = read_laws() + CorrMatrix = read_or_create_corrmatrix(LawNames, NonActiveIndices, TSindices) + + continLines, continGroups, continTransfos, continLoads, continMotors, continVal, continProb, N_1_fromFile, folderN_1 = contingency() + + time_serie_flag, time_serie_mat, time_serie_time, timeVect = TS(CorrMatrix) + + + exit() - # Enregistrement de l'heure de debut de simulation - f=open(exec_file, 'a') - start_time=time.clock() - f.write("Starting time: %f; Monte Carlo Size : %f; " % (start_time, SimuParams["SIZE_PACKAGE"])) - f.close() - #read sav - psspy.case(Paths['sav_file']) - all_inputs_init=read_sav(Paths['sav_file']) - -# plants = all_inputs_init[3] -# for item in plants: -# bus = item[0] -# status = item[1] -# _id = item[2] -# pgen = item[3] -# qgen = item[4] -# pmax = item[6] -# name = item[7] -# machine_type = item[11] -# print (bus, _id, machine_type) -# -# pdb.set_trace() + ## configuration de l opf dans psse if PSSEParams['ALGORITHM']=='Optimum Power Flow': #run OPF so that adjustable bus shunts are included psspy.produce_opf_log_file(1,r"""DETAIL""") TapChange = 1-int(PSSEParams['LOCK_TAPS']) #0 if locked, 1 if stepping @@ -494,19 +398,21 @@ if __name__ == '__main__': psspy.nopf(0,1) # Lancement OPF postOPFinitialization(Paths['sav_file'],all_inputs_init,AdjLoadTables,init_gen=True,init_bus=True,init_fxshnt=True,init_swshnt=True,init_load=True,init_P0=InitializeDispatchGentoP0) #print "OPF run" - - all_inputs_base=read_sav(Paths['sav_file']) - buses_base=all_inputs_base[0] - lines_base=all_inputs_base[1] - trans_base=all_inputs_base[2] - plants_base=all_inputs_base[3] - loads_base=all_inputs_base[4] - shunt_base=all_inputs_base[5] - motors_base=all_inputs_base[6] - trans3_base=all_inputs_base[7] - swshunt_base=all_inputs_base[8] - - + + all_inputs_after_OPF = read_sav(Paths['sav_file']) + +## est ce qu on recopie ? + buses_base=all_inputs_after_OPF[0] + lines_base=all_inputs_after_OPF[1] + trans_base=all_inputs_after_OPF[2] + plants_base=all_inputs_after_OPF[3] + loads_base=all_inputs_after_OPF[4] + shunt_base=all_inputs_after_OPF[5] + motors_base=all_inputs_after_OPF[6] + trans3_base=all_inputs_after_OPF[7] + swshunt_base=all_inputs_after_OPF[8] + + ## passer en pandas # Initialize size output sizeY0=len(plants_base) #np.matrix(plants_base).shape[0] sizeY1=len(buses_base) #np.matrix(buses_base).shape[0] @@ -520,7 +426,8 @@ if __name__ == '__main__': sizeY=[sizeY0,sizeY1,sizeY2,sizeY5,sizeY7,sizeY3,sizeY6,sizeY4,sizeY8] sizeOutput=sizeY2 - + ##################################################################################### + ## a mettre dans la partie "lecture des parametres" if SimuParams.has_key('MAX_CORES'): max_cores = SimuParams['MAX_CORES'] else: @@ -532,19 +439,25 @@ if __name__ == '__main__': if max_cores==1: print('Must use at least 2 cores for probabilistic simulation. MAX_CORES parameter set to 2.') max_cores=2 - num_cores=min(min(multiprocessing.cpu_count(),max_cores)-1, nb_fix) #Num cores + num_cores=min(min(multiprocessing.cpu_count(),max_cores)-1, nb_fix) #Num cores - print('Number of cores used: ' + str(num_cores + 1)) - else: - num_cores=min(multiprocessing.cpu_count(),max_cores) - NoMultiProcTS=False - if num_cores==1: - NoMultiProcTS = True - if Debug==True: - NoMultiProcTS = True - print('Number of cores used: ' + str(num_cores)) + print('Number of cores used: ' + str(num_cores + 1)) + ## a tester ( a prioiri on ne passe pas dans le else et donc on n'arrive pas à ne pas faire du multiprocessing) + ## on a decale le else sous le if : cela devrait fonctionner + else: + num_cores=min(multiprocessing.cpu_count(),max_cores) + NoMultiProcTS=False + if num_cores==1: + NoMultiProcTS = True + if Debug==True: + NoMultiProcTS = True + print('Number of cores used: ' + str(num_cores)) + #Extension name for the folders and files + day=time.strftime("%Y%m%d", time.gmtime()) + hour=time.strftime("%Hh%Mm%S", time.gmtime()) + # Initialize the big folder pathBigFolder = Paths['results_folder']+"/N"+folderN_1+day+"_"+hour if not os.path.exists(pathBigFolder): os.makedirs(pathBigFolder) @@ -555,9 +468,13 @@ if __name__ == '__main__': # Initialize a folder per core pathSmallFolder = pathBigFolder+'\package'+str(j)+"_N"+folderN_1+day+"_"+hour if not os.path.exists(pathSmallFolder): os.makedirs(pathSmallFolder) + ##################################################################################### - + ## ecriture des fichiers de sortie + ## a passer en pandas + + ## ecriture des entetes # Initialize the logger : write the headers entete = "" unit = "" @@ -612,6 +529,7 @@ if __name__ == '__main__': logCSVfilename=[] logCSVfilename_UC=[] + ## attention : on ecrit un fichier de sortie dans chaque sous dossier for i in range(num_cores): logCSVfilename.append(pathBigFolder+'/package'+str(i)+"_N"+folderN_1+day+ "_" + hour + "/simulationDClog_"+hour+".csv") # Name of the file : global variable logCSVfilename_UC.append(pathBigFolder+'/package'+str(i)+"_N"+folderN_1+day+ "_" + hour + "/simulationDClog_beforeUC_"+hour+".csv") # Name of the file : global variable @@ -735,7 +653,7 @@ if __name__ == '__main__': f.close() f2.close() - + ## faire le test avant l ecriture des deux fichiers if PSSEParams['ALGORITHM']=='Economic Dispatch and Power Flow': PSSEParams['MVAR_COST'] = False for filename in logCSVfilename_UC: @@ -752,6 +670,7 @@ if __name__ == '__main__': #Create dictionnary for different useful values to use psse function + ## ?? dico={'TStest':0,'Xt':[],'sizeY0':sizeY0,'sizeY1':sizeY1,'sizeY2':sizeY2,\ 'sizeY3':sizeY3,'sizeY4':sizeY4,'sizeY5':sizeY5,'sizeY6':sizeY6,'sizeY7':sizeY7,'sizeY8':sizeY8, 'sizeY':sizeY,\ 'folder':pathBigFolder,'folderN_1':folderN_1,\ @@ -762,7 +681,7 @@ if __name__ == '__main__': 'Lines':PSENconfig.LineDico,'Transformers':PSENconfig.TransfoDico,\ 'doc_base':'','continLines':continLines,'continTransfos':continTransfos,'timeVect':[],\ 'continGroups':continGroups,'continLoads':continLoads,'continMotors':continMotors,'continVal':continVal,'continProb':continProb,\ - 'N_1_fromFile': N_1_fromFile,'all_inputs_init':all_inputs_init, 'AdjLoadTables':AdjLoadTables, 'Paths':Paths} + 'N_1_fromFile': N_1_fromFile,'all_inputs_init':all_inputs_after_OPF, 'AdjLoadTables':AdjLoadTables, 'Paths':Paths} if PSSEParams["ALGORITHM"]=="Optimum Power Flow": dico['flag2']=int(PSSEParams['MVAR_COST']) diff --git a/PSEN_Eficas/PSEN/__init__.py b/PSSE_PF_Eficas/PSEN2/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from PSEN_Eficas/PSEN/__init__.py rename to PSSE_PF_Eficas/PSEN2/__init__.py diff --git a/PSEN_Eficas/PSEN/comfile.py b/PSSE_PF_Eficas/PSEN2/comfile.py similarity index 100% rename from PSEN_Eficas/PSEN/comfile.py rename to PSSE_PF_Eficas/PSEN2/comfile.py diff --git a/PSEN_Eficas/PSEN/correct_comtask.py b/PSSE_PF_Eficas/PSEN2/correct_comtask.py similarity index 100% rename from PSEN_Eficas/PSEN/correct_comtask.py rename to PSSE_PF_Eficas/PSEN2/correct_comtask.py diff --git a/PSEN_Eficas/PSEN/ecd.py b/PSSE_PF_Eficas/PSEN2/ecd.py similarity index 100% rename from PSEN_Eficas/PSEN/ecd.py rename to PSSE_PF_Eficas/PSEN2/ecd.py diff --git a/PSEN_Eficas/PSEN/read_pfd_wrapper.py b/PSSE_PF_Eficas/PSEN2/read_pfd_wrapper.py similarity index 100% rename from PSEN_Eficas/PSEN/read_pfd_wrapper.py rename to PSSE_PF_Eficas/PSEN2/read_pfd_wrapper.py diff --git a/PSEN_Eficas/PSEN/run_in_PFfunction.py b/PSSE_PF_Eficas/PSEN2/run_in_PFfunction.py similarity index 100% rename from PSEN_Eficas/PSEN/run_in_PFfunction.py rename to PSSE_PF_Eficas/PSEN2/run_in_PFfunction.py diff --git a/PSEN_Eficas/PSEN/runreadOPF.py b/PSSE_PF_Eficas/PSEN2/runreadOPF.py similarity index 100% rename from PSEN_Eficas/PSEN/runreadOPF.py rename to PSSE_PF_Eficas/PSEN2/runreadOPF.py diff --git a/PSEN_Eficas/PSEN/support_functions.py b/PSSE_PF_Eficas/PSEN2/support_functions.py old mode 100755 new mode 100644 similarity index 97% rename from PSEN_Eficas/PSEN/support_functions.py rename to PSSE_PF_Eficas/PSEN2/support_functions.py index 48c8b7a0..11982fb1 --- a/PSEN_Eficas/PSEN/support_functions.py +++ b/PSSE_PF_Eficas/PSEN2/support_functions.py @@ -1,3132 +1,3132 @@ -# -*- coding: utf-8 -*- -""" -Created on Mon Jun 03 15:31:42 2013 - -@author: B31272 - -Fonctions de support -""" -import os,sys,random,string -import PSENconfig -sys.path.append(PSENconfig.Dico['DIRECTORY']['PSSPY_path']) -os.environ['PATH'] = PSENconfig.Dico['DIRECTORY']['PSSE_path'] + ";"+ os.environ['PATH'] -import psspy -import pssarrays -import redirect - - -import pdb -import numpy as np -from math import * -from decimal import * -from openturns import * -from time import sleep, strftime, gmtime -import multiprocessing -from threading import Thread -from Queue import Queue, Empty - -Debug = False #debug mode for PSSEFunct -Disconnect_RES = False #disconnect renewable generators when generate 0 MW -DEWA_PV_Qlimits = True #lower Q limits when P of renewable generators is < 0.2 Pmax -ReserveCorrection = True #add Pmin to units that are necessary to satisfy reserve requirements so that they are not disconnected after unit commitment -DisconnectThreshhold = 0.10 #seuil en per unit de la puissance active en dessous duquel on deconnecte des generateurs pour qu'ils ne participent ni à la reserve ni à la compensation reactive. -#=============================================================================== -# DEFINITION DES FONCTIONS - CREATION OF THE FUNCTIONS -#=============================================================================== - - -#read a ROP file containing all opf data -def readOPFdata(RopFile): - - fo = open(RopFile, 'r') - Lines = fo.readlines() - fo.close() - - for i,line in enumerate(Lines): - if 'begin Generator Dispatch data' in line: - startgendisp = i+1 - if 'End of Generator Dispatch data' in line: - endgendisp = i - if 'begin Active Power Dispatch Tables' in line: - startdisptable = i+1 - if 'End of Active Power Dispatch Tables' in line: - enddisptable = i - if 'begin Piece-wise Linear Cost Tables' in line: - startlincosttable = i+1 - if 'End of Piece-wise Linear Cost Tables' in line: - endlincosttable = i - if 'begin Piece-wise Quadratic Cost Tables' in line: - startquadcosttable = i+1 - if 'End of Piece-wise Quadratic Cost Tables' in line: - endquadcosttable = i - if 'begin Polynomial Cost Tables' in line: - startpolycosttable = i+1 - if 'End of Polynomial Cost Tables' in line: - endpolycosttable = i - if 'begin Generation Reserve data' in line: - startgenreservedata = i+1 - if 'End of Generation Reserve data' in line: - endgenreservedata = i - if 'begin Period Reserve data' in line: - startperiodreservedata = i+1 - if 'end of period reserve' in line.lower(): - endperiodreservedata = i - if 'begin Adjustable Bus Shunt data' in line: - startadjbusshuntdata = i+1 - if 'End of Adjustable Bus Shunt data' in line: - endadjbusshuntdata = i - if 'begin Adjustable Bus Load Tables' in line: - startadjloadtable = i+1 - if 'End of Adjustable Bus Load Tables' in line: - endadjloadtable = i - - - GenDispatchData = [] - for i in range(startgendisp,endgendisp): - data = Lines[i].split() - busNum = int(data[0]) - ID = data[1] - dispatch = float(data[2]) - dispTable = int(data[3]) - GenDispatchData.append([busNum,ID,dispatch, dispTable]) - - DispTableData = [] - for i in range(startdisptable,enddisptable): - data = Lines[i].split() - DispTable = int(data[0]) - Pmax = float(data[1]) - Pmin = float(data[2]) - FuelCostScaleCoef = float(data[3]) - CurveType = int(data[4]) #2 = piece wise linear, - Status = int(data[5]) - CostTable = int(data[6]) - DispTableData.append([DispTable,Pmax,Pmin,FuelCostScaleCoef,CurveType,Status,CostTable]) - - LinCostTables = [] - i = startlincosttable - while i >= startlincosttable and i < endlincosttable: - headerdata = Lines[i].split() - CostTable = int(headerdata[0]) - #tableName = str(headerdata[1]) - numpoints = int(headerdata[-1]) - points=[] - i+=1 - for k in range(numpoints): - #pdb.set_trace() - pointdata = Lines[i+k].split() - x =float(pointdata[0]) - y =float(pointdata[1]) - points.append([x,y]) - i+=numpoints - LinCostTables.append([CostTable, numpoints, points]) - - QuadCostTables = [] - PolyCostTables = [] - - GenReserveData = [] - for i in range(startgenreservedata,endgenreservedata): - data = Lines[i].split() - busNum = int(data[0]) - ID = data[1] - ramp =float(data[2]) - Pmax = float(data[3]) - GenReserveData.append([busNum, ID, ramp, Pmax]) - - PeriodReserveData = [] - for i in range(startperiodreservedata,endperiodreservedata): - data = Lines[i].split() - if len(data)==4: - ResNum = int(data[0]) - ResLevel = float(data[1]) - ResPeriod = float(data[2]) - InService = int(data[3]) - ParticipatingUnits = [] - elif len(data)==2: - busNum = int(data[0]) - ID = data[1] - ParticipatingUnits.append([busNum,ID]) - elif 'End of Participating Reserve Units' in Lines[i]: - PeriodReserveData.append([ResNum,ResLevel,ResPeriod,InService,ParticipatingUnits]) - else: - pass - - AdjBusShuntData = [] - for i in range(startadjbusshuntdata,endadjbusshuntdata): - data = Lines[i].split() - busNum = int(data[0]) - ID = data[1] - SuscInit = float(data[2]) - SuscMax = float(data[3]) - SuscMin = float(data[4]) - CostScale = float(data[5]) - InService = int(data[6]) - AdjBusShuntData.append([busNum,ID, SuscInit,SuscMax,SuscMin,CostScale,InService]) - - AdjLoadTables = [] - for i in range(startadjloadtable,endadjloadtable): - data = Lines[i].split() - tableNum = int(data[0]) - LoadMult = float(data[1]) - Max = float(data[2]) - Min = float(data[3]) - CostScale = float(data[7]) - InService = int(data[9]) - AdjLoadTables.append([tableNum,LoadMult,Max,Min,CostScale,InService]) - - return GenDispatchData, DispTableData, LinCostTables, QuadCostTables, PolyCostTables, GenReserveData, PeriodReserveData, AdjBusShuntData, AdjLoadTables - - -#to remve a list from a string "['wind 1', 'wind 2', 'charge']" --> ['wind 1', 'wind 2', 'charge'] -def RemoveListfromString(List): - List = List.replace("]","") - List = List.replace("[","") - List = List.replace(")","") - List = List.replace("(","") - List = List.replace("'","") - List = List.replace('"',"") - List = List.replace(" ","") - List = List.split(",") - return List - -def RemoveTuplesfromString(TList): - TL = RemoveListfromString(TList) - nTL = [] - for i in range(len(TL)/2): - nTL.append([TL[2*i],float(TL[2*i+1])]) - return nTL - -###Fonction de transfert vent-puissance d'une eolienne -##def eol_old(wind, WTconfig): -## Vcin = WTconfig ['cutinWS'] -## Vrate = WTconfig ['ratedWS'] -## Vcout = WTconfig ['cutoutWS'] -## Rho = WTconfig ['rho'] -## lossrate = WTconfig ['lossrate'] -## if wind <= Vcin : -## Pnorm=0 -## elif wind < Vrate : -## Pnorm=wind*(1-lossrate)#((wind**2-Vcin**2)/(Vrate**2-Vcin**2)*Rho/1.225*(1-lossrate)) -## elif wind < Vcout : -## Pnorm = 1*(1-lossrate) -## else : -## Pnorm=0 -## return Pnorm - -def applyTF(x_in, TF): - - X = [] - P = [] - for (x,p) in TF: - X.append(x) - P.append(p) - - - Pmax=max(P) - precision = 0.001 - #calculate precision of values entered - for i in range(len(X)): - d1 = Decimal(str(X[i])) - d2 = Decimal(str(P[i])) - d1expo = d1.as_tuple().exponent - d2expo = d2.as_tuple().exponent - expo = np.minimum(d1expo,d2expo) - precision = min(10**(expo-1),precision) - - - #change to array type for consistency - X = np.array(X) - P = np.array(P) - - #interpolate between values so that precise wind speed data doesnt output heavily discretized power levels - from scipy import interpolate - finterp = interpolate.interp1d(X,P, kind='linear') - Xmin = min(X) - Xmax = max(X) - Xnew = np.arange(Xmin,Xmax,precision) - Pnew = finterp(Xnew) - - #calculate power by applying transfer function - if x_in >= Xmax-precision: - index = len(Pnew)-1 - elif x_in <= Xmin + precision: - index = 0 - else: - index = int(round((x_in-Xmin)/precision)) - Power = Pnew[index] - - PowerNorm = Power/Pmax #normalize - - return PowerNorm - - - -def eol(WS, z_WS, pathWT, HH, alpha=1./7, PercentLoss = 5): - - ''' - - Reconstitute wind production from wind speed histories for a single site. - - syntax: - ACPower = ReconstituteWind(WS, z_WS, pathWT, N_turbines, HH, alpha=1./7, PercentLoss=5) - - inputs: - WS: numpy array of wind speed measurements to be converted to production values - z_WS: height, in meters above ground level, of the wind speed measurements - pathWT: location of selected wind turbine technology's power curve file in computer file system - N_turbines: number of wind turbines in the installation/farm being modelled - HH: wind turbine hub height - alpha (optional, default = 1/7): exponential factor describing the vertical wind profile; used to extrapolate - wind data to hub height. Can be scalar or vector with same length as wind data. - PercentLoss (optional, default = 5): percent loss due to multiple effects: the wake effect of adjacent wind turbines, - cable resistance between wind turbine/farm and injection point, grid and turbine unavailability, extreme weather conditions, etc. -. - - outputs: - ACPower: numpy array of normalized expected wind production for the given wind farm. - - ''' - - - #open and treat wind turbine data in .pow file - f = open(pathWT) - lines = f.readlines() - WTdata = {} - WTdata["model"] = lines[0][1:-2] - WTdata['diameter'] = float(lines[1][1:-2]) - WTdata['CutInWindSpeed'] = float(lines[4][1:-2]) - WTdata['CutOutWindSpeed'] = float(lines[3][1:-2]) - WTdata['PowerCurve'] = {} - WTdata['PowerCurve']['WindSpeed'] = np.arange(0, 31) - WTdata['PowerCurve']['Power'] = [float(0)] #in kW - for i in range(5,35): - WTdata['PowerCurve']['Power'].append(float(lines[i][1:-2])) - - WTdata['Pmax']=max(WTdata['PowerCurve']['Power']) - - #insert WT hub height - WTdata['z'] = HH - - #correct wind speed values for appropriate height - WS_hh = WS*(WTdata['z']/z_WS)**alpha #wind speed at hub height - - #calculate precision of cut in and cut out windspeeds - d1 = Decimal(str(WTdata['CutInWindSpeed'])) - d2 = Decimal(str(WTdata['CutOutWindSpeed'])) - expo = np.minimum(d1.as_tuple().exponent, d2.as_tuple().exponent) - precision = 10**(expo-1) - - #insert points for cut-in and cut-out wind speeds - add_ci = 0 - add_co= 0 - if np.mod(WTdata['CutInWindSpeed'],1)==0: - add_ci = precision - if np.mod(WTdata['CutOutWindSpeed'],1)==0: - add_co = precision - i_cutin = np.where(WTdata['PowerCurve']['WindSpeed']>(WTdata['CutInWindSpeed']+add_ci))[0][0] - i_cutout = np.where(WTdata['PowerCurve']['WindSpeed']>(WTdata['CutOutWindSpeed']+add_co))[0][0] + 1 #+1 to account for addition of cut in point - WTdata['PowerCurve']['WindSpeed'] = list(WTdata['PowerCurve']['WindSpeed']) - WTdata['PowerCurve']['WindSpeed'].insert(i_cutin, WTdata['CutInWindSpeed']+add_ci) - WTdata['PowerCurve']['WindSpeed'].insert(i_cutout, WTdata['CutOutWindSpeed']+add_co) - WTdata['PowerCurve']['Power'].insert(i_cutin, 0) - WTdata['PowerCurve']['Power'].insert(i_cutout, 0) - - #change to array type for consistency - WTdata['PowerCurve']['WindSpeed'] = np.array(WTdata['PowerCurve']['WindSpeed']) - WTdata['PowerCurve']['Power'] = np.array(WTdata['PowerCurve']['Power']) - - #interpolate between values so that precise wind speed data doesnt output heavily discretized power levels - from scipy import interpolate - finterp = interpolate.interp1d(WTdata['PowerCurve']['WindSpeed'],WTdata['PowerCurve']['Power'], kind='linear') - Vnew = np.arange(0,30,precision) - Pnew = finterp(Vnew) - - #calculate power produced by turbine in function of wind speed - Pac_turbine = [] - for i, ws in enumerate(WS_hh): - if ws >= 30-precision: - index = len(Pnew)-1 - else: - index = int(round(ws/precision)) #index of correct wind speed - Pac_turbine.append(Pnew[index]) #Power corresponds to value with same index as wind speed vector - Pac_turbine = np.array(Pac_turbine) - - #account for Losses...currently a single loss factor but could imagine implementing a per-point method - #WakeEffects = 4 #3-8% for a typical farm, 0% for an individual windmill - #CableResistanceLosses = 1 #1-3% between windmills and electric counter, depending on voltage levels and cable length - #GridUnavalability = 1 - #WTUnavailability = 3 - #AcousticCurtailment = 1-4 - #Freezing = 0.5 - #LF = (1-WakeEffects/100)*(1-CableResistanceLosses/100) #loss factor - ACPower = Pac_turbine*(1-PercentLoss/100) #total AC power produced by wind turbine - ACPowerNorm = ACPower/WTdata['Pmax'] - return ACPowerNorm - -def postOPFinitialization(sav_file,all_inputs_init,AdjLoadTables,init_gen=True,init_bus=True,init_fxshnt=True,init_swshnt=True,init_load=True,init_P0=False): - - psspy.save(sav_file) - - buses_init=all_inputs_init[0] - lines_init=all_inputs_init[1] - trans_init=all_inputs_init[2] - plants_init=all_inputs_init[3] - loads_init=all_inputs_init[4] - shunt_init=all_inputs_init[5] - motors_init=all_inputs_init[6] - trans3_init=all_inputs_init[7] - swshunt_init=all_inputs_init[8] - - all_inputs_base=read_sav(sav_file) - buses_base=all_inputs_base[0] - lines_base=all_inputs_base[1] - trans_base=all_inputs_base[2] - plants_base=all_inputs_base[3] - loads_base=all_inputs_base[4] - shunt_base=all_inputs_base[5] - motors_base=all_inputs_base[6] - trans3_base=all_inputs_base[7] - swshunt_base=all_inputs_base[8] - - _i=psspy.getdefaultint() - _f=psspy.getdefaultreal() - _s=psspy.getdefaultchar() - - #re-initialize generators to original value - if init_gen: - for plant in plants_init: - busNum = plant[0] - ID = plant[2] - P = plant[3] - Q = plant[4] - psspy.machine_chng_2(busNum,ID,[_i,_i,_i,_i,_i,_i],\ - [P, Q,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) - - #re-initialize voltages and angles - if init_bus: - for bus in buses_init: - busNum = bus[0] - Upu = bus[2] - angleDegrees = bus[7] - psspy.bus_chng_3(busNum,[_i,_i,_i,_i],[_f,Upu,angleDegrees,_f,_f,_f,_f],_s) - - #re-initialize fixed shunts to original value - if init_fxshnt: - for shunt in shunt_base: - sh_init = next((sh for sh in shunt_init if (sh[0] == shunt[0]) and sh[5]==shunt[5]),'not found') - if sh_init == 'not found': #this means the added shunt is an adjustable bus shunt with no existing shunt at the same bus - #initialize the fixed shunt to 0 - ID = shunt[5] #(ID always == 1) - busNum = shunt[0] - Qnom = 0 - psspy.shunt_chng(busNum,ID,_i,[_f, Qnom]) - else: #this shunt already existed in initial saved case file, re-initialize to initial value - ID = sh_init[5] - busNum = sh_init[0] - Q = sh_init[2] - Qnom = sh_init[4] - psspy.shunt_chng(busNum,ID,_i,[_f, Qnom]) - - #re-initialize switched shunts to original values - if init_swshnt: - for swshunt in swshunt_init: - busNum = swshunt[0] - Q = swshunt[2] - Qnom = swshunt[4] - psspy.switched_shunt_chng_3(busNum,[_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i],[_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,Qnom,_f],"") - - #re-initialize loads to original values - if init_load: - # for load in loads_init: - # busNum = load[0] - # ID = load[5] - # P = load[1] - # Q = load[2] - # psspy.load_chng_4(busNum,ID,[_i,_i,_i,_i,_i,_i],[P, Q,_f,_f,_f,_f]) - for table in AdjLoadTables: - tableNum = table[0] - LoadMult = table[1] - psspy.opf_adjload_tbl(tableNum,[_i,_i,_i],[LoadMult,_f,_f,_f,_f,_f,_f]) - - #initialize dispatchable generators to P = 0 - if init_P0: - for gen in GenDispatchData: - busNum = gen[0] - ID = gen[1] - dispatch = gen[2] - if dispatch>0: - P=0 - psspy.machine_chng_2(busNum,ID,[_i,_i,_i,_i,_i,_i],\ - [P,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) - - ##save changes - psspy.save(sav_file) - - return - - -#Fonction permettant de lire les donnees qui nous interessent et de les mettre dans une matrice -def read_sav(doc): - psspy.case(doc) - # Select what to report - if psspy.bsysisdef(0): - sid = 0 - else: # Select subsytem with all buses - sid = -1 - - flag_bus = 2 #all buses 1 # in-service - flag_plant = 4 #all machines - flag_load = 4 #all loads 1 # in-service - flag_motor = 4 #all motors 1 # in-service - flag_swsh = 4 #all fixed shunts 1 # in-service - flag_brflow = 1 # in-service - owner_brflow = 1 # bus, ignored if sid is -ve - ties_brflow = 5 # ignored if sid is -ve - entry = 1 # gives a single entry (each branch once) - - #Bus data (number, basekV, pu, name, ...) : PSSe has 3 functions one for integer data, one for real data and one for strings - istrings = ['number'] - ierr, idata = psspy.abusint(sid, flag_bus, istrings) - buses=idata - - rstrings = ['base','pu'] - ierr, rdata = psspy.abusreal(sid, flag_bus, rstrings) - buses.append(rdata[0]) - buses.append(rdata[1]) - - cstrings = ['name'] - ierr, cdata = psspy.abuschar(sid, flag_bus, cstrings) - cdata[0]=map( lambda s: s.replace("\n"," "),cdata[0]) - buses.append(cdata[0]) - - rstrings = ['nvlmlo','nvlmhi'] - ierr, rdata = psspy.abusreal(sid, flag_bus, rstrings) - buses.append(rdata[0]) - buses.append(rdata[1]) - - istrings = ['type'] - ierr, idata = psspy.abusint(sid, flag_bus, istrings) - buses.append(idata[0]) - - rstrings = ['angled'] - ierr, rdata = psspy.abusreal(sid, flag_bus, rstrings) - buses.append(rdata[0]) - - buses=zip(*buses) # transpose the matrix - - del idata, rdata, istrings, rstrings - - #Lines data (from, to, amps, rate%a, ploss, qloss) - flag=2 #All non-transformer branches - istrings = ['fromnumber','tonumber'] - ierr, idata = psspy.abrnint(sid, owner_brflow, ties_brflow, flag, entry, istrings) - lines=idata - - rstrings=['amps','pctratea','pctrateb','pctratec','p','q'] - ierr, rdata = psspy.abrnreal(sid, owner_brflow, ties_brflow, flag, entry, rstrings) - for rc in range (np.matrix(rdata).shape[0]) : - lines.append(rdata[rc]) - - cstrings=['fromname','toname','id'] - ierr, cdata = psspy.abrnchar(sid, owner_brflow, ties_brflow, flag, entry, cstrings) - for rc in range (np.matrix(cdata).shape[0]) : - cdata[rc]=map( lambda s: s.replace("\n"," "),cdata[rc]) - lines.append(cdata[rc]) - - #eliminate breakers and switches - linesAll=zip(*lines) # transpose the matrix - lines = [] - for line in linesAll: - if ('@' not in line[10]) and ('*' not in line[10]): - lines.append(line) - - del idata, rdata, istrings, rstrings - - #2 windings transformers data (from, to, amps, rate%a, ploss, qloss) - flag=6 #All transformer branches - istrings = ['fromnumber','tonumber'] - ierr, idata = psspy.abrnint(sid, owner_brflow, ties_brflow, flag, entry, istrings) - transf=idata - - rstrings=['amps','pctratea','pctrateb','pctratec','p','q'] - ierr, rdata = psspy.abrnreal(sid, owner_brflow, ties_brflow, flag, entry, rstrings) - for rc in range (np.matrix(rdata).shape[0]) : - transf.append(rdata[rc]) - - cstrings=['fromname','toname','id'] - ierr, cdata = psspy.abrnchar(sid, owner_brflow, ties_brflow, flag, entry, cstrings) - for rc in range (np.matrix(cdata).shape[0]) : - cdata[rc]=map( lambda s: s.replace("\n"," "),cdata[rc]) - transf.append(cdata[rc]) - - transf=zip(*transf) # transpose the matrix - - del idata, rdata, istrings, rstrings - - #3 windings transformers data (from, to, amps, rate%a, ploss, qloss) - #sid = -1 #assume a subsystem containing all buses in working case - owner_3flow = 1 #1 = use bus ownership 2 = use tfo ownership - ties_3flow = 3 #ignored bc sid is negative. 3 = interior subsystem and subsystem tie 3 winding transformers - flag=3 #all 3 winding transfo windings - entry = 2 #1=winding 1 bus order, 2=transformer name order - - istrings = ['wind1number','wind2number','wind3number', 'wndnum'] - ierr, idata = psspy.awndint(sid, owner_3flow, ties_3flow, flag, entry, istrings) - transf3 = idata - - rstrings=['amps','pctratea','pctrateb','pctratec','p','q'] - ierr, rdata = psspy.awndreal(sid, owner_3flow, ties_3flow, flag, entry, rstrings) - for rc in range (np.matrix(rdata).shape[0]) : - transf3.append(rdata[rc]) - - cstrings=['wind1name','wind2name','wind3name','id'] - ierr, cdata = psspy.awndchar(sid, owner_3flow, ties_3flow, flag, entry, cstrings) - for rc in range (np.matrix(cdata).shape[0]) : - cdata[rc]=map( lambda s: s.replace("\n"," "),cdata[rc]) - transf3.append(cdata[rc]) - - transf3=zip(*transf3) # transpose the matrix - - del idata, rdata, istrings, rstrings - - - #Machines data (bus, inservice, number, pgen, qgen, mvabase, pmax, qmax, name) - istrings = ['number','status'] - ierr, idata = psspy.amachint(sid, flag_plant, istrings) - plants=idata - - cstrings = ['id'] - ierr, cdata = psspy.amachchar(sid, flag_plant, cstrings) - for rc in range (np.matrix(cdata).shape[0]) : - plants.append(cdata[rc]) - - rstrings = ['pgen','qgen','mbase','pmax','qmax'] - ierr, rdata = psspy.amachreal(sid, flag_plant, rstrings) - for rc in range (np.matrix(rdata).shape[0]) : - plants.append(rdata[rc]) - - cstrings = ['name'] - ierr, cdata = psspy.amachchar(sid, flag_plant, cstrings) - cdata[0]= map( lambda s: s.replace("\n"," "),cdata[0]) - plants.append(cdata[0]) - - rstrings = ['pmin','qmin'] - ierr, rdata = psspy.amachreal(sid, flag_plant, rstrings) - for rc in range (np.matrix(rdata).shape[0]) : - plants.append(rdata[rc]) - - istrings = ['wmod'] - ierr, idata = psspy.amachint(sid, flag_plant, istrings) - for rc in range (np.matrix(idata).shape[0]) : - plants.append(idata[rc]) - - nb_plants=np.matrix(plants).shape[1] - for rc in range (0,nb_plants) : - plants[3][rc]=float(plants[3][rc]*int(plants[1][rc])) # If the plant isn't in service its production is fixed to zero - plants[4][rc]=float(plants[4][rc]*int(plants[1][rc])) # If the plant isn't in service its production is fixed to zero - - plants=zip(*plants) # transpose the matrix - - del idata, rdata, cdata - - #Loads data (bus, active, reactive, status, name, id) - istrings = ['number'] - ierr, idata = psspy.aloadint(sid, flag_load, istrings) - loads=idata - - xstrings = ['mvaact'] - ierr, xdata = psspy.aloadcplx(sid, flag_load, xstrings) - loads.append(np.real(xdata)[0]) # Append the real part of the load - loads.append(np.imag(xdata)[0]) #Append the imaginary part of the load - - istrings = ['status'] - ierr, idata = psspy.aloadint(sid, flag_load, istrings) - loads.append(idata[0]) - - cstrings = ['name', 'id'] - ierr, cdata = psspy.aloadchar(sid, flag_load, cstrings) - cdata[0]=map( lambda s: s.replace("\n"," "),cdata[0]) - loads.append(cdata[0]) - loads.append(cdata[1]) - - nb_loads=np.matrix(loads).shape[1] - for rc in range (0,nb_loads) : - loads[1][rc]=float(loads[1][rc]*int(loads[3][rc])) # If the load isn't in service its consumption is fixed to zero - loads[2][rc]=float(loads[2][rc]*int(loads[3][rc])) # If the load isn't in service its consumption is fixed to zero - - loads=zip(*loads) # transpose the matrix - - del idata, cdata, xdata - - #Fixed shunt data (number, MVAR, name, ...) - istrings = ['number','status'] - ierr, idata = psspy.afxshuntint(sid, flag_bus, istrings) - shunt=idata - - xstrings = ['shuntact'] - ierr, xdata = psspy.afxshuntcplx(sid, flag_bus, xstrings) - shunt.append(np.imag(xdata)[0]) #Append the imaginary part of the shunt - - cstrings = ['name'] - ierr, cdata = psspy.afxshuntchar(sid, flag_bus, cstrings) - cdata[0]=map( lambda s: s.replace("\n"," "),cdata[0]) - shunt.append(cdata[0]) - - xstrings = ['shuntnom'] - ierr, xdata = psspy.afxshuntcplx(sid, flag_bus, xstrings) - shunt.append(np.imag(xdata)[0]) #Append the imaginary part of the shunt - - cstrings = ['id'] - ierr, cdata = psspy.afxshuntchar(sid, flag_bus, cstrings) - cdata[0]=map( lambda s: s.replace("\n"," "),cdata[0]) - shunt.append(cdata[0]) - - nb_sh=np.matrix(shunt).shape[1] - for rc in range (0,nb_sh) : # If the swshunt isn't in service its MVAR is fixed to zero - shunt[2][rc]=float(shunt[2][rc]*int(shunt[1][rc])) - shunt[4][rc]=float(shunt[4][rc]*int(shunt[1][rc])) - - shunt=zip(*shunt) # transpose the matrix - - del idata, cdata, xdata - - #Switched shunt data (number, MVAR, name, ...) - istrings = ['number','status'] - ierr, idata = psspy.aswshint(sid, flag_swsh, istrings) - swshunt=idata - status = np.array(swshunt[1]) - - - rstrings = ['bswact'] - ierr, rdata = psspy.aswshreal(sid, flag_swsh, rstrings) - swshunt.append(rdata[0]) #Append the imaginary part of the load - - cstrings = ['name'] - ierr, cdata = psspy.aswshchar(sid, flag_swsh, cstrings) - #cdata[0]=map( lambda s: s.replace("\n"," "),cdata[0]) - swshunt.append(cdata[0]) - - rstrings = ['bswnom'] - ierr, rdata = psspy.aswshreal(sid, flag_swsh, rstrings) - swshunt.append(rdata[0]) #Append the imaginary part of the load - - nb_swsh=np.matrix(swshunt).shape[1] - for rc in range (0,nb_swsh) : # If the swshunt isn't in service its MVAR is fixed to zero - swshunt[2][rc]=float(swshunt[2][rc]*int(swshunt[1][rc])) - swshunt[4][rc]=float(swshunt[4][rc]*int(swshunt[1][rc])) - - swshunt=zip(*swshunt) # transpose the matrix - - del idata, cdata, rdata - - #Motors data (bus, active, reactive, status, name, id) - istrings = ['number'] - ierr, idata = psspy.aindmacint(sid, flag_motor, istrings) - motors=idata - - rstrings = ['p','q'] - ierr, rdata = psspy.aindmacreal(sid, flag_motor, rstrings) - motors.append(rdata[0]) #Append the real part of the motor load - motors.append(rdata[1]) #Append the imaginary part of the motor load - - istrings = ['status'] - ierr, idata = psspy.aindmacint(sid, flag_motor, istrings) - motors.append(idata[0]) - - cstrings = ['name', 'id'] - ierr, cdata = psspy.aindmacchar(sid, flag_motor, cstrings) - cdata[0]=map( lambda s: s.replace("\n"," "),cdata[0]) - motors.append(cdata[0]) - motors.append(cdata[1]) - - nb_motors=np.matrix(motors).shape[1] - for rc in range (0,nb_motors) : - motors[1][rc]=float(motors[1][rc]*int(motors[3][rc])) # If the load isn't in service its consumption is fixed to zero - motors[2][rc]=float(motors[2][rc]*int(motors[3][rc])) # If the load isn't in service its consumption is fixed to zero - - motors=zip(*motors) # transpose the matrix - - del idata, cdata, rdata - - return buses, lines, transf, plants, loads, shunt, motors, transf3, swshunt - -def MyLogger(x,y,z,logCSVfilename,ite): - f=open(logCSVfilename, 'a') - f.write(str(ite)+';') - f.write(";") - nx = len(x) - for i in range(0,nx): - f.write(str(x[i]))#f.write("%f;" % (x[i])) - f.write(";") - f.write(";") - nz = len(z) - for i in range(0,nz): - try: - f.write("%f;" % (z[i])) - except: - f.write(str(z[i])+";") - f.write(";") - ny = len(y) - for j in range(0,ny): - f.write("%f;" % (y[j])) - f.write("\n") - f.close() - -# Fonction pour ecrire un fichier de sortie type csv pour chaque type de grandeur de sortie -def MyMultiLogger (x, y, sizeY, z, ite, folder, day, fich, hour): - global ny - y0=0 - for fich in range (np.size(sizeY,0)): - multilogfilename=folder+"\N"+day+"\Y"+str(fich)+"simulationDClog_"+hour+".csv" - f=open(multilogfilename, 'a') - f.write("%f;" % (ite)) - f.write(";") - nx = len(x) - for i in range(0,nx): - f.write("%f;" % (x[i])) - f.write(";") - nz = len(z) - for i in range(0,nz): - f.write("%f;" % (z[i])) - f.write(";") - ny = sizeY[fich] - for j in range(0,ny): - f.write("%f;" % (y[j+y0])) - f.write("\n") - f.close() - y0 += ny - print( "Fichiers "+str(ite)+" enregistres\n\n") - -# Analyses graphiques -def graphical_out (inputSample, outputSampleAll, inputDim, outputDim, montecarlosize) : - print "\n\n\n Writing graphical analysis files..." - # A Pairwise scatter plot of the inputs - myGraph = Graph() - myPairs = Pairs(inputSample, 'Inputs relations', inputSample.getDescription(), "red", "bullet") - myGraph.add(Drawable(myPairs)) - myGraph.draw("Input Samples",640,480,GraphImplementation.PDF) - #View(myGraph.getBitmap()) - print 'Input pairwise scatterplot done...' - - # A Pairwise scatter plot of the outputs - myGraph = Graph() - myPairs = Pairs(outputSampleAll, 'Output relations', outputSampleAll.getDescription(), "red", "bullet") - myGraph.add(Drawable(myPairs)) - myGraph.draw("Output Samples",640,480,GraphImplementation.PDF) - #View(myGraph.getBitmap()) - print 'Output pairwise scatterplot done...' - - # A Pairwise scatter plot of the inputs/outputs - # Draw all scatter plots yj vs xi - for j in range(outputDim): - outputSamplej=outputSampleAll.getMarginal(j) - Ylabelstr=outputSamplej.getDescription()[0] - for i in range(inputDim): - inputSamplei=inputSample.getMarginal(i) - Xlabelstr=inputSamplei.getDescription()[0] - X=NumericalSample(montecarlosize,2) - for k in range(montecarlosize): - X[k,0]=inputSamplei[k][0] - X[k,1]=outputSamplej[k][0] - myGraph = Graph() - myCloud=Cloud(X); - mytitle=Ylabelstr+"vs"+Xlabelstr - myGraph.add(Drawable(myCloud)) - myGraph.setAxes(1) - myGraph.setXTitle(Xlabelstr) - myGraph.setYTitle(Ylabelstr) - myGraph.draw(mytitle,640,480,GraphImplementation.PDF) - #ViewImage(myGraph.getBitmap()) - print 'Input/Output pairwise scatterplot done...' - - # An histogram of the inputs - for i in range(inputDim): - inputSamplei=inputSample.getMarginal(i) - myGraph = VisualTest.DrawHistogram(inputSamplei) - labelarray=inputSamplei.getDescription() - labelstr=labelarray[0] - myGraph.setTitle(labelstr) - myGraph.setName(labelstr) - myGraph.setXTitle(labelstr) - myGraph.setYTitle("Frequency") - myGraph.draw(labelstr,640,480,GraphImplementation.PDF) - #View(myGraph.getBitmap()) - print 'Input histogram done...' - - # An histogram of the outputs - for j in range(outputDim): - outputSamplej=outputSampleAll.getMarginal(j) - myGraph = VisualTest.DrawHistogram(outputSamplej) - labelarray=outputSamplej.getDescription() - labelstr=labelarray[0] - myGraph.setTitle(labelstr) - myGraph.setName(labelstr) - myGraph.setXTitle(labelstr) - myGraph.setYTitle("Frequency") - myGraph.draw(labelstr,640,480,GraphImplementation.PDF) - #View(myGraph.getBitmap()) - print 'Output histogram done' - print 'Graphical output terminated' - - -def config_contingency(LinesList,GroupsList,TransformersList,LoadsList,MotorsList) : - - lines_con=[] - groups_con=[] - loads_con = [] - transfos_con = [] - motors_con = [] - sizeLines = len(LinesList) - sizeGroups = len(GroupsList) - sizeTransfos = len(TransformersList) - sizeLoads = len(LoadsList) - sizeMotors = len(MotorsList) - val=[] - prob=[] - - for i in range(sizeLines+sizeGroups+sizeTransfos + sizeLoads + sizeMotors) : - val.append(int(i)) - for i in range (sizeLines) : - lines_con.append(LinesList[i][0]) - prob.append(LinesList[i][1]) - for i in range (sizeGroups) : - prob.append(GroupsList[i][1]) - groups_con.append(GroupsList[i][0]) - for i in range (sizeTransfos) : - prob.append(TransformersList[i][1]) - transfos_con.append(TransformersList[i][0]) - for i in range (sizeLoads) : - prob.append(LoadsList[i][1]) - loads_con.append(LoadsList[i][0]) - for i in range (sizeMotors) : - prob.append(MotorsList[i][1]) - motors_con.append(MotorsList[i][0]) - - return lines_con, groups_con, transfos_con, loads_con, motors_con, val, prob - -##def config_contingency(LinesPath,GeneratorsPath,TransformersPath,LoadsPath) : -## -## lines_con=[] -## groups_con=[] -## loads_con = [] -## transfos_con = [] -## -## # Loading of lines contingency configuration -## if LinesPath != '': -## f=open(LinesPath,"r") -## lines=f.readlines() -## f.close() -## for i in range (len(lines)) : -## line=lines[i].split(";") -## try : -## int(line[1]) -## except ValueError : -## pass -## else : -## if line[0] == '' : -## line[0] = '0' -## lines_con.append([int(line[1]), int(line[3]), str(line[5]),float(line[0].replace(',','.'))]) -## -## # Loading of lines contingency configuration -## if TransformersPath != '': -## f=open(TransformersPath,"r") -## lines=f.readlines() -## f.close() -## for i in range (len(lines)) : -## line=lines[i].split(";") -## try : -## int(line[1]) -## except ValueError : -## pass -## else : -## if line[0] == '' : -## line[0] = '0' -## transfos_con.append([int(line[1]), int(line[3]), str(line[5]),float(line[0].replace(',','.'))]) -## -## # Loading of groups contingency configuration -## if GeneratorsPath != '': -## f=open(GeneratorsPath,"r") -## lines=f.readlines() -## f.close() -## for i in range (len(lines)) : -## line=lines[i].split(";") -## try : -## int(line[1]) -## except ValueError : -## pass -## else : -## if line[0] == '' : -## line[0] = '0' -## groups_con.append([int(line[1]), int(line[3]),float(line[0].replace(',','.'))]) -## -## # Loading of loads contingency configuration -## if LoadsPath != '': -## f=open(LoadsPath,"r") -## lines=f.readlines() -## f.close() -## for i in range (len(lines)) : -## line=lines[i].split(";") -## try : -## int(line[1]) -## except ValueError : -## pass -## else : -## if line[0] == '' : -## line[0] = '0' -## loads_con.append([int(line[1]), int(line[3]), float(line[0].replace(',','.'))]) -## -## sizeLines = len(lines_con) -## sizeGroups = len(groups_con) -## sizeTransfos = len(transfos_con) -## sizeLoads = len(loads_con) -## val=[] -## prob=[] -## for i in range(sizeLines+sizeGroups+sizeTransfos + sizeLoads) : -## val.append(int(i)) -## -## for i in range (sizeLines) : -## prob.append(lines_con[i][3]) -## for i in range (sizeGroups) : -## prob.append(groups_con[i][2]) -## for i in range (sizeTransfos) : -## prob.append(transfos_con[i][3]) -## for i in range (sizeLoads) : -## prob.append(loads_con[i][2]) -## return lines_con, groups_con, transfos_con, loads_con, val, prob - -def LoadARMA(time_serie_file, time_serie_SS, time_serie_TH) : - f=open(time_serie_file,"r") - lines=f.readlines() - N=len(lines) - Xt=[] - for i in range(N) : - Xt.append([float(lines[i])]) - - myTG=RegularGrid(0,float(time_serie_SS),N) - TS=TimeSeries(myTG,NumericalSample(Xt)) - myWN=WhiteNoise(Distribution(Normal(0,1)),myTG) - myState=ARMAState(TS.getSample(),NumericalSample()) - p=12 - q=0 - d=1 - myFactory = ARMALikelihoodFactory ( p , q , d ) - myARMA = myFactory.build(TS) - - myARMA.setState(myState) - - AR = myARMA.getARCoefficients() - MA = myARMA.getMACoefficients() - - ts = myARMA.getRealization() - ts.setName('A realization') - myTSGraph=ts.drawMarginal(0) - myTSGraph.draw('Realization'+str(p)+","+str(q),640,480,GraphImplementation.PDF) - myARMAState=myARMA.getState() - - #Make a prediction of the future on next Nit instants - Nit = int(time_serie_TH) - myARMA2=ARMA(AR,MA,myWN,myARMAState) - possibleFuture=myARMA2.getFuture(Nit) - possibleFuture.setName('Possible future') - - Xt2=[] - for i in range (len(possibleFuture)): - Xt2.append(possibleFuture.getValueAtIndex(i)[0]) - Max=float(max(Xt2)) - Min=float(min(Xt2)) - h=float(Max-Min) - for i in range (len(possibleFuture)): - value= (Xt2[i]-Min+h/3)/(Max-Min+h/3) - possibleFuture.setValueAtIndex(i,NumericalPoint(1,value)) - - myFG=possibleFuture.drawMarginal(0) - myFG.draw('Future'+str(Nit),640,480,GraphImplementation.PDF) - - return possibleFuture - -def LoadTS(time_serie_file) : - TS=[] - for i in range(len(time_serie_file)) : - if time_serie_file[i] == -1 : - pass - else : - f=open(time_serie_file[i],"r") - lines=f.readlines() - N=len(lines) - Xt=[] - for j in range(N) : - try : - float(lines[i]) - except ValueError : - lines[i] = commaToPoint(lines[i]) - else : - pass - Xt.append([float(lines[j])]) - TS.append(Xt) - return TS - - -def KSDist(lines) : - print "Creating Kernel Smoothing distribution " - N=len(lines) - Xt=[] - for i in range(N) : - if lines[i] == "\n" : - print "End of file" - break - else : - try : - float(lines[i]) - except ValueError : - lines[i] = commaToPoint(lines[i]) - else : - pass - Xt.append([float(lines[i])]) - NS=NumericalSample(Xt) - kernel=KernelSmoothing(Uniform()) - myBandwith = kernel.computeSilvermanBandwidth(NS) - KS=kernel.build(NS,myBandwith,1) - return KS - - -def threshold (inputRandomVector, outputVariableOfInterest,pssefun,inputDistribution) : - # We create a quadraticCumul algorithm - myQuadraticCumul = QuadraticCumul(outputVariableOfInterest) - - # We compute the several elements provided by the quadratic cumul algorithm - # and evaluate the number of calculus needed - nbBefr = pssefun.getEvaluationCallsNumber() - - # Mean first order - meanFirstOrder = myQuadraticCumul.getMeanFirstOrder()[0] - nbAfter1 = pssefun.getEvaluationCallsNumber() - - # Mean second order - meanSecondOrder = myQuadraticCumul.getMeanSecondOrder()[0] - nbAfter2 = pssefun.getEvaluationCallsNumber() - - # Standard deviation - stdDeviation = sqrt(myQuadraticCumul.getCovariance()[0,0]) - nbAfter3 = pssefun.getEvaluationCallsNumber() - - print "First order mean=", myQuadraticCumul.getMeanFirstOrder()[0] - print "Evaluation calls number = ", nbAfter1 - nbBefr - print "Second order mean=", myQuadraticCumul.getMeanSecondOrder()[0] - print "Evaluation calls number = ", nbAfter2 - nbAfter1 - print "Standard deviation=", sqrt(myQuadraticCumul.getCovariance()[0,0]) - print "Evaluation calls number = ", nbAfter3 - nbAfter2 - - print "Importance factors=" - for i in range(inputRandomVector.getDimension()) : - print inputDistribution.getDescription()[i], " = ", myQuadraticCumul.getImportanceFactors()[i] - print "" - -def getUserDefined (values): - val = [] - prob = [] - for a in values: - val.append(a[0]) - prob.append(a[1]) - dim = len (val) - - prob = map(float,prob) - prob = [p/sum(prob) for p in prob] - -## weights = NumericalPoint(prob) -## Vals = [] -## for i in range(dim): -## Vals.append([float(val[i]),float(val[i])+0.000001]) -## ranges = NumericalSample(Vals) -## return UserDefined(ranges, weights) - coll = UserDefinedPairCollection() - for i in range (dim) : - UDpair=UserDefinedPair(NumericalPoint(1,float(val[i])),float(prob[i])) - coll.add(UDpair) - return UserDefined(coll) - - -def getHistogram (values) : - step = [] - prob = [] - for a in values: - step.append(a[0]) - prob.append(a[1]) - dim = len (step) - myHistogram = HistogramPairCollection(dim) - for i in range (dim) : - try: - myHistogram[i]=HistogramPair(float(step[i]),float(prob[i])) - except: - pass - return myHistogram - - - -def getUserLaw(LawDico): - time_serie = 0 - time_serie_file = '' - time_serie_SS = 0 - time_serie_TH = 0 - if LawDico['Law']=="Normal": - law = Normal(float(LawDico['Mu']),float(LawDico['Sigma']))#Openturns - elif LawDico['Law']=="Uniform": - law=Uniform(float(LawDico['A']),float(LawDico['B'])) - elif LawDico['Law']=="Exponential": - law=Exponential(float(LawDico['Lambda']),float(LawDico['Gamma'])) - elif LawDico['Law']=="Weibull": - if LawDico['Settings']=='AlphaBeta': - law=Weibull(float(LawDico['Alpha']),float(LawDico['Beta']),float(LawDico['Gamma'])) - elif LawDico['Settings']=='MuSigma': - law=Weibull(float(LawDico['Mu']),float(LawDico['Sigma']),float(LawDico['Gamma']),Weibull.MUSIGMA) - elif LawDico['Law']=="TruncatedNormal": - law=TruncatedNormal(float(LawDico['MuN']),float(LawDico['SigmaN']),float(LawDico['A']),float(LawDico['B'])) - elif LawDico['Law']=="UserDefined": - law=UserDefined(getUserDefined (LawDico['Values'])) - elif LawDico['Law']=="Histogram": - law=Histogram(LawDico['First'], getHistogram (LawDico['Values'])) - elif LawDico['Law']=="PDF_from_file": - law=KSDist(LawDico['FileContents']) - elif LawDico['Law']=="TimeSeries_from_file": - law = Uniform(0.999999,1) - time_serie=1 - time_serie_file=LawDico['FileContents'] - else : - law = Uniform(0.999999,1) - return law, [time_serie, time_serie_file] #[time_serie, time_serie_file, time_serie_SS, time_serie_TH] - - - - -def contingency_automatic (dfxPath, acccPath, rate) : - psspy.accc_with_dsp_3( 0.5,[0,0,0,1,1,2,0,0,0,0,0],r"""ALL""",dfxPath,acccPath,"","","") - psspy.accc_single_run_report_4([1,int(rate),int(rate),1,1,0,1,0,0,0,0,0],[0,0,0,0,6000],[ 0.5, 5.0, 100.0,0.0,0.0,0.0, 99999.],acccPath) - - rslt_summary=pssarrays.accc_summary(acccPath) - if int(rate) == 1 : - rate = rslt_summary.rating.a - elif int(rate) == 2 : - rate = rslt_summary.rating.b - elif int(rate) == 3 : - rate = rslt_summary.rating.c - else : - print "NO RATE CHOOSEN" - - Labels=rlst.colabel - contin_load=[] - for label in Labels : - t=[] - rslt=pssarrays.accc_solution(acccPath,contingency,label,0.5,5.0) - ampFlow=rslt.ampflow - for i in range (len(rA)) : - t.append(ampFlow[i]/rate[i]) - contin_load.append(t) - return contin_load - -def commaToPoint (string) : - stringReplaced = string.replace(',','.') - return stringReplaced - -def PSSEFunct(dico,x): - if 1: - #try: -## if dico['TStest']==1: -## os.chdir(dico['doc_base']) #to work in right directory of the package -## sys.stdout=open('process num'+str(os.getpid())+'_package '+\ -## str(dico['num_pac'])+'.out','w') - - #Get all the dico values - TStest=dico['TStest'] - sizeY0=dico['sizeY0'] - sizeY1=dico['sizeY1'] - sizeY2=dico['sizeY2'] - sizeY3=dico['sizeY3'] - sizeY4=dico['sizeY4'] - sizeY5=dico['sizeY5'] - sizeY6=dico['sizeY6'] - sizeY7=dico['sizeY7'] - sizeY8=dico['sizeY8'] - sizeY=dico['sizeY'] - Xt=dico['Xt'] - folder=dico['folder'] - folderN_1=dico['folderN_1'] - day=dico['day'] - doc_base=dico['doc_base'] - PSSEParams=dico['PSSEParams'] - _i=dico['_i'] - _f=dico['_f'] - _s=dico['_s'] - if dico['PSSEParams']['I_MAX']=='RateA': - Irate_num=1 - elif dico['PSSEParams']['I_MAX']=='RateB': - Irate_num=2 - elif dico['PSSEParams']['I_MAX']=='RateC': - Irate_num=3 - num_pac=dico['num_pac'] - logCSVfilename=dico['logCSVfilename'] - continLines=dico['continLines'] - continGroups=dico['continGroups'] - continTransfos=dico['continTransfos'] - continLoads=dico['continLoads'] - continMotors=dico['continMotors'] - continVal=dico['continVal'] - continProb=dico['continProb'] - position=dico['position'] - timeVect=dico['timeVect'] - LawsList = dico['CorrMatrix']['laws'] - all_inputs_init = dico['all_inputs_init'] - AdjLoadTables = dico['AdjLoadTables'] - - - #initializations - Output=[] - LS=[] - FS=[] - Pmachine=[] - LStable=[] - FStable=[] - - LS_beforeUC=[] - FS_beforeUC=[] - Pmachine_beforeUC=[] - LStable_beforeUC=[] - FStable_beforeUC=[] - Output_beforeUC = [] - - outputSampleAll=NumericalSample(0,9) - inputSample=[] - redirect.psse2py() - #import pssdb - psspy.psseinit(80000) - - # Silent execution of PSSe - islct=6 # 6=no output; 1=standard - psspy.progress_output(islct) - - - x_copy = [] - for ite in range(len(x)): - xite = [] - for j in range(len(x[ite])): - xite.append(x[ite][j]) - x_copy.append(xite) - - - for ite in range(len(x)): - - position+=1 - os.chdir(doc_base) #to work in right directory of the package - # Load data from PSSe - psspy.case(doc_base+'/BaseCase.sav') #Launching of PSSE and opening the working file - all_inputs_base=read_sav(doc_base+'/BaseCase.sav') - buses_base=all_inputs_base[0] - lines_base=all_inputs_base[1] - transf_base=all_inputs_base[2] - plants_base=all_inputs_base[3] - loads_base=all_inputs_base[4] - shunt_base=all_inputs_base[5] - motors_base=all_inputs_base[6] - transf3_base=all_inputs_base[7] - swshunt_base=all_inputs_base[8] - #Calculate Losses: - P_load = 0 - for load in loads_base: - P_load += load[1] - for motor in motors_base: - P_load+= motor[1] - P_gen = 0 - for gen in plants_base: - busnum = gen[0] - genid = gen[2].strip() - pgen = gen[3] - P_gen+=pgen - Losses = P_gen - P_load - LossesRatio = (Losses/P_load)*1.25 #overestimate losses to avoid surpassing swing bus capacity after economic dispatch - doci=os.path.join(doc_base,"Case_"+str(position)+".sav") - doci_beforeUC = os.path.join(doc_base,"Case_beforeUC_" + str(position) + ".sav") - psspy.save(doci) - # Total initial (fixed) shunt on buses - init_shunt = 0 - for i in range(len(shunt_base)) : - init_shunt += float(shunt_base[i][2]) - # Configuration de l'OPF a partir des parametres de l'utilisateur - TapChange = 1-int(dico['PSSEParams']['LOCK_TAPS']) #0 if locked, 1 if stepping - psspy.report_output(6,"",[0,0]) #6=no output - if PSSEParams['ALGORITHM']=='Optimum Power Flow': - if Debug: - print 'Got to OPF parametrization' - logfile = os.path.join(doc_base,r"""DETAIL""") - psspy.produce_opf_log_file(1,logfile) - psspy.opf_fix_tap_ratios(1-TapChange) #0 : do not fix transformer tap ratios - psspy.minimize_fuel_cost(int(dico['PSSEParams']['FUEL_COST'])) - psspy.minimize_adj_bus_shunts(int(dico['PSSEParams']['MVAR_COST'])) - psspy.minimize_load_adjustments(int(dico['PSSEParams']['LOADSHEDDING_COST'])) - #psspy.minimize_load_adjustments(False) #block load adjustments during application of laws - #psspy.initial_opf_barrier_coeff(100) - #psspy.final_opf_barrier_coeff(0.0001) - #psspy.opf_step_length_tolerance(0.00001) - #psspy.opf_fix_all_generators(0) - psspy.set_opf_report_subsystem(3,1) - psspy.solution_parameters_4([PSSEParams['ITERATION_LIMIT'],PSSEParams['ITERATION_LIMIT'],PSSEParams['ITERATION_LIMIT'],_i,_i], [_f]*19) - #[1.6, 1.6, 1, 0.0001, 1, 1, 1, 0.00001, 5, 0.7, 0.0001, 0.005, 1, 0.05, 0.99, 0.99, 1, 0.0001, 100]) - - else: #economic dispatch - ecd_file = PSSEParams['ecd_file'] - # 1. Affiche - nx = len(x[0]) - if TStest==1 : - for i,law in enumerate(LawsList): - if Xt[ite][i] == -1 : - if law != 'N_1_fromFile': - if 'Availability' in dico['Laws'][law]['Type']: - status = int(round(x[ite][i])) #idealement on a tiré un chiffre entre 0 et 1, 0 et 1 inclus - status = min(status,1) #on force status à avoir une valeur 0 ou 1 - status = max(status,0) - x_copy[ite][i]=status - if dico['Laws'][law]['ComponentType']=='Generator' and 'Level' in dico['Laws'][law]['Type']: - if dico['Laws'][law]['TransferFunction']==True: - if dico['Laws'][law]['TF_Input']=='.pow file': - z_WS = dico['Laws'][law]['Wind_Speed_Measurement_Height'] - pathWT = dico['Laws'][law]['File_Name'] - HH = dico['Laws'][law]['Hub_Height'] - alpha = dico['Laws'][law]['AlphaWS'] - PercentLoss = dico['Laws'][law]['Percent_Losses'] - x_copy[ite][i]=eol(np.array([x[ite][i]]), z_WS, pathWT, HH, alpha, PercentLoss)[0] - elif dico['Laws'][law]['TF_Input']=='tuples list': - x_copy[ite][i]=applyTF(x[ite][i], dico['Laws'][law]['TF_Values']) - else: #ensure values are between 0 and 1 - Pval = x[ite][i] - Pval = min(Pval,1) - Pval = max(Pval,0) - x_copy[ite][i]=Pval - else: #law=='N_1_fromFile" - x_copy[ite][i]==int(floor(x[ite][i])) - - else: - x_copy[ite][i]=float(Xt[ite][i]) # Dans le cas d'une etude temporelle on lui donne la valeur de Xt - - else : - for i,law in enumerate(LawsList): - if law != 'N_1_fromFile': - if 'Availability' in dico['Laws'][law]['Type']: - status = int(round(x[ite][i])) #idealement on a tiré un chiffre entre 0 et 1, 0 et 1 inclus - status = min(status,1) #on force status à avoir une valeur 0 ou 1 - status = max(status,0) - x_copy[ite][i]=status - if dico['Laws'][law]['ComponentType']=='Generator' and 'Level' in dico['Laws'][law]['Type']: - if dico['Laws'][law]['TransferFunction']==True: - if dico['Laws'][law]['TF_Input']=='.pow file': - z_WS = dico['Laws'][law]['Wind_Speed_Measurement_Height'] - pathWT = dico['Laws'][law]['File_Name'] - HH = dico['Laws'][law]['Hub_Height'] - alpha = dico['Laws'][law]['AlphaWS'] - PercentLoss = dico['Laws'][law]['Percent_Losses'] - x_copy[ite][i]=eol(np.array([x[ite][i]]), z_WS, pathWT, HH, alpha, PercentLoss)[0] - #x_copy[ite][i]=x[ite][i] - elif dico['Laws'][law]['TF_Input']=='tuples list': - x_copy[ite][i]=applyTF(x[ite][i], dico['Laws'][law]['TF_Values']) - else: #ensure values are between 0 and 1 - Pval = x[ite][i] - Pval = min(Pval,1) - Pval = max(Pval,0) - x_copy[ite][i]=Pval - else: #law=='N_1_fromFile" - x_copy[ite][i]==int(floor(x[ite][i])) - inputSample.append(np.array(x[ite])) - - if PSSEParams['ALGORITHM']=='Optimum Power Flow': - #get OPF data - allbus=1 - include = [1,1,1,1] #isolated buses, out of service branches, subsystem data, subsystem tie lines - out = 0 #out to file, not window - # if psspy.bsysisdef(0): - # sid = 0 - # else: # Select subsytem with all buses - # sid = -1 - sid = 3 - RopFile = os.path.join(dico['doc_base'],"BaseCase.rop" ) - AlreadyRop=os.path.isfile(RopFile) - if not AlreadyRop: - ierr = psspy.rwop(sid,allbus,include,out,RopFile) #write rop file - - GenDispatchData, DispTableData, LinCostTables, QuadCostTables, PolyCostTables, GenReserveData, PeriodReserveData,AdjBusShuntData,AdjLoadTables = readOPFdata(RopFile) - - if Debug: - print "Starting application of laws" - - # 2. Fait le calcul avec PSSE - - #Editing some values in the PSSE .sav input file - x2 = [] #list to store sampled values for logger function - for i,law in enumerate(LawsList): - if law != 'N_1_fromFile': - - #Reserve Constraint Law: change level of required reserve for a period reserve constraint - if dico['Laws'][law]['ComponentType']=='Reserve Constraint': - ReserveID = dico['Laws'][law]['ReserveID'] - ReserveFound = False - ReserveActive=False - for PRD in PeriodReserveData: - if PRD[0] == ReserveID: - ReserveFound=True - ReserveActive=PRD[3] - if not ReserveFound: - print 'ALERT: ReserveID ', str(ReserveID), ' is not found. User must define period reserve in .sav file before incluing a distribution on the reserve constraint in PSEN.' - elif not ReserveActive: - print 'ALERT: Spinning Reserve Correction entered in PSEN, but ReserveID ', str(ReserveID), ' is not activated in PSS/E.' - else: - status=_i #enabled/not enabled - level=x_copy[ite][i] #MW - timeframe = _f #minutes - psspy.opf_perrsv_main(ReserveID,status,[level, timeframe]) #change reserve constraint level - x2.append(x_copy[ite][i]) #store values for logger function - - # Load Law: change the values of the different loads and treat large changes of load to help convergence - #if dico['Laws'][law]['ComponentType']=='Load' and ('N_1' not in law) and ('out' not in law.lower()): - if dico['Laws'][law]['ComponentType']=='Load' and ('Availability' not in dico['Laws'][law]['Type']): - LoadList = dico['Laws'][law]['Load'] - if x_copy[ite][i] > 0.75 : # On change directement l(es) charge(s) - for LoadName in LoadList: - busNum = dico['Loads'][LoadName]['NUMBER'] - ID = dico['Loads'][LoadName]['ID'] - P = dico['Loads'][LoadName]['P'] - Q = dico['Loads'][LoadName]['Q'] - psspy.load_chng_4(busNum,ID,[_i,_i,_i,_i,_i,_i],[x_copy[ite][i]*P,x_copy[ite][i]*Q,_f,_f,_f,_f]) - - elif x_copy[ite][i] > 0.4 : # On effectue un pretraitement en passant par une charge intermediaire - for LoadName in LoadList: - busNum = dico['Loads'][LoadName]['NUMBER'] - ID = dico['Loads'][LoadName]['ID'] - P = dico['Loads'][LoadName]['P'] - Q = dico['Loads'][LoadName]['Q'] - psspy.load_chng_4(busNum,ID,[_i,_i,_i,_i,_i,_i],[(1+x_copy[ite][i])/2*P,(1+x_copy[ite][i])/2*Q,_f,_f,_f,_f]) - if PSSEParams['ALGORITHM']=='Optimum Power Flow': - if Debug: - print 'OPF load 1' - psspy.bsys(3,0,[0.0,0.0],0,[],1,[1],0,[],0,[]) - psspy.set_opf_report_subsystem(3,0) - psspy.nopf(0,1) # Lancement OPF - postOPFinitialization(doci,all_inputs_init,AdjLoadTables,init_gen=False,init_bus=False,init_fxshnt=True,init_swshnt=False,init_load=True,init_P0=False) - #psspy.fnsl([0, _i, 0, 0, 0, 0, _i,_i]) # Load flow Newton Raphson - else: - if Debug: - print "Economic Dispatch load 1" - #economic dispatch - EcdErrorCodes, LFcode, Plimit, Qlimit = EconomicDispatch(doci, ecd_file, LossesRatio, TapChange) - if Debug: - print "Returned from EconomicDispatch" - if np.any(np.array(EcdErrorCodes)!=0): - print "Error in economic dispatch." - for LoadName in LoadList : # On change toutes les charges - busNum = dico['Loads'][LoadName]['NUMBER'] - ID = dico['Loads'][LoadName]['ID'] - P = dico['Loads'][LoadName]['P'] - Q = dico['Loads'][LoadName]['Q'] - psspy.load_chng_4(busNum,ID,[_i,_i,_i,_i,_i,_i],[x_copy[ite][i]*P,x_copy[ite][i]*Q,_f,_f,_f,_f]) - - else : # On effectue un pretraitement en passant par une charge intermediaire - for LoadName in LoadList: - busNum = dico['Loads'][LoadName]['NUMBER'] - ID = dico['Loads'][LoadName]['ID'] - P = dico['Loads'][LoadName]['P'] - Q = dico['Loads'][LoadName]['Q'] - psspy.load_chng_4(busNum,ID,[_i,_i,_i,_i,_i,_i],[0.7*P,0.7*Q,_f,_f,_f,_f]) - - if PSSEParams['ALGORITHM']=='Optimum Power Flow': - if Debug: - print 'OPF load 2a' - psspy.bsys(3,0,[0.0,0.0],0,[],1,[1],0,[],0,[]) - psspy.set_opf_report_subsystem(3,0) - psspy.nopf(0,1) # Lancement OPF - postOPFinitialization(doci,all_inputs_init,AdjLoadTables,init_gen=False,init_bus=False,init_fxshnt=True,init_swshnt=False,init_load=True,init_P0=False) - #psspy.fnsl([0, _i, 0, 0, 0, 0, _i,_i]) # Load flow Newton Raphson - else: - if Debug: - print "Economic Dispatch load 2" - #economic dispatch - EcdErrorCodes, LFcode, Plimit, Qlimit = EconomicDispatch(doci, ecd_file, LossesRatio, TapChange) - if np.any(np.array(EcdErrorCodes)!=0): - print "Error in economic dispatch." - - for LoadName in LoadList : # On change toutes les charges - busNum = dico['Loads'][LoadName]['NUMBER'] - ID = dico['Loads'][LoadName]['ID'] - P = dico['Loads'][LoadName]['P'] - Q = dico['Loads'][LoadName]['Q'] - psspy.load_chng_4(busNum,ID,[_i,_i,_i,_i,_i,_i],[0.4*P,0.4*Q,_f,_f,_f,_f]) - if PSSEParams['ALGORITHM']=='Optimum Power Flow': - if Debug: - print 'OPF load 2b' - psspy.bsys(3,0,[0.0,0.0],0,[],1,[1],0,[],0,[]) - psspy.set_opf_report_subsystem(3,0) - psspy.nopf(0,1) # Lancement OPF - postOPFinitialization(doci,all_inputs_init,AdjLoadTables,init_gen=False,init_bus=False,init_fxshnt=True,init_swshnt=False,init_load=True,init_P0=False) - #psspy.fnsl([0, _i, 0, 0, 0, 0, _i,_i]) # Load flow Newton Raphson - else: - #economic dispatch - EcdErrorCodes, LFcode, Plimit, Qlimit = EconomicDispatch(doci, ecd_file, LossesRatio, TapChange) - if np.any(np.array(EcdErrorCodes)!=0): - print "Error in economic dispatch." - if Debug: - print "Economic Dispatch load 2" - for LoadName in LoadList : # On change toutes les charges - busNum = dico['Loads'][LoadName]['NUMBER'] - ID = dico['Loads'][LoadName]['ID'] - P = dico['Loads'][LoadName]['P'] - Q = dico['Loads'][LoadName]['Q'] - psspy.load_chng_4(busNum,ID,[_i,_i,_i,_i,_i,_i],[x_copy[ite][i]*P,x_copy[ite][i]*Q,_f,_f,_f,_f]) - x2.append(x_copy[ite][i]) #store values sampled for logger function - # Motor Load Law: change the values of the different induction motor loads and treat large changes of load to help convergence - #if dico['Laws'][law]['ComponentType']=='Motor' and ('N_1' not in law) and ('out' not in law.lower()): - if dico['Laws'][law]['ComponentType']=='Motor' and ('Availability' not in dico['Laws'][law]['Type']): - MotorList = dico['Laws'][law]['Motor'] - if x_copy[ite][i] > 0.75 : # On change directement l(es) charge(s) - for MotorName in MotorList: - busNum = dico['Motors'][MotorName]['NUMBER'] - ID = dico['Motors'][MotorName]['ID'] - Mbase = dico['Motors'][MotorName]['MBASE'] - BaseCode = dico['Motors'][MotorName]['BASECODE'] - Pinit = dico['Motors'][MotorName]['P'] - Qinit = dico['Motors'][MotorName]['Q'] - if BaseCode==2: #max is in MVA - PF = Pinit/((Pinit**2+Qinit**2)**0.5) - Pmax = PF*Mbase - else: - Pmax = Mbase - I_list = [_i]*9 - F_list = [_f]*23 - F_list[2]=x_copy[ite][i]*Pmax - psspy.induction_machine_chng(busNum,ID,I_list,F_list) - - elif x_copy[ite][i] > 0.4 : # On effectue un pretraitement en passant par une charge intermediaire - for MotorName in MotorList: - busNum = dico['Motors'][MotorName]['NUMBER'] - ID = dico['Motors'][MotorName]['ID'] - Mbase = dico['Motors'][MotorName]['MBASE'] - BaseCode = dico['Motors'][MotorName]['BASECODE'] - Pinit = dico['Motors'][MotorName]['P'] - Qinit = dico['Motors'][MotorName]['Q'] - if BaseCode==2: #max is in MVA - PF = Pinit/((Pinit**2+Qinit**2)**0.5) - Pmax = PF*Mbase - else: - Pmax = Mbase - I_list = [_i]*9 - F_list = [_f]*23 - F_list[2]=x_copy[ite][i]*Pmax*0.7 - psspy.induction_machine_chng(busNum,ID,I_list,F_list) - if PSSEParams['ALGORITHM']=='Optimum Power Flow': - if Debug: - print 'OPF motor load 1' - psspy.bsys(3,0,[0.0,0.0],0,[],1,[1],0,[],0,[]) - psspy.set_opf_report_subsystem(3,0) - psspy.nopf(0,1) # Lancement OPF - postOPFinitialization(doci,all_inputs_init,AdjLoadTables,init_gen=False,init_bus=False,init_fxshnt=True,init_swshnt=False,init_load=True,init_P0=False) - #psspy.fnsl([0, _i, 0, 0, 0, 0, _i,_i]) # Load flow Newton Raphson - else: - #economic dispatch - EcdErrorCodes, LFcode, Plimit, Qlimit = EconomicDispatch(doci, ecd_file, LossesRatio, TapChange) - if np.any(np.array(EcdErrorCodes)!=0): - print "Error in economic dispatch." - - for MotorName in MotorList: - busNum = dico['Motors'][MotorName]['NUMBER'] - ID = dico['Motors'][MotorName]['ID'] - Mbase = dico['Motors'][MotorName]['MBASE'] - BaseCode = dico['Motors'][MotorName]['BASECODE'] - Pinit = dico['Motors'][MotorName]['P'] - Qinit = dico['Motors'][MotorName]['Q'] - if BaseCode==2: #max is in MVA - PF = Pinit/((Pinit**2+Qinit**2)**0.5) - Pmax = PF*Mbase - else: - Pmax = Mbase - I_list = [_i]*9 - F_list = [_f]*23 - F_list[2]=x_copy[ite][i]*Pmax - psspy.induction_machine_chng(busNum,ID,I_list,F_list) - - else : # On effectue un pretraitement en passant par une charge intermediaire - for MotorName in MotorList: - busNum = dico['Motors'][MotorName]['NUMBER'] - ID = dico['Motors'][MotorName]['ID'] - Mbase = dico['Motors'][MotorName]['MBASE'] - BaseCode = dico['Motors'][MotorName]['BASECODE'] - Pinit = dico['Motors'][MotorName]['P'] - Qinit = dico['Motors'][MotorName]['Q'] - if BaseCode==2: #max is in MVA - PF = Pinit/((Pinit**2+Qinit**2)**0.5) - Pmax = PF*Mbase - else: - Pmax = Mbase - I_list = [_i]*9 - F_list = [_f]*23 - F_list[2]=x_copy[ite][i]*Pmax*0.7 - psspy.induction_machine_chng(busNum,ID,I_list,F_list) - if PSSEParams['ALGORITHM']=='Optimum Power Flow': - if Debug: - print 'OPF motor load 2a' - psspy.bsys(3,0,[0.0,0.0],0,[],1,[1],0,[],0,[]) - psspy.set_opf_report_subsystem(3,0) - psspy.nopf(0,1) # Lancement OPF - postOPFinitialization(doci,all_inputs_init,AdjLoadTables,init_gen=False,init_bus=False,init_fxshnt=True,init_swshnt=False,init_load=True,init_P0=False) - #psspy.fnsl([0, _i, 0, 0, 0, 0, _i,_i]) # Load flow Newton Raphson - else: - #economic dispatch - EcdErrorCodes, LFcode, Plimit, Qlimit = EconomicDispatch(doci, ecd_file, LossesRatio, TapChange) - if np.any(np.array(EcdErrorCodes)!=0): - print "Error in economic dispatch." - - for MotorName in MotorList: - busNum = dico['Motors'][MotorName]['NUMBER'] - ID = dico['Motors'][MotorName]['ID'] - Mbase = dico['Motors'][MotorName]['MBASE'] - BaseCode = dico['Motors'][MotorName]['BASECODE'] - Pinit = dico['Motors'][MotorName]['P'] - Qinit = dico['Motors'][MotorName]['Q'] - if BaseCode==2: #max is in MVA - PF = Pinit/((Pinit**2+Qinit**2)**0.5) - Pmax = PF*Mbase - else: - Pmax = Mbase - I_list = [_i]*9 - F_list = [_f]*23 - F_list[2]=x_copy[ite][i]*Pmax*0.4 - psspy.induction_machine_chng(busNum,ID,I_list,F_list) - if PSSEParams['ALGORITHM']=='Optimum Power Flow': - if Debug: - print 'OPF motor load 2b' - psspy.bsys(3,0,[0.0,0.0],0,[],1,[1],0,[],0,[]) - psspy.set_opf_report_subsystem(3,0) - psspy.nopf(0,1) # Lancement OPF - postOPFinitialization(doci,all_inputs_init,AdjLoadTables,init_gen=False,init_bus=False,init_fxshnt=True,init_swshnt=False,init_load=True,init_P0=False) - #psspy.fnsl([0, _i, 0, 0, 0, 0, _i,_i]) # Load flow Newton Raphson - else: - #economic dispatch - EcdErrorCodes, LFcode, Plimit, Qlimit = EconomicDispatch(doci, ecd_file, LossesRatio, TapChange) - if np.any(np.array(EcdErrorCodes)!=0): - print "Error in economic dispatch." - - for MotorName in MotorList: - busNum = dico['Motors'][MotorName]['NUMBER'] - ID = dico['Motors'][MotorName]['ID'] - Mbase = dico['Motors'][MotorName]['MBASE'] - BaseCode = dico['Motors'][MotorName]['BASECODE'] - Pinit = dico['Motors'][MotorName]['P'] - Qinit = dico['Motors'][MotorName]['Q'] - if BaseCode==2: #max is in MVA - PF = Pinit/((Pinit**2+Qinit**2)**0.5) - Pmax = PF*Mbase - else: - Pmax = Mbase - I_list = [_i]*9 - F_list = [_f]*23 - F_list[2]=x_copy[ite][i]*Pmax - psspy.induction_machine_chng(busNum,ID,I_list,F_list) - x2.append(x_copy[ite][i]) #store values sampled for logger function - # Generator Law : Change generation level - #if dico['Laws'][law]['ComponentType']=='Generator' and ('N_1' not in law) and ('out' not in law.lower()): - if dico['Laws'][law]['ComponentType']=='Generator' and ('Availability' not in dico['Laws'][law]['Type']): - GenList = dico['Laws'][law]['Generator'] - for GenName in GenList: - busNum = dico['Generators'][GenName]['NUMBER'] - ID = dico['Generators'][GenName]['ID'] - Pmax = dico['Generators'][GenName]['PMAX'] - Pmin = dico['Generators'][GenName]['PMIN'] - if Pmin < 0 and abs(Pmin) > Pmax: #motor, not generator - psspy.machine_chng_2(busNum,ID,[_i,_i,_i,_i,_i,_i],\ - [x_copy[ite][i]*Pmin,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) - else: #generator - psspy.machine_chng_2(busNum,ID,[_i,_i,_i,_i,_i,_i],\ - [x_copy[ite][i]*Pmax,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) - x2.append(x_copy[ite][i]) #store values sampled for logger function - #Line or Transformer Availability Law: disconnect component if sample=0 - elif dico['Laws'][law]['ComponentType']=='Line' or dico['Laws'][law]['ComponentType']=='Transformer': - compType = dico['Laws'][law]['ComponentType'] - CompList = dico['Laws'][law][compType] - - for Name in CompList: - from_bus = dico[compType + 's'][Name]['FROMNUMBER'] - to_bus = dico[compType+ 's'][Name]['TONUMBER'] - - ID = dico[compType+ 's'][Name]['ID'] - if compType=='Line': - psspy.branch_chng(from_bus,to_bus,ID,[x_copy[ite][i],_i,_i,_i,_i,_i],\ - [_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) - elif compType=='Transformer': - if dico[compType+ 's'][Name]['#WIND']==2: - i_args = [_i]*15 - i_args[0]=status - f_args = [_f]*24 - c_args = [_s]*2 - psspy.two_winding_chng_4(from_bus,to_bus,ID,i_args,f_args,c_args) - elif dico[compType+ 's'][Name]['#WIND']==3: - three_bus = dico[compType + 's'][Name]['3NUMBER'] - i_args = [_i]*12 - i_args[7]=status - f_args = [_f]*17 - c_args = [_s]*2 - psspy.three_wnd_imped_chng_3(from_bus,to_bus,three_bus,ID,i_args,f_args,c_args) - x2.append(x_copy[ite][i]) #store values sampled for logger function - - #Generator or Load or Motor Availability Law: disconnect component if sample = 0 - #elif (dico['Laws'][law]['ComponentType']=='Generator' and ('N_1' in law or 'out' in law.lower())) or\ - # (dico['Laws'][law]['ComponentType']=='Load' and ('N_1' in law or 'out' in law.lower())) or\ - # (dico['Laws'][law]['ComponentType']=='Motor' and ('N_1' in law or 'out' in law.lower())): - elif (dico['Laws'][law]['ComponentType']=='Generator' and ('Availability' in dico['Laws'][law]['Type'])) or\ - (dico['Laws'][law]['ComponentType']=='Load' and ('Availability' in dico['Laws'][law]['Type'])) or\ - (dico['Laws'][law]['ComponentType']=='Motor' and ('Availability' in dico['Laws'][law]['Type'])): - compType = dico['Laws'][law]['ComponentType'] - CompList = dico['Laws'][law][compType] - - for Name in CompList: - busNum = dico[compType + 's'][Name]['NUMBER'] - ID = dico[compType + 's'][Name]['ID'] - if compType=='Generator': - psspy.machine_chng_2(busNum,ID,[x_copy[ite][i],_i,_i,_i,_i,_i],\ - [_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) - elif compType=='Load': - psspy.load_chng_4(busNum,ID,[x_copy[ite][i],_i,_i,_i,_i,_i],[_f,_f,_f,_f,_f,_f]) - - elif compType=='Motor': - psspy.induction_machine_chng(busNum,ID,[x_copy[ite][i],_i,_i,_i,_i,_i,_i,_i,_i],[_f]*23) - x2.append(x_copy[ite][i]) #store values sampled for logger function - - #N-1 from file : systematic disconnection of a component - else: #law='N_1_fromFile' - if x_copy[ite][i]<0: - x2.append("") - pass - elif x_copy[ite][i] < len(continLines) : # L'element tire est une ligne - - line_num=int(x_copy[ite][i]) - line_name=continLines[int(line_num)] - - from_bus=dico['Lines'][line_name]['FROMNUMBER'] - to_bus=dico['Lines'][line_name]['TONUMBER'] - br_id=dico['Lines'][line_name]['ID'] - psspy.branch_chng(from_bus,to_bus,br_id,[0,_i,_i,_i,_i,_i],\ - [ _f, _f, _f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) - x2.append('Line '+str(from_bus)+'-'+str(to_bus)+'#'+str(br_id)) - - elif x_copy[ite][i] < (len(continLines)+len(continGroups)) : - - group_num = int(x_copy[ite][i])-len(continLines) - group_name = continGroups[int(group_num)] - bus_num = dico['Generators'][group_name]['NUMBER'] - bus_id = dico['Generators'][group_name]['ID'] - psspy.machine_chng_2(int(bus_num),str(bus_id),[0,_i,_i,_i,_i,_i],\ - [_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) # Disconnect component - psspy.opf_gendsp_indv(int(bus_num),str(bus_id),_i,0.0) - x2.append('Group '+str(bus_num)+'#'+str(bus_id)) - - elif x_copy[ite][i] < (len(continLines)+len(continGroups)+len(continTransfos)) : - transfo_num=int(x_copy[ite][i])-len(continLines)-len(continGroups) - transfo_name = continTransfos[int(transfo_num)] - from_bus= dico['Transformers'][transfo_name]['FROMNUMBER'] - to_bus=dico['Transformers'][transfo_name]['TONUMBER'] - ID=dico['Transformers'][transfo_name]['ID'] - - if dico['Transformers'][transfo_name]['#WIND']==2: - i_args = [_i]*15 - i_args[0]=0 - f_args = [_f]*24 - c_args = [_s]*2 - psspy.two_winding_chng_4(from_bus,to_bus,ID,i_args,f_args,c_args) - x2.append('Transfo '+str(from_bus)+'-'+str(to_bus)+'#'+str(ID)) - - elif dico['Transformers'][transfo_name]['#WIND']==3: - three_bus = dico['Transformers'][transfo_name]['3NUMBER'] - i_args = [_i]*12 - i_args[7]=0 - f_args = [_f]*17 - c_args = [_s]*2 - psspy.three_wnd_imped_chng_3(from_bus,to_bus,three_bus,ID,i_args,f_args,c_args) - x2.append('Transfo '+str(from_bus)+'-'+str(to_bus)+'-'+str(three_bus)+'#'+str(ID)) - - elif x_copy[ite][i] < (len(continLines)+len(continGroups)+len(continTransfos)+len(continLoads)) : - - load_num = int(x_copy[ite][i])-len(continLines)-len(continGroups)-len(continTransfos) - load_name = continLoads[int(load_num)] - bus_num = dico['Loads'][load_name]['NUMBER'] - ID = dico['Loads'][load_name]['ID'] - psspy.load_chng_4(int(bus_num),str(ID),[0,_i,_i,_i,_i,_i],[_f,_f,_f,_f,_f,_f]) # Disconnect component - x2.append('Load '+str(bus_num)+'#'+str(ID)) - - elif x_copy[ite][i] < (len(continLines)+len(continGroups)+len(continTransfos)+len(continLoads)+len(continMotors)) : - motor_num = int(x_copy[ite][i])-len(continLines)-len(continGroups)-len(continTransfos)-len(continLoads) - motor_name = continMotors[int(motor_num)] - bus_num = dico['Motors'][motor_name]['NUMBER'] - ID = dico['Motors'][motor_name]['ID'] - psspy.induction_machine_chng(int(bus_num),str(ID),[0,_i,_i,_i,_i,_i,_i,_i,_i],[_f]*23) # Disconnect component - x2.append('Motor '+str(bus_num)+'#'+str(ID)) - else : - pass - - psspy.save(doci) #Saving .sav modifications - - if PSSEParams['ALGORITHM']=='Optimum Power Flow': - #save OPF data - allbus=1 - include = [1,1,1,1] #isolated buses, out of service branches, subsystem data, subsystem tie lines - out = 0 #out to file, not window - # if psspy.bsysisdef(0): - # sid = 0 - # else: # Select subsytem with all buses - # sid = -1 - sid = 3 - RopFile = os.path.join(dico['doc_base'],"BaseCase.rop" ) - AlreadyRop=os.path.isfile(RopFile) - if not AlreadyRop: - ierr = psspy.rwop(sid,allbus,include,out,RopFile) #write rop file - - ok = True - - if Debug: - print "Finished applying laws" - loadShed = [] - fxshnt = [] - indexLS = [] - indexFS = [] - indicLS = 0 - indicFS = 0 - xstrings = ['mvaact'] - ierr, xdata1 = psspy.aloadcplx(-1, 1, xstrings) - istrings = ['number'] - ierr, idata = psspy.aloadint(-1, 1, istrings) - cstrings = ['name'] - ierr, cdata = psspy.aloadchar(-1, 1, cstrings) - bistrings = ['number'] - ierr, bidata1 = psspy.afxshuntint(-1, 1, bistrings) - bxstrings = ['shuntnom'] - ierr, bxdata1 = psspy.afxshuntcplx(-1, 1, bxstrings) - bcstrings = ['id'] - ierr, bcdata1 = psspy.afxshuntchar(-1, 1, bcstrings) - #Unit commitment pass only valid for OPF (economic dispatch turns on and off generators) - ##=========================================================================# - if PSSEParams['ALGORITHM']=='Optimum Power Flow': - # First OPF to disconnect all generators at P=0 - if dico['UnitCommitment']: - #increase load by reserve level so that after unit commitment there are enough groups to provide reserve - GenDispatchData, DispTableData, LinCostTables, QuadCostTables, PolyCostTables, GenReserveData, PeriodReserveData,AdjBusShuntData,AdjLoadTables = readOPFdata(RopFile) - ReserveFound=False - TotalReserveLevel = 0 - AllReserveActive = [] - for num in range(1,16): #16 potential reserves defined in OPF - keyname = 'SpinningReserveID_'+str(int(num)) - if PSSEParams.has_key(keyname): - ReserveID = PSSEParams[keyname] - for PRD in PeriodReserveData: - if PRD[0]==ReserveID: - ReserveFound=True - ReserveActive = PRD[3] - ReserveLevel = PRD[1] - AllReserveActive.append(ReserveActive) - TotalReserveLevel += ReserveActive*ReserveLevel - #print('Total Reserve = ', str(TotalReserveLevel)) - if ReserveFound and any(AllReserveActive): - outputs = read_sav(doci) - loads = outputs[4] - total_load = 0 - for load in loads: - total_load += load[1] - - x_with_reserve = (total_load + TotalReserveLevel)/total_load - x_remove_reserve = 1.0/x_with_reserve - for load in loads: - busNum = load[0] - ID = load[5] - P = load[1] - Q = load[2] - psspy.load_chng_4(busNum,ID,[_i,_i,_i,_i,_i,_i],[x_with_reserve*P,x_with_reserve*Q,_f,_f,_f,_f]) - - #set Pmin so necessary units to supply reserve are not disconnected - if ReserveCorrection: - NoDisconnectionAllowedTotal = [] - for res in PeriodReserveData: - ResNum = res[0] - ResLevel = res[1] - ResPeriod = res[2] - InService = res[3] - if InService == 0: - continue - ParticipatingUnits = res[4] - ParticipatingUnitsFull = [] - NoDisconnectionAllowed = [] - for unit in ParticipatingUnits: - busNum = unit[0] - ID = unit[1] - - for gen in GenReserveData: - busNum2 = gen[0] - ID2 = gen[1] - if busNum==busNum2 and ID == ID2: - ramp =gen[2] - #Pmax = gen[3] - break - - for gen in GenDispatchData: - busNum3 = gen[0] - ID3 = gen[1] - if busNum==busNum3 and ID == ID3: - dispatch = gen[2] - dispTable = gen[3] - break - - for dTable in DispTableData: - dispTable2 = dTable[0] - if dispTable == dispTable2: - PmaxTable = dTable[1] - Pmax = PmaxTable #take Pmax from dispatch table to avoid errors - PminTable = dTable[2] - FuelCostScaleCoef = dTable[3] - CurveType = dTable[4] #2 = piece wise linear, - Status = dTable[5] - CostTable = dTable[6] - break - - for table in LinCostTables: - CostTable2 = table[0] - if CostTable2==CostTable: - numpoints = table[1] - points = table[2] - break - - MaxContribution = min(ResPeriod * ramp, Pmax) - - for i,[x_,y_] in enumerate(points): - if x_ > Pmax: - x1 = x_ - y1 = y_ - x0 = points[i-1][0] - y0 = points[i-1][1] - break - y_i = (y1 - y0)*Pmax/(x1-x0) - - if Pmax > 0: - CostCoef = y_i / Pmax - else: - #pdb.set_trace() - CostCoef = 0 - - ParticipatingUnitsFull.append([busNum, ID, Pmax, dispTable, MaxContribution, CostCoef]) - - ParticipatingUnitsFull.sort(key=lambda d: d[-1], reverse=False) - ReserveCapability = 0 - - for unit in ParticipatingUnitsFull: - MaxContribution = unit[4] - if ReserveCapability >= ResLevel: - break - else: - ReserveCapability += MaxContribution - dispTable = unit[3] - Pmax = unit[2] - busNum = unit[0] - ID = unit[1] - NoDisconnectionAllowed.append([busNum, ID]) - Pmin = (DisconnectThreshhold*1.1)*Pmax - psspy.opf_apdsp_tbl(dispTable,[_i,_i,_i],[_f, Pmin,_f]) - - for grp in NoDisconnectionAllowed: - if grp not in NoDisconnectionAllowedTotal: - NoDisconnectionAllowedTotal.append(grp) - - else: - pass - - #psspy.minimize_load_adjustments(int(dico['PSSEParams']['LOADSHEDDING_COST'])) #now apply load shedding - #save new load levels to be able to initialize after opf run - psspy.save(doci) #Saving .sav modifications - all_inputs_base=read_sav(doci) - loads_base=all_inputs_base[4] - all_inputs_init_i =[] - for h, inputs in enumerate(all_inputs_init): - if h != 4: - all_inputs_init_i.append(inputs) - else: - all_inputs_init_i.append(loads_base) - - - if PSSEParams['ALGORITHM']=='Optimum Power Flow': - # First OPF to disconnect all generators at P=0 - if dico['UnitCommitment']: - - if Debug: - print "principal OPF before unit commitment" - - loadShed = [] - fxshnt = [] - - indexLS = [] - indexFS = [] - - indicLS = 0 - indicFS = 0 - - xstrings = ['mvaact'] - ierr, xdata1 = psspy.aloadcplx(-1, 1, xstrings) - istrings = ['number'] - ierr, idata = psspy.aloadint(-1, 1, istrings) - cstrings = ['name'] - ierr, cdata = psspy.aloadchar(-1, 1, cstrings) - - bistrings = ['number'] - ierr, bidata1 = psspy.afxshuntint(-1, 1, bistrings) - bxstrings = ['shuntnom'] - ierr, bxdata1 = psspy.afxshuntcplx(-1, 1, bxstrings) - bcstrings = ['id'] - ierr, bcdata1 = psspy.afxshuntchar(-1, 1, bcstrings) - - psspy.bsys(3,0,[0.0,0.0],0,[],1,[1],0,[],0,[]) - psspy.set_opf_report_subsystem(3,0) - psspy.nopf(0,1) # Lancement OPF - - ok = False - flagLS = 0 - flagFS = 0 - - # solved() => check if last solution attempt reached tolerance - # 0 = met convergence tolerance - # 1 = iteration limit exceeded - # 2 = blown up - # 3 = terminated by non-divergent option - # 4 = terminated by console input - # 5 = singular jacobian matrix or voltage of 0.0 detected - # 6 = inertial power flow dispatch error (INLF) - # 7 = OPF solution met convergence tolerance (NOPF) - # 8 does not exist ? - # 9 = solution not attempted - - if psspy.solved() == 7 or psspy.solved()==0: - pass - else: #run OPF in loop to attempt convergence - postOPFinitialization(doci,all_inputs_init_i,AdjLoadTables,init_gen=False,init_bus=False,init_fxshnt=True,init_swshnt=False,init_load=True,init_P0=False) - MAX_OPF = 5 # 5 = Nombre de lancement max de l'OPF pour atteindre la convergence de l'algorithme - for nbeOPF in range(0, MAX_OPF): - psspy.bsys(3,0,[0.0,0.0],0,[],1,[1],0,[],0,[]) - psspy.set_opf_report_subsystem(3,0) - psspy.nopf(0,1) # Lancement OPF - if psspy.solved()==7 or psspy.solved()==0: - break - else: - postOPFinitialization(doci,all_inputs_init_i,AdjLoadTables,init_gen=False,init_bus=False,init_fxshnt=True,init_swshnt=False,init_load=True,init_P0=False) - - #treat status of OPF - if psspy.solved() == 7 or psspy.solved()==0: - ok = True - elif psspy.solved() == 2: - print "OPF diverged. (before Q control)" - elif psspy.solved()== 3: - print "Terminated by non-divergent option. (before unit commitment)" - elif psspy.solved()== 4: - print "Terminated by console input. (before Q control)" - elif psspy.solved()== 5: - print "Singular jacobian matrix or voltage of 0.0 detected. (before unit commitment)" - elif psspy.solved()== 6: - print "Inertial power flow dispatch error (INLF) (before unit commitment)." - elif psspy.solved()== 8: - print "Solution does not exist. (before unit commitment)" - elif psspy.solved()== 9: - print "Solution not attempted. (before unit commitment)" - elif psspy.solved == 2: - print "OPF diverged. (before unit commitment)" - elif psspy.solved() == 1: #if iteration limit exceeded, try load flow - print "Iteration limit exceeded (before unit commitment), trying load flow." - # Newton-Raphson power flow calculation. Params: - # tap adjustment flag (0 = disable / 1 = enable stepping / 2 = enable direct) - # area interchange adjustement (0 = disable) - # phase shift adjustment (0 = disable) - # dc tap adjustment (1 = enable) - # switched shunt adjustment (1 = enable) - # flat start (0 = default / disabled, 1 = enabled), disabled parce qu'on n'est pas dans une situation de départ - # var limit (default = 99, -1 = ignore limit, 0 = apply var limit immediatly) - # non-divergent solution (0 = disable) - psspy.fnsl([0, _i, 0, 0, 0, 0, _i,_i]) - if psspy.solved() == 0: - ok=True - elif psspy.solved() == 2: - print "Load flow diverged. (before unit commitment)" - if ok: - # Returns an "array of complex values for subsystem loads" - ierr, xdata2 = psspy.aloadcplx(-1, 1, xstrings) # retrieve load MVA # Renvoie une liste de chaque load en format complexe (P+Q) - - # aFxShuntInt: return an array of integer values for subsystem fixed shunts - ierr, bidata2 = psspy.afxshuntint(-1, 1, bistrings) - - # aFxShuntCplx: return an array of complex values for sybsystem fixed shunts - ierr, bxdata2 = psspy.afxshuntcplx(-1, 1, bxstrings) # retrieve bus shunt MVar - - #Fixed shunt strings: return array of ids - ierr, bcdata2 = psspy.afxshuntchar(-1, 1, bcstrings) - - # Extraction of the load shedding quantities - for i in range(len(xdata2[0])): - if np.real(xdata1)[0][i] != np.real(xdata2)[0][i]: # np.real returns the real part of the elements in the given array - indexLS.append(i) - flagLS = 1 # rise flag loadshedding - try: # if / else would be better here ? - flagLS - except: - flagLS = 0 - else: - loadShed.append([position]) # Position seems to correspond to the number of the case we are treating - loadShed[0].extend(['' for i in range(len(indexLS)-1)]) # why [0] ? Maybe it would be better to have 2 lists ? Or a dict ? - loadShed.append([idata[0][i] for i in indexLS]) - loadShed.append([cdata[0][i] for i in indexLS]) - loadShed.append([np.real(xdata1)[0][i] - np.real(xdata2)[0][i] for i in indexLS]) - loadShed.append([np.real(xdata2)[0][i] for i in indexLS]) - indicLS = sum(loadShed[3]) # sum all Effective MW loads - loadShed = zip(*loadShed) # transpose the matrix - - # extraction adj. fixed shunt quantities - if len(bidata1[0]) == len(bidata2[0]): # one first opf may have occured... - # so we check first if both vectors have the same length - - for i in range(len(bxdata2[0])): - if np.imag(bxdata1)[0][i] != np.imag(bxdata2)[0][i]: # search for differences - indexFS.append(i) - flagFS = 1 # rise flag adj. bus shunt - try: - flagFS - except: - flagFS = 0 - else: - bxdata2[0] = [np.imag(bxdata2)[0][i] for i in indexFS] # fulfill output vector - bidata2[0] = [bidata1[0][i] for i in indexFS] - bcdata2[0] = [bcdata1[0][i] for i in indexFS] - g = -1 - while (g <= len(bidata2)): - g += 1 - try: - #if fabs(bxdata2[0][g]) < 1: # discard value in ]-1,1[ - if fabs(bxdata2[0][g]) < 0.001: # discard value in ]-1,1[ - # pdb.set_trace() - bxdata2[0].pop(g) - bidata2[0].pop(g) - bcdata2[0].pop(g) - g -= 1 - except: pass - if bxdata2[0] != []: # Get all fixed shunt buses - fxshnt.append([position]) - fxshnt[0].extend(['' for i in range(len(bxdata2[0]) - 1)]) # Same here => maybe two lists or a dict would be a better choice - fxshnt.append(bidata2[0]) - fxshnt.append(bxdata2[0]) - indicFS = sum(fxshnt[2]) - fxshnt = zip(*fxshnt) # transpose the matrix - flagFS = 1 - else: - flagFS = 0 - - else: # if not same length, bus data corresponding to the adjustable bus shunt have been added to the vector - for i in range(len(bidata1[0])): # remove bus data of bus which are not added after the opf - try: - bxdata2[0].pop(bxdata2[0].index(bxdata1[0][i])) - bidata2[0].pop(bidata2[0].index(bidata1[0][i])) - bcdata2[0].pop(bcdata2[0].index(bcdata1[0][i])) - except: - pass - g = -1 - bx = list(np.imag(bxdata2[0])) # retrieve Mvar - while g <= len(bidata2): - g += 1 - try: - if fabs(bx[g]) < 1: # discard value in ]-1,1[ - bx.pop(g) - bidata2[0].pop(g) - g -= 1 - except: pass - if bx != []: - fxshnt.append([position]) - fxshnt[0].extend(['' for i in range(len(bidata2[0]) - 1)]) - fxshnt.append(bidata2[0]) - fxshnt.append(bx) - indicFS = sum(fxshnt[2]) - fxshnt = zip(*fxshnt) - flagFS = 1 - else: - flagFS = 0 - - - if PSSEParams['SAVE_CASE_BEFORE_UNIT_COMMITMENT']: - psspy.save(doci_beforeUC) - all_inputs = read_sav(doci_beforeUC) - psspy.save(doci) - all_inputs = read_sav(doci) - - buses = all_inputs[0] - lines = all_inputs[1] - transf = all_inputs[2] - plants = all_inputs[3] - loads = all_inputs[4] - shunt = all_inputs[5] - motors = all_inputs[6] - transf3 = all_inputs[7] - swshunt = all_inputs[8] - - - gen_UC_list = [] - for item in plants: - bus = item[0] - status = item[1] - _id = item[2] - pgen = item[3] - qgen = item[4] - pmax = item[6] - name = item[7] - machine_type = item[11] - - #and if a conventional generating unit as specified in Machines tab of PSSE - if machine_type == 0: - if abs(pgen) <= pmax*DisconnectThreshhold: - if status==1: - #print('P < 5% of Pmax and Q > 0 at bus ' + str(bus) + ' gen ' + str(_id) + '--> generator disconnected.') - # disconnect the plant - pgen=0 - qgen=0 - status = 0 - psspy.machine_chng_2(bus, _id, [status,_i,_i,_i,_i,_i],[pgen,qgen,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) - gen_UC_list.append((bus,_id)) - elif machine_type==1: #renewable generator fixed Q limits - if abs(pgen) <= pmax*0.2 and DEWA_PV_Qlimits: #change q limits if P renewable is < 20% Pmax (DEWA grid code) - if status==1: - qmin = -0.04*pmax - qmax = 0.04*pmax - qgen=min(qmax,qgen) - qgen=max(qmin,qgen) - psspy.machine_chng_2(bus, _id, [_i,_i,_i,_i,_i,_i],[_f,qgen,qmax,qmin,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) - if abs(pgen) <= pmax*0.005 and Disconnect_RES: #disconnect if very low P - if status==1: - #print('P < 5% of Pmax and Q > 0 at bus ' + str(bus) + ' gen ' + str(_id) + '--> generator disconnected.') - # disconnect the plant - pgen=0 - qgen=0 - status = 0 - psspy.machine_chng_2(bus, _id, [status,_i,_i,_i,_i,_i],[pgen,qgen,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) - gen_UC_list.append((bus,_id)) - elif machine_type==2: #renewable generator with cos phi control - if abs(pgen) <= pmax*0.005 and Disconnect_RES: #disconnect if very low P - if status==1: - #print('P < 5% of Pmax and Q > 0 at bus ' + str(bus) + ' gen ' + str(_id) + '--> generator disconnected.') - # disconnect the plant - pgen=0 - qgen=0 - status = 0 - psspy.machine_chng_2(bus, _id, [status,_i,_i,_i,_i,_i],[pgen,qgen,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) - gen_UC_list.append((bus,_id)) - elif machine_type==3: #renewable generator with fixed Q based on cos phi control - if abs(pgen) <= pmax*0.005 and Disconnect_RES: #disconnect if very low P - if status==1: - #print('P < 5% of Pmax and Q > 0 at bus ' + str(bus) + ' gen ' + str(_id) + '--> generator disconnected.') - # disconnect the plant - pgen=0 - qgen=0 - status = 0 - psspy.machine_chng_2(bus, _id, [status,_i,_i,_i,_i,_i],[pgen,qgen,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) - gen_UC_list.append((bus,_id)) - elif machine_type==4: #infeed machine that's still considered renewable - if abs(pgen) <= pmax*0.005 and Disconnect_RES: #disconnect if very low P - if status==1: - #print('P < 5% of Pmax and Q > 0 at bus ' + str(bus) + ' gen ' + str(_id) + '--> generator disconnected.') - # disconnect the plant - pgen=0 - qgen=0 - status = 0 - psspy.machine_chng_2(bus, _id, [status,_i,_i,_i,_i,_i],[pgen,qgen,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) - gen_UC_list.append((bus,_id)) - # 3. Affiche Y - sizeY4 = len(shunt) - y_before = np.zeros(2 * sizeY0 + sizeY1 + 3 * sizeY2 + sizeY3 + 2*sizeY6 + sizeY4 + sizeY8 + 3 * sizeY5 + 3 * sizeY7) - z_before = [0]*13 # np.zeros returns a new array of the given shape and type filled with zeros - rate_mat_index = Irate_num + 2 - rate_mat_index_3w = Irate_num + 4 - Ymac_before = np.zeros(sizeY0) - if ok: - # Creates the quantities of interest - for i in range (sizeY2) : - if lines [i][rate_mat_index]>100 : - z_before[0]+=1 # Number of lines above 100% of their limits - for i in range (sizeY5) : - if transf [i][rate_mat_index]>100 : - z_before[1]+=1 # Number of transformers above 100% of their limits - for i in range (sizeY7) : - if transf3 [i][rate_mat_index_3w]>100 : - z_before[1]+=1 # Number of transformers above 100% of their limits (each winding of a 3 winding counted) - - for i in range (sizeY1): - if buses[i][2]>buses[i][5] : - z_before[2]+=1 - if buses[i][2]z_before[6] : - z_before[6]=lines[i][rate_mat_index] # Max flow in lines - for i in range (sizeY5) : - if transf [i][rate_mat_index]>z_before[7] : - z_before[7]=transf[i][rate_mat_index] # Max flow in transformers - for i in range (sizeY7) : - if transf3 [i][rate_mat_index_3w]>z_before[7] : - z_before[7]=transf3[i][rate_mat_index_3w] # Max flow in 3w transformers - - for i in range (sizeY2) : - if lines [i][rate_mat_index]>90 : - z_before[8]+=1 - z_before[8]=z_before[8]-z_before[0] # Number of lines between 90% and 100% of their limits - for i in range (sizeY5) : - if transf [i][rate_mat_index]>90 : - z_before[9]+=1 - for i in range (sizeY7) : - if transf3 [i][rate_mat_index_3w]>90 : - z_before[9]+=1 - - z_before[9]=z_before[9]-z_before[1] # Number of transformers between 90% and 100% of their limits - - z_before[10]=indicFS - - z_before[11]=indicLS - - z_before[12] = str(gen_UC_list) - - # Creates the output vectors - for Pmach in range (sizeY0): - y_before[Pmach]=float(plants[Pmach][3]) - Ymac_before[Pmach]=float(plants[Pmach][3]) - for Qmach in range (sizeY0): - y_before[Qmach+sizeY0]=float(plants[Qmach][4]) - for Vbus in range (sizeY1): - y_before[Vbus+2*sizeY0]=float(buses[Vbus][2]) - for Iline in range (sizeY2): - y_before[Iline+2*sizeY0+sizeY1]=float(lines[Iline][rate_mat_index]) - for Pline in range (sizeY2): - y_before[Pline+2*sizeY0+sizeY1+sizeY2]=float(lines[Pline][6]) - for Qline in range (sizeY2): - y_before[Qline+2*sizeY0+sizeY1+2*sizeY2]=float(lines[Qline][7]) - for Itrans in range (sizeY5): - y_before[Itrans+2*sizeY0+sizeY1+3*sizeY2]=float(transf[Itrans][rate_mat_index]) - for Ptrans in range (sizeY5): - y_before[Ptrans+2*sizeY0+sizeY1+3*sizeY2+sizeY5]=float(transf[Ptrans][6]) - for Qtrans in range (sizeY5): - y_before[Qtrans+2*sizeY0+sizeY1+3*sizeY2+2*sizeY5]=float(transf[Qtrans][7]) - for Itrans in range (sizeY7): - y_before[Itrans+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5]=float(transf3[Itrans][rate_mat_index_3w]) - for Ptrans in range (sizeY7): - y_before[Ptrans+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+sizeY7]=float(transf3[Ptrans][8]) - for Qtrans in range (sizeY7): - y_before[Qtrans+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+2*sizeY7]=float(transf3[Qtrans][9]) - for Pload in range (sizeY3) : - y_before[Pload+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+3*sizeY7]=float(loads[Pload][1]) - for Pmotor in range (sizeY6) : - y_before[Pmotor+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+3*sizeY7+sizeY3]=float(motors[Pmotor][1]) - for Qmotor in range (sizeY6) : - y_before[Qmotor+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+3*sizeY7+sizeY3+sizeY6]=float(motors[Qmotor][2]) - for Qshunt in range (sizeY4) : - y_before[Qshunt+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+3*sizeY7+sizeY3+2*sizeY6]=float(shunt[Qshunt][2]) - for Qshunt in range (sizeY8) : - y_before[Qshunt+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+3*sizeY7+sizeY3+2*sizeY6+sizeY4]=float(swshunt[Qshunt][4]) - nz = len(z_before) - - else : - print 'NON CONVERGENCE BEFORE UNIT COMMITMENT CASE '+str(position)+' CORE '+str(num_pac) - if TStest==1: - MyLogger(x2, y_before, z_before, dico['logCSVfilename_UC'][num_pac], timeVect[ite]) - else: - MyLogger(x2, y_before, z_before, dico['logCSVfilename_UC'][num_pac], position) - - #re-initialize OPF for post-unit commitment - postOPFinitialization(doci,all_inputs_init_i,AdjLoadTables,init_gen=False,init_bus=False,init_fxshnt=True,init_swshnt=False,init_load=True,init_P0=False) - all_inputs = read_sav(doci) - loads = all_inputs[4] - - #return load to original level post spinning reserve correction for unit commitment - for num in range(1,16): - keyname = 'SpinningReserveID_' + str(int(num)) - if PSSEParams.has_key(keyname): - ReserveID = PSSEParams[keyname] - ReserveFound=False - AllReserveActive = [] - for PRD in PeriodReserveData: - if PRD[0]==ReserveID: - ReserveFound=True - ReserveActive = PRD[3] - AllReserveActive.append(ReserveActive) - if ReserveFound and any(AllReserveActive): - for load in loads: - busNum = load[0] - ID = load[5] - P = load[1] - Q = load[2] - psspy.load_chng_4(busNum,ID,[_i,_i,_i,_i,_i,_i],[x_remove_reserve*P,x_remove_reserve*Q,_f,_f,_f,_f]) - psspy.save(doci) - else: - break - - #store loadshedding and added MVAR values for before UC - loadShed_beforeUC = loadShed - fxshnt_beforeUC = fxshnt - indexLS_beforeUC = indexLS - indexFS_beforeUC = indexFS - - indicLS_beforeUC = indicLS - indicFS_beforeUC = indicFS - - - - # Unit commitment pass only valid for OPF (economic dispatch turns on and off generators) - ##=========================================================================# - # nvm on FAIT deux passages, un puis on regarde les groupes P==0 Q!=0, on les déconnecte et on refait l'OPF - # Et on log : le % de cas où ça arrive, - # Combien de puissance réactive il nous faut en moyenne, - # Quelles sont les machines qui font ça - loadShed = [] - fxshnt = [] - indexLS = [] - indexFS = [] - indicLS = 0 - indicFS = 0 - flagLS = 0 - flagFS = 0 - ok = False - - xstrings = ['mvaact'] - ierr, xdata1 = psspy.aloadcplx(-1, 1, xstrings) - istrings = ['number'] - ierr, idata = psspy.aloadint(-1, 1, istrings) - cstrings = ['name'] - ierr, cdata = psspy.aloadchar(-1, 1, cstrings) - bistrings = ['number'] - ierr, bidata1 = psspy.afxshuntint(-1, 1, bistrings) - bxstrings = ['shuntnom'] - ierr, bxdata1 = psspy.afxshuntcplx(-1, 1, bxstrings) - bcstrings = ['id'] - ierr, bcdata1 = psspy.afxshuntchar(-1, 1, bcstrings) - - if Debug: - print "got to principal OPF/LF" - - #Solve OPF - if PSSEParams['ALGORITHM']=='Optimum Power Flow': - psspy.bsys(3,0,[0.0,0.0],0,[],1,[1],0,[],0,[]) - psspy.set_opf_report_subsystem(3,0) - psspy.nopf(0,1) # Lancement OPF - flagLS = 0 - flagFS = 0 - ok = False - #psspy.fnsl([0, _i, 0, 0, 0, 0, _i,_i]) # Load flow Newton Raphson - - # solved() => check if last solution attempt reached tolerance - # 0 = met convergence tolerance - # 1 = iteration limit exceeded - # 2 = blown up - # 3 = terminated by non-divergent option - # 4 = terminated by console input - # 5 = singular jacobian matrix or voltage of 0.0 detected - # 6 = inertial power flow dispatch error (INLF) - # 7 = OPF solution met convergence tolerance (NOPF) - # 8 does not exist ? - # 9 = solution not attempted - if psspy.solved() == 7 or psspy.solved()==0: - pass - else: #run OPF in loop to attempt convergence - postOPFinitialization(doci,all_inputs_init_i,AdjLoadTables,init_gen=False,init_bus=False,init_fxshnt=True,init_swshnt=False,init_load=True,init_P0=False) - MAX_OPF = 5 # 5 = Nombre de lancement max de l'OPF pour atteindre la convergence de l'algorithme - for nbeOPF in range(0, MAX_OPF): - psspy.bsys(3,0,[0.0,0.0],0,[],1,[1],0,[],0,[]) - psspy.set_opf_report_subsystem(3,0) - psspy.nopf(0,1) # Lancement OPF - if psspy.solved()==7 or psspy.solved()==0: - break - else: - postOPFinitialization(doci,all_inputs_init_i,AdjLoadTables,init_gen=False,init_bus=False,init_fxshnt=True,init_swshnt=False,init_load=True,init_P0=False) - - #treat OPF status code - if psspy.solved() == 7 or psspy.solved() == 0: - ok = True - elif psspy.solved() == 2: - print "OPF diverged." - elif psspy.solved()== 3: - print "Terminated by non-divergent option." - elif psspy.solved()== 4: - print "Terminated by console input." - elif psspy.solved()== 5: - print "Singular jacobian matrix or voltage of 0.0 detected." - elif psspy.solved()== 6: - print "Inertial power flow dispatch error (INLF)." - elif psspy.solved()== 8: - print "Solution does not exist." - elif psspy.solved()== 9: - print "Solution not attempted." - elif psspy.solved() == 1: #if iteration limit exceeded, try load flow - print "Iteration limit exceeded, trying load flow (CASE " + str(ite) + ")." - # Newton-Raphson power flow calculation. Params: - # tap adjustment flag (0 = disable / 1 = enable stepping / 2 = enable direct) - # area interchange adjustement (0 = disable) - # phase shift adjustment (0 = disable) - # dc tap adjustment (1 = enable) - # switched shunt adjustment (1 = enable) - # flat start (0 = default / disabled, 1 = enabled), disabled parce qu'on n'est pas dans une situation de départ - # var limit (default = 99, -1 = ignore limit, 0 = apply var limit immediatly) - # non-divergent solution (0 = disable) - psspy.fnsl([0, _i, 0, 0, 0, 0, _i,_i]) - if psspy.solved() == 0: - ok=True - elif psspy.solved() == 2: - print "Load flow diverged" - # else: - # #PlimitList = [] - # #QlimitList = [] - # if Debug: - # print "Got to principal economic dispatch" - # #economic dispatch - # EcdErrorCodes, LFcode, Plimit, Qlimit = EconomicDispatch(doci, ecd_file, LossesRatio, TapChange) - # #PlimitList.append(Plimit) - # #QlimitList.append(Qlimit) - # if Debug: - # print "Ran principal economic dispatch" - # if np.any(np.array(EcdErrorCodes)!=0): - # print "Error in economic dispatch." - # elif LFcode != 0: - # print "Load flow did not converge" - # else: - # ok = True - # - # if Plimit == True: - # print "Swing generator exceeds active power limits after economic dispatch." - # if Qlimit == True: - # print "Swing generator exceeds reactive power limits after economic dispatch." - if ok==True: - ierr, xdata2 = psspy.aloadcplx(-1, 1, xstrings) # retrieve load MVA # Renvoie une liste de chaque load en format complexe (P+Q) - ierr, bidata2 = psspy.afxshuntint(-1, 1, bistrings) - ierr, bxdata2 = psspy.afxshuntcplx(-1, 1, bxstrings) # retrieve bus shunt MVar - ierr, bcdata2 = psspy.afxshuntchar(-1, 1, bcstrings) - # Extraction of the load shedding quantities - for i in range(len(xdata2[0])): - if np.real(xdata1)[0][i] != np.real(xdata2)[0][i]: # np.real returns the real part of the elements in the given array - indexLS.append(i) - flagLS = 1 # raise flag loadshedding - try: # if / else would be better here ? - flagLS - except: - flagLS = 0 - else: - loadShed.append([position]) # Position seems to correspond to the number of the case we are treating - loadShed[0].extend(['' for i in range(len(indexLS)-1)]) # why [0] ? Maybe it would be better to have 2 lists ? Or a dict ? - loadShed.append([idata[0][i] for i in indexLS]) - loadShed.append([cdata[0][i] for i in indexLS]) - loadShed.append([np.real(xdata1)[0][i] - np.real(xdata2)[0][i] for i in indexLS]) #loadShed[3] - loadShed.append([np.real(xdata2)[0][i] for i in indexLS]) #loadShed[4] - indicLS = sum(loadShed[3]) # sum all Effective MW loads #sum(loadShed[3]) - loadShed = zip(*loadShed) # transpose the matrix - - # extraction adj. fixed shunt quantities - if len(bidata1[0]) == len(bidata2[0]): # one first opf may have occured... - # so we check first if both vectors have the same length - - for i in range(len(bxdata2[0])): - if np.imag(bxdata1)[0][i] != np.imag(bxdata2)[0][i]: # search for differencies - indexFS.append(i) - flagFS = 1 # rise flag adj. bus shunt - try: - flagFS - except: - flagFS = 0 - else: - bxdata2[0] = [np.imag(bxdata2)[0][i] for i in indexFS] # fulfill output vector - bidata2[0] = [bidata1[0][i] for i in indexFS] - bcdata2[0] = [bcdata1[0][i] for i in indexFS] - g = -1 - while (g <= len(bidata2)): - g += 1 - try: - #if fabs(bxdata2[0][g]) < 1: # discard value in ]-1,1[ - if fabs(bxdata2[0][g]) < 0.001: # discard value in ]-1,1[ - # pdb.set_trace() - bxdata2[0].pop(g) - bidata2[0].pop(g) - bcdata2[0].pop(g) - g -= 1 - except: pass - if bxdata2[0] != []: # Get all fixed shunt buses - fxshnt.append([position]) - fxshnt[0].extend(['' for i in range(len(bxdata2[0]) - 1)]) # Same here => maybe two lists or a dict would be a better choice - fxshnt.append(bidata2[0]) - fxshnt.append(bxdata2[0]) - indicFS = sum(fxshnt[2]) - fxshnt = zip(*fxshnt) # transpose the matrix - flagFS = 1 - else: - flagFS = 0 - - else: # if not same length, bus data corresponding to the adjusted bus shunt have been added to the vector - for i in range(len(bidata1[0])): # remove bus data of bus which are not added after the opf - try: - bxdata2[0].pop(bxdata2[0].index(bxdata1[0][i])) - bidata2[0].pop(bidata2[0].index(bidata1[0][i])) - bcdata2[0].pop(bcdata2[0].index(bcdata1[0][i])) - except: - pass - g = -1 - bx = list(np.imag(bxdata2[0])) # retrieve Mvar - while g <= len(bidata2): - g += 1 - try: - if fabs(bx[g]) < 1: # discard value in ]-1,1[ - bx.pop(g) - bidata2[0].pop(g) - g -= 1 - except: pass - if bx != []: - fxshnt.append([position]) - fxshnt[0].extend(['' for i in range(len(bidata2[0]) - 1)]) - fxshnt.append(bidata2[0]) - fxshnt.append(bx) - indicFS = sum(fxshnt[2]) - fxshnt = zip(*fxshnt) - flagFS = 1 - else: - flagFS = 0 - - - psspy.save(doci) - all_inputs=read_sav(doci) - buses = all_inputs[0] - lines = all_inputs[1] - transf = all_inputs[2] - plants = all_inputs[3] - loads = all_inputs[4] - shunt = all_inputs[5] - motors = all_inputs[6] - transf3=all_inputs[7] - swshunt = all_inputs[8] - - #pdb.set_trace() - - # 3. Affiche Y - sizeY4 = len(shunt) - y = np.zeros(2 * sizeY0 + sizeY1 + 3 * sizeY2 + sizeY3 + 2*sizeY6 + sizeY4 + sizeY8 + 3 * sizeY5+ 3 * sizeY7) - z = np.zeros(12+ 2*int(PSSEParams['ALGORITHM']=='Economic Dispatch and Power Flow')) # np.zeros returns a new array of the given shape and type filled with zeros - rate_mat_index = Irate_num + 2 - rate_mat_index_3w = Irate_num + 4 - Ymac = np.zeros(sizeY0) - if ok: - # Creates the quantities of interest - for i in range (sizeY2) : - if lines [i][rate_mat_index]>100 : - z[0]+=1 # Number of lines above 100% of their limits - for i in range (sizeY5) : - if transf [i][rate_mat_index]>100 : - z[1]+=1 # Number of transformers above 100% of their limits - for i in range (sizeY7) : - if transf3 [i][rate_mat_index_3w]>100 : - z[1]+=1 # Add number of 3w transformers above 100% of their limits - for i in range (sizeY1): - if buses[i][2]>buses[i][5] : - z[2]+=1 - if buses[i][2]z[6] : - z[6]=lines[i][rate_mat_index] # Max flow in lines - for i in range (sizeY5) : - if transf [i][rate_mat_index]>z[7] : - z[7]=transf[i][rate_mat_index] # Max flow in transformers - for i in range (sizeY7) : - #pdb.set_trace() - if transf [i][rate_mat_index]>z[7] : - z[7]=transf3[i][rate_mat_index_3w] # Max flow in 3w transformers - for i in range (sizeY2) : - if lines [i][rate_mat_index]>90 : - z[8]+=1 - z[8]=z[8]-z[0] # Number of lines between 90% and 100% of their limits - for i in range (sizeY5) : - if transf [i][rate_mat_index]>90 : - z[9]+=1 - for i in range (sizeY7) : - if transf3 [i][rate_mat_index_3w]>90 : - z[9]+=1 - z[9]=z[9]-z[1] # Number of transformers between 90% and 100% of their limits - - z[10]=indicFS - - z[11]=indicLS - - # if PSSEParams['ALGORITHM']=='Economic Dispatch and Power Flow': - # z[12] = int(Plimit) - # z[13] = int(Qlimit) - - # Creates the output vectors - for Pmach in range (sizeY0): - y[Pmach]=float(plants[Pmach][3]) - Ymac[Pmach]=float(plants[Pmach][3]) - for Qmach in range (sizeY0): - y[Qmach+sizeY0]=float(plants[Qmach][4]) - for Vbus in range (sizeY1): - y[Vbus+2*sizeY0]=float(buses[Vbus][2]) - for Iline in range (sizeY2): - y[Iline+2*sizeY0+sizeY1]=float(lines[Iline][rate_mat_index]) - for Pline in range (sizeY2): - y[Pline+2*sizeY0+sizeY1+sizeY2]=float(lines[Pline][6]) - for Qline in range (sizeY2): - y[Qline+2*sizeY0+sizeY1+2*sizeY2]=float(lines[Qline][7]) - for Itrans in range (sizeY5): - y[Itrans+2*sizeY0+sizeY1+3*sizeY2]=float(transf[Itrans][rate_mat_index]) - for Ptrans in range (sizeY5): - y[Ptrans+2*sizeY0+sizeY1+3*sizeY2+sizeY5]=float(transf[Ptrans][6]) - for Qtrans in range (sizeY5): - y[Qtrans+2*sizeY0+sizeY1+3*sizeY2+2*sizeY5]=float(transf[Qtrans][7]) - for Itrans in range (sizeY7): - y[Itrans+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5]=float(transf3[Itrans][rate_mat_index_3w]) - for Ptrans in range (sizeY7): - y[Ptrans+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+sizeY7]=float(transf3[Ptrans][8]) - for Qtrans in range (sizeY7): - y[Qtrans+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+2*sizeY7]=float(transf3[Qtrans][9]) - for Pload in range (sizeY3) : - y[Pload+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+3*sizeY7]=float(loads[Pload][1]) - for Pmotor in range (sizeY6) : - y[Pmotor+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+3*sizeY7+sizeY3]=float(motors[Pmotor][1]) - for Qmotor in range (sizeY6) : - y[Qmotor+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+3*sizeY7+sizeY3+sizeY6]=float(motors[Qmotor][2]) - for Qshunt in range (sizeY4) : - y[Qshunt+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+3*sizeY7+sizeY3+2*sizeY6]=float(shunt[Qshunt][2]) - for Qshunt in range (sizeY8) : - y[Qshunt+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+3*sizeY7+sizeY3+2*sizeY6+sizeY4]=float(swshunt[Qshunt][4]) - - nz = len(z) - - else : - print ('NON CONVERGENCE CASE '+str(position)+' CORE '+str(num_pac)) - - if dico['UnitCommitment']: - Output_beforeUC.append(z_before)#append the output - Pmachine_beforeUC.append(Ymac_before) - LS_beforeUC.append(indicLS_beforeUC) - FS_beforeUC.append(indicFS_beforeUC) - LStable_beforeUC.extend(loadShed_beforeUC) - FStable_beforeUC.extend(fxshnt_beforeUC) - - Output.append(z)#append the output - Pmachine.append(Ymac) - LS.append(indicLS) - FS.append(indicFS) - LStable.extend(loadShed) - FStable.extend(fxshnt) - - if TStest==1: - MyLogger(x2,y,z,logCSVfilename[num_pac],timeVect[ite]) - else: - MyLogger(x2,y,z,logCSVfilename[num_pac],position) #for each iteration write in the CSV - -## if dico['TStest']==1: -## sys.stdout.close() - return inputSample, Output, Pmachine, LS, FS, LStable, FStable, Output_beforeUC, Pmachine_beforeUC, LS_beforeUC, FS_beforeUC, LStable_beforeUC, FStable_beforeUC - -## except Exception,e: -## print e -## a=[] -## return a - -def create_dist(dico): - - NumLaws = len(dico['Laws']) + int(dico['N_1_fromFile']) - - #Create a correlation matrix as copulas - CorrMatrixNames = dico['CorrMatrix']['laws'] - CorrMatrix = dico['CorrMatrix']['matrix'] - corr=CorrelationMatrix(NumLaws)#Openturns - - # Create a collection of the marginal distributions - collectionMarginals = DistributionCollection(NumLaws)#Openturns - - distributionX = [] - for i,key in enumerate(CorrMatrixNames): - data, [time_serie, time_serie_file] = getUserLaw(dico['Laws'][key]) - distributionX.append( data ) - collectionMarginals[i] = Distribution(data) - - #add N_1 components entered as Files - if dico['N_1_fromFile']==True: - continTuples = [] - for j in range(len(dico['continVal'])): - continTuples.append((dico['continVal'][j],dico['continProb'][j])) - data = getUserDefined(continTuples) - distributionX.append(data) - collectionMarginals[i+1] = Distribution(data) - CorrMatrixNames.append('N_1_fromFile') - CorrMatrixEx = np.hstack((CorrMatrix, np.zeros((NumLaws-1,1)))) #assume no correlation between N-1 and other laws - LastLine = np.hstack((np.zeros((1,NumLaws-1)),np.ones((1,1)))) - CorrMatrixEx = np.vstack((CorrMatrixEx, LastLine)) - CorrMatrix = CorrMatrixEx - (Nrows, Ncols) = np.shape(CorrMatrixEx) - else: - (Nrows, Ncols) = np.shape(CorrMatrix) - for i in range(Nrows): - for j in range(Ncols): - corr[i,j]=CorrMatrix[i,j] - - corr2= NormalCopula.GetCorrelationFromSpearmanCorrelation(corr) - copula=Copula(NormalCopula(corr2)) - #copula=Copula(NormalCopula(corr)) - - # Create the input probability distribution, args are the distributions, the correlation laws - inputDistribution = ComposedDistribution(collectionMarginals, copula) - - return inputDistribution - -def Calculation(dico,data1,msg): - - - os.chdir(dico['doc_base']) #to work in correct directory -## sys.stdout=open('process num'+str(os.getpid())+'_package '+\ -## str(dico['num_pac'])+'.out','w') - #pdb.set_trace() - flag2=dico['flag2'] - inputDistribution=create_dist(dico) #create new distribution - #initialization - LStable=[] - FStable=[] - output=[] - inputSample=[] - Pmachine=[] - - LStable_beforeUC=[] - FStable_beforeUC=[] - output_beforeUC=[] - Pmachine_beforeUC=[] - - outputSampleAll=NumericalSample(0,12 + 2*int(dico['PSSEParams']['ALGORITHM']=='Economic Dispatch and Power Flow')) - - RandomGenerator.SetSeed(os.getpid()) - Message=msg.get() - print(Message+'=======OK') - - - while(Message !='stop'): - myMCE = MonteCarloExperiment(inputDistribution,dico['lenpac']) #create new sample - inputSamp = myMCE.generate() - - try: - Message=msg.get(block=False) - if Message=='stop': break - except: - pass - res=PSSEFunct(dico.copy(),inputSamp) #launch PSSEFunct (OPF) - #subprocess.Popen(['c:/python34/python.exe','PFfunction.py']) - dico['position']+=dico['lenpac'] - # 0 1 2 3 4 5 6 - #inputSample, Output, Pmachine, LS, FS, LStable, FStable, - # 7 8 9 10 11 12 - #Output_beforeUC, Pmachine_beforeUC, LS_beforeUC, FS_beforeUC, LStable_beforeUC, FStable_beforeUC - for result in res[1]: - outputSampleAll.add(NumericalPoint(result)) #create a Numerical Sample variable - - if (flag2): - LS=(np.mean(res[3])) #mean per package - FS=(np.mean(res[4])) #mean per package - z=[LS,FS] - data1.put(z) - sleep(1) - - #if criteria on nbeTension and NbeTransit - else: - NbeTransit=(float(NumericalPoint(1,outputSampleAll.computeMean()[0])[0])) #mean per package - NbeTension=(float(NumericalPoint(1,outputSampleAll.computeMean()[1])[0])) - z=[NbeTransit,NbeTension] - data1.put(z) - sleep(1) - - inputSample.extend(res[0]) - - LStable.extend(res[5]) - FStable.extend(res[6]) - output.extend(res[1]) - Pmachine.extend(res[2]) - - LStable_beforeUC.extend(res[11]) - FStable_beforeUC.extend(res[12]) - output_beforeUC.extend(res[7]) - Pmachine_beforeUC.extend(res[8]) - - if msg.empty(): - Message = "empty" - else: - Message=msg.get(block=True,timeout=2) - print 'MSG is '+str(Message)+' time: '+str(strftime("%Hh%Mm%S", gmtime())) - -# sys.stdout.close() - - ## #write summary tables for before UC - if dico['UnitCommitment']: - f=open(dico['logCSVfilename_UC'][dico['num_pac']],'a') - f.write("\n Summary Table for MW Load Adjustments;;;;;;;;Summary Table for Added Shunt (Mvar)\n") - f.write("Iteration;;Bus Number;Name;Load Shed;Remaining Load;;;Iteration;;Bus Number;Final \n") - for i in range(max(len(LStable_beforeUC),len(FStable_beforeUC))): - try: - f.write('{0};;{1};{2};{3};{4}'.format(LStable_beforeUC[i][0],LStable_beforeUC[i][1]\ - ,LStable_beforeUC[i][2],LStable_beforeUC[i][3],LStable_beforeUC[i][4])) - except: - f.write(';;;;;') - - try: - f.write(';;;{0};;{1};{2} \n'.format(FStable_beforeUC[i][0],FStable_beforeUC[i][1],FStable_beforeUC[i][2])) - except: - f.write('\n') - f.write("\n\n") - f.close() - - ## #write summary tables - f=open(dico['logCSVfilename'][dico['num_pac']],'a') - f.write("\n Summary Table for MW Load Adjustments;;;;;;;;Summary Table for Added Shunt (Mvar)\n") - f.write("Iteration;;Bus Number;Name;Load Shed;Remaining Load;;;Iteration;;Bus Number;Final \n") - for i in range(max(len(LStable), len(FStable))): - try: - f.write('{0};;{1};{2};{3};{4}'.format(LStable[i][0],LStable[i][1]\ - ,LStable[i][2],LStable[i][3],LStable[i][4])) - except: - f.write(';;;;;') - try: - f.write(';;;{0};;{1};{2} \n'.format(FStable[i][0],FStable[i][1],FStable[i][2])) - except: - f.write('\n') - f.write("\n\n") - f.close() - - - - return output, inputSample,Pmachine - -class NonBlockingStreamReader(): #class object to read in a stdout process - - def __init__(self, stream): - ''' - stream: the stream to read from. - Usually a process' stdout or stderr. - ''' - - self._s = stream - self._q = Queue() - - def _populateQueue(stream, queue): - ''' - Collect lines from 'stream' and put them in 'queue'. - ''' - - while True: - line = stream.read() - if line: - queue.put(line) - else: - pass - - self._t = Thread(target = _populateQueue, - args = (self._s, self._q)) - self._t.daemon = True - self._t.start() #start collecting lines from the stream - - def readline(self, timeout = None): - try: - return self._q.get(block = timeout is not None, - timeout = timeout) - except Empty: - return None - - -def Convergence(data2,msg,OPF,nb_fix,cmd_Path): - - LS=[] - FS=[] - MoyTension=[] - MoyTransit=[] - MoyCumuLS=[] - MoyCumuFS=[] - NbeTension=[] - NbeTransit=[] - Ind1=[] - Ind2=[] - ind=1 - t=0 - p=subprocess.Popen(['python',cmd_Path],stdout=subprocess.PIPE) #launch subprocess - nbsr=NonBlockingStreamReader(p.stdout) #monitor subprocess stdout - - print 'Calculating convergence criteria\n' - while(ind): - - output=nbsr.readline(0.1) - if output: - print 'Simulation Interrupting.....' - break - - for i in range(multiprocessing.cpu_count()*3): #put 'ok' in the queue three times the number of cores - msg.put('ok') - - debut=data2.get(block=True) - t+=1 - print 'Package '+str(t) - - if (OPF): #if criteria on Load shed and mvar - LS.append(debut[0]) - FS.append(debut[1]) - - MoyCumuLS.append(np.mean(LS[0:t])) - MoyCumuFS.append(np.mean(FS[0:t])) - - if t==1: - indice1=1 - indice2=1 - else: - indice1=np.std(MoyCumuLS) #calculate stop criterion for load shedding - indice2=np.std(MoyCumuFS) #calculate stop criterion for mvar - - Ind1.append(indice1) - Ind2.append(indice2) - print 'indicator Load Shedding= '+str(indice1)+';'+' indicator Added Mvar= '+str(indice2)+'\n' - - if (indice1<0.2) and (indice2<0.015) and nb_fix==0: - ind=0 - break - elif len(Ind1)==nb_fix: - break - else: - NbeTransit.append(debut[0]) - NbeTension.append(debut[1]) - - MoyTension.append(np.mean(NbeTension[0:len(NbeTension)])) - MoyTransit.append(np.mean(NbeTransit[0:len(NbeTransit)])) - - if t==1: - indice1=1 - indice2=1 - else: - indice1=np.std(MoyTension) #calculate stop criterion for tension - indice2=np.std(MoyTransit) #calculate stop criterion for transit - - Ind1.append(indice1) - Ind2.append(indice2) - print 'indicator Nbe Tension= '+str(indice1)+' indicator Transit= '+str(indice2)+'\n' - - if (indice1<0.01) and (indice2<0.01) and nb_fix==0: - ind=0 - break - elif len(Ind1)==nb_fix: - break - - while msg.empty()==False : #flush the queue - msg.get() - # print(msg.qsize()) - for i in range(100): #put a lot of 'stop's in the queue to make all processes stop - msg.put_nowait('stop') - # print(msg.qsize()) - - p.terminate() - - return Ind1,Ind2 +# -*- coding: utf-8 -*- +""" +Created on Mon Jun 03 15:31:42 2013 + +@author: B31272 + +Fonctions de support +""" +import os,sys,random,string +import PSENconfig +sys.path.append(PSENconfig.Dico['DIRECTORY']['PSSPY_path']) +os.environ['PATH'] = PSENconfig.Dico['DIRECTORY']['PSSE_path'] + ";"+ os.environ['PATH'] +import psspy +import pssarrays +import redirect + + +import pdb +import numpy as np +from math import * +from decimal import * +from openturns import * +from time import sleep, strftime, gmtime +import multiprocessing +from threading import Thread +from Queue import Queue, Empty + +Debug = False #debug mode for PSSEFunct +Disconnect_RES = False #disconnect renewable generators when generate 0 MW +DEWA_PV_Qlimits = True #lower Q limits when P of renewable generators is < 0.2 Pmax +ReserveCorrection = True #add Pmin to units that are necessary to satisfy reserve requirements so that they are not disconnected after unit commitment +DisconnectThreshhold = 0.10 #seuil en per unit de la puissance active en dessous duquel on deconnecte des generateurs pour qu'ils ne participent ni à la reserve ni à la compensation reactive. +#=============================================================================== +# DEFINITION DES FONCTIONS - CREATION OF THE FUNCTIONS +#=============================================================================== + + +#read a ROP file containing all opf data +def readOPFdata(RopFile): + + fo = open(RopFile, 'r') + Lines = fo.readlines() + fo.close() + + for i,line in enumerate(Lines): + if 'begin Generator Dispatch data' in line: + startgendisp = i+1 + if 'End of Generator Dispatch data' in line: + endgendisp = i + if 'begin Active Power Dispatch Tables' in line: + startdisptable = i+1 + if 'End of Active Power Dispatch Tables' in line: + enddisptable = i + if 'begin Piece-wise Linear Cost Tables' in line: + startlincosttable = i+1 + if 'End of Piece-wise Linear Cost Tables' in line: + endlincosttable = i + if 'begin Piece-wise Quadratic Cost Tables' in line: + startquadcosttable = i+1 + if 'End of Piece-wise Quadratic Cost Tables' in line: + endquadcosttable = i + if 'begin Polynomial Cost Tables' in line: + startpolycosttable = i+1 + if 'End of Polynomial Cost Tables' in line: + endpolycosttable = i + if 'begin Generation Reserve data' in line: + startgenreservedata = i+1 + if 'End of Generation Reserve data' in line: + endgenreservedata = i + if 'begin Period Reserve data' in line: + startperiodreservedata = i+1 + if 'end of period reserve' in line.lower(): + endperiodreservedata = i + if 'begin Adjustable Bus Shunt data' in line: + startadjbusshuntdata = i+1 + if 'End of Adjustable Bus Shunt data' in line: + endadjbusshuntdata = i + if 'begin Adjustable Bus Load Tables' in line: + startadjloadtable = i+1 + if 'End of Adjustable Bus Load Tables' in line: + endadjloadtable = i + + + GenDispatchData = [] + for i in range(startgendisp,endgendisp): + data = Lines[i].split() + busNum = int(data[0]) + ID = data[1] + dispatch = float(data[2]) + dispTable = int(data[3]) + GenDispatchData.append([busNum,ID,dispatch, dispTable]) + + DispTableData = [] + for i in range(startdisptable,enddisptable): + data = Lines[i].split() + DispTable = int(data[0]) + Pmax = float(data[1]) + Pmin = float(data[2]) + FuelCostScaleCoef = float(data[3]) + CurveType = int(data[4]) #2 = piece wise linear, + Status = int(data[5]) + CostTable = int(data[6]) + DispTableData.append([DispTable,Pmax,Pmin,FuelCostScaleCoef,CurveType,Status,CostTable]) + + LinCostTables = [] + i = startlincosttable + while i >= startlincosttable and i < endlincosttable: + headerdata = Lines[i].split() + CostTable = int(headerdata[0]) + #tableName = str(headerdata[1]) + numpoints = int(headerdata[-1]) + points=[] + i+=1 + for k in range(numpoints): + #pdb.set_trace() + pointdata = Lines[i+k].split() + x =float(pointdata[0]) + y =float(pointdata[1]) + points.append([x,y]) + i+=numpoints + LinCostTables.append([CostTable, numpoints, points]) + + QuadCostTables = [] + PolyCostTables = [] + + GenReserveData = [] + for i in range(startgenreservedata,endgenreservedata): + data = Lines[i].split() + busNum = int(data[0]) + ID = data[1] + ramp =float(data[2]) + Pmax = float(data[3]) + GenReserveData.append([busNum, ID, ramp, Pmax]) + + PeriodReserveData = [] + for i in range(startperiodreservedata,endperiodreservedata): + data = Lines[i].split() + if len(data)==4: + ResNum = int(data[0]) + ResLevel = float(data[1]) + ResPeriod = float(data[2]) + InService = int(data[3]) + ParticipatingUnits = [] + elif len(data)==2: + busNum = int(data[0]) + ID = data[1] + ParticipatingUnits.append([busNum,ID]) + elif 'End of Participating Reserve Units' in Lines[i]: + PeriodReserveData.append([ResNum,ResLevel,ResPeriod,InService,ParticipatingUnits]) + else: + pass + + AdjBusShuntData = [] + for i in range(startadjbusshuntdata,endadjbusshuntdata): + data = Lines[i].split() + busNum = int(data[0]) + ID = data[1] + SuscInit = float(data[2]) + SuscMax = float(data[3]) + SuscMin = float(data[4]) + CostScale = float(data[5]) + InService = int(data[6]) + AdjBusShuntData.append([busNum,ID, SuscInit,SuscMax,SuscMin,CostScale,InService]) + + AdjLoadTables = [] + for i in range(startadjloadtable,endadjloadtable): + data = Lines[i].split() + tableNum = int(data[0]) + LoadMult = float(data[1]) + Max = float(data[2]) + Min = float(data[3]) + CostScale = float(data[7]) + InService = int(data[9]) + AdjLoadTables.append([tableNum,LoadMult,Max,Min,CostScale,InService]) + + return GenDispatchData, DispTableData, LinCostTables, QuadCostTables, PolyCostTables, GenReserveData, PeriodReserveData, AdjBusShuntData, AdjLoadTables + + +#to remve a list from a string "['wind 1', 'wind 2', 'charge']" --> ['wind 1', 'wind 2', 'charge'] +def RemoveListfromString(List): + List = List.replace("]","") + List = List.replace("[","") + List = List.replace(")","") + List = List.replace("(","") + List = List.replace("'","") + List = List.replace('"',"") + List = List.replace(" ","") + List = List.split(",") + return List + +def RemoveTuplesfromString(TList): + TL = RemoveListfromString(TList) + nTL = [] + for i in range(len(TL)/2): + nTL.append([TL[2*i],float(TL[2*i+1])]) + return nTL + +###Fonction de transfert vent-puissance d'une eolienne +##def eol_old(wind, WTconfig): +## Vcin = WTconfig ['cutinWS'] +## Vrate = WTconfig ['ratedWS'] +## Vcout = WTconfig ['cutoutWS'] +## Rho = WTconfig ['rho'] +## lossrate = WTconfig ['lossrate'] +## if wind <= Vcin : +## Pnorm=0 +## elif wind < Vrate : +## Pnorm=wind*(1-lossrate)#((wind**2-Vcin**2)/(Vrate**2-Vcin**2)*Rho/1.225*(1-lossrate)) +## elif wind < Vcout : +## Pnorm = 1*(1-lossrate) +## else : +## Pnorm=0 +## return Pnorm + +def applyTF(x_in, TF): + + X = [] + P = [] + for (x,p) in TF: + X.append(x) + P.append(p) + + + Pmax=max(P) + precision = 0.001 + #calculate precision of values entered + for i in range(len(X)): + d1 = Decimal(str(X[i])) + d2 = Decimal(str(P[i])) + d1expo = d1.as_tuple().exponent + d2expo = d2.as_tuple().exponent + expo = np.minimum(d1expo,d2expo) + precision = min(10**(expo-1),precision) + + + #change to array type for consistency + X = np.array(X) + P = np.array(P) + + #interpolate between values so that precise wind speed data doesnt output heavily discretized power levels + from scipy import interpolate + finterp = interpolate.interp1d(X,P, kind='linear') + Xmin = min(X) + Xmax = max(X) + Xnew = np.arange(Xmin,Xmax,precision) + Pnew = finterp(Xnew) + + #calculate power by applying transfer function + if x_in >= Xmax-precision: + index = len(Pnew)-1 + elif x_in <= Xmin + precision: + index = 0 + else: + index = int(round((x_in-Xmin)/precision)) + Power = Pnew[index] + + PowerNorm = Power/Pmax #normalize + + return PowerNorm + + + +def eol(WS, z_WS, pathWT, HH, alpha=1./7, PercentLoss = 5): + + ''' + + Reconstitute wind production from wind speed histories for a single site. + + syntax: + ACPower = ReconstituteWind(WS, z_WS, pathWT, N_turbines, HH, alpha=1./7, PercentLoss=5) + + inputs: + WS: numpy array of wind speed measurements to be converted to production values + z_WS: height, in meters above ground level, of the wind speed measurements + pathWT: location of selected wind turbine technology's power curve file in computer file system + N_turbines: number of wind turbines in the installation/farm being modelled + HH: wind turbine hub height + alpha (optional, default = 1/7): exponential factor describing the vertical wind profile; used to extrapolate + wind data to hub height. Can be scalar or vector with same length as wind data. + PercentLoss (optional, default = 5): percent loss due to multiple effects: the wake effect of adjacent wind turbines, + cable resistance between wind turbine/farm and injection point, grid and turbine unavailability, extreme weather conditions, etc. +. + + outputs: + ACPower: numpy array of normalized expected wind production for the given wind farm. + + ''' + + + #open and treat wind turbine data in .pow file + f = open(pathWT) + lines = f.readlines() + WTdata = {} + WTdata["model"] = lines[0][1:-2] + WTdata['diameter'] = float(lines[1][1:-2]) + WTdata['CutInWindSpeed'] = float(lines[4][1:-2]) + WTdata['CutOutWindSpeed'] = float(lines[3][1:-2]) + WTdata['PowerCurve'] = {} + WTdata['PowerCurve']['WindSpeed'] = np.arange(0, 31) + WTdata['PowerCurve']['Power'] = [float(0)] #in kW + for i in range(5,35): + WTdata['PowerCurve']['Power'].append(float(lines[i][1:-2])) + + WTdata['Pmax']=max(WTdata['PowerCurve']['Power']) + + #insert WT hub height + WTdata['z'] = HH + + #correct wind speed values for appropriate height + WS_hh = WS*(WTdata['z']/z_WS)**alpha #wind speed at hub height + + #calculate precision of cut in and cut out windspeeds + d1 = Decimal(str(WTdata['CutInWindSpeed'])) + d2 = Decimal(str(WTdata['CutOutWindSpeed'])) + expo = np.minimum(d1.as_tuple().exponent, d2.as_tuple().exponent) + precision = 10**(expo-1) + + #insert points for cut-in and cut-out wind speeds + add_ci = 0 + add_co= 0 + if np.mod(WTdata['CutInWindSpeed'],1)==0: + add_ci = precision + if np.mod(WTdata['CutOutWindSpeed'],1)==0: + add_co = precision + i_cutin = np.where(WTdata['PowerCurve']['WindSpeed']>(WTdata['CutInWindSpeed']+add_ci))[0][0] + i_cutout = np.where(WTdata['PowerCurve']['WindSpeed']>(WTdata['CutOutWindSpeed']+add_co))[0][0] + 1 #+1 to account for addition of cut in point + WTdata['PowerCurve']['WindSpeed'] = list(WTdata['PowerCurve']['WindSpeed']) + WTdata['PowerCurve']['WindSpeed'].insert(i_cutin, WTdata['CutInWindSpeed']+add_ci) + WTdata['PowerCurve']['WindSpeed'].insert(i_cutout, WTdata['CutOutWindSpeed']+add_co) + WTdata['PowerCurve']['Power'].insert(i_cutin, 0) + WTdata['PowerCurve']['Power'].insert(i_cutout, 0) + + #change to array type for consistency + WTdata['PowerCurve']['WindSpeed'] = np.array(WTdata['PowerCurve']['WindSpeed']) + WTdata['PowerCurve']['Power'] = np.array(WTdata['PowerCurve']['Power']) + + #interpolate between values so that precise wind speed data doesnt output heavily discretized power levels + from scipy import interpolate + finterp = interpolate.interp1d(WTdata['PowerCurve']['WindSpeed'],WTdata['PowerCurve']['Power'], kind='linear') + Vnew = np.arange(0,30,precision) + Pnew = finterp(Vnew) + + #calculate power produced by turbine in function of wind speed + Pac_turbine = [] + for i, ws in enumerate(WS_hh): + if ws >= 30-precision: + index = len(Pnew)-1 + else: + index = int(round(ws/precision)) #index of correct wind speed + Pac_turbine.append(Pnew[index]) #Power corresponds to value with same index as wind speed vector + Pac_turbine = np.array(Pac_turbine) + + #account for Losses...currently a single loss factor but could imagine implementing a per-point method + #WakeEffects = 4 #3-8% for a typical farm, 0% for an individual windmill + #CableResistanceLosses = 1 #1-3% between windmills and electric counter, depending on voltage levels and cable length + #GridUnavalability = 1 + #WTUnavailability = 3 + #AcousticCurtailment = 1-4 + #Freezing = 0.5 + #LF = (1-WakeEffects/100)*(1-CableResistanceLosses/100) #loss factor + ACPower = Pac_turbine*(1-PercentLoss/100) #total AC power produced by wind turbine + ACPowerNorm = ACPower/WTdata['Pmax'] + return ACPowerNorm + +def postOPFinitialization(sav_file,all_inputs_init,AdjLoadTables,init_gen=True,init_bus=True,init_fxshnt=True,init_swshnt=True,init_load=True,init_P0=False): + + psspy.save(sav_file) + + buses_init=all_inputs_init[0] + lines_init=all_inputs_init[1] + trans_init=all_inputs_init[2] + plants_init=all_inputs_init[3] + loads_init=all_inputs_init[4] + shunt_init=all_inputs_init[5] + motors_init=all_inputs_init[6] + trans3_init=all_inputs_init[7] + swshunt_init=all_inputs_init[8] + + all_inputs_base=read_sav(sav_file) + buses_base=all_inputs_base[0] + lines_base=all_inputs_base[1] + trans_base=all_inputs_base[2] + plants_base=all_inputs_base[3] + loads_base=all_inputs_base[4] + shunt_base=all_inputs_base[5] + motors_base=all_inputs_base[6] + trans3_base=all_inputs_base[7] + swshunt_base=all_inputs_base[8] + + _i=psspy.getdefaultint() + _f=psspy.getdefaultreal() + _s=psspy.getdefaultchar() + + #re-initialize generators to original value + if init_gen: + for plant in plants_init: + busNum = plant[0] + ID = plant[2] + P = plant[3] + Q = plant[4] + psspy.machine_chng_2(busNum,ID,[_i,_i,_i,_i,_i,_i],\ + [P, Q,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) + + #re-initialize voltages and angles + if init_bus: + for bus in buses_init: + busNum = bus[0] + Upu = bus[2] + angleDegrees = bus[7] + psspy.bus_chng_3(busNum,[_i,_i,_i,_i],[_f,Upu,angleDegrees,_f,_f,_f,_f],_s) + + #re-initialize fixed shunts to original value + if init_fxshnt: + for shunt in shunt_base: + sh_init = next((sh for sh in shunt_init if (sh[0] == shunt[0]) and sh[5]==shunt[5]),'not found') + if sh_init == 'not found': #this means the added shunt is an adjustable bus shunt with no existing shunt at the same bus + #initialize the fixed shunt to 0 + ID = shunt[5] #(ID always == 1) + busNum = shunt[0] + Qnom = 0 + psspy.shunt_chng(busNum,ID,_i,[_f, Qnom]) + else: #this shunt already existed in initial saved case file, re-initialize to initial value + ID = sh_init[5] + busNum = sh_init[0] + Q = sh_init[2] + Qnom = sh_init[4] + psspy.shunt_chng(busNum,ID,_i,[_f, Qnom]) + + #re-initialize switched shunts to original values + if init_swshnt: + for swshunt in swshunt_init: + busNum = swshunt[0] + Q = swshunt[2] + Qnom = swshunt[4] + psspy.switched_shunt_chng_3(busNum,[_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i],[_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,Qnom,_f],"") + + #re-initialize loads to original values + if init_load: + # for load in loads_init: + # busNum = load[0] + # ID = load[5] + # P = load[1] + # Q = load[2] + # psspy.load_chng_4(busNum,ID,[_i,_i,_i,_i,_i,_i],[P, Q,_f,_f,_f,_f]) + for table in AdjLoadTables: + tableNum = table[0] + LoadMult = table[1] + psspy.opf_adjload_tbl(tableNum,[_i,_i,_i],[LoadMult,_f,_f,_f,_f,_f,_f]) + + #initialize dispatchable generators to P = 0 + if init_P0: + for gen in GenDispatchData: + busNum = gen[0] + ID = gen[1] + dispatch = gen[2] + if dispatch>0: + P=0 + psspy.machine_chng_2(busNum,ID,[_i,_i,_i,_i,_i,_i],\ + [P,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) + + ##save changes + psspy.save(sav_file) + + return + + +#Fonction permettant de lire les donnees qui nous interessent et de les mettre dans une matrice +def read_sav(doc): + psspy.case(doc) + # Select what to report + if psspy.bsysisdef(0): + sid = 0 + else: # Select subsytem with all buses + sid = -1 + + flag_bus = 2 #all buses 1 # in-service + flag_plant = 4 #all machines + flag_load = 4 #all loads 1 # in-service + flag_motor = 4 #all motors 1 # in-service + flag_swsh = 4 #all fixed shunts 1 # in-service + flag_brflow = 1 # in-service + owner_brflow = 1 # bus, ignored if sid is -ve + ties_brflow = 5 # ignored if sid is -ve + entry = 1 # gives a single entry (each branch once) + + #Bus data (number, basekV, pu, name, ...) : PSSe has 3 functions one for integer data, one for real data and one for strings + istrings = ['number'] + ierr, idata = psspy.abusint(sid, flag_bus, istrings) + buses=idata + + rstrings = ['base','pu'] + ierr, rdata = psspy.abusreal(sid, flag_bus, rstrings) + buses.append(rdata[0]) + buses.append(rdata[1]) + + cstrings = ['name'] + ierr, cdata = psspy.abuschar(sid, flag_bus, cstrings) + cdata[0]=map( lambda s: s.replace("\n"," "),cdata[0]) + buses.append(cdata[0]) + + rstrings = ['nvlmlo','nvlmhi'] + ierr, rdata = psspy.abusreal(sid, flag_bus, rstrings) + buses.append(rdata[0]) + buses.append(rdata[1]) + + istrings = ['type'] + ierr, idata = psspy.abusint(sid, flag_bus, istrings) + buses.append(idata[0]) + + rstrings = ['angled'] + ierr, rdata = psspy.abusreal(sid, flag_bus, rstrings) + buses.append(rdata[0]) + + buses=zip(*buses) # transpose the matrix + + del idata, rdata, istrings, rstrings + + #Lines data (from, to, amps, rate%a, ploss, qloss) + flag=2 #All non-transformer branches + istrings = ['fromnumber','tonumber'] + ierr, idata = psspy.abrnint(sid, owner_brflow, ties_brflow, flag, entry, istrings) + lines=idata + + rstrings=['amps','pctratea','pctrateb','pctratec','p','q'] + ierr, rdata = psspy.abrnreal(sid, owner_brflow, ties_brflow, flag, entry, rstrings) + for rc in range (np.matrix(rdata).shape[0]) : + lines.append(rdata[rc]) + + cstrings=['fromname','toname','id'] + ierr, cdata = psspy.abrnchar(sid, owner_brflow, ties_brflow, flag, entry, cstrings) + for rc in range (np.matrix(cdata).shape[0]) : + cdata[rc]=map( lambda s: s.replace("\n"," "),cdata[rc]) + lines.append(cdata[rc]) + + #eliminate breakers and switches + linesAll=zip(*lines) # transpose the matrix + lines = [] + for line in linesAll: + if ('@' not in line[10]) and ('*' not in line[10]): + lines.append(line) + + del idata, rdata, istrings, rstrings + + #2 windings transformers data (from, to, amps, rate%a, ploss, qloss) + flag=6 #All transformer branches + istrings = ['fromnumber','tonumber'] + ierr, idata = psspy.abrnint(sid, owner_brflow, ties_brflow, flag, entry, istrings) + transf=idata + + rstrings=['amps','pctratea','pctrateb','pctratec','p','q'] + ierr, rdata = psspy.abrnreal(sid, owner_brflow, ties_brflow, flag, entry, rstrings) + for rc in range (np.matrix(rdata).shape[0]) : + transf.append(rdata[rc]) + + cstrings=['fromname','toname','id'] + ierr, cdata = psspy.abrnchar(sid, owner_brflow, ties_brflow, flag, entry, cstrings) + for rc in range (np.matrix(cdata).shape[0]) : + cdata[rc]=map( lambda s: s.replace("\n"," "),cdata[rc]) + transf.append(cdata[rc]) + + transf=zip(*transf) # transpose the matrix + + del idata, rdata, istrings, rstrings + + #3 windings transformers data (from, to, amps, rate%a, ploss, qloss) + #sid = -1 #assume a subsystem containing all buses in working case + owner_3flow = 1 #1 = use bus ownership 2 = use tfo ownership + ties_3flow = 3 #ignored bc sid is negative. 3 = interior subsystem and subsystem tie 3 winding transformers + flag=3 #all 3 winding transfo windings + entry = 2 #1=winding 1 bus order, 2=transformer name order + + istrings = ['wind1number','wind2number','wind3number', 'wndnum'] + ierr, idata = psspy.awndint(sid, owner_3flow, ties_3flow, flag, entry, istrings) + transf3 = idata + + rstrings=['amps','pctratea','pctrateb','pctratec','p','q'] + ierr, rdata = psspy.awndreal(sid, owner_3flow, ties_3flow, flag, entry, rstrings) + for rc in range (np.matrix(rdata).shape[0]) : + transf3.append(rdata[rc]) + + cstrings=['wind1name','wind2name','wind3name','id'] + ierr, cdata = psspy.awndchar(sid, owner_3flow, ties_3flow, flag, entry, cstrings) + for rc in range (np.matrix(cdata).shape[0]) : + cdata[rc]=map( lambda s: s.replace("\n"," "),cdata[rc]) + transf3.append(cdata[rc]) + + transf3=zip(*transf3) # transpose the matrix + + del idata, rdata, istrings, rstrings + + + #Machines data (bus, inservice, number, pgen, qgen, mvabase, pmax, qmax, name) + istrings = ['number','status'] + ierr, idata = psspy.amachint(sid, flag_plant, istrings) + plants=idata + + cstrings = ['id'] + ierr, cdata = psspy.amachchar(sid, flag_plant, cstrings) + for rc in range (np.matrix(cdata).shape[0]) : + plants.append(cdata[rc]) + + rstrings = ['pgen','qgen','mbase','pmax','qmax'] + ierr, rdata = psspy.amachreal(sid, flag_plant, rstrings) + for rc in range (np.matrix(rdata).shape[0]) : + plants.append(rdata[rc]) + + cstrings = ['name'] + ierr, cdata = psspy.amachchar(sid, flag_plant, cstrings) + cdata[0]= map( lambda s: s.replace("\n"," "),cdata[0]) + plants.append(cdata[0]) + + rstrings = ['pmin','qmin'] + ierr, rdata = psspy.amachreal(sid, flag_plant, rstrings) + for rc in range (np.matrix(rdata).shape[0]) : + plants.append(rdata[rc]) + + istrings = ['wmod'] + ierr, idata = psspy.amachint(sid, flag_plant, istrings) + for rc in range (np.matrix(idata).shape[0]) : + plants.append(idata[rc]) + + nb_plants=np.matrix(plants).shape[1] + for rc in range (0,nb_plants) : + plants[3][rc]=float(plants[3][rc]*int(plants[1][rc])) # If the plant isn't in service its production is fixed to zero + plants[4][rc]=float(plants[4][rc]*int(plants[1][rc])) # If the plant isn't in service its production is fixed to zero + + plants=zip(*plants) # transpose the matrix + + del idata, rdata, cdata + + #Loads data (bus, active, reactive, status, name, id) + istrings = ['number'] + ierr, idata = psspy.aloadint(sid, flag_load, istrings) + loads=idata + + xstrings = ['mvaact'] + ierr, xdata = psspy.aloadcplx(sid, flag_load, xstrings) + loads.append(np.real(xdata)[0]) # Append the real part of the load + loads.append(np.imag(xdata)[0]) #Append the imaginary part of the load + + istrings = ['status'] + ierr, idata = psspy.aloadint(sid, flag_load, istrings) + loads.append(idata[0]) + + cstrings = ['name', 'id'] + ierr, cdata = psspy.aloadchar(sid, flag_load, cstrings) + cdata[0]=map( lambda s: s.replace("\n"," "),cdata[0]) + loads.append(cdata[0]) + loads.append(cdata[1]) + + nb_loads=np.matrix(loads).shape[1] + for rc in range (0,nb_loads) : + loads[1][rc]=float(loads[1][rc]*int(loads[3][rc])) # If the load isn't in service its consumption is fixed to zero + loads[2][rc]=float(loads[2][rc]*int(loads[3][rc])) # If the load isn't in service its consumption is fixed to zero + + loads=zip(*loads) # transpose the matrix + + del idata, cdata, xdata + + #Fixed shunt data (number, MVAR, name, ...) + istrings = ['number','status'] + ierr, idata = psspy.afxshuntint(sid, flag_bus, istrings) + shunt=idata + + xstrings = ['shuntact'] + ierr, xdata = psspy.afxshuntcplx(sid, flag_bus, xstrings) + shunt.append(np.imag(xdata)[0]) #Append the imaginary part of the shunt + + cstrings = ['name'] + ierr, cdata = psspy.afxshuntchar(sid, flag_bus, cstrings) + cdata[0]=map( lambda s: s.replace("\n"," "),cdata[0]) + shunt.append(cdata[0]) + + xstrings = ['shuntnom'] + ierr, xdata = psspy.afxshuntcplx(sid, flag_bus, xstrings) + shunt.append(np.imag(xdata)[0]) #Append the imaginary part of the shunt + + cstrings = ['id'] + ierr, cdata = psspy.afxshuntchar(sid, flag_bus, cstrings) + cdata[0]=map( lambda s: s.replace("\n"," "),cdata[0]) + shunt.append(cdata[0]) + + nb_sh=np.matrix(shunt).shape[1] + for rc in range (0,nb_sh) : # If the swshunt isn't in service its MVAR is fixed to zero + shunt[2][rc]=float(shunt[2][rc]*int(shunt[1][rc])) + shunt[4][rc]=float(shunt[4][rc]*int(shunt[1][rc])) + + shunt=zip(*shunt) # transpose the matrix + + del idata, cdata, xdata + + #Switched shunt data (number, MVAR, name, ...) + istrings = ['number','status'] + ierr, idata = psspy.aswshint(sid, flag_swsh, istrings) + swshunt=idata + status = np.array(swshunt[1]) + + + rstrings = ['bswact'] + ierr, rdata = psspy.aswshreal(sid, flag_swsh, rstrings) + swshunt.append(rdata[0]) #Append the imaginary part of the load + + cstrings = ['name'] + ierr, cdata = psspy.aswshchar(sid, flag_swsh, cstrings) + #cdata[0]=map( lambda s: s.replace("\n"," "),cdata[0]) + swshunt.append(cdata[0]) + + rstrings = ['bswnom'] + ierr, rdata = psspy.aswshreal(sid, flag_swsh, rstrings) + swshunt.append(rdata[0]) #Append the imaginary part of the load + + nb_swsh=np.matrix(swshunt).shape[1] + for rc in range (0,nb_swsh) : # If the swshunt isn't in service its MVAR is fixed to zero + swshunt[2][rc]=float(swshunt[2][rc]*int(swshunt[1][rc])) + swshunt[4][rc]=float(swshunt[4][rc]*int(swshunt[1][rc])) + + swshunt=zip(*swshunt) # transpose the matrix + + del idata, cdata, rdata + + #Motors data (bus, active, reactive, status, name, id) + istrings = ['number'] + ierr, idata = psspy.aindmacint(sid, flag_motor, istrings) + motors=idata + + rstrings = ['p','q'] + ierr, rdata = psspy.aindmacreal(sid, flag_motor, rstrings) + motors.append(rdata[0]) #Append the real part of the motor load + motors.append(rdata[1]) #Append the imaginary part of the motor load + + istrings = ['status'] + ierr, idata = psspy.aindmacint(sid, flag_motor, istrings) + motors.append(idata[0]) + + cstrings = ['name', 'id'] + ierr, cdata = psspy.aindmacchar(sid, flag_motor, cstrings) + cdata[0]=map( lambda s: s.replace("\n"," "),cdata[0]) + motors.append(cdata[0]) + motors.append(cdata[1]) + + nb_motors=np.matrix(motors).shape[1] + for rc in range (0,nb_motors) : + motors[1][rc]=float(motors[1][rc]*int(motors[3][rc])) # If the load isn't in service its consumption is fixed to zero + motors[2][rc]=float(motors[2][rc]*int(motors[3][rc])) # If the load isn't in service its consumption is fixed to zero + + motors=zip(*motors) # transpose the matrix + + del idata, cdata, rdata + + return buses, lines, transf, plants, loads, shunt, motors, transf3, swshunt + +def MyLogger(x,y,z,logCSVfilename,ite): + f=open(logCSVfilename, 'a') + f.write(str(ite)+';') + f.write(";") + nx = len(x) + for i in range(0,nx): + f.write(str(x[i]))#f.write("%f;" % (x[i])) + f.write(";") + f.write(";") + nz = len(z) + for i in range(0,nz): + try: + f.write("%f;" % (z[i])) + except: + f.write(str(z[i])+";") + f.write(";") + ny = len(y) + for j in range(0,ny): + f.write("%f;" % (y[j])) + f.write("\n") + f.close() + +# Fonction pour ecrire un fichier de sortie type csv pour chaque type de grandeur de sortie +def MyMultiLogger (x, y, sizeY, z, ite, folder, day, fich, hour): + global ny + y0=0 + for fich in range (np.size(sizeY,0)): + multilogfilename=folder+"\N"+day+"\Y"+str(fich)+"simulationDClog_"+hour+".csv" + f=open(multilogfilename, 'a') + f.write("%f;" % (ite)) + f.write(";") + nx = len(x) + for i in range(0,nx): + f.write("%f;" % (x[i])) + f.write(";") + nz = len(z) + for i in range(0,nz): + f.write("%f;" % (z[i])) + f.write(";") + ny = sizeY[fich] + for j in range(0,ny): + f.write("%f;" % (y[j+y0])) + f.write("\n") + f.close() + y0 += ny + print( "Fichiers "+str(ite)+" enregistres\n\n") + +# Analyses graphiques +def graphical_out (inputSample, outputSampleAll, inputDim, outputDim, montecarlosize) : + print "\n\n\n Writing graphical analysis files..." + # A Pairwise scatter plot of the inputs + myGraph = Graph() + myPairs = Pairs(inputSample, 'Inputs relations', inputSample.getDescription(), "red", "bullet") + myGraph.add(Drawable(myPairs)) + myGraph.draw("Input Samples",640,480,GraphImplementation.PDF) + #View(myGraph.getBitmap()) + print 'Input pairwise scatterplot done...' + + # A Pairwise scatter plot of the outputs + myGraph = Graph() + myPairs = Pairs(outputSampleAll, 'Output relations', outputSampleAll.getDescription(), "red", "bullet") + myGraph.add(Drawable(myPairs)) + myGraph.draw("Output Samples",640,480,GraphImplementation.PDF) + #View(myGraph.getBitmap()) + print 'Output pairwise scatterplot done...' + + # A Pairwise scatter plot of the inputs/outputs + # Draw all scatter plots yj vs xi + for j in range(outputDim): + outputSamplej=outputSampleAll.getMarginal(j) + Ylabelstr=outputSamplej.getDescription()[0] + for i in range(inputDim): + inputSamplei=inputSample.getMarginal(i) + Xlabelstr=inputSamplei.getDescription()[0] + X=NumericalSample(montecarlosize,2) + for k in range(montecarlosize): + X[k,0]=inputSamplei[k][0] + X[k,1]=outputSamplej[k][0] + myGraph = Graph() + myCloud=Cloud(X); + mytitle=Ylabelstr+"vs"+Xlabelstr + myGraph.add(Drawable(myCloud)) + myGraph.setAxes(1) + myGraph.setXTitle(Xlabelstr) + myGraph.setYTitle(Ylabelstr) + myGraph.draw(mytitle,640,480,GraphImplementation.PDF) + #ViewImage(myGraph.getBitmap()) + print 'Input/Output pairwise scatterplot done...' + + # An histogram of the inputs + for i in range(inputDim): + inputSamplei=inputSample.getMarginal(i) + myGraph = VisualTest.DrawHistogram(inputSamplei) + labelarray=inputSamplei.getDescription() + labelstr=labelarray[0] + myGraph.setTitle(labelstr) + myGraph.setName(labelstr) + myGraph.setXTitle(labelstr) + myGraph.setYTitle("Frequency") + myGraph.draw(labelstr,640,480,GraphImplementation.PDF) + #View(myGraph.getBitmap()) + print 'Input histogram done...' + + # An histogram of the outputs + for j in range(outputDim): + outputSamplej=outputSampleAll.getMarginal(j) + myGraph = VisualTest.DrawHistogram(outputSamplej) + labelarray=outputSamplej.getDescription() + labelstr=labelarray[0] + myGraph.setTitle(labelstr) + myGraph.setName(labelstr) + myGraph.setXTitle(labelstr) + myGraph.setYTitle("Frequency") + myGraph.draw(labelstr,640,480,GraphImplementation.PDF) + #View(myGraph.getBitmap()) + print 'Output histogram done' + print 'Graphical output terminated' + + +def config_contingency(LinesList,GroupsList,TransformersList,LoadsList,MotorsList) : + + lines_con=[] + groups_con=[] + loads_con = [] + transfos_con = [] + motors_con = [] + sizeLines = len(LinesList) + sizeGroups = len(GroupsList) + sizeTransfos = len(TransformersList) + sizeLoads = len(LoadsList) + sizeMotors = len(MotorsList) + val=[] + prob=[] + + for i in range(sizeLines+sizeGroups+sizeTransfos + sizeLoads + sizeMotors) : + val.append(int(i)) + for i in range (sizeLines) : + lines_con.append(LinesList[i][0]) + prob.append(LinesList[i][1]) + for i in range (sizeGroups) : + prob.append(GroupsList[i][1]) + groups_con.append(GroupsList[i][0]) + for i in range (sizeTransfos) : + prob.append(TransformersList[i][1]) + transfos_con.append(TransformersList[i][0]) + for i in range (sizeLoads) : + prob.append(LoadsList[i][1]) + loads_con.append(LoadsList[i][0]) + for i in range (sizeMotors) : + prob.append(MotorsList[i][1]) + motors_con.append(MotorsList[i][0]) + + return lines_con, groups_con, transfos_con, loads_con, motors_con, val, prob + +##def config_contingency(LinesPath,GeneratorsPath,TransformersPath,LoadsPath) : +## +## lines_con=[] +## groups_con=[] +## loads_con = [] +## transfos_con = [] +## +## # Loading of lines contingency configuration +## if LinesPath != '': +## f=open(LinesPath,"r") +## lines=f.readlines() +## f.close() +## for i in range (len(lines)) : +## line=lines[i].split(";") +## try : +## int(line[1]) +## except ValueError : +## pass +## else : +## if line[0] == '' : +## line[0] = '0' +## lines_con.append([int(line[1]), int(line[3]), str(line[5]),float(line[0].replace(',','.'))]) +## +## # Loading of lines contingency configuration +## if TransformersPath != '': +## f=open(TransformersPath,"r") +## lines=f.readlines() +## f.close() +## for i in range (len(lines)) : +## line=lines[i].split(";") +## try : +## int(line[1]) +## except ValueError : +## pass +## else : +## if line[0] == '' : +## line[0] = '0' +## transfos_con.append([int(line[1]), int(line[3]), str(line[5]),float(line[0].replace(',','.'))]) +## +## # Loading of groups contingency configuration +## if GeneratorsPath != '': +## f=open(GeneratorsPath,"r") +## lines=f.readlines() +## f.close() +## for i in range (len(lines)) : +## line=lines[i].split(";") +## try : +## int(line[1]) +## except ValueError : +## pass +## else : +## if line[0] == '' : +## line[0] = '0' +## groups_con.append([int(line[1]), int(line[3]),float(line[0].replace(',','.'))]) +## +## # Loading of loads contingency configuration +## if LoadsPath != '': +## f=open(LoadsPath,"r") +## lines=f.readlines() +## f.close() +## for i in range (len(lines)) : +## line=lines[i].split(";") +## try : +## int(line[1]) +## except ValueError : +## pass +## else : +## if line[0] == '' : +## line[0] = '0' +## loads_con.append([int(line[1]), int(line[3]), float(line[0].replace(',','.'))]) +## +## sizeLines = len(lines_con) +## sizeGroups = len(groups_con) +## sizeTransfos = len(transfos_con) +## sizeLoads = len(loads_con) +## val=[] +## prob=[] +## for i in range(sizeLines+sizeGroups+sizeTransfos + sizeLoads) : +## val.append(int(i)) +## +## for i in range (sizeLines) : +## prob.append(lines_con[i][3]) +## for i in range (sizeGroups) : +## prob.append(groups_con[i][2]) +## for i in range (sizeTransfos) : +## prob.append(transfos_con[i][3]) +## for i in range (sizeLoads) : +## prob.append(loads_con[i][2]) +## return lines_con, groups_con, transfos_con, loads_con, val, prob + +def LoadARMA(time_serie_file, time_serie_SS, time_serie_TH) : + f=open(time_serie_file,"r") + lines=f.readlines() + N=len(lines) + Xt=[] + for i in range(N) : + Xt.append([float(lines[i])]) + + myTG=RegularGrid(0,float(time_serie_SS),N) + TS=TimeSeries(myTG,NumericalSample(Xt)) + myWN=WhiteNoise(Distribution(Normal(0,1)),myTG) + myState=ARMAState(TS.getSample(),NumericalSample()) + p=12 + q=0 + d=1 + myFactory = ARMALikelihoodFactory ( p , q , d ) + myARMA = myFactory.build(TS) + + myARMA.setState(myState) + + AR = myARMA.getARCoefficients() + MA = myARMA.getMACoefficients() + + ts = myARMA.getRealization() + ts.setName('A realization') + myTSGraph=ts.drawMarginal(0) + myTSGraph.draw('Realization'+str(p)+","+str(q),640,480,GraphImplementation.PDF) + myARMAState=myARMA.getState() + + #Make a prediction of the future on next Nit instants + Nit = int(time_serie_TH) + myARMA2=ARMA(AR,MA,myWN,myARMAState) + possibleFuture=myARMA2.getFuture(Nit) + possibleFuture.setName('Possible future') + + Xt2=[] + for i in range (len(possibleFuture)): + Xt2.append(possibleFuture.getValueAtIndex(i)[0]) + Max=float(max(Xt2)) + Min=float(min(Xt2)) + h=float(Max-Min) + for i in range (len(possibleFuture)): + value= (Xt2[i]-Min+h/3)/(Max-Min+h/3) + possibleFuture.setValueAtIndex(i,NumericalPoint(1,value)) + + myFG=possibleFuture.drawMarginal(0) + myFG.draw('Future'+str(Nit),640,480,GraphImplementation.PDF) + + return possibleFuture + +def LoadTS(time_serie_file) : + TS=[] + for i in range(len(time_serie_file)) : + if time_serie_file[i] == -1 : + pass + else : + f=open(time_serie_file[i],"r") + lines=f.readlines() + N=len(lines) + Xt=[] + for j in range(N) : + try : + float(lines[i]) + except ValueError : + lines[i] = commaToPoint(lines[i]) + else : + pass + Xt.append([float(lines[j])]) + TS.append(Xt) + return TS + + +def KSDist(lines) : + print "Creating Kernel Smoothing distribution " + N=len(lines) + Xt=[] + for i in range(N) : + if lines[i] == "\n" : + print "End of file" + break + else : + try : + float(lines[i]) + except ValueError : + lines[i] = commaToPoint(lines[i]) + else : + pass + Xt.append([float(lines[i])]) + NS=NumericalSample(Xt) + kernel=KernelSmoothing(Uniform()) + myBandwith = kernel.computeSilvermanBandwidth(NS) + KS=kernel.build(NS,myBandwith,1) + return KS + + +def threshold (inputRandomVector, outputVariableOfInterest,pssefun,inputDistribution) : + # We create a quadraticCumul algorithm + myQuadraticCumul = QuadraticCumul(outputVariableOfInterest) + + # We compute the several elements provided by the quadratic cumul algorithm + # and evaluate the number of calculus needed + nbBefr = pssefun.getEvaluationCallsNumber() + + # Mean first order + meanFirstOrder = myQuadraticCumul.getMeanFirstOrder()[0] + nbAfter1 = pssefun.getEvaluationCallsNumber() + + # Mean second order + meanSecondOrder = myQuadraticCumul.getMeanSecondOrder()[0] + nbAfter2 = pssefun.getEvaluationCallsNumber() + + # Standard deviation + stdDeviation = sqrt(myQuadraticCumul.getCovariance()[0,0]) + nbAfter3 = pssefun.getEvaluationCallsNumber() + + print "First order mean=", myQuadraticCumul.getMeanFirstOrder()[0] + print "Evaluation calls number = ", nbAfter1 - nbBefr + print "Second order mean=", myQuadraticCumul.getMeanSecondOrder()[0] + print "Evaluation calls number = ", nbAfter2 - nbAfter1 + print "Standard deviation=", sqrt(myQuadraticCumul.getCovariance()[0,0]) + print "Evaluation calls number = ", nbAfter3 - nbAfter2 + + print "Importance factors=" + for i in range(inputRandomVector.getDimension()) : + print inputDistribution.getDescription()[i], " = ", myQuadraticCumul.getImportanceFactors()[i] + print "" + +def getUserDefined (values): + val = [] + prob = [] + for a in values: + val.append(a[0]) + prob.append(a[1]) + dim = len (val) + + prob = map(float,prob) + prob = [p/sum(prob) for p in prob] + +## weights = NumericalPoint(prob) +## Vals = [] +## for i in range(dim): +## Vals.append([float(val[i]),float(val[i])+0.000001]) +## ranges = NumericalSample(Vals) +## return UserDefined(ranges, weights) + coll = UserDefinedPairCollection() + for i in range (dim) : + UDpair=UserDefinedPair(NumericalPoint(1,float(val[i])),float(prob[i])) + coll.add(UDpair) + return UserDefined(coll) + + +def getHistogram (values) : + step = [] + prob = [] + for a in values: + step.append(a[0]) + prob.append(a[1]) + dim = len (step) + myHistogram = HistogramPairCollection(dim) + for i in range (dim) : + try: + myHistogram[i]=HistogramPair(float(step[i]),float(prob[i])) + except: + pass + return myHistogram + + + +def getUserLaw(LawDico): + time_serie = 0 + time_serie_file = '' + time_serie_SS = 0 + time_serie_TH = 0 + if LawDico['Law']=="Normal": + law = Normal(float(LawDico['Mu']),float(LawDico['Sigma']))#Openturns + elif LawDico['Law']=="Uniform": + law=Uniform(float(LawDico['A']),float(LawDico['B'])) + elif LawDico['Law']=="Exponential": + law=Exponential(float(LawDico['Lambda']),float(LawDico['Gamma'])) + elif LawDico['Law']=="Weibull": + if LawDico['Settings']=='AlphaBeta': + law=Weibull(float(LawDico['Alpha']),float(LawDico['Beta']),float(LawDico['Gamma'])) + elif LawDico['Settings']=='MuSigma': + law=Weibull(float(LawDico['Mu']),float(LawDico['Sigma']),float(LawDico['Gamma']),Weibull.MUSIGMA) + elif LawDico['Law']=="TruncatedNormal": + law=TruncatedNormal(float(LawDico['MuN']),float(LawDico['SigmaN']),float(LawDico['A']),float(LawDico['B'])) + elif LawDico['Law']=="UserDefined": + law=UserDefined(getUserDefined (LawDico['Values'])) + elif LawDico['Law']=="Histogram": + law=Histogram(LawDico['First'], getHistogram (LawDico['Values'])) + elif LawDico['Law']=="PDF_from_file": + law=KSDist(LawDico['FileContents']) + elif LawDico['Law']=="TimeSeries_from_file": + law = Uniform(0.999999,1) + time_serie=1 + time_serie_file=LawDico['FileContents'] + else : + law = Uniform(0.999999,1) + return law, [time_serie, time_serie_file] #[time_serie, time_serie_file, time_serie_SS, time_serie_TH] + + + + +def contingency_automatic (dfxPath, acccPath, rate) : + psspy.accc_with_dsp_3( 0.5,[0,0,0,1,1,2,0,0,0,0,0],r"""ALL""",dfxPath,acccPath,"","","") + psspy.accc_single_run_report_4([1,int(rate),int(rate),1,1,0,1,0,0,0,0,0],[0,0,0,0,6000],[ 0.5, 5.0, 100.0,0.0,0.0,0.0, 99999.],acccPath) + + rslt_summary=pssarrays.accc_summary(acccPath) + if int(rate) == 1 : + rate = rslt_summary.rating.a + elif int(rate) == 2 : + rate = rslt_summary.rating.b + elif int(rate) == 3 : + rate = rslt_summary.rating.c + else : + print "NO RATE CHOOSEN" + + Labels=rlst.colabel + contin_load=[] + for label in Labels : + t=[] + rslt=pssarrays.accc_solution(acccPath,contingency,label,0.5,5.0) + ampFlow=rslt.ampflow + for i in range (len(rA)) : + t.append(ampFlow[i]/rate[i]) + contin_load.append(t) + return contin_load + +def commaToPoint (string) : + stringReplaced = string.replace(',','.') + return stringReplaced + +def PSSEFunct(dico,x): + if 1: + #try: +## if dico['TStest']==1: +## os.chdir(dico['doc_base']) #to work in right directory of the package +## sys.stdout=open('process num'+str(os.getpid())+'_package '+\ +## str(dico['num_pac'])+'.out','w') + + #Get all the dico values + TStest=dico['TStest'] + sizeY0=dico['sizeY0'] + sizeY1=dico['sizeY1'] + sizeY2=dico['sizeY2'] + sizeY3=dico['sizeY3'] + sizeY4=dico['sizeY4'] + sizeY5=dico['sizeY5'] + sizeY6=dico['sizeY6'] + sizeY7=dico['sizeY7'] + sizeY8=dico['sizeY8'] + sizeY=dico['sizeY'] + Xt=dico['Xt'] + folder=dico['folder'] + folderN_1=dico['folderN_1'] + day=dico['day'] + doc_base=dico['doc_base'] + PSSEParams=dico['PSSEParams'] + _i=dico['_i'] + _f=dico['_f'] + _s=dico['_s'] + if dico['PSSEParams']['I_MAX']=='RateA': + Irate_num=1 + elif dico['PSSEParams']['I_MAX']=='RateB': + Irate_num=2 + elif dico['PSSEParams']['I_MAX']=='RateC': + Irate_num=3 + num_pac=dico['num_pac'] + logCSVfilename=dico['logCSVfilename'] + continLines=dico['continLines'] + continGroups=dico['continGroups'] + continTransfos=dico['continTransfos'] + continLoads=dico['continLoads'] + continMotors=dico['continMotors'] + continVal=dico['continVal'] + continProb=dico['continProb'] + position=dico['position'] + timeVect=dico['timeVect'] + LawsList = dico['CorrMatrix']['laws'] + all_inputs_init = dico['all_inputs_init'] + AdjLoadTables = dico['AdjLoadTables'] + + + #initializations + Output=[] + LS=[] + FS=[] + Pmachine=[] + LStable=[] + FStable=[] + + LS_beforeUC=[] + FS_beforeUC=[] + Pmachine_beforeUC=[] + LStable_beforeUC=[] + FStable_beforeUC=[] + Output_beforeUC = [] + + outputSampleAll=NumericalSample(0,9) + inputSample=[] + redirect.psse2py() + #import pssdb + psspy.psseinit(80000) + + # Silent execution of PSSe + islct=6 # 6=no output; 1=standard + psspy.progress_output(islct) + + + x_copy = [] + for ite in range(len(x)): + xite = [] + for j in range(len(x[ite])): + xite.append(x[ite][j]) + x_copy.append(xite) + + + for ite in range(len(x)): + + position+=1 + os.chdir(doc_base) #to work in right directory of the package + # Load data from PSSe + psspy.case(doc_base+'/BaseCase.sav') #Launching of PSSE and opening the working file + all_inputs_base=read_sav(doc_base+'/BaseCase.sav') + buses_base=all_inputs_base[0] + lines_base=all_inputs_base[1] + transf_base=all_inputs_base[2] + plants_base=all_inputs_base[3] + loads_base=all_inputs_base[4] + shunt_base=all_inputs_base[5] + motors_base=all_inputs_base[6] + transf3_base=all_inputs_base[7] + swshunt_base=all_inputs_base[8] + #Calculate Losses: + P_load = 0 + for load in loads_base: + P_load += load[1] + for motor in motors_base: + P_load+= motor[1] + P_gen = 0 + for gen in plants_base: + busnum = gen[0] + genid = gen[2].strip() + pgen = gen[3] + P_gen+=pgen + Losses = P_gen - P_load + LossesRatio = (Losses/P_load)*1.25 #overestimate losses to avoid surpassing swing bus capacity after economic dispatch + doci=os.path.join(doc_base,"Case_"+str(position)+".sav") + doci_beforeUC = os.path.join(doc_base,"Case_beforeUC_" + str(position) + ".sav") + psspy.save(doci) + # Total initial (fixed) shunt on buses + init_shunt = 0 + for i in range(len(shunt_base)) : + init_shunt += float(shunt_base[i][2]) + # Configuration de l'OPF a partir des parametres de l'utilisateur + TapChange = 1-int(dico['PSSEParams']['LOCK_TAPS']) #0 if locked, 1 if stepping + psspy.report_output(6,"",[0,0]) #6=no output + if PSSEParams['ALGORITHM']=='Optimum Power Flow': + if Debug: + print 'Got to OPF parametrization' + logfile = os.path.join(doc_base,r"""DETAIL""") + psspy.produce_opf_log_file(1,logfile) + psspy.opf_fix_tap_ratios(1-TapChange) #0 : do not fix transformer tap ratios + psspy.minimize_fuel_cost(int(dico['PSSEParams']['FUEL_COST'])) + psspy.minimize_adj_bus_shunts(int(dico['PSSEParams']['MVAR_COST'])) + psspy.minimize_load_adjustments(int(dico['PSSEParams']['LOADSHEDDING_COST'])) + #psspy.minimize_load_adjustments(False) #block load adjustments during application of laws + #psspy.initial_opf_barrier_coeff(100) + #psspy.final_opf_barrier_coeff(0.0001) + #psspy.opf_step_length_tolerance(0.00001) + #psspy.opf_fix_all_generators(0) + psspy.set_opf_report_subsystem(3,1) + psspy.solution_parameters_4([PSSEParams['ITERATION_LIMIT'],PSSEParams['ITERATION_LIMIT'],PSSEParams['ITERATION_LIMIT'],_i,_i], [_f]*19) + #[1.6, 1.6, 1, 0.0001, 1, 1, 1, 0.00001, 5, 0.7, 0.0001, 0.005, 1, 0.05, 0.99, 0.99, 1, 0.0001, 100]) + + else: #economic dispatch + ecd_file = PSSEParams['ecd_file'] + # 1. Affiche + nx = len(x[0]) + if TStest==1 : + for i,law in enumerate(LawsList): + if Xt[ite][i] == -1 : + if law != 'N_1_fromFile': + if 'Availability' in dico['Laws'][law]['Type']: + status = int(round(x[ite][i])) #idealement on a tiré un chiffre entre 0 et 1, 0 et 1 inclus + status = min(status,1) #on force status à avoir une valeur 0 ou 1 + status = max(status,0) + x_copy[ite][i]=status + if dico['Laws'][law]['ComponentType']=='Generator' and 'Level' in dico['Laws'][law]['Type']: + if dico['Laws'][law]['TransferFunction']==True: + if dico['Laws'][law]['TF_Input']=='.pow file': + z_WS = dico['Laws'][law]['Wind_Speed_Measurement_Height'] + pathWT = dico['Laws'][law]['File_Name'] + HH = dico['Laws'][law]['Hub_Height'] + alpha = dico['Laws'][law]['AlphaWS'] + PercentLoss = dico['Laws'][law]['Percent_Losses'] + x_copy[ite][i]=eol(np.array([x[ite][i]]), z_WS, pathWT, HH, alpha, PercentLoss)[0] + elif dico['Laws'][law]['TF_Input']=='tuples list': + x_copy[ite][i]=applyTF(x[ite][i], dico['Laws'][law]['TF_Values']) + else: #ensure values are between 0 and 1 + Pval = x[ite][i] + Pval = min(Pval,1) + Pval = max(Pval,0) + x_copy[ite][i]=Pval + else: #law=='N_1_fromFile" + x_copy[ite][i]==int(floor(x[ite][i])) + + else: + x_copy[ite][i]=float(Xt[ite][i]) # Dans le cas d'une etude temporelle on lui donne la valeur de Xt + + else : + for i,law in enumerate(LawsList): + if law != 'N_1_fromFile': + if 'Availability' in dico['Laws'][law]['Type']: + status = int(round(x[ite][i])) #idealement on a tiré un chiffre entre 0 et 1, 0 et 1 inclus + status = min(status,1) #on force status à avoir une valeur 0 ou 1 + status = max(status,0) + x_copy[ite][i]=status + if dico['Laws'][law]['ComponentType']=='Generator' and 'Level' in dico['Laws'][law]['Type']: + if dico['Laws'][law]['TransferFunction']==True: + if dico['Laws'][law]['TF_Input']=='.pow file': + z_WS = dico['Laws'][law]['Wind_Speed_Measurement_Height'] + pathWT = dico['Laws'][law]['File_Name'] + HH = dico['Laws'][law]['Hub_Height'] + alpha = dico['Laws'][law]['AlphaWS'] + PercentLoss = dico['Laws'][law]['Percent_Losses'] + x_copy[ite][i]=eol(np.array([x[ite][i]]), z_WS, pathWT, HH, alpha, PercentLoss)[0] + #x_copy[ite][i]=x[ite][i] + elif dico['Laws'][law]['TF_Input']=='tuples list': + x_copy[ite][i]=applyTF(x[ite][i], dico['Laws'][law]['TF_Values']) + else: #ensure values are between 0 and 1 + Pval = x[ite][i] + Pval = min(Pval,1) + Pval = max(Pval,0) + x_copy[ite][i]=Pval + else: #law=='N_1_fromFile" + x_copy[ite][i]==int(floor(x[ite][i])) + inputSample.append(np.array(x[ite])) + + if PSSEParams['ALGORITHM']=='Optimum Power Flow': + #get OPF data + allbus=1 + include = [1,1,1,1] #isolated buses, out of service branches, subsystem data, subsystem tie lines + out = 0 #out to file, not window + # if psspy.bsysisdef(0): + # sid = 0 + # else: # Select subsytem with all buses + # sid = -1 + sid = 3 + RopFile = os.path.join(dico['doc_base'],"BaseCase.rop" ) + AlreadyRop=os.path.isfile(RopFile) + if not AlreadyRop: + ierr = psspy.rwop(sid,allbus,include,out,RopFile) #write rop file + + GenDispatchData, DispTableData, LinCostTables, QuadCostTables, PolyCostTables, GenReserveData, PeriodReserveData,AdjBusShuntData,AdjLoadTables = readOPFdata(RopFile) + + if Debug: + print "Starting application of laws" + + # 2. Fait le calcul avec PSSE + + #Editing some values in the PSSE .sav input file + x2 = [] #list to store sampled values for logger function + for i,law in enumerate(LawsList): + if law != 'N_1_fromFile': + + #Reserve Constraint Law: change level of required reserve for a period reserve constraint + if dico['Laws'][law]['ComponentType']=='Reserve Constraint': + ReserveID = dico['Laws'][law]['ReserveID'] + ReserveFound = False + ReserveActive=False + for PRD in PeriodReserveData: + if PRD[0] == ReserveID: + ReserveFound=True + ReserveActive=PRD[3] + if not ReserveFound: + print 'ALERT: ReserveID ', str(ReserveID), ' is not found. User must define period reserve in .sav file before incluing a distribution on the reserve constraint in PSEN.' + elif not ReserveActive: + print 'ALERT: Spinning Reserve Correction entered in PSEN, but ReserveID ', str(ReserveID), ' is not activated in PSS/E.' + else: + status=_i #enabled/not enabled + level=x_copy[ite][i] #MW + timeframe = _f #minutes + psspy.opf_perrsv_main(ReserveID,status,[level, timeframe]) #change reserve constraint level + x2.append(x_copy[ite][i]) #store values for logger function + + # Load Law: change the values of the different loads and treat large changes of load to help convergence + #if dico['Laws'][law]['ComponentType']=='Load' and ('N_1' not in law) and ('out' not in law.lower()): + if dico['Laws'][law]['ComponentType']=='Load' and ('Availability' not in dico['Laws'][law]['Type']): + LoadList = dico['Laws'][law]['Load'] + if x_copy[ite][i] > 0.75 : # On change directement l(es) charge(s) + for LoadName in LoadList: + busNum = dico['Loads'][LoadName]['NUMBER'] + ID = dico['Loads'][LoadName]['ID'] + P = dico['Loads'][LoadName]['P'] + Q = dico['Loads'][LoadName]['Q'] + psspy.load_chng_4(busNum,ID,[_i,_i,_i,_i,_i,_i],[x_copy[ite][i]*P,x_copy[ite][i]*Q,_f,_f,_f,_f]) + + elif x_copy[ite][i] > 0.4 : # On effectue un pretraitement en passant par une charge intermediaire + for LoadName in LoadList: + busNum = dico['Loads'][LoadName]['NUMBER'] + ID = dico['Loads'][LoadName]['ID'] + P = dico['Loads'][LoadName]['P'] + Q = dico['Loads'][LoadName]['Q'] + psspy.load_chng_4(busNum,ID,[_i,_i,_i,_i,_i,_i],[(1+x_copy[ite][i])/2*P,(1+x_copy[ite][i])/2*Q,_f,_f,_f,_f]) + if PSSEParams['ALGORITHM']=='Optimum Power Flow': + if Debug: + print 'OPF load 1' + psspy.bsys(3,0,[0.0,0.0],0,[],1,[1],0,[],0,[]) + psspy.set_opf_report_subsystem(3,0) + psspy.nopf(0,1) # Lancement OPF + postOPFinitialization(doci,all_inputs_init,AdjLoadTables,init_gen=False,init_bus=False,init_fxshnt=True,init_swshnt=False,init_load=True,init_P0=False) + #psspy.fnsl([0, _i, 0, 0, 0, 0, _i,_i]) # Load flow Newton Raphson + else: + if Debug: + print "Economic Dispatch load 1" + #economic dispatch + EcdErrorCodes, LFcode, Plimit, Qlimit = EconomicDispatch(doci, ecd_file, LossesRatio, TapChange) + if Debug: + print "Returned from EconomicDispatch" + if np.any(np.array(EcdErrorCodes)!=0): + print "Error in economic dispatch." + for LoadName in LoadList : # On change toutes les charges + busNum = dico['Loads'][LoadName]['NUMBER'] + ID = dico['Loads'][LoadName]['ID'] + P = dico['Loads'][LoadName]['P'] + Q = dico['Loads'][LoadName]['Q'] + psspy.load_chng_4(busNum,ID,[_i,_i,_i,_i,_i,_i],[x_copy[ite][i]*P,x_copy[ite][i]*Q,_f,_f,_f,_f]) + + else : # On effectue un pretraitement en passant par une charge intermediaire + for LoadName in LoadList: + busNum = dico['Loads'][LoadName]['NUMBER'] + ID = dico['Loads'][LoadName]['ID'] + P = dico['Loads'][LoadName]['P'] + Q = dico['Loads'][LoadName]['Q'] + psspy.load_chng_4(busNum,ID,[_i,_i,_i,_i,_i,_i],[0.7*P,0.7*Q,_f,_f,_f,_f]) + + if PSSEParams['ALGORITHM']=='Optimum Power Flow': + if Debug: + print 'OPF load 2a' + psspy.bsys(3,0,[0.0,0.0],0,[],1,[1],0,[],0,[]) + psspy.set_opf_report_subsystem(3,0) + psspy.nopf(0,1) # Lancement OPF + postOPFinitialization(doci,all_inputs_init,AdjLoadTables,init_gen=False,init_bus=False,init_fxshnt=True,init_swshnt=False,init_load=True,init_P0=False) + #psspy.fnsl([0, _i, 0, 0, 0, 0, _i,_i]) # Load flow Newton Raphson + else: + if Debug: + print "Economic Dispatch load 2" + #economic dispatch + EcdErrorCodes, LFcode, Plimit, Qlimit = EconomicDispatch(doci, ecd_file, LossesRatio, TapChange) + if np.any(np.array(EcdErrorCodes)!=0): + print "Error in economic dispatch." + + for LoadName in LoadList : # On change toutes les charges + busNum = dico['Loads'][LoadName]['NUMBER'] + ID = dico['Loads'][LoadName]['ID'] + P = dico['Loads'][LoadName]['P'] + Q = dico['Loads'][LoadName]['Q'] + psspy.load_chng_4(busNum,ID,[_i,_i,_i,_i,_i,_i],[0.4*P,0.4*Q,_f,_f,_f,_f]) + if PSSEParams['ALGORITHM']=='Optimum Power Flow': + if Debug: + print 'OPF load 2b' + psspy.bsys(3,0,[0.0,0.0],0,[],1,[1],0,[],0,[]) + psspy.set_opf_report_subsystem(3,0) + psspy.nopf(0,1) # Lancement OPF + postOPFinitialization(doci,all_inputs_init,AdjLoadTables,init_gen=False,init_bus=False,init_fxshnt=True,init_swshnt=False,init_load=True,init_P0=False) + #psspy.fnsl([0, _i, 0, 0, 0, 0, _i,_i]) # Load flow Newton Raphson + else: + #economic dispatch + EcdErrorCodes, LFcode, Plimit, Qlimit = EconomicDispatch(doci, ecd_file, LossesRatio, TapChange) + if np.any(np.array(EcdErrorCodes)!=0): + print "Error in economic dispatch." + if Debug: + print "Economic Dispatch load 2" + for LoadName in LoadList : # On change toutes les charges + busNum = dico['Loads'][LoadName]['NUMBER'] + ID = dico['Loads'][LoadName]['ID'] + P = dico['Loads'][LoadName]['P'] + Q = dico['Loads'][LoadName]['Q'] + psspy.load_chng_4(busNum,ID,[_i,_i,_i,_i,_i,_i],[x_copy[ite][i]*P,x_copy[ite][i]*Q,_f,_f,_f,_f]) + x2.append(x_copy[ite][i]) #store values sampled for logger function + # Motor Load Law: change the values of the different induction motor loads and treat large changes of load to help convergence + #if dico['Laws'][law]['ComponentType']=='Motor' and ('N_1' not in law) and ('out' not in law.lower()): + if dico['Laws'][law]['ComponentType']=='Motor' and ('Availability' not in dico['Laws'][law]['Type']): + MotorList = dico['Laws'][law]['Motor'] + if x_copy[ite][i] > 0.75 : # On change directement l(es) charge(s) + for MotorName in MotorList: + busNum = dico['Motors'][MotorName]['NUMBER'] + ID = dico['Motors'][MotorName]['ID'] + Mbase = dico['Motors'][MotorName]['MBASE'] + BaseCode = dico['Motors'][MotorName]['BASECODE'] + Pinit = dico['Motors'][MotorName]['P'] + Qinit = dico['Motors'][MotorName]['Q'] + if BaseCode==2: #max is in MVA + PF = Pinit/((Pinit**2+Qinit**2)**0.5) + Pmax = PF*Mbase + else: + Pmax = Mbase + I_list = [_i]*9 + F_list = [_f]*23 + F_list[2]=x_copy[ite][i]*Pmax + psspy.induction_machine_chng(busNum,ID,I_list,F_list) + + elif x_copy[ite][i] > 0.4 : # On effectue un pretraitement en passant par une charge intermediaire + for MotorName in MotorList: + busNum = dico['Motors'][MotorName]['NUMBER'] + ID = dico['Motors'][MotorName]['ID'] + Mbase = dico['Motors'][MotorName]['MBASE'] + BaseCode = dico['Motors'][MotorName]['BASECODE'] + Pinit = dico['Motors'][MotorName]['P'] + Qinit = dico['Motors'][MotorName]['Q'] + if BaseCode==2: #max is in MVA + PF = Pinit/((Pinit**2+Qinit**2)**0.5) + Pmax = PF*Mbase + else: + Pmax = Mbase + I_list = [_i]*9 + F_list = [_f]*23 + F_list[2]=x_copy[ite][i]*Pmax*0.7 + psspy.induction_machine_chng(busNum,ID,I_list,F_list) + if PSSEParams['ALGORITHM']=='Optimum Power Flow': + if Debug: + print 'OPF motor load 1' + psspy.bsys(3,0,[0.0,0.0],0,[],1,[1],0,[],0,[]) + psspy.set_opf_report_subsystem(3,0) + psspy.nopf(0,1) # Lancement OPF + postOPFinitialization(doci,all_inputs_init,AdjLoadTables,init_gen=False,init_bus=False,init_fxshnt=True,init_swshnt=False,init_load=True,init_P0=False) + #psspy.fnsl([0, _i, 0, 0, 0, 0, _i,_i]) # Load flow Newton Raphson + else: + #economic dispatch + EcdErrorCodes, LFcode, Plimit, Qlimit = EconomicDispatch(doci, ecd_file, LossesRatio, TapChange) + if np.any(np.array(EcdErrorCodes)!=0): + print "Error in economic dispatch." + + for MotorName in MotorList: + busNum = dico['Motors'][MotorName]['NUMBER'] + ID = dico['Motors'][MotorName]['ID'] + Mbase = dico['Motors'][MotorName]['MBASE'] + BaseCode = dico['Motors'][MotorName]['BASECODE'] + Pinit = dico['Motors'][MotorName]['P'] + Qinit = dico['Motors'][MotorName]['Q'] + if BaseCode==2: #max is in MVA + PF = Pinit/((Pinit**2+Qinit**2)**0.5) + Pmax = PF*Mbase + else: + Pmax = Mbase + I_list = [_i]*9 + F_list = [_f]*23 + F_list[2]=x_copy[ite][i]*Pmax + psspy.induction_machine_chng(busNum,ID,I_list,F_list) + + else : # On effectue un pretraitement en passant par une charge intermediaire + for MotorName in MotorList: + busNum = dico['Motors'][MotorName]['NUMBER'] + ID = dico['Motors'][MotorName]['ID'] + Mbase = dico['Motors'][MotorName]['MBASE'] + BaseCode = dico['Motors'][MotorName]['BASECODE'] + Pinit = dico['Motors'][MotorName]['P'] + Qinit = dico['Motors'][MotorName]['Q'] + if BaseCode==2: #max is in MVA + PF = Pinit/((Pinit**2+Qinit**2)**0.5) + Pmax = PF*Mbase + else: + Pmax = Mbase + I_list = [_i]*9 + F_list = [_f]*23 + F_list[2]=x_copy[ite][i]*Pmax*0.7 + psspy.induction_machine_chng(busNum,ID,I_list,F_list) + if PSSEParams['ALGORITHM']=='Optimum Power Flow': + if Debug: + print 'OPF motor load 2a' + psspy.bsys(3,0,[0.0,0.0],0,[],1,[1],0,[],0,[]) + psspy.set_opf_report_subsystem(3,0) + psspy.nopf(0,1) # Lancement OPF + postOPFinitialization(doci,all_inputs_init,AdjLoadTables,init_gen=False,init_bus=False,init_fxshnt=True,init_swshnt=False,init_load=True,init_P0=False) + #psspy.fnsl([0, _i, 0, 0, 0, 0, _i,_i]) # Load flow Newton Raphson + else: + #economic dispatch + EcdErrorCodes, LFcode, Plimit, Qlimit = EconomicDispatch(doci, ecd_file, LossesRatio, TapChange) + if np.any(np.array(EcdErrorCodes)!=0): + print "Error in economic dispatch." + + for MotorName in MotorList: + busNum = dico['Motors'][MotorName]['NUMBER'] + ID = dico['Motors'][MotorName]['ID'] + Mbase = dico['Motors'][MotorName]['MBASE'] + BaseCode = dico['Motors'][MotorName]['BASECODE'] + Pinit = dico['Motors'][MotorName]['P'] + Qinit = dico['Motors'][MotorName]['Q'] + if BaseCode==2: #max is in MVA + PF = Pinit/((Pinit**2+Qinit**2)**0.5) + Pmax = PF*Mbase + else: + Pmax = Mbase + I_list = [_i]*9 + F_list = [_f]*23 + F_list[2]=x_copy[ite][i]*Pmax*0.4 + psspy.induction_machine_chng(busNum,ID,I_list,F_list) + if PSSEParams['ALGORITHM']=='Optimum Power Flow': + if Debug: + print 'OPF motor load 2b' + psspy.bsys(3,0,[0.0,0.0],0,[],1,[1],0,[],0,[]) + psspy.set_opf_report_subsystem(3,0) + psspy.nopf(0,1) # Lancement OPF + postOPFinitialization(doci,all_inputs_init,AdjLoadTables,init_gen=False,init_bus=False,init_fxshnt=True,init_swshnt=False,init_load=True,init_P0=False) + #psspy.fnsl([0, _i, 0, 0, 0, 0, _i,_i]) # Load flow Newton Raphson + else: + #economic dispatch + EcdErrorCodes, LFcode, Plimit, Qlimit = EconomicDispatch(doci, ecd_file, LossesRatio, TapChange) + if np.any(np.array(EcdErrorCodes)!=0): + print "Error in economic dispatch." + + for MotorName in MotorList: + busNum = dico['Motors'][MotorName]['NUMBER'] + ID = dico['Motors'][MotorName]['ID'] + Mbase = dico['Motors'][MotorName]['MBASE'] + BaseCode = dico['Motors'][MotorName]['BASECODE'] + Pinit = dico['Motors'][MotorName]['P'] + Qinit = dico['Motors'][MotorName]['Q'] + if BaseCode==2: #max is in MVA + PF = Pinit/((Pinit**2+Qinit**2)**0.5) + Pmax = PF*Mbase + else: + Pmax = Mbase + I_list = [_i]*9 + F_list = [_f]*23 + F_list[2]=x_copy[ite][i]*Pmax + psspy.induction_machine_chng(busNum,ID,I_list,F_list) + x2.append(x_copy[ite][i]) #store values sampled for logger function + # Generator Law : Change generation level + #if dico['Laws'][law]['ComponentType']=='Generator' and ('N_1' not in law) and ('out' not in law.lower()): + if dico['Laws'][law]['ComponentType']=='Generator' and ('Availability' not in dico['Laws'][law]['Type']): + GenList = dico['Laws'][law]['Generator'] + for GenName in GenList: + busNum = dico['Generators'][GenName]['NUMBER'] + ID = dico['Generators'][GenName]['ID'] + Pmax = dico['Generators'][GenName]['PMAX'] + Pmin = dico['Generators'][GenName]['PMIN'] + if Pmin < 0 and abs(Pmin) > Pmax: #motor, not generator + psspy.machine_chng_2(busNum,ID,[_i,_i,_i,_i,_i,_i],\ + [x_copy[ite][i]*Pmin,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) + else: #generator + psspy.machine_chng_2(busNum,ID,[_i,_i,_i,_i,_i,_i],\ + [x_copy[ite][i]*Pmax,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) + x2.append(x_copy[ite][i]) #store values sampled for logger function + #Line or Transformer Availability Law: disconnect component if sample=0 + elif dico['Laws'][law]['ComponentType']=='Line' or dico['Laws'][law]['ComponentType']=='Transformer': + compType = dico['Laws'][law]['ComponentType'] + CompList = dico['Laws'][law][compType] + + for Name in CompList: + from_bus = dico[compType + 's'][Name]['FROMNUMBER'] + to_bus = dico[compType+ 's'][Name]['TONUMBER'] + + ID = dico[compType+ 's'][Name]['ID'] + if compType=='Line': + psspy.branch_chng(from_bus,to_bus,ID,[x_copy[ite][i],_i,_i,_i,_i,_i],\ + [_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) + elif compType=='Transformer': + if dico[compType+ 's'][Name]['#WIND']==2: + i_args = [_i]*15 + i_args[0]=status + f_args = [_f]*24 + c_args = [_s]*2 + psspy.two_winding_chng_4(from_bus,to_bus,ID,i_args,f_args,c_args) + elif dico[compType+ 's'][Name]['#WIND']==3: + three_bus = dico[compType + 's'][Name]['3NUMBER'] + i_args = [_i]*12 + i_args[7]=status + f_args = [_f]*17 + c_args = [_s]*2 + psspy.three_wnd_imped_chng_3(from_bus,to_bus,three_bus,ID,i_args,f_args,c_args) + x2.append(x_copy[ite][i]) #store values sampled for logger function + + #Generator or Load or Motor Availability Law: disconnect component if sample = 0 + #elif (dico['Laws'][law]['ComponentType']=='Generator' and ('N_1' in law or 'out' in law.lower())) or\ + # (dico['Laws'][law]['ComponentType']=='Load' and ('N_1' in law or 'out' in law.lower())) or\ + # (dico['Laws'][law]['ComponentType']=='Motor' and ('N_1' in law or 'out' in law.lower())): + elif (dico['Laws'][law]['ComponentType']=='Generator' and ('Availability' in dico['Laws'][law]['Type'])) or\ + (dico['Laws'][law]['ComponentType']=='Load' and ('Availability' in dico['Laws'][law]['Type'])) or\ + (dico['Laws'][law]['ComponentType']=='Motor' and ('Availability' in dico['Laws'][law]['Type'])): + compType = dico['Laws'][law]['ComponentType'] + CompList = dico['Laws'][law][compType] + + for Name in CompList: + busNum = dico[compType + 's'][Name]['NUMBER'] + ID = dico[compType + 's'][Name]['ID'] + if compType=='Generator': + psspy.machine_chng_2(busNum,ID,[x_copy[ite][i],_i,_i,_i,_i,_i],\ + [_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) + elif compType=='Load': + psspy.load_chng_4(busNum,ID,[x_copy[ite][i],_i,_i,_i,_i,_i],[_f,_f,_f,_f,_f,_f]) + + elif compType=='Motor': + psspy.induction_machine_chng(busNum,ID,[x_copy[ite][i],_i,_i,_i,_i,_i,_i,_i,_i],[_f]*23) + x2.append(x_copy[ite][i]) #store values sampled for logger function + + #N-1 from file : systematic disconnection of a component + else: #law='N_1_fromFile' + if x_copy[ite][i]<0: + x2.append("") + pass + elif x_copy[ite][i] < len(continLines) : # L'element tire est une ligne + + line_num=int(x_copy[ite][i]) + line_name=continLines[int(line_num)] + + from_bus=dico['Lines'][line_name]['FROMNUMBER'] + to_bus=dico['Lines'][line_name]['TONUMBER'] + br_id=dico['Lines'][line_name]['ID'] + psspy.branch_chng(from_bus,to_bus,br_id,[0,_i,_i,_i,_i,_i],\ + [ _f, _f, _f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) + x2.append('Line '+str(from_bus)+'-'+str(to_bus)+'#'+str(br_id)) + + elif x_copy[ite][i] < (len(continLines)+len(continGroups)) : + + group_num = int(x_copy[ite][i])-len(continLines) + group_name = continGroups[int(group_num)] + bus_num = dico['Generators'][group_name]['NUMBER'] + bus_id = dico['Generators'][group_name]['ID'] + psspy.machine_chng_2(int(bus_num),str(bus_id),[0,_i,_i,_i,_i,_i],\ + [_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) # Disconnect component + psspy.opf_gendsp_indv(int(bus_num),str(bus_id),_i,0.0) + x2.append('Group '+str(bus_num)+'#'+str(bus_id)) + + elif x_copy[ite][i] < (len(continLines)+len(continGroups)+len(continTransfos)) : + transfo_num=int(x_copy[ite][i])-len(continLines)-len(continGroups) + transfo_name = continTransfos[int(transfo_num)] + from_bus= dico['Transformers'][transfo_name]['FROMNUMBER'] + to_bus=dico['Transformers'][transfo_name]['TONUMBER'] + ID=dico['Transformers'][transfo_name]['ID'] + + if dico['Transformers'][transfo_name]['#WIND']==2: + i_args = [_i]*15 + i_args[0]=0 + f_args = [_f]*24 + c_args = [_s]*2 + psspy.two_winding_chng_4(from_bus,to_bus,ID,i_args,f_args,c_args) + x2.append('Transfo '+str(from_bus)+'-'+str(to_bus)+'#'+str(ID)) + + elif dico['Transformers'][transfo_name]['#WIND']==3: + three_bus = dico['Transformers'][transfo_name]['3NUMBER'] + i_args = [_i]*12 + i_args[7]=0 + f_args = [_f]*17 + c_args = [_s]*2 + psspy.three_wnd_imped_chng_3(from_bus,to_bus,three_bus,ID,i_args,f_args,c_args) + x2.append('Transfo '+str(from_bus)+'-'+str(to_bus)+'-'+str(three_bus)+'#'+str(ID)) + + elif x_copy[ite][i] < (len(continLines)+len(continGroups)+len(continTransfos)+len(continLoads)) : + + load_num = int(x_copy[ite][i])-len(continLines)-len(continGroups)-len(continTransfos) + load_name = continLoads[int(load_num)] + bus_num = dico['Loads'][load_name]['NUMBER'] + ID = dico['Loads'][load_name]['ID'] + psspy.load_chng_4(int(bus_num),str(ID),[0,_i,_i,_i,_i,_i],[_f,_f,_f,_f,_f,_f]) # Disconnect component + x2.append('Load '+str(bus_num)+'#'+str(ID)) + + elif x_copy[ite][i] < (len(continLines)+len(continGroups)+len(continTransfos)+len(continLoads)+len(continMotors)) : + motor_num = int(x_copy[ite][i])-len(continLines)-len(continGroups)-len(continTransfos)-len(continLoads) + motor_name = continMotors[int(motor_num)] + bus_num = dico['Motors'][motor_name]['NUMBER'] + ID = dico['Motors'][motor_name]['ID'] + psspy.induction_machine_chng(int(bus_num),str(ID),[0,_i,_i,_i,_i,_i,_i,_i,_i],[_f]*23) # Disconnect component + x2.append('Motor '+str(bus_num)+'#'+str(ID)) + else : + pass + + psspy.save(doci) #Saving .sav modifications + + if PSSEParams['ALGORITHM']=='Optimum Power Flow': + #save OPF data + allbus=1 + include = [1,1,1,1] #isolated buses, out of service branches, subsystem data, subsystem tie lines + out = 0 #out to file, not window + # if psspy.bsysisdef(0): + # sid = 0 + # else: # Select subsytem with all buses + # sid = -1 + sid = 3 + RopFile = os.path.join(dico['doc_base'],"BaseCase.rop" ) + AlreadyRop=os.path.isfile(RopFile) + if not AlreadyRop: + ierr = psspy.rwop(sid,allbus,include,out,RopFile) #write rop file + + ok = True + + if Debug: + print "Finished applying laws" + loadShed = [] + fxshnt = [] + indexLS = [] + indexFS = [] + indicLS = 0 + indicFS = 0 + xstrings = ['mvaact'] + ierr, xdata1 = psspy.aloadcplx(-1, 1, xstrings) + istrings = ['number'] + ierr, idata = psspy.aloadint(-1, 1, istrings) + cstrings = ['name'] + ierr, cdata = psspy.aloadchar(-1, 1, cstrings) + bistrings = ['number'] + ierr, bidata1 = psspy.afxshuntint(-1, 1, bistrings) + bxstrings = ['shuntnom'] + ierr, bxdata1 = psspy.afxshuntcplx(-1, 1, bxstrings) + bcstrings = ['id'] + ierr, bcdata1 = psspy.afxshuntchar(-1, 1, bcstrings) + #Unit commitment pass only valid for OPF (economic dispatch turns on and off generators) + ##=========================================================================# + if PSSEParams['ALGORITHM']=='Optimum Power Flow': + # First OPF to disconnect all generators at P=0 + if dico['UnitCommitment']: + #increase load by reserve level so that after unit commitment there are enough groups to provide reserve + GenDispatchData, DispTableData, LinCostTables, QuadCostTables, PolyCostTables, GenReserveData, PeriodReserveData,AdjBusShuntData,AdjLoadTables = readOPFdata(RopFile) + ReserveFound=False + TotalReserveLevel = 0 + AllReserveActive = [] + for num in range(1,16): #16 potential reserves defined in OPF + keyname = 'SpinningReserveID_'+str(int(num)) + if PSSEParams.has_key(keyname): + ReserveID = PSSEParams[keyname] + for PRD in PeriodReserveData: + if PRD[0]==ReserveID: + ReserveFound=True + ReserveActive = PRD[3] + ReserveLevel = PRD[1] + AllReserveActive.append(ReserveActive) + TotalReserveLevel += ReserveActive*ReserveLevel + #print('Total Reserve = ', str(TotalReserveLevel)) + if ReserveFound and any(AllReserveActive): + outputs = read_sav(doci) + loads = outputs[4] + total_load = 0 + for load in loads: + total_load += load[1] + + x_with_reserve = (total_load + TotalReserveLevel)/total_load + x_remove_reserve = 1.0/x_with_reserve + for load in loads: + busNum = load[0] + ID = load[5] + P = load[1] + Q = load[2] + psspy.load_chng_4(busNum,ID,[_i,_i,_i,_i,_i,_i],[x_with_reserve*P,x_with_reserve*Q,_f,_f,_f,_f]) + + #set Pmin so necessary units to supply reserve are not disconnected + if ReserveCorrection: + NoDisconnectionAllowedTotal = [] + for res in PeriodReserveData: + ResNum = res[0] + ResLevel = res[1] + ResPeriod = res[2] + InService = res[3] + if InService == 0: + continue + ParticipatingUnits = res[4] + ParticipatingUnitsFull = [] + NoDisconnectionAllowed = [] + for unit in ParticipatingUnits: + busNum = unit[0] + ID = unit[1] + + for gen in GenReserveData: + busNum2 = gen[0] + ID2 = gen[1] + if busNum==busNum2 and ID == ID2: + ramp =gen[2] + #Pmax = gen[3] + break + + for gen in GenDispatchData: + busNum3 = gen[0] + ID3 = gen[1] + if busNum==busNum3 and ID == ID3: + dispatch = gen[2] + dispTable = gen[3] + break + + for dTable in DispTableData: + dispTable2 = dTable[0] + if dispTable == dispTable2: + PmaxTable = dTable[1] + Pmax = PmaxTable #take Pmax from dispatch table to avoid errors + PminTable = dTable[2] + FuelCostScaleCoef = dTable[3] + CurveType = dTable[4] #2 = piece wise linear, + Status = dTable[5] + CostTable = dTable[6] + break + + for table in LinCostTables: + CostTable2 = table[0] + if CostTable2==CostTable: + numpoints = table[1] + points = table[2] + break + + MaxContribution = min(ResPeriod * ramp, Pmax) + + for i,[x_,y_] in enumerate(points): + if x_ > Pmax: + x1 = x_ + y1 = y_ + x0 = points[i-1][0] + y0 = points[i-1][1] + break + y_i = (y1 - y0)*Pmax/(x1-x0) + + if Pmax > 0: + CostCoef = y_i / Pmax + else: + #pdb.set_trace() + CostCoef = 0 + + ParticipatingUnitsFull.append([busNum, ID, Pmax, dispTable, MaxContribution, CostCoef]) + + ParticipatingUnitsFull.sort(key=lambda d: d[-1], reverse=False) + ReserveCapability = 0 + + for unit in ParticipatingUnitsFull: + MaxContribution = unit[4] + if ReserveCapability >= ResLevel: + break + else: + ReserveCapability += MaxContribution + dispTable = unit[3] + Pmax = unit[2] + busNum = unit[0] + ID = unit[1] + NoDisconnectionAllowed.append([busNum, ID]) + Pmin = (DisconnectThreshhold*1.1)*Pmax + psspy.opf_apdsp_tbl(dispTable,[_i,_i,_i],[_f, Pmin,_f]) + + for grp in NoDisconnectionAllowed: + if grp not in NoDisconnectionAllowedTotal: + NoDisconnectionAllowedTotal.append(grp) + + else: + pass + + #psspy.minimize_load_adjustments(int(dico['PSSEParams']['LOADSHEDDING_COST'])) #now apply load shedding + #save new load levels to be able to initialize after opf run + psspy.save(doci) #Saving .sav modifications + all_inputs_base=read_sav(doci) + loads_base=all_inputs_base[4] + all_inputs_init_i =[] + for h, inputs in enumerate(all_inputs_init): + if h != 4: + all_inputs_init_i.append(inputs) + else: + all_inputs_init_i.append(loads_base) + + + if PSSEParams['ALGORITHM']=='Optimum Power Flow': + # First OPF to disconnect all generators at P=0 + if dico['UnitCommitment']: + + if Debug: + print "principal OPF before unit commitment" + + loadShed = [] + fxshnt = [] + + indexLS = [] + indexFS = [] + + indicLS = 0 + indicFS = 0 + + xstrings = ['mvaact'] + ierr, xdata1 = psspy.aloadcplx(-1, 1, xstrings) + istrings = ['number'] + ierr, idata = psspy.aloadint(-1, 1, istrings) + cstrings = ['name'] + ierr, cdata = psspy.aloadchar(-1, 1, cstrings) + + bistrings = ['number'] + ierr, bidata1 = psspy.afxshuntint(-1, 1, bistrings) + bxstrings = ['shuntnom'] + ierr, bxdata1 = psspy.afxshuntcplx(-1, 1, bxstrings) + bcstrings = ['id'] + ierr, bcdata1 = psspy.afxshuntchar(-1, 1, bcstrings) + + psspy.bsys(3,0,[0.0,0.0],0,[],1,[1],0,[],0,[]) + psspy.set_opf_report_subsystem(3,0) + psspy.nopf(0,1) # Lancement OPF + + ok = False + flagLS = 0 + flagFS = 0 + + # solved() => check if last solution attempt reached tolerance + # 0 = met convergence tolerance + # 1 = iteration limit exceeded + # 2 = blown up + # 3 = terminated by non-divergent option + # 4 = terminated by console input + # 5 = singular jacobian matrix or voltage of 0.0 detected + # 6 = inertial power flow dispatch error (INLF) + # 7 = OPF solution met convergence tolerance (NOPF) + # 8 does not exist ? + # 9 = solution not attempted + + if psspy.solved() == 7 or psspy.solved()==0: + pass + else: #run OPF in loop to attempt convergence + postOPFinitialization(doci,all_inputs_init_i,AdjLoadTables,init_gen=False,init_bus=False,init_fxshnt=True,init_swshnt=False,init_load=True,init_P0=False) + MAX_OPF = 5 # 5 = Nombre de lancement max de l'OPF pour atteindre la convergence de l'algorithme + for nbeOPF in range(0, MAX_OPF): + psspy.bsys(3,0,[0.0,0.0],0,[],1,[1],0,[],0,[]) + psspy.set_opf_report_subsystem(3,0) + psspy.nopf(0,1) # Lancement OPF + if psspy.solved()==7 or psspy.solved()==0: + break + else: + postOPFinitialization(doci,all_inputs_init_i,AdjLoadTables,init_gen=False,init_bus=False,init_fxshnt=True,init_swshnt=False,init_load=True,init_P0=False) + + #treat status of OPF + if psspy.solved() == 7 or psspy.solved()==0: + ok = True + elif psspy.solved() == 2: + print "OPF diverged. (before Q control)" + elif psspy.solved()== 3: + print "Terminated by non-divergent option. (before unit commitment)" + elif psspy.solved()== 4: + print "Terminated by console input. (before Q control)" + elif psspy.solved()== 5: + print "Singular jacobian matrix or voltage of 0.0 detected. (before unit commitment)" + elif psspy.solved()== 6: + print "Inertial power flow dispatch error (INLF) (before unit commitment)." + elif psspy.solved()== 8: + print "Solution does not exist. (before unit commitment)" + elif psspy.solved()== 9: + print "Solution not attempted. (before unit commitment)" + elif psspy.solved == 2: + print "OPF diverged. (before unit commitment)" + elif psspy.solved() == 1: #if iteration limit exceeded, try load flow + print "Iteration limit exceeded (before unit commitment), trying load flow." + # Newton-Raphson power flow calculation. Params: + # tap adjustment flag (0 = disable / 1 = enable stepping / 2 = enable direct) + # area interchange adjustement (0 = disable) + # phase shift adjustment (0 = disable) + # dc tap adjustment (1 = enable) + # switched shunt adjustment (1 = enable) + # flat start (0 = default / disabled, 1 = enabled), disabled parce qu'on n'est pas dans une situation de départ + # var limit (default = 99, -1 = ignore limit, 0 = apply var limit immediatly) + # non-divergent solution (0 = disable) + psspy.fnsl([0, _i, 0, 0, 0, 0, _i,_i]) + if psspy.solved() == 0: + ok=True + elif psspy.solved() == 2: + print "Load flow diverged. (before unit commitment)" + if ok: + # Returns an "array of complex values for subsystem loads" + ierr, xdata2 = psspy.aloadcplx(-1, 1, xstrings) # retrieve load MVA # Renvoie une liste de chaque load en format complexe (P+Q) + + # aFxShuntInt: return an array of integer values for subsystem fixed shunts + ierr, bidata2 = psspy.afxshuntint(-1, 1, bistrings) + + # aFxShuntCplx: return an array of complex values for sybsystem fixed shunts + ierr, bxdata2 = psspy.afxshuntcplx(-1, 1, bxstrings) # retrieve bus shunt MVar + + #Fixed shunt strings: return array of ids + ierr, bcdata2 = psspy.afxshuntchar(-1, 1, bcstrings) + + # Extraction of the load shedding quantities + for i in range(len(xdata2[0])): + if np.real(xdata1)[0][i] != np.real(xdata2)[0][i]: # np.real returns the real part of the elements in the given array + indexLS.append(i) + flagLS = 1 # rise flag loadshedding + try: # if / else would be better here ? + flagLS + except: + flagLS = 0 + else: + loadShed.append([position]) # Position seems to correspond to the number of the case we are treating + loadShed[0].extend(['' for i in range(len(indexLS)-1)]) # why [0] ? Maybe it would be better to have 2 lists ? Or a dict ? + loadShed.append([idata[0][i] for i in indexLS]) + loadShed.append([cdata[0][i] for i in indexLS]) + loadShed.append([np.real(xdata1)[0][i] - np.real(xdata2)[0][i] for i in indexLS]) + loadShed.append([np.real(xdata2)[0][i] for i in indexLS]) + indicLS = sum(loadShed[3]) # sum all Effective MW loads + loadShed = zip(*loadShed) # transpose the matrix + + # extraction adj. fixed shunt quantities + if len(bidata1[0]) == len(bidata2[0]): # one first opf may have occured... + # so we check first if both vectors have the same length + + for i in range(len(bxdata2[0])): + if np.imag(bxdata1)[0][i] != np.imag(bxdata2)[0][i]: # search for differences + indexFS.append(i) + flagFS = 1 # rise flag adj. bus shunt + try: + flagFS + except: + flagFS = 0 + else: + bxdata2[0] = [np.imag(bxdata2)[0][i] for i in indexFS] # fulfill output vector + bidata2[0] = [bidata1[0][i] for i in indexFS] + bcdata2[0] = [bcdata1[0][i] for i in indexFS] + g = -1 + while (g <= len(bidata2)): + g += 1 + try: + #if fabs(bxdata2[0][g]) < 1: # discard value in ]-1,1[ + if fabs(bxdata2[0][g]) < 0.001: # discard value in ]-1,1[ + # pdb.set_trace() + bxdata2[0].pop(g) + bidata2[0].pop(g) + bcdata2[0].pop(g) + g -= 1 + except: pass + if bxdata2[0] != []: # Get all fixed shunt buses + fxshnt.append([position]) + fxshnt[0].extend(['' for i in range(len(bxdata2[0]) - 1)]) # Same here => maybe two lists or a dict would be a better choice + fxshnt.append(bidata2[0]) + fxshnt.append(bxdata2[0]) + indicFS = sum(fxshnt[2]) + fxshnt = zip(*fxshnt) # transpose the matrix + flagFS = 1 + else: + flagFS = 0 + + else: # if not same length, bus data corresponding to the adjustable bus shunt have been added to the vector + for i in range(len(bidata1[0])): # remove bus data of bus which are not added after the opf + try: + bxdata2[0].pop(bxdata2[0].index(bxdata1[0][i])) + bidata2[0].pop(bidata2[0].index(bidata1[0][i])) + bcdata2[0].pop(bcdata2[0].index(bcdata1[0][i])) + except: + pass + g = -1 + bx = list(np.imag(bxdata2[0])) # retrieve Mvar + while g <= len(bidata2): + g += 1 + try: + if fabs(bx[g]) < 1: # discard value in ]-1,1[ + bx.pop(g) + bidata2[0].pop(g) + g -= 1 + except: pass + if bx != []: + fxshnt.append([position]) + fxshnt[0].extend(['' for i in range(len(bidata2[0]) - 1)]) + fxshnt.append(bidata2[0]) + fxshnt.append(bx) + indicFS = sum(fxshnt[2]) + fxshnt = zip(*fxshnt) + flagFS = 1 + else: + flagFS = 0 + + + if PSSEParams['SAVE_CASE_BEFORE_UNIT_COMMITMENT']: + psspy.save(doci_beforeUC) + all_inputs = read_sav(doci_beforeUC) + psspy.save(doci) + all_inputs = read_sav(doci) + + buses = all_inputs[0] + lines = all_inputs[1] + transf = all_inputs[2] + plants = all_inputs[3] + loads = all_inputs[4] + shunt = all_inputs[5] + motors = all_inputs[6] + transf3 = all_inputs[7] + swshunt = all_inputs[8] + + + gen_UC_list = [] + for item in plants: + bus = item[0] + status = item[1] + _id = item[2] + pgen = item[3] + qgen = item[4] + pmax = item[6] + name = item[7] + machine_type = item[11] + + #and if a conventional generating unit as specified in Machines tab of PSSE + if machine_type == 0: + if abs(pgen) <= pmax*DisconnectThreshhold: + if status==1: + #print('P < 5% of Pmax and Q > 0 at bus ' + str(bus) + ' gen ' + str(_id) + '--> generator disconnected.') + # disconnect the plant + pgen=0 + qgen=0 + status = 0 + psspy.machine_chng_2(bus, _id, [status,_i,_i,_i,_i,_i],[pgen,qgen,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) + gen_UC_list.append((bus,_id)) + elif machine_type==1: #renewable generator fixed Q limits + if abs(pgen) <= pmax*0.2 and DEWA_PV_Qlimits: #change q limits if P renewable is < 20% Pmax (DEWA grid code) + if status==1: + qmin = -0.04*pmax + qmax = 0.04*pmax + qgen=min(qmax,qgen) + qgen=max(qmin,qgen) + psspy.machine_chng_2(bus, _id, [_i,_i,_i,_i,_i,_i],[_f,qgen,qmax,qmin,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) + if abs(pgen) <= pmax*0.005 and Disconnect_RES: #disconnect if very low P + if status==1: + #print('P < 5% of Pmax and Q > 0 at bus ' + str(bus) + ' gen ' + str(_id) + '--> generator disconnected.') + # disconnect the plant + pgen=0 + qgen=0 + status = 0 + psspy.machine_chng_2(bus, _id, [status,_i,_i,_i,_i,_i],[pgen,qgen,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) + gen_UC_list.append((bus,_id)) + elif machine_type==2: #renewable generator with cos phi control + if abs(pgen) <= pmax*0.005 and Disconnect_RES: #disconnect if very low P + if status==1: + #print('P < 5% of Pmax and Q > 0 at bus ' + str(bus) + ' gen ' + str(_id) + '--> generator disconnected.') + # disconnect the plant + pgen=0 + qgen=0 + status = 0 + psspy.machine_chng_2(bus, _id, [status,_i,_i,_i,_i,_i],[pgen,qgen,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) + gen_UC_list.append((bus,_id)) + elif machine_type==3: #renewable generator with fixed Q based on cos phi control + if abs(pgen) <= pmax*0.005 and Disconnect_RES: #disconnect if very low P + if status==1: + #print('P < 5% of Pmax and Q > 0 at bus ' + str(bus) + ' gen ' + str(_id) + '--> generator disconnected.') + # disconnect the plant + pgen=0 + qgen=0 + status = 0 + psspy.machine_chng_2(bus, _id, [status,_i,_i,_i,_i,_i],[pgen,qgen,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) + gen_UC_list.append((bus,_id)) + elif machine_type==4: #infeed machine that's still considered renewable + if abs(pgen) <= pmax*0.005 and Disconnect_RES: #disconnect if very low P + if status==1: + #print('P < 5% of Pmax and Q > 0 at bus ' + str(bus) + ' gen ' + str(_id) + '--> generator disconnected.') + # disconnect the plant + pgen=0 + qgen=0 + status = 0 + psspy.machine_chng_2(bus, _id, [status,_i,_i,_i,_i,_i],[pgen,qgen,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f]) + gen_UC_list.append((bus,_id)) + # 3. Affiche Y + sizeY4 = len(shunt) + y_before = np.zeros(2 * sizeY0 + sizeY1 + 3 * sizeY2 + sizeY3 + 2*sizeY6 + sizeY4 + sizeY8 + 3 * sizeY5 + 3 * sizeY7) + z_before = [0]*13 # np.zeros returns a new array of the given shape and type filled with zeros + rate_mat_index = Irate_num + 2 + rate_mat_index_3w = Irate_num + 4 + Ymac_before = np.zeros(sizeY0) + if ok: + # Creates the quantities of interest + for i in range (sizeY2) : + if lines [i][rate_mat_index]>100 : + z_before[0]+=1 # Number of lines above 100% of their limits + for i in range (sizeY5) : + if transf [i][rate_mat_index]>100 : + z_before[1]+=1 # Number of transformers above 100% of their limits + for i in range (sizeY7) : + if transf3 [i][rate_mat_index_3w]>100 : + z_before[1]+=1 # Number of transformers above 100% of their limits (each winding of a 3 winding counted) + + for i in range (sizeY1): + if buses[i][2]>buses[i][5] : + z_before[2]+=1 + if buses[i][2]z_before[6] : + z_before[6]=lines[i][rate_mat_index] # Max flow in lines + for i in range (sizeY5) : + if transf [i][rate_mat_index]>z_before[7] : + z_before[7]=transf[i][rate_mat_index] # Max flow in transformers + for i in range (sizeY7) : + if transf3 [i][rate_mat_index_3w]>z_before[7] : + z_before[7]=transf3[i][rate_mat_index_3w] # Max flow in 3w transformers + + for i in range (sizeY2) : + if lines [i][rate_mat_index]>90 : + z_before[8]+=1 + z_before[8]=z_before[8]-z_before[0] # Number of lines between 90% and 100% of their limits + for i in range (sizeY5) : + if transf [i][rate_mat_index]>90 : + z_before[9]+=1 + for i in range (sizeY7) : + if transf3 [i][rate_mat_index_3w]>90 : + z_before[9]+=1 + + z_before[9]=z_before[9]-z_before[1] # Number of transformers between 90% and 100% of their limits + + z_before[10]=indicFS + + z_before[11]=indicLS + + z_before[12] = str(gen_UC_list) + + # Creates the output vectors + for Pmach in range (sizeY0): + y_before[Pmach]=float(plants[Pmach][3]) + Ymac_before[Pmach]=float(plants[Pmach][3]) + for Qmach in range (sizeY0): + y_before[Qmach+sizeY0]=float(plants[Qmach][4]) + for Vbus in range (sizeY1): + y_before[Vbus+2*sizeY0]=float(buses[Vbus][2]) + for Iline in range (sizeY2): + y_before[Iline+2*sizeY0+sizeY1]=float(lines[Iline][rate_mat_index]) + for Pline in range (sizeY2): + y_before[Pline+2*sizeY0+sizeY1+sizeY2]=float(lines[Pline][6]) + for Qline in range (sizeY2): + y_before[Qline+2*sizeY0+sizeY1+2*sizeY2]=float(lines[Qline][7]) + for Itrans in range (sizeY5): + y_before[Itrans+2*sizeY0+sizeY1+3*sizeY2]=float(transf[Itrans][rate_mat_index]) + for Ptrans in range (sizeY5): + y_before[Ptrans+2*sizeY0+sizeY1+3*sizeY2+sizeY5]=float(transf[Ptrans][6]) + for Qtrans in range (sizeY5): + y_before[Qtrans+2*sizeY0+sizeY1+3*sizeY2+2*sizeY5]=float(transf[Qtrans][7]) + for Itrans in range (sizeY7): + y_before[Itrans+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5]=float(transf3[Itrans][rate_mat_index_3w]) + for Ptrans in range (sizeY7): + y_before[Ptrans+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+sizeY7]=float(transf3[Ptrans][8]) + for Qtrans in range (sizeY7): + y_before[Qtrans+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+2*sizeY7]=float(transf3[Qtrans][9]) + for Pload in range (sizeY3) : + y_before[Pload+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+3*sizeY7]=float(loads[Pload][1]) + for Pmotor in range (sizeY6) : + y_before[Pmotor+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+3*sizeY7+sizeY3]=float(motors[Pmotor][1]) + for Qmotor in range (sizeY6) : + y_before[Qmotor+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+3*sizeY7+sizeY3+sizeY6]=float(motors[Qmotor][2]) + for Qshunt in range (sizeY4) : + y_before[Qshunt+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+3*sizeY7+sizeY3+2*sizeY6]=float(shunt[Qshunt][2]) + for Qshunt in range (sizeY8) : + y_before[Qshunt+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+3*sizeY7+sizeY3+2*sizeY6+sizeY4]=float(swshunt[Qshunt][4]) + nz = len(z_before) + + else : + print 'NON CONVERGENCE BEFORE UNIT COMMITMENT CASE '+str(position)+' CORE '+str(num_pac) + if TStest==1: + MyLogger(x2, y_before, z_before, dico['logCSVfilename_UC'][num_pac], timeVect[ite]) + else: + MyLogger(x2, y_before, z_before, dico['logCSVfilename_UC'][num_pac], position) + + #re-initialize OPF for post-unit commitment + postOPFinitialization(doci,all_inputs_init_i,AdjLoadTables,init_gen=False,init_bus=False,init_fxshnt=True,init_swshnt=False,init_load=True,init_P0=False) + all_inputs = read_sav(doci) + loads = all_inputs[4] + + #return load to original level post spinning reserve correction for unit commitment + for num in range(1,16): + keyname = 'SpinningReserveID_' + str(int(num)) + if PSSEParams.has_key(keyname): + ReserveID = PSSEParams[keyname] + ReserveFound=False + AllReserveActive = [] + for PRD in PeriodReserveData: + if PRD[0]==ReserveID: + ReserveFound=True + ReserveActive = PRD[3] + AllReserveActive.append(ReserveActive) + if ReserveFound and any(AllReserveActive): + for load in loads: + busNum = load[0] + ID = load[5] + P = load[1] + Q = load[2] + psspy.load_chng_4(busNum,ID,[_i,_i,_i,_i,_i,_i],[x_remove_reserve*P,x_remove_reserve*Q,_f,_f,_f,_f]) + psspy.save(doci) + else: + break + + #store loadshedding and added MVAR values for before UC + loadShed_beforeUC = loadShed + fxshnt_beforeUC = fxshnt + indexLS_beforeUC = indexLS + indexFS_beforeUC = indexFS + + indicLS_beforeUC = indicLS + indicFS_beforeUC = indicFS + + + + # Unit commitment pass only valid for OPF (economic dispatch turns on and off generators) + ##=========================================================================# + # nvm on FAIT deux passages, un puis on regarde les groupes P==0 Q!=0, on les déconnecte et on refait l'OPF + # Et on log : le % de cas où ça arrive, + # Combien de puissance réactive il nous faut en moyenne, + # Quelles sont les machines qui font ça + loadShed = [] + fxshnt = [] + indexLS = [] + indexFS = [] + indicLS = 0 + indicFS = 0 + flagLS = 0 + flagFS = 0 + ok = False + + xstrings = ['mvaact'] + ierr, xdata1 = psspy.aloadcplx(-1, 1, xstrings) + istrings = ['number'] + ierr, idata = psspy.aloadint(-1, 1, istrings) + cstrings = ['name'] + ierr, cdata = psspy.aloadchar(-1, 1, cstrings) + bistrings = ['number'] + ierr, bidata1 = psspy.afxshuntint(-1, 1, bistrings) + bxstrings = ['shuntnom'] + ierr, bxdata1 = psspy.afxshuntcplx(-1, 1, bxstrings) + bcstrings = ['id'] + ierr, bcdata1 = psspy.afxshuntchar(-1, 1, bcstrings) + + if Debug: + print "got to principal OPF/LF" + + #Solve OPF + if PSSEParams['ALGORITHM']=='Optimum Power Flow': + psspy.bsys(3,0,[0.0,0.0],0,[],1,[1],0,[],0,[]) + psspy.set_opf_report_subsystem(3,0) + psspy.nopf(0,1) # Lancement OPF + flagLS = 0 + flagFS = 0 + ok = False + #psspy.fnsl([0, _i, 0, 0, 0, 0, _i,_i]) # Load flow Newton Raphson + + # solved() => check if last solution attempt reached tolerance + # 0 = met convergence tolerance + # 1 = iteration limit exceeded + # 2 = blown up + # 3 = terminated by non-divergent option + # 4 = terminated by console input + # 5 = singular jacobian matrix or voltage of 0.0 detected + # 6 = inertial power flow dispatch error (INLF) + # 7 = OPF solution met convergence tolerance (NOPF) + # 8 does not exist ? + # 9 = solution not attempted + if psspy.solved() == 7 or psspy.solved()==0: + pass + else: #run OPF in loop to attempt convergence + postOPFinitialization(doci,all_inputs_init_i,AdjLoadTables,init_gen=False,init_bus=False,init_fxshnt=True,init_swshnt=False,init_load=True,init_P0=False) + MAX_OPF = 5 # 5 = Nombre de lancement max de l'OPF pour atteindre la convergence de l'algorithme + for nbeOPF in range(0, MAX_OPF): + psspy.bsys(3,0,[0.0,0.0],0,[],1,[1],0,[],0,[]) + psspy.set_opf_report_subsystem(3,0) + psspy.nopf(0,1) # Lancement OPF + if psspy.solved()==7 or psspy.solved()==0: + break + else: + postOPFinitialization(doci,all_inputs_init_i,AdjLoadTables,init_gen=False,init_bus=False,init_fxshnt=True,init_swshnt=False,init_load=True,init_P0=False) + + #treat OPF status code + if psspy.solved() == 7 or psspy.solved() == 0: + ok = True + elif psspy.solved() == 2: + print "OPF diverged." + elif psspy.solved()== 3: + print "Terminated by non-divergent option." + elif psspy.solved()== 4: + print "Terminated by console input." + elif psspy.solved()== 5: + print "Singular jacobian matrix or voltage of 0.0 detected." + elif psspy.solved()== 6: + print "Inertial power flow dispatch error (INLF)." + elif psspy.solved()== 8: + print "Solution does not exist." + elif psspy.solved()== 9: + print "Solution not attempted." + elif psspy.solved() == 1: #if iteration limit exceeded, try load flow + print "Iteration limit exceeded, trying load flow (CASE " + str(ite) + ")." + # Newton-Raphson power flow calculation. Params: + # tap adjustment flag (0 = disable / 1 = enable stepping / 2 = enable direct) + # area interchange adjustement (0 = disable) + # phase shift adjustment (0 = disable) + # dc tap adjustment (1 = enable) + # switched shunt adjustment (1 = enable) + # flat start (0 = default / disabled, 1 = enabled), disabled parce qu'on n'est pas dans une situation de départ + # var limit (default = 99, -1 = ignore limit, 0 = apply var limit immediatly) + # non-divergent solution (0 = disable) + psspy.fnsl([0, _i, 0, 0, 0, 0, _i,_i]) + if psspy.solved() == 0: + ok=True + elif psspy.solved() == 2: + print "Load flow diverged" + # else: + # #PlimitList = [] + # #QlimitList = [] + # if Debug: + # print "Got to principal economic dispatch" + # #economic dispatch + # EcdErrorCodes, LFcode, Plimit, Qlimit = EconomicDispatch(doci, ecd_file, LossesRatio, TapChange) + # #PlimitList.append(Plimit) + # #QlimitList.append(Qlimit) + # if Debug: + # print "Ran principal economic dispatch" + # if np.any(np.array(EcdErrorCodes)!=0): + # print "Error in economic dispatch." + # elif LFcode != 0: + # print "Load flow did not converge" + # else: + # ok = True + # + # if Plimit == True: + # print "Swing generator exceeds active power limits after economic dispatch." + # if Qlimit == True: + # print "Swing generator exceeds reactive power limits after economic dispatch." + if ok==True: + ierr, xdata2 = psspy.aloadcplx(-1, 1, xstrings) # retrieve load MVA # Renvoie une liste de chaque load en format complexe (P+Q) + ierr, bidata2 = psspy.afxshuntint(-1, 1, bistrings) + ierr, bxdata2 = psspy.afxshuntcplx(-1, 1, bxstrings) # retrieve bus shunt MVar + ierr, bcdata2 = psspy.afxshuntchar(-1, 1, bcstrings) + # Extraction of the load shedding quantities + for i in range(len(xdata2[0])): + if np.real(xdata1)[0][i] != np.real(xdata2)[0][i]: # np.real returns the real part of the elements in the given array + indexLS.append(i) + flagLS = 1 # raise flag loadshedding + try: # if / else would be better here ? + flagLS + except: + flagLS = 0 + else: + loadShed.append([position]) # Position seems to correspond to the number of the case we are treating + loadShed[0].extend(['' for i in range(len(indexLS)-1)]) # why [0] ? Maybe it would be better to have 2 lists ? Or a dict ? + loadShed.append([idata[0][i] for i in indexLS]) + loadShed.append([cdata[0][i] for i in indexLS]) + loadShed.append([np.real(xdata1)[0][i] - np.real(xdata2)[0][i] for i in indexLS]) #loadShed[3] + loadShed.append([np.real(xdata2)[0][i] for i in indexLS]) #loadShed[4] + indicLS = sum(loadShed[3]) # sum all Effective MW loads #sum(loadShed[3]) + loadShed = zip(*loadShed) # transpose the matrix + + # extraction adj. fixed shunt quantities + if len(bidata1[0]) == len(bidata2[0]): # one first opf may have occured... + # so we check first if both vectors have the same length + + for i in range(len(bxdata2[0])): + if np.imag(bxdata1)[0][i] != np.imag(bxdata2)[0][i]: # search for differencies + indexFS.append(i) + flagFS = 1 # rise flag adj. bus shunt + try: + flagFS + except: + flagFS = 0 + else: + bxdata2[0] = [np.imag(bxdata2)[0][i] for i in indexFS] # fulfill output vector + bidata2[0] = [bidata1[0][i] for i in indexFS] + bcdata2[0] = [bcdata1[0][i] for i in indexFS] + g = -1 + while (g <= len(bidata2)): + g += 1 + try: + #if fabs(bxdata2[0][g]) < 1: # discard value in ]-1,1[ + if fabs(bxdata2[0][g]) < 0.001: # discard value in ]-1,1[ + # pdb.set_trace() + bxdata2[0].pop(g) + bidata2[0].pop(g) + bcdata2[0].pop(g) + g -= 1 + except: pass + if bxdata2[0] != []: # Get all fixed shunt buses + fxshnt.append([position]) + fxshnt[0].extend(['' for i in range(len(bxdata2[0]) - 1)]) # Same here => maybe two lists or a dict would be a better choice + fxshnt.append(bidata2[0]) + fxshnt.append(bxdata2[0]) + indicFS = sum(fxshnt[2]) + fxshnt = zip(*fxshnt) # transpose the matrix + flagFS = 1 + else: + flagFS = 0 + + else: # if not same length, bus data corresponding to the adjusted bus shunt have been added to the vector + for i in range(len(bidata1[0])): # remove bus data of bus which are not added after the opf + try: + bxdata2[0].pop(bxdata2[0].index(bxdata1[0][i])) + bidata2[0].pop(bidata2[0].index(bidata1[0][i])) + bcdata2[0].pop(bcdata2[0].index(bcdata1[0][i])) + except: + pass + g = -1 + bx = list(np.imag(bxdata2[0])) # retrieve Mvar + while g <= len(bidata2): + g += 1 + try: + if fabs(bx[g]) < 1: # discard value in ]-1,1[ + bx.pop(g) + bidata2[0].pop(g) + g -= 1 + except: pass + if bx != []: + fxshnt.append([position]) + fxshnt[0].extend(['' for i in range(len(bidata2[0]) - 1)]) + fxshnt.append(bidata2[0]) + fxshnt.append(bx) + indicFS = sum(fxshnt[2]) + fxshnt = zip(*fxshnt) + flagFS = 1 + else: + flagFS = 0 + + + psspy.save(doci) + all_inputs=read_sav(doci) + buses = all_inputs[0] + lines = all_inputs[1] + transf = all_inputs[2] + plants = all_inputs[3] + loads = all_inputs[4] + shunt = all_inputs[5] + motors = all_inputs[6] + transf3=all_inputs[7] + swshunt = all_inputs[8] + + #pdb.set_trace() + + # 3. Affiche Y + sizeY4 = len(shunt) + y = np.zeros(2 * sizeY0 + sizeY1 + 3 * sizeY2 + sizeY3 + 2*sizeY6 + sizeY4 + sizeY8 + 3 * sizeY5+ 3 * sizeY7) + z = np.zeros(12+ 2*int(PSSEParams['ALGORITHM']=='Economic Dispatch and Power Flow')) # np.zeros returns a new array of the given shape and type filled with zeros + rate_mat_index = Irate_num + 2 + rate_mat_index_3w = Irate_num + 4 + Ymac = np.zeros(sizeY0) + if ok: + # Creates the quantities of interest + for i in range (sizeY2) : + if lines [i][rate_mat_index]>100 : + z[0]+=1 # Number of lines above 100% of their limits + for i in range (sizeY5) : + if transf [i][rate_mat_index]>100 : + z[1]+=1 # Number of transformers above 100% of their limits + for i in range (sizeY7) : + if transf3 [i][rate_mat_index_3w]>100 : + z[1]+=1 # Add number of 3w transformers above 100% of their limits + for i in range (sizeY1): + if buses[i][2]>buses[i][5] : + z[2]+=1 + if buses[i][2]z[6] : + z[6]=lines[i][rate_mat_index] # Max flow in lines + for i in range (sizeY5) : + if transf [i][rate_mat_index]>z[7] : + z[7]=transf[i][rate_mat_index] # Max flow in transformers + for i in range (sizeY7) : + #pdb.set_trace() + if transf [i][rate_mat_index]>z[7] : + z[7]=transf3[i][rate_mat_index_3w] # Max flow in 3w transformers + for i in range (sizeY2) : + if lines [i][rate_mat_index]>90 : + z[8]+=1 + z[8]=z[8]-z[0] # Number of lines between 90% and 100% of their limits + for i in range (sizeY5) : + if transf [i][rate_mat_index]>90 : + z[9]+=1 + for i in range (sizeY7) : + if transf3 [i][rate_mat_index_3w]>90 : + z[9]+=1 + z[9]=z[9]-z[1] # Number of transformers between 90% and 100% of their limits + + z[10]=indicFS + + z[11]=indicLS + + # if PSSEParams['ALGORITHM']=='Economic Dispatch and Power Flow': + # z[12] = int(Plimit) + # z[13] = int(Qlimit) + + # Creates the output vectors + for Pmach in range (sizeY0): + y[Pmach]=float(plants[Pmach][3]) + Ymac[Pmach]=float(plants[Pmach][3]) + for Qmach in range (sizeY0): + y[Qmach+sizeY0]=float(plants[Qmach][4]) + for Vbus in range (sizeY1): + y[Vbus+2*sizeY0]=float(buses[Vbus][2]) + for Iline in range (sizeY2): + y[Iline+2*sizeY0+sizeY1]=float(lines[Iline][rate_mat_index]) + for Pline in range (sizeY2): + y[Pline+2*sizeY0+sizeY1+sizeY2]=float(lines[Pline][6]) + for Qline in range (sizeY2): + y[Qline+2*sizeY0+sizeY1+2*sizeY2]=float(lines[Qline][7]) + for Itrans in range (sizeY5): + y[Itrans+2*sizeY0+sizeY1+3*sizeY2]=float(transf[Itrans][rate_mat_index]) + for Ptrans in range (sizeY5): + y[Ptrans+2*sizeY0+sizeY1+3*sizeY2+sizeY5]=float(transf[Ptrans][6]) + for Qtrans in range (sizeY5): + y[Qtrans+2*sizeY0+sizeY1+3*sizeY2+2*sizeY5]=float(transf[Qtrans][7]) + for Itrans in range (sizeY7): + y[Itrans+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5]=float(transf3[Itrans][rate_mat_index_3w]) + for Ptrans in range (sizeY7): + y[Ptrans+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+sizeY7]=float(transf3[Ptrans][8]) + for Qtrans in range (sizeY7): + y[Qtrans+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+2*sizeY7]=float(transf3[Qtrans][9]) + for Pload in range (sizeY3) : + y[Pload+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+3*sizeY7]=float(loads[Pload][1]) + for Pmotor in range (sizeY6) : + y[Pmotor+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+3*sizeY7+sizeY3]=float(motors[Pmotor][1]) + for Qmotor in range (sizeY6) : + y[Qmotor+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+3*sizeY7+sizeY3+sizeY6]=float(motors[Qmotor][2]) + for Qshunt in range (sizeY4) : + y[Qshunt+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+3*sizeY7+sizeY3+2*sizeY6]=float(shunt[Qshunt][2]) + for Qshunt in range (sizeY8) : + y[Qshunt+2*sizeY0+sizeY1+3*sizeY2+3*sizeY5+3*sizeY7+sizeY3+2*sizeY6+sizeY4]=float(swshunt[Qshunt][4]) + + nz = len(z) + + else : + print ('NON CONVERGENCE CASE '+str(position)+' CORE '+str(num_pac)) + + if dico['UnitCommitment']: + Output_beforeUC.append(z_before)#append the output + Pmachine_beforeUC.append(Ymac_before) + LS_beforeUC.append(indicLS_beforeUC) + FS_beforeUC.append(indicFS_beforeUC) + LStable_beforeUC.extend(loadShed_beforeUC) + FStable_beforeUC.extend(fxshnt_beforeUC) + + Output.append(z)#append the output + Pmachine.append(Ymac) + LS.append(indicLS) + FS.append(indicFS) + LStable.extend(loadShed) + FStable.extend(fxshnt) + + if TStest==1: + MyLogger(x2,y,z,logCSVfilename[num_pac],timeVect[ite]) + else: + MyLogger(x2,y,z,logCSVfilename[num_pac],position) #for each iteration write in the CSV + +## if dico['TStest']==1: +## sys.stdout.close() + return inputSample, Output, Pmachine, LS, FS, LStable, FStable, Output_beforeUC, Pmachine_beforeUC, LS_beforeUC, FS_beforeUC, LStable_beforeUC, FStable_beforeUC + +## except Exception,e: +## print e +## a=[] +## return a + +def create_dist(dico): + + NumLaws = len(dico['Laws']) + int(dico['N_1_fromFile']) + + #Create a correlation matrix as copulas + CorrMatrixNames = dico['CorrMatrix']['laws'] + CorrMatrix = dico['CorrMatrix']['matrix'] + corr=CorrelationMatrix(NumLaws)#Openturns + + # Create a collection of the marginal distributions + collectionMarginals = DistributionCollection(NumLaws)#Openturns + + distributionX = [] + for i,key in enumerate(CorrMatrixNames): + data, [time_serie, time_serie_file] = getUserLaw(dico['Laws'][key]) + distributionX.append( data ) + collectionMarginals[i] = Distribution(data) + + #add N_1 components entered as Files + if dico['N_1_fromFile']==True: + continTuples = [] + for j in range(len(dico['continVal'])): + continTuples.append((dico['continVal'][j],dico['continProb'][j])) + data = getUserDefined(continTuples) + distributionX.append(data) + collectionMarginals[i+1] = Distribution(data) + CorrMatrixNames.append('N_1_fromFile') + CorrMatrixEx = np.hstack((CorrMatrix, np.zeros((NumLaws-1,1)))) #assume no correlation between N-1 and other laws + LastLine = np.hstack((np.zeros((1,NumLaws-1)),np.ones((1,1)))) + CorrMatrixEx = np.vstack((CorrMatrixEx, LastLine)) + CorrMatrix = CorrMatrixEx + (Nrows, Ncols) = np.shape(CorrMatrixEx) + else: + (Nrows, Ncols) = np.shape(CorrMatrix) + for i in range(Nrows): + for j in range(Ncols): + corr[i,j]=CorrMatrix[i,j] + + corr2= NormalCopula.GetCorrelationFromSpearmanCorrelation(corr) + copula=Copula(NormalCopula(corr2)) + #copula=Copula(NormalCopula(corr)) + + # Create the input probability distribution, args are the distributions, the correlation laws + inputDistribution = ComposedDistribution(collectionMarginals, copula) + + return inputDistribution + +def Calculation(dico,data1,msg): + + + os.chdir(dico['doc_base']) #to work in correct directory +## sys.stdout=open('process num'+str(os.getpid())+'_package '+\ +## str(dico['num_pac'])+'.out','w') + #pdb.set_trace() + flag2=dico['flag2'] + inputDistribution=create_dist(dico) #create new distribution + #initialization + LStable=[] + FStable=[] + output=[] + inputSample=[] + Pmachine=[] + + LStable_beforeUC=[] + FStable_beforeUC=[] + output_beforeUC=[] + Pmachine_beforeUC=[] + + outputSampleAll=NumericalSample(0,12 + 2*int(dico['PSSEParams']['ALGORITHM']=='Economic Dispatch and Power Flow')) + + RandomGenerator.SetSeed(os.getpid()) + Message=msg.get() + print(Message+'=======OK') + + + while(Message !='stop'): + myMCE = MonteCarloExperiment(inputDistribution,dico['lenpac']) #create new sample + inputSamp = myMCE.generate() + + try: + Message=msg.get(block=False) + if Message=='stop': break + except: + pass + res=PSSEFunct(dico.copy(),inputSamp) #launch PSSEFunct (OPF) + #subprocess.Popen(['c:/python34/python.exe','PFfunction.py']) + dico['position']+=dico['lenpac'] + # 0 1 2 3 4 5 6 + #inputSample, Output, Pmachine, LS, FS, LStable, FStable, + # 7 8 9 10 11 12 + #Output_beforeUC, Pmachine_beforeUC, LS_beforeUC, FS_beforeUC, LStable_beforeUC, FStable_beforeUC + for result in res[1]: + outputSampleAll.add(NumericalPoint(result)) #create a Numerical Sample variable + + if (flag2): + LS=(np.mean(res[3])) #mean per package + FS=(np.mean(res[4])) #mean per package + z=[LS,FS] + data1.put(z) + sleep(1) + + #if criteria on nbeTension and NbeTransit + else: + NbeTransit=(float(NumericalPoint(1,outputSampleAll.computeMean()[0])[0])) #mean per package + NbeTension=(float(NumericalPoint(1,outputSampleAll.computeMean()[1])[0])) + z=[NbeTransit,NbeTension] + data1.put(z) + sleep(1) + + inputSample.extend(res[0]) + + LStable.extend(res[5]) + FStable.extend(res[6]) + output.extend(res[1]) + Pmachine.extend(res[2]) + + LStable_beforeUC.extend(res[11]) + FStable_beforeUC.extend(res[12]) + output_beforeUC.extend(res[7]) + Pmachine_beforeUC.extend(res[8]) + + if msg.empty(): + Message = "empty" + else: + Message=msg.get(block=True,timeout=2) + print 'MSG is '+str(Message)+' time: '+str(strftime("%Hh%Mm%S", gmtime())) + +# sys.stdout.close() + + ## #write summary tables for before UC + if dico['UnitCommitment']: + f=open(dico['logCSVfilename_UC'][dico['num_pac']],'a') + f.write("\n Summary Table for MW Load Adjustments;;;;;;;;Summary Table for Added Shunt (Mvar)\n") + f.write("Iteration;;Bus Number;Name;Load Shed;Remaining Load;;;Iteration;;Bus Number;Final \n") + for i in range(max(len(LStable_beforeUC),len(FStable_beforeUC))): + try: + f.write('{0};;{1};{2};{3};{4}'.format(LStable_beforeUC[i][0],LStable_beforeUC[i][1]\ + ,LStable_beforeUC[i][2],LStable_beforeUC[i][3],LStable_beforeUC[i][4])) + except: + f.write(';;;;;') + + try: + f.write(';;;{0};;{1};{2} \n'.format(FStable_beforeUC[i][0],FStable_beforeUC[i][1],FStable_beforeUC[i][2])) + except: + f.write('\n') + f.write("\n\n") + f.close() + + ## #write summary tables + f=open(dico['logCSVfilename'][dico['num_pac']],'a') + f.write("\n Summary Table for MW Load Adjustments;;;;;;;;Summary Table for Added Shunt (Mvar)\n") + f.write("Iteration;;Bus Number;Name;Load Shed;Remaining Load;;;Iteration;;Bus Number;Final \n") + for i in range(max(len(LStable), len(FStable))): + try: + f.write('{0};;{1};{2};{3};{4}'.format(LStable[i][0],LStable[i][1]\ + ,LStable[i][2],LStable[i][3],LStable[i][4])) + except: + f.write(';;;;;') + try: + f.write(';;;{0};;{1};{2} \n'.format(FStable[i][0],FStable[i][1],FStable[i][2])) + except: + f.write('\n') + f.write("\n\n") + f.close() + + + + return output, inputSample,Pmachine + +class NonBlockingStreamReader(): #class object to read in a stdout process + + def __init__(self, stream): + ''' + stream: the stream to read from. + Usually a process' stdout or stderr. + ''' + + self._s = stream + self._q = Queue() + + def _populateQueue(stream, queue): + ''' + Collect lines from 'stream' and put them in 'queue'. + ''' + + while True: + line = stream.read() + if line: + queue.put(line) + else: + pass + + self._t = Thread(target = _populateQueue, + args = (self._s, self._q)) + self._t.daemon = True + self._t.start() #start collecting lines from the stream + + def readline(self, timeout = None): + try: + return self._q.get(block = timeout is not None, + timeout = timeout) + except Empty: + return None + + +def Convergence(data2,msg,OPF,nb_fix,cmd_Path): + + LS=[] + FS=[] + MoyTension=[] + MoyTransit=[] + MoyCumuLS=[] + MoyCumuFS=[] + NbeTension=[] + NbeTransit=[] + Ind1=[] + Ind2=[] + ind=1 + t=0 + p=subprocess.Popen(['python',cmd_Path],stdout=subprocess.PIPE) #launch subprocess + nbsr=NonBlockingStreamReader(p.stdout) #monitor subprocess stdout + + print 'Calculating convergence criteria\n' + while(ind): + + output=nbsr.readline(0.1) + if output: + print 'Simulation Interrupting.....' + break + + for i in range(multiprocessing.cpu_count()*3): #put 'ok' in the queue three times the number of cores + msg.put('ok') + + debut=data2.get(block=True) + t+=1 + print 'Package '+str(t) + + if (OPF): #if criteria on Load shed and mvar + LS.append(debut[0]) + FS.append(debut[1]) + + MoyCumuLS.append(np.mean(LS[0:t])) + MoyCumuFS.append(np.mean(FS[0:t])) + + if t==1: + indice1=1 + indice2=1 + else: + indice1=np.std(MoyCumuLS) #calculate stop criterion for load shedding + indice2=np.std(MoyCumuFS) #calculate stop criterion for mvar + + Ind1.append(indice1) + Ind2.append(indice2) + print 'indicator Load Shedding= '+str(indice1)+';'+' indicator Added Mvar= '+str(indice2)+'\n' + + if (indice1<0.2) and (indice2<0.015) and nb_fix==0: + ind=0 + break + elif len(Ind1)==nb_fix: + break + else: + NbeTransit.append(debut[0]) + NbeTension.append(debut[1]) + + MoyTension.append(np.mean(NbeTension[0:len(NbeTension)])) + MoyTransit.append(np.mean(NbeTransit[0:len(NbeTransit)])) + + if t==1: + indice1=1 + indice2=1 + else: + indice1=np.std(MoyTension) #calculate stop criterion for tension + indice2=np.std(MoyTransit) #calculate stop criterion for transit + + Ind1.append(indice1) + Ind2.append(indice2) + print 'indicator Nbe Tension= '+str(indice1)+' indicator Transit= '+str(indice2)+'\n' + + if (indice1<0.01) and (indice2<0.01) and nb_fix==0: + ind=0 + break + elif len(Ind1)==nb_fix: + break + + while msg.empty()==False : #flush the queue + msg.get() + # print(msg.qsize()) + for i in range(100): #put a lot of 'stop's in the queue to make all processes stop + msg.put_nowait('stop') + # print(msg.qsize()) + + p.terminate() + + return Ind1,Ind2 diff --git a/PSEN_Eficas/PSEN/support_functionsPF.py b/PSSE_PF_Eficas/PSEN2/support_functionsPF.py similarity index 100% rename from PSEN_Eficas/PSEN/support_functionsPF.py rename to PSSE_PF_Eficas/PSEN2/support_functionsPF.py diff --git a/PSEN_Eficas/PSEN/usrCmd.py b/PSSE_PF_Eficas/PSEN2/usrCmd.py similarity index 100% rename from PSEN_Eficas/PSEN/usrCmd.py rename to PSSE_PF_Eficas/PSEN2/usrCmd.py diff --git a/PSEN_Eficas/PSEN/usrCmdPF.py b/PSSE_PF_Eficas/PSEN2/usrCmdPF.py similarity index 100% rename from PSEN_Eficas/PSEN/usrCmdPF.py rename to PSSE_PF_Eficas/PSEN2/usrCmdPF.py -- 2.39.2