Salome HOME
Replaced tuple by dict in ExecWithVarList method
[samples/genericsolver.git] / src / GENERICSOLVER / GENERICSOLVER.py
index 6a852f477b0021af684200e9ac62d7df3dc10bcb..d7f49e95a1d700b1dc40f1857b76bbc6ab75c7dd 100644 (file)
 #  $Id$
 #
 
+import logging
+import threading
+import inspect
 import traceback
+
+import salome
 import GENERICSOLVER_ORB__POA
 import SALOME_ComponentPy
 import SALOME_DriverPy
+import SALOME
 
-from omniORB import CORBA
-from SALOME_NamingServicePy import *
-from LifeCycleCORBA import *
-import SALOMEDS
-import SALOMEDS_Attributes_idl
-
+from pal.logger import Logger
+from pal import termcolor
+logger = Logger("GENERICSOLVER", color = termcolor.BLUE_FG)
+logger.setLevel(logging.INFO)
 
 VARIABLE_ID = 1030
 
-################################################
-
-# init ORB
-orb = CORBA.ORB_init( [''], CORBA.ORB_ID )
-
-# create naming service instance
-naming_service = SALOME_NamingServicePy_i( orb )
-
-# create life cycle CORBA instance
-lcc = LifeCycleCORBA( orb )
-
-# get study manager
-obj = naming_service.Resolve( '/myStudyManager' )
-studyManager = obj._narrow( SALOMEDS.StudyManager )
-
-################################################
-###
-# get active study
-###
-def getStudy( studyId ):
-    #studyId = getStudyId()
-    study = studyManager.GetStudyByID( studyId )
-    return study
-
 ###
 # Retrieve data from selected case
 ###
 def GetDataFromCase( studyId, caseEntry ):
     theCase = {}
-    study = getStudy( studyId )
+    study = salome.myStudyManager.GetStudyByID( studyId )
     case = study.FindObjectID( caseEntry )
     builder = study.NewBuilder()
     # Get the values of the variables and make them a list
     for name in ("E", "F", "L", "I"):
         var = getSubSObjectByName( studyId, case, name )
         if var == None:
-            print "GENERICSOLVER.GetDataFromCase : ERROR! no variable '%s'" % name
+            logger.error("GENERICSOLVER.GetDataFromCase : ERROR! no variable '%s'" % name)
             break
         theCase[ name ] = getValueOfVariable( builder, var )
     return theCase
@@ -81,7 +61,7 @@ def GetDataFromCase( studyId, caseEntry ):
 # Add some variable to the case
 ###
 def AddDataToCase( studyId, caseEntry, varName, varValue ):
-    study = getStudy( studyId )
+    study = salome.myStudyManager.GetStudyByID( studyId )
     case = study.FindObjectID( caseEntry )
     builder = study.NewBuilder()
     var = addObjectInStudy( builder, case, varName, VARIABLE_ID )
@@ -125,13 +105,13 @@ def getValueOfVariable( builder, varobj ):
     return 0.
 
 def getSubSObjectByName( studyId, sobjFather, childName ):
-    print "GENERICSOLVER.getSubSObjectByName Looking for sobjet named", childName
-    study = getStudy( studyId )
+    logger.debug("GENERICSOLVER.getSubSObjectByName Looking for sobjet named " + childName)
+    study = salome.myStudyManager.GetStudyByID( studyId )
     iter = study.NewChildIterator( sobjFather )
     #builder = study.NewBuilder()
     while iter.More():
         sobj = iter.Value()
-        print "GENERICSOLVER.getSubSObjectByName Got sobjet named", sobj.GetName()
+        logger.debug("GENERICSOLVER.getSubSObjectByName Got sobjet named " + sobj.GetName())
         if sobj.GetName() == childName:
             return sobj
         iter.Next()
@@ -141,8 +121,11 @@ def getSubSObjectByName( studyId, sobjFather, childName ):
 ################################################
 
 class GENERICSOLVER(GENERICSOLVER_ORB__POA.GENERICSOLVER_Gen,
-              SALOME_ComponentPy.SALOME_ComponentPy_i,
-              SALOME_DriverPy.SALOME_DriverPy_i):
+                    SALOME_ComponentPy.SALOME_ComponentPy_i,
+                    SALOME_DriverPy.SALOME_DriverPy_i):
+    
+    lock = threading.Lock()
+    
     """
         Pour etre un composant SALOME cette classe Python
         doit avoir le nom du composant et heriter de la
@@ -152,7 +135,7 @@ class GENERICSOLVER(GENERICSOLVER_ORB__POA.GENERICSOLVER_Gen,
     """
     def __init__ ( self, orb, poa, contID, containerName, instanceName, 
                    interfaceName ):
-        print "GENERICSOLVER.__init__: ", containerName, ';', instanceName
+        logger.info("GENERICSOLVER.__init__: " + containerName + ' ; ' + instanceName)
         SALOME_ComponentPy.SALOME_ComponentPy_i.__init__(self, orb, poa,
                     contID, containerName, instanceName, interfaceName, 0)
         SALOME_DriverPy.SALOME_DriverPy_i.__init__(self, interfaceName)
@@ -170,41 +153,52 @@ class GENERICSOLVER(GENERICSOLVER_ORB__POA.GENERICSOLVER_Gen,
 # are free to call the legacy interface (see below).
 ######################################################################
 
+    def _raiseSalomeError(self):
+        message = "Error in component %s running in container %s." % (self._instanceName, self._containerName)
+        logger.exception(message)
+        message += " " + traceback.format_exc()
+        exc = SALOME.ExceptionStruct(SALOME.INTERNAL_ERROR, message,
+                                     inspect.stack()[1][1], inspect.stack()[1][2])
+        raise SALOME.SALOME_Exception(exc)
 
     def Init ( self, studyId, caseEntry, wrapperDescription ):
         """
         This method is an implementation for the GENERICSOLVER interface.
         It sets the component with some deterministic parametrization.
         """
-        print "GENERICSOLVER.Init : enter"
-        print "GENERICSOLVER.Init : studyId = %d - caseEntry = %s - wrapperDescription = %s" % ( studyId, caseEntry, wrapperDescription )
-        self.wrapperDescription = wrapperDescription
-        
         try:
+            logger.info("GENERICSOLVER.Init: " + self._containerName + ' ; ' + self._instanceName)
+            logger.debug("GENERICSOLVER.Init : enter")
+            logger.debug("GENERICSOLVER.Init : studyId = %d - caseEntry = %s - wrapperDescription = %s" % ( studyId, caseEntry, wrapperDescription ))
+            self.wrapperDescription = wrapperDescription
+            GENERICSOLVER.lock.acquire()
+            salome.salome_init()
+            GENERICSOLVER.lock.release()
+        
             self.case = GetDataFromCase( studyId, caseEntry )
+            if self.case is None:
+                return 1
+            logger.debug("GENERICSOLVER.Init : exit")
+            return 0
         except:
-            traceback.print_exc()
-        if self.case is None:
-            return 1
-        print "GENERICSOLVER.Init : exit"
-        return 0
+            self._raiseSalomeError()
 
     def Exec ( self , inPoint ):
         """
         This method is an implementation for the GENERICSOLVER interface.
         It runs the component with some new parameters compared with the deterministic ones.
         """
-        if self.case is None :
-            print "GENERICSOLVER.Exec : Init not run"
-            return 1, None
-        
-        print "GENERICSOLVER.Exec (1): inPoint  = ", inPoint
-
         try:
+            logger.info("GENERICSOLVER.Exec: " + self._containerName + ' ; ' + self._instanceName)
+            if self.case is None :
+                logger.error("GENERICSOLVER.Exec : Init not run")
+                return 1, None
+        
+            logger.debug("GENERICSOLVER.Exec (1): inPoint  = %s" % inPoint)
             case = dict( self.case )
             if self.wrapperDescription != "":
                 import sys
-                print "sys.path = ", sys.path
+                logger.debug("sys.path = %s" % sys.path)
                 import openturns.wrapper
                 wrapper = openturns.wrapper.WrapperFile.BuildWrapperFromStream( self.wrapperDescription )
                 data = wrapper.getWrapperData()
@@ -213,29 +207,35 @@ class GENERICSOLVER(GENERICSOLVER_ORB__POA.GENERICSOLVER_Gen,
                 for idx in range( variableList.getSize() ):
                     variable = variableList[ idx ]
                     if variable.type_ == 0:
-                        print "variable %s <-> index %d" % ( variable.id_, i )
+                        logger.debug("variable %s <-> index %d" % ( variable.id_, i ))
                         case[ variable.id_ ] = inPoint[ i ]
                         i += 1
 
-            print "Case = ", case
+            logger.debug("Case = %s" % case)
+            logger.info("Evaluating case by component %s in container %s" %
+                        (self._instanceName, self._containerName))
             outPoint = self.BeamModel( **case )
-        except:
-            traceback.print_exc()
-            return 1, None
-         
 
-        print "GENERICSOLVER.Exec (2): inPoint  = ", inPoint
-        print "GENERICSOLVER.Exec (2): outPoint = ", outPoint
-        return 0, outPoint
+            logger.debug("GENERICSOLVER.Exec (2): inPoint  = %s" % inPoint)
+            logger.debug("GENERICSOLVER.Exec (2): outPoint = %s" % outPoint)
+            return 0, outPoint
+
+        except:
+            self._raiseSalomeError()
 
     def Finalize ( self ):
         """
         This method is an implementation for the GENERICSOLVER interface.
         It cleans everything set so far.
         """
-        print "GENERICSOLVER.Finalize : enter"
-        print "GENERICSOLVER.Finalize : exit"
-        return 0
+        try:
+            logger.info("GENERICSOLVER.Finalize: " + self._containerName + ' ; ' + self._instanceName)
+            logger.debug("GENERICSOLVER.Finalize : enter")
+            logger.debug("GENERICSOLVER.Finalize : exit")
+            return 0
+        except:
+            self._raiseSalomeError()
+        
 ######################################################################
 # This is the computation part of the GENERICSOLVER module, ie
 # the following method realizes what the solver is intended to do.
@@ -249,6 +249,55 @@ class GENERICSOLVER(GENERICSOLVER_ORB__POA.GENERICSOLVER_Gen,
        deviation = ( Force * Length^3 ) / ( 3 * YoungModulus * InertiaSection )
        """
        d = ( F * L*L*L ) / ( 3. * E * I )
-       print "GENERICSOLVER.Exec (2): BeamModel (E=%g, F=%g, L=%g, I=%g) = %g" % (E,F,L,I,d)
+       logger.debug("GENERICSOLVER.BeamModel (E=%g, F=%g, L=%g, I=%g) = %g" % (E,F,L,I,d))
 
        return (d,)
+
+
+
+    def InitWithVarList(self, inputVarList, outputVarList, deterministicVars):
+        """
+        This method is an example for the initialization of a computation component for
+        use with OpenTURNS in SALOME 5.1.5 and later (for YACS integration)
+        """
+        try:
+            logger.info("GENERICSOLVER.InitWithVarList: " + self._containerName +
+                        ' ; ' + self._instanceName)
+            import cPickle
+            self.inputVarList = inputVarList
+            self.outputVarList = outputVarList
+            self.evalPoint = cPickle.loads(deterministicVars)
+            logger.debug("inputVarList: %s" % self.inputVarList)
+            logger.debug("outputVarList: %s" % self.outputVarList)
+            logger.debug("evalPoint: %s" % self.evalPoint)
+        except:
+            self._raiseSalomeError()
+
+    def ExecWithVarList(self, inPoint):
+        """
+        This method is an example for the execution of a computation component for
+        use with OpenTURNS in SALOME 5.1.5 and later (for YACS integration)
+        """
+        try:
+            logger.info("GENERICSOLVER.ExecWithVarList: " + self._containerName +
+                        ' ; ' + self._instanceName)
+            if self.inputVarList is None:
+                raise Exception("InitWithVarList not run")
+            if len(inPoint) != len(self.inputVarList):
+                raise Exception("Size mismatch between inputVarList and point to evaluate")
+
+            logger.debug("GENERICSOLVER.ExecWithVarList (1): inPoint  = %s" % inPoint)
+            for i in range(len(self.inputVarList)):
+                self.evalPoint[self.inputVarList[i]] = inPoint[i]
+            logger.debug("evalPoint = %s" % self.evalPoint)
+
+            resDict = {}
+            (resDict["dev"],) = self.BeamModel(**self.evalPoint)
+
+            outPoint = []
+            for outputVar in self.outputVarList:
+                outPoint.append(resDict[outputVar])
+            logger.debug("GENERICSOLVER.ExecWithVarList (2): outPoint = %s" % outPoint)
+            return outPoint
+        except:
+            self._raiseSalomeError()