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