Salome HOME
7df999a39c1362f97b8681aed4a19defefdd4090
[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("DEVIATION.__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.inputVarList = None
112         self.outputVarList = None
113         self.evalPoint = None
114
115 ######################################################################
116 # This is the Wrapper part of the GENERICSOLVER module, ie
117 # the three following methods are used by generic controlling
118 # modules like OpenTURNS in order to launch a computation.
119 # The interface is declared in GENERICSOLVER_Gen.idl. The methods
120 # are free to call the legacy interface (see below).
121 ######################################################################
122
123     def _raiseSalomeError(self):
124         message = "Error in component %s running in container %s." % (self._instanceName, self._containerName)
125         logger.exception(message)
126         message += " " + traceback.format_exc()
127         exc = SALOME.ExceptionStruct(SALOME.INTERNAL_ERROR, message,
128                                      inspect.stack()[1][1], inspect.stack()[1][2])
129         raise SALOME.SALOME_Exception(exc)
130
131     def Init(self, inputVarList, outputVarList, studyId, caseEntry):
132         """
133         This method is an example for the initialization of a computation component for
134         use with OpenTURNS in SALOME 5.1.5 and later (for YACS integration)
135         """
136         try:
137             logger.info("DEVIATION.Init: " + self._containerName +
138                         ' ; ' + self._instanceName)
139             DEVIATION.lock.acquire()
140             salome.salome_init()
141             DEVIATION.lock.release()
142
143             self.inputVarList = inputVarList
144             self.outputVarList = outputVarList
145             self.evalPoint = GetDataFromCase(studyId, caseEntry)
146             logger.debug("inputVarList: %s" % self.inputVarList)
147             logger.debug("outputVarList: %s" % self.outputVarList)
148             logger.debug("evalPoint: %s" % self.evalPoint)
149         except:
150             self._raiseSalomeError()
151
152     def Exec(self, inPoint):
153         """
154         This method is an example for the execution of a computation component for
155         use with OpenTURNS in SALOME 5.1.5 and later (for YACS integration)
156         """
157         try:
158             logger.info("DEVIATION.Exec: " + self._containerName +
159                         ' ; ' + self._instanceName)
160             if self.inputVarList is None:
161                 raise Exception("Init not run")
162             if len(inPoint) != len(self.inputVarList):
163                 raise Exception("Size mismatch between inputVarList and point to evaluate")
164
165             logger.debug("DEVIATION.Exec (1): inPoint  = %s" % inPoint)
166             for i in range(len(self.inputVarList)):
167                 self.evalPoint[self.inputVarList[i]] = inPoint[i]
168             logger.debug("evalPoint = %s" % self.evalPoint)
169
170             resDict = {}
171             resDict["dev"] = self.BeamModel(**self.evalPoint)
172
173             outPoint = []
174             for outputVar in self.outputVarList:
175                 outPoint.append(resDict[outputVar])
176             logger.debug("DEVIATION.Exec (2): outPoint = %s" % outPoint)
177             return outPoint
178         except:
179             self._raiseSalomeError()
180
181     def Finalize(self):
182         """
183         This method is an implementation for the DEVIATION interface.
184         It cleans everything set so far.
185         """
186         try:
187             logger.info("DEVIATION.Finalize: " + self._containerName + ' ; ' + self._instanceName)
188         except:
189             self._raiseSalomeError()
190         
191 ######################################################################
192 # This is the computation part of the GENERICSOLVER module, ie
193 # the following method realizes what the solver is intended to do.
194 # The interface of this method (and maybe other ones) is absolutely
195 # free and depends on the module (legacy interface).
196 ######################################################################
197
198     def BeamModel(self, E, F, L, I):
199        """
200        This method implements a beam bending model based on the following formula:
201        deviation = ( Force * Length^3 ) / ( 3 * YoungModulus * InertiaSection )
202        """
203        d = (F * L * L * L) / (3. * E * I)
204        logger.debug("DEVIATION.BeamModel (E=%g, F=%g, L=%g, I=%g) = %g" % (E, F, L, I, d))
205        return d