]> SALOME platform Git repositories - tools/yacsgen.git/blob - module_generator/astcompo.py
Salome HOME
Merge from V6_main 01/04/2013
[tools/yacsgen.git] / module_generator / astcompo.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 """
21   This module defines the ASTERComponent class for ASTER component generation
22   An ASTER component comes in 3 flavors :
23    - implemented as a dynamic library (kind='lib')
24    - implemented as a standalone component (kind='exe')
25    - implemented as a specific container (kind='cexe')
26 """
27 import re, os, sys
28
29 from gener import Component, Invalid, makedirs
30
31 from pyth_tmpl import pyinitEXEService, pyinitCEXEService, pyinitService
32 import aster_tmpl
33 from aster_tmpl import asterCEXEService, asterEXEService
34 from aster_tmpl import asterService, asterEXECompo, asterCEXECompo, asterCompo
35 from aster_tmpl import comm, make_etude, cexe, exeaster
36 from aster_tmpl import container, component
37
38 class ASTERComponent(Component):
39   """
40    A :class:`ASTERComponent` instance represents an ASTER SALOME component (special component for Code_Aster that is a mix of
41    Fortran and Python code) with services given as a list of :class:`Service` instances with the parameter *services*.
42
43    :param name: gives the name of the component.
44    :type name: str
45    :param services: the list of services (:class:`Service`) of the component.
46    :param kind: If it is given and has the value "exe", the component will be built as a standalone
47       component (executable or shell script). The default is to build the component as a dynamic library.
48    :param libs: gives all the libraries options to add when linking the generated component (-L...).
49    :param rlibs: gives all the runtime libraries options to add when linking the generated component (-R...).
50    :param exe_path: is only used when kind is "exe" and gives the path to the standalone component.
51    :param aster_dir: gives the Code_Aster installation directory.
52    :param python_path: If it is given (as a list of paths), all the paths are added to the python path (sys.path).
53    :param argv: is a list of strings that gives the command line parameters for Code_Aster. This parameter is only useful when
54       kind is "lib".
55
56    For example, the following call defines a Code_Aster component named "mycompo" with one service s1 (it must have been defined before).
57    This standalone component takes some command line arguments::
58
59       >>> c1 = module_generator.ASTERComponent('mycompo', services=[s1,], kind="exe",
60                                                           exe_path="launch.sh",
61                                                           argv=["-memjeveux","4"])
62   """
63   def __init__(self, name, services=None, libs="", rlibs="", aster_dir="", 
64                      python_path=None, argv=None, kind="lib", exe_path=None):
65     """initialise component attributes"""
66     self.aster_dir = aster_dir
67     self.python_path = python_path or []
68     self.argv = argv or []
69     self.exe_path = exe_path
70     Component.__init__(self, name, services, impl="ASTER", libs=libs, 
71                              rlibs=rlibs, kind=kind)
72
73   def validate(self):
74     """validate the component definition"""
75     Component.validate(self)
76     if not self.aster_dir:
77       raise Invalid("aster_dir must be defined for component %s" % self.name)
78
79     kinds = ("lib", "cexe", "exe")
80     if self.kind not in kinds:
81       raise Invalid("kind must be one of %s for component %s" % (kinds,self.name))
82     if self.kind == "lib" and not self.python_path:
83       raise Invalid("python_path must be defined for component %s" % self.name)
84     if self.kind == "cexe" :
85       if not self.exe_path:
86         raise Invalid("exe_path must be defined for component %s" % self.name)
87     if self.kind == "exe" :
88       if not self.exe_path:
89         raise Invalid("exe_path must be defined for component %s" % self.name)
90
91     #Si un port de nom jdc n'est pas defini dans la liste des inports du service,
92     #on en ajoute un de type string en premiere position
93     for serv in self.services:
94       found=False
95       for port_name,port_type in serv.inport:
96         if port_name == "jdc":
97           found=True
98           break
99       if not found:
100         serv.inport.insert(0, ("jdc", "string"))
101
102   def makeCompo(self, gen):
103     """drive the generation of SALOME module files and code files
104        depending on the choosen component kind
105     """
106     filename = "%s.py" % self.name
107     #on suppose que les composants ASTER sont homogenes (utilisent meme install)
108     gen.aster = self.aster_dir
109
110     #get ASTER version
111     f = os.path.join(self.aster_dir, "bibpyt", 'Accas', 'properties.py')
112     self.version=(0,0,0)
113     if os.path.isfile(f):
114       mydict = {}
115       execfile(f, mydict)
116       v,r,p = mydict['version'].split('.')
117       self.version=(int(v),int(r),int(p))
118
119     if self.kind == "lib":
120       return {"Makefile.am":gen.makeMakefile(self.getMakefileItems(gen)),
121               filename:self.makeaster(gen)}
122     elif self.kind == "cexe":
123       fdict=self.makecexepath(gen)
124       d= {"Makefile.am":gen.makeMakefile(self.getMakefileItems(gen)),
125            self.name+".exe":cexe.substitute(compoexe=self.exe_path),
126            filename:self.makecexeaster(gen)
127          }
128       d.update(fdict)
129       return d
130     elif self.kind == "exe":
131       fdict=self.makeexepath(gen)
132       d= {"Makefile.am":gen.makeMakefile(self.getMakefileItems(gen)),
133            self.name+".exe":exeaster.substitute(compoexe=self.exe_path),
134            self.name+"_module.py":self.makeexeaster(gen)
135          }
136       d.update(fdict)
137       return d
138
139   def getMakefileItems(self,gen):
140     makefileItems={"header":"include $(top_srcdir)/adm_local/make_common_starter.am"}
141     if self.kind == "lib":
142       makefileItems["salomepython_PYTHON"]=[self.name+".py"]
143     elif self.kind == "exe":
144       makefileItems["salomepython_PYTHON"]=[self.name+"_module.py",self.name+"_component.py"]
145       if self.version < (10,1,2):
146         makefileItems["salomepython_PYTHON"].append("E_SUPERV.py")
147       makefileItems["dist_salomescript_SCRIPTS"]=[self.name+".exe"]
148       makefileItems["salomeres_DATA"]=[self.name+"_config.txt"]
149     elif self.kind == "cexe":
150       makefileItems["salomepython_PYTHON"]=[self.name+".py",self.name+"_container.py"]
151       if self.version < (10,1,2):
152         makefileItems["salomepython_PYTHON"].append("E_SUPERV.py")
153       makefileItems["dist_salomescript_SCRIPTS"]=[self.name+".exe"]
154       makefileItems["salomeres_DATA"]=[self.name+"_config.txt"]
155     return makefileItems
156
157
158   def makeexepath(self, gen):
159     """standalone component: generate files for calculation code"""
160
161     fdict={}
162
163     if self.version < (10,1,2):
164       #patch to E_SUPERV.py
165       fil = open(os.path.join(self.aster_dir, "bibpyt", "Execution", "E_SUPERV.py"))
166       esuperv = fil.read()
167       fil.close()
168       esuperv = re.sub("def Execute\(self\)", "def Execute(self, params)", esuperv)
169       esuperv = re.sub("j=self.JdC", "self.jdc=j=self.JdC", esuperv)
170       esuperv = re.sub("\*\*args", "context_ini=params, **args", esuperv)
171       esuperv = re.sub("def main\(self\)", "def main(self,params={})", esuperv)
172       esuperv = re.sub("return self.Execute\(\)", "return self.Execute(params)", esuperv)
173       fdict["E_SUPERV.py"]=esuperv
174
175     #use a specific main program (modification of config.txt file)
176     fil = open(os.path.join(self.aster_dir, "config.txt"))
177     config = fil.read()
178     fil.close()
179     config = re.sub(" profile.sh", os.path.join(self.aster_dir, "profile.sh"), config)
180
181     path=os.path.join(os.path.abspath(gen.module.prefix),'lib',
182                       'python%s.%s' % (sys.version_info[0], sys.version_info[1]),
183                       'site-packages','salome','%s_component.py'%self.name)
184     config = re.sub("Execution\/E_SUPERV.py", path, config)
185
186     fdict["%s_config.txt" % self.name] = config
187     fdict["%s_component.py" % self.name] = component.substitute(component=self.name)
188
189     return fdict
190
191   def makecexepath(self, gen):
192     """specific container: generate files"""
193
194     fdict={}
195
196     if self.version < (10,1,2):
197       #patch to E_SUPERV.py
198       fil = open(os.path.join(self.aster_dir, "bibpyt", "Execution", "E_SUPERV.py"))
199       esuperv = fil.read()
200       fil.close()
201       esuperv = re.sub("def Execute\(self\)", "def Execute(self, params)", esuperv)
202       esuperv = re.sub("j=self.JdC", "self.jdc=j=self.JdC", esuperv)
203       esuperv = re.sub("\*\*args", "context_ini=params, **args", esuperv)
204       esuperv = re.sub("def main\(self\)", "def main(self,params={})", esuperv)
205       esuperv = re.sub("return self.Execute\(\)", "return self.Execute(params)", esuperv)
206       fdict["E_SUPERV.py"]=esuperv
207
208     #use a specific main program
209     fil = open(os.path.join(self.aster_dir, "config.txt"))
210     config = fil.read()
211     fil.close()
212     config = re.sub(" profile.sh", os.path.join(self.aster_dir, "profile.sh"), config)
213     path=os.path.join(os.path.abspath(gen.module.prefix),'lib',
214                       'python%s.%s' % (sys.version_info[0], sys.version_info[1]),
215                       'site-packages','salome','%s_container.py' % self.name)
216     config = re.sub("Execution\/E_SUPERV.py", path, config)
217
218     fdict["%s_container.py" % self.name] = container
219     fdict["%s_config.txt" % self.name] = config
220
221     return fdict
222
223   def makeexeaster(self, gen):
224     """standalone component: generate SALOME component source"""
225     services = []
226     inits = []
227     defs = []
228     for serv in self.services:
229       defs.append(serv.defs)
230       params = []
231       datas = []
232       for name, typ in serv.inport:
233         if typ=="file":continue #files are not passed through service interface
234         params.append(name)
235         if typ == "pyobj":
236           datas.append('"%s":cPickle.loads(%s)' % (name, name))
237         else:
238           datas.append('"%s":%s' % (name, name))
239       #ajout de l'adresse du composant
240       datas.append('"component":self.proxy.ptr()')
241       dvars = "{"+','.join(datas)+"}"
242       inparams = ",".join(params)
243
244       params = []
245       datas = []
246       for name, typ in serv.outport:
247         if typ=="file":continue #files are not passed through service interface
248         params.append(name)
249         if typ == "pyobj":
250           datas.append('cPickle.dumps(j.g_context["%s"],-1)'%name)
251         else:
252           datas.append('j.g_context["%s"]'%name)
253       outparams = ",".join(params)
254       rvars = ",".join(datas)
255
256       service = asterEXEService.substitute(component=self.name,
257                                            service=serv.name,
258                                            inparams=inparams,
259                                            outparams=outparams,
260                                            body=serv.body,
261                                            dvars=dvars, rvars=rvars)
262       streams = []
263       for name, typ, dep in serv.instream:
264         streams.append('       calcium.create_calcium_port(self.proxy,"%s","%s","IN","%s")'% (name, typ, dep))
265       instream = "\n".join(streams)
266       streams = []
267       for name, typ, dep in serv.outstream:
268         streams.append('       calcium.create_calcium_port(self.proxy,"%s","%s","OUT","%s")'% (name, typ, dep))
269       outstream = "\n".join(streams)
270
271       init = pyinitEXEService.substitute(component=self.name, service=serv.name,
272                                          instream=instream, outstream=outstream)
273       services.append(service)
274       inits.append(init)
275
276     if self.version < (10,1,2):
277       importesuperv="from E_SUPERV import SUPERV"
278     else:
279       importesuperv="""sys.path=["%s"]+sys.path
280 from Execution.E_SUPERV import SUPERV
281 """ % os.path.join(self.aster_dir, "bibpyt")
282
283     return asterEXECompo.substitute(component=self.name, module=gen.module.name,
284                                     servicesdef="\n".join(defs),
285                                     servicesimpl="\n".join(services),
286                                     initservice='\n'.join(inits),
287                                     aster_dir=self.aster_dir,
288                                     importesuperv=importesuperv,
289                                     )
290
291   def makecexeaster(self, gen):
292     """specific container: generate SALOME component source"""
293     services = []
294     inits = []
295     defs = []
296     for serv in self.services:
297       defs.append(serv.defs)
298       params = []
299       datas = []
300       for name, typ in serv.inport:
301         if typ=="file":continue #files are not passed through service interface
302         params.append(name)
303         if typ == "pyobj":
304           datas.append('"%s":cPickle.loads(%s)' % (name, name))
305         else:
306           datas.append('"%s":%s' % (name, name))
307       #ajout de l'adresse du composant
308       datas.append('"component":self.proxy.ptr()')
309       dvars = "{"+','.join(datas)+"}"
310       inparams = ",".join(params)
311
312       params = []
313       datas = []
314       for name, typ in serv.outport:
315         params.append(name)
316         if typ == "pyobj":
317           datas.append('cPickle.dumps(j.g_context["%s"],-1)'%name)
318         else:
319           datas.append('j.g_context["%s"]'%name)
320       outparams = ",".join(params)
321       rvars = ",".join(datas)
322
323       service = asterCEXEService.substitute(component=self.name,
324                                             service=serv.name,
325                                             inparams=inparams,
326                                             outparams=outparams,
327                                             body=serv.body,
328                                             dvars=dvars, rvars=rvars)
329       streams = []
330       for name, typ, dep in serv.instream:
331         streams.append('       calcium.create_calcium_port(self.proxy,"%s","%s","IN","%s")'% (name, typ, dep))
332       instream = "\n".join(streams)
333       streams = []
334       for name, typ, dep in serv.outstream:
335         streams.append('       calcium.create_calcium_port(self.proxy,"%s","%s","OUT","%s")'% (name, typ, dep))
336       outstream = "\n".join(streams)
337
338       init = pyinitCEXEService.substitute(component=self.name, 
339                                           service=serv.name,
340                                           instream=instream, 
341                                           outstream=outstream)
342       services.append(service)
343       inits.append(init)
344
345     if self.version < (10,1,2):
346       importesuperv="from E_SUPERV import SUPERV"
347     else:
348       importesuperv="""sys.path=["%s"] +sys.path
349 from Execution.E_SUPERV import SUPERV
350 """ % os.path.join(self.aster_dir, "bibpyt")
351
352     return asterCEXECompo.substitute(component=self.name, 
353                                      module=gen.module.name,
354                                      servicesdef="\n".join(defs), 
355                                      servicesimpl="\n".join(services), 
356                                      initservice='\n'.join(inits),
357                                      aster_dir=self.aster_dir,
358                                      importesuperv=importesuperv,
359                                      )
360
361   def getImpl(self):
362     if self.kind == "cexe":
363       return "CEXE", self.name+".exe"
364     else:
365       return "SO", ""
366
367   def makeaster(self, gen):
368     """library component: generate SALOME component source"""
369     services = []
370     inits = []
371     defs = []
372     for serv in self.services:
373       defs.append(serv.defs)
374       params = []
375       datas = []
376       for name, typ in serv.inport:
377         if typ=="file":continue #files are not passed through service interface
378         params.append(name)
379         if typ == "pyobj":
380           datas.append('"%s":cPickle.loads(%s)' % (name, name))
381         else:
382           datas.append('"%s":%s' % (name, name))
383       #ajout de l'adresse du composant
384       datas.append('"component":self.proxy.ptr()')
385       dvars = "{"+','.join(datas)+"}"
386       inparams = ",".join(params)
387
388       params = []
389       datas = []
390       for name, typ in serv.outport:
391         params.append(name)
392         if typ == "pyobj":
393           datas.append('cPickle.dumps(j.g_context["%s"],-1)'%name)
394         else:
395           datas.append('j.g_context["%s"]'%name)
396       outparams = ",".join(params)
397       rvars = ",".join(datas)
398
399       service = asterService.substitute(component=self.name, service=serv.name, 
400                                         inparams=inparams, outparams=outparams, 
401                                         body=serv.body, 
402                                         dvars=dvars, rvars=rvars)
403       streams = []
404       for name, typ, dep in serv.instream:
405         streams.append('       calcium.create_calcium_port(self.proxy,"%s","%s","IN","%s")'% (name, typ, dep))
406       instream = "\n".join(streams)
407       streams = []
408       for name, typ, dep in serv.outstream:
409         streams.append('       calcium.create_calcium_port(self.proxy,"%s","%s","OUT","%s")'% (name, typ, dep))
410       outstream = "\n".join(streams)
411
412       init = pyinitService.substitute(component=self.name, service=serv.name,
413                                       instream=instream, outstream=outstream)
414       services.append(service)
415       inits.append(init)
416
417     python_path = ",".join([repr(p) for p in self.python_path])
418     argv = ",".join([repr(p) for p in self.argv])
419     return asterCompo.substitute(component=self.name, module=gen.module.name,
420                                  servicesdef="\n".join(defs), 
421                                  servicesimpl="\n".join(services), 
422                                  initservice='\n'.join(inits),
423                                  aster_dir=self.aster_dir, 
424                                  python_path=python_path, argv=argv)
425