Salome HOME
numero de version
[tools/eficas.git] / InterfaceQT4 / sauveTELEMAC.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_blanc = re.compile(r"^ *$")
31 pattern_OUI   = re.compile(r"^ *OUI *")
32 pattern_oui   = re.compile(r"^ *oui *")
33 pattern_NON   = re.compile(r"^ *NON *")
34 pattern_non   = re.compile(r"^ *non *")
35 pattern_vide  = re.compile(r"^ *$")
36 pattern_texte =re.compile(r"^[\w*'-]+[ *[\w*'-]* *]*[:=] *['](?P<texte>.*)[']")
37 # le pattern texte reconnait 
38 #nom1 nom 2 : ou = chaine entre ' 
39 # avec eventuellement  des quotes au milieu par exemple
40 # TITRE = 'TELEMAC 2D : GOUTTE D''EAU DANS UN BASSIN$'
41 # m.group("texte") va rendre 'TELEMAC 2D : GOUTTE D''EAU DANS UN BASSIN$' 
42
43
44 #Si le code n est pas Telemac
45 try :
46    from aideAuxConvertisseurs import DicoEficasToCas, ListeSupprimeCasToEficas
47    from aideAuxConvertisseurs import ListeCalculCasToEficas, DicoAvecMajuscules
48    from enumDicoTelemac2      import DicoEnumCasEn
49 except :
50    pass
51
52 from Extensions import localisation
53
54 from determine import monEnvQT5
55
56
57
58 def entryPoint():
59    """
60    Return a dictionary containing the description needed to load the plugin
61    """
62    return {
63           'name' : 'TELEMAC',
64           'factory' : TELEMACParser
65           }
66
67 class TELEMACParser(PythonParser):
68    """
69    This converter works like PythonParser, except that it also initializes all
70    model variables to None in order to avoid Python syntax errors when loading
71    a file with a different or inexistent definition of variables.
72    """
73
74    def convert(self, outformat, appli=None):
75       self.dicoInverseFrancais=appli.readercata.dicoInverseFrancais
76       self.dicoAnglaisFrancais=appli.readercata.dicoAnglaisFrancais
77       self.dicoFrancaisAnglais=appli.readercata.dicoFrancaisAnglais
78       self.dicoMC=appli.readercata.dicoMC
79       self.Ordre_Des_Commandes=appli.readercata.Ordre_Des_Commandes
80    
81
82       #print self.dicoInverseFrancais
83       #text = PythonParser.convert(self, outformat, appli)
84       
85       text=""
86       l_lignes = string.split(self.text,'\n')
87       self.dictSimp={}
88       lignesATraiter=[]
89       for ligne in l_lignes :
90           if pattern_comment_slash.match(ligne) : continue
91           if pattern_eta.match(ligne) : continue
92           if pattern_fin.match(ligne) : continue
93           if pattern_texte.match(ligne) : 
94             lignesATraiter.append(l)
95             continue
96       
97           for l in ligne.split('\t'):
98                 lignesATraiter.append(l)
99
100       for ligne in lignesATraiter :
101           if pattern_blanc.match(ligne) : continue
102           ligneInitiale=ligne
103
104           if pattern_texte.match(ligne) : 
105              self.traiteLigneTexte(ligne)
106              continue
107  
108
109           ligne=re.sub("'",' ',ligne)
110           ligne=re.sub(":",'=',ligne)
111           if ligne.count('=') != 1 :
112               print "pb avec la ligne " , ligne
113               continue 
114
115      
116           motsInLigne=string.split(ligne,' ')
117           listeMotsSimp=()
118           simp=""
119           for mot in motsInLigne:
120               if mot == ""   : continue
121               if mot == "="  :
122                  simp=simp[0:-1]
123                  while simp[-1] == " " : simp=simp[0:-1]
124                  if simp.find('-') > 0 : simp=self.redecoupeSimp(simp)
125                  break
126
127               mot=mot.replace('_','__')
128               simp=simp+mot[0].upper() +mot[1:].lower()+'_'
129           valeur=ligne.split('=')[1]
130           self.dictSimp[simp]=valeur
131
132       
133       
134       #print dictSimp
135       #print self.dicoInverseFrancais
136
137       dicoParMC={}
138       #print ListeCalculCasToEficas
139
140       print self.dictSimp.keys()
141       if 'Title' not in self.dictSimp.keys():
142           import os
143           self.dictSimp['Titre']=os.path.basename(self.filename)
144       
145       for simp in self.dictSimp.keys():
146           if simp in TELEMACParser.__dict__.keys() : apply(TELEMACParser.__dict__[simp],(self,))
147
148       for simp in self.dictSimp.keys():
149           if simp in ListeSupprimeCasToEficas: continue
150           if simp not in self.dicoInverseFrancais.keys() : 
151              print "************"
152              print "pb avec ", simp,'------'
153              print "************"
154              continue
155           listeGenea=self.dicoInverseFrancais[simp]
156           listeGeneaReverse=[]
157           for (u,v) in listeGenea : 
158               if isinstance(v,BLOC): continue
159               listeGeneaReverse.append(u)
160           listeGeneaReverse.reverse()
161           dicoTravail=dicoParMC
162           i=0
163           #print (listeGeneaReverse[0:-1])
164           while i < len(listeGeneaReverse[0:-1]) : 
165             mot=listeGeneaReverse[i]
166             i=i+1
167             if mot not in dicoTravail.keys(): dicoTravail[mot]={}
168             dicoTravail=dicoTravail[mot]
169           dicoTravail[simp]=self.dictSimp[simp]
170         
171       self.textePy=""
172       #print "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"
173       #print dicoParMC
174       #print "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"
175       listeMC=self.tri(dicoParMC.keys())
176       for k in listeMC :
177           #print "----------- traitement de " , k
178           self.textePy += self.dicoFrancaisAnglais[k] + "("
179           self.traiteMC(dicoParMC[k])
180           self.textePy += ");\n"
181           #print "----------- " 
182            
183               
184       print self.textePy
185       return self.textePy 
186
187    def traiteLigneTexte(self,ligne):
188         m=pattern_texte.match(ligne) 
189         valeur=m.group("texte")
190         ligne=ligne[0:ligne.find(valeur)]
191         ligne=re.sub("'",' ',ligne)
192         ligne=re.sub(":",'=',ligne)
193         motsInLigne=string.split(ligne,' ')
194         simp=""
195         for mot in motsInLigne:
196            if mot == ""   : continue
197            if mot == "="  :
198               simp=simp[0:-1]
199               while simp[-1] == " " : simp=simp[0:-1]
200               if simp.find('-') > 0 : simp=self.redecoupeSimp(simp)
201               break
202
203            mot=mot.replace('_','__')
204            simp=simp+mot[0].upper() +mot[1:].lower()+'_'
205         self.dictSimp[simp]=valeur
206
207    def traiteMC(self,dico) :
208        for k in dico.keys() :
209            valeur= dico[k]
210            if k not in self.dicoMC.keys() : kA=self.dicoFrancaisAnglais[k] 
211            else : kA=k
212            obj=self.dicoMC[kA]
213            if isinstance(obj,FACT):   self.generFACT(obj,kA,valeur)
214            elif isinstance(obj,BLOC): self.generBLOC(obj,kA,valeur)
215            elif isinstance(obj,SIMP): self.generSIMP(obj,kA,valeur)
216            else : print "%%%%%%%%%%%\n", "pb generation pour", k, obj, "\n%%%%%%%%%%%"
217
218            #print "_____________"
219
220    def generFACT(self,obj,nom,valeur):
221        if nom in TELEMACParser.__dict__.keys() : 
222           apply(TELEMACParser.__dict__[nom],(self,))
223           return
224        self.textePy +=  nom + "=_F( "
225        self.traiteMC(valeur)
226        self.textePy += '),\n'
227
228
229    def generBLOC(self,obj,nom,valeur):
230        print "BLOC "
231        print nom
232
233    def generSIMP(self,obj,nom,valeur):
234        if nom in ("Prescribed_Flowrates", "Prescribed_Velocities", "Prescribed_Elevations" ): return
235        if obj.max==1 : 
236           if 'TXM' in obj.type :
237               valeur=str(valeur)
238               while valeur[-1] == " " : valeur=valeur[0:-1]
239               while valeur[0]  == " " : valeur=valeur[1:]
240               valeur=valeur[0].upper()+valeur[1:].lower()
241               valeur=tr(valeur)
242           try    : valeur=eval(valeur,{})
243           except : pass
244           if nom in DicoEnumCasEn.keys(): 
245              try    : valeur=DicoEnumCasEn[nom][valeur]
246              except : pass
247           if 'Fichier' in obj.type or 'TXM' in obj.type or 'Repertoire' in obj.type :
248               valeur=str(valeur)
249               while valeur[-1] == " " : valeur=valeur[0:-1]
250               while valeur[0]  == " " : valeur=valeur[1:]
251               self.textePy += nom + "= '" + str(valeur) +"' ,"
252               return
253           if bool in obj.type :
254             if pattern_OUI.match(valeur) or  pattern_oui.match(valeur) : self.textePy += nom + "= True,"
255             if pattern_NON.match(valeur) or  pattern_non.match(valeur) : self.textePy += nom + "= False,"
256             return
257           self.textePy += nom + "=" + str(valeur) +","
258        else :
259           if pattern_vide.match(valeur) : return
260           while valeur[-1] == " " : valeur=valeur[0:-1]
261           while valeur[0]  == " " : valeur=valeur[1:]
262
263           if   ";" in valeur : valeur=valeur.split(';')
264           elif "," in valeur : valeur=valeur.split(',')
265
266           if valeur == None : return
267           newVal=[]
268           for v in valeur :
269             try :    v==eval(v,{})
270             except : pass
271             if nom in DicoEnumCasEn.keys():
272                try    : v=DicoEnumCasEn[nom][v]
273                except : pass
274             newVal.append(v)
275           self.textePy += nom + "=" + str(newVal) +","
276           
277
278
279    def tri(self, listeIn):
280       if len(listeIn) == 1 : return listeIn
281       if self.Ordre_Des_Commandes == None : return listeIn
282       #print self.Ordre_Des_Commandes
283       listeOut=[listeIn[0],]
284       for kF in listeIn[1:]:
285           k=str(self.dicoFrancaisAnglais[kF])
286           ordreK=self.Ordre_Des_Commandes.index(k)
287           i=0
288           while i < len(listeOut):
289              ordreI=self.Ordre_Des_Commandes.index(self.dicoFrancaisAnglais[listeOut[i]])
290              if ordreK < ordreI : break
291              i=i+1
292           listeOut.insert(i,kF)
293       return listeOut
294
295    def Processeurs_Paralleles(self):
296       #YOANN
297       if self.dictSimp["Processeurs_Paralleles"] == 0 : del  self.dictSimp["Processeurs_Paralleles"]
298       else : self.dictSimp["Parallel_Computation"]="Parallel"
299  
300    def decoupeSUPG(self,valeurs,label):
301       i=0
302       for prefixe in ('_U_And_V','_H'):
303           labelComplet=label+prefixe
304           self.dictSimp["labelComplet"]=valeurs[i]
305           i=i+1
306       if len(valeurs)==2 : return
307       for prefixe in ('_K_And_Epsilon','_Tracers'):
308           labelComplet=label+prefixe
309           self.dictSimp["labelComplet"]=valeurs[i]
310           i=i+1
311       
312    def Option_De_Supg(self):
313        print "ds Option_De_Supg"
314        self.decoupeSUPG( self.dictSimp["Option_De_Supg"],"Option_De_Supg")
315        del self.dictSimp["Option_De_Supg"]
316
317    def Forme_De_La_Convection(self):
318        self.decoupeSUPG( self.dictSimp["Forme_De_La_Convection"],"Forme_De_La_Convection")
319        del self.dictSimp["Forme_De_La_Convection"]
320
321    def redecoupeSimp(self,simp): 
322       # replace('-','_')  uniquement dans les identifiants
323       while simp.find('-') > 0 : 
324         ind=simp.find('-')
325         if ind==len(simp)-1 : break
326         simp=simp[0:ind]+'_'+simp[ind+1].upper()+simp[ind+2:]
327       return simp
328
329
330
331    def Liquid_Boundaries(self):
332        texte_Boundaries="Liquid_Boundaries=( "
333        premier=0
334        if 'Prescribed_Elevations' in self.dictSimp.keys(): 
335            valeurs=self.dictSimp["Prescribed_Elevations"].split(";")
336        elif 'Cotes_Imposees' in self.dictSimp.keys(): 
337            valeurs=self.dictSimp["Cotes_Imposees"].split(";")
338        else : valeurs=()
339        for e in range(len(valeurs)):
340           if valeurs[e] == "" or valeurs[e] == "\n" : continue
341           if eval(valeurs[e],{})==0 : continue
342           if not premier : premier=1
343           texte_Boundaries += "_F(Type_Condition = 'Prescribed Elevations',\n"
344           texte_Boundaries += "Prescribed_Elevations = " + str(valeurs[e]) + "),\n"
345                
346        if 'Prescribed_Flowrates' in self.dictSimp.keys(): 
347           valeurs=self.dictSimp["Prescribed_Flowrates"].split(";")
348        elif 'Debits_Imposes' in self.dictSimp.keys(): 
349           valeurs=self.dictSimp["Debits_Imposes"].split(";")
350        else : valeurs=()
351        for e in range(len(valeurs)):
352           if valeurs[e] == "" or valeurs[e] == "\n" : continue
353           if eval(valeurs[e],{})==0 : continue
354           if not premier : premier=1
355           texte_Boundaries += "_F(Type_Condition = 'Prescribed Flowrates',\n"
356           texte_Boundaries += "Prescribed_Flowrates = " + str(valeurs[e]) + "),\n"
357                
358        if 'Prescribed_Velocity' in self.dictSimp.keys(): 
359            valeurs=self.dictSimp["Prescribed_Velocity"].split(";")
360        elif 'Vitesses_Imposees' in self.dictSimp.keys(): 
361            valeurs=self.dictSimp["Vitesses_Imposees"].split(";")
362        else : valeurs=()
363        for e in range(len(valeurs)):
364           if valeurs[e] == "" or valeurs[e] == "\n" : continue
365           if eval(valeurs[e],{})==0 : continue
366           if not premier : premier=1
367           texte_Boundaries += "_F(Type_Condition = 'Prescribed Velocity',\n"
368           texte_Boundaries += "Prescribed_Velocity = " + str(valeurs[e]) + "),\n"
369        if premier :  texte_Boundaries +="),\n"
370        else : texte_Boundaries="" ; print "pb texte_Boundaries "
371        self.textePy += texte_Boundaries
372