Salome HOME
Merge branch V7_3_1_BR
[tools/yacsgen.git] / module_generator / aster_tmpl.py
1 # Copyright (C) 2009-2014  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 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
318 check_aster="""
319 #
320 # Check availability of Aster binary distribution
321 #
322
323 AC_DEFUN([AC_CHECK_ASTER],[
324
325 AC_CHECKING(for Aster)
326
327 Aster_ok=no
328
329 AC_ARG_WITH(aster,
330       [AC_HELP_STRING([--with-aster=DIR],[root directory path of Aster installation])],
331       [ASTER_DIR="$withval"],[ASTER_DIR=""])
332
333 if test -f ${ASTER_DIR}/bin/aster ; then
334    Aster_ok=yes
335    AC_MSG_RESULT(Using Aster distribution in ${ASTER_DIR})
336
337    ASTER_INCLUDES=-I$ASTER_DIR/include/aster
338
339    AC_SUBST(ASTER_DIR)
340    AC_SUBST(ASTER_INCLUDES)
341
342 else
343    AC_MSG_WARN("Cannot find Aster distribution")
344 fi
345
346 AC_MSG_RESULT(for Aster: $Aster_ok)
347
348 ])dnl
349 """
350
351 comm="""
352 DEBUT(PAR_LOT='NON')
353 """
354
355 make_etude="""P actions make_etude
356 P version NEW9
357 P nomjob salome
358 P ncpus 1
359 A memjeveux 4.000000
360 P mem_aster 100
361 A tpmax 60
362 P memjob 32768
363 P mpi_nbcpu 1
364 P mpi_nbnoeud 1
365 P tpsjob 1
366 P mode batch
367 P soumbtc oui
368 P consbtc oui
369 F conf ${config} D 0
370 F comm ${comm} D 1
371 ${extras}
372 """
373 make_etude=Template(make_etude)
374
375 make_etude_exe="""P actions make_etude
376 P version NEW9
377 P nomjob salome
378 P ncpus 1
379 A memjeveux 4.000000
380 P mem_aster 100
381 A tpmax 60
382 P memjob 32768
383 P mpi_nbcpu 1
384 P mpi_nbnoeud 1
385 P tpsjob 1
386 P mode batch
387 P soumbtc oui
388 P consbtc oui
389 F comm ${comm} D 1
390 """
391 make_etude_exe=Template(make_etude_exe)
392
393 cexe="""#!/bin/sh
394
395 export SALOME_CONTAINERNAME=$$1
396
397 ${compoexe}
398 """
399 cexe=Template(cexe)
400
401 exeaster="""#!/bin/sh
402
403 export SALOME_CONTAINER=$$1
404 export SALOME_CONTAINERNAME=$$2
405 export SALOME_INSTANCE=$$3
406
407 ${compoexe}
408 """
409 exeaster=Template(exeaster)
410
411 container="""import sys,os
412 from omniORB import CORBA
413 from SALOME_ContainerPy import SALOME_ContainerPy_i
414
415 if __name__ == '__main__':
416
417   print sys.argv
418   orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID)
419   poa = orb.resolve_initial_references("RootPOA")
420   print "ORB and POA initialized"
421   containerName=os.getenv("SALOME_CONTAINERNAME")
422   cpy_i = SALOME_ContainerPy_i(orb, poa, containerName)
423   print "SALOME_ContainerPy_i instance created ",cpy_i
424   cpy_o = cpy_i._this()
425   print "SALOME_ContainerPy_i instance activated ",cpy_o
426   sys.stdout.flush()
427   sys.stderr.flush()
428
429   #activate the POA
430   poaManager = poa._get_the_POAManager()
431   poaManager.activate()
432
433   #Block for ever
434   orb.run()
435   print "fin container aster"
436   sys.stdout.flush()
437   sys.stderr.flush()
438 """
439
440 component="""import sys,os
441 from omniORB import CORBA
442 from ${component}_module import ${component}
443
444 if __name__ == '__main__':
445
446   print sys.argv
447   orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID)
448   poa = orb.resolve_initial_references("RootPOA")
449   print "ORB and POA initialized",orb,poa
450   sys.stdout.flush()
451   sys.stderr.flush()
452
453   container=orb.string_to_object(os.getenv("SALOME_CONTAINER"))
454   containerName=os.getenv("SALOME_CONTAINERNAME")
455   instanceName=os.getenv("SALOME_INSTANCE")
456
457   compo=${component}(orb,poa,container,containerName, instanceName, "${component}")
458   comp_o = compo._this()
459   comp_iors = orb.object_to_string(comp_o)
460   print "ior aster",comp_iors
461
462   sys.stdout.flush()
463   sys.stderr.flush()
464
465   #activate the POA
466   poaManager = poa._get_the_POAManager()
467   poaManager.activate()
468
469   orb.run()
470   print "fin du composant aster standalone"
471
472 """
473 component=Template(component)
474