Salome HOME
Updating copyright date information
[modules/adao.git] / src / daComposant / daAlgorithms / LinearityTest.py
index 27dc0d984561abdd048dd1504b8814e20694015c..144b791f3811f86afb5a0a2d8fd6e291eb6fbcd2 100644 (file)
@@ -1,34 +1,33 @@
 #-*-coding:iso-8859-1-*-
 #
-#  Copyright (C) 2008-2014 EDF R&D
+# Copyright (C) 2008-2017 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
-#  License as published by the Free Software Foundation; either
-#  version 2.1 of the License.
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
 #
-#  This library is distributed in the hope that it will be useful,
-#  but WITHOUT ANY WARRANTY; without even the implied warranty of
-#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-#  Lesser General Public License for more details.
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# Lesser General Public License for more details.
 #
-#  You should have received a copy of the GNU Lesser General Public
-#  License along with this library; if not, write to the Free Software
-#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 #
-#  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 #
-#  Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
 
 import logging
-from daCore import BasicObjects, PlatformInfo
-m = PlatformInfo.SystemUsage()
+from daCore import BasicObjects
 import numpy, math
 
 # ==============================================================================
 class ElementaryAlgorithm(BasicObjects.Algorithm):
     def __init__(self):
-        BasicObjects.Algorithm.__init__(self, "FUNCTIONTEST")
+        BasicObjects.Algorithm.__init__(self, "LINEARITYTEST")
         self.defineRequiredParameter(
             name     = "ResiduFormula",
             default  = "CenteredDL",
@@ -56,6 +55,14 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
             typecast = float,
             message  = "Amplitude de la direction initiale de la dérivée directionnelle autour du point nominal",
             )
+        self.defineRequiredParameter(
+            name     = "AmplitudeOfTangentPerturbation",
+            default  = 1.e-2,
+            typecast = float,
+            message  = "Amplitude de la perturbation pour le calcul de la forme tangente",
+            minval   = 1.e-10,
+            maxval   = 1.,
+            )
         self.defineRequiredParameter(
             name     = "SetSeed",
             typecast = numpy.random.seed,
@@ -67,10 +74,16 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
             typecast = str,
             message  = "Titre du tableau et de la figure",
             )
+        self.defineRequiredParameter(
+            name     = "StoreSupplementaryCalculations",
+            default  = [],
+            typecast = tuple,
+            message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
+            listval  = ["CurrentState", "Residu", "SimulatedObservationAtCurrentState"]
+            )
 
     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
-        logging.debug("%s Lancement"%self._name)
-        logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
+        self._pre_run()
         #
         # Paramètres de pilotage
         # ----------------------
@@ -97,6 +110,10 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
         FX      = numpy.asmatrix(numpy.ravel( Hm( Xn ) )).T
         NormeX  = numpy.linalg.norm( Xn )
         NormeFX = numpy.linalg.norm( FX )
+        if "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
+            self.StoredVariables["CurrentState"].store( numpy.ravel(Xn) )
+        if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
+            self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(FX) )
         #
         # Fabrication de la direction de  l'incrément dX
         # ----------------------------------------------
@@ -115,16 +132,18 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
         # Calcul du gradient au point courant X pour l'incrément dX
         # ---------------------------------------------------------
         if self._parameters["ResiduFormula"] in ["Taylor", "NominalTaylor", "NominalTaylorRMS"]:
-            GradFxdX = Ht( (Xn, dX0) )
+            dX1      = float(self._parameters["AmplitudeOfTangentPerturbation"]) * dX0
+            GradFxdX = Ht( (Xn, dX1) )
             GradFxdX = numpy.asmatrix(numpy.ravel( GradFxdX )).T
+            GradFxdX = float(1./self._parameters["AmplitudeOfTangentPerturbation"]) * GradFxdX
         #
         # Entete des resultats
         # --------------------
         __marge =  12*" "
         if self._parameters["ResiduFormula"] == "CenteredDL":
-            __entete = "  i   Alpha     ||X||      ||F(X)||   |   R(Alpha)   log( R )  "
+            __entete = "  i   Alpha     ||X||      ||F(X)||   |   R(Alpha)  log10( R )  "
             __msgdoc = """
-            On observe le residu provenant de la différence centrée des valeurs de F
+            On observe le résidu provenant de la différence centrée des valeurs de F
             au point nominal et aux points perturbés, normalisée par la valeur au
             point nominal :
 
@@ -140,15 +159,15 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
             de F n'est pas vérifiée.
 
             Si le résidu décroit et que la décroissance se fait en Alpha**2 selon Alpha,
-            cela signifie que le gradient est bien calculé jusqu'à la précision d'arrêt
+            cela signifie que le gradient est calculable jusqu'à la précision d'arrêt
             de la décroissance quadratique.
 
             On prend dX0 = Normal(0,X) et dX = Alpha*dX0. F est le code de calcul.
             """
         if self._parameters["ResiduFormula"] == "Taylor":
-            __entete = "  i   Alpha     ||X||      ||F(X)||   |   R(Alpha)   log( R )  "
+            __entete = "  i   Alpha     ||X||      ||F(X)||   |   R(Alpha)  log10( R )  "
             __msgdoc = """
-            On observe le residu issu du développement de Taylor de la fonction F,
+            On observe le résidu issu du développement de Taylor de la fonction F,
             normalisée par la valeur au point nominal :
 
                          || F(X+Alpha*dX) - F(X) - Alpha * GradientF_X(dX) ||
@@ -164,14 +183,14 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
 
             Si le résidu décroit et que la décroissance se fait en Alpha**2 selon Alpha,
             cela signifie que le gradient est bien calculé jusqu'à la précision d'arrêt
-            de la décroissance.
+            de la décroissance quadratique.
 
             On prend dX0 = Normal(0,X) et dX = Alpha*dX0. F est le code de calcul.
             """
         if self._parameters["ResiduFormula"] == "NominalTaylor":
             __entete = "  i   Alpha     ||X||      ||F(X)||   |   R(Alpha)   |R-1| en %  "
             __msgdoc = """
-            On observe le residu obtenu à partir de deux approximations d'ordre 1 de F(X),
+            On observe le résidu obtenu à partir de deux approximations d'ordre 1 de F(X),
             normalisées par la valeur au point nominal :
 
               R(Alpha) = max(
@@ -192,7 +211,7 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
         if self._parameters["ResiduFormula"] == "NominalTaylorRMS":
             __entete = "  i   Alpha     ||X||      ||F(X)||   |   R(Alpha)    |R| en %  "
             __msgdoc = """
-            On observe le residu obtenu à partir de deux approximations d'ordre 1 de F(X),
+            On observe le résidu obtenu à partir de deux approximations d'ordre 1 de F(X),
             normalisées par la valeur au point nominal :
 
               R(Alpha) = max(
@@ -230,50 +249,84 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
             dX      = amplitude * dX0
             #
             if self._parameters["ResiduFormula"] == "CenteredDL":
+                if "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
+                    self.StoredVariables["CurrentState"].store( numpy.ravel(Xn + dX) )
+                    self.StoredVariables["CurrentState"].store( numpy.ravel(Xn - dX) )
+                #
                 FX_plus_dX  = numpy.asmatrix(numpy.ravel( Hm( Xn + dX ) )).T
                 FX_moins_dX = numpy.asmatrix(numpy.ravel( Hm( Xn - dX ) )).T
                 #
+                if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
+                    self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(FX_plus_dX) )
+                    self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(FX_moins_dX) )
+                #
                 Residu = numpy.linalg.norm( FX_plus_dX + FX_moins_dX - 2 * FX ) / NormeFX
                 #
-                self.StoredVariables["CostFunctionJ"].store( Residu )
+                self.StoredVariables["Residu"].store( Residu )
                 msg = "  %2i  %5.0e   %9.3e   %9.3e   |   %9.3e   %4.0f"%(i,amplitude,NormeX,NormeFX,Residu,math.log10(max(1.e-99,Residu)))
                 msgs += "\n" + __marge + msg
             #
             if self._parameters["ResiduFormula"] == "Taylor":
+                if "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
+                    self.StoredVariables["CurrentState"].store( numpy.ravel(Xn + dX) )
+                #
                 FX_plus_dX  = numpy.asmatrix(numpy.ravel( Hm( Xn + dX ) )).T
                 #
+                if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
+                    self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(FX_plus_dX) )
+                #
                 Residu = numpy.linalg.norm( FX_plus_dX - FX - amplitude * GradFxdX ) / NormeFX
                 #
-                self.StoredVariables["CostFunctionJ"].store( Residu )
+                self.StoredVariables["Residu"].store( Residu )
                 msg = "  %2i  %5.0e   %9.3e   %9.3e   |   %9.3e   %4.0f"%(i,amplitude,NormeX,NormeFX,Residu,math.log10(max(1.e-99,Residu)))
                 msgs += "\n" + __marge + msg
             #
             if self._parameters["ResiduFormula"] == "NominalTaylor":
+                if "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
+                    self.StoredVariables["CurrentState"].store( numpy.ravel(Xn + dX) )
+                    self.StoredVariables["CurrentState"].store( numpy.ravel(Xn - dX) )
+                    self.StoredVariables["CurrentState"].store( numpy.ravel(dX) )
+                #
                 FX_plus_dX  = numpy.asmatrix(numpy.ravel( Hm( Xn + dX ) )).T
                 FX_moins_dX = numpy.asmatrix(numpy.ravel( Hm( Xn - dX ) )).T
                 FdX         = numpy.asmatrix(numpy.ravel( Hm( dX ) )).T
                 #
+                if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
+                    self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(FX_plus_dX) )
+                    self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(FX_moins_dX) )
+                    self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(FdX) )
+                #
                 Residu = max(
                     numpy.linalg.norm( FX_plus_dX  - amplitude * FdX ) / NormeFX,
                     numpy.linalg.norm( FX_moins_dX + amplitude * FdX ) / NormeFX,
                     )
                 #
-                self.StoredVariables["CostFunctionJ"].store( Residu )
-                msg = "  %2i  %5.0e   %9.3e   %9.3e   |   %9.3e   %5i %s"%(i,amplitude,NormeX,NormeFX,Residu,100*abs(Residu-1),"%")
+                self.StoredVariables["Residu"].store( Residu )
+                msg = "  %2i  %5.0e   %9.3e   %9.3e   |   %9.3e   %5i %s"%(i,amplitude,NormeX,NormeFX,Residu,100.*abs(Residu-1.),"%")
                 msgs += "\n" + __marge + msg
             #
             if self._parameters["ResiduFormula"] == "NominalTaylorRMS":
+                if "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
+                    self.StoredVariables["CurrentState"].store( numpy.ravel(Xn + dX) )
+                    self.StoredVariables["CurrentState"].store( numpy.ravel(Xn - dX) )
+                    self.StoredVariables["CurrentState"].store( numpy.ravel(dX) )
+                #
                 FX_plus_dX  = numpy.asmatrix(numpy.ravel( Hm( Xn + dX ) )).T
                 FX_moins_dX = numpy.asmatrix(numpy.ravel( Hm( Xn - dX ) )).T
                 FdX         = numpy.asmatrix(numpy.ravel( Hm( dX ) )).T
                 #
+                if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
+                    self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(FX_plus_dX) )
+                    self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(FX_moins_dX) )
+                    self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(FdX) )
+                #
                 Residu = max(
                     RMS( FX, FX_plus_dX   - amplitude * FdX ) / NormeFX,
                     RMS( FX, FX_moins_dX  + amplitude * FdX ) / NormeFX,
                     )
                 #
-                self.StoredVariables["CostFunctionJ"].store( Residu )
-                msg = "  %2i  %5.0e   %9.3e   %9.3e   |   %9.3e   %5i %s"%(i,amplitude,NormeX,NormeFX,Residu,100*Residu,"%")
+                self.StoredVariables["Residu"].store( Residu )
+                msg = "  %2i  %5.0e   %9.3e   %9.3e   |   %9.3e   %5i %s"%(i,amplitude,NormeX,NormeFX,Residu,100.*Residu,"%")
                 msgs += "\n" + __marge + msg
         #
         msgs += "\n" + __marge + "-"*__nbtirets
@@ -285,10 +338,7 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
         print "Results of linearity check by \"%s\" formula:"%self._parameters["ResiduFormula"]
         print msgs
         #
-        logging.debug("%s Nombre d'évaluation(s) de l'opérateur d'observation direct/tangent/adjoint : %i/%i/%i"%(self._name, HO["Direct"].nbcalls()[0],HO["Tangent"].nbcalls()[0],HO["Adjoint"].nbcalls()[0]))
-        logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
-        logging.debug("%s Terminé"%self._name)
-        #
+        self._post_run(HO)
         return 0
 
 # ==============================================================================