Salome HOME
af7f42ebf56dc1ea86259e4adae3bca6313e618b
[tools/eficas.git] / convert / convert_TELEMAC.py
1 # Copyright (C) 2007-2013   EDF R&D
2 #
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License.
7 #
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 # Lesser General Public License for more details.
12 #
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 #
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 #
19 import re, string
20 from Extensions.i18n import tr
21 from Accas.A_BLOC import BLOC
22 from Accas import *
23
24                                                                                         
25 from convert_python import PythonParser
26
27 pattern_comment_slash   = re.compile(r"^\s*/")
28 pattern_eta   = re.compile(r".*&ETA.*")
29 pattern_fin   = re.compile(r".*&FIN.*")
30 pattern_oui   = re.compile(r"^\s*(oui|OUI|YES|yes|TRUE|VRAI)\s*$")
31 pattern_non   = re.compile(r"^\s*(non|NON|NO|no|FALSE|FAUX)\*s$")
32 pattern_blanc = re.compile(r"^\s*$")
33 pattern_listeVide = re.compile(r"^\s*'\s*'\s*$")
34
35 pattern_ligne=re.compile(r'^\s*(?P<ident>[^=:]*)\s*[:=]\s*(?P<reste>.*)$')
36
37 # Attention aux listes de flottants
38 pattern_liste=re.compile(r'^\s*(?P<valeur>[+-.\w]+(\s*;\s*[+-.\w]+)+)\s*(?P<reste>.*)$')
39 pattern_flottant=re.compile(r'^\s*(?P<valeur>[+-]?((\d+(\.\d*)?)|(\.\d+))([dDeE][+-]?\d+)?)\s*(?P<reste>.*)$')
40 pattern_texteQuote  = re.compile (r"^\s*(?P<valeur>'[^']+(''[^']+)*')\s*(?P<reste>.*)$")
41 pattern_texteSimple = re.compile (r"(?P<valeur>(^|\s)\s*[\w\.-]+)\s*(?P<reste>.*)$")
42 pattern_texteVide  = re.compile (r"^\s*(?P<valeur>'')\s*(?P<reste>.*)$")
43
44 pattern_ContientDouble=re.compile (r"^.*''.*$")
45
46
47 # le pattern texte reconnait 
48 #nom1 nom 2 : ou = chaine entre ' 
49 # avec eventuellement  des quotes au milieu par exemple
50 # TITRE = 'TELEMAC 2D : GOUTTE D''EAU DANS UN BASSIN$'
51 # m.group("texte") va rendre 'TELEMAC 2D : GOUTTE D''EAU DANS UN BASSIN$' 
52
53
54 #Si le code n est pas Telemac
55 try :
56    from aideAuxConvertisseurs import DicoEficasToCas, ListeSupprimeCasToEficas
57    from aideAuxConvertisseurs import ListeCalculCasToEficas, DicoAvecMajuscules
58    from enumDicoTelemac2      import DicoEnumCasEn
59 except :
60    pass
61
62 from Extensions import localisation
63
64 from determine import monEnvQT5
65
66
67
68 def entryPoint():
69    """
70    Return a dictionary containing the description needed to load the plugin
71    """
72    return {
73           'name' : 'TELEMAC',
74           'factory' : TELEMACParser
75           }
76
77 class TELEMACParser(PythonParser):
78    """
79    This converter works like PythonParser, except that it also initializes all
80    model variables to None in order to avoid Python syntax errors when loading
81    a file with a different or inexistent definition of variables.
82    """
83
84    def convert(self, outformat, appli=None):
85       self.dicoInverseFrancais=appli.readercata.dicoInverseFrancais
86       self.dicoAnglaisFrancais=appli.readercata.dicoAnglaisFrancais
87       self.dicoFrancaisAnglais=appli.readercata.dicoFrancaisAnglais
88       self.dicoMC=appli.readercata.dicoMC
89       self.Ordre_Des_Commandes=appli.readercata.Ordre_Des_Commandes
90    
91
92       #print self.dicoInverseFrancais
93       #text = PythonParser.convert(self, outformat, appli)
94       
95       text=""
96       l_lignes = string.split(self.text,'\n')
97       self.dictSimp={}
98       for ligne in l_lignes :
99
100           if pattern_comment_slash.match(ligne) : continue
101           if pattern_eta.match(ligne) : continue
102           if pattern_fin.match(ligne) : continue
103           if pattern_blanc.match(ligne) : continue
104  
105
106           finLigne=ligne
107           while finLigne != "" :
108               print finLigne
109               valeur=""
110               m=pattern_ligne.match(finLigne)
111               if m == None : 
112                  print "________________________________________________"
113                  print 'pb avec ****', finLigne , '**** dans ', ligne
114                  print "________________________________________________"
115                  break
116       
117               simp=self.traiteIdent(m.group('ident'))
118               finLigne=m.group('reste')
119
120               # attention, l ordre des if est important
121               if pattern_liste.match(finLigne) :
122                  m=pattern_liste.match(finLigne)
123               elif pattern_texteQuote.match(finLigne) :
124                  m=pattern_texteQuote.match(finLigne)
125               elif pattern_flottant.match(finLigne) : 
126                  m=pattern_flottant.match(finLigne)
127               elif pattern_texteVide.match(finLigne):
128                  m=pattern_texteVide.match(finLigne)
129               elif pattern_texteSimple.match(finLigne):
130                  m=pattern_texteSimple.match(finLigne)
131               else :
132                  print "________________________________________________"
133                  print 'pb avec ****', finLigne , '**** dans ', ligne
134                  print "non match"
135                  print "________________________________________________"
136                  break
137               
138               valeur=m.group('valeur')
139               if pattern_blanc.match(valeur) : valeur=None
140
141               if pattern_flottant.match(finLigne) : 
142                  valeur=re.sub("d","e",valeur)
143                  valeur=re.sub("D","E",valeur)
144
145               if pattern_liste.match(finLigne):
146                  valeur=valeur.split(";")
147
148               finLigne=m.group('reste')
149               #print simp 
150               #print valeur
151               #print finLigne
152               self.dictSimp[simp]=valeur
153       
154       if 'Title' not in self.dictSimp.keys() and 'Titre' not in self.dictSimp.keys():
155           import os
156           self.dictSimp['Titre']=os.path.basename(self.filename)
157       
158       dicoParMC={}
159       for simp in self.dictSimp.keys():
160           #print simp, " : ", self.dictSimp[simp]
161            
162           if simp in TELEMACParser.__dict__.keys() : apply(TELEMACParser.__dict__[simp],(self,))
163
164       for simp in self.dictSimp.keys():
165           if simp in ListeSupprimeCasToEficas: continue
166           if simp not in self.dicoInverseFrancais.keys() : 
167              print "************"
168              print "pb avec dans dicoInverseFrancais", simp,'------'
169              print "************"
170              print poum
171              continue
172           listeGenea=self.dicoInverseFrancais[simp]
173           listeGeneaReverse=[]
174           for (u,v) in listeGenea : 
175               if isinstance(v,BLOC): continue
176               listeGeneaReverse.append(u)
177           listeGeneaReverse.reverse()
178           dicoTravail=dicoParMC
179           i=0
180           #print (listeGeneaReverse[0:-1])
181           while i < len(listeGeneaReverse[0:-1]) : 
182             mot=listeGeneaReverse[i]
183             i=i+1
184             if mot not in dicoTravail.keys(): dicoTravail[mot]={}
185             dicoTravail=dicoTravail[mot]
186           dicoTravail[simp]=self.dictSimp[simp]
187         
188       self.textePy=""
189       #print "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"
190       #print dicoParMC
191       #print "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"
192       listeMC=self.tri(dicoParMC.keys())
193       for k in listeMC :
194           #print "----------- traitement de " , k
195           self.textePy += self.dicoFrancaisAnglais[k] + "("
196           self.traiteMC(dicoParMC[k])
197           self.textePy += ");\n"
198           #print "----------- " 
199            
200               
201       print self.textePy
202       return self.textePy 
203
204    #----------------------------------------
205    def redecoupeSimp(self,simp): 
206    # traite les - dans les identifants python
207    # les remplace par des _
208    #----------------------------------------
209       # replace('-','_')  uniquement dans les identifiants
210       while simp.find('-') > 0 : 
211         ind=simp.find('-')
212         if ind==len(simp)-1 : break
213         simp=simp[0:ind]+'_'+simp[ind+1].upper()+simp[ind+2:]
214
215    #----------------------------------------
216    def traiteIdent(self,listeIdent):
217    # Recree l identifiant Python
218    #----------------------------------------
219           while listeIdent[-1] == " " or listeIdent[-1] == '\t' : listeIdent=listeIdent[0:-1]
220           while listeIdent[0]  == " " or listeIdent[0]  == '\t' : listeIdent=listeIdent[1:]
221           
222           listeIdent=re.sub("'"," ",listeIdent)
223           motsInIdent=string.split(listeIdent,' ')
224           simp=""
225           for mot in motsInIdent:
226               if re.compile(r"^\s*$").match(mot) : continue
227               mot=mot.replace('_','__')
228               simp=simp+mot[0].upper() +mot[1:].lower()+'_'
229
230           simp=simp[0:-1]
231           while simp[-1] == " " : simp=simp[0:-1]
232           if simp.find('-') > 0 : simp=self.redecoupeSimp(simp)
233           return simp
234
235
236    def traiteMC(self,dico) :
237        for k in dico.keys() :
238            valeur= dico[k]
239            if k not in self.dicoMC.keys() : kA=self.dicoFrancaisAnglais[k] 
240            else : kA=k
241            obj=self.dicoMC[kA]
242            if isinstance(obj,FACT):   self.generFACT(obj,kA,valeur)
243            elif isinstance(obj,BLOC): self.generBLOC(obj,kA,valeur)
244            elif isinstance(obj,SIMP): self.generSIMP(obj,kA,valeur)
245            else : print "%%%%%%%%%%%\n", "pb generation pour", k, obj, "\n%%%%%%%%%%%"
246
247            #print "_____________"
248
249    def generFACT(self,obj,nom,valeur):
250        if nom in TELEMACParser.__dict__.keys() : 
251           apply(TELEMACParser.__dict__[nom],(self,))
252           return
253        self.textePy +=  nom + "=_F( "
254        self.traiteMC(valeur)
255        self.textePy += '),\n'
256
257
258    def generBLOC(self,obj,nom,valeur):
259        print "BLOC "
260        print nom
261
262    def generSIMP(self,obj,nom,valeur):
263        if nom in ("Prescribed_Flowrates", "Prescribed_Velocities", "Prescribed_Elevations" ): return
264        #print "___________________________"
265        #print nom
266        #print valeur
267        if valeur == None : print nom
268        if obj.max==1 : 
269           if 'TXM' in obj.type :
270
271               if pattern_ContientDouble.match(valeur):
272                  valeur=re.sub("''","\'\'",valeur)
273                  print str(valeur)
274                  print valeur
275                  print tr(valeur)
276                  print poum
277               valeur=str(valeur)
278
279               # ceinture et bretelle si les re sont correctes -)
280               while valeur[-1] == " " or valeur[-1] == '\t' : valeur=valeur[0:-1]
281               while valeur[0]  == " " or valeur[0]  == '\t' : valeur=valeur[1:]
282
283               if pattern_ContientDouble.match(valeur):
284                  valeur=re.sub("''","\'\'",valeur)
285                  print valeur
286                  print tr(valeur)
287                  print poum
288
289
290           # Pour les enum
291           try    : valeur=eval(valeur,{})
292           except : pass
293           if nom in DicoEnumCasEn.keys(): 
294              #print "est dans le dico des enum, valeur simple"
295              try    : valeur=DicoEnumCasEn[nom][valeur]
296              except : pass
297
298
299           if obj.into != [] and obj.into != None :
300              for possible in obj.into :
301                   if possible.upper() == valeur.upper():
302                      valeur=possible
303                      break
304                   v=valeur[0].upper()+valeur[1:].lower()
305                   v2=tr(v)
306                   if possible.upper() == v2.upper():
307                      valeur=possible
308                      break
309
310           if 'Fichier' in obj.type or 'TXM' in obj.type or 'Repertoire' in obj.type :
311               valeur=str(valeur)
312               while valeur[-1] == " " : valeur=valeur[0:-1]
313               while valeur[0]  == " " : valeur=valeur[1:]
314               self.textePy += nom + "= '" + str(valeur) +"' ,"
315               return
316
317           if bool in obj.type :
318             if   valeur == True  :  self.textePy += nom + "= True,"
319             elif valeur == False :  self.textePy += nom + "= False,"
320             elif pattern_oui.match(valeur) : self.textePy += nom + "= True,"
321             elif pattern_non.match(valeur) : self.textePy += nom + "= False,"
322             else :  self.textePy += nom + "= None,"
323             return
324           self.textePy += nom + "=" + str(valeur) +","
325
326        else :
327           if pattern_listeVide.match(valeur) :
328              self.textePy += nom + "= None,"
329              return
330           while valeur[-1] == " " or  valeur[-1]=="'" : valeur=valeur[0:-1]
331           while valeur[0]  == " " or  valeur[-0]=="'" : valeur=valeur[1:]
332
333           if   ";" in valeur : valeur=valeur.split(';')
334           elif "," in valeur : valeur=valeur.split(',')
335
336           if valeur == None : return
337           newVal=[]
338           for v in valeur :
339             try :    v=eval(v,{})
340             except : pass
341             if nom in DicoEnumCasEn.keys():
342                #print "est dans le dico des enum, valeurs multiples"
343                try    : v=DicoEnumCasEn[nom][v]
344                except : pass
345             newVal.append(v)
346           self.textePy += nom + "=" + str(newVal) +","
347           
348
349
350    def tri(self, listeIn):
351       if len(listeIn) == 1 : return listeIn
352       if self.Ordre_Des_Commandes == None : return listeIn
353       #print self.Ordre_Des_Commandes
354       listeOut=[listeIn[0],]
355       for kF in listeIn[1:]:
356           k=str(self.dicoFrancaisAnglais[kF])
357           ordreK=self.Ordre_Des_Commandes.index(k)
358           i=0
359           while i < len(listeOut):
360              ordreI=self.Ordre_Des_Commandes.index(self.dicoFrancaisAnglais[listeOut[i]])
361              if ordreK < ordreI : break
362              i=i+1
363           listeOut.insert(i,kF)
364       return listeOut
365
366    def Processeurs_Paralleles(self):
367       #YOANN
368       if self.dictSimp["Processeurs_Paralleles"] == 0 : del  self.dictSimp["Processeurs_Paralleles"]
369       else : self.dictSimp["Parallel_Computation"]="Parallel"
370  
371    def decoupeListe(self,valeurs,label):
372       print "decoupeSUPG"
373       print valeurs
374       i=0
375       for prefixe in ('_U_And_V','_H'):
376           labelComplet=label+prefixe
377           valeur=valeurs[i]
378           try    : valeur=eval(valeur,{})
379           except : pass
380           if tr(label) in DicoEnumCasEn.keys(): 
381              try    : valeur=DicoEnumCasEn[tr(label)][valeur]
382              except : pass
383           self.dictSimp[labelComplet]=valeur
384           i=i+1
385       if len(valeurs)==2 : return
386       for prefixe in ('_K_And_Epsilon','_Tracers'):
387           labelComplet=label+prefixe
388           valeur=valeurs[i]
389           try    : valeur=eval(valeur,{})
390           except : pass
391           if tr(label) in DicoEnumCasEn.keys(): 
392              try    : valeur=DicoEnumCasEn[tr(label)][valeur]
393              except : pass
394           self.dictSimp[labelComplet]=valeur
395           i=i+1
396       
397    def Option_De_Supg(self):
398        #print "ds Option_De_Supg"
399        self.decoupeListe( self.dictSimp["Option_De_Supg"],"Option_De_Supg")
400        del self.dictSimp["Option_De_Supg"]
401
402    def Forme_De_La_Convection(self):
403        self.decoupeListe( self.dictSimp["Forme_De_La_Convection"],"Forme_De_La_Convection")
404        valeurs=self.dictSimp["Forme_De_La_Convection"]
405        del self.dictSimp["Forme_De_La_Convection"]
406        self.dictSimp['Convection_De_U_Et_V']=True
407        self.dictSimp['Convection_De_H']=True
408        if len(valeurs)==2 : return
409        self.dictSimp['Advection_Of_K_And_Epsilon']=True
410        self.dictSimp['Advection_Of_Tracers']=True
411
412    def Discretisations_En_Espace(self):
413        self.decoupeListe( self.dictSimp["Discretisations_En_Espace"],"Discretisations_En_Espace")
414        del self.dictSimp["Discretisations_En_Espace"]
415        
416
417    def Liquid_Boundaries(self):
418        #print 'Liquid Boundaries'
419        texte_Boundaries="Liquid_Boundaries=( "
420        premier=0
421        if 'Prescribed_Elevations' in self.dictSimp.keys(): 
422            valeurs=self.dictSimp["Prescribed_Elevations"]
423        elif 'Cotes_Imposees' in self.dictSimp.keys(): 
424            valeurs=self.dictSimp["Cotes_Imposees"]
425        else : valeurs=()
426        #print valeurs
427        for e in range(len(valeurs)):
428           if valeurs[e] == "" or valeurs[e] == "\n" : continue
429           if eval(valeurs[e],{})==0 : continue
430           if not premier : premier=1
431           texte_Boundaries += "_F(Type_Condition = 'Prescribed Elevations',\n"
432           texte_Boundaries += "Prescribed_Elevations = " + str(valeurs[e]) + "),\n"
433                
434        if 'Prescribed_Flowrates' in self.dictSimp.keys(): 
435           valeurs=self.dictSimp["Prescribed_Flowrates"]
436        elif 'Debits_Imposes' in self.dictSimp.keys(): 
437           valeurs=self.dictSimp["Debits_Imposes"]
438        else : valeurs=()
439        #print valeurs
440        for e in range(len(valeurs)):
441           if valeurs[e] == "" or valeurs[e] == "\n" : continue
442           if eval(valeurs[e],{})==0 : continue
443           if not premier : premier=1
444           texte_Boundaries += "_F(Type_Condition = 'Prescribed Flowrates',\n"
445           texte_Boundaries += "Prescribed_Flowrates = " + str(valeurs[e]) + "),\n"
446                
447        if 'Prescribed_Velocity' in self.dictSimp.keys(): 
448            valeurs=self.dictSimp["Prescribed_Velocity"]
449        elif 'Vitesses_Imposees' in self.dictSimp.keys(): 
450            valeurs=self.dictSimp["Vitesses_Imposees"]
451        else : valeurs=()
452        #print valeurs
453        for e in range(len(valeurs)):
454           if valeurs[e] == "" or valeurs[e] == "\n" : continue
455           if eval(valeurs[e],{})==0 : continue
456           if not premier : premier=1
457           texte_Boundaries += "_F(Type_Condition = 'Prescribed Velocity',\n"
458           texte_Boundaries += "Prescribed_Velocity = " + str(valeurs[e]) + "),\n"
459        if premier :  texte_Boundaries +="),\n"
460        else : texte_Boundaries="" ; print "pb texte_Boundaries "
461        self.textePy += texte_Boundaries
462