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, "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",
43 "APosterioriCorrelations",
44 "APosterioriCovariance",
45 "APosterioriStandardDeviations",
46 "APosterioriVariances",
57 "MahalanobisConsistency",
58 "SimulationQuantiles",
59 "SimulatedObservationAtBackground",
60 "SimulatedObservationAtCurrentState",
61 "SimulatedObservationAtOptimum",
64 self.defineRequiredParameter(
68 message = "Liste des valeurs de quantiles",
72 self.defineRequiredParameter(
74 typecast = numpy.random.seed,
75 message = "Graine fixée pour le générateur aléatoire",
77 self.defineRequiredParameter(
78 name = "NumberOfSamplesForQuantiles",
81 message = "Nombre d'échantillons simulés pour le calcul des quantiles",
84 self.defineRequiredParameter(
85 name = "SimulationForQuantiles",
88 message = "Type de simulation pour l'estimation des quantiles",
89 listval = ["Linear", "NonLinear"]
91 self.requireInputArguments(
92 mandatory= ("Xb", "Y", "HO", "R", "B"),
95 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
96 self._pre_run(Parameters, Xb, Y, R, B, Q)
98 Hm = HO["Tangent"].asMatrix(Xb)
99 Hm = Hm.reshape(Y.size,Xb.size) # ADAO & check shape
100 Ha = HO["Adjoint"].asMatrix(Xb)
101 Ha = Ha.reshape(Xb.size,Y.size) # ADAO & check shape
103 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
104 # ----------------------------------------------------
105 if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
106 HXb = HO["AppliedInX"]["HXb"]
109 HXb = numpy.asmatrix(numpy.ravel( HXb )).T
110 if Y.size != HXb.size:
111 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))
112 if max(Y.shape) != max(HXb.shape):
113 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))
115 # Précalcul des inversions de B et R
116 # ----------------------------------
120 # Calcul de l'innovation
121 # ----------------------
124 # Calcul de la matrice de gain et de l'analyse
125 # --------------------------------------------
126 if Y.size <= Xb.size:
128 _u = numpy.linalg.solve( _A , d )
129 Xa = Xb + B * Ha * _u
131 _A = BI + Ha * RI * Hm
132 _u = numpy.linalg.solve( _A , Ha * RI * d )
134 self.StoredVariables["Analysis"].store( Xa.A1 )
136 # Calcul de la fonction coût
137 # --------------------------
138 if self._parameters["StoreInternalVariables"] or \
139 self._toStore("CostFunctionJ") or \
140 self._toStore("OMA") or \
141 self._toStore("SigmaObs2") or \
142 self._toStore("MahalanobisConsistency") or \
143 self._toStore("SimulatedObservationAtCurrentState") or \
144 self._toStore("SimulatedObservationAtOptimum") or \
145 self._toStore("SimulationQuantiles"):
148 if self._parameters["StoreInternalVariables"] or \
149 self._toStore("CostFunctionJ") or \
150 self._toStore("MahalanobisConsistency"):
151 Jb = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
152 Jo = float( 0.5 * oma.T * RI * oma )
154 self.StoredVariables["CostFunctionJb"].store( Jb )
155 self.StoredVariables["CostFunctionJo"].store( Jo )
156 self.StoredVariables["CostFunctionJ" ].store( J )
158 # Calcul de la covariance d'analyse
159 # ---------------------------------
160 if self._toStore("APosterioriCovariance") or \
161 self._toStore("SimulationQuantiles"):
162 if (Y.size <= Xb.size): K = B * Ha * (R + Hm * B * Ha).I
163 elif (Y.size > Xb.size): K = (BI + Ha * RI * Hm).I * Ha * RI
165 if min(A.shape) != max(A.shape):
166 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)))
167 if (numpy.diag(A) < 0).any():
168 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,))
169 if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
171 L = numpy.linalg.cholesky( A )
173 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,))
174 self.StoredVariables["APosterioriCovariance"].store( A )
176 # Calculs et/ou stockages supplémentaires
177 # ---------------------------------------
178 if self._parameters["StoreInternalVariables"] or self._toStore("CurrentState"):
179 self.StoredVariables["CurrentState"].store( numpy.ravel(Xa) )
180 if self._toStore("Innovation"):
181 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
182 if self._toStore("BMA"):
183 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
184 if self._toStore("OMA"):
185 self.StoredVariables["OMA"].store( numpy.ravel(oma) )
186 if self._toStore("OMB"):
187 self.StoredVariables["OMB"].store( numpy.ravel(d) )
188 if self._toStore("SigmaObs2"):
189 TraceR = R.trace(Y.size)
190 self.StoredVariables["SigmaObs2"].store( float( (d.T * (numpy.asmatrix(numpy.ravel(oma)).T)) ) / TraceR )
191 if self._toStore("SigmaBck2"):
192 self.StoredVariables["SigmaBck2"].store( float( (d.T * Hm * (Xa - Xb))/(Hm * B * Hm.T).trace() ) )
193 if self._toStore("MahalanobisConsistency"):
194 self.StoredVariables["MahalanobisConsistency"].store( float( 2.*J/d.size ) )
195 if self._toStore("SimulationQuantiles"):
196 nech = self._parameters["NumberOfSamplesForQuantiles"]
198 for i in range(nech):
199 if self._parameters["SimulationForQuantiles"] == "Linear":
200 dXr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A) - Xa.A1).T
201 dYr = numpy.matrix(numpy.ravel( Hm * dXr )).T
203 elif self._parameters["SimulationForQuantiles"] == "NonLinear":
204 Xr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A)).T
205 Yr = numpy.matrix(numpy.ravel( Hm * Xr )).T
209 YfQ = numpy.hstack((YfQ,Yr))
212 for quantile in self._parameters["Quantiles"]:
213 if not (0. <= float(quantile) <= 1.): continue
214 indice = int(nech * float(quantile) - 1./nech)
215 if YQ is None: YQ = YfQ[:,indice]
216 else: YQ = numpy.hstack((YQ,YfQ[:,indice]))
217 self.StoredVariables["SimulationQuantiles"].store( YQ )
218 if self._toStore("SimulatedObservationAtBackground"):
219 self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
220 if self._toStore("SimulatedObservationAtCurrentState"):
221 self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(HXa) )
222 if self._toStore("SimulatedObservationAtOptimum"):
223 self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
228 # ==============================================================================
229 if __name__ == "__main__":
230 print('\n AUTODIAGNOSTIC \n')