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, "EXTENDEDKALMANFILTER")
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 = "EstimationOf",
43 message = "Estimation d'etat ou de parametres",
44 listval = ["State", "Parameters"],
46 self.defineRequiredParameter(
47 name = "ConstrainedBy",
48 default = "EstimateProjection",
50 message = "Prise en compte des contraintes",
51 listval = ["EstimateProjection"],
53 self.defineRequiredParameter(
54 name = "StoreInternalVariables",
57 message = "Stockage des variables internes ou intermédiaires du calcul",
60 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
61 logging.debug("%s Lancement"%self._name)
62 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
64 # Paramètres de pilotage
65 # ----------------------
66 self.setParameters(Parameters)
68 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):
69 Bounds = self._parameters["Bounds"]
70 logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
73 if self._parameters["EstimationOf"] == "Parameters":
74 self._parameters["StoreInternalVariables"] = True
79 raise ValueError("Background error covariance matrix has to be properly defined!")
81 raise ValueError("Observation error covariance matrix has to be properly defined!")
83 H = HO["Direct"].appliedControledFormTo
85 if self._parameters["EstimationOf"] == "State":
86 M = EM["Direct"].appliedControledFormTo
88 if CM is not None and CM.has_key("Tangent") and U is not None:
89 Cm = CM["Tangent"].asMatrix(Xb)
93 # Nombre de pas du Kalman identique au nombre de pas d'observations
94 # -----------------------------------------------------------------
95 if hasattr(Y,"stepnumber"):
96 duration = Y.stepnumber()
100 # Précalcul des inversions de B et R
101 # ----------------------------------
102 if self._parameters["StoreInternalVariables"]:
105 elif self._parameters["B_scalar"] is not None:
106 BI = 1.0 / self._parameters["B_scalar"]
110 elif self._parameters["R_scalar"] is not None:
111 RI = 1.0 / self._parameters["R_scalar"]
118 self.StoredVariables["Analysis"].store( Xn.A1 )
119 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
120 self.StoredVariables["APosterioriCovariance"].store( Pn )
123 previousJMinimum = numpy.finfo(float).max
125 for step in range(duration-1):
126 if hasattr(Y,"store"):
127 Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
129 Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
131 Ht = HO["Tangent"].asMatrix(ValueForMethodForm = Xn)
132 Ht = Ht.reshape(Ynpu.size,Xn.size) # ADAO & check shape
133 Ha = HO["Adjoint"].asMatrix(ValueForMethodForm = Xn)
134 Ha = Ha.reshape(Xn.size,Ynpu.size) # ADAO & check shape
136 if self._parameters["EstimationOf"] == "State":
137 Mt = EM["Tangent"].asMatrix(ValueForMethodForm = Xn)
138 Mt = Mt.reshape(Xn.size,Xn.size) # ADAO & check shape
139 Ma = EM["Adjoint"].asMatrix(ValueForMethodForm = Xn)
140 Ma = Ma.reshape(Xn.size,Xn.size) # ADAO & check shape
143 if hasattr(U,"store") and len(U)>1:
144 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
145 elif hasattr(U,"store") and len(U)==1:
146 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
148 Un = numpy.asmatrix(numpy.ravel( U )).T
152 if self._parameters["EstimationOf"] == "State":
153 Xn_predicted = numpy.asmatrix(numpy.ravel( M( (Xn, Un) ) )).T
154 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
155 Cm = Cm.reshape(Xn.size,Un.size) # ADAO & check shape
156 Xn_predicted = Xn_predicted + Cm * Un
157 Pn_predicted = Mt * Pn * Ma + Q
158 elif self._parameters["EstimationOf"] == "Parameters":
159 # --- > Par principe, M = Id, Q = 0
163 if Bounds is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
164 Xn_predicted = numpy.max(numpy.hstack((Xn_predicted,numpy.asmatrix(Bounds)[:,0])),axis=1)
165 Xn_predicted = numpy.min(numpy.hstack((Xn_predicted,numpy.asmatrix(Bounds)[:,1])),axis=1)
167 if self._parameters["EstimationOf"] == "State":
168 d = Ynpu - numpy.asmatrix(numpy.ravel( H( (Xn_predicted, None) ) )).T
169 elif self._parameters["EstimationOf"] == "Parameters":
170 d = Ynpu - numpy.asmatrix(numpy.ravel( H( (Xn_predicted, Un) ) )).T
171 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans H, doublon !
174 K = Pn_predicted * Ha * (Ht * Pn_predicted * Ha + R).I
175 Xn = Xn_predicted + K * d
176 Pn = Pn_predicted - K * Ht * Pn_predicted
178 self.StoredVariables["Analysis"].store( Xn.A1 )
179 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
180 self.StoredVariables["APosterioriCovariance"].store( Pn )
181 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
182 self.StoredVariables["Innovation"].store( numpy.ravel( d.A1 ) )
183 if self._parameters["StoreInternalVariables"]:
184 Jb = 0.5 * (Xn - Xb).T * BI * (Xn - Xb)
185 Jo = 0.5 * d.T * RI * d
186 J = float( Jb ) + float( Jo )
187 self.StoredVariables["CurrentState"].store( Xn.A1 )
188 self.StoredVariables["CostFunctionJb"].store( Jb )
189 self.StoredVariables["CostFunctionJo"].store( Jo )
190 self.StoredVariables["CostFunctionJ" ].store( J )
191 if J < previousJMinimum:
194 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
200 # Stockage supplementaire de l'optimum en estimation de parametres
201 # ----------------------------------------------------------------
202 if self._parameters["EstimationOf"] == "Parameters":
203 self.StoredVariables["Analysis"].store( Xa.A1 )
204 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
205 self.StoredVariables["APosterioriCovariance"].store( covarianceXa )
207 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
208 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
210 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
211 logging.debug("%s Terminé"%self._name)
215 # ==============================================================================
216 if __name__ == "__main__":
217 print '\n AUTODIAGNOSTIC \n'