Salome HOME
Adding linear independant control and bounds possibilities
[modules/adao.git] / src / daComposant / daAlgorithms / KalmanFilter.py
index 708d5fe8fe779fcdd0268717a67aacffffead1d3..88fdb7b420f4cc9a894dbb1d223cba6788312a29 100644 (file)
@@ -1,6 +1,6 @@
 #-*-coding:iso-8859-1-*-
 #
-#  Copyright (C) 2008-2012 EDF R&D
+#  Copyright (C) 2008-2013 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
 #
 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 #
+#  Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
 
 import logging
 from daCore import BasicObjects, PlatformInfo
 m = PlatformInfo.SystemUsage()
+import numpy
 
 # ==============================================================================
 class ElementaryAlgorithm(BasicObjects.Algorithm):
     def __init__(self):
         BasicObjects.Algorithm.__init__(self, "KALMANFILTER")
         self.defineRequiredParameter(
-            name     = "CalculateAPosterioriCovariance",
+            name     = "StoreSupplementaryCalculations",
+            default  = [],
+            typecast = tuple,
+            message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
+            listval  = ["APosterioriCovariance", "BMA", "Innovation"]
+            )
+        self.defineRequiredParameter(
+            name     = "EstimationType",
+            default  = "State",
+            typecast = str,
+            message  = "Estimation d'etat ou de parametres",
+            listval  = ["State", "Parameters"],
+            )
+        self.defineRequiredParameter(
+            name     = "StoreInternalVariables",
             default  = False,
             typecast = bool,
-            message  = "Calcul de la covariance a posteriori",
+            message  = "Stockage des variables internes ou intermédiaires du calcul",
             )
 
-    def run(self, Xb=None, Y=None, H=None, M=None, R=None, B=None, Q=None, Parameters=None):
-        """
-        Calcul de l'estimateur du filtre de Kalman
-
-        Remarque : les observations sont exploitées à partir du pas de temps 1,
-        et sont utilisées dans Yo comme rangées selon ces indices. Donc le pas 0
-        n'est pas utilisé puisque la première étape de Kalman passe de 0 à 1
-        avec l'observation du pas 1.
-        """
+    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("Mo")))
+        logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
         #
         # Paramètres de pilotage
         # ----------------------
         self.setParameters(Parameters)
         #
-        # Opérateur d'observation
-        # -----------------------
-        Hm = H["Tangent"].asMatrix(None)
-        Ha = H["Adjoint"].asMatrix(None)
+        if self._parameters["EstimationType"] == "Parameters":
+            self._parameters["StoreInternalVariables"] = True
         #
+        # 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!")
         #
-        # Opérateur d'évolution
-        # ---------------------
-        Mm = M["Tangent"].asMatrix(None)
-        Mt = M["Adjoint"].asMatrix(None)
+        Ht = HO["Tangent"].asMatrix(Xb)
+        Ha = HO["Adjoint"].asMatrix(Xb)
+        #
+        if self._parameters["EstimationType"] == "State":
+            Mt = EM["Tangent"].asMatrix(Xb)
+            Ma = EM["Adjoint"].asMatrix(Xb)
+        #
+        if CM is not None and CM.has_key("Tangent") 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
         # -----------------------------------------------------------------
-        duration = Y.stepnumber()
+        if hasattr(Y,"stepnumber"):
+            duration = Y.stepnumber()
+        else:
+            duration = 2
+        #
+        # Précalcul des inversions de B et R
+        # ----------------------------------
+        if self._parameters["StoreInternalVariables"]:
+            if B is not None:
+                BI = B.I
+            elif self._parameters["B_scalar"] is not None:
+                BI = 1.0 / self._parameters["B_scalar"]
+            #
+            if R is not None:
+                RI = R.I
+            elif self._parameters["R_scalar"] is not None:
+                RI = 1.0 / self._parameters["R_scalar"]
         #
         # Initialisation
         # --------------
         Xn = Xb
         Pn = B
+        #
         self.StoredVariables["Analysis"].store( Xn.A1 )
-        if self._parameters["CalculateAPosterioriCovariance"]:
+        if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
             self.StoredVariables["APosterioriCovariance"].store( Pn )
+            covarianceXa = Pn
+        Xa               = Xn
+        previousJMinimum = numpy.finfo(float).max
         #
         for step in range(duration-1):
-            logging.debug("%s Etape de Kalman %i (i.e. %i->%i) sur un total de %i"%(self._name, step+1, step,step+1, duration-1))
+            if hasattr(Y,"store"):
+                Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
+            else:
+                Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
+            #
+            if U is not None:
+                if hasattr(U,"store") and len(U)>1:
+                    Un = numpy.asmatrix(numpy.ravel( U[step] )).T
+                elif hasattr(U,"store") and len(U)==1:
+                    Un = numpy.asmatrix(numpy.ravel( U[0] )).T
+                else:
+                    Un = numpy.asmatrix(numpy.ravel( U )).T
+            else:
+                Un = None
+            #
+            if self._parameters["EstimationType"] == "State" and Cm is not None and Un is not None:
+                Xn_predicted = Mt * Xn + Cm * Un
+                Pn_predicted = Mt * Pn * Ma + Q
+            elif self._parameters["EstimationType"] == "State" and (Cm is None or Un is None):
+                Xn_predicted = Mt * Xn
+                Pn_predicted = Mt * Pn * Ma + Q
+            elif self._parameters["EstimationType"] == "Parameters":
+                # Xn_predicted = Mt * Xn
+                # Pn_predicted = Mt * Pn * Ma + Q
+                # --- > Par principe, M = Id, Q = 0
+                Xn_predicted = Xn
+                Pn_predicted = Pn
             #
-            # Etape de prédiction
-            # -------------------
-            Xn_predicted = Mm * Xn
-            Pn_predicted = Mm * Pn * Mt + Q
+            if self._parameters["EstimationType"] == "Parameters" and Cm is not None and Un is not None:
+                d  = Ynpu - Ht * Xn_predicted - Cm * Un
+            else:
+                d  = Ynpu - Ht * Xn_predicted
             #
-            # Etape de correction
-            # -------------------
-            d  = Y.valueserie(step+1) - Hm * Xn_predicted
-            K  = Pn_predicted * Ha * (Hm * Pn_predicted * Ha + R).I
+            K  = Pn_predicted * Ha * (Ht * Pn_predicted * Ha + R).I
             Xn = Xn_predicted + K * d
-            Pn = Pn_predicted - K * Hm * Pn_predicted
+            Pn = Pn_predicted - K * Ht * Pn_predicted
             #
             self.StoredVariables["Analysis"].store( Xn.A1 )
-            self.StoredVariables["Innovation"].store( d.A1 )
-            if self._parameters["CalculateAPosterioriCovariance"]:
+            if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
                 self.StoredVariables["APosterioriCovariance"].store( Pn )
+            if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
+                self.StoredVariables["Innovation"].store( numpy.ravel( d.A1 ) )
+            if self._parameters["StoreInternalVariables"]:
+                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 )
+                self.StoredVariables["CostFunctionJb"].store( Jb )
+                self.StoredVariables["CostFunctionJo"].store( Jo )
+                self.StoredVariables["CostFunctionJ" ].store( J )
+                if J < previousJMinimum:
+                    previousJMinimum  = J
+                    Xa                = Xn
+                    if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
+                        covarianceXa  = Pn
+            else:
+                Xa = Xn
+            #
+        #
+        # Stockage supplementaire de l'optimum en estimation de parametres
+        # ----------------------------------------------------------------
+        if self._parameters["EstimationType"] == "Parameters":
+            self.StoredVariables["Analysis"].store( Xa.A1 )
+            if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
+                self.StoredVariables["APosterioriCovariance"].store( covarianceXa )
+        #
+        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("Mo")))
+        logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
         logging.debug("%s Terminé"%self._name)
         #
         return 0