Salome HOME
Added catalog and modified idl file to make GENERICSOLVER component usable in YACS.
[samples/genericsolver.git] / src / GENERICSOLVER / GENERICSOLVER.py
1 #  Copyright (C) 2007-2010  CEA/DEN, EDF R&D, OPEN CASCADE
2 #
3 #  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 #  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 #
6 #  This library is free software; you can redistribute it and/or
7 #  modify it under the terms of the GNU Lesser General Public
8 #  License as published by the Free Software Foundation; either
9 #  version 2.1 of the License.
10 #
11 #  This library is distributed in the hope that it will be useful,
12 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 #  Lesser General Public License for more details.
15 #
16 #  You should have received a copy of the GNU Lesser General Public
17 #  License along with this library; if not, write to the Free Software
18 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 #
20 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 #
22 #  $Id$
23 #
24
25 import traceback
26 import GENERICSOLVER_ORB__POA
27 import SALOME_ComponentPy
28 import SALOME_DriverPy
29
30 from omniORB import CORBA
31 from SALOME_NamingServicePy import *
32 from LifeCycleCORBA import *
33 import SALOMEDS
34 import SALOMEDS_Attributes_idl
35
36
37 VARIABLE_ID = 1030
38
39 ################################################
40
41 # init ORB
42 orb = CORBA.ORB_init( [''], CORBA.ORB_ID )
43
44 # create naming service instance
45 naming_service = SALOME_NamingServicePy_i( orb )
46
47 # create life cycle CORBA instance
48 lcc = LifeCycleCORBA( orb )
49
50 # get study manager
51 obj = naming_service.Resolve( '/myStudyManager' )
52 studyManager = obj._narrow( SALOMEDS.StudyManager )
53
54 ################################################
55 ###
56 # get active study
57 ###
58 def getStudy( studyId ):
59     #studyId = getStudyId()
60     study = studyManager.GetStudyByID( studyId )
61     return study
62
63 ###
64 # Retrieve data from selected case
65 ###
66 def GetDataFromCase( studyId, caseEntry ):
67     theCase = {}
68     study = getStudy( studyId )
69     case = study.FindObjectID( caseEntry )
70     builder = study.NewBuilder()
71     # Get the values of the variables and make them a list
72     for name in ("E", "F", "L", "I"):
73         var = getSubSObjectByName( studyId, case, name )
74         if var == None:
75             print "GENERICSOLVER.GetDataFromCase : ERROR! no variable '%s'" % name
76             break
77         theCase[ name ] = getValueOfVariable( builder, var )
78     return theCase
79
80 ###
81 # Add some variable to the case
82 ###
83 def AddDataToCase( studyId, caseEntry, varName, varValue ):
84     study = getStudy( studyId )
85     case = study.FindObjectID( caseEntry )
86     builder = study.NewBuilder()
87     var = addObjectInStudy( builder, case, varName, VARIABLE_ID )
88     setValueToVariable( builder, var, varValue )
89     sg.updateObjBrowser( True )
90     pass
91
92 ###
93 # Plays with study
94 ###
95 def addObjectInStudy( builder, father, objname, objid ):
96     obj = getSubSObjectByName( father, objname )
97     if obj is None:
98         obj  = builder.NewObject( father )
99         attr = builder.FindOrCreateAttribute( obj, "AttributeName" )
100         attr.SetValue( objname )
101         attr = builder.FindOrCreateAttribute( obj, "AttributeLocalID" )
102         attr.SetValue( objid )
103     return obj
104
105 def setValueToVariable( builder, varobj, value ):
106     attr = builder.FindOrCreateAttribute( varobj, "AttributeLocalID" )
107     objid = attr.Value()
108     if (objid == VARIABLE_ID):
109         attr = builder.FindOrCreateAttribute( varobj, "AttributeReal" )
110         attr.SetValue( value )
111     else:
112         attr = builder.FindOrCreateAttribute( varobj, "AttributeName" )
113         QMessageBox.information( sgPyQt.getDesktop(), 'Info', "Object '%s' isn't a variable. Can't set value." % attr.Value() )
114     pass
115
116 def getValueOfVariable( builder, varobj ):
117     attr = builder.FindOrCreateAttribute( varobj, "AttributeLocalID" )
118     objid = attr.Value()
119     if (objid == VARIABLE_ID):
120         attr = builder.FindOrCreateAttribute( varobj, "AttributeReal" )
121         return attr.Value()
122     else:
123         attr = builder.FindOrCreateAttribute( varobj, "AttributeName" )
124         QMessageBox.information( sgPyQt.getDesktop(), 'Info', "Object '%s' isn't a variable. Can't set value." % attr.Value() )
125     return 0.
126
127 def getSubSObjectByName( studyId, sobjFather, childName ):
128     print "GENERICSOLVER.getSubSObjectByName Looking for sobjet named", childName
129     study = getStudy( studyId )
130     iter = study.NewChildIterator( sobjFather )
131     #builder = study.NewBuilder()
132     while iter.More():
133         sobj = iter.Value()
134         print "GENERICSOLVER.getSubSObjectByName Got sobjet named", sobj.GetName()
135         if sobj.GetName() == childName:
136             return sobj
137         iter.Next()
138         pass
139     return None
140
141 ################################################
142
143 class GENERICSOLVER(GENERICSOLVER_ORB__POA.GENERICSOLVER_Gen,
144               SALOME_ComponentPy.SALOME_ComponentPy_i,
145               SALOME_DriverPy.SALOME_DriverPy_i):
146     """
147         Pour etre un composant SALOME cette classe Python
148         doit avoir le nom du composant et heriter de la
149         classe GENERICSOLVER_Gen issue de la compilation de l'idl
150         par omniidl et de la classe SALOME_ComponentPy_i
151         qui porte les services generaux d'un composant SALOME
152     """
153     def __init__ ( self, orb, poa, contID, containerName, instanceName, 
154                    interfaceName ):
155         print "GENERICSOLVER.__init__: ", containerName, ';', instanceName
156         SALOME_ComponentPy.SALOME_ComponentPy_i.__init__(self, orb, poa,
157                     contID, containerName, instanceName, interfaceName, 0)
158         SALOME_DriverPy.SALOME_DriverPy_i.__init__(self, interfaceName)
159         # On stocke dans l'attribut _naming_service, une reference sur
160         # le Naming Service CORBA
161         self._naming_service = SALOME_ComponentPy.SALOME_NamingServicePy_i( self._orb )
162         self.case = None
163         self.wrapperDescription = ""
164
165 ######################################################################
166 # This is the Wrapper part of the GENERICSOLVER module, ie
167 # the three following methods are used by generic controlling
168 # modules like OpenTURNS in order to launch a computation.
169 # The interface is declared in GENERICSOLVER_Gen.idl. The methods
170 # are free to call the legacy interface (see below).
171 ######################################################################
172
173
174     def Init ( self, studyId, caseEntry, wrapperDescription ):
175         """
176         This method is an implementation for the GENERICSOLVER interface.
177         It sets the component with some deterministic parametrization.
178         """
179         print "GENERICSOLVER.Init : enter"
180         print "GENERICSOLVER.Init : studyId = %d - caseEntry = %s - wrapperDescription = %s" % ( studyId, caseEntry, wrapperDescription )
181         self.wrapperDescription = wrapperDescription
182         
183         try:
184             self.case = GetDataFromCase( studyId, caseEntry )
185         except:
186             traceback.print_exc()
187         if self.case is None:
188             return 1
189         print "GENERICSOLVER.Init : exit"
190         return 0
191
192     def Exec ( self , inPoint ):
193         """
194         This method is an implementation for the GENERICSOLVER interface.
195         It runs the component with some new parameters compared with the deterministic ones.
196         """
197         if self.case is None :
198             print "GENERICSOLVER.Exec : Init not run"
199             return 1, None
200         
201         print "GENERICSOLVER.Exec (1): inPoint  = ", inPoint
202
203         try:
204             case = dict( self.case )
205             if self.wrapperDescription != "":
206                 import sys
207                 print "sys.path = ", sys.path
208                 import openturns.wrapper
209                 wrapper = openturns.wrapper.WrapperFile.BuildWrapperFromStream( self.wrapperDescription )
210                 data = wrapper.getWrapperData()
211                 variableList = data.getVariableList()
212                 i = 0
213                 for idx in range( variableList.getSize() ):
214                     variable = variableList[ idx ]
215                     if variable.type_ == 0:
216                         print "variable %s <-> index %d" % ( variable.id_, i )
217                         case[ variable.id_ ] = inPoint[ i ]
218                         i += 1
219
220             print "Case = ", case
221             outPoint = self.BeamModel( **case )
222         except:
223             traceback.print_exc()
224             return 1, None
225          
226
227         print "GENERICSOLVER.Exec (2): inPoint  = ", inPoint
228         print "GENERICSOLVER.Exec (2): outPoint = ", outPoint
229         return 0, outPoint
230
231     def Finalize ( self ):
232         """
233         This method is an implementation for the GENERICSOLVER interface.
234         It cleans everything set so far.
235         """
236         print "GENERICSOLVER.Finalize : enter"
237         print "GENERICSOLVER.Finalize : exit"
238         return 0
239 ######################################################################
240 # This is the computation part of the GENERICSOLVER module, ie
241 # the following method realizes what the solver is intended to do.
242 # The interface of this method (and maybe other ones) is absolutely
243 # free and depends on the module (legacy interface).
244 ######################################################################
245
246     def BeamModel ( self , E=1., F=0., L=0., I=1. ):
247        """
248        This method implements a beam bending model based on the following formula:
249        deviation = ( Force * Length^3 ) / ( 3 * YoungModulus * InertiaSection )
250        """
251        d = ( F * L*L*L ) / ( 3. * E * I )
252        print "GENERICSOLVER.Exec (2): BeamModel (E=%g, F=%g, L=%g, I=%g) = %g" % (E,F,L,I,d)
253
254        return (d,)