]> SALOME platform Git repositories - tools/yacsgen.git/blob - module_generator/astcompo.py
Salome HOME
Merge from V6_main_20120808 08Aug12
[tools/yacsgen.git] / module_generator / astcompo.py
1 # Copyright (C) 2009-2012  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     config += "ENV_SH         | env      | -    | " + self.prerequisites + "\n"
186
187     fdict["%s_config.txt" % self.name] = config
188     fdict["%s_component.py" % self.name] = component.substitute(component=self.name)
189
190     return fdict
191
192   def makecexepath(self, gen):
193     """specific container: generate files"""
194
195     fdict={}
196
197     if self.version < (10,1,2):
198       #patch to E_SUPERV.py
199       fil = open(os.path.join(self.aster_dir, "bibpyt", "Execution", "E_SUPERV.py"))
200       esuperv = fil.read()
201       fil.close()
202       esuperv = re.sub("def Execute\(self\)", "def Execute(self, params)", esuperv)
203       esuperv = re.sub("j=self.JdC", "self.jdc=j=self.JdC", esuperv)
204       esuperv = re.sub("\*\*args", "context_ini=params, **args", esuperv)
205       esuperv = re.sub("def main\(self\)", "def main(self,params={})", esuperv)
206       esuperv = re.sub("return self.Execute\(\)", "return self.Execute(params)", esuperv)
207       fdict["E_SUPERV.py"]=esuperv
208
209     #use a specific main program
210     fil = open(os.path.join(self.aster_dir, "config.txt"))
211     config = fil.read()
212     fil.close()
213     config = re.sub(" profile.sh", os.path.join(self.aster_dir, "profile.sh"), config)
214     path=os.path.join(os.path.abspath(gen.module.prefix),'lib',
215                       'python%s.%s' % (sys.version_info[0], sys.version_info[1]),
216                       'site-packages','salome','%s_container.py' % self.name)
217     config = re.sub("Execution\/E_SUPERV.py", path, config)
218     config += "ENV_SH         | env      | -    | " + self.prerequisites + "\n"
219
220     fdict["%s_container.py" % self.name] = container
221     fdict["%s_config.txt" % self.name] = config
222
223     return fdict
224
225   def makeexeaster(self, gen):
226     """standalone component: generate SALOME component source"""
227     services = []
228     inits = []
229     defs = []
230     for serv in self.services:
231       defs.append(serv.defs)
232       params = []
233       datas = []
234       for name, typ in serv.inport:
235         if typ=="file":continue #files are not passed through service interface
236         params.append(name)
237         if typ == "pyobj":
238           datas.append('"%s":cPickle.loads(%s)' % (name, name))
239         else:
240           datas.append('"%s":%s' % (name, name))
241       #ajout de l'adresse du composant
242       datas.append('"component":self.proxy.ptr()')
243       dvars = "{"+','.join(datas)+"}"
244       inparams = ",".join(params)
245
246       params = []
247       datas = []
248       for name, typ in serv.outport:
249         if typ=="file":continue #files are not passed through service interface
250         params.append(name)
251         if typ == "pyobj":
252           datas.append('cPickle.dumps(j.g_context["%s"],-1)'%name)
253         else:
254           datas.append('j.g_context["%s"]'%name)
255       outparams = ",".join(params)
256       rvars = ",".join(datas)
257
258       service = asterEXEService.substitute(component=self.name,
259                                            service=serv.name,
260                                            inparams=inparams,
261                                            outparams=outparams,
262                                            body=serv.body,
263                                            dvars=dvars, rvars=rvars)
264       streams = []
265       for name, typ, dep in serv.instream:
266         streams.append('       calcium.create_calcium_port(self.proxy,"%s","%s","IN","%s")'% (name, typ, dep))
267       instream = "\n".join(streams)
268       streams = []
269       for name, typ, dep in serv.outstream:
270         streams.append('       calcium.create_calcium_port(self.proxy,"%s","%s","OUT","%s")'% (name, typ, dep))
271       outstream = "\n".join(streams)
272
273       init = pyinitEXEService.substitute(component=self.name, service=serv.name,
274                                          instream=instream, outstream=outstream)
275       services.append(service)
276       inits.append(init)
277
278     if self.version < (10,1,2):
279       importesuperv="from E_SUPERV import SUPERV"
280     else:
281       importesuperv="""sys.path=["%s"]+sys.path
282 from Execution.E_SUPERV import SUPERV
283 """ % os.path.join(self.aster_dir, "bibpyt")
284
285     return asterEXECompo.substitute(component=self.name, module=gen.module.name,
286                                     servicesdef="\n".join(defs),
287                                     servicesimpl="\n".join(services),
288                                     initservice='\n'.join(inits),
289                                     aster_dir=self.aster_dir,
290                                     importesuperv=importesuperv,
291                                     )
292
293   def makecexeaster(self, gen):
294     """specific container: generate SALOME component source"""
295     services = []
296     inits = []
297     defs = []
298     for serv in self.services:
299       defs.append(serv.defs)
300       params = []
301       datas = []
302       for name, typ in serv.inport:
303         if typ=="file":continue #files are not passed through service interface
304         params.append(name)
305         if typ == "pyobj":
306           datas.append('"%s":cPickle.loads(%s)' % (name, name))
307         else:
308           datas.append('"%s":%s' % (name, name))
309       #ajout de l'adresse du composant
310       datas.append('"component":self.proxy.ptr()')
311       dvars = "{"+','.join(datas)+"}"
312       inparams = ",".join(params)
313
314       params = []
315       datas = []
316       for name, typ in serv.outport:
317         params.append(name)
318         if typ == "pyobj":
319           datas.append('cPickle.dumps(j.g_context["%s"],-1)'%name)
320         else:
321           datas.append('j.g_context["%s"]'%name)
322       outparams = ",".join(params)
323       rvars = ",".join(datas)
324
325       service = asterCEXEService.substitute(component=self.name,
326                                             service=serv.name,
327                                             inparams=inparams,
328                                             outparams=outparams,
329                                             body=serv.body,
330                                             dvars=dvars, rvars=rvars)
331       streams = []
332       for name, typ, dep in serv.instream:
333         streams.append('       calcium.create_calcium_port(self.proxy,"%s","%s","IN","%s")'% (name, typ, dep))
334       instream = "\n".join(streams)
335       streams = []
336       for name, typ, dep in serv.outstream:
337         streams.append('       calcium.create_calcium_port(self.proxy,"%s","%s","OUT","%s")'% (name, typ, dep))
338       outstream = "\n".join(streams)
339
340       init = pyinitCEXEService.substitute(component=self.name, 
341                                           service=serv.name,
342                                           instream=instream, 
343                                           outstream=outstream)
344       services.append(service)
345       inits.append(init)
346
347     if self.version < (10,1,2):
348       importesuperv="from E_SUPERV import SUPERV"
349     else:
350       importesuperv="""sys.path=["%s"] +sys.path
351 from Execution.E_SUPERV import SUPERV
352 """ % os.path.join(self.aster_dir, "bibpyt")
353
354     return asterCEXECompo.substitute(component=self.name, 
355                                      module=gen.module.name,
356                                      servicesdef="\n".join(defs), 
357                                      servicesimpl="\n".join(services), 
358                                      initservice='\n'.join(inits),
359                                      aster_dir=self.aster_dir,
360                                      importesuperv=importesuperv,
361                                      )
362
363   def getImpl(self):
364     if self.kind == "cexe":
365       return "CEXE", self.name+".exe"
366     else:
367       return "SO", ""
368
369   def makeaster(self, gen):
370     """library component: generate SALOME component source"""
371     services = []
372     inits = []
373     defs = []
374     for serv in self.services:
375       defs.append(serv.defs)
376       params = []
377       datas = []
378       for name, typ in serv.inport:
379         if typ=="file":continue #files are not passed through service interface
380         params.append(name)
381         if typ == "pyobj":
382           datas.append('"%s":cPickle.loads(%s)' % (name, name))
383         else:
384           datas.append('"%s":%s' % (name, name))
385       #ajout de l'adresse du composant
386       datas.append('"component":self.proxy.ptr()')
387       dvars = "{"+','.join(datas)+"}"
388       inparams = ",".join(params)
389
390       params = []
391       datas = []
392       for name, typ in serv.outport:
393         params.append(name)
394         if typ == "pyobj":
395           datas.append('cPickle.dumps(j.g_context["%s"],-1)'%name)
396         else:
397           datas.append('j.g_context["%s"]'%name)
398       outparams = ",".join(params)
399       rvars = ",".join(datas)
400
401       service = asterService.substitute(component=self.name, service=serv.name, 
402                                         inparams=inparams, outparams=outparams, 
403                                         body=serv.body, 
404                                         dvars=dvars, rvars=rvars)
405       streams = []
406       for name, typ, dep in serv.instream:
407         streams.append('       calcium.create_calcium_port(self.proxy,"%s","%s","IN","%s")'% (name, typ, dep))
408       instream = "\n".join(streams)
409       streams = []
410       for name, typ, dep in serv.outstream:
411         streams.append('       calcium.create_calcium_port(self.proxy,"%s","%s","OUT","%s")'% (name, typ, dep))
412       outstream = "\n".join(streams)
413
414       init = pyinitService.substitute(component=self.name, service=serv.name,
415                                       instream=instream, outstream=outstream)
416       services.append(service)
417       inits.append(init)
418
419     python_path = ",".join([repr(p) for p in self.python_path])
420     argv = ",".join([repr(p) for p in self.argv])
421     return asterCompo.substitute(component=self.name, module=gen.module.name,
422                                  servicesdef="\n".join(defs), 
423                                  servicesimpl="\n".join(services), 
424                                  initservice='\n'.join(inits),
425                                  aster_dir=self.aster_dir, 
426                                  python_path=python_path, argv=argv)
427