Salome HOME
Changed the exchange types to the structure InputDescription and the sequence ValueList
[samples/genericsolver.git] / src / GENERICSOLVER / DEVIATION.py
1 #  Copyright (C) 2009-2010 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 #  $Id$
20 #
21
22 import logging
23 import threading
24 import inspect
25 import traceback
26
27 import salome
28 import GENERICSOLVER_ORB__POA
29 import SALOME_ComponentPy
30 import SALOME_DriverPy
31 import SALOME
32
33 from pal.logger import Logger
34 from pal import termcolor
35 logger = Logger("DEVIATION", color = termcolor.RED_FG)
36 logger.setLevel(logging.INFO)
37
38 VARIABLE_ID = 1030
39
40 ###
41 # Retrieve data from selected case
42 ###
43 def GetDataFromCase( studyId, caseEntry ):
44     theCase = {}
45     study = salome.myStudyManager.GetStudyByID( studyId )
46     case = study.FindObjectID( caseEntry )
47     builder = study.NewBuilder()
48     # Get the values of the variables and make them a list
49     for name in ("E", "F", "L", "I"):
50         var = getSubSObjectByName( studyId, case, name )
51         if var is None:
52             raise Exception('No variable "%s" was found in case "%s" (entry %s). '
53                             'It is probably not a case for the code DEVIATION.' %
54                             (name, case.GetName(), caseEntry))
55         theCase[ name ] = getValueOfVariable( builder, var )
56     return theCase
57
58 ###
59 # Plays with study
60 ###
61
62 def getValueOfVariable( builder, varobj ):
63     attr = builder.FindOrCreateAttribute( varobj, "AttributeLocalID" )
64     objid = attr.Value()
65     if (objid == VARIABLE_ID):
66         attr = builder.FindOrCreateAttribute( varobj, "AttributeReal" )
67         return attr.Value()
68     else:
69         attr = builder.FindOrCreateAttribute( varobj, "AttributeName" )
70         QMessageBox.information( sgPyQt.getDesktop(), 'Info', "Object '%s' isn't a variable. Can't set value." % attr.Value() )
71     return 0.
72
73 def getSubSObjectByName( studyId, sobjFather, childName ):
74     logger.debug("GENERICSOLVER.getSubSObjectByName Looking for sobjet named " + childName)
75     study = salome.myStudyManager.GetStudyByID( studyId )
76     iter = study.NewChildIterator( sobjFather )
77     #builder = study.NewBuilder()
78     while iter.More():
79         sobj = iter.Value()
80         logger.debug("GENERICSOLVER.getSubSObjectByName Got sobjet named " + sobj.GetName())
81         if sobj.GetName() == childName:
82             return sobj
83         iter.Next()
84         pass
85     return None
86
87 ################################################
88
89 class DEVIATION(GENERICSOLVER_ORB__POA.DEVIATION_Gen,
90                 SALOME_ComponentPy.SALOME_ComponentPy_i,
91                 SALOME_DriverPy.SALOME_DriverPy_i):
92     
93     lock = threading.Lock()
94     
95     """
96         Pour etre un composant SALOME cette classe Python
97         doit avoir le nom du composant et heriter de la
98         classe DEVIATION_Gen issue de la compilation de l'idl
99         par omniidl et de la classe SALOME_ComponentPy_i
100         qui porte les services generaux d'un composant SALOME
101     """
102     def __init__ ( self, orb, poa, contID, containerName, instanceName, 
103                    interfaceName ):
104         logger.info("__init__: " + containerName + ' ; ' + instanceName)
105         SALOME_ComponentPy.SALOME_ComponentPy_i.__init__(self, orb, poa,
106                     contID, containerName, instanceName, interfaceName, 0)
107         SALOME_DriverPy.SALOME_DriverPy_i.__init__(self, interfaceName)
108         # On stocke dans l'attribut _naming_service, une reference sur
109         # le Naming Service CORBA
110         self._naming_service = SALOME_ComponentPy.SALOME_NamingServicePy_i( self._orb )
111         self.deterministicValues = {}
112
113 ######################################################################
114 # This is the Wrapper part of the GENERICSOLVER module, ie
115 # the three following methods are used by generic controlling
116 # modules like OpenTURNS in order to launch a computation.
117 # The interface is declared in GENERICSOLVER_Gen.idl. The methods
118 # are free to call the legacy interface (see below).
119 ######################################################################
120
121     def _raiseSalomeError(self):
122         message = "Error in component %s running in container %s." % (self._instanceName, self._containerName)
123         logger.exception(message)
124         message += " " + traceback.format_exc()
125         exc = SALOME.ExceptionStruct(SALOME.INTERNAL_ERROR, message,
126                                      inspect.stack()[1][1], inspect.stack()[1][2])
127         raise SALOME.SALOME_Exception(exc)
128
129     def Init(self, studyId, caseEntry):
130         """
131         This method is an example for the initialization of a computation component for
132         use with OpenTURNS in SALOME 5.1.5 and later (for YACS integration)
133         """
134         try:
135             logger.info("Init: " + self._containerName + ' ; ' + self._instanceName)
136             DEVIATION.lock.acquire()
137             salome.salome_init()
138             DEVIATION.lock.release()
139
140             self.deterministicValues = GetDataFromCase(studyId, caseEntry)
141             logger.debug("deterministic values: %s" % self.deterministicValues)
142         except:
143             self._raiseSalomeError()
144
145     def Exec(self, inputDesc):
146         """
147         This method is an example for the execution of a computation component for
148         use with OpenTURNS in SALOME 5.1.5 and later (for YACS integration)
149         """
150         try:
151             logger.info("Exec: " + self._containerName + ' ; ' + self._instanceName)
152             logger.debug("inputVarList: %s" % inputDesc.inputVarList)
153             logger.debug("outputVarList: %s" % inputDesc.outputVarList)
154             logger.debug("inputValues: %s" % inputDesc.inputValues)
155             if len(inputDesc.inputValues) != len(inputDesc.inputVarList):
156                 raise Exception("Size mismatch between inputVarList and point to evaluate")
157
158             evalPoint = self.deterministicValues
159             for i in range(len(inputDesc.inputVarList)):
160                 evalPoint[inputDesc.inputVarList[i]] = inputDesc.inputValues[i][0]
161             logger.debug("evalPoint = %s" % evalPoint)
162
163             resDict = {}
164             resDict["dev"] = self.BeamModel(**evalPoint)
165
166             outputValues = []
167             for outputVar in inputDesc.outputVarList:
168                 outputValues.append([resDict[outputVar]])
169             logger.debug("outputValues: %s" % outputValues)
170             return outputValues
171         except:
172             self._raiseSalomeError()
173
174     def Finalize(self):
175         """
176         This method is an implementation for the DEVIATION interface.
177         It cleans everything set so far.
178         """
179         try:
180             logger.info("Finalize: " + self._containerName + ' ; ' + self._instanceName)
181         except:
182             self._raiseSalomeError()
183         
184 ######################################################################
185 # This is the computation part of the GENERICSOLVER module, ie
186 # the following method realizes what the solver is intended to do.
187 # The interface of this method (and maybe other ones) is absolutely
188 # free and depends on the module (legacy interface).
189 ######################################################################
190
191     def BeamModel(self, E, F, L, I):
192        """
193        This method implements a beam bending model based on the following formula:
194        deviation = ( Force * Length^3 ) / ( 3 * YoungModulus * InertiaSection )
195        """
196        d = (F * L * L * L) / (3. * E * I)
197        logger.debug("BeamModel (E=%g, F=%g, L=%g, I=%g) = %g" % (E, F, L, I, d))
198        return d