Salome HOME
Copyright update 2022
[tools/yacsgen.git] / module_generator / aster_tmpl.py
1 # Copyright (C) 2009-2022  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, or (at your option) any later version.
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
20 try:
21  from string import Template
22 except:
23  from module_generator.compat import Template,set
24
25 asterCompo="""
26 import sys,traceback,os
27 import ${module}_ORB__POA
28 import calcium
29 import dsccalcium
30 import SALOME
31 import linecache
32 import shutil
33
34 sys.path=sys.path+[${python_path}]
35 import aster
36 import Accas
37 import Cata.cata
38 from Execution.E_SUPERV import SUPERV
39
40 aster_dir="${aster_dir}"
41
42 try:
43   import numpy
44 except:
45   numpy=None
46
47 #DEFS
48 ${servicesdef}
49 #ENDDEF
50
51 class ${component}(${module}_ORB__POA.${component},dsccalcium.PyDSCComponent,SUPERV):
52   '''
53      To be identified as a SALOME component this Python class
54      must have the same name as the component, inherit omniorb
55      class ${module}_ORB__POA.${component} and DSC class dsccalcium.PyDSCComponent
56      that implements DSC API.
57   '''
58   def __init__ ( self, orb, poa, contID, containerName, instanceName, interfaceName ):
59     dsccalcium.PyDSCComponent.__init__(self, orb, poa,contID,containerName,instanceName,interfaceName)
60     self.argv=[${argv}]
61     #modif pour aster 9.0
62     if hasattr(self,"init_timer"):
63       self.init_timer()
64     #fin modif pour aster 9.0
65     elements_file = ""
66     if os.path.exists(os.path.join(aster_dir,"share", "aster", "elements")):
67       elements_file = os.path.join(aster_dir,"elements")
68     elif os.path.exists(os.path.join(aster_dir,"elements")):
69       elements_file = os.path.join(aster_dir,"elements")
70     else:
71       elements_file = os.path.join(aster_dir,"catobj","elements")
72     shutil.copyfile(elements_file,"elem.1")
73     
74
75   def init_service(self,service):
76 ${initservice}
77     return False
78
79 ${servicesimpl}
80 """
81 asterCompo=Template(asterCompo)
82
83 asterCEXECompo="""
84 # Par rapport a la version precedente
85 # Chaque service est complete par l'appel initial a Complement
86 # Cette methode rajoute a l'appel du premier service de l'instance un prefixe au fichier de commande
87 # Ce prefixe est fourni dans le fichier fort.99 via as_run et exeaster
88 # Le fichier est lu a la creation du module
89 # Interet: introduire DEBUT() dans ce prefixe pour ne plus avoir a s'en preoccuper (ex: boucle for each)
90 import sys,traceback,os
91 import string
92 import ${module}_ORB__POA
93 import calcium
94 import dsccalcium
95 import SALOME
96 import linecache
97 ${importesuperv}
98
99 try:
100   import numpy
101 except:
102   numpy=None
103
104 #DEFS
105 ${servicesdef}
106 #ENDDEF
107
108 class ExecutionError(Exception):
109   '''General exception during execution'''
110
111 class ${component}(${module}_ORB__POA.${component},dsccalcium.PyDSCComponent,SUPERV):
112   '''
113      To be identified as a SALOME component this Python class
114      must have the same name as the component, inherit omniorb
115      class ${module}_ORB__POA.${component} and DSC class dsccalcium.PyDSCComponent
116      that implements DSC API.
117   '''
118   def __init__ ( self, orb, poa, contID, containerName, instanceName, interfaceName ):
119     self.init=0
120     if os.path.isfile('fort.99'):
121       prefixFile = file("fort.99","r")
122       self.prefixJdc = prefixFile.read()
123       prefixFile.close()
124     else:
125       self.prefixJdc = ""
126     dsccalcium.PyDSCComponent.__init__(self, orb, poa,contID,containerName,instanceName,interfaceName)
127
128   def init_service(self,service):
129 ${initservice}
130     return False
131
132   def insertPrefix(self,jdc):
133     if not self.init:
134       jdc = self.prefixJdc + jdc
135     return jdc
136
137   def insertPrePost(self,jdc,prepost):
138     if prepost != "":
139       exec(prepost)
140       try:
141         jdc = os.linesep + pre + os.linesep + jdc + os.linesep + post + os.linesep
142       except NameError:
143         pass
144     return jdc
145     
146   def interpstring(self,text,args):
147     try:
148       self.jdc.g_context.update(args)
149       CONTEXT.set_current_step(self.jdc)
150       linecache.cache['<string>']=0,None,string.split(text,'\\n'),'<string>'
151       exec(text in self.jdc.const_context,self.jdc.g_context)
152       CONTEXT.unset_current_step()
153     except EOFError:
154       CONTEXT.unset_current_step()
155     except:
156       CONTEXT.unset_current_step()
157       raise
158
159 ${servicesimpl}
160 """
161
162 asterEXECompo=asterCEXECompo+"""
163   def destroy(self):
164      self._orb.shutdown(0)
165 """
166
167 asterCEXECompo=Template(asterCEXECompo)
168 asterEXECompo=Template(asterEXECompo)
169
170 asterService="""
171   def ${service}(self,${inparams}):
172     self.beginService("${component}.${service}")
173     self.jdc=Cata.cata.JdC(procedure=jdc,cata=Cata.cata,nom="Salome",context_ini=${dvars})
174     j=self.jdc
175     #modif pour aster 9.0
176     if hasattr(self,"init_timer"):
177       j.timer = self.timer
178     #fin modif pour aster 9.0
179
180     # On compile le texte Python
181     j.compile()
182
183     #modif pour aster 9.0
184     # On initialise les tops de mesure globale de temps d'execution du jdc
185     if hasattr(self,"init_timer"):
186        j.cpu_user=os.times()[0]
187        j.cpu_syst=os.times()[1]
188     #fin modif pour aster 9.0
189
190     if not j.cr.estvide():
191        msg="ERREUR DE COMPILATION DANS ACCAS - INTERRUPTION"
192        self.MESSAGE(msg)
193        print (">> JDC.py : DEBUT RAPPORT")
194        print (j.cr)
195        print (">> JDC.py : FIN RAPPORT")
196        j.supprime()
197        sys.stdout.flush()
198        raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,msg+'\\n'+str(j.cr),"${component}.py",0))
199
200     #surcharge des arguments de la ligne de commande (defaut stocke dans le composant) par un eventuel port de nom argv
201     try:
202       self.argv=self.argv+argv.split()
203     except:
204       pass
205
206     #initialisation des arguments de la ligne de commande (remplace la methode initexec de B_JDC.py)
207     aster.argv(self.argv)
208     aster.init(CONTEXT.debug)
209     j.setmode(1)
210     j.ini=1
211
212     try:
213       j.exec_compile()
214     except:
215       sys.stdout.flush()
216       exc_typ,exc_val,exc_fr=sys.exc_info()
217       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
218       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"${component}.py",0))
219
220     ier=0
221     if not j.cr.estvide():
222        msg="ERREUR A L'INTERPRETATION DANS ACCAS - INTERRUPTION"
223        self.MESSAGE(msg)
224        ier=1
225        print (">> JDC.py : DEBUT RAPPORT")
226        print (j.cr)
227        print (">> JDC.py : FIN RAPPORT")
228        sys.stdout.flush()
229        raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,msg+'\\n'+str(j.cr), "${component}.py",0))
230
231     if j.par_lot == 'NON':
232        print ("FIN EXECUTION")
233        #err=calcium.cp_fin(self.proxy,calcium.CP_ARRET)
234        #retour sans erreur (il faut pousser les variables de sortie)
235        sys.stdout.flush()
236        self.endService("${component}.${service}")
237        return ${rvars}
238
239     # Verification de la validite du jeu de commande
240     cr=j.report()
241     if not cr.estvide():
242        msg="ERREUR A LA VERIFICATION SYNTAXIQUE - INTERRUPTION"
243        self.MESSAGE(msg)
244        print( ">> JDC.py : DEBUT RAPPORT")
245        print( cr)
246        print( ">> JDC.py : FIN RAPPORT")
247        sys.stdout.flush()
248        raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,msg+'\\n'+str(cr),"${component}.py",0))
249
250     j.set_par_lot("NON")
251     try:
252        j.BuildExec()
253        ier=0
254        if not j.cr.estvide():
255           msg="ERREUR A L'EXECUTION - INTERRUPTION"
256           self.MESSAGE(msg)
257           ier=1
258           print( ">> JDC.py : DEBUT RAPPORT")
259           print( j.cr)
260           print( ">> JDC.py : FIN RAPPORT")
261           sys.stdout.flush()
262           raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,msg+'\\n'+str(j.cr),"${component}.py",0))
263        else:
264          #retour sans erreur (il faut pousser les variables de sortie)
265          #err=calcium.cp_fin(self.proxy,calcium.CP_ARRET)
266          sys.stdout.flush()
267          self.endService("${component}.${service}")
268          return ${rvars}
269     except :
270       self.MESSAGE("ERREUR INOPINEE - INTERRUPTION")
271       sys.stdout.flush()
272       exc_typ,exc_val,exc_fr=sys.exc_info()
273       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
274       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"${component}.py",0))
275 """
276 asterService=Template(asterService)
277
278 asterCEXEService="""
279   def ${service}(self,${inparams}):
280     self.beginService("${component}.${service}")
281     try:
282       args=${dvars}
283       if "jdc" not in args:
284         fcomm=open("jdc",'r')
285         jdc=fcomm.read()
286         fcomm.close()
287         #args["jdc"]=jdc
288       prepost = '''${body}'''
289       jdc = self.insertPrePost(jdc,prepost)
290       jdc = self.insertPrefix(jdc)
291       if not self.init:
292         self.init=1
293         fcomm=open("fort.1",'w')
294         fcomm.write(jdc)
295         fcomm.close()
296         ier=self.main(args)
297         if ier != 0:
298           raise ExecutionError("Error in initial execution")
299       else:
300         self.interpstring(jdc,args)
301
302       self.endService("${component}.${service}")
303       j=self.jdc
304       return ${rvars}
305     except:
306       exc_typ,exc_val,exc_fr=sys.exc_info()
307       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
308       self.endService("${component}.${service}")
309       sys.stdout.flush()
310       sys.stderr.flush()
311       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"${component}.py",0))
312 """
313 asterCEXEService=Template(asterCEXEService)
314 asterEXEService=asterCEXEService
315
316 comm="""
317 DEBUT(PAR_LOT='NON')
318 """
319
320 make_etude="""P actions make_etude
321 P version NEW9
322 P nomjob salome
323 P ncpus 1
324 A memjeveux 4.000000
325 P mem_aster 100
326 A tpmax 60
327 P memjob 32768
328 P mpi_nbcpu 1
329 P mpi_nbnoeud 1
330 P tpsjob 1
331 P mode batch
332 P soumbtc oui
333 P consbtc oui
334 F conf ${config} D 0
335 F comm ${comm} D 1
336 ${extras}
337 """
338 make_etude=Template(make_etude)
339
340 make_etude_exe="""P actions make_etude
341 P version NEW9
342 P nomjob salome
343 P ncpus 1
344 A memjeveux 4.000000
345 P mem_aster 100
346 A tpmax 60
347 P memjob 32768
348 P mpi_nbcpu 1
349 P mpi_nbnoeud 1
350 P tpsjob 1
351 P mode batch
352 P soumbtc oui
353 P consbtc oui
354 F comm ${comm} D 1
355 """
356 make_etude_exe=Template(make_etude_exe)
357
358 cexe="""#!/bin/sh
359
360 export SALOME_CONTAINERNAME=$$1
361
362 ${compoexe}
363 """
364 cexe=Template(cexe)
365
366 exeaster="""#!/bin/sh
367
368 export SALOME_CONTAINER=$$1
369 export SALOME_CONTAINERNAME=$$2
370 export SALOME_INSTANCE=$$3
371
372 ${compoexe}
373 """
374 exeaster=Template(exeaster)
375
376 container="""import sys,os
377 from omniORB import CORBA
378 from SALOME_ContainerPy import SALOME_ContainerPy_i
379
380 if __name__ == '__main__':
381
382   print( sys.argv)
383   orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID)
384   poa = orb.resolve_initial_references("RootPOA")
385   print( "ORB and POA initialized")
386   containerName=os.getenv("SALOME_CONTAINERNAME")
387   cpy_i = SALOME_ContainerPy_i(orb, poa, containerName)
388   print( "SALOME_ContainerPy_i instance created ",cpy_i)
389   cpy_o = cpy_i._this()
390   print( "SALOME_ContainerPy_i instance activated ",cpy_o)
391   sys.stdout.flush()
392   sys.stderr.flush()
393
394   #activate the POA
395   poaManager = poa._get_the_POAManager()
396   poaManager.activate()
397
398   #Block for ever
399   orb.run()
400   print( "fin container aster")
401   sys.stdout.flush()
402   sys.stderr.flush()
403 """
404
405 component="""import sys,os
406 from omniORB import CORBA
407 from ${component}_module import ${component}
408
409 if __name__ == '__main__':
410
411   print( sys.argv)
412   orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID)
413   poa = orb.resolve_initial_references("RootPOA")
414   print( "ORB and POA initialized",orb,poa)
415   sys.stdout.flush()
416   sys.stderr.flush()
417
418   container=orb.string_to_object(os.getenv("SALOME_CONTAINER"))
419   containerName=os.getenv("SALOME_CONTAINERNAME")
420   instanceName=os.getenv("SALOME_INSTANCE")
421
422   compo=${component}(orb,poa,container,containerName, instanceName, "${component}")
423   comp_o = compo._this()
424   comp_iors = orb.object_to_string(comp_o)
425   print( "ior aster",comp_iors)
426
427   sys.stdout.flush()
428   sys.stderr.flush()
429
430   #activate the POA
431   poaManager = poa._get_the_POAManager()
432   poaManager.activate()
433
434   orb.run()
435   print( "fin du composant aster standalone")
436
437 """
438 component=Template(component)
439
440 # CMakeLists.txt in src/<component> for an aster component
441 # template parameters:
442 #   sources: source files, separated by spaces
443 #   module: module name
444 #   resources: files to be installed in resources directory
445 #   scripts: scripts to be installed
446 cmake_src_compo_aster="""
447 # scripts / static
448 SET(_bin_py
449   ${sources}
450 )
451
452 SET(_res_files
453   ${resources}
454 )
455
456 SET(_bin_scripts
457   ${scripts}
458 )
459
460 # --- rules ---
461 INSTALL(FILES $${_res_files} DESTINATION $${SALOME_${module}_INSTALL_RES_DATA})
462 SALOME_INSTALL_SCRIPTS("$${_bin_scripts}" $${SALOME_INSTALL_SCRIPT_SCRIPTS})
463 SALOME_INSTALL_SCRIPTS("$${_bin_py}" $${SALOME_INSTALL_PYTHON})
464 """
465 cmake_src_compo_aster=Template(cmake_src_compo_aster)
466
467 # CMakeLists.txt in src/<component> for an aster lib component
468 # template parameters:
469 #   sources: source files, separated by spaces
470 cmake_src_compo_aster_lib="""
471 # scripts / static
472 SET(_bin_SCRIPTS
473   ${sources}
474 )
475
476 # --- rules ---
477 SALOME_INSTALL_SCRIPTS("$${_bin_SCRIPTS}" $${SALOME_INSTALL_PYTHON})
478 """
479 cmake_src_compo_aster_lib=Template(cmake_src_compo_aster_lib)