Salome HOME
Updating copyright date information
[modules/adao.git] / src / daComposant / daAlgorithms / LinearityTest.py
index 882578317e95a105efb9edaecacc29b16be760ee..144b791f3811f86afb5a0a2d8fd6e291eb6fbcd2 100644 (file)
@@ -1,36 +1,33 @@
 #-*-coding:iso-8859-1-*-
 #
-#  Copyright (C) 2008-2013 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()
-
-import numpy
-import math
+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",
@@ -58,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,
@@ -69,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
         # ----------------------
@@ -85,7 +96,7 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
         # Opérateurs
         # ----------
         Hm = HO["Direct"].appliedTo
-        if self._parameters["ResiduFormula"] in ["Taylor", "NominalTaylor", "NotNominalTaylor", "NominalTaylorRMS", "NotNominalTaylorRMS"]:
+        if self._parameters["ResiduFormula"] in ["Taylor", "NominalTaylor", "NominalTaylorRMS"]:
             Ht = HO["Tangent"].appliedInXTo
         #
         # Construction des perturbations
@@ -99,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
         # ----------------------------------------------
@@ -116,20 +131,22 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
         #
         # Calcul du gradient au point courant X pour l'incrément dX
         # ---------------------------------------------------------
-        if self._parameters["ResiduFormula"] in ["Taylor", "NominalTaylor", "NotNominalTaylor", "NominalTaylorRMS", "NotNominalTaylorRMS"]:
-            GradFxdX = Ht( (Xn, dX0) )
+        if self._parameters["ResiduFormula"] in ["Taylor", "NominalTaylor", "NominalTaylorRMS"]:
+            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"] is "CenteredDL":
-            entete = "  i   Alpha     ||X||      ||F(X)||   |   R(Alpha)   log( R )  "
-            __doc__ = """
-            On observe le residu provenant de la différence centrée des valeurs de F
+        __marge =  12*" "
+        if self._parameters["ResiduFormula"] == "CenteredDL":
+            __entete = "  i   Alpha     ||X||      ||F(X)||   |   R(Alpha)  log10( R )  "
+            __msgdoc = """
+            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 :
-            
+
                          || F(X+Alpha*dX) + F(X-Alpha*dX) - 2*F(X) ||
               R(Alpha) = --------------------------------------------
                                          || F(X) ||
@@ -142,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"] is "Taylor":
-            entete = "  i   Alpha     ||X||      ||F(X)||   |   R(Alpha)   log( R )  "
-            __doc__ = """
-            On observe le residu issu du développement de Taylor de la fonction F,
+        if self._parameters["ResiduFormula"] == "Taylor":
+            __entete = "  i   Alpha     ||X||      ||F(X)||   |   R(Alpha)  log10( R )  "
+            __msgdoc = """
+            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) ||
@@ -166,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"] is "NominalTaylor":
-            entete = "  i   Alpha     ||X||      ||F(X)||   |   R(Alpha)   |R-1| en %  "
-            __doc__ = """
-            On observe le residu obtenu à partir de deux approximations d'ordre 1 de F(X),
+        if self._parameters["ResiduFormula"] == "NominalTaylor":
+            __entete = "  i   Alpha     ||X||      ||F(X)||   |   R(Alpha)   |R-1| en %  "
+            __msgdoc = """
+            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(
@@ -181,19 +198,20 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
                 || F(X-Alpha*dX) + Alpha * F(dX) || / || F(X) ||,
               )
 
-            S'il reste constamment égal à 1 à moins de 2 ou 3 pourcents prés, c'est
-            que l'hypothèse de linéarité de F est vérifiée.
-            
+            S'il reste constamment égal à 1 à moins de 2 ou 3 pourcents prés (c'est-à-dire
+            que |R-1| reste égal à 2 ou 3 pourcents), c'est que l'hypothèse de linéarité
+            de F est vérifiée.
+
             S'il est égal à 1 sur une partie seulement du domaine de variation de
             l'incrément Alpha, c'est sur cette partie que l'hypothèse de linéarité de F
             est vérifiée.
-            
+
             On prend dX0 = Normal(0,X) et dX = Alpha*dX0. F est le code de calcul.
             """
-        if self._parameters["ResiduFormula"] is "NominalTaylorRMS":
-            entete = "  i   Alpha     ||X||      ||F(X)||   |   R(Alpha)    |R| en %  "
-            __doc__ = """
-            On observe le residu obtenu à partir de deux approximations d'ordre 1 de F(X),
+        if self._parameters["ResiduFormula"] == "NominalTaylorRMS":
+            __entete = "  i   Alpha     ||X||      ||F(X)||   |   R(Alpha)    |R| en %  "
+            __msgdoc = """
+            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(
@@ -203,91 +221,124 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
 
             S'il reste constamment égal à 0 à moins de 1 ou 2 pourcents prés, c'est
             que l'hypothèse de linéarité de F est vérifiée.
-            
+
             S'il est égal à 0 sur une partie seulement du domaine de variation de
             l'incrément Alpha, c'est sur cette partie que l'hypothèse de linéarité de F
             est vérifiée.
-            
+
             On prend dX0 = Normal(0,X) et dX = Alpha*dX0. F est le code de calcul.
             """
         #
         if len(self._parameters["ResultTitle"]) > 0:
-            msgs  = marge + "====" + "="*len(self._parameters["ResultTitle"]) + "====\n"
-            msgs += marge + "   " + self._parameters["ResultTitle"] + "\n"
-            msgs += marge + "====" + "="*len(self._parameters["ResultTitle"]) + "====\n"
+            msgs  = "\n"
+            msgs += __marge + "====" + "="*len(self._parameters["ResultTitle"]) + "====\n"
+            msgs += __marge + "    " + self._parameters["ResultTitle"] + "\n"
+            msgs += __marge + "====" + "="*len(self._parameters["ResultTitle"]) + "====\n"
         else:
             msgs  = ""
-        msgs += __doc__
+        msgs += __msgdoc
         #
-        nbtirets = len(entete)
-        msgs += "\n" + marge + "-"*nbtirets
-        msgs += "\n" + marge + entete
-        msgs += "\n" + marge + "-"*nbtirets
+        __nbtirets = len(__entete)
+        msgs += "\n" + __marge + "-"*__nbtirets
+        msgs += "\n" + __marge + __entete
+        msgs += "\n" + __marge + "-"*__nbtirets
         #
         # Boucle sur les perturbations
         # ----------------------------
         for i,amplitude in enumerate(Perturbations):
             dX      = amplitude * dX0
             #
-            if self._parameters["ResiduFormula"] is "CenteredDL":
+            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
+                msgs += "\n" + __marge + msg
             #
-            if self._parameters["ResiduFormula"] is "Taylor":
+            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
+                msgs += "\n" + __marge + msg
             #
-            if self._parameters["ResiduFormula"] is "NominalTaylor":
+            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),"%")
-                msgs += "\n" + marge + msg
+                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"] is "NominalTaylorRMS":
+            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,"%")
-                msgs += "\n" + marge + msg
+                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
+        msgs += "\n" + __marge + "-"*__nbtirets
         msgs += "\n"
         #
         # Sorties eventuelles
         # -------------------
         print
-        print "Results of linearity check by \"%s\" formula:\n"%self._parameters["ResiduFormula"]
+        print "Results of linearity check by \"%s\" formula:"%self._parameters["ResiduFormula"]
         print msgs
         #
-        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
 
 # ==============================================================================