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