Salome HOME
Minor documentation and code review corrections (25)
[modules/adao.git] / src / daComposant / daCore / BasicObjects.py
index 3b6b0d5ae74a4fc8333930c71e85c55c20c96a4c..d4b9a27e279fdf9aa50ac02ae15fed6a941b9983 100644 (file)
@@ -625,6 +625,7 @@ class Algorithm(object):
             - CurrentIterationNumber : numéro courant d'itération dans les algorithmes itératifs, à partir de 0
             - CurrentOptimum : état optimal courant lors d'itérations
             - CurrentState : état courant lors d'itérations
+            - CurrentStepNumber : numéro courant de pas de mesure dans les algorithmes temporels
             - GradientOfCostFunctionJ  : gradient de la fonction-coût globale
             - GradientOfCostFunctionJb : gradient de la partie ébauche de la fonction-coût
             - GradientOfCostFunctionJo : gradient de la partie observations de la fonction-coût
@@ -684,6 +685,7 @@ class Algorithm(object):
         self.StoredVariables["CurrentIterationNumber"]               = Persistence.OneIndex(name  = "CurrentIterationNumber")
         self.StoredVariables["CurrentOptimum"]                       = Persistence.OneVector(name = "CurrentOptimum")
         self.StoredVariables["CurrentState"]                         = Persistence.OneVector(name = "CurrentState")
+        self.StoredVariables["CurrentStepNumber"]                    = Persistence.OneIndex(name  = "CurrentStepNumber")
         self.StoredVariables["ForecastCovariance"]                   = Persistence.OneMatrix(name = "ForecastCovariance")
         self.StoredVariables["ForecastState"]                        = Persistence.OneVector(name = "ForecastState")
         self.StoredVariables["GradientOfCostFunctionJ"]              = Persistence.OneVector(name = "GradientOfCostFunctionJ")
@@ -827,18 +829,10 @@ class Algorithm(object):
         # Verbosité et logging
         if logging.getLogger().level < logging.WARNING:
             self._parameters["optiprint"], self._parameters["optdisp"] = 1, 1
-            if PlatformInfo.has_scipy:
-                import scipy.optimize
-                self._parameters["optmessages"] = scipy.optimize.tnc.MSG_ALL
-            else:
-                self._parameters["optmessages"] = 15
+            self._parameters["optmessages"] = 15
         else:
             self._parameters["optiprint"], self._parameters["optdisp"] = -1, 0
-            if PlatformInfo.has_scipy:
-                import scipy.optimize
-                self._parameters["optmessages"] = scipy.optimize.tnc.MSG_NONE
-            else:
-                self._parameters["optmessages"] = 15
+            self._parameters["optmessages"] = 0
         #
         return 0
 
@@ -1094,6 +1088,7 @@ class PartialAlgorithm(object):
         self.StoredVariables["CostFunctionJb"]                       = Persistence.OneScalar(name = "CostFunctionJb")
         self.StoredVariables["CostFunctionJo"]                       = Persistence.OneScalar(name = "CostFunctionJo")
         self.StoredVariables["CurrentIterationNumber"]               = Persistence.OneIndex(name  = "CurrentIterationNumber")
+        self.StoredVariables["CurrentStepNumber"]                    = Persistence.OneIndex(name  = "CurrentStepNumber")
         #
         self.__canonical_stored_name = {}
         for k in self.StoredVariables:
@@ -1769,7 +1764,6 @@ class State(object):
         elif __Series is not None:
             self.__is_series  = True
             if isinstance(__Series, (tuple, list, numpy.ndarray, numpy.matrix, str)):
-                #~ self.__V = Persistence.OneVector(self.__name, basetype=numpy.matrix)
                 self.__V = Persistence.OneVector(self.__name)
                 if isinstance(__Series, str):
                     __Series = PlatformInfo.strmatrix2liststr(__Series)
@@ -1925,12 +1919,12 @@ class Covariance(object):
             raise ValueError("The \"%s\" covariance matrix is not positive-definite. Please check your vector input."%(self.__name,))
         if self.ismatrix() and (self.__check or logging.getLogger().level < logging.WARNING):
             try:
-                L = numpy.linalg.cholesky( self.__C )
+                numpy.linalg.cholesky( self.__C )
             except:
                 raise ValueError("The %s covariance matrix is not symmetric positive-definite. Please check your matrix input."%(self.__name,))
         if self.isobject() and (self.__check or logging.getLogger().level < logging.WARNING):
             try:
-                L = self.__C.cholesky()
+                self.__C.cholesky()
             except:
                 raise ValueError("The %s covariance object is not symmetric positive-definite. Please check your matrix input."%(self.__name,))
 
@@ -2099,7 +2093,10 @@ class Covariance(object):
             return self.__C + numpy.asmatrix(other)
         elif self.isvector() or self.isscalar():
             _A = numpy.asarray(other)
-            _A.reshape(_A.size)[::_A.shape[1]+1] += self.__C
+            if len(_A.shape) == 1:
+                _A.reshape((-1,1))[::2] += self.__C
+            else:
+                _A.reshape(_A.size)[::_A.shape[1]+1] += self.__C
             return numpy.asmatrix(_A)
 
     def __radd__(self, other):
@@ -2340,7 +2337,6 @@ def MultiFonction(
     if __mpEnabled:
         _jobs = __xserie
         # logging.debug("MULTF Internal multiprocessing calculations begin : evaluation of %i point(s)"%(len(_jobs),))
-        import multiprocessing
         with multiprocessing.Pool(__mpWorkers) as pool:
             __multiHX = pool.map( _sFunction, _jobs )
             pool.close()
@@ -2365,121 +2361,6 @@ def MultiFonction(
     # logging.debug("MULTF Internal multifonction calculations end")
     return __multiHX
 
-# ==============================================================================
-def CostFunction3D(_x,
-                   _Hm  = None,  # Pour simuler Hm(x) : HO["Direct"].appliedTo
-                   _HmX = None,  # Simulation déjà faite de Hm(x)
-                   _arg = None,  # Arguments supplementaires pour Hm, sous la forme d'un tuple
-                   _BI  = None,
-                   _RI  = None,
-                   _Xb  = None,
-                   _Y   = None,
-                   _SIV = False, # A résorber pour la 8.0
-                   _SSC = [],    # self._parameters["StoreSupplementaryCalculations"]
-                   _nPS = 0,     # nbPreviousSteps
-                   _QM  = "DA",  # QualityMeasure
-                   _SSV = {},    # Entrée et/ou sortie : self.StoredVariables
-                   _fRt = False, # Restitue ou pas la sortie étendue
-                   _sSc = True,  # Stocke ou pas les SSC
-                  ):
-    """
-    Fonction-coût générale utile pour les algorithmes statiques/3D : 3DVAR, BLUE
-    et dérivés, Kalman et dérivés, LeastSquares, SamplingTest, PSO, SA, Tabu,
-    DFO, QuantileRegression
-    """
-    if not _sSc:
-        _SIV = False
-        _SSC = {}
-    else:
-        for k in ["CostFunctionJ",
-                  "CostFunctionJb",
-                  "CostFunctionJo",
-                  "CurrentOptimum",
-                  "CurrentState",
-                  "IndexOfOptimum",
-                  "SimulatedObservationAtCurrentOptimum",
-                  "SimulatedObservationAtCurrentState",
-                 ]:
-            if k not in _SSV:
-                _SSV[k] = []
-            if hasattr(_SSV[k],"store"):
-                _SSV[k].append = _SSV[k].store # Pour utiliser "append" au lieu de "store"
-    #
-    _X  = numpy.asmatrix(numpy.ravel( _x )).T
-    if _SIV or "CurrentState" in _SSC or "CurrentOptimum" in _SSC:
-        _SSV["CurrentState"].append( _X )
-    #
-    if _HmX is not None:
-        _HX = _HmX
-    else:
-        if _Hm is None:
-            raise ValueError("COSTFUNCTION3D Operator has to be defined.")
-        if _arg is None:
-            _HX = _Hm( _X )
-        else:
-            _HX = _Hm( _X, *_arg )
-    _HX = numpy.asmatrix(numpy.ravel( _HX )).T
-    #
-    if "SimulatedObservationAtCurrentState" in _SSC or \
-       "SimulatedObservationAtCurrentOptimum" in _SSC:
-        _SSV["SimulatedObservationAtCurrentState"].append( _HX )
-    #
-    if numpy.any(numpy.isnan(_HX)):
-        Jb, Jo, J = numpy.nan, numpy.nan, numpy.nan
-    else:
-        _Y   = numpy.asmatrix(numpy.ravel( _Y )).T
-        if _QM in ["AugmentedWeightedLeastSquares", "AWLS", "AugmentedPonderatedLeastSquares", "APLS", "DA"]:
-            if _BI is None or _RI is None:
-                raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
-            _Xb  = numpy.asmatrix(numpy.ravel( _Xb )).T
-            Jb  = 0.5 * (_X - _Xb).T * _BI * (_X - _Xb)
-            Jo  = 0.5 * (_Y - _HX).T * _RI * (_Y - _HX)
-        elif _QM in ["WeightedLeastSquares", "WLS", "PonderatedLeastSquares", "PLS"]:
-            if _RI is None:
-                raise ValueError("Observation error covariance matrix has to be properly defined!")
-            Jb  = 0.
-            Jo  = 0.5 * (_Y - _HX).T * _RI * (_Y - _HX)
-        elif _QM in ["LeastSquares", "LS", "L2"]:
-            Jb  = 0.
-            Jo  = 0.5 * (_Y - _HX).T * (_Y - _HX)
-        elif _QM in ["AbsoluteValue", "L1"]:
-            Jb  = 0.
-            Jo  = numpy.sum( numpy.abs(_Y - _HX) )
-        elif _QM in ["MaximumError", "ME"]:
-            Jb  = 0.
-            Jo  = numpy.max( numpy.abs(_Y - _HX) )
-        elif _QM in ["QR", "Null"]:
-            Jb  = 0.
-            Jo  = 0.
-        else:
-            raise ValueError("Unknown asked quality measure!")
-        #
-        J   = float( Jb ) + float( Jo )
-    #
-    if _sSc:
-        _SSV["CostFunctionJb"].append( Jb )
-        _SSV["CostFunctionJo"].append( Jo )
-        _SSV["CostFunctionJ" ].append( J )
-    #
-    if "IndexOfOptimum" in _SSC or \
-       "CurrentOptimum" in _SSC or \
-       "SimulatedObservationAtCurrentOptimum" in _SSC:
-        IndexMin = numpy.argmin( _SSV["CostFunctionJ"][_nPS:] ) + _nPS
-    if "IndexOfOptimum" in _SSC:
-        _SSV["IndexOfOptimum"].append( IndexMin )
-    if "CurrentOptimum" in _SSC:
-        _SSV["CurrentOptimum"].append( _SSV["CurrentState"][IndexMin] )
-    if "SimulatedObservationAtCurrentOptimum" in _SSC:
-        _SSV["SimulatedObservationAtCurrentOptimum"].append( _SSV["SimulatedObservationAtCurrentState"][IndexMin] )
-    #
-    if _fRt:
-        return _SSV
-    else:
-        if _QM in ["QR"]: # Pour le QuantileRegression
-            return _HX
-        else:
-            return J
-
 # ==============================================================================
 if __name__ == "__main__":
     print('\n AUTODIAGNOSTIC\n')