Salome HOME
Documentation and reporting improvements
[modules/adao.git] / src / daComposant / daAlgorithms / DerivativeFreeOptimization.py
index e9d9a5f0a33f4e2f491183f866ae77d6ea4ce4c6..78e2a3068b523be0d209d628dc0ec5e656ce6547 100644 (file)
@@ -1,6 +1,6 @@
-#-*-coding:iso-8859-1-*-
+# -*- coding: utf-8 -*-
 #
-# Copyright (C) 2008-2017 EDF R&D
+# Copyright (C) 2008-2021 EDF R&D
 #
 # This library is free software; you can redistribute it and/or
 # modify it under the terms of the GNU Lesser General Public
@@ -32,8 +32,15 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
             name     = "Minimizer",
             default  = "BOBYQA",
             typecast = str,
-            message  = "Minimiseur utilisé",
-            listval  = ["BOBYQA", "COBYLA", "NEWUOA", "POWELL", "SIMPLEX", "SUBPLEX"],
+            message  = "Minimiseur utilisé",
+            listval  = [
+                "BOBYQA",
+                "COBYLA",
+                "NEWUOA",
+                "POWELL",
+                "SIMPLEX",
+                "SUBPLEX",
+                ],
             )
         self.defineRequiredParameter(
             name     = "MaximumNumberOfSteps",
@@ -46,26 +53,26 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
             name     = "MaximumNumberOfFunctionEvaluations",
             default  = 15000,
             typecast = int,
-            message  = "Nombre maximal d'évaluations de la fonction",
+            message  = "Nombre maximal d'évaluations de la fonction",
             minval   = -1,
             )
         self.defineRequiredParameter(
             name     = "StateVariationTolerance",
             default  = 1.e-4,
             typecast = float,
-            message  = "Variation relative maximale de l'état lors de l'arrêt",
+            message  = "Variation relative maximale de l'état lors de l'arrêt",
             )
         self.defineRequiredParameter(
             name     = "CostDecrementTolerance",
             default  = 1.e-7,
             typecast = float,
-            message  = "Diminution relative minimale du cout lors de l'arrêt",
+            message  = "Diminution relative minimale du cout lors de l'arrêt",
             )
         self.defineRequiredParameter(
             name     = "QualityCriterion",
             default  = "AugmentedWeightedLeastSquares",
             typecast = str,
-            message  = "Critère de qualité utilisé",
+            message  = "Critère de qualité utilisé",
             listval  = ["AugmentedWeightedLeastSquares","AWLS","DA",
                         "WeightedLeastSquares","WLS",
                         "LeastSquares","LS","L2",
@@ -76,36 +83,66 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
             name     = "StoreInternalVariables",
             default  = False,
             typecast = bool,
-            message  = "Stockage des variables internes ou intermédiaires du calcul",
+            message  = "Stockage des variables internes ou intermédiaires du calcul",
             )
         self.defineRequiredParameter(
             name     = "StoreSupplementaryCalculations",
             default  = [],
             typecast = tuple,
-            message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
-            listval  = ["CurrentState", "CostFunctionJ", "CostFunctionJb", "CostFunctionJo", "CostFunctionJAtCurrentOptimum", "CurrentOptimum", "IndexOfOptimum", "InnovationAtCurrentState", "BMA", "OMA", "OMB", "SimulatedObservationAtBackground", "SimulatedObservationAtCurrentOptimum", "SimulatedObservationAtCurrentState", "SimulatedObservationAtOptimum"]
+            message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
+            listval  = [
+                "Analysis",
+                "BMA",
+                "CostFunctionJ",
+                "CostFunctionJb",
+                "CostFunctionJo",
+                "CostFunctionJAtCurrentOptimum",
+                "CostFunctionJbAtCurrentOptimum",
+                "CostFunctionJoAtCurrentOptimum",
+                "CurrentIterationNumber",
+                "CurrentOptimum",
+                "CurrentState",
+                "IndexOfOptimum",
+                "Innovation",
+                "InnovationAtCurrentState",
+                "OMA",
+                "OMB",
+                "SimulatedObservationAtBackground",
+                "SimulatedObservationAtCurrentOptimum",
+                "SimulatedObservationAtCurrentState",
+                "SimulatedObservationAtOptimum",
+                ]
             )
         self.defineRequiredParameter( # Pas de type
             name     = "Bounds",
             message  = "Liste des valeurs de bornes",
             )
+        self.requireInputArguments(
+            mandatory= ("Xb", "Y", "HO", "R", "B" ),
+            )
+        self.setAttributes(tags=(
+            "Optimization",
+            "NonLinear",
+            "MetaHeuristic",
+            ))
 
     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
-        self._pre_run(Parameters)
+        self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
         #
         if not PlatformInfo.has_nlopt and not self._parameters["Minimizer"] in ["COBYLA", "POWELL", "SIMPLEX"]:
+            logging.warning("%s Minimization by SIMPLEX is forced because %s is unavailable (COBYLA, POWELL are also available)"%(self._name,self._parameters["Minimizer"]))
             self._parameters["Minimizer"] = "SIMPLEX"
         #
-        # Opérateurs
+        # Opérateurs
         # ----------
         Hm = HO["Direct"].appliedTo
         #
-        # Précalcul des inversions de B et R
+        # Précalcul des inversions de B et R
         # ----------------------------------
         BI = B.getI()
         RI = R.getI()
         #
-        # Définition de la fonction-coût
+        # Définition de la fonction-coût
         # ------------------------------
         def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
             _X  = numpy.asmatrix(numpy.ravel( x )).T
@@ -113,10 +150,10 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
             _HX = Hm( _X )
             _HX = numpy.asmatrix(numpy.ravel( _HX )).T
             _Innovation = Y - _HX
-            if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"] or \
-               "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
+            if self._toStore("SimulatedObservationAtCurrentState") or \
+                self._toStore("SimulatedObservationAtCurrentOptimum"):
                 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
-            if "InnovationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
+            if self._toStore("InnovationAtCurrentState"):
                 self.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
             #
             if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","DA"]:
@@ -141,27 +178,32 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
             #
             J   = float( Jb ) + float( Jo )
             #
+            self.StoredVariables["CurrentIterationNumber"].store( len(self.StoredVariables["CostFunctionJ"]) )
             self.StoredVariables["CostFunctionJb"].store( Jb )
             self.StoredVariables["CostFunctionJo"].store( Jo )
             self.StoredVariables["CostFunctionJ" ].store( J )
-            if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
-               "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
-               "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
-               "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
+            if self._toStore("IndexOfOptimum") or \
+                self._toStore("CurrentOptimum") or \
+                self._toStore("CostFunctionJAtCurrentOptimum") or \
+                self._toStore("CostFunctionJbAtCurrentOptimum") or \
+                self._toStore("CostFunctionJoAtCurrentOptimum") or \
+                self._toStore("SimulatedObservationAtCurrentOptimum"):
                 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
-            if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"]:
+            if self._toStore("IndexOfOptimum"):
                 self.StoredVariables["IndexOfOptimum"].store( IndexMin )
-            if "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
+            if self._toStore("CurrentOptimum"):
                 self.StoredVariables["CurrentOptimum"].store( self.StoredVariables["CurrentState"][IndexMin] )
-            if "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
+            if self._toStore("SimulatedObservationAtCurrentOptimum"):
                 self.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] )
-            if "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
+            if self._toStore("CostFunctionJAtCurrentOptimum"):
+                self.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( self.StoredVariables["CostFunctionJ" ][IndexMin] )
+            if self._toStore("CostFunctionJbAtCurrentOptimum"):
                 self.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJb"][IndexMin] )
+            if self._toStore("CostFunctionJoAtCurrentOptimum"):
                 self.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJo"][IndexMin] )
-                self.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( self.StoredVariables["CostFunctionJ" ][IndexMin] )
             return J
         #
-        # Point de démarrage de l'optimisation : Xini = Xb
+        # Point de démarrage de l'optimisation : Xini = Xb
         # ------------------------------------
         Xini = numpy.ravel(Xb)
         if len(Xini) < 2 and self._parameters["Minimizer"] == "NEWUOA":
@@ -350,26 +392,30 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
         #
         self.StoredVariables["Analysis"].store( Xa.A1 )
         #
-        if "OMA"                           in self._parameters["StoreSupplementaryCalculations"] or \
-           "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
-            if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
+        # Calculs et/ou stockages supplémentaires
+        # ---------------------------------------
+        if self._toStore("OMA" ) or \
+            self._toStore("SimulatedObservationAtOptimum"):
+            if self._toStore("SimulatedObservationAtCurrentState"):
                 HXa = self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
-            elif "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
+            elif self._toStore("SimulatedObservationAtCurrentOptimum"):
                 HXa = self.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
             else:
                 HXa = Hm(Xa)
-        #
-        if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
+        if self._toStore("Innovation") or \
+            self._toStore("OMB"):
+            d  = Y - HXb
+        if self._toStore("Innovation"):
             self.StoredVariables["Innovation"].store( numpy.ravel(d) )
-        if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
+        if self._toStore("OMB"):
             self.StoredVariables["OMB"].store( numpy.ravel(d) )
-        if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
+        if self._toStore("BMA"):
             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
-        if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
+        if self._toStore("OMA"):
             self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
-        if "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
+        if self._toStore("SimulatedObservationAtBackground"):
             self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(Hm(Xb)) )
-        if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
+        if self._toStore("SimulatedObservationAtOptimum"):
             self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
         #
         self._post_run()
@@ -377,4 +423,4 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
 
 # ==============================================================================
 if __name__ == "__main__":
-    print('\n AUTODIAGNOSTIC \n')
+    print('\n AUTODIAGNOSTIC\n')