Salome HOME
Updates for Telemac
[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 from __future__ import absolute_import
24 from __future__ import print_function
25 try :
26    from builtins import str
27 except : pass
28
29 import traceback
30 import types,re,os
31 from Extensions.i18n import tr
32 from .generator_python import PythonGenerator
33
34 extensions=('.comm',)
35
36
37
38
39 def entryPoint():
40    """
41       Retourne les informations necessaires pour le chargeur de plugins
42       Ces informations sont retournees dans un dictionnaire
43    """
44    return {
45         # Le nom du plugin
46           'name' : 'TELEMAC',
47         # La factory pour creer une instance du plugin
48           'factory' : TELEMACGenerator,
49           }
50
51
52 class TELEMACGenerator(PythonGenerator):
53    """
54       Ce generateur parcourt un objet de type JDC et produit
55       un texte au format eficas et
56       un texte au format dictionnaire
57
58    """
59
60 #----------------------------------------------------------------------------------------
61    def gener(self,obj,format='brut',config=None,appli=None,statut="Leger"):
62
63       self.statut        = statut
64       self.langue        = appli.langue
65       try : self.TelemacdicoEn = appli.readercata.TelemacdicoEn
66       except :
67         print ('Attention : pas de TelemacdicoEn declare')
68         self.TelemacdicoEn = {}
69       self.DicoEnumCasEnInverse = {}
70       #from enum_Telemac2d_auto       import self.TelemacdicoEn
71       for motClef in self.TelemacdicoEn:
72           d={}
73           for valTelemac in self.TelemacdicoEn[motClef]:
74              valEficas   = self.TelemacdicoEn[motClef][valTelemac]
75              d[valEficas] =valTelemac
76           self.DicoEnumCasEnInverse[motClef]=d
77       if self.langue == 'fr' :
78          #from  enum_Telemac2d_auto import DicoEnumCasFrToEnumCasEn
79          self.DicoEnumCasFrToEnumCasEn = appli.readercata.DicoEnumCasFrToEnumCasEn
80          for motClef in self.DicoEnumCasFrToEnumCasEn:
81               d={}
82               for valTelemac in self.DicoEnumCasFrToEnumCasEn[motClef]:
83                  valEficas    = self.DicoEnumCasFrToEnumCasEn[motClef][valTelemac]
84                  d[valEficas] = valTelemac
85               self.DicoEnumCasEnInverse[motClef]=d
86       self.initDico()
87       # Pour Simplifier les verifs d ecriture
88       if hasattr(appli,'listeTelemac') : self.listeTelemac=appli.listeTelemac
89       else : self.listeTelemac = ()
90
91       self.dicoCataToCas={}
92       try :
93         self.dicoCasToCata=appli.readercata.dicoCasToCata
94       except :
95         print ('Attention pas de dicoCasToCata declare')
96         self.dicoCasToCata={}
97         self.dicoCataToCas={}
98       for motClef in self.dicoCasToCata:
99            self.dicoCataToCas[self.dicoCasToCata[motClef]]=motClef
100
101
102
103       # Cette instruction genere le contenu du fichier de commandes (persistance)
104       self.text=PythonGenerator.gener(self,obj,format)
105       return self.text
106
107
108 #----------------------------------------------------------------------------------------
109 # initialisations
110 #----------------------------------------------------------------------------------------
111
112    def initDico(self) :
113
114       self.PE=False
115       self.FE=False
116       self.VE=False
117       self.commentaireAvant = False
118       self.texteCom=''
119       if self.langue == "fr" :
120         self.textPE = 'COTES IMPOSEES :'
121         self.textFE = 'DEBITS IMPOSES :'
122         self.textVE = 'VITESSES IMPOSEES :'
123       else :
124         self.textPE = 'PRESCRIBED ELEVATIONS :'
125         self.textFE = 'PRESCRIBED FLOWRATES :'
126         self.textVE = 'PRESCRIBED VELOCITIES :'
127       self.nbTracers = 0
128       self.texteDico = ""
129
130
131
132
133 #----------------------------------------------------------------------------------------
134 # ecriture de tout
135 #----------------------------------------------------------------------------------------
136
137    def writeDefault(self,fn) :
138        self.texteDico+='&ETA\n'
139        #if self.statut == 'Leger' : extension = ".Lcas"
140        #else                      : extension = ".cas"
141        extension=".cas"
142        fileDico = fn[:fn.rfind(".")] + extension
143        f = open( str(fileDico), 'w')
144        f.write( self.texteDico )
145        f.close()
146
147 #----------------------------------------------------------------------------------------
148 # ecriture de Leger
149 #----------------------------------------------------------------------------------------
150
151    def writeComplet(self,fn,jdc,config,appli) :
152        jdc_formate=self.gener(jdc,config=config,appli=appli,statut="Entier")
153        self.writeDefault(fn)
154
155
156 #----------------------------------------------------------------------------------------
157 #  analyse de chaque noeud de l'arbre
158 #----------------------------------------------------------------------------------------
159
160    def generPROC_ETAPE(self,obj):
161         if  not self.commentaireAvant or self.texteCom.find(obj.nom) < 0:
162             self.texteDico += '/------------------------------------------------------------------/\n'
163             self.texteDico += '/\t\t\t'+obj.nom +'\n'
164             self.texteDico += '/------------------------------------------------------------------/\n'
165         self.commentaireAvant = False
166         self.texteCom=''
167         s=PythonGenerator.generPROC_ETAPE(self,obj)
168         if obj.nom in TELEMACGenerator.__dict__ : TELEMACGenerator.__dict__[obj.nom](*(self,obj))
169
170         return s
171
172    def generMCSIMP(self,obj) :
173         """recuperation de l objet MCSIMP"""
174         s=PythonGenerator.generMCSIMP(self,obj)
175
176
177         # Attention pas sur --> ds certains cas non traite par MCFACT ?
178         # a reflechir avec Yoann
179         # ajouter le statut ?
180         if self.statut == 'Leger' :
181           if hasattr(obj.definition,'defaut') and (obj.definition.defaut == obj.valeur) and (obj.nom not in self.listeTelemac) : return s
182           if hasattr(obj.definition,'defaut') and obj.definition.defaut != None and (type(obj.valeur) == tuple or type(obj.valeur) == list) and (tuple(obj.definition.defaut) == tuple(obj.valeur)) and (obj.nom not in self.listeTelemac) : return s
183
184
185         #nomMajuscule=obj.nom.upper()
186         #nom=nomMajuscule.replace('_',' ')
187         #if nom in listeSupprime or s == "" : return s
188         if s == "None," : s=None
189         if s == "" or s==None : return s
190
191         sTelemac=s[0:-1]
192         if not( type(obj.valeur) in (tuple,list) ):
193            if obj.nom in self.DicoEnumCasEnInverse:
194              try : sTelemac=str(self.DicoEnumCasEnInverse[obj.nom][obj.valeur])
195              except :
196                if obj.valeur==None :  sTelemac=obj.valeur
197                else : print(("generMCSIMP Pb valeur avec ", obj.nom, obj.valeur))
198              # Si le resultat est du texte on ajoute des guillemets
199              if sTelemac[0] not in '0123456789':
200                sTelemac = "'" + sTelemac +"'"
201
202         if type(obj.valeur) in (tuple,list) :
203            if obj.nom in self.DicoEnumCasEnInverse:
204              #sT = "'"
205              sT=''
206              for v in obj.valeur:
207                try : sT +=str(self.DicoEnumCasEnInverse[obj.nom][v]) +";"
208                except :
209                  if obj.definition.intoSug != [] : sT +=str(v) + ";"
210                  else : print(("generMCSIMP Pb Tuple avec ", obj.nom, v, obj.valeur))
211              #sTelemac=sT[0:-1]+"'"
212              sTelemac=sT[0:-1]
213            else  :
214              sTelemac=sTelemac[0:-1]
215              if sTelemac.find("'") > 0 :
216                 sTelemac= sTelemac.replace (',',';\n    ')
217                 # on enleve le dernier  ';'
218                 index=(sTelemac.rfind(";"))
219                 sTelemac=sTelemac[:index]+' '+sTelemac[index+1:]
220
221         if self.langue=='fr' :
222            s1=str(sTelemac).replace('True','OUI')
223            s2=s1.replace('False','NON')
224         else :
225            s1=str(sTelemac).replace('True','YES')
226            s2=s1.replace('False','NO')
227         if hasattr(obj.definition,'max'):
228            if obj.definition.max != 1:
229               s3=s2.replace(',',';')
230            else:
231               s3=s2
232         if s3 != "" and s3[0]=='(' :
233           try : s3=s3[1:-1] # cas de liste vide
234           except : s3 = ' '
235
236
237         # LIQUID_BOUNDARIES
238         #if obj.nom in ('PRESCRIBED_FLOWRATES','PRESCRIBED_VELOCITIES','PRESCRIBED_ELEVATIONS') :
239         #   return s
240
241         # cas des Tuples
242         if obj.waitTuple()  and s3 != '' and s3  != 'None':
243            s3=s
244            if s3[-1] == ',': s3=s3[:-1]
245
246
247         if obj.nom not in self.dicoCataToCas :
248            if obj.nom == 'Consigne' : return ""
249            return s
250
251         nom=self.dicoCataToCas[obj.nom]
252         if nom in ["VARIABLES FOR GRAPHIC PRINTOUTS", "VARIABLES POUR LES SORTIES GRAPHIQUES",
253                    "VARIABLES TO BE PRINTED","VARIABLES A IMPRIMER",
254                    "VARIABLES FOR 3D GRAPHIC PRINTOUTS", "VARIABLES POUR LES SORTIES GRAPHIQUES 3D",
255                    "VARIABLES POUR LES SORTIES GRAPHIQUES 2D", "VARIABLES FOR 2D GRAPHIC PRINTOUTS",
256                    "C_VSM_PRINTOUT_SELECTION"]:
257               if s3 != '' and s3  != 'None':
258                 s3=s3.replace(';',',')
259                 s3="'"+ s3 +"'"
260               else:
261                 s3 = "''"
262         if nom in ["COUPLING WITH", "COUPLAGE AVEC"]:
263             s3 = s3.strip().replace("\n","")\
264                            .replace(" ", "")\
265                            .replace("\t", "")\
266                            .replace("';'", ",")
267         if s3 == "" or s3 == " " : s3 = " "
268         ligne=nom+ " : " + s3 + "\n"
269         if len(ligne) > 72 : ligne=self.redecoupeLigne(nom,s3)
270         self.texteDico+=ligne
271
272    def generMCFACT(self,obj):
273       """
274       """
275       s=PythonGenerator.generMCFACT(self,obj)
276       if obj.nom in TELEMACGenerator.__dict__ : TELEMACGenerator.__dict__[obj.nom](self,obj)
277
278       return s
279
280
281    def TRACERS(self,obj):
282        if self.nbTracers != 0 :  self.texteDico += 'NUMBER_OF_TRACERS : '+str(self.nbTracers) + '\n'
283
284
285    def NAME_OF_TRACER(self,obj):
286        print((dir(obj) ))
287        print((obj.getGenealogiePrecise()))
288
289    def Validation(self,obj):
290        self.texteDico += "VALIDATION : True \n"
291
292    def Date_De_L_Origine_Des_Temps (self,obj):
293        an=obj.getChild('Year').valeur
294        mois=obj.getChild('Month').valeur
295        jour=obj.getChild('Day').valeur
296        self.texteDico += "ORIGINAL DATE OF TIME  :"+ str(an)+ " ,"+str(mois)+ "," +str(jour)+ "\n"
297
298    def Original_Hour_Of_Time (self,obj):
299        hh=obj.getChild('Hour').valeur
300        mm=obj.getChild('Minute').valeur
301        ss=obj.getChild('Second').valeur
302        self.texteDico += "ORIGINAL HOUR OF TIME :"+str(hh)+" ,"+str(mm)+ ","+str(ss)+"\n"
303
304    def Type_Of_Advection(self,obj):
305        listeAdvection=[1,5,1,1]
306        listeSupg=[2,2,2,2]
307        listeUpwind=[1.,1.,1.,1.]
308        self.listeMCAdvection=[]
309        self.chercheChildren(obj)
310        dicoSuf={ 'U_And_V' : 0, 'H' : 1, 'K_And_Epsilon' : 2, 'Tracers' : 3}
311        for c in  self.listeMCAdvection:
312            if c.nom[0:18] == 'Type_Of_Advection_' and c.valeur!=None:
313               suf=c.nom[18:]
314               index=dicoSuf[suf]
315               listeAdvection[index]=self.DicoEnumCasEnInverse['Type_Of_Advection'][c.valeur]
316            if c.nom[0:13] == 'Supg_Option_' and c.valeur!=None:
317               suf=c.nom[13:]
318               index=dicoSuf[suf]
319               listeAdvection[index]=self.DicoEnumCasEnInverse['Supg_Option'][c.valeur]
320            if c.nom[0:23] == 'Upwind_Coefficients_Of_' and c.valeur!=None:
321               suf=c.nom[23:]
322               index=dicoSuf[suf]
323               listeUpwind[index]=c.valeur
324        self.texteDico += "TYPE OF ADVECTION = "+ str(listeAdvection) + "\n"
325        self.texteDico += "SUPG OPTION = "+ str(listeSupg) + "\n"
326        self.texteDico += "UPWIND COEFFICIENTS = "+ str(listeUpwind) + "\n"
327
328    def chercheChildren(self,obj):
329        for c in obj.listeMcPresents():
330            objc=obj.getChild(c)
331            if hasattr(objc,'listeMcPresents') and objc.listeMcPresents() != [] : self.chercheChildren(objc)
332            else : self.listeMCAdvection.append(objc)
333
334
335
336    def redecoupeLigne(self,nom,valeur) :
337        text=nom+ " : \n"
338        valeur=valeur
339        if valeur.find("'") > -1:
340           lval=valeur.split(";")
341           for v in lval : text+='   '+v+';'
342           text=text[0:-1]+'\n'
343        else :
344          lval=valeur.split(";")
345          ligne="   "
346          for v in lval :
347            if len(ligne+ str(v)+'; ') < 70 : ligne += str(v)+'; '
348            else :
349               text+= ligne+"\n"
350               ligne="   "+str(v)+'; '
351          text+= ligne[0:-2]+'\n'
352        return text
353
354    def generCOMMENTAIRE(self,obj):
355        sans_saut = re.sub("\n$","",obj.valeur)
356        l_lignes = sans_saut.split('\n')
357        txt='/'+66*'-'+'/'+'\n'
358        i=1
359        for ligne in l_lignes:
360          self.texteCom+=ligne+'\n'
361          txt = txt + '/'+ligne+'\n'
362        txt= txt + '/'+66*'-'+'/'+'\n'
363        self.texteDico += txt
364        self.commentaireAvant= True
365        return PythonGenerator.generCOMMENTAIRE(self,obj)
366
367