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