1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2013 EDF R&D
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.
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.
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
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
24 from daCore import BasicObjects, PlatformInfo
25 m = PlatformInfo.SystemUsage()
28 # ==============================================================================
29 class ElementaryAlgorithm(BasicObjects.Algorithm):
31 BasicObjects.Algorithm.__init__(self, "KALMANFILTER")
32 self.defineRequiredParameter(
33 name = "StoreSupplementaryCalculations",
36 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
37 listval = ["APosterioriCovariance", "BMA", "Innovation"]
39 self.defineRequiredParameter(
40 name = "EstimationType",
43 message = "Estimation d'etat ou de parametres",
44 listval = ["State", "Parameters"],
46 self.defineRequiredParameter(
47 name = "StoreInternalVariables",
50 message = "Stockage des variables internes ou intermédiaires du calcul",
53 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
54 logging.debug("%s Lancement"%self._name)
55 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
57 # Paramètres de pilotage
58 # ----------------------
59 self.setParameters(Parameters)
61 if self._parameters["EstimationType"] == "Parameters":
62 self._parameters["StoreInternalVariables"] = True
67 raise ValueError("Background error covariance matrix has to be properly defined!")
69 raise ValueError("Observation error covariance matrix has to be properly defined!")
71 Ht = HO["Tangent"].asMatrix(Xb)
72 Ha = HO["Adjoint"].asMatrix(Xb)
74 if self._parameters["EstimationType"] == "State":
75 Mt = EM["Tangent"].asMatrix(Xb)
76 Ma = EM["Adjoint"].asMatrix(Xb)
78 if CM is not None and CM.has_key("Tangent") and U is not None:
79 Cm = CM["Tangent"].asMatrix(Xb)
83 # Nombre de pas du Kalman identique au nombre de pas d'observations
84 # -----------------------------------------------------------------
85 if hasattr(Y,"stepnumber"):
86 duration = Y.stepnumber()
90 # Précalcul des inversions de B et R
91 # ----------------------------------
92 if self._parameters["StoreInternalVariables"]:
95 elif self._parameters["B_scalar"] is not None:
96 BI = 1.0 / self._parameters["B_scalar"]
100 elif self._parameters["R_scalar"] is not None:
101 RI = 1.0 / self._parameters["R_scalar"]
108 self.StoredVariables["Analysis"].store( Xn.A1 )
109 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
110 self.StoredVariables["APosterioriCovariance"].store( Pn )
113 previousJMinimum = numpy.finfo(float).max
115 for step in range(duration-1):
116 if hasattr(Y,"store"):
117 Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
119 Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
122 if hasattr(U,"store") and len(U)>1:
123 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
124 elif hasattr(U,"store") and len(U)==1:
125 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
127 Un = numpy.asmatrix(numpy.ravel( U )).T
131 if self._parameters["EstimationType"] == "State":
132 Xn_predicted = Mt * Xn
133 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
134 Xn_predicted = Xn_predicted + Cm * Un
135 Pn_predicted = Mt * Pn * Ma + Q
136 elif self._parameters["EstimationType"] == "Parameters":
137 # --- > Par principe, M = Id, Q = 0
141 if self._parameters["EstimationType"] == "State":
142 d = Ynpu - Ht * Xn_predicted
143 elif self._parameters["EstimationType"] == "Parameters":
144 d = Ynpu - Ht * Xn_predicted
145 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans H, doublon !
148 K = Pn_predicted * Ha * (Ht * Pn_predicted * Ha + R).I
149 Xn = Xn_predicted + K * d
150 Pn = Pn_predicted - K * Ht * Pn_predicted
152 self.StoredVariables["Analysis"].store( Xn.A1 )
153 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
154 self.StoredVariables["APosterioriCovariance"].store( Pn )
155 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
156 self.StoredVariables["Innovation"].store( numpy.ravel( d.A1 ) )
157 if self._parameters["StoreInternalVariables"]:
158 Jb = 0.5 * (Xn - Xb).T * BI * (Xn - Xb)
159 Jo = 0.5 * d.T * RI * d
160 J = float( Jb ) + float( Jo )
161 self.StoredVariables["CurrentState"].store( Xn.A1 )
162 self.StoredVariables["CostFunctionJb"].store( Jb )
163 self.StoredVariables["CostFunctionJo"].store( Jo )
164 self.StoredVariables["CostFunctionJ" ].store( J )
165 if J < previousJMinimum:
168 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
174 # Stockage supplementaire de l'optimum en estimation de parametres
175 # ----------------------------------------------------------------
176 if self._parameters["EstimationType"] == "Parameters":
177 self.StoredVariables["Analysis"].store( Xa.A1 )
178 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
179 self.StoredVariables["APosterioriCovariance"].store( covarianceXa )
181 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
182 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
184 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
185 logging.debug("%s Terminé"%self._name)
189 # ==============================================================================
190 if __name__ == "__main__":
191 print '\n AUTODIAGNOSTIC \n'