Salome HOME
Merge from V6_main 01/04/2013
[tools/yacsgen.git] / module_generator / aster_tmpl.py
1 # Copyright (C) 2009-2013  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.
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     if os.path.exists(os.path.join(aster_dir,"elements")):
66       shutil.copyfile(os.path.join(aster_dir,"elements"),"elem.1")
67     else:
68       shutil.copyfile(os.path.join(aster_dir,"catobj","elements"),"elem.1")
69
70   def init_service(self,service):
71 ${initservice}
72     return False
73
74 ${servicesimpl}
75 """
76 asterCompo=Template(asterCompo)
77
78 asterCEXECompo="""
79 import sys,traceback,os
80 import string
81 import ${module}_ORB__POA
82 import calcium
83 import dsccalcium
84 import SALOME
85 import linecache
86 ${importesuperv}
87
88 try:
89   import numpy
90 except:
91   numpy=None
92
93 #DEFS
94 ${servicesdef}
95 #ENDDEF
96
97 class ExecutionError(Exception):
98   '''General exception during execution'''
99
100 class ${component}(${module}_ORB__POA.${component},dsccalcium.PyDSCComponent,SUPERV):
101   '''
102      To be identified as a SALOME component this Python class
103      must have the same name as the component, inherit omniorb
104      class ${module}_ORB__POA.${component} and DSC class dsccalcium.PyDSCComponent
105      that implements DSC API.
106   '''
107   def __init__ ( self, orb, poa, contID, containerName, instanceName, interfaceName ):
108     self.init=0
109     dsccalcium.PyDSCComponent.__init__(self, orb, poa,contID,containerName,instanceName,interfaceName)
110
111   def init_service(self,service):
112 ${initservice}
113     return False
114
115   def interpstring(self,text,args):
116     try:
117       self.jdc.g_context.update(args)
118       CONTEXT.set_current_step(self.jdc)
119       linecache.cache['<string>']=0,None,string.split(text,'\\n'),'<string>'
120       exec text in self.jdc.const_context,self.jdc.g_context
121       CONTEXT.unset_current_step()
122     except EOFError:
123       CONTEXT.unset_current_step()
124     except:
125       CONTEXT.unset_current_step()
126       raise
127
128 ${servicesimpl}
129 """
130
131 asterEXECompo=asterCEXECompo+"""
132   def destroy(self):
133      self._orb.shutdown(0)
134 """
135
136 asterCEXECompo=Template(asterCEXECompo)
137 asterEXECompo=Template(asterEXECompo)
138
139 asterService="""
140   def ${service}(self,${inparams}):
141     self.beginService("${component}.${service}")
142     self.jdc=Cata.cata.JdC(procedure=jdc,cata=Cata.cata,nom="Salome",context_ini=${dvars})
143     j=self.jdc
144     #modif pour aster 9.0
145     if hasattr(self,"init_timer"):
146       j.timer = self.timer
147     #fin modif pour aster 9.0
148
149     # On compile le texte Python
150     j.compile()
151
152     #modif pour aster 9.0
153     # On initialise les tops de mesure globale de temps d'execution du jdc
154     if hasattr(self,"init_timer"):
155        j.cpu_user=os.times()[0]
156        j.cpu_syst=os.times()[1]
157     #fin modif pour aster 9.0
158
159     if not j.cr.estvide():
160        msg="ERREUR DE COMPILATION DANS ACCAS - INTERRUPTION"
161        self.MESSAGE(msg)
162        print ">> JDC.py : DEBUT RAPPORT"
163        print j.cr
164        print ">> JDC.py : FIN RAPPORT"
165        j.supprime()
166        sys.stdout.flush()
167        raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,msg+'\\n'+str(j.cr),"${component}.py",0))
168
169     #surcharge des arguments de la ligne de commande (defaut stocke dans le composant) par un eventuel port de nom argv
170     try:
171       self.argv=self.argv+argv.split()
172     except:
173       pass
174
175     #initialisation des arguments de la ligne de commande (remplace la methode initexec de B_JDC.py)
176     aster.argv(self.argv)
177     aster.init(CONTEXT.debug)
178     j.setmode(1)
179     j.ini=1
180
181     try:
182       j.exec_compile()
183     except:
184       sys.stdout.flush()
185       exc_typ,exc_val,exc_fr=sys.exc_info()
186       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
187       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"${component}.py",0))
188
189     ier=0
190     if not j.cr.estvide():
191        msg="ERREUR A L'INTERPRETATION DANS ACCAS - INTERRUPTION"
192        self.MESSAGE(msg)
193        ier=1
194        print ">> JDC.py : DEBUT RAPPORT"
195        print j.cr
196        print ">> JDC.py : FIN RAPPORT"
197        sys.stdout.flush()
198        raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,msg+'\\n'+str(j.cr), "${component}.py",0))
199
200     if j.par_lot == 'NON':
201        print "FIN EXECUTION"
202        #err=calcium.cp_fin(self.proxy,calcium.CP_ARRET)
203        #retour sans erreur (il faut pousser les variables de sortie)
204        sys.stdout.flush()
205        self.endService("${component}.${service}")
206        return ${rvars}
207
208     # Verification de la validite du jeu de commande
209     cr=j.report()
210     if not cr.estvide():
211        msg="ERREUR A LA VERIFICATION SYNTAXIQUE - INTERRUPTION"
212        self.MESSAGE(msg)
213        print ">> JDC.py : DEBUT RAPPORT"
214        print cr
215        print ">> JDC.py : FIN RAPPORT"
216        sys.stdout.flush()
217        raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,msg+'\\n'+str(cr),"${component}.py",0))
218
219     j.set_par_lot("NON")
220     try:
221        j.BuildExec()
222        ier=0
223        if not j.cr.estvide():
224           msg="ERREUR A L'EXECUTION - INTERRUPTION"
225           self.MESSAGE(msg)
226           ier=1
227           print ">> JDC.py : DEBUT RAPPORT"
228           print j.cr
229           print ">> JDC.py : FIN RAPPORT"
230           sys.stdout.flush()
231           raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,msg+'\\n'+str(j.cr),"${component}.py",0))
232        else:
233          #retour sans erreur (il faut pousser les variables de sortie)
234          #err=calcium.cp_fin(self.proxy,calcium.CP_ARRET)
235          sys.stdout.flush()
236          self.endService("${component}.${service}")
237          return ${rvars}
238     except :
239       self.MESSAGE("ERREUR INOPINEE - INTERRUPTION")
240       sys.stdout.flush()
241       exc_typ,exc_val,exc_fr=sys.exc_info()
242       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
243       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"${component}.py",0))
244 """
245 asterService=Template(asterService)
246
247 asterCEXEService="""
248   def ${service}(self,${inparams}):
249     self.beginService("${component}.${service}")
250     try:
251       args=${dvars}
252       if not args.has_key("jdc"):
253         fcomm=open("jdc",'r')
254         jdc=fcomm.read()
255         fcomm.close()
256         #args["jdc"]=jdc
257       if not self.init:
258         self.init=1
259         fcomm=open("fort.1",'w')
260         fcomm.write(jdc)
261         fcomm.close()
262         ier=self.main(args)
263         if ier != 0:
264           raise ExecutionError("Error in initial execution")
265       else:
266         self.interpstring(jdc,args)
267
268       self.endService("${component}.${service}")
269       j=self.jdc
270       return ${rvars}
271     except:
272       exc_typ,exc_val,exc_fr=sys.exc_info()
273       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
274       self.endService("${component}.${service}")
275       sys.stdout.flush()
276       sys.stderr.flush()
277       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"${component}.py",0))
278 """
279 asterCEXEService=Template(asterCEXEService)
280 asterEXEService=asterCEXEService
281
282
283 check_aster="""
284 #
285 # Check availability of Aster binary distribution
286 #
287
288 AC_DEFUN([AC_CHECK_ASTER],[
289
290 AC_CHECKING(for Aster)
291
292 Aster_ok=no
293
294 AC_ARG_WITH(aster,
295       [AC_HELP_STRING([--with-aster=DIR],[root directory path of Aster installation])],
296       [ASTER_DIR="$withval"],[ASTER_DIR=""])
297
298 if test -f ${ASTER_DIR}/asteru ; then
299    Aster_ok=yes
300    AC_MSG_RESULT(Using Aster distribution in ${ASTER_DIR})
301
302    ASTER_INCLUDES=-I$ASTER_DIR/bibc/include
303
304    AC_SUBST(ASTER_DIR)
305    AC_SUBST(ASTER_INCLUDES)
306
307 else
308    AC_MSG_WARN("Cannot find Aster distribution")
309 fi
310
311 AC_MSG_RESULT(for Aster: $Aster_ok)
312
313 ])dnl
314 """
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