1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2021 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, "BLUE")
31 self.defineRequiredParameter(
32 name = "StoreInternalVariables",
35 message = "Stockage des variables internes ou intermédiaires du calcul",
37 self.defineRequiredParameter(
38 name = "StoreSupplementaryCalculations",
41 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
44 "APosterioriCorrelations",
45 "APosterioriCovariance",
46 "APosterioriStandardDeviations",
47 "APosterioriVariances",
50 "CostFunctionJAtCurrentOptimum",
52 "CostFunctionJbAtCurrentOptimum",
54 "CostFunctionJoAtCurrentOptimum",
58 "MahalanobisConsistency",
63 "SimulatedObservationAtBackground",
64 "SimulatedObservationAtCurrentOptimum",
65 "SimulatedObservationAtCurrentState",
66 "SimulatedObservationAtOptimum",
67 "SimulationQuantiles",
70 self.defineRequiredParameter(
74 message = "Liste des valeurs de quantiles",
78 self.defineRequiredParameter(
80 typecast = numpy.random.seed,
81 message = "Graine fixée pour le générateur aléatoire",
83 self.defineRequiredParameter(
84 name = "NumberOfSamplesForQuantiles",
87 message = "Nombre d'échantillons simulés pour le calcul des quantiles",
90 self.defineRequiredParameter(
91 name = "SimulationForQuantiles",
94 message = "Type de simulation pour l'estimation des quantiles",
95 listval = ["Linear", "NonLinear"]
97 self.requireInputArguments(
98 mandatory= ("Xb", "Y", "HO", "R", "B"),
100 self.setAttributes(tags=(
106 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
107 self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
109 Hm = HO["Tangent"].asMatrix(Xb)
110 Hm = Hm.reshape(Y.size,Xb.size) # ADAO & check shape
111 Ha = HO["Adjoint"].asMatrix(Xb)
112 Ha = Ha.reshape(Xb.size,Y.size) # ADAO & check shape
114 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
115 # ----------------------------------------------------
116 if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
117 HXb = HO["AppliedInX"]["HXb"]
120 HXb = numpy.asmatrix(numpy.ravel( HXb )).T
121 if Y.size != HXb.size:
122 raise ValueError("The size %i of observations Y and %i of observed calculation H(X) are different, they have to be identical."%(Y.size,HXb.size))
123 if max(Y.shape) != max(HXb.shape):
124 raise ValueError("The shapes %s of observations Y and %s of observed calculation H(X) are different, they have to be identical."%(Y.shape,HXb.shape))
126 # Précalcul des inversions de B et R
127 # ----------------------------------
131 # Calcul de l'innovation
132 # ----------------------
135 # Calcul de la matrice de gain et de l'analyse
136 # --------------------------------------------
137 if Y.size <= Xb.size:
138 _A = R + numpy.dot(Hm, B * Ha)
139 _u = numpy.linalg.solve( _A , d )
140 Xa = Xb + B * Ha * _u
142 _A = BI + numpy.dot(Ha, RI * Hm)
143 _u = numpy.linalg.solve( _A , numpy.dot(Ha, RI * d) )
145 self.StoredVariables["Analysis"].store( Xa.A1 )
147 # Calcul de la fonction coût
148 # --------------------------
149 if self._parameters["StoreInternalVariables"] or \
150 self._toStore("CostFunctionJ") or self._toStore("CostFunctionJAtCurrentOptimum") or \
151 self._toStore("CostFunctionJb") or self._toStore("CostFunctionJbAtCurrentOptimum") or \
152 self._toStore("CostFunctionJo") or self._toStore("CostFunctionJoAtCurrentOptimum") or \
153 self._toStore("OMA") or \
154 self._toStore("SigmaObs2") or \
155 self._toStore("MahalanobisConsistency") or \
156 self._toStore("SimulatedObservationAtCurrentOptimum") or \
157 self._toStore("SimulatedObservationAtCurrentState") or \
158 self._toStore("SimulatedObservationAtOptimum") or \
159 self._toStore("SimulationQuantiles"):
162 if self._parameters["StoreInternalVariables"] or \
163 self._toStore("CostFunctionJ") or self._toStore("CostFunctionJAtCurrentOptimum") or \
164 self._toStore("CostFunctionJb") or self._toStore("CostFunctionJbAtCurrentOptimum") or \
165 self._toStore("CostFunctionJo") or self._toStore("CostFunctionJoAtCurrentOptimum") or \
166 self._toStore("MahalanobisConsistency"):
167 Jb = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
168 Jo = float( 0.5 * oma.T * RI * oma )
170 self.StoredVariables["CostFunctionJb"].store( Jb )
171 self.StoredVariables["CostFunctionJo"].store( Jo )
172 self.StoredVariables["CostFunctionJ" ].store( J )
173 self.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( Jb )
174 self.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( Jo )
175 self.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( J )
177 # Calcul de la covariance d'analyse
178 # ---------------------------------
179 if self._toStore("APosterioriCovariance") or \
180 self._toStore("SimulationQuantiles"):
181 if (Y.size <= Xb.size): K = B * Ha * (R + numpy.dot(Hm, B * Ha)).I
182 elif (Y.size > Xb.size): K = (BI + numpy.dot(Ha, RI * Hm)).I * Ha * RI
184 if min(A.shape) != max(A.shape):
185 raise ValueError("The %s a posteriori covariance matrix A is of shape %s, despites it has to be a squared matrix. There is an error in the observation operator, please check it."%(self._name,str(A.shape)))
186 if (numpy.diag(A) < 0).any():
187 raise ValueError("The %s a posteriori covariance matrix A has at least one negative value on its diagonal. There is an error in the observation operator, please check it."%(self._name,))
188 if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
190 L = numpy.linalg.cholesky( A )
192 raise ValueError("The %s a posteriori covariance matrix A is not symmetric positive-definite. Please check your a priori covariances and your observation operator."%(self._name,))
193 self.StoredVariables["APosterioriCovariance"].store( A )
195 # Calculs et/ou stockages supplémentaires
196 # ---------------------------------------
197 if self._parameters["StoreInternalVariables"] or self._toStore("CurrentState"):
198 self.StoredVariables["CurrentState"].store( numpy.ravel(Xa) )
199 if self._toStore("CurrentOptimum"):
200 self.StoredVariables["CurrentOptimum"].store( numpy.ravel(Xa) )
201 if self._toStore("Innovation"):
202 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
203 if self._toStore("BMA"):
204 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
205 if self._toStore("OMA"):
206 self.StoredVariables["OMA"].store( numpy.ravel(oma) )
207 if self._toStore("OMB"):
208 self.StoredVariables["OMB"].store( numpy.ravel(d) )
209 if self._toStore("SigmaObs2"):
210 TraceR = R.trace(Y.size)
211 self.StoredVariables["SigmaObs2"].store( float( (d.T * (numpy.asmatrix(numpy.ravel(oma)).T)) ) / TraceR )
212 if self._toStore("SigmaBck2"):
213 self.StoredVariables["SigmaBck2"].store( float( (d.T * Hm * (Xa - Xb))/(Hm * B * Hm.T).trace() ) )
214 if self._toStore("MahalanobisConsistency"):
215 self.StoredVariables["MahalanobisConsistency"].store( float( 2.*J/d.size ) )
216 if self._toStore("SimulationQuantiles"):
217 nech = self._parameters["NumberOfSamplesForQuantiles"]
219 for i in range(nech):
220 if self._parameters["SimulationForQuantiles"] == "Linear":
221 dXr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A) - Xa.A1).T
222 dYr = numpy.matrix(numpy.ravel( Hm * dXr )).T
224 elif self._parameters["SimulationForQuantiles"] == "NonLinear":
225 Xr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A)).T
226 Yr = numpy.matrix(numpy.ravel( Hm * Xr )).T
230 YfQ = numpy.hstack((YfQ,Yr))
233 for quantile in self._parameters["Quantiles"]:
234 if not (0. <= float(quantile) <= 1.): continue
235 indice = int(nech * float(quantile) - 1./nech)
236 if YQ is None: YQ = YfQ[:,indice]
237 else: YQ = numpy.hstack((YQ,YfQ[:,indice]))
238 self.StoredVariables["SimulationQuantiles"].store( YQ )
239 if self._toStore("SimulatedObservationAtBackground"):
240 self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
241 if self._toStore("SimulatedObservationAtCurrentState"):
242 self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(HXa) )
243 if self._toStore("SimulatedObservationAtCurrentOptimum"):
244 self.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( numpy.ravel(HXa) )
245 if self._toStore("SimulatedObservationAtOptimum"):
246 self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
251 # ==============================================================================
252 if __name__ == "__main__":
253 print('\n AUTODIAGNOSTIC\n')