1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2018 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 = ["APosterioriCorrelations", "APosterioriCovariance", "APosterioriStandardDeviations", "APosterioriVariances", "BMA", "CurrentState", "CostFunctionJ", "CostFunctionJb", "CostFunctionJo", "Innovation"]
58 self.defineRequiredParameter( # Pas de type
60 message = "Liste des valeurs de bornes",
62 self.requireInputArguments(
63 mandatory= ("Xb", "Y", "HO", "R", "B" ),
64 optional = ("U", "EM", "CM", "Q"),
67 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
68 self._pre_run(Parameters, Xb, Y, R, B, Q)
70 if self._parameters["EstimationOf"] == "Parameters":
71 self._parameters["StoreInternalVariables"] = True
76 raise ValueError("Background error covariance matrix has to be properly defined!")
78 raise ValueError("Observation error covariance matrix has to be properly defined!")
80 H = HO["Direct"].appliedControledFormTo
82 if self._parameters["EstimationOf"] == "State":
83 M = EM["Direct"].appliedControledFormTo
85 if CM is not None and "Tangent" in CM and U is not None:
86 Cm = CM["Tangent"].asMatrix(Xb)
90 # Nombre de pas identique au nombre de pas d'observations
91 # -------------------------------------------------------
92 if hasattr(Y,"stepnumber"):
93 duration = Y.stepnumber()
97 # Précalcul des inversions de B et R
98 # ----------------------------------
99 if self._parameters["StoreInternalVariables"]:
108 self.StoredVariables["Analysis"].store( Xn.A1 )
109 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
110 self.StoredVariables["APosterioriCovariance"].store( Pn.asfullmatrix(Xn.size) )
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
121 Ht = HO["Tangent"].asMatrix(ValueForMethodForm = Xn)
122 Ht = Ht.reshape(Ynpu.size,Xn.size) # ADAO & check shape
123 Ha = HO["Adjoint"].asMatrix(ValueForMethodForm = Xn)
124 Ha = Ha.reshape(Xn.size,Ynpu.size) # ADAO & check shape
126 if self._parameters["EstimationOf"] == "State":
127 Mt = EM["Tangent"].asMatrix(ValueForMethodForm = Xn)
128 Mt = Mt.reshape(Xn.size,Xn.size) # ADAO & check shape
129 Ma = EM["Adjoint"].asMatrix(ValueForMethodForm = Xn)
130 Ma = Ma.reshape(Xn.size,Xn.size) # ADAO & check shape
133 if hasattr(U,"store") and len(U)>1:
134 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
135 elif hasattr(U,"store") and len(U)==1:
136 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
138 Un = numpy.asmatrix(numpy.ravel( U )).T
142 if self._parameters["EstimationOf"] == "State":
143 Xn_predicted = numpy.asmatrix(numpy.ravel( M( (Xn, Un) ) )).T
144 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
145 Cm = Cm.reshape(Xn.size,Un.size) # ADAO & check shape
146 Xn_predicted = Xn_predicted + Cm * Un
147 Pn_predicted = Q + Mt * Pn * Ma
148 elif self._parameters["EstimationOf"] == "Parameters":
149 # --- > Par principe, M = Id, Q = 0
153 if self._parameters["Bounds"] is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
154 Xn_predicted = numpy.max(numpy.hstack((Xn_predicted,numpy.asmatrix(self._parameters["Bounds"])[:,0])),axis=1)
155 Xn_predicted = numpy.min(numpy.hstack((Xn_predicted,numpy.asmatrix(self._parameters["Bounds"])[:,1])),axis=1)
157 if self._parameters["EstimationOf"] == "State":
158 d = Ynpu - numpy.asmatrix(numpy.ravel( H( (Xn_predicted, None) ) )).T
159 elif self._parameters["EstimationOf"] == "Parameters":
160 d = Ynpu - numpy.asmatrix(numpy.ravel( H( (Xn_predicted, Un) ) )).T
161 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans H, doublon !
164 _A = R + Ht * Pn_predicted * Ha
165 _u = numpy.linalg.solve( _A , d )
166 Xn = Xn_predicted + Pn_predicted * Ha * _u
167 Kn = Pn_predicted * Ha * (R + Ht * Pn_predicted * Ha).I
168 Pn = Pn_predicted - Kn * Ht * Pn_predicted
170 self.StoredVariables["Analysis"].store( Xn.A1 )
171 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
172 self.StoredVariables["APosterioriCovariance"].store( Pn )
173 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
174 self.StoredVariables["Innovation"].store( numpy.ravel( d.A1 ) )
175 if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
176 self.StoredVariables["CurrentState"].store( Xn )
177 if self._parameters["StoreInternalVariables"] \
178 or "CostFunctionJ" in self._parameters["StoreSupplementaryCalculations"] \
179 or "CostFunctionJb" in self._parameters["StoreSupplementaryCalculations"] \
180 or "CostFunctionJo" in self._parameters["StoreSupplementaryCalculations"]:
181 Jb = 0.5 * (Xn - Xb).T * BI * (Xn - Xb)
182 Jo = 0.5 * d.T * RI * d
183 J = float( Jb ) + float( Jo )
184 self.StoredVariables["CostFunctionJb"].store( Jb )
185 self.StoredVariables["CostFunctionJo"].store( Jo )
186 self.StoredVariables["CostFunctionJ" ].store( J )
187 if J < previousJMinimum:
190 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
196 # Stockage supplementaire de l'optimum en estimation de parametres
197 # ----------------------------------------------------------------
198 if self._parameters["EstimationOf"] == "Parameters":
199 self.StoredVariables["Analysis"].store( Xa.A1 )
200 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
201 self.StoredVariables["APosterioriCovariance"].store( covarianceXa )
203 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
204 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
209 # ==============================================================================
210 if __name__ == "__main__":
211 print('\n AUTODIAGNOSTIC \n')