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