1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2014 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 = "ConstrainedBy",
34 default = "EstimateProjection",
36 message = "Prise en compte des contraintes",
37 listval = ["EstimateProjection"],
39 self.defineRequiredParameter(
40 name = "EstimationOf",
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",
52 self.defineRequiredParameter(
53 name = "StoreSupplementaryCalculations",
56 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
57 listval = ["APosterioriCovariance", "BMA", "Innovation"]
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"]:
111 self.StoredVariables["Analysis"].store( Xn.A1 )
112 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
113 self.StoredVariables["APosterioriCovariance"].store( Pn )
116 previousJMinimum = numpy.finfo(float).max
118 for step in range(duration-1):
119 if hasattr(Y,"store"):
120 Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
122 Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
124 Ht = HO["Tangent"].asMatrix(ValueForMethodForm = Xn)
125 Ht = Ht.reshape(Ynpu.size,Xn.size) # ADAO & check shape
126 Ha = HO["Adjoint"].asMatrix(ValueForMethodForm = Xn)
127 Ha = Ha.reshape(Xn.size,Ynpu.size) # ADAO & check shape
129 if self._parameters["EstimationOf"] == "State":
130 Mt = EM["Tangent"].asMatrix(ValueForMethodForm = Xn)
131 Mt = Mt.reshape(Xn.size,Xn.size) # ADAO & check shape
132 Ma = EM["Adjoint"].asMatrix(ValueForMethodForm = Xn)
133 Ma = Ma.reshape(Xn.size,Xn.size) # ADAO & check shape
136 if hasattr(U,"store") and len(U)>1:
137 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
138 elif hasattr(U,"store") and len(U)==1:
139 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
141 Un = numpy.asmatrix(numpy.ravel( U )).T
145 if self._parameters["EstimationOf"] == "State":
146 Xn_predicted = numpy.asmatrix(numpy.ravel( M( (Xn, Un) ) )).T
147 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
148 Cm = Cm.reshape(Xn.size,Un.size) # ADAO & check shape
149 Xn_predicted = Xn_predicted + Cm * Un
150 Pn_predicted = Q + Mt * Pn * Ma
151 elif self._parameters["EstimationOf"] == "Parameters":
152 # --- > Par principe, M = Id, Q = 0
156 if Bounds is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
157 Xn_predicted = numpy.max(numpy.hstack((Xn_predicted,numpy.asmatrix(Bounds)[:,0])),axis=1)
158 Xn_predicted = numpy.min(numpy.hstack((Xn_predicted,numpy.asmatrix(Bounds)[:,1])),axis=1)
160 if self._parameters["EstimationOf"] == "State":
161 d = Ynpu - numpy.asmatrix(numpy.ravel( H( (Xn_predicted, None) ) )).T
162 elif self._parameters["EstimationOf"] == "Parameters":
163 d = Ynpu - numpy.asmatrix(numpy.ravel( H( (Xn_predicted, Un) ) )).T
164 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans H, doublon !
167 Kn = Pn_predicted * Ha * (R + Ht * Pn_predicted * Ha).I
168 Xn = Xn_predicted + Kn * d
169 Pn = Pn_predicted - Kn * Ht * Pn_predicted
171 self.StoredVariables["Analysis"].store( Xn.A1 )
172 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
173 self.StoredVariables["APosterioriCovariance"].store( Pn )
174 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
175 self.StoredVariables["Innovation"].store( numpy.ravel( d.A1 ) )
176 if self._parameters["StoreInternalVariables"]:
177 Jb = 0.5 * (Xn - Xb).T * BI * (Xn - Xb)
178 Jo = 0.5 * d.T * RI * d
179 J = float( Jb ) + float( Jo )
180 self.StoredVariables["CurrentState"].store( Xn )
181 self.StoredVariables["CostFunctionJb"].store( Jb )
182 self.StoredVariables["CostFunctionJo"].store( Jo )
183 self.StoredVariables["CostFunctionJ" ].store( J )
184 if J < previousJMinimum:
187 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
193 # Stockage supplementaire de l'optimum en estimation de parametres
194 # ----------------------------------------------------------------
195 if self._parameters["EstimationOf"] == "Parameters":
196 self.StoredVariables["Analysis"].store( Xa.A1 )
197 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
198 self.StoredVariables["APosterioriCovariance"].store( covarianceXa )
200 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
201 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
203 logging.debug("%s Nombre d'évaluation(s) de l'opérateur d'observation direct/tangent/adjoint : %i/%i/%i"%(self._name, HO["Direct"].nbcalls()[0],HO["Tangent"].nbcalls()[0],HO["Adjoint"].nbcalls()[0]))
204 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
205 logging.debug("%s Terminé"%self._name)
209 # ==============================================================================
210 if __name__ == "__main__":
211 print '\n AUTODIAGNOSTIC \n'