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, NumericObjects
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",
61 "SampledStateForQuantiles",
64 "SimulatedObservationAtBackground",
65 "SimulatedObservationAtCurrentOptimum",
66 "SimulatedObservationAtCurrentState",
67 "SimulatedObservationAtOptimum",
68 "SimulationQuantiles",
71 self.defineRequiredParameter(
75 message = "Liste des valeurs de quantiles",
79 self.defineRequiredParameter(
81 typecast = numpy.random.seed,
82 message = "Graine fixée pour le générateur aléatoire",
84 self.defineRequiredParameter(
85 name = "NumberOfSamplesForQuantiles",
88 message = "Nombre d'échantillons simulés pour le calcul des quantiles",
91 self.defineRequiredParameter(
92 name = "SimulationForQuantiles",
95 message = "Type de simulation en estimation des quantiles",
96 listval = ["Linear", "NonLinear"]
98 self.defineRequiredParameter( # Pas de type
99 name = "StateBoundsForQuantiles",
100 message = "Liste des paires de bornes pour les états utilisés en estimation des quantiles",
102 self.requireInputArguments(
103 mandatory= ("Xb", "Y", "HO", "R", "B"),
105 self.setAttributes(tags=(
111 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
112 self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
114 Hm = HO["Tangent"].asMatrix(Xb)
115 Hm = Hm.reshape(Y.size,Xb.size) # ADAO & check shape
116 Ha = HO["Adjoint"].asMatrix(Xb)
117 Ha = Ha.reshape(Xb.size,Y.size) # ADAO & check shape
119 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
120 # ----------------------------------------------------
121 if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
122 HXb = HO["AppliedInX"]["HXb"]
125 HXb = numpy.asmatrix(numpy.ravel( HXb )).T
126 if Y.size != HXb.size:
127 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))
128 if max(Y.shape) != max(HXb.shape):
129 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))
131 # Précalcul des inversions de B et R
132 # ----------------------------------
136 # Calcul de l'innovation
137 # ----------------------
140 # Calcul de la matrice de gain et de l'analyse
141 # --------------------------------------------
142 if Y.size <= Xb.size:
143 _A = R + numpy.dot(Hm, B * Ha)
144 _u = numpy.linalg.solve( _A , d )
145 Xa = Xb + B * Ha * _u
147 _A = BI + numpy.dot(Ha, RI * Hm)
148 _u = numpy.linalg.solve( _A , numpy.dot(Ha, RI * d) )
150 self.StoredVariables["Analysis"].store( Xa.A1 )
152 # Calcul de la fonction coût
153 # --------------------------
154 if self._parameters["StoreInternalVariables"] or \
155 self._toStore("CostFunctionJ") or self._toStore("CostFunctionJAtCurrentOptimum") or \
156 self._toStore("CostFunctionJb") or self._toStore("CostFunctionJbAtCurrentOptimum") or \
157 self._toStore("CostFunctionJo") or self._toStore("CostFunctionJoAtCurrentOptimum") or \
158 self._toStore("OMA") or \
159 self._toStore("SigmaObs2") or \
160 self._toStore("MahalanobisConsistency") or \
161 self._toStore("SimulatedObservationAtCurrentOptimum") or \
162 self._toStore("SimulatedObservationAtCurrentState") or \
163 self._toStore("SimulatedObservationAtOptimum") or \
164 self._toStore("SimulationQuantiles"):
167 if self._parameters["StoreInternalVariables"] or \
168 self._toStore("CostFunctionJ") or self._toStore("CostFunctionJAtCurrentOptimum") or \
169 self._toStore("CostFunctionJb") or self._toStore("CostFunctionJbAtCurrentOptimum") or \
170 self._toStore("CostFunctionJo") or self._toStore("CostFunctionJoAtCurrentOptimum") or \
171 self._toStore("MahalanobisConsistency"):
172 Jb = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
173 Jo = float( 0.5 * oma.T * RI * oma )
175 self.StoredVariables["CostFunctionJb"].store( Jb )
176 self.StoredVariables["CostFunctionJo"].store( Jo )
177 self.StoredVariables["CostFunctionJ" ].store( J )
178 self.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( Jb )
179 self.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( Jo )
180 self.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( J )
182 # Calcul de la covariance d'analyse
183 # ---------------------------------
184 if self._toStore("APosterioriCovariance") or \
185 self._toStore("SimulationQuantiles"):
186 if (Y.size <= Xb.size): K = B * Ha * (R + numpy.dot(Hm, B * Ha)).I
187 elif (Y.size > Xb.size): K = (BI + numpy.dot(Ha, RI * Hm)).I * Ha * RI
189 if min(A.shape) != max(A.shape):
190 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)))
191 if (numpy.diag(A) < 0).any():
192 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,))
193 if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
195 L = numpy.linalg.cholesky( A )
197 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,))
198 self.StoredVariables["APosterioriCovariance"].store( A )
200 # Calculs et/ou stockages supplémentaires
201 # ---------------------------------------
202 if self._parameters["StoreInternalVariables"] or self._toStore("CurrentState"):
203 self.StoredVariables["CurrentState"].store( numpy.ravel(Xa) )
204 if self._toStore("CurrentOptimum"):
205 self.StoredVariables["CurrentOptimum"].store( numpy.ravel(Xa) )
206 if self._toStore("Innovation"):
207 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
208 if self._toStore("BMA"):
209 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
210 if self._toStore("OMA"):
211 self.StoredVariables["OMA"].store( numpy.ravel(oma) )
212 if self._toStore("OMB"):
213 self.StoredVariables["OMB"].store( numpy.ravel(d) )
214 if self._toStore("SigmaObs2"):
215 TraceR = R.trace(Y.size)
216 self.StoredVariables["SigmaObs2"].store( float( (d.T * (numpy.asmatrix(numpy.ravel(oma)).T)) ) / TraceR )
217 if self._toStore("SigmaBck2"):
218 self.StoredVariables["SigmaBck2"].store( float( (d.T * Hm * (Xa - Xb))/(Hm * B * Hm.T).trace() ) )
219 if self._toStore("MahalanobisConsistency"):
220 self.StoredVariables["MahalanobisConsistency"].store( float( 2.*J/d.size ) )
221 if self._toStore("SimulationQuantiles"):
222 H = HO["Direct"].appliedTo
223 NumericObjects.QuantilesEstimations(self, A, Xa, HXa, H, Hm)
224 if self._toStore("SimulatedObservationAtBackground"):
225 self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
226 if self._toStore("SimulatedObservationAtCurrentState"):
227 self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(HXa) )
228 if self._toStore("SimulatedObservationAtCurrentOptimum"):
229 self.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( numpy.ravel(HXa) )
230 if self._toStore("SimulatedObservationAtOptimum"):
231 self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
236 # ==============================================================================
237 if __name__ == "__main__":
238 print('\n AUTODIAGNOSTIC\n')