]> SALOME platform Git repositories - tools/eficas.git/commitdiff
Salome HOME
cleaning_v1
authorARNER Kevin <kevin.arner@edf.fr>
Fri, 1 Mar 2019 15:37:27 +0000 (16:37 +0100)
committerARNER Kevin <kevin.arner@edf.fr>
Fri, 1 Mar 2019 15:37:27 +0000 (16:37 +0100)
PSSE_PF_Eficas/ExtractGeneratorLoadLineandTransfoDico.py
PSSE_PF_Eficas/ExtractGeneratorLoadLineandTransfoDico_old.py [new file with mode: 0644]
PSSE_PF_Eficas/PSEN_Cata_PF.py
PSSE_PF_Eficas/com.py
PSSE_PF_Eficas/debugPFWrapper.py
PSSE_PF_Eficas/opsPSEN_PF.py
PSSE_PF_Eficas/temp.txt
PSSE_PF_Eficas/utils.py

index 7d686a635baf222a1cefefa6d3d2ceb14552e5e9..7cdd0cb835e456dfab3dad2be824446fdb8b4615 100644 (file)
@@ -1,22 +1,26 @@
 
-###################################################################################
-# objectif de ce module: extraire des donnees pour afficher dans l'interface Eficas
-###################################################################################
+"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
+
+ Ojectif de ce module: extraire des donnes pour afficher dans l'interface Eficas
+
+"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
 NoBreakersandSwitches = True
-#_____________ TODO : demander a Claire si il faut absolument garder cela
-# si oui, eventuellement en faire une option propre
 
-import os
-import sys
-import numpy as np
-import pickle
-from utils import nettoyeName
+# TODO _______  
+# Demander a Claire si il faut absolument garder cela
+# Si oui, eventuellement en faire une option propre
 
+def ExtractGeneratorLoadLineandTransfoDico(NetworkFile,PSSE_PATH, PSSPY_PATH,debug=False):
 
-def initPSSE ( PSSE_PATH, PSSPY_PATH):
-#_____________________________________
-# initialisation de PSSE
-# Appele de  ExtractGeneratorLoadLineandTransfoDico 
+    import os
+    import sys
+    import numpy as np
+    from   utils import cleanName
+    
+    
+    """""""""""""""""
+    PSSE Initialization
+    """""""""""""""""
 
     sys.path.append(PSSPY_PATH)
     os.environ['PATH'] +=  ';' + PSSE_PATH + ';'
@@ -24,53 +28,46 @@ def initPSSE ( PSSE_PATH, PSSPY_PATH):
     import psspy
     import redirect
 
-    ###initialization PSSE
     psspy.psseinit(10000)
-    _i=psspy.getdefaultint()
-    _f=psspy.getdefaultreal()
-    _s=psspy.getdefaultchar()
+    _i = psspy.getdefaultint()
+    _f = psspy.getdefaultreal()
+    _s = psspy.getdefaultchar()
     redirect.psse2py()
 
-    # Silent execution of PSSe
+    # Silent execution of PSSE
     islct=6 # 6=no output; 1=standard
     psspy.progress_output(islct)
 
-
-def ExtractGeneratorLoadLineandTransfoDico(NetworkFile,PSSE_PATH, PSSPY_PATH,debug=False):
-# ________________________________________________________________________________________
-# genere un dictionnaire contient reseau pour interface Eficas 
-# a partir d un fichier PSSE
-# return des 5 dicos et ecriture dans le fichier temp.txt
-
-    # initialisation PSS
-    if debug : print ('initialisation PSSE')
-    initPSSE ( PSSE_PATH, PSSPY_PATH)
-
-    # extration du Reseau
+    # Open Network File
     psspy.case(NetworkFile)
 
-    # Remplit Les dicos pour eficas
 
-    #Extract Loads depuis PSSE
-    if debug : print ("Read Load")
-    sid = -1 #all buses
-    flag = 1 #all in service loads/generators (4 all loads/generators)
+    """
+    Extract Loads 
+    """
+    if debug : 
+        print ("Read Load")
+        
+    sid  = -1                                                                    # All buses
+    flag =  1                                                                    # All in service loads/generators (4 all loads/generators)
 
-    string = ['NUMBER']
+    string      = ['NUMBER']
     ierr,iarray = psspy.aloadint(sid,flag,string)
-    string = ['NAME','ID','EXNAME']
+
+    string      = ['NAME','ID','EXNAME']
     ierr,carray = psspy.aloadchar(sid,flag,string)
-    string = ['mvaact']
+
+    string      = ['mvaact']
     ierr, xdata = psspy.aloadcplx(sid, flag, string)
 
-    LoadDico = {}  # [Bus name, load ID, extended bus name, bus number]
+    LoadDico = {}                                                               # [Bus name, load ID, extended bus name, bus number]
+    
     for i in range(len(iarray[0])):
         idname = "Lo" + carray[1][i].strip()
         loadname = carray[0][i].strip()+ "__" + idname
-        loadname=nettoyeName(loadname)
-
-        LoadDico[loadname]= {}
+        loadname = cleanName(loadname)
+        
+        LoadDico[loadname]           = {}
         LoadDico[loadname]['NAME']   = carray[0][i].strip()
         LoadDico[loadname]['ID']     = carray[1][i]
         LoadDico[loadname]['EXNAME'] = carray[2][i]
@@ -78,23 +75,33 @@ def ExtractGeneratorLoadLineandTransfoDico(NetworkFile,PSSE_PATH, PSSPY_PATH,deb
         LoadDico[loadname]['P']      = np.real(xdata)[0][i]
         LoadDico[loadname]['Q']      = np.imag(xdata)[0][i]
 
-    #Extract Generators
-    if debug : print ("Read Generators")
-    sid = -1 #all buses
-    flag = 1 #all in service loads/generators (4 all loads/generators)
-    string = ['NUMBER']
+
+    """""""""""""""""""""
+    Extract Genrators 
+    """""""""""""""""""""
+    if debug : 
+        print ("Read 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']
+
+    string      = ['NAME','ID','EXNAME']
     ierr,carray = psspy.amachchar(sid,flag,string)
-    rstrings = ['pgen','qgen','mbase','pmax','qmax','pmin','qmin']
+
+    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]
+    MachineDico = {}                                                            # [Bus name, machine ID, extended bus name, bus number]
+    
     for i in range(len(iarray[0])):
         idname = "Gr" + carray[1][i].strip()
-        machinename = carray[0][i].strip()+ "__" + idname
-        machinename=nettoyeName(machinename)
-        MachineDico[machinename]={}
+        machinename = carray[0][i].strip() + "__" + idname
+        machinename = cleanName(machinename)
+        
+        MachineDico[machinename]           = {}
         MachineDico[machinename]['NAME']   = carray[0][i].strip()
         MachineDico[machinename]['ID']     = carray[1][i]
         MachineDico[machinename]['EXNAME'] = carray[2][i]
@@ -106,24 +113,34 @@ def ExtractGeneratorLoadLineandTransfoDico(NetworkFile,PSSE_PATH, PSSPY_PATH,deb
         MachineDico[machinename]['PMIN']   = rarray[5][i]
         MachineDico[machinename]['QMIN']   = rarray[6][i]
 
-    #Extract Motors
-    if debug : print ("Read Motors")
-    sid = -1 #all buses
-    flag = 1 #all in service loads/generators (4 all loads/generators)
 
-    string = ['NUMBER','PSETCODE','BASECODE']
+    """""""""""""""""""""
+    Extract Motors
+    """""""""""""""""""""
+    if debug : 
+        print ("Read 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']
+
+    string      = ['NAME','ID','EXNAME']
     ierr,carray = psspy.aindmacchar(sid,flag,string)
-    rstrings = ['psetpoint','mbase','p','q']
+
+    rstrings     = ['psetpoint','mbase','p','q']
     ierr, rarray = psspy.aindmacreal(sid, flag, rstrings)
 
-    MotorDico = {} # [Bus name, machine ID, extended bus name, bus number]
+
+    MotorDico = {}                                                              # [Bus name, machine ID, extended bus name, bus number]
+    
     for i in range(len(iarray[0])):
         idname = "Mo" + carray[1][i].strip()
-        motorname = carray[0][i].strip()+ "__" + idname
-        motorname = nettoyeName(motorname)
-        MotorDico[motorname]={}
+        motorname = carray[0][i].strip() +  "__" + idname
+        motorname = cleanName(motorname)
+        
+        MotorDico[motorname]              = {}
         MotorDico[motorname]['NAME']      = carray[0][i].strip()
         MotorDico[motorname]['ID']        = carray[1][i]
         MotorDico[motorname]['EXNAME']    = carray[2][i]
@@ -136,29 +153,45 @@ def ExtractGeneratorLoadLineandTransfoDico(NetworkFile,PSSE_PATH, PSSPY_PATH,deb
         MotorDico[motorname]['Q']         = rarray[3][i]
 
 
-    #Extract Line
-    if debug : print ("Read Line")
+    """""""""""""""""""""
+    Extract Lines
+    """""""""""""""""""""
+    if debug : 
+        print ("Read Lines")
+    
     sid   = -1
-    owner = 1
-    ties  = 1
-    flag  = 2            #6 for two-winding transfos
-    entry = 1            #each branch once, not both directions
-    string = ['FROMNUMBER','TONUMBER']
+    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']
+    
+    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]
+    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()
-        linename = nettoyeName(linename)
+        idname = cleanName(idname)
+        
+        try:
+            idname = 'Li' + str(int(idname))
+        except:
+            idname = 'Li' + idname
+        
+        linename = carray[0][i].strip() + "__" + carray[1][i].strip() + "__" + idname
+        linename = cleanName(linename)
 
 # TODO ______ 
 #   Attention : ceci peut exlure des lignes qui auraient leur place ici et qui s apelleraient BRquelquechose
 #   faire le test avant le remplacement dans la chaine et utilser continue
+        
         if NoBreakersandSwitches:
             if 'Br' not in idname and 'Sw' not in idname:
-                LineDico[linename]={}
+                LineDico[linename]               = {}
                 LineDico[linename]['FROMNAME']   = carray[0][i].strip()
                 LineDico[linename]['TONAME']     = carray[1][i].strip()
                 LineDico[linename]['ID']         = carray[4][i]
@@ -166,29 +199,36 @@ def ExtractGeneratorLoadLineandTransfoDico(NetworkFile,PSSE_PATH, PSSPY_PATH,deb
                 LineDico[linename]['TOEXNAME']   = carray[3][i]
                 LineDico[linename]['FROMNUMBER'] = iarray[0][i]
                 LineDico[linename]['TONUMBER']   = iarray[1][i]
-
-
     
-    #Extract Transfos
-    if debug : print ("Read Transfos")
+    """""""""""""""""""""
+    Extract Transfos
+    """""""""""""""""""""
+    if debug : 
+        print ("Read Transfos")
+
 # TODO ______ 
 # se renseigner sur sid owner  ...
-    sid = -1
-    owner = 1
-    ties = 1
-    flag = 6               #two-winding transfos
-    entry = 1              #each branch once, not both directions
-    string = ['FROMNUMBER','TONUMBER']
+   
+    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']
+    
+    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]
+    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()
         tfoname = carray[0][i].strip() + "__" + carray[1][i].strip() + "__" + idname
-        tfoname = nettoyeName(tfoname)
-        TfoDico[tfoname]={}
+        tfoname = cleanName(tfoname)
+    
+        TfoDico[tfoname]               = {}
         TfoDico[tfoname]['FROMNAME']   = carray[0][i].strip()
         TfoDico[tfoname]['TONAME']     = carray[1][i].strip()
         TfoDico[tfoname]['ID']         = carray[4][i]
@@ -197,25 +237,34 @@ def ExtractGeneratorLoadLineandTransfoDico(NetworkFile,PSSE_PATH, PSSPY_PATH,deb
         TfoDico[tfoname]['FROMNUMBER'] = iarray[0][i]
         TfoDico[tfoname]['TONUMBER']   = iarray[1][i]
         TfoDico[tfoname]['#WIND']      = 2
-
-    #Extract 3 winding Transfos
-    if debug : print ("Read 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
+   
+    
+    """""""""""""""""""""
+    Extract 3 winding Transfos
+    """""""""""""""""""""
+
+    if debug : 
+        print ("Read 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()
-        tfoname = nettoyeName(tfoname)
         tfoname = carray[0][i].strip() + "__" + carray[1][i].strip() + "__" + carray[2][i].strip() + "__" + idname
-        TfoDico[tfoname]={}
+        tfoname = cleanName(tfoname)
+        
+        TfoDico[tfoname]               = {}
         TfoDico[tfoname]['FROMNAME']   = carray[0][i].strip()
         TfoDico[tfoname]['TONAME']     = carray[1][i].strip()
         TfoDico[tfoname]['3NAME']      = carray[2][i].strip()
@@ -228,7 +277,7 @@ def ExtractGeneratorLoadLineandTransfoDico(NetworkFile,PSSE_PATH, PSSPY_PATH,deb
         TfoDico[tfoname]['3NUMBER']    = iarray[2][i]
         TfoDico[tfoname]['#WIND']      = 3
 
-# ___ TODO __ verifier si on peut les enlever pour PSSE ?
+# TODO ____ verifier si on peut les enlever pour PSSE ?
     filew = open('temp.txt', 'w')
     filew.write(NetworkFile + '\n')
     filew.write(PSSE_PATH + '\n')
@@ -237,66 +286,58 @@ def ExtractGeneratorLoadLineandTransfoDico(NetworkFile,PSSE_PATH, PSSPY_PATH,deb
     return MachineDico, LoadDico, LineDico, TfoDico, MotorDico
 
 
-def convert(data):
-# _________________
-# fonction recursive permettant de relire les data issues de python3
-# appelee uniquement par PFExtractGeneratorLoadLineandTransfoDico
-# a resorber si le code est compatible python 2 / 3
-
-    import collections
-    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
-
-def PFExtractGeneratorLoadLineandTransfoDico(NetworkFile, PF_PATH, Python3_path):
-#_________________________________________________________________________________
-# PSEN sous PowerFactory Lecture les donnees de Generateur,Load,Line,Transfo
-# fonction identique mais lit un reseau PowerFactory et non PSSE
-# attention --> python3 et non python2 dou subprocess et ecriture de fichier pour passer/recuperer  les donnees 
-# a simplifier lorsqu on aura un code compatible 2.7 et 3
-# lance le code com.py dans un sous process
-
+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()
-
-# ___ TODO __ verifier que python.exe est bien sous Python3_path et sinon 
-# afficher un message 
-    #print('changer le chemin de Python3 executable')
-
-    lancer = [Python3_path+'/python.exe', path1+'/com.py']
-    import subprocess
+    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()
-
-# reconvertit les donnees crees en python3 pour les returner a Eficas
     with open('Data_for_interface', 'rb') as fichier:
        mon_depickler = pickle.Unpickler(fichier)
-       data_file = mon_depickler.load()
+       data_file = mon_depickler.load() 
+    import collections
+    def convert(data):
+        if isinstance(data, basestring):
+            try:
+               return str(data)
+            except:
+               return 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']
+    LoadDico = data['LoadDico']
+    LineDico = data['LineDico']
+    TfoDico = data['TransfoDico']
+    MotorDico = data['MotorDico']
     os.remove('Data_for_interface')
-    
-    return MachineDico, LoadDico, LineDico, TfoDico, MotorDico
 
-if __name__ == "__main__":
-     pass
+    # return MachineDico, LoadDico, LineDico, TfoDico, MotorDico    
+    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"
 
-     # tester convert
-     # faire 2 methodes testPFExtractGeneratorLoadLineandTransfoDico et testExtractGeneratorLoadLineandTransfoDico
-     # appelle les methodes PFExtractGeneratorLoadLineandTransfoDico et  ExtractGeneratorLoadLineandTransfoDico avec un mini reseau connu
-     # on verifie que MachineDico, LoadDico, LineDico, TfoDico, MotorDico contiennent bien ce qu on attendait 
-     # les 2 fichiers contenant les reseaux seront dans la base git
+#MachineDico, LoadDico, LineDico, TfoDico, MotorDico = ExtractGeneratorLoadLineandTransfoDico(NetworkFile,PSSE_PATH,PSSPY_PATH)
diff --git a/PSSE_PF_Eficas/ExtractGeneratorLoadLineandTransfoDico_old.py b/PSSE_PF_Eficas/ExtractGeneratorLoadLineandTransfoDico_old.py
new file mode 100644 (file)
index 0000000..93fec82
--- /dev/null
@@ -0,0 +1,351 @@
+"""
+
+         Objectif de ce module: extraire des donnees pour afficher 
+                        dans l'interface Eficas
+
+"""
+
+NoBreakersandSwitches = True
+#_____________ TODO : demander a Claire si il faut absolument garder cela
+# si oui, eventuellement en faire une option propre
+
+import os
+import sys
+import numpy as np
+import pickle
+from   utils import nettoyeName
+
+
+def initPSSE(PSSE_PATH, PSSPY_PATH):
+#_____________________________________
+# Initialisation de PSSE
+# Appel de  ExtractGeneratorLoadLineandTransfoDico 
+
+    sys.path.append(PSSPY_PATH)
+    os.environ['PATH'] +=  ';' + PSSE_PATH + ';'
+
+    import psspy
+    import redirect
+
+    # Initialisation 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)
+
+
+def ExtractGeneratorLoadLineandTransfoDico(NetworkFile,PSSE_PATH, PSSPY_PATH,debug=False):
+# ________________________________________________________________________________________
+# Genere un dictionnaire qui contient reseau pour interface Eficas a partir d un fichier PSSE
+# Return des 5 dicos et ecriture dans le fichier temp.txt
+
+    # Initialisation PSS
+    if debug : 
+        print('initialisation PSSE')
+        
+    initPSSE(PSSE_PATH, PSSPY_PATH)
+
+    # Extration du Reseau
+    psspy.case(NetworkFile)
+
+    """
+    Extract Loads 
+    """
+    
+    if debug : 
+        print ("Read Load")
+    
+    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()
+        loadname = carray[0][i].strip()+ "__" + idname
+        loadname = nettoyeName(loadname)
+
+        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 Genrators 
+    """""""""""""""""""""
+    
+    if debug : 
+        print ("Read 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()
+        machinename = carray[0][i].strip()+ "__" + idname
+        machinename = nettoyeName(machinename)
+        
+        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
+    """""""""""""""""""""
+    
+    if debug : 
+        print ("Read 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()
+        motorname = carray[0][i].strip()+ "__" + idname
+        motorname = nettoyeName(motorname)
+        
+        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 Lines
+    """""""""""""""""""""
+    
+    if debug : 
+        print ("Read Lines")
+    
+    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 = {}                                                               #[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()
+        linename = nettoyeName(linename)
+
+# TODO ______ 
+#   Attention : ceci peut exlure des lignes qui auraient leur place ici et qui s apelleraient BRquelquechose
+#   faire le test avant le remplacement dans la chaine et utilser continue
+        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]
+
+
+    
+    """""""""""""""""""""
+    Extract Transfos
+    """""""""""""""""""""
+    
+    if debug : 
+        print ("Read Transfos")
+# TODO ______ 
+# se renseigner sur sid owner  ...
+    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 = {}                                                                #[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()
+        tfoname = carray[0][i].strip() + "__" + carray[1][i].strip() + "__" + idname
+        tfoname = nettoyeName(tfoname)
+        
+        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
+
+
+    """""""""""""""""""""
+    Extract 3 winding Transfos
+    """""""""""""""""""""
+
+    if debug : 
+        print ("Read 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()
+        tfoname = nettoyeName(tfoname)
+        tfoname = carray[0][i].strip() + "__" + carray[1][i].strip() + "__" + carray[2][i].strip() + "__" + idname
+        
+        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
+
+# ___ TODO __ verifier si on peut les enlever pour PSSE ?
+    filew = open('temp.txt', 'w')
+    filew.write(NetworkFile + '\n')
+    filew.write(PSSE_PATH + '\n')
+    filew.close()
+
+    return MachineDico, LoadDico, LineDico, TfoDico, MotorDico
+
+
+def convert(data):
+# _________________
+# Fonction recursive permettant de relire les data issues de python3
+# Appelee uniquement par PFExtractGeneratorLoadLineandTransfoDico
+# A resorber si le code est compatible python 2 / 3
+
+    import collections
+    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
+
+def PFExtractGeneratorLoadLineandTransfoDico(NetworkFile, PF_PATH, Python3_path):
+#_________________________________________________________________________________
+# PSEN sous PowerFactory. Lecture des donnees de Generateur,Load,Line,Transfo
+# Fonction identique mais lit un reseau PowerFactory et non PSSE
+# ATTENTION --> python3 et non python2 d ou subprocess et ecriture de fichier pour passer/recuperer  les donnees 
+# A simplifier lorsqu on aura un code compatible 2.7 et 3
+# Lance le code com.py dans un sous process
+
+    path1 = os.getcwd()
+    filew = open('temp.txt','w')
+    filew.write(NetworkFile+'\n')
+    filew.write(PF_PATH + '\n')
+    filew.write(Python3_path + '\n')
+    filew.close()
+
+# ___ TODO __ verifier que python.exe est bien sous Python3_path et sinon 
+# afficher un message 
+    #print('changer le chemin de Python3 executable')
+
+    lancer = [Python3_path+'/python.exe', path1+'/com.py']
+    
+    import subprocess
+    proc  = subprocess.Popen(lancer)
+    proc.wait()
+
+# Reconvertit les donnees crees en python3 pour les retourner a Eficas
+    with open('Data_for_interface', 'rb') as fichier:
+       mon_depickler = pickle.Unpickler(fichier)
+       data_file = mon_depickler.load()
+    data=convert(data_file)
+
+#    MachineDico = data['MachineDico']
+#    LoadDico    = data['LoadDico']
+#    LineDico    = data['LineDico']
+#    TfoDico     = data['TransfoDico']
+#    MotorDico   = data['MotorDico']
+#    os.remove('Data_for_interface')
+    LoadDico    = data['LoadDico']
+    
+    
+#    return MachineDico, LoadDico, LineDico, TfoDico, MotorDico
+    return LoadDico
+
+if __name__ == "__main__":
+     pass
+
+     # Tester convert
+     # Faire 2 methodes testPFExtractGeneratorLoadLineandTransfoDico et testExtractGeneratorLoadLineandTransfoDico
+     # Appelle les methodes PFExtractGeneratorLoadLineandTransfoDico et  ExtractGeneratorLoadLineandTransfoDico avec un mini reseau connu
+     # on verifie que MachineDico, LoadDico, LineDico, TfoDico, MotorDico contiennent bien ce qu on attendait 
+     # les 2 fichiers contenant les reseaux seront dans la base git
index 34c0482c027b01994157183b2eb38edd89e1bf78..80494a11ea2660a7553bd3d7bb6a06d0950e772f 100644 (file)
@@ -138,6 +138,7 @@ MALIGNE =  OPER ( nom = "MALIGNE",
 
   ID = SIMP ( statut = 'o', typ = "TXM", fr = "nom ligne", ang = "line name",),
 )
+
 MONTRANSFO =  OPER ( nom = "MONTRANSFO",
             sd_prod = sd_transfo,
             UIinfo = {"groupes": ("CACHE")},
@@ -1442,7 +1443,7 @@ DISTRIBUTION = OPER ( nom = "DISTRIBUTION",
                defaut = "Same sample for all lines",
                ),
 
-  Line   = SIMP(statut='o',typ=sd_ligne,max="**", homo="SansOrdreNiDoublon"),
+  Line   = SIMP(statut='o',typ=sd_ligne, max="**", homo="SansOrdreNiDoublon"),
 
   Law = SIMP ( statut = "o", typ = "TXM",
                 into = ( #"Exponential",
index 0e656bf4335dbfafd4d9d84f9e32837d12fad7c0..83ff246f3b2d959dddf24134172cd4a40a76a326 100644 (file)
@@ -1,8 +1,9 @@
 #!/usr/bin/python3
-##############################################################################################################################################
+########################################################################################################################
 # ojectif de ce module: extraire des donnes pour afficher dans l'interface Eficas. Subprocess dans la fonction PFExtractGeneratorLoadLineandTransfoDico
-##############################################################################################################################################
+########################################################################################################################
 import pdb
+from math import *
 
 NoBreakersandSwitches = True
 
@@ -10,99 +11,152 @@ NetworkFile = r'C:\Logiciels DER\PSEN_MERGED_V6\Example\Corse PF\Modele_Corse_PS
 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
+    #PSEN sous PowerFactory, extract data from Gen, Load, Bus, Branch, Transfo, Motor
     import os
     import sys
     import numpy as np
+    from   utils import cleanName 
 
     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)) + ';'
+    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     = pf.GetApplication()
+    user    = app.GetCurrentUser()
+    ComImp  = user.CreateObject('ComPFDIMPORT')                                 # Object to import pfd file
 
-    app.SetWriteCacheEnabled(1)             # Disable consistency check
+    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.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
+    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  = prjs[0]
     prj.Activate()
+    
     studycase = app.GetActiveStudyCase()
-    grids = studycase.GetChildren(1, '*.ElmNet', 1)[0].contents
+    grids     = studycase.GetChildren(1, '*.ElmNet', 1)[0].contents
+    
     tous = []
     for grid in grids:
         tous.extend(grid.obj_id.GetContents('*.ElmTerm', 1))
-    bus = []
+    
+    bus  = []
     for noeud in tous:
-        # if ((noeud.iUsage == 0) and (noeud.outserv == 0)):  # eliminer tous les noeuds out-service
+        # 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]
+        busname = cleanName(noeuds[ii].cStatName)
+        aa = [ii, noeuds[ii].uknom, busname, noeuds[ii].GetBusType()]           # [numero,nominal KV,busname]
         buses.append(aa)
-    # ==============================================================#
-    # Loads data (busnumber, active, reactive, status, name, id)
+
+    """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
+    Loads data (busname, ID, extended busname, busnumber, P, Q)
+    """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
+    LoadDico = {}
+    
+    """
+    Load classique 
+    """
     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("$","_")
+            busname = cleanName(busname)
+            
             if busname == bus[2]:
-                idload += 1  # cree id pour load
+                idload   += 1                                                     # Create id for loads
                 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  = busname
+                loadname  = cleanName(loadname)
+                
+                if loadname[0] == "_":
+                    loadname = "C" + loadname
+               
                 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
+    """
+    Load MV 
+    """               
+    tous = []
+    for grid in grids:
+        tous.extend(grid.obj_id.GetContents( '*.ElmLodMV', 1))
+    
+    tous = sorted(tous, key=lambda x: x.bus1.cBusBar.cStatName)
+    
+    for bus in buses:
+        idload = 0
+        
+        for load in tous:
+            busname = load.bus1.cBusBar.cStatName
+            busname = cleanName(busname)
+            
+            if busname == bus[2]:
+                idload   += 1  # cree id pour load
+                busnumber = bus[0]
+                loadname  = busname
+                loadname  = cleanName(loadname)
+                
+                if loadname[0] == "_":
+                    loadname    = "C" + loadname
+                    
+                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
+                s = load.slini_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]
+                LoadDico[loadname]['P']      = p
+                LoadDico[loadname]['Q']      = np.sqrt(s**2-p**2)
+   
+             
+    """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
+    Generators data (busname, ID, extended busname, busnumber, P, Q, Pmax, Pmin, Qmax, Qmin)
+    """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
+    MachineDico = {}  
+    
+    """
+    Generateur synchrone
+    """
     tous = []
     for grid in grids:
         tous.extend(grid.obj_id.GetContents( '*.ElmSym', 1))
@@ -110,52 +164,46 @@ def PFExtractData(NetworkFile, PF_PATH):
     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("$","_")
+            busname = cleanName(busname)
+            
             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
+            
+            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)         # Synchronous generators
+            #machinename = machinename.replace("Generator", "gen")
+            machinename = cleanName(machinename)
+            #machinename = machinename + '_' +'syn_' + 'Gr_' + str(idplant)      # Synchronous generators
+            
+            if machinename[0] == "_":
+                machinename    = "G" + machinename
+
+            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
+            MachineDico[machinename]['P']      = p
+            MachineDico[machinename]['Q']      = q
+            MachineDico[machinename]['PMAX']   = pmax
+            MachineDico[machinename]['QMAX']   = qmax
+            MachineDico[machinename]['PMIN']   = pmin
+            MachineDico[machinename]['QMIN']   = qmin
+    """
+    Generateur asynchrone
+    """
     tous = []
     for grid in grids:
         tous.extend(grid.obj_id.GetContents( '*.ElmAsm', 1))
@@ -163,155 +211,142 @@ def PFExtractData(NetworkFile, PF_PATH):
     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("$","_")
+            busname = cleanName(busname)
+            
             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
+            #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)        # Asynchronous generators 
+            machinename = cleanName(machinename)
+            # machinename = machinename + '_' +'asyn_' + 'Gr_' + str(idplant)   # Asynchronous generators 
+            
+            if machinename[0] == "_":
+                machinename    = "G" + machinename
+   
+
+            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
+            MachineDico[machinename]['P']      = p
+            MachineDico[machinename]['Q']      = q
+            MachineDico[machinename]['PMAX']   = pmax
+            MachineDico[machinename]['QMAX']   = qmax
+            MachineDico[machinename]['PMIN']   = pmin
+            MachineDico[machinename]['QMIN']   = qmin
+    
+    
+    """
+    Generateur statique
+    """    
     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("$","_")
+        busname = cleanName(busname)
+        
         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
+        #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)         # Static generators 
+        machinename = cleanName(machinename)
+    
+        if machinename[0] == "_":
+            machinename    = "G" + machinename
+
+        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
+        MachineDico[machinename]['P']      = p
+        MachineDico[machinename]['Q']      = q
+        MachineDico[machinename]['PMAX']   = pmax
+        MachineDico[machinename]['QMAX']   = qmax
+        MachineDico[machinename]['PMIN']   = pmin
+        MachineDico[machinename]['QMIN']   = qmin
+
 
+    """
+    Systeme photovoltaique
+    """ 
     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("$","_")
+        busname = cleanName(busname)
+       
         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
+       
+        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)              # PV generators
+        machinename = cleanName(machinename)
+        
+        if machinename[0] == "_":
+            machinename    = "G" + machinename
+
+        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
+        MachineDico[machinename]['P']      = p
+        MachineDico[machinename]['Q']      = q
+        MachineDico[machinename]['PMAX']   = pmax
+        MachineDico[machinename]['QMAX']   = qmax
+        MachineDico[machinename]['PMIN']   = pmin
+        MachineDico[machinename]['QMIN']   = qmin
+
 
+    """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
+    Motors data (busname, ID, extended busname, busnumber, P, Q, Pmax, Pmin, Qmax, Qmin)
+    """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
     MotorDico = {}  # [Bus name, machine ID, extended bus name, bus number]
+   
+    """
+    Moteur synchrone
+    """
     tous = []
     for grid in grids:
         tous.extend(grid.obj_id.GetContents( '*.ElmSym', 1))
@@ -319,49 +354,44 @@ def PFExtractData(NetworkFile, PF_PATH):
     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
+            
+            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)         # Synchronous motors
+            machinename = cleanName(machinename)
+            
+            if machinename[0] == "_":
+                machinename    = "M" + machinename
+       
+            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
+            MotorDico[machinename]['P']      = p
+            MotorDico[machinename]['Q']      = q
+            MotorDico[machinename]['PMAX']   = pmax
+            MotorDico[machinename]['QMAX']   = qmax
+            MotorDico[machinename]['PMIN']   = pmin
+            MotorDico[machinename]['QMIN']   = qmin
+
+
+    """
+    Moteur asynchrone
+    """   
     tous = []
     for grid in grids:
         tous.extend(grid.obj_id.GetContents( '*.ElmAsm', 1))
@@ -369,116 +399,113 @@ def PFExtractData(NetworkFile, PF_PATH):
     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("$","_")
+            busname = cleanName(busname)
+            
             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
+            
+            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)        # Asynchronous motors 
+            machinename = cleanName(machinename)
+            
+            if machinename[0] == "_":
+                machinename    = "M" + machinename
+        
+            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]
+            MotorDico[machinename]['P']      = p
+            MotorDico[machinename]['Q']      = q
+            MotorDico[machinename]['PMAX']   = pmax
+            MotorDico[machinename]['QMAX']   = qmax
+            MotorDico[machinename]['PMIN']   = pmin
+            MotorDico[machinename]['QMIN']   = qmin
+
+
+    """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
+    Lines data (busname1, busname2, ID, extended bus name 1, extended bus name 2, bus number 1, bus number 2)
+    """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
+    LineDico = {}  
+  
     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
+        if (line.bus1 != None) & (line.bus2 != None):
+            linename     = line.loc_name
+            frombus_name = line.bus1.cBusBar.cStatName
+            frombus_name = cleanName(frombus_name)
+            
+            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 = cleanName(tobus_name)
+            
+            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 = cleanName(linename)
+            
+            if linename[0] == "_":
+                linename    = "L" + linename
+
+            if NoBreakersandSwitches:
+                if 'Br' not in idline and 'Sw' not in idline:
+                    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
+
+
+    """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
+    Transfo data (Bus name 1, Bus name 2, machine ID, extended bus name 1, extended bus name 2, bus number 1, bus number 2)
+    """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
     TfoDico = {}  # [tranlinename, Bus name 1, Bus name 2, machine ID, extended bus name 1, extended bus name 2, bus number 1, bus number 2]
+  
+    """
+    2-winding transfo
+    """    
     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("$","_")
+        #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 = cleanName(frombus_name)
+        tobus_name   = cleanName(tobus_name)
+        
         for ii in range(len(buses)):
             if frombus_name in buses[ii]:
                 frombus_number = ii
@@ -490,118 +517,103 @@ def PFExtractData(NetworkFile, PF_PATH):
                 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
+        tfoname = frombus_name + '_' + tobus_name + '_' + str(id_tfo) + '_' + 'Tr'
+        tfoname = cleanName(tfoname) 
+      
         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
+            if 'Br' not in id_tfo and 'Sw' not in id_tfo:
+                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
+      
+             
+    """
+    3-winding transfo
+    """    
     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
+        #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("$","_")
+        tobus_name   = tfo.busmv.cBusBar.cStatName
+        bus3         = tfo.buslv.cBusBar.cStatName
+        frombus_name = cleanName(frombus_name)
+        tobus_name   = cleanName(tobus_name)
+        bus3         = cleanName(bus3)
+        
         for ii in range(len(buses)):
             if frombus_name in buses[ii]:
                 frombus_number = ii
-                frombus_KV=buses[ii][1]
+                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]
+                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]
+                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
+        
+        tfoname = frombus_name + '_' + tobus_name + '_' +bus3 + '_' + str(id_tfo) + '_' + 'Tr3'
+        tfoname = cleanName(tfoname)
+
         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()
+            if 'Br' not in id_tfo and 'Sw' not in id_tfo:
+                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
+
 
+    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)
 
+with open('Data_for_interface', 'wb') as fichier:
+    mon_pickler = pickle.Pickler(fichier,protocol=2)
+    mon_pickler.dump(Data)
\ No newline at end of file
index 0712ed462261132db453126b37be31c5e32087a6..ffa8b5ee7b24405ce4bacef97f8a6659aacb6dc3 100644 (file)
@@ -6,7 +6,7 @@ Created on Thu Feb  9 14:57:43 2017
 """
 
 import sys,os
-path1 = os.path.abspath(os.path.join(os.path.abspath(__file__), '../', '../', 'PSEN_Eficas', 'PSEN'))
+path1 = os.path.abspath(os.path.join(os.path.abspath(__file__), '../', '../', 'PSSE_PF_Eficas', 'PSEN'))
 sys.path.append(path1) 
 import PSENconfig
 import subprocess
index 269402b4dfc01615e3a45dd56e5f611dbc6b312c..d3d945bf937d7983759634ba3da1227caa4844c4 100644 (file)
@@ -54,6 +54,7 @@ def INCLUDE(self, PF_path, pfd_file,Python3_path, **args):
 
    try:
        print('before PFExtractGeneratorLoadLineandTransfoDico')
+       # MachineDico, LoadDico, LineDico, TransfoDico, MotorDico = PFExtractGeneratorLoadLineandTransfoDico(pfd_file, PF_path,Python3_path)
        MachineDico, LoadDico, LineDico, TransfoDico, MotorDico = PFExtractGeneratorLoadLineandTransfoDico(pfd_file, PF_path,Python3_path)
 
        print('after extract')
@@ -66,7 +67,6 @@ def INCLUDE(self, PF_path, pfd_file,Python3_path, **args):
         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)
@@ -74,7 +74,7 @@ def INCLUDE(self, PF_path, pfd_file,Python3_path, **args):
    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)
@@ -85,19 +85,21 @@ def INCLUDE(self, PF_path, pfd_file,Python3_path, **args):
 
    for nom in MotorDico.keys():
       self.fichier_text += "%s=MONMOTEUR(ID='%s',);\n" % (nom,'a')
+      listeNouveau.append(nom)
 
    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)
index 78d21f9a0db52bf61953ab9b02afacacef54921e..3818feecb26fd3ce0108a352475432006c9cfab2 100644 (file)
@@ -1,2 +1,3 @@
-X:/Small Grid PSSE/TestIsland_2015_OPF - Areas.sav
-C:\Program Files (x86)\PTI\PSSE34\PSSBIN
+C:/Users/H92579/Documents/Formation_PF/ex_PFD/Mayotte_Test.pfd
+C:/Program Files/DIgSILENT/PowerFactory 2018 SP3/Python/3.5
+C:/Python35
index 5b36e5e302fbd94135cd23639fa519e705c5ff61..46826fbda264e000ffeab5d4b5ba15fc342d4f7c 100644 (file)
@@ -4,51 +4,59 @@
 ############################################################
 debug = True
 
-dicoCaracteresSpeciaux = {
-        " "  : "_",
-        "-"  : "_" ,
-        "."  : "_" ,
-        "&"  : "and" ,
-        "%"  : "pct" ,
+dictSpecialCharacters = {
+        " "  : "_"  ,
+        "-"  : "_"  ,
+        "."  : "_"  ,
+        ";"  : "_"  ,
+        "&"  : "and",
+        "%"  : "pct",
         "="  : "eq" ,
-        "#"  : "_" ,
-        "$"  : "_" ,
-        "/"  : "_" ,
-        "\\" : "_" ,
-        "@"  : "Br",
-        "*"  : "Sw",
-        "'"  : "_"
-       }
-def nettoyeName (name)  : 
+        "#"  : "_"  ,
+        "$"  : "_"  ,
+        "/"  : "_"  ,
+        "\\" : "_"  ,
+        "@"  : "Br" ,
+        "*"  : "Sw" ,
+        "'"  : "_"  ,
+        "("  : "_"  ,
+        ")"  : "_"  ,
+        "é"  : "_"  ,
+        "è"  : "_"  ,
+        "à"  : "_" 
+        }
+
+def cleanName (name)  : 
 # ---------------------
-# remplace les caracteres speciaux definis dans dicoCaracteresSpeciaux
+# remplace les caracteres speciaux definis dans dictSpecialCharacters
 # de la chaine name passe en argument et retourne une chaine nettoyee
 # prefixe la chaine d un _ si la chaine commence par un chiffre
 
-    nouveauNom = name
-    for c in dicoCaracteresSpeciaux.keys():
-        nouveauNom = nouveauNom.replace(c,dicoCaracteresSpeciaux[c])
-    if nouveauNom[0] in ( '0','1','2','3','4','5','6','7','8','9') : nouveauNom = '_'+nouveauNom
-    return nouveauNom
+    newName = name
+    for c in dictSpecialCharacters.keys():
+        newName = newName.replace(c,dictSpecialCharacters[c])
+    if newName[0] in ( '0','1','2','3','4','5','6','7','8','9'): 
+        newName = '_' + newName
+    return newName
 
 
-def testNettoyeName():
-    nom1 = 'a b-c'
-    if nettoyeName(nom1) != 'a_b_c':
-       print ('Echec de testNettoyeName sur remplacement du blanc')
+def testCleanName():
+    nom1 = 'a&b-c'
+    if cleanName(nom1) != 'aandb_c':
+       print ('Echec de testCleanName sur remplacement du blanc')
        exit()
     nom2 = '2a'
-    if nettoyeName(nom2) != '_2a':
-       print ('Echec de testNettoyeName sur prefixe par _ ')
+    if cleanName(nom2) != '_2a':
+       print ('Echec de testCleanName sur prefixe par _ ')
        exit()
-    print ('succes testNettoyeName')
+    print ('succes testCleaname')
 
-def testNettoyeNameAvecProfil():
+def testCleanNameAvecProfil():
       import cProfile, pstats, StringIO
       pr = cProfile.Profile()
       pr.enable()
       # appel de la fonction qu on veut profiler
-      testNettoyeName()
+      testCleanName()
       pr.disable()
       s = StringIO.StringIO()
       sortby = 'cumulative'
@@ -58,5 +66,5 @@ def testNettoyeNameAvecProfil():
     
 
 if __name__ == "__main__":
-     testNettoyeName()
-     testNettoyeNameAvecProfil()
+     testCleanName()
+     testCleanNameAvecProfil()