Salome HOME
exceptions prints
[tools/eficas.git] / generator / generator_TELEMAC.py
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2007-2013   EDF R&D
3 #
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License.
8 #
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 # Lesser General Public License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 #
18 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 #
20 """Ce module contient le plugin generateur de fichier au format  Code_Carmel3D pour EFICAS.
21 """
22
23 import traceback
24 import types,string,re,os
25 from Extensions.i18n import tr
26 from generator_python import PythonGenerator
27
28 extensions=('.comm',)
29 #if 1:
30 try :
31    from enumDicoTelemac       import TelemacdicoEn
32    DicoEnumCasEnInverse={}
33    for motClef in TelemacdicoEn.keys():
34      d={}
35      for valTelemac in TelemacdicoEn[motClef].keys():
36         valEficas= TelemacdicoEn[motClef][valTelemac]
37         d[valEficas]=valTelemac
38      DicoEnumCasEnInverse[motClef]=d
39
40 except :
41  pass
42
43
44 def entryPoint():
45    """
46       Retourne les informations necessaires pour le chargeur de plugins
47       Ces informations sont retournees dans un dictionnaire
48    """
49    return {
50         # Le nom du plugin
51           'name' : 'TELEMAC',
52         # La factory pour creer une instance du plugin
53           'factory' : TELEMACGenerator,
54           }
55
56
57 class TELEMACGenerator(PythonGenerator):
58    """
59       Ce generateur parcourt un objet de type JDC et produit
60       un texte au format eficas et 
61       un texte au format dictionnaire
62
63    """
64
65 #----------------------------------------------------------------------------------------
66    def gener(self,obj,format='brut',config=None,appli=None,statut="Entier"):
67        
68       self.statut=statut
69       self.langue=appli.langue
70       self.initDico()
71       # Pour Simplifier les verifs d ecriture
72       if hasattr(appli,'listeTelemac') : self.listeTelemac=appli.listeTelemac
73       else : self.listeTelemac = ()
74
75       self.dicoCataToCas={}
76       self.dicoCasToCata=appli.readercata.dicoCasToCata
77       for motClef in self.dicoCasToCata.keys():
78            self.dicoCataToCas[self.dicoCasToCata[motClef]]=motClef
79
80
81
82       # Cette instruction genere le contenu du fichier de commandes (persistance)
83       self.text=PythonGenerator.gener(self,obj,format)
84       return self.text
85
86
87 #----------------------------------------------------------------------------------------
88 # initialisations
89 #----------------------------------------------------------------------------------------
90    
91    def initDico(self) :
92  
93       self.PE=False
94       self.FE=False
95       self.VE=False
96       if self.langue == "fr" :
97         self.textPE = 'COTES IMPOSEES :'
98         self.textFE = 'DEBITS IMPOSES :'
99         self.textVE = 'VITESSES IMPOSEES :'
100       else :
101         self.textPE = 'PRESCRIBED ELEVATIONS :'
102         self.textFE = 'PRESCRIBED FLOWRATES :'
103         self.textVE = 'PRESCRIBED VELOCITIES :'
104       self.nbTracers = 0
105       self.texteDico = ""
106  
107
108
109
110 #----------------------------------------------------------------------------------------
111 # ecriture de tout
112 #----------------------------------------------------------------------------------------
113
114    def writeDefault(self,fn) :
115        self.texteDico+='\n&ETA\n&FIN\n'
116        if self.statut == 'Leger' : extension = ".Lcas"
117        else                      : extension = ".cas"
118        fileDico = fn[:fn.rfind(".")] + extension 
119        f = open( str(fileDico), 'wb')
120        f.write( self.texteDico )
121        f.close()
122
123 #----------------------------------------------------------------------------------------
124 # ecriture de Leger
125 #----------------------------------------------------------------------------------------
126
127    def writeLeger(self,fn,jdc,config,appli) :
128        jdc_formate=self.gener(jdc,config=config,appli=appli,statut="Leger")
129        self.writeDefault(fn) 
130
131
132 #----------------------------------------------------------------------------------------
133 #  analyse de chaque noeud de l'arbre 
134 #----------------------------------------------------------------------------------------
135
136    def generPROC_ETAPE(self,obj):
137         self.texteDico += '/------------------------------------------------------/\n'
138         self.texteDico += '/\t\t\t'+obj.nom +'\n'
139         self.texteDico += '/------------------------------------------------------/\n'
140         s=PythonGenerator.generPROC_ETAPE(self,obj)
141         if obj.nom in TELEMACGenerator.__dict__.keys() : apply(TELEMACGenerator.__dict__[obj.nom],(self,obj))
142         
143         return s
144
145    def generMCSIMP(self,obj) :
146         """recuperation de l objet MCSIMP"""
147         s=PythonGenerator.generMCSIMP(self,obj)
148
149        
150         # Attention pas sur --> ds certains cas non traite par MCFACT ?
151         # a reflechir avec Yoann 
152         # ajouter le statut ?
153         if self.statut == 'Leger' :
154           if hasattr(obj.definition,'defaut') and (obj.definition.defaut == obj.valeur) and (obj.nom not in self.listeTelemac) : return s
155           if hasattr(obj.definition,'defaut') and obj.definition.defaut != None and (type(obj.valeur) == types.TupleType or type(obj.valeur) == types.ListType) and (tuple(obj.definition.defaut) == tuple(obj.valeur)) and (obj.nom not in self.listeTelemac) : return s
156  
157
158         #nomMajuscule=obj.nom.upper()
159         #nom=nomMajuscule.replace('_',' ') 
160         #if nom in listeSupprime or s == "" : return s
161         if s == "" : return s
162
163       
164        
165         sTelemac=s[0:-1]
166         if not( type(obj.valeur) in (types.TupleType,types.ListType) ):
167            if obj.nom in DicoEnumCasEnInverse.keys():  
168              try : sTelemac=str(DicoEnumCasEnInverse[obj.nom][obj.valeur])
169              except : print ("generMCSIMP Pb valeur avec ", obj.nom, obj.valeur)
170         if type(obj.valeur) in (types.TupleType,types.ListType) :
171            if obj.nom in DicoEnumCasEnInverse.keys():  
172              #sT = "'"
173              sT=''
174              for v in obj.valeur:
175                try : sT +=str(DicoEnumCasEnInverse[obj.nom][v]) +";"
176                except : print ("generMCSIMP Pb Tuple avec ", obj.nom, v, obj.valeur)
177              #sTelemac=sT[0:-1]+"'"
178              sTelemac=sT[0:-1]
179            else  :
180              sTelemac=sTelemac[0:-1]
181              if sTelemac.find("'") > 0 :
182                 sTelemac= sTelemac.replace (',',';\n    ') 
183
184
185         if self.langue=='fr' :
186            s1=str(sTelemac).replace('True','OUI')
187            s2=s1.replace('False','NON')
188         else :
189            s1=str(sTelemac).replace('True','YES')
190            s2=s1.replace('False','NO')
191         s3=s2.replace(',',';')
192         if s3 != "" and s3[0]=='(' : 
193           try : s3=s3[1:-1] # cas de liste vide
194           except : s3 = ' '
195         
196        
197         # LIQUID_BOUNDARIES
198         if obj.nom in ('PRESCRIBED_FLOWRATES','PRESCRIBED_VELOCITIES','PRESCRIBED_ELEVATIONS') :
199            return s
200
201         if obj.nom not in self.dicoCataToCas :
202            if obj.nom == 'Consigne' : return ""
203            return s
204
205         nom=self.dicoCataToCas[obj.nom]
206         if nom == "VARIABLES FOR GRAPHIC PRINTOUTS" : s3=s3.replace(';',',')
207         if nom == "VARIABLES POUR LES SORTIES GRAPHIQUES" : s3=s3.replace(';',',')
208         if s3 == "" or s3 == " " : s3 = "None"
209         ligne=nom+ " : " + s3 + "\n"
210         if len(ligne) > 72 : ligne=self.redecoupeLigne(nom,s3) 
211         self.texteDico+=ligne
212
213    def generMCFACT(self,obj):
214       """
215       """
216       s=PythonGenerator.generMCFACT(self,obj)
217       if obj.nom in TELEMACGenerator.__dict__.keys() : apply(TELEMACGenerator.__dict__[obj.nom],(self,obj))
218  
219       return s
220
221   
222    def LIQUID_BOUNDARIES(self,obj):
223       if 'BOUNDARY_TYPE' in  obj.liste_mc_presents() :
224           objForme=obj.get_child('BOUNDARY_TYPE')
225           valForme=objForme.valeur
226           if valForme == None : return
227
228           nomBloc='b_'+valForme.split(" ")[1] 
229           if nomBloc in  obj.liste_mc_presents() :
230              objBloc=obj.get_child(nomBloc)
231              objValeur=objBloc.get_child(objBloc.liste_mc_presents()[0])
232              valeur=objValeur.valeur
233              if valeur== None : valeur="0."
234           if valForme == 'Prescribed Elevations' :
235               self.PE=True
236               self.textPE += str(valeur) +"; "
237           else : self.textPE += "0.; "
238           if valForme == 'Prescribed Flowrates' :
239               self.FE=True
240               self.textFE += str(valeur) +"; "
241           else : self.textFE += "0.; "
242           if valForme == 'Prescribed Velocity'  :
243               self.VE=True
244               self.textVE += str(valeur) +"; "
245           else : self.textVE += "0.; "
246
247    def BOUNDARY_CONDITIONS(self,obj):
248        # sans '; '
249        if self.FE :  self.texteDico += self.textFE[0:-2]+'\n' 
250        if self.PE :  self.texteDico += self.textPE[0:-2]+'\n' 
251        if self.VE :  self.texteDico += self.textVE[0:-2]+'\n' 
252
253    def TRACERS(self,obj):
254        if self.nbTracers != 0 :  self.texteDico += 'NUMBER_OF_TRACERS : '+str(self.nbTracers) + '\n'
255  
256
257    def NAME_OF_TRACER(self,obj):
258        print (dir(obj) )
259        print (obj.get_genealogie_precise())
260
261    def Validation(self,obj):
262        self.texteDico += "VALIDATION : True \n"
263  
264    def Date_De_L_Origine_Des_Temps (self,obj):
265        an=obj.get_child('Year').valeur
266        mois=obj.get_child('Month').valeur
267        jour=obj.get_child('Day').valeur
268        self.texteDico += "ORIGINAL DATE OF TIME  :"+ str(an)+ " ,"+str(mois)+ "," +str(jour)+ "\n"
269
270    def Original_Hour_Of_Time (self,obj):
271        hh=obj.get_child('Hour').valeur
272        mm=obj.get_child('Minute').valeur
273        ss=obj.get_child('Second').valeur
274        self.texteDico += "ORIGINAL HOUR OF TIME :"+str(hh)+" ,"+str(mm)+ ","+str(ss)+"\n"
275
276    def Type_Of_Advection(self,obj):
277        listeAdvection=[1,5,1,1]
278        listeSupg=[2,2,2,2]
279        listeUpwind=[1.,1.,1.,1.]
280        self.listeMCAdvection=[]
281        self.chercheChildren(obj)
282        dicoSuf={ 'U_And_V' : 0, 'H' : 1, 'K_And_Epsilon' : 2, 'Tracers' : 3}
283        for c in  self.listeMCAdvection:
284            if c.nom[0:18] == 'Type_Of_Advection_' and c.valeur!=None:
285               suf=c.nom[18:]
286               index=dicoSuf[suf]
287               listeAdvection[index]=DicoEnumCasEnInverse['Type_Of_Advection'][c.valeur]
288            if c.nom[0:13] == 'Supg_Option_' and c.valeur!=None:
289               suf=c.nom[13:]
290               index=dicoSuf[suf]
291               listeAdvection[index]=DicoEnumCasEnInverse['Supg_Option'][c.valeur]
292            if c.nom[0:23] == 'Upwind_Coefficients_Of_' and c.valeur!=None:
293               suf=c.nom[23:]
294               index=dicoSuf[suf]
295               listeUpwind[index]=c.valeur
296        self.texteDico += "TYPE OF ADVECTION = "+ str(listeAdvection) + "\n"
297        self.texteDico += "SUPG OPTION = "+ str(listeSupg) + "\n"
298        self.texteDico += "UPWIND COEFFICIENTS = "+ str(listeUpwind) + "\n"
299        
300    def chercheChildren(self,obj):
301        for c in obj.liste_mc_presents():
302            objc=obj.get_child(c)
303            if hasattr(objc,'liste_mc_presents') and objc.liste_mc_presents() != [] : self.chercheChildren(objc)
304            else : self.listeMCAdvection.append(objc)
305
306       
307  
308    def redecoupeLigne(self,nom,valeur) :
309        text=nom+ " : \n"
310        valeur=valeur
311        if valeur.find("'") > -1:
312           lval=valeur.split(";")
313           for v in lval : text+='   '+v+';'
314           text=text[0:-1]+'\n'
315        else :
316          lval=valeur.split(";")
317          ligne="   "
318          for v in lval :
319            if len(ligne) < 70 : ligne += str(v)+'; '
320            else :
321               text+= ligne+"\n"
322               ligne="   "+str(v)+'; '
323          text+= ligne[0:-2]+'\n'
324        return text