Salome HOME
Python 3 compatibility improvement (UTF-8) and data interface changes
[modules/adao.git] / src / daComposant / daAlgorithms / ExtendedBlue.py
index a5d5ec34ee6ac9fd7e9973d960647e38579738b4..893a099fe378c2ae498172d80530f2a47da1bd9d 100644 (file)
@@ -1,28 +1,27 @@
-#-*-coding:iso-8859-1-*-
+# -*- coding: utf-8 -*-
 #
-#  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
 
 # ==============================================================================
@@ -33,31 +32,33 @@ 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  = ["APosterioriCovariance", "BMA", "OMA", "OMB", "Innovation", "SigmaBck2", "SigmaObs2", "MahalanobisConsistency", "SimulationQuantiles"]
+            message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
+            listval  = ["APosterioriCorrelations", "APosterioriCovariance", "APosterioriStandardDeviations", "APosterioriVariances", "BMA", "OMA", "OMB", "CurrentState", "CostFunctionJ", "CostFunctionJb", "CostFunctionJo", "Innovation", "SigmaBck2", "SigmaObs2", "MahalanobisConsistency", "SimulationQuantiles", "SimulatedObservationAtBackground", "SimulatedObservationAtCurrentState", "SimulatedObservationAtOptimum"]
             )
         self.defineRequiredParameter(
             name     = "Quantiles",
             default  = [],
             typecast = tuple,
             message  = "Liste des valeurs de quantiles",
+            minval   = 0.,
+            maxval   = 1.,
             )
         self.defineRequiredParameter(
             name     = "SetSeed",
             typecast = numpy.random.seed,
-            message  = "Graine fixée pour le générateur aléatoire",
+            message  = "Graine fixée pour le générateur aléatoire",
             )
         self.defineRequiredParameter(
             name     = "NumberOfSamplesForQuantiles",
             default  = 100,
             typecast = int,
-            message  = "Nombre d'échantillons simulés pour le calcul des quantiles",
+            message  = "Nombre d'échantillons simulés pour le calcul des quantiles",
             minval   = 1,
             )
         self.defineRequiredParameter(
@@ -69,30 +70,23 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
             )
 
     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(Parameters)
         #
-        # Paramètres de pilotage
-        # ----------------------
-        self.setParameters(Parameters)
-        #
-        # Opérateur d'observation
-        # -----------------------
         Hm = HO["Tangent"].asMatrix(Xb)
         Hm = Hm.reshape(Y.size,Xb.size) # ADAO & check shape
         Ha = HO["Adjoint"].asMatrix(Xb)
         Ha = Ha.reshape(Xb.size,Y.size) # ADAO & check shape
         H  = HO["Direct"].appliedTo
         #
-        # Utilisation éventuelle d'un vecteur H(Xb) précalculé
+        # Utilisation éventuelle d'un vecteur H(Xb) précalculé
         # ----------------------------------------------------
-        if HO["AppliedToX"] is not None and HO["AppliedToX"].has_key("HXb"):
-            HXb = HO["AppliedToX"]["HXb"]
+        if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
+            HXb = H( Xb, HO["AppliedInX"]["HXb"])
         else:
             HXb = H( Xb )
         HXb = numpy.asmatrix(numpy.ravel( HXb )).T
         #
-        # Précalcul des inversions de B et R
+        # Précalcul des inversions de B et R
         # ----------------------------------
         BI = B.getI()
         RI = R.getI()
@@ -108,37 +102,33 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
         # Calcul de la matrice de gain et de l'analyse
         # --------------------------------------------
         if Y.size <= Xb.size:
-            if Y.size > 100: # len(R)
-                _A = R + Hm * B * Ha
-                _u = numpy.linalg.solve( _A , d )
-                Xa = Xb + B * Ha * _u
-            else:
-                K  = B * Ha * (R + Hm * B * Ha).I
-                Xa = Xb + K*d
+            _A = R + Hm * B * Ha
+            _u = numpy.linalg.solve( _A , d )
+            Xa = Xb + B * Ha * _u
         else:
-            if Y.size > 100: # len(R)
-                _A = BI + Ha * RI * Hm
-                _u = numpy.linalg.solve( _A , Ha * RI * d )
-                Xa = Xb + _u
-            else:
-                K = (BI + Ha * RI * Hm).I * Ha * RI
-                Xa = Xb + K*d
+            _A = BI + Ha * RI * Hm
+            _u = numpy.linalg.solve( _A , Ha * RI * d )
+            Xa = Xb + _u
         self.StoredVariables["Analysis"].store( Xa.A1 )
         #
-        # Calcul de la fonction coût
+        # Calcul de la fonction coût
         # --------------------------
         if self._parameters["StoreInternalVariables"] or \
-           "OMA" in self._parameters["StoreSupplementaryCalculations"] or \
-           "SigmaObs2" in self._parameters["StoreSupplementaryCalculations"] or \
-           "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"] or \
-           "SimulationQuantiles" in self._parameters["StoreSupplementaryCalculations"]:
+           "CostFunctionJ"                      in self._parameters["StoreSupplementaryCalculations"] or \
+           "OMA"                                in self._parameters["StoreSupplementaryCalculations"] or \
+           "SigmaObs2"                          in self._parameters["StoreSupplementaryCalculations"] or \
+           "MahalanobisConsistency"             in self._parameters["StoreSupplementaryCalculations"] or \
+           "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"] or \
+           "SimulatedObservationAtOptimum"      in self._parameters["StoreSupplementaryCalculations"] or \
+           "SimulationQuantiles"                in self._parameters["StoreSupplementaryCalculations"]:
             HXa  = numpy.matrix(numpy.ravel( H( Xa ) )).T
             oma = Y - HXa
         if self._parameters["StoreInternalVariables"] or \
-           "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"]:
-            Jb  = 0.5 * (Xa - Xb).T * BI * (Xa - Xb)
-            Jo  = 0.5 * oma.T * RI * oma
-            J   = float( Jb ) + float( Jo )
+           "CostFunctionJ"                 in self._parameters["StoreSupplementaryCalculations"] or \
+           "MahalanobisConsistency"        in self._parameters["StoreSupplementaryCalculations"]:
+            Jb  = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
+            Jo  = float( 0.5 * oma.T * RI * oma )
+            J   = Jb + Jo
             self.StoredVariables["CostFunctionJb"].store( Jb )
             self.StoredVariables["CostFunctionJo"].store( Jo )
             self.StoredVariables["CostFunctionJ" ].store( J )
@@ -146,10 +136,9 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
         # Calcul de la covariance d'analyse
         # ---------------------------------
         if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"] or \
-           "SimulationQuantiles" in self._parameters["StoreSupplementaryCalculations"]:
-            if   (Y.size <= Xb.size) and (Y.size > 100): K  = B * Ha * (R + Hm * B * Ha).I
-            elif (Y.size >  Xb.size) and (Y.size > 100): K = (BI + Ha * RI * Hm).I * Ha * RI
-            else:                                        pass # K deja calcule
+           "SimulationQuantiles"   in self._parameters["StoreSupplementaryCalculations"]:
+            if   (Y.size <= Xb.size): K  = B * Ha * (R + Hm * B * Ha).I
+            elif (Y.size >  Xb.size): K = (BI + Ha * RI * Hm).I * Ha * RI
             A = B - K * Hm * B
             if min(A.shape) != max(A.shape):
                 raise ValueError("The %s a posteriori covariance matrix A is of shape %s, despites it has to be a squared matrix. There is an error in the observation operator, please check it."%(self._name,str(A.shape)))
@@ -162,8 +151,10 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
                     raise ValueError("The %s a posteriori covariance matrix A is not symmetric positive-definite. Please check your a priori covariances and your observation operator."%(self._name,))
             self.StoredVariables["APosterioriCovariance"].store( A )
         #
-        # Calculs et/ou stockages supplémentaires
+        # Calculs et/ou stockages supplémentaires
         # ---------------------------------------
+        if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
+            self.StoredVariables["CurrentState"].store( numpy.ravel(Xa) )
         if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
             self.StoredVariables["Innovation"].store( numpy.ravel(d) )
         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
@@ -180,7 +171,6 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
         if "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"]:
             self.StoredVariables["MahalanobisConsistency"].store( float( 2.*J/d.size ) )
         if "SimulationQuantiles" in self._parameters["StoreSupplementaryCalculations"]:
-            Qtls = self._parameters["Quantiles"]
             nech = self._parameters["NumberOfSamplesForQuantiles"]
             HtM  = HO["Tangent"].asMatrix(ValueForMethodForm = Xa)
             HtM  = HtM.reshape(Y.size,Xa.size) # ADAO & check shape
@@ -199,20 +189,22 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
                     YfQ = numpy.hstack((YfQ,Yr))
             YfQ.sort(axis=-1)
             YQ = None
-            for quantile in Qtls:
-                if not (0. <= quantile <= 1.): continue
-                indice = int(nech * quantile - 1./nech)
+            for quantile in self._parameters["Quantiles"]:
+                if not (0. <= float(quantile) <= 1.): continue
+                indice = int(nech * float(quantile) - 1./nech)
                 if YQ is None: YQ = YfQ[:,indice]
                 else:          YQ = numpy.hstack((YQ,YfQ[:,indice]))
             self.StoredVariables["SimulationQuantiles"].store( YQ )
+        if "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
+            self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
+        if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
+            self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(HXa) )
+        if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
+            self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
         #
-        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 Nombre d'appels au cache d'opérateur d'observation direct/tangent/adjoint..: %i/%i/%i"%(self._name, HO["Direct"].nbcalls(3),HO["Tangent"].nbcalls(3),HO["Adjoint"].nbcalls(3)))
-        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
 
 # ==============================================================================
 if __name__ == "__main__":
-    print '\n AUTODIAGNOSTIC \n'
+    print('\n AUTODIAGNOSTIC \n')