1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2015 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
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
30 BasicObjects.Algorithm.__init__(self, "EXTENDEDKALMANFILTER")
31 self.defineRequiredParameter(
32 name = "ConstrainedBy",
33 default = "EstimateProjection",
35 message = "Prise en compte des contraintes",
36 listval = ["EstimateProjection"],
38 self.defineRequiredParameter(
39 name = "EstimationOf",
42 message = "Estimation d'etat ou de parametres",
43 listval = ["State", "Parameters"],
45 self.defineRequiredParameter(
46 name = "StoreInternalVariables",
49 message = "Stockage des variables internes ou intermédiaires du calcul",
51 self.defineRequiredParameter(
52 name = "StoreSupplementaryCalculations",
55 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
56 listval = ["APosterioriCovariance", "BMA", "CurrentState", "CostFunctionJ", "Innovation"]
59 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
62 # Paramètres de pilotage
63 # ----------------------
64 self.setParameters(Parameters)
66 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):
67 Bounds = self._parameters["Bounds"]
68 logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
71 if self._parameters["EstimationOf"] == "Parameters":
72 self._parameters["StoreInternalVariables"] = True
77 raise ValueError("Background error covariance matrix has to be properly defined!")
79 raise ValueError("Observation error covariance matrix has to be properly defined!")
81 H = HO["Direct"].appliedControledFormTo
83 if self._parameters["EstimationOf"] == "State":
84 M = EM["Direct"].appliedControledFormTo
86 if CM is not None and CM.has_key("Tangent") and U is not None:
87 Cm = CM["Tangent"].asMatrix(Xb)
91 # Nombre de pas identique au nombre de pas d'observations
92 # -------------------------------------------------------
93 if hasattr(Y,"stepnumber"):
94 duration = Y.stepnumber()
98 # Précalcul des inversions de B et R
99 # ----------------------------------
100 if self._parameters["StoreInternalVariables"]:
109 self.StoredVariables["Analysis"].store( Xn.A1 )
110 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
111 self.StoredVariables["APosterioriCovariance"].store( Pn )
114 previousJMinimum = numpy.finfo(float).max
116 for step in range(duration-1):
117 if hasattr(Y,"store"):
118 Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
120 Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
122 Ht = HO["Tangent"].asMatrix(ValueForMethodForm = Xn)
123 Ht = Ht.reshape(Ynpu.size,Xn.size) # ADAO & check shape
124 Ha = HO["Adjoint"].asMatrix(ValueForMethodForm = Xn)
125 Ha = Ha.reshape(Xn.size,Ynpu.size) # ADAO & check shape
127 if self._parameters["EstimationOf"] == "State":
128 Mt = EM["Tangent"].asMatrix(ValueForMethodForm = Xn)
129 Mt = Mt.reshape(Xn.size,Xn.size) # ADAO & check shape
130 Ma = EM["Adjoint"].asMatrix(ValueForMethodForm = Xn)
131 Ma = Ma.reshape(Xn.size,Xn.size) # ADAO & check shape
134 if hasattr(U,"store") and len(U)>1:
135 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
136 elif hasattr(U,"store") and len(U)==1:
137 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
139 Un = numpy.asmatrix(numpy.ravel( U )).T
143 if self._parameters["EstimationOf"] == "State":
144 Xn_predicted = numpy.asmatrix(numpy.ravel( M( (Xn, Un) ) )).T
145 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
146 Cm = Cm.reshape(Xn.size,Un.size) # ADAO & check shape
147 Xn_predicted = Xn_predicted + Cm * Un
148 Pn_predicted = Q + Mt * Pn * Ma
149 elif self._parameters["EstimationOf"] == "Parameters":
150 # --- > Par principe, M = Id, Q = 0
154 if Bounds is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
155 Xn_predicted = numpy.max(numpy.hstack((Xn_predicted,numpy.asmatrix(Bounds)[:,0])),axis=1)
156 Xn_predicted = numpy.min(numpy.hstack((Xn_predicted,numpy.asmatrix(Bounds)[:,1])),axis=1)
158 if self._parameters["EstimationOf"] == "State":
159 d = Ynpu - numpy.asmatrix(numpy.ravel( H( (Xn_predicted, None) ) )).T
160 elif self._parameters["EstimationOf"] == "Parameters":
161 d = Ynpu - numpy.asmatrix(numpy.ravel( H( (Xn_predicted, Un) ) )).T
162 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans H, doublon !
165 Kn = Pn_predicted * Ha * (R + Ht * Pn_predicted * Ha).I
166 Xn = Xn_predicted + Kn * d
167 Pn = Pn_predicted - Kn * Ht * Pn_predicted
169 self.StoredVariables["Analysis"].store( Xn.A1 )
170 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
171 self.StoredVariables["APosterioriCovariance"].store( Pn )
172 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
173 self.StoredVariables["Innovation"].store( numpy.ravel( d.A1 ) )
174 if self._parameters["StoreInternalVariables"]:
175 Jb = 0.5 * (Xn - Xb).T * BI * (Xn - Xb)
176 Jo = 0.5 * d.T * RI * d
177 J = float( Jb ) + float( Jo )
178 if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
179 self.StoredVariables["CurrentState"].store( Xn )
180 self.StoredVariables["CostFunctionJb"].store( Jb )
181 self.StoredVariables["CostFunctionJo"].store( Jo )
182 self.StoredVariables["CostFunctionJ" ].store( J )
183 if J < previousJMinimum:
186 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
192 # Stockage supplementaire de l'optimum en estimation de parametres
193 # ----------------------------------------------------------------
194 if self._parameters["EstimationOf"] == "Parameters":
195 self.StoredVariables["Analysis"].store( Xa.A1 )
196 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
197 self.StoredVariables["APosterioriCovariance"].store( covarianceXa )
199 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
200 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
205 # ==============================================================================
206 if __name__ == "__main__":
207 print '\n AUTODIAGNOSTIC \n'