]> SALOME platform Git repositories - tools/eficas.git/blob - convert/convert_TELEMAC2.py
Salome HOME
sauve0206
[tools/eficas.git] / convert / convert_TELEMAC2.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
22                                                                                         
23 from convert_python import PythonParser
24
25 pattern_comment_slash   = re.compile(r"^\s*/")
26 pattern_eta   = re.compile(r".*&ETA.*")
27 pattern_fin   = re.compile(r".*&FIN.*")
28 pattern_oui   = re.compile(r"^\s*(oui|OUI|YES|yes|TRUE|VRAI)\s*$")
29 pattern_non   = re.compile(r"^\s*(non|NON|NO|no|FALSE|FAUX)\*s$")
30 pattern_blanc = re.compile(r"^\s*$")
31 pattern_listeVide = re.compile(r"^\s*'\s*'\s*$")
32
33 pattern_ligne=re.compile(r'^\s*(?P<ident>[^=:]*)\s*[:=]\s*(?P<reste>.*)$')
34
35 pattern_variables=re.compile (r"^\s*(?P<ident>VARIABLES POUR LES SORTIES GRAPHIQUES)\s*[:=]\s*(?P<valeur>\w(,\w)*)\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 enumDicoTelemac       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' : 'TELEMAC2',
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       from Accas import A_BLOC, A_FACT, A_SIMP
86       #self.dicoInverseFrancais=appli.readercata.dicoInverseFrancais
87       #self.dicoAnglaisFrancais=appli.readercata.dicoAnglaisFrancais
88       #self.dicoFrancaisAnglais=appli.readercata.dicoFrancaisAnglais
89       self.dicoInverse=appli.readercata.dicoInverse
90       self.dicoMC=appli.readercata.dicoMC
91       self.Ordre_Des_Commandes=appli.readercata.Ordre_Des_Commandes
92    
93
94       #print self.dicoInverseFrancais
95       #text = PythonParser.convert(self, outformat, appli)
96       
97       text=""
98       l_lignes = string.split(self.text,'\n')
99       self.dictSimp={}
100       for ligne in l_lignes :
101
102           if pattern_comment_slash.match(ligne) : continue
103           if pattern_eta.match(ligne) : continue
104           if pattern_fin.match(ligne) : continue
105           if pattern_blanc.match(ligne) : continue
106  
107
108           finLigne=ligne
109           while finLigne != "" :
110               #print finLigne
111               if pattern_comment_slash.match(finLigne) : finLigne=""; continue
112               valeur=""
113               if pattern_variables.match(finLigne) :
114                  m=pattern_variables.match(finLigne)
115                  valeur=m.group('valeur')
116                  finLigne=m.group('reste')
117                  self.dictSimp[simp]=valeur
118                  continue
119
120               m=pattern_ligne.match(finLigne)
121               if m == None : 
122                  #print "________________________________________________"
123                  print 'pb avec ****', finLigne , '**** dans ', ligne
124                  #print "________________________________________________"
125                  break
126       
127               simp=self.traiteIdent(m.group('ident'))
128               finLigne=m.group('reste')
129
130               # attention, l ordre des if est important
131               if pattern_liste.match(finLigne) :
132                  m=pattern_liste.match(finLigne)
133               elif pattern_texteQuote.match(finLigne) :
134                  m=pattern_texteQuote.match(finLigne)
135               elif pattern_flottant.match(finLigne) : 
136                  m=pattern_flottant.match(finLigne)
137               elif pattern_texteVide.match(finLigne):
138                  m=pattern_texteVide.match(finLigne)
139               elif pattern_texteSimple.match(finLigne):
140                  m=pattern_texteSimple.match(finLigne)
141               else :
142                  #print "________________________________________________"
143                  print 'pb avec ****', finLigne , '**** dans ', ligne
144                  print "non match"
145                  #print "________________________________________________"
146                  break
147               
148               valeur=m.group('valeur')
149               if pattern_blanc.match(valeur) : valeur=None
150
151               if pattern_flottant.match(finLigne) : 
152                  valeur=re.sub("d","e",valeur)
153                  valeur=re.sub("D","E",valeur)
154
155               if pattern_liste.match(finLigne):
156                  valeur=valeur.split(";")
157
158               finLigne=m.group('reste')
159               self.dictSimp[simp]=valeur
160       
161       if 'TITLE' not in self.dictSimp.keys() :
162           import os
163           self.dictSimp['TITLE']=os.path.basename(self.filename)
164       
165       dicoParMC={}
166       for simp in self.dictSimp.keys():
167           if simp in TELEMACParser.__dict__.keys() : apply(TELEMACParser.__dict__[simp],(self,))
168
169       for simp in self.dictSimp.keys():
170           if simp in ListeSupprimeCasToEficas: continue
171           if simp not in self.dicoInverse.keys() : 
172              print "************"
173              print "pb avec dans dicoInverse", simp,'------'
174              print "************"
175              #print poum
176              continue
177           listeGenea=self.dicoInverse[simp]
178           listeGeneaReverse=[]
179           for (u,v) in listeGenea : 
180               if isinstance(v,A_BLOC.BLOC): continue
181               listeGeneaReverse.append(u)
182           listeGeneaReverse.reverse()
183           dicoTravail=dicoParMC
184           i=0
185           #print (listeGeneaReverse[0:-1])
186           while i < len(listeGeneaReverse[0:-1]) : 
187             mot=listeGeneaReverse[i]
188             i=i+1
189             if mot not in dicoTravail.keys(): dicoTravail[mot]={}
190             dicoTravail=dicoTravail[mot]
191           dicoTravail[simp]=self.dictSimp[simp]
192         
193       self.textePy=""
194       #print "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"
195       #print dicoParMC
196       #print "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"
197       listeMC=self.tri(dicoParMC.keys())
198       for k in listeMC :
199           #print "----------- traitement de " , k
200           #self.textePy += self.dicoFrancaisAnglais[k] + "("
201           self.textePy += str(k )+ "("
202           #self.traiteMC(dicoParMC[k])
203           self.textePy += ");\n"
204           #print "----------- " 
205            
206               
207       print self.textePy
208       return self.textePy 
209
210
211    #----------------------------------------
212    def traiteIdent(self,ident):
213    # enleve les espaces de part et autre
214    #----------------------------------------
215           while ident[-1] == " " or ident[-1] == '\t' : ident=ident[0:-1]
216           while ident[0]  == " " or ident[0]  == '\t' : ident=ident[1:]
217           return tr(ident)
218
219
220    def traiteMC(self,dico) :
221        from Accas import A_BLOC, A_FACT, A_SIMP
222        for k in dico.keys() :
223            valeur= dico[k]
224            if k not in self.dicoMC.keys() : kA=self.dicoFrancaisAnglais[k] 
225            else : kA=k
226            obj=self.dicoMC[kA]
227            if isinstance(obj,A_FACT.FACT):   self.convertFACT(obj,kA,valeur)
228            elif isinstance(obj,A_BLOC.BLOC): self.convertBLOC(obj,kA,valeur)
229            elif isinstance(obj,A_SIMP.SIMP): self.convertSIMP(obj,kA,valeur)
230            else : print "%%%%%%%%%%%\n", "pb conversion type pour", k, obj, "\n%%%%%%%%%%%"
231
232            #print "_____________"
233
234    def convertFACT(self,obj,nom,valeur):
235        if nom in TELEMACParser.__dict__.keys() : 
236           apply(TELEMACParser.__dict__[nom],(self,))
237           return
238        self.textePy +=  nom + "=_F( "
239        self.traiteMC(valeur)
240        self.textePy += '),\n'
241
242
243    def convertBLOC(self,obj,nom,valeur):
244        print "BLOC "
245        print nom
246
247    def convertSIMP(self,obj,nom,valeur):
248        if nom in ("PRESCRIBED_FLOWRATES", "PRESCRIBED_VELOCITIES", "PRESCRIBED_ELEVATIONS" ): return
249        if obj.max==1 : 
250           if hasattr(obj.type[0],'ntuple') : 
251              lval=[]
252              for v in valeur : 
253                try :    v=eval(v,{})
254                except : pass
255                lval.append(v)
256              self.textePy += nom + "=" + str(lval) +","
257              return
258           if 'TXM' in obj.type :
259
260               if pattern_ContientDouble.match(str(valeur)):
261                  valeur=re.sub("''","\'\'",str(valeur))
262                  self.textePy += nom + "=" + str(valeur) +","
263                  return
264               valeur=str(valeur)
265
266               # ceinture et bretelle si les re sont correctes -)
267               while valeur[-1] == " " or valeur[-1] == '\t' : valeur=valeur[0:-1]
268               while valeur[0]  == " " or valeur[0]  == '\t' : valeur=valeur[1:]
269
270
271
272           # Pour les enum
273           try    : valeur=eval(valeur,{})
274           except : pass
275           if nom in DicoEnumCasEn.keys(): 
276              try    : 
277                valeur=DicoEnumCasEn[nom][valeur]
278                self.textePy += nom + "= '" + str(valeur) +"',"
279                return
280              except : pass
281
282
283           if obj.into != [] and obj.into != None and not('R' in obj.type) and not('I' in obj.type):
284              for possible in obj.into :
285                 try :
286                   if possible.upper() == valeur.upper():
287                      valeur=possible
288                      break
289                   v=valeur[0].upper()+valeur[1:].lower()
290                   v2=tr(v)
291                   if possible.upper() == v2.upper():
292                      valeur=possible
293                      break
294                 except:
295                    print "pb avec le type de ", obj.nom, obj.type, 'et la valeur ', valeur
296
297           if 'Fichier' in obj.type or 'TXM' in obj.type or 'Repertoire' in obj.type :
298               valeur=str(valeur)
299               while valeur[-1] == " " : valeur=valeur[0:-1]
300               while valeur[0]  == " " : valeur=valeur[1:]
301               self.textePy += nom + "= '" + str(valeur) +"' ,"
302               return
303
304           if bool in obj.type :
305             if   valeur == True  :  self.textePy += nom + "= True,"
306             elif valeur == False :  self.textePy += nom + "= False,"
307             elif pattern_oui.match(valeur) : self.textePy += nom + "= True,"
308             elif pattern_non.match(valeur) : self.textePy += nom + "= False,"
309             else :  self.textePy += nom + "= None,"
310             return
311           self.textePy += nom + "=" + str(valeur) +","
312
313        else :
314           if pattern_listeVide.match(valeur) :
315              self.textePy += nom + "= None,"
316              return
317           while valeur[-1] == " " or  valeur[-1]=="'" : valeur=valeur[0:-1]
318           while valeur[0]  == " " or  valeur[-0]=="'" : valeur=valeur[1:]
319
320           if   ";" in valeur : valeur=valeur.split(';')
321           elif "," in valeur : valeur=valeur.split(',')
322
323           if valeur == None : return
324           newVal=[]
325           for v in valeur :
326             try :    v=eval(v,{})
327             except : pass
328             if nom in DicoEnumCasEn.keys():
329                #print "est dans le dico des enum, valeurs multiples"
330                try    : v=DicoEnumCasEn[nom][v]
331                except : pass
332             newVal.append(v)
333           self.textePy += nom + "=" + str(newVal) +","
334           
335
336
337    def tri(self, listeIn):
338       if len(listeIn) == 1 : return listeIn
339       if self.Ordre_Des_Commandes == None : return listeIn
340       #print self.Ordre_Des_Commandes
341       listeOut=[listeIn[0],]
342       for kF in listeIn[1:]:
343           k=str(self.dicoFrancaisAnglais[kF])
344           ordreK=self.Ordre_Des_Commandes.index(k)
345           i=0
346           while i < len(listeOut):
347              ordreI=self.Ordre_Des_Commandes.index(self.dicoFrancaisAnglais[listeOut[i]])
348              if ordreK < ordreI : break
349              i=i+1
350           listeOut.insert(i,kF)
351       return listeOut
352
353    def Processeurs_Paralleles(self):
354       #YOANN
355       if self.dictSimp["Processeurs_Paralleles"] == 0 : del  self.dictSimp["Processeurs_Paralleles"]
356       else : self.dictSimp["Parallel_Computation"]="Parallel"
357  
358    def decoupeListe(self,valeurs,label):
359       #print "decoupeListe"
360       #print valeurs
361       i=0
362       for prefixe in ('_U_And_V','_H'):
363           labelComplet=label+prefixe
364           valeur=valeurs[i]
365           try    : valeur=eval(valeur,{})
366           except : pass
367           if tr(label) in DicoEnumCasEn.keys(): 
368              try    : valeur=DicoEnumCasEn[tr(label)][valeur]
369              except : pass
370           self.dictSimp[labelComplet]=valeur
371           i=i+1
372       if len(valeurs)==2 : return
373       for prefixe in ('_K_And_Epsilon','_Tracers'):
374           labelComplet=label+prefixe
375           valeur=valeurs[i]
376           try    : valeur=eval(valeur,{})
377           except : pass
378           if tr(label) in DicoEnumCasEn.keys(): 
379              try    : valeur=DicoEnumCasEn[tr(label)][valeur]
380              except : pass
381           self.dictSimp[labelComplet]=valeur
382           i=i+1
383       
384    def Option_De_Supg(self):
385        #print "ds Option_De_Supg"
386        self.decoupeListe( self.dictSimp["Option_De_Supg"],"Option_De_Supg")
387        del self.dictSimp["Option_De_Supg"]
388
389    def Forme_De_La_Convection(self):
390        self.decoupeListe( self.dictSimp["Forme_De_La_Convection"],"Forme_De_La_Convection")
391        valeurs=self.dictSimp["Forme_De_La_Convection"]
392        del self.dictSimp["Forme_De_La_Convection"]
393        self.dictSimp['Convection_De_U_Et_V']=True
394        self.dictSimp['Convection_De_H']=True
395        if len(valeurs)==2 : return
396        self.dictSimp['Convection_De_K_Et_Epsilon']=True
397        self.dictSimp['Convection_Des_Traceurs']=True
398
399    def Discretisations_En_Espace(self):
400        self.decoupeListe( self.dictSimp["Discretisations_En_Espace"],"Discretisations_En_Espace")
401        del self.dictSimp["Discretisations_En_Espace"]
402        
403    def Date_De_L_Origine_Des_Temps (self):
404        valeurs=self.dictSimp["Date_De_L_Origine_Des_Temps"]
405        self.dictSimp['Annee']=valeurs[0]
406        self.dictSimp['Mois']=valeurs[1]
407        self.dictSimp['Jour']=valeurs[2]
408        del  self.dictSimp["Date_De_L_Origine_Des_Temps"]
409        
410    
411    def Heure_De_L_Origine_Des_Temps (self):
412        valeurs=self.dictSimp["Heure_De_L_Origine_Des_Temps"]
413        self.dictSimp['Heure']=valeurs[0]
414        self.dictSimp['Minute']=valeurs[1]
415        self.dictSimp['Seconde']=valeurs[2]
416        del  self.dictSimp["Heure_De_L_Origine_Des_Temps"]
417
418    def Liquid_Boundaries(self):
419        #print 'Liquid Boundaries'
420        texte_Boundaries="Liquid_Boundaries=( "
421        premier=0
422        if 'Prescribed_Elevations' in self.dictSimp.keys(): 
423            valeurs=self.dictSimp["Prescribed_Elevations"]
424        elif 'Cotes_Imposees' in self.dictSimp.keys(): 
425            valeurs=self.dictSimp["Cotes_Imposees"]
426        else : valeurs=()
427        #print valeurs
428        for e in range(len(valeurs)):
429           if valeurs[e] == "" or valeurs[e] == "\n" : continue
430           if eval(valeurs[e],{})==0 : continue
431           if not premier : premier=1
432           texte_Boundaries += "_F(Type_Condition = 'Prescribed Elevations',\n"
433           texte_Boundaries += "Prescribed_Elevations = " + str(valeurs[e]) + "),\n"
434                
435        if 'Prescribed_Flowrates' in self.dictSimp.keys(): 
436           valeurs=self.dictSimp["Prescribed_Flowrates"]
437        elif 'Debits_Imposes' in self.dictSimp.keys(): 
438           valeurs=self.dictSimp["Debits_Imposes"]
439        else : valeurs=()
440        #print valeurs
441        for e in range(len(valeurs)):
442           if valeurs[e] == "" or valeurs[e] == "\n" : continue
443           if eval(valeurs[e],{})==0 : continue
444           if not premier : premier=1
445           texte_Boundaries += "_F(Type_Condition = 'Prescribed Flowrates',\n"
446           texte_Boundaries += "Prescribed_Flowrates = " + str(valeurs[e]) + "),\n"
447                
448        if 'Prescribed_Velocity' in self.dictSimp.keys(): 
449            valeurs=self.dictSimp["Prescribed_Velocity"]
450        elif 'Vitesses_Imposees' in self.dictSimp.keys(): 
451            valeurs=self.dictSimp["Vitesses_Imposees"]
452        else : valeurs=()
453        #print valeurs
454        for e in range(len(valeurs)):
455           if valeurs[e] == "" or valeurs[e] == "\n" : continue
456           if eval(valeurs[e],{})==0 : continue
457           if not premier : premier=1
458           texte_Boundaries += "_F(Type_Condition = 'Prescribed Velocity',\n"
459           texte_Boundaries += "Prescribed_Velocity = " + str(valeurs[e]) + "),\n"
460        if premier :  texte_Boundaries +="),\n"
461        else : texte_Boundaries="" ; print "pb texte_Boundaries "
462        self.textePy += texte_Boundaries
463