1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2019 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",
57 "APosterioriCorrelations",
58 "APosterioriCovariance",
59 "APosterioriStandardDeviations",
60 "APosterioriVariances",
70 self.defineRequiredParameter( # Pas de type
72 message = "Liste des valeurs de bornes",
74 self.requireInputArguments(
75 mandatory= ("Xb", "Y", "HO", "R", "B" ),
76 optional = ("U", "EM", "CM", "Q"),
79 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
80 self._pre_run(Parameters, Xb, Y, R, B, Q)
82 if self._parameters["EstimationOf"] == "Parameters":
83 self._parameters["StoreInternalVariables"] = True
87 Hm = HO["Direct"].appliedControledFormTo
89 if self._parameters["EstimationOf"] == "State":
90 Mm = EM["Direct"].appliedControledFormTo
92 if CM is not None and "Tangent" in CM and U is not None:
93 Cm = CM["Tangent"].asMatrix(Xb)
97 # Nombre de pas identique au nombre de pas d'observations
98 # -------------------------------------------------------
99 if hasattr(Y,"stepnumber"):
100 duration = Y.stepnumber()
104 # Précalcul des inversions de B et R
105 # ----------------------------------
106 if self._parameters["StoreInternalVariables"] \
107 or self._toStore("CostFunctionJ") \
108 or self._toStore("CostFunctionJb") \
109 or self._toStore("CostFunctionJo"):
118 self.StoredVariables["Analysis"].store( Xn.A1 )
119 if self._toStore("APosterioriCovariance"):
120 self.StoredVariables["APosterioriCovariance"].store( Pn.asfullmatrix(Xn.size) )
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( Mm( (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 = Q + Mt * Pn * Ma
158 elif self._parameters["EstimationOf"] == "Parameters":
159 # --- > Par principe, M = Id, Q = 0
163 if self._parameters["Bounds"] is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
164 Xn_predicted = numpy.max(numpy.hstack((Xn_predicted,numpy.asmatrix(self._parameters["Bounds"])[:,0])),axis=1)
165 Xn_predicted = numpy.min(numpy.hstack((Xn_predicted,numpy.asmatrix(self._parameters["Bounds"])[:,1])),axis=1)
167 if self._parameters["EstimationOf"] == "State":
168 d = Ynpu - numpy.asmatrix(numpy.ravel( Hm( (Xn_predicted, None) ) )).T
169 elif self._parameters["EstimationOf"] == "Parameters":
170 d = Ynpu - numpy.asmatrix(numpy.ravel( Hm( (Xn_predicted, Un) ) )).T
171 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans H, doublon !
174 _A = R + numpy.dot(Ht, Pn_predicted * Ha)
175 _u = numpy.linalg.solve( _A , d )
176 Xn = Xn_predicted + Pn_predicted * Ha * _u
177 Kn = Pn_predicted * Ha * (R + numpy.dot(Ht, Pn_predicted * Ha)).I
178 Pn = Pn_predicted - Kn * Ht * Pn_predicted
180 self.StoredVariables["Analysis"].store( Xn.A1 )
181 if self._toStore("APosterioriCovariance"):
182 self.StoredVariables["APosterioriCovariance"].store( Pn )
183 if self._toStore("Innovation"):
184 self.StoredVariables["Innovation"].store( numpy.ravel( d.A1 ) )
185 if self._parameters["StoreInternalVariables"] \
186 or self._toStore("CurrentState"):
187 self.StoredVariables["CurrentState"].store( Xn )
188 if self._parameters["StoreInternalVariables"] \
189 or self._toStore("PredictedState"):
190 self.StoredVariables["PredictedState"].store( Xn_predicted )
191 if self._parameters["StoreInternalVariables"] \
192 or self._toStore("CostFunctionJ") \
193 or self._toStore("CostFunctionJb") \
194 or self._toStore("CostFunctionJo"):
195 Jb = 0.5 * (Xn - Xb).T * BI * (Xn - Xb)
196 Jo = 0.5 * d.T * RI * d
197 J = float( Jb ) + float( Jo )
198 self.StoredVariables["CostFunctionJb"].store( Jb )
199 self.StoredVariables["CostFunctionJo"].store( Jo )
200 self.StoredVariables["CostFunctionJ" ].store( J )
201 if J < previousJMinimum:
204 if self._toStore("APosterioriCovariance"):
210 # Stockage supplementaire de l'optimum en estimation de parametres
211 # ----------------------------------------------------------------
212 if self._parameters["EstimationOf"] == "Parameters":
213 self.StoredVariables["Analysis"].store( Xa.A1 )
214 if self._toStore("APosterioriCovariance"):
215 self.StoredVariables["APosterioriCovariance"].store( covarianceXa )
217 if self._toStore("BMA"):
218 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
223 # ==============================================================================
224 if __name__ == "__main__":
225 print('\n AUTODIAGNOSTIC \n')