Salome HOME
QString et ses amis
[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 pattern_tracers = re.compile(r"^\s*(NAMES OF TRACERS|NOMS DES TRACEURS).*")
33 pattern_commence_par_quote=re.compile(r'^\s*[\'"].*')
34
35 pattern_ligne=re.compile(r'^\s*(?P<ident>[^=:]*)\s*[:=]\s*(?P<reste>.*)$')
36
37 pattern_variables=re.compile (r"^\s*(?P<ident>VARIABLES POUR LES SORTIES GRAPHIQUES)\s*[:=]\s*(?P<valeur>\w(,\w)*)\s*(?P<reste>.*)$")
38
39 # Attention aux listes de flottants
40 pattern_liste=re.compile(r'^\s*(?P<valeur>[+-.\w]+(\s*;\s*[+-.\w]+)+)\s*(?P<reste>.*)$')
41 pattern_liste_texte=re.compile(r"^\s*(?P<valeur>('.*(';\s*)))+(?P<reste>.*)$")
42 pattern_flottant=re.compile(r'^\s*(?P<valeur>[+-]?((\d+(\.\d*)?)|(\.\d+))([dDeE][+-]?\d+)?)\s*(?P<reste>.*)$')
43 pattern_texteQuote  = re.compile (r"^\s*(?P<valeur>'[^']+(''[^']+)*')\s*(?P<reste>.*)$")
44 pattern_texteSimple = re.compile (r"(?P<valeur>(^|\s)\s*[\w\.-]+)\s*(?P<reste>.*)$")
45 pattern_texteVide   = re.compile (r"^\s*(?P<valeur>'')\s*(?P<reste>.*)$")
46
47 pattern_ContientDouble=re.compile (r"^.*''.*$")
48
49
50 # le pattern texte reconnait 
51 #nom1 nom 2 : ou = chaine entre ' 
52 # avec eventuellement  des quotes au milieu par exemple
53 # TITRE = 'TELEMAC 2D : GOUTTE D''EAU DANS UN BASSIN$'
54 # m.group("texte") va rendre 'TELEMAC 2D : GOUTTE D''EAU DANS UN BASSIN$' 
55
56
57 #Si le code n est pas Telemac
58 try :
59 #if 1 :
60    from aideAuxConvertisseurs import DicoEficasToCas, ListeSupprimeCasToEficas
61    from aideAuxConvertisseurs import ListeCalculCasToEficas, DicoAvecMajuscules
62    from enumDicoTelemac       import DicoEnumCasEn
63 except :
64    pass
65
66 from Extensions import localisation
67
68 from determine import monEnvQT5
69
70
71
72 def entryPoint():
73    """
74    Return a dictionary containing the description needed to load the plugin
75    """
76    return {
77           'name' : 'TELEMAC2',
78           'factory' : TELEMACParser
79           }
80
81 class TELEMACParser(PythonParser):
82    """
83    This converter works like PythonParser, except that it also initializes all
84    model variables to None in order to avoid Python syntax errors when loading
85    a file with a different or inexistent definition of variables.
86    """
87
88    def convert(self, outformat, appli=None):
89       from Accas import A_BLOC, A_FACT, A_SIMP
90       self.dicoCasToCata=appli.readercata.dicoCasToCata
91       self.dicoInverse=appli.readercata.dicoInverse
92       self.dicoMC=appli.readercata.dicoMC
93       self.Ordre_Des_Commandes=appli.readercata.Ordre_Des_Commandes
94    
95
96       #print self.dicoInverseFrancais
97       #text = PythonParser.convert(self, outformat, appli)
98       
99       text=""
100       self.dictSimp={}
101
102       # Traitement des noms des tracers qui peuvent etre sur plusieurs lignes
103       l_lignes_texte = string.split(self.text,'\n')
104       l_lignes=[]
105       i=0
106       while (i < len(l_lignes_texte)) :
107           ligne=l_lignes_texte[i]
108           i=i+1
109           if not(pattern_tracers.match(ligne)):
110              l_lignes.append(ligne)
111              continue
112           while (i < len(l_lignes_texte)):
113              ligne_complementaire=l_lignes_texte[i]
114              if not(pattern_commence_par_quote.match(ligne_complementaire)) :
115                 l_lignes.append(ligne)
116                 break
117              else : 
118                 ligne=ligne +ligne_complementaire
119                 i=i+1
120                 if i == len(l_lignes_texte):
121                    l_lignes.append(ligne)
122                    continue
123   
124
125       for ligne in l_lignes :
126           if pattern_comment_slash.match(ligne) : continue
127           if pattern_eta.match(ligne) : continue
128           if pattern_fin.match(ligne) : continue
129           if pattern_blanc.match(ligne) : continue
130  
131
132           finLigne=ligne
133           while finLigne != "" :
134               #print finLigne
135               if pattern_comment_slash.match(finLigne) : finLigne=""; continue
136               valeur=""
137               if pattern_variables.match(finLigne) :
138                  m=pattern_variables.match(finLigne)
139                  valeur=m.group('valeur')
140                  finLigne=m.group('reste')
141                  self.dictSimp[simp]=valeur
142                  continue
143
144               m=pattern_ligne.match(finLigne)
145               if m == None : 
146                  #print "________________________________________________"
147                  print 'pb avec ****', finLigne , '**** dans ', ligne
148                  #print "________________________________________________"
149                  break
150       
151               simpCas=self.traiteIdent(m.group('ident'))
152               if not simpCas : continue
153
154               finLigne=m.group('reste')
155               # attention, l ordre des if est important
156               if pattern_liste.match(finLigne) :
157                  m=pattern_liste.match(finLigne)
158               elif pattern_liste_texte.match(finLigne) :
159                  m=pattern_liste_texte.match(finLigne)
160               elif pattern_texteQuote.match(finLigne) :
161                  m=pattern_texteQuote.match(finLigne)
162               elif pattern_flottant.match(finLigne) : 
163                  m=pattern_flottant.match(finLigne)
164               elif pattern_texteVide.match(finLigne):
165                  m=pattern_texteVide.match(finLigne)
166               elif pattern_texteSimple.match(finLigne):
167                  m=pattern_texteSimple.match(finLigne)
168               else :
169                  #print "________________________________________________"
170                  print 'pb avec ****', finLigne , '**** dans ', ligne
171                  print "non match"
172                  #print "________________________________________________"
173                  break
174               
175
176               valeur=m.group('valeur')
177               if pattern_blanc.match(valeur) : valeur=None
178
179               if pattern_flottant.match(finLigne) : 
180                  valeur=re.sub("d","e",valeur)
181                  valeur=re.sub("D","E",valeur)
182
183               if pattern_liste.match(finLigne) or pattern_liste_texte.match(finLigne):
184                  valeur=valeur.split(";")
185
186
187               finLigne=m.group('reste')
188               self.dictSimp[simpCas]=valeur
189       
190       if 'TITLE' not in self.dictSimp.keys() :
191           import os
192           self.dictSimp['TITLE']=os.path.basename(self.filename)
193       
194       dicoParMC={}
195       for simp in self.dictSimp.keys():
196           if simp in TELEMACParser.__dict__.keys() : apply(TELEMACParser.__dict__[simp],(self,))
197
198       for simp in self.dictSimp.keys():
199           if simp in ListeSupprimeCasToEficas: continue
200           if simp not in self.dicoInverse.keys() : 
201              print "************"
202              print "pb avec dans dicoInverse", simp,'------'
203              print "************"
204              #print poum
205              continue
206           listeGenea=self.dicoInverse[simp]
207           listeGeneaReverse=[]
208           for (u,v) in listeGenea : 
209               if isinstance(v,A_BLOC.BLOC): continue
210               listeGeneaReverse.append(u)
211           listeGeneaReverse.reverse()
212           dicoTravail=dicoParMC
213           i=0
214           #print (listeGeneaReverse[0:-1])
215           while i < len(listeGeneaReverse[0:-1]) : 
216             mot=listeGeneaReverse[i]
217             i=i+1
218             if mot not in dicoTravail.keys(): dicoTravail[mot]={}
219             dicoTravail=dicoTravail[mot]
220           dicoTravail[simp]=self.dictSimp[simp]
221         
222       self.textePy=""
223       #print "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"
224       #print dicoParMC
225       #print "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"
226       listeMC=self.tri(dicoParMC.keys())
227       for k in listeMC :
228           #print "----------- traitement de " , k
229           self.textePy += str(k )+ "("
230           self.traiteMC(dicoParMC[k])
231           self.textePy += ");\n"
232           #print "----------- " 
233            
234               
235       print self.textePy
236       return self.textePy 
237
238
239    #----------------------------------------
240    def traiteIdent(self,ident):
241    # enleve les espaces de part et autre
242    #----------------------------------------
243           while ident[-1] == " " or ident[-1] == '\t' : ident=ident[0:-1]
244           while ident[0]  == " " or ident[0]  == '\t' : ident=ident[1:]
245           try : identCata=self.dicoCasToCata[ident]
246           except :  
247             print  "%%%%%%%%%%%\n", "pb conversion type pour", identCata
248             identCata=None
249           return identCata
250
251
252    def traiteMC(self,dico) :
253        from Accas import A_BLOC, A_FACT, A_SIMP
254        for k in dico.keys() :
255            valeur= dico[k]
256            if k not in self.dicoMC.keys() : kA=self.dicoFrancaisAnglais[k] 
257            else : kA=k
258            obj=self.dicoMC[kA]
259            if isinstance(obj,A_FACT.FACT):   self.convertFACT(obj,kA,valeur)
260            elif isinstance(obj,A_BLOC.BLOC): self.convertBLOC(obj,kA,valeur)
261            elif isinstance(obj,A_SIMP.SIMP): self.convertSIMP(obj,kA,valeur)
262            else : print "%%%%%%%%%%%\n", "pb conversion type pour", k, obj, "\n%%%%%%%%%%%"
263
264            #print "_____________"
265
266    def convertFACT(self,obj,nom,valeur):
267        print "convertFACT", nom,valeur
268        #if nom in TELEMACParser.__dict__.keys() : 
269        #   apply(TELEMACParser.__dict__[nom],(self,))
270        #   return
271        self.textePy +=  nom + "=_F( "
272        self.traiteMC(valeur)
273        self.textePy += '),\n'
274
275
276    def convertBLOC(self,obj,nom,valeur):
277        print "BLOC "
278        print nom
279
280    def convertSIMP(self,obj,nom,valeur):
281        print obj,nom,valeur
282        if nom in ("PRESCRIBED_FLOWRATES", "PRESCRIBED_VELOCITIES", "PRESCRIBED_ELEVATIONS" ): return
283        if obj.max==1 : 
284           if hasattr(obj.type[0],'ntuple') : 
285              lval=[]
286              for v in valeur : 
287                try :    v=eval(v,{})
288                except : pass
289                lval.append(v)
290              self.textePy += nom + "=" + str(lval) +","
291              return
292           if 'TXM' in obj.type :
293
294               if pattern_ContientDouble.match(str(valeur)):
295                  valeur=re.sub("''","\'\'",str(valeur))
296                  self.textePy += nom + "=" + str(valeur) +","
297                  return
298               valeur=str(valeur)
299
300               # ceinture et bretelle si les re sont correctes -)
301               while valeur[-1] == " " or valeur[-1] == '\t' : valeur=valeur[0:-1]
302               while valeur[0]  == " " or valeur[0]  == '\t' : valeur=valeur[1:]
303
304
305
306           # Pour les enum
307           try    : valeur=eval(valeur,{})
308           except : pass
309
310           if nom in DicoEnumCasEn.keys(): 
311              try    : 
312                valeur=DicoEnumCasEn[nom][valeur]
313                self.textePy += nom + "= '" + str(valeur) +"',"
314                return
315              except : pass
316
317
318           if obj.into != [] and obj.into != None and not('R' in obj.type) and not('I' in obj.type):
319              for possible in obj.into :
320                 try :
321                   if possible.upper() == valeur.upper():
322                      valeur=possible
323                      break
324                   v=valeur[0].upper()+valeur[1:].lower()
325                   v2=tr(v)
326                   if possible.upper() == v2.upper():
327                      valeur=possible
328                      break
329                 except:
330                    print "pb avec le type de ", obj.nom, obj.type, 'et la valeur ', valeur
331
332           if 'Fichier' in obj.type or 'TXM' in obj.type or 'Repertoire' in obj.type :
333               valeur=str(valeur)
334               while valeur[-1] == " " : valeur=valeur[0:-1]
335               while valeur[0]  == " " : valeur=valeur[1:]
336               self.textePy += nom + "= '" + str(valeur) +"' ,"
337               return
338
339           if bool in obj.type :
340             if   valeur == True  :  self.textePy += nom + "= True,"
341             elif valeur == False :  self.textePy += nom + "= False,"
342             elif pattern_oui.match(valeur) : self.textePy += nom + "= True,"
343             elif pattern_non.match(valeur) : self.textePy += nom + "= False,"
344             else :  self.textePy += nom + "= None,"
345             return
346           self.textePy += nom + "=" + str(valeur) +","
347
348        else :
349           if valeur == () or valeur ==[] or pattern_listeVide.match(str(valeur)) :
350              self.textePy += nom + "= None,"
351              return
352
353           # les 4 lignes suivantes sont probablement inutiles
354           while valeur[-1] == " " or  valeur[-1]=="'" : valeur=valeur[0:-1]
355           while valeur[0]  == " " or  valeur[-0]=="'" : valeur=valeur[1:]
356           if   ";" in valeur : valeur=valeur.split(';')
357           elif "," in valeur : valeur=valeur.split(',')
358
359  
360           if valeur == None : return
361           newVal=[]
362           for v in valeur :
363             try :    v=eval(v,{})
364             except : pass
365             if nom in DicoEnumCasEn.keys():
366                print "est dans le dico des enum, valeurs multiples"
367                try    : v=DicoEnumCasEn[nom][v]
368                except : pass
369             newVal.append(v)
370           self.textePy += nom + "=" + str(newVal) +","
371           
372
373
374    def tri(self, listeIn):
375       if len(listeIn) == 1 : return listeIn
376       if self.Ordre_Des_Commandes == None : return listeIn
377       print self.Ordre_Des_Commandes
378       print listeIn
379       listeOut=[listeIn[0],]
380       for kF in listeIn[1:]:
381           k=str(self.dicoFrancaisAnglais[kF])
382           ordreK=self.Ordre_Des_Commandes.index(k)
383           i=0
384           while i < len(listeOut):
385              ordreI=self.Ordre_Des_Commandes.index(self.dicoFrancaisAnglais[listeOut[i]])
386              if ordreK < ordreI : break
387              i=i+1
388           listeOut.insert(i,kF)
389       return listeOut
390
391    def PARALLEL_PROCESSORS(self):
392       #YOANN
393       if self.dictSimp["PARALLEL_PROCESSORS"] == 0 : del  self.dictSimp["PARALLEL_PROCESSORS"]
394       #else : self.dictSimp["Parallel_Computation"]="Parallel"
395  
396    def decoupeListe(self,valeurs,label):
397       #print "decoupeListe"
398       #print valeurs
399       i=0
400       for prefixe in ('_U_AND_V','_H'):
401           labelComplet=label+prefixe
402           valeur=valeurs[i]
403           try    : valeur=eval(valeur,{})
404           except : pass
405           if label in DicoEnumCasEn.keys(): 
406              try    : valeur=DicoEnumCasEn[label][valeur]
407              except : pass
408           self.dictSimp[labelComplet]=valeur
409           i=i+1
410       if len(valeurs)==2 : return
411       for prefixe in ('_K_AND_EPSILON','_TRACERS'):
412           labelComplet=label+prefixe
413           valeur=valeurs[i]
414           try    : valeur=eval(valeur,{})
415           except : pass
416           if label in DicoEnumCasEn.keys(): 
417              try    : valeur=DicoEnumCasEn[label][valeur]
418              except : pass
419           self.dictSimp[labelComplet]=valeur
420           i=i+1
421
422    def SUPG_OPTION(self):
423        #print "ds Option_De_Supg"
424        self.decoupeListe( self.dictSimp["SUPG_OPTION"],"SUPG_OPTION")
425        del self.dictSimp["SUPG_OPTION"]
426
427    def TYPE_OF_ADVECTION(self):
428        self.decoupeListe( self.dictSimp["TYPE_OF_ADVECTION"],"ADVECTION")
429        valeurs=self.dictSimp["TYPE_OF_ADVECTION"]
430        del self.dictSimp["TYPE_OF_ADVECTION"]
431        self.dictSimp['ADVECTION_OF_U_AND_V']=True
432        self.dictSimp['ADVECTION_OF_H']=True
433        if len(valeurs)==2 : return
434        self.dictSimp['ADVECTION_OF_K_AND_EPSILON']=True
435        self.dictSimp['ADVECTION_OF_TRACERS']=True
436
437    def DISCRETIZATIONS_IN_SPACE(self):
438        self.decoupeListe( self.dictSimp["DISCRETIZATIONS_IN_SPACE"],"DISCRETIZATIONS_IN_SPACE")
439        del self.dictSimp["Discretisations_En_Espace"]
440        
441    #def Date_De_L_Origine_Des_Temps (self):
442    #    valeurs=self.dictSimp["Date_De_L_Origine_Des_Temps"]
443    #    self.dictSimp['Annee']=valeurs[0]
444    #    self.dictSimp['Mois']=valeurs[1]
445    #    self.dictSimp['Jour']=valeurs[2]
446    #    del  self.dictSimp["Date_De_L_Origine_Des_Temps"]
447        
448    
449    #def ORIGINAL_HOUR_OF_TIME (self):
450    #    valeurs=self.dictSimp["ORIGINAL_HOUR_OF_TIME"]
451    #    self.dictSimp['Heure']=valeurs[0]
452    #    self.dictSimp['Minute']=valeurs[1]
453    #    self.dictSimp['Seconde']=valeurs[2]
454    #    del  self.dictSimp["ORIGINAL_HOUR_OF_TIME"]
455
456    def Liquid_Boundaries(self):
457        #print 'Liquid Boundaries'
458        texte_Boundaries="Liquid_Boundaries=( "
459        premier=0
460        if 'Prescribed_Elevations' in self.dictSimp.keys(): 
461            valeurs=self.dictSimp["Prescribed_Elevations"]
462        elif 'Cotes_Imposees' in self.dictSimp.keys(): 
463            valeurs=self.dictSimp["Cotes_Imposees"]
464        else : valeurs=()
465        #print valeurs
466        for e in range(len(valeurs)):
467           if valeurs[e] == "" or valeurs[e] == "\n" : continue
468           if eval(valeurs[e],{})==0 : continue
469           if not premier : premier=1
470           texte_Boundaries += "_F(Type_Condition = 'Prescribed Elevations',\n"
471           texte_Boundaries += "Prescribed_Elevations = " + str(valeurs[e]) + "),\n"
472                
473        if 'Prescribed_Flowrates' in self.dictSimp.keys(): 
474           valeurs=self.dictSimp["Prescribed_Flowrates"]
475        elif 'Debits_Imposes' in self.dictSimp.keys(): 
476           valeurs=self.dictSimp["Debits_Imposes"]
477        else : valeurs=()
478        #print valeurs
479        for e in range(len(valeurs)):
480           if valeurs[e] == "" or valeurs[e] == "\n" : continue
481           if eval(valeurs[e],{})==0 : continue
482           if not premier : premier=1
483           texte_Boundaries += "_F(Type_Condition = 'Prescribed Flowrates',\n"
484           texte_Boundaries += "Prescribed_Flowrates = " + str(valeurs[e]) + "),\n"
485                
486        if 'Prescribed_Velocity' in self.dictSimp.keys(): 
487            valeurs=self.dictSimp["Prescribed_Velocity"]
488        elif 'Vitesses_Imposees' in self.dictSimp.keys(): 
489            valeurs=self.dictSimp["Vitesses_Imposees"]
490        else : valeurs=()
491        #print valeurs
492        for e in range(len(valeurs)):
493           if valeurs[e] == "" or valeurs[e] == "\n" : continue
494           if eval(valeurs[e],{})==0 : continue
495           if not premier : premier=1
496           texte_Boundaries += "_F(Type_Condition = 'Prescribed Velocity',\n"
497           texte_Boundaries += "Prescribed_Velocity = " + str(valeurs[e]) + "),\n"
498        if premier :  texte_Boundaries +="),\n"
499        else : texte_Boundaries="" ; print "pb texte_Boundaries "
500        self.textePy += texte_Boundaries
501