Salome HOME
Simplification of naming for memory sizes
[modules/adao.git] / src / daComposant / daAlgorithms / KalmanFilter.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2012 EDF R&D
4 #
5 #  This library is free software; you can redistribute it and/or
6 #  modify it under the terms of the GNU Lesser General Public
7 #  License as published by the Free Software Foundation; either
8 #  version 2.1 of the License.
9 #
10 #  This library is distributed in the hope that it will be useful,
11 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 #  Lesser General Public License for more details.
14 #
15 #  You should have received a copy of the GNU Lesser General Public
16 #  License along with this library; if not, write to the Free Software
17 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18 #
19 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #
21 #  Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
22
23 import logging
24 from daCore import BasicObjects, PlatformInfo
25 m = PlatformInfo.SystemUsage()
26
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
29     def __init__(self):
30         BasicObjects.Algorithm.__init__(self, "KALMANFILTER")
31         self.defineRequiredParameter(
32             name     = "CalculateAPosterioriCovariance",
33             default  = False,
34             typecast = bool,
35             message  = "Calcul de la covariance a posteriori",
36             )
37
38     def run(self, Xb=None, Y=None, H=None, M=None, R=None, B=None, Q=None, Parameters=None):
39         """
40         Calcul de l'estimateur du filtre de Kalman
41
42         Remarque : les observations sont exploitées à partir du pas de temps 1,
43         et sont utilisées dans Yo comme rangées selon ces indices. Donc le pas 0
44         n'est pas utilisé puisque la première étape de Kalman passe de 0 à 1
45         avec l'observation du pas 1.
46         """
47         logging.debug("%s Lancement"%self._name)
48         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
49         #
50         # Paramètres de pilotage
51         # ----------------------
52         self.setParameters(Parameters)
53         #
54         # Opérateur d'observation
55         # -----------------------
56         Hm = H["Tangent"].asMatrix(None)
57         Ha = H["Adjoint"].asMatrix(None)
58         #
59         if B is None:
60             raise ValueError("Background error covariance matrix has to be properly defined!")
61         if R is None:
62             raise ValueError("Observation error covariance matrix has to be properly defined!")
63         #
64         # Opérateur d'évolution
65         # ---------------------
66         Mm = M["Tangent"].asMatrix(None)
67         Mt = M["Adjoint"].asMatrix(None)
68         #
69         # Nombre de pas du Kalman identique au nombre de pas d'observations
70         # -----------------------------------------------------------------
71         duration = Y.stepnumber()
72         #
73         # Initialisation
74         # --------------
75         Xn = Xb
76         Pn = B
77         self.StoredVariables["Analysis"].store( Xn.A1 )
78         if self._parameters["CalculateAPosterioriCovariance"]:
79             self.StoredVariables["APosterioriCovariance"].store( Pn )
80         #
81         for step in range(duration-1):
82             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))
83             #
84             # Etape de prédiction
85             # -------------------
86             Xn_predicted = Mm * Xn
87             Pn_predicted = Mm * Pn * Mt + Q
88             #
89             # Etape de correction
90             # -------------------
91             d  = Y.valueserie(step+1) - Hm * Xn_predicted
92             K  = Pn_predicted * Ha * (Hm * Pn_predicted * Ha + R).I
93             Xn = Xn_predicted + K * d
94             Pn = Pn_predicted - K * Hm * Pn_predicted
95             #
96             self.StoredVariables["Analysis"].store( Xn.A1 )
97             self.StoredVariables["Innovation"].store( d.A1 )
98             if self._parameters["CalculateAPosterioriCovariance"]:
99                 self.StoredVariables["APosterioriCovariance"].store( Pn )
100         #
101         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
102         logging.debug("%s Terminé"%self._name)
103         #
104         return 0
105
106 # ==============================================================================
107 if __name__ == "__main__":
108     print '\n AUTODIAGNOSTIC \n'