Salome HOME
Updating copyright date information (1)
[modules/adao.git] / src / daComposant / daAlgorithms / UnscentedKalmanFilter.py
index f07dc70ce95ded76d24056dcce52c6a797e38b7b..fb05316dbb62d39d2b678b6db90bea251d72e829 100644 (file)
@@ -1,28 +1,27 @@
-#-*-coding:iso-8859-1-*-
+# -*- coding: utf-8 -*-
 #
-#  Copyright (C) 2008-2013 EDF R&D
+# Copyright (C) 2008-2018 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
 
 # ==============================================================================
@@ -76,29 +75,27 @@ 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", "Innovation"]
+            message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
+            listval  = ["APosterioriCorrelations", "APosterioriCovariance", "APosterioriStandardDeviations", "APosterioriVariances", "BMA", "CurrentState", "CostFunctionJ", "CostFunctionJb", "CostFunctionJo", "Innovation"]
+            )
+        self.defineRequiredParameter( # Pas de type
+            name     = "Bounds",
+            message  = "Liste des valeurs de bornes",
+            )
+        self.requireInputArguments(
+            mandatory= ("Xb", "Y", "HO", "R", "B" ),
+            optional = ("U", "EM", "CM", "Q"),
             )
 
     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")))
-        #
-        # Paramètres de pilotage
-        # ----------------------
-        self.setParameters(Parameters)
+        self._pre_run(Parameters, Xb, Y, R, B, Q)
         #
-        if self._parameters.has_key("Bounds") and (type(self._parameters["Bounds"]) is type([]) or type(self._parameters["Bounds"]) is type(())) and (len(self._parameters["Bounds"]) > 0):
-            Bounds = self._parameters["Bounds"]
-            logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
-        else:
-            Bounds = None
         if self._parameters["EstimationOf"] == "Parameters":
             self._parameters["StoreInternalVariables"] = True
         #
@@ -125,31 +122,26 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
         Wc = numpy.array( Ww )
         Wc[0] = Lambda / (L + Lambda) + (1. - Alpha**2 + Beta)
         #
-        # Opérateurs
+        # Opérateurs
         # ----------
-        if B is None:
-            raise ValueError("Background error covariance matrix has to be properly defined!")
-        if R is None:
-            raise ValueError("Observation error covariance matrix has to be properly defined!")
-        #
         H = HO["Direct"].appliedControledFormTo
         #
         if self._parameters["EstimationOf"] == "State":
             M = EM["Direct"].appliedControledFormTo
         #
-        if CM is not None and CM.has_key("Tangent") and U is not None:
+        if CM is not None and "Tangent" in CM and U is not None:
             Cm = CM["Tangent"].asMatrix(Xb)
         else:
             Cm = None
         #
-        # Nombre de pas du Kalman identique au nombre de pas d'observations
-        # -----------------------------------------------------------------
+        # Nombre de pas identique au nombre de pas d'observations
+        # -------------------------------------------------------
         if hasattr(Y,"stepnumber"):
             duration = Y.stepnumber()
         else:
             duration = 2
         #
-        # Précalcul des inversions de B et R
+        # Précalcul des inversions de B et R
         # ----------------------------------
         if self._parameters["StoreInternalVariables"]:
             BI = B.getI()
@@ -190,10 +182,10 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
             Xnp = numpy.hstack([Xn, Xn+Gamma*Pndemi, Xn-Gamma*Pndemi])
             nbSpts = 2*Xn.size+1
             #
-            if Bounds is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
+            if self._parameters["Bounds"] is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
                 for point in range(nbSpts):
-                    Xnp[:,point] = numpy.max(numpy.hstack((Xnp[:,point],numpy.asmatrix(Bounds)[:,0])),axis=1)
-                    Xnp[:,point] = numpy.min(numpy.hstack((Xnp[:,point],numpy.asmatrix(Bounds)[:,1])),axis=1)
+                    Xnp[:,point] = numpy.max(numpy.hstack((Xnp[:,point],numpy.asmatrix(self._parameters["Bounds"])[:,0])),axis=1)
+                    Xnp[:,point] = numpy.min(numpy.hstack((Xnp[:,point],numpy.asmatrix(self._parameters["Bounds"])[:,1])),axis=1)
             #
             XEtnnp = []
             for point in range(nbSpts):
@@ -202,9 +194,9 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
                     if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
                         Cm = Cm.reshape(Xn.size,Un.size) # ADAO & check shape
                         XEtnnpi = XEtnnpi + Cm * Un
-                    if Bounds is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
-                        XEtnnpi = numpy.max(numpy.hstack((XEtnnpi,numpy.asmatrix(Bounds)[:,0])),axis=1)
-                        XEtnnpi = numpy.min(numpy.hstack((XEtnnpi,numpy.asmatrix(Bounds)[:,1])),axis=1)
+                    if self._parameters["Bounds"] is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
+                        XEtnnpi = numpy.max(numpy.hstack((XEtnnpi,numpy.asmatrix(self._parameters["Bounds"])[:,0])),axis=1)
+                        XEtnnpi = numpy.min(numpy.hstack((XEtnnpi,numpy.asmatrix(self._parameters["Bounds"])[:,1])),axis=1)
                 elif self._parameters["EstimationOf"] == "Parameters":
                     # --- > Par principe, M = Id, Q = 0
                     XEtnnpi = Xnp[:,point]
@@ -213,26 +205,26 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
             #
             Xncm = numpy.matrix( XEtnnp.getA()*numpy.array(Wm) ).sum(axis=1)
             #
-            if Bounds is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
-                Xncm = numpy.max(numpy.hstack((Xncm,numpy.asmatrix(Bounds)[:,0])),axis=1)
-                Xncm = numpy.min(numpy.hstack((Xncm,numpy.asmatrix(Bounds)[:,1])),axis=1)
+            if self._parameters["Bounds"] is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
+                Xncm = numpy.max(numpy.hstack((Xncm,numpy.asmatrix(self._parameters["Bounds"])[:,0])),axis=1)
+                Xncm = numpy.min(numpy.hstack((Xncm,numpy.asmatrix(self._parameters["Bounds"])[:,1])),axis=1)
             #
             if self._parameters["EstimationOf"] == "State":        Pnm = Q
             elif self._parameters["EstimationOf"] == "Parameters": Pnm = 0.
             for point in range(nbSpts):
                 Pnm += Wc[i] * (XEtnnp[:,point]-Xncm) * (XEtnnp[:,point]-Xncm).T
             #
-            if self._parameters["EstimationOf"] == "Parameters" and Bounds is not None:
+            if self._parameters["EstimationOf"] == "Parameters" and self._parameters["Bounds"] is not None:
                 Pnmdemi = self._parameters["Reconditioner"] * numpy.linalg.cholesky(Pnm)
             else:
                 Pnmdemi = numpy.linalg.cholesky(Pnm)
             #
             Xnnp = numpy.hstack([Xncm, Xncm+Gamma*Pnmdemi, Xncm-Gamma*Pnmdemi])
             #
-            if Bounds is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
+            if self._parameters["Bounds"] is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
                 for point in range(nbSpts):
-                    Xnnp[:,point] = numpy.max(numpy.hstack((Xnnp[:,point],numpy.asmatrix(Bounds)[:,0])),axis=1)
-                    Xnnp[:,point] = numpy.min(numpy.hstack((Xnnp[:,point],numpy.asmatrix(Bounds)[:,1])),axis=1)
+                    Xnnp[:,point] = numpy.max(numpy.hstack((Xnnp[:,point],numpy.asmatrix(self._parameters["Bounds"])[:,0])),axis=1)
+                    Xnnp[:,point] = numpy.min(numpy.hstack((Xnnp[:,point],numpy.asmatrix(self._parameters["Bounds"])[:,1])),axis=1)
             #
             Ynnp = []
             for point in range(nbSpts):
@@ -260,9 +252,9 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
             Xn = Xncm + Kn * d
             Pn = Pnm - Kn * Pyyn * Kn.T
             #
-            if Bounds is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
-                Xn = numpy.max(numpy.hstack((Xn,numpy.asmatrix(Bounds)[:,0])),axis=1)
-                Xn = numpy.min(numpy.hstack((Xn,numpy.asmatrix(Bounds)[:,1])),axis=1)
+            if self._parameters["Bounds"] is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
+                Xn = numpy.max(numpy.hstack((Xn,numpy.asmatrix(self._parameters["Bounds"])[:,0])),axis=1)
+                Xn = numpy.min(numpy.hstack((Xn,numpy.asmatrix(self._parameters["Bounds"])[:,1])),axis=1)
             #
             self.StoredVariables["Analysis"].store( Xn.A1 )
             if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
@@ -273,7 +265,8 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
                 Jb  = 0.5 * (Xn - Xb).T * BI * (Xn - Xb)
                 Jo  = 0.5 * d.T * RI * d
                 J   = float( Jb ) + float( Jo )
-                self.StoredVariables["CurrentState"].store( Xn.A1 )
+                if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
+                    self.StoredVariables["CurrentState"].store( Xn )
                 self.StoredVariables["CostFunctionJb"].store( Jb )
                 self.StoredVariables["CostFunctionJo"].store( Jo )
                 self.StoredVariables["CostFunctionJ" ].store( J )
@@ -296,11 +289,9 @@ class ElementaryAlgorithm(BasicObjects.Algorithm):
         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
         #
-        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')