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
25 import numpy, scipy.optimize
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
30 BasicObjects.Algorithm.__init__(self, "3DVAR")
31 self.defineRequiredParameter(
35 message = "Minimiseur utilisé",
36 listval = ["LBFGSB","TNC", "CG", "NCG", "BFGS"],
38 self.defineRequiredParameter(
39 name = "MaximumNumberOfSteps",
42 message = "Nombre maximal de pas d'optimisation",
45 self.defineRequiredParameter(
46 name = "CostDecrementTolerance",
49 message = "Diminution relative minimale du coût lors de l'arrêt",
52 self.defineRequiredParameter(
53 name = "ProjectedGradientTolerance",
56 message = "Maximum des composantes du gradient projeté lors de l'arrêt",
59 self.defineRequiredParameter(
60 name = "GradientNormTolerance",
63 message = "Maximum des composantes du gradient lors de l'arrêt",
66 self.defineRequiredParameter(
67 name = "StoreInternalVariables",
70 message = "Stockage des variables internes ou intermédiaires du calcul",
72 self.defineRequiredParameter(
73 name = "StoreSupplementaryCalculations",
76 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
78 "APosterioriCorrelations",
79 "APosterioriCovariance",
80 "APosterioriStandardDeviations",
81 "APosterioriVariances",
84 "CostFunctionJAtCurrentOptimum",
86 "CostFunctionJbAtCurrentOptimum",
88 "CostFunctionJoAtCurrentOptimum",
93 "InnovationAtCurrentState",
94 "MahalanobisConsistency",
98 "SimulatedObservationAtBackground",
99 "SimulatedObservationAtCurrentOptimum",
100 "SimulatedObservationAtCurrentState",
101 "SimulatedObservationAtOptimum",
102 "SimulationQuantiles",
105 self.defineRequiredParameter(
109 message = "Liste des valeurs de quantiles",
113 self.defineRequiredParameter(
115 typecast = numpy.random.seed,
116 message = "Graine fixée pour le générateur aléatoire",
118 self.defineRequiredParameter(
119 name = "NumberOfSamplesForQuantiles",
122 message = "Nombre d'échantillons simulés pour le calcul des quantiles",
125 self.defineRequiredParameter(
126 name = "SimulationForQuantiles",
129 message = "Type de simulation pour l'estimation des quantiles",
130 listval = ["Linear", "NonLinear"]
132 self.defineRequiredParameter( # Pas de type
134 message = "Liste des valeurs de bornes",
136 self.requireInputArguments(
137 mandatory= ("Xb", "Y", "HO", "R", "B" ),
140 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
141 self._pre_run(Parameters, Xb, Y, R, B, Q)
143 # Correction pour pallier a un bug de TNC sur le retour du Minimum
144 if "Minimizer" in self._parameters and self._parameters["Minimizer"] == "TNC":
145 self.setParameterValue("StoreInternalVariables",True)
149 Hm = HO["Direct"].appliedTo
150 Ha = HO["Adjoint"].appliedInXTo
152 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
153 # ----------------------------------------------------
154 if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
155 HXb = Hm( Xb, HO["AppliedInX"]["HXb"] )
158 HXb = numpy.asmatrix(numpy.ravel( HXb )).T
159 if Y.size != HXb.size:
160 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))
161 if max(Y.shape) != max(HXb.shape):
162 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))
164 # Précalcul des inversions de B et R
165 # ----------------------------------
169 # Définition de la fonction-coût
170 # ------------------------------
172 _X = numpy.asmatrix(numpy.ravel( x )).T
173 if self._parameters["StoreInternalVariables"] or \
174 self._toStore("CurrentState") or \
175 self._toStore("CurrentOptimum"):
176 self.StoredVariables["CurrentState"].store( _X )
178 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
179 _Innovation = Y - _HX
180 if self._toStore("SimulatedObservationAtCurrentState") or \
181 self._toStore("SimulatedObservationAtCurrentOptimum"):
182 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
183 if self._toStore("InnovationAtCurrentState"):
184 self.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
186 Jb = float( 0.5 * (_X - Xb).T * BI * (_X - Xb) )
187 Jo = float( 0.5 * _Innovation.T * RI * _Innovation )
190 self.StoredVariables["CostFunctionJb"].store( Jb )
191 self.StoredVariables["CostFunctionJo"].store( Jo )
192 self.StoredVariables["CostFunctionJ" ].store( J )
193 if self._toStore("IndexOfOptimum") or \
194 self._toStore("CurrentOptimum") or \
195 self._toStore("CostFunctionJAtCurrentOptimum") or \
196 self._toStore("CostFunctionJbAtCurrentOptimum") or \
197 self._toStore("CostFunctionJoAtCurrentOptimum") or \
198 self._toStore("SimulatedObservationAtCurrentOptimum"):
199 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
200 if self._toStore("IndexOfOptimum"):
201 self.StoredVariables["IndexOfOptimum"].store( IndexMin )
202 if self._toStore("CurrentOptimum"):
203 self.StoredVariables["CurrentOptimum"].store( self.StoredVariables["CurrentState"][IndexMin] )
204 if self._toStore("SimulatedObservationAtCurrentOptimum"):
205 self.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] )
206 if self._toStore("CostFunctionJbAtCurrentOptimum"):
207 self.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJb"][IndexMin] )
208 if self._toStore("CostFunctionJoAtCurrentOptimum"):
209 self.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJo"][IndexMin] )
210 if self._toStore("CostFunctionJAtCurrentOptimum"):
211 self.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( self.StoredVariables["CostFunctionJ" ][IndexMin] )
214 def GradientOfCostFunction(x):
215 _X = numpy.asmatrix(numpy.ravel( x )).T
217 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
218 GradJb = BI * (_X - Xb)
219 GradJo = - Ha( (_X, RI * (Y - _HX)) )
220 GradJ = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
223 # Point de démarrage de l'optimisation : Xini = Xb
224 # ------------------------------------
225 Xini = numpy.ravel(Xb)
227 # Minimisation de la fonctionnelle
228 # --------------------------------
229 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
231 if self._parameters["Minimizer"] == "LBFGSB":
232 # Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
234 Minimum, J_optimal, Informations = lbfgsbhlt.fmin_l_bfgs_b(
237 fprime = GradientOfCostFunction,
239 bounds = self._parameters["Bounds"],
240 maxfun = self._parameters["MaximumNumberOfSteps"]-1,
241 factr = self._parameters["CostDecrementTolerance"]*1.e14,
242 pgtol = self._parameters["ProjectedGradientTolerance"],
243 iprint = self._parameters["optiprint"],
245 nfeval = Informations['funcalls']
246 rc = Informations['warnflag']
247 elif self._parameters["Minimizer"] == "TNC":
248 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
251 fprime = GradientOfCostFunction,
253 bounds = self._parameters["Bounds"],
254 maxfun = self._parameters["MaximumNumberOfSteps"],
255 pgtol = self._parameters["ProjectedGradientTolerance"],
256 ftol = self._parameters["CostDecrementTolerance"],
257 messages = self._parameters["optmessages"],
259 elif self._parameters["Minimizer"] == "CG":
260 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
263 fprime = GradientOfCostFunction,
265 maxiter = self._parameters["MaximumNumberOfSteps"],
266 gtol = self._parameters["GradientNormTolerance"],
267 disp = self._parameters["optdisp"],
270 elif self._parameters["Minimizer"] == "NCG":
271 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
274 fprime = GradientOfCostFunction,
276 maxiter = self._parameters["MaximumNumberOfSteps"],
277 avextol = self._parameters["CostDecrementTolerance"],
278 disp = self._parameters["optdisp"],
281 elif self._parameters["Minimizer"] == "BFGS":
282 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
285 fprime = GradientOfCostFunction,
287 maxiter = self._parameters["MaximumNumberOfSteps"],
288 gtol = self._parameters["GradientNormTolerance"],
289 disp = self._parameters["optdisp"],
293 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
295 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
296 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
298 # Correction pour pallier a un bug de TNC sur le retour du Minimum
299 # ----------------------------------------------------------------
300 if self._parameters["StoreInternalVariables"] or self._toStore("CurrentState"):
301 Minimum = self.StoredVariables["CurrentState"][IndexMin]
303 # Obtention de l'analyse
304 # ----------------------
305 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
307 self.StoredVariables["Analysis"].store( Xa.A1 )
309 if self._toStore("OMA") or \
310 self._toStore("SigmaObs2") or \
311 self._toStore("SimulationQuantiles") or \
312 self._toStore("SimulatedObservationAtOptimum"):
313 if self._toStore("SimulatedObservationAtCurrentState"):
314 HXa = self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
315 elif self._toStore("SimulatedObservationAtCurrentOptimum"):
316 HXa = self.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
320 # Calcul de la covariance d'analyse
321 # ---------------------------------
322 if self._toStore("APosterioriCovariance") or \
323 self._toStore("SimulationQuantiles"):
324 HtM = HO["Tangent"].asMatrix(ValueForMethodForm = Xa)
325 HtM = HtM.reshape(Y.size,Xa.size) # ADAO & check shape
326 HaM = HO["Adjoint"].asMatrix(ValueForMethodForm = Xa)
327 HaM = HaM.reshape(Xa.size,Y.size) # ADAO & check shape
331 _ee = numpy.matrix(numpy.zeros(nb)).T
333 _HtEE = numpy.dot(HtM,_ee)
334 _HtEE = numpy.asmatrix(numpy.ravel( _HtEE )).T
335 HessienneI.append( numpy.ravel( BI*_ee + HaM * (RI * _HtEE) ) )
336 HessienneI = numpy.matrix( HessienneI )
338 if min(A.shape) != max(A.shape):
339 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)))
340 if (numpy.diag(A) < 0).any():
341 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,))
342 if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
344 L = numpy.linalg.cholesky( A )
346 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,))
347 if self._toStore("APosterioriCovariance"):
348 self.StoredVariables["APosterioriCovariance"].store( A )
350 # Calculs et/ou stockages supplémentaires
351 # ---------------------------------------
352 if self._toStore("Innovation") or \
353 self._toStore("SigmaObs2") or \
354 self._toStore("MahalanobisConsistency") or \
355 self._toStore("OMB"):
357 if self._toStore("Innovation"):
358 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
359 if self._toStore("BMA"):
360 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
361 if self._toStore("OMA"):
362 self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
363 if self._toStore("OMB"):
364 self.StoredVariables["OMB"].store( numpy.ravel(d) )
365 if self._toStore("SigmaObs2"):
366 TraceR = R.trace(Y.size)
367 self.StoredVariables["SigmaObs2"].store( float( (d.T * (numpy.asmatrix(numpy.ravel(Y)).T-numpy.asmatrix(numpy.ravel(HXa)).T)) ) / TraceR )
368 if self._toStore("MahalanobisConsistency"):
369 self.StoredVariables["MahalanobisConsistency"].store( float( 2.*MinJ/d.size ) )
370 if self._toStore("SimulationQuantiles"):
371 nech = self._parameters["NumberOfSamplesForQuantiles"]
372 HXa = numpy.matrix(numpy.ravel( HXa )).T
374 for i in range(nech):
375 if self._parameters["SimulationForQuantiles"] == "Linear":
376 dXr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A) - Xa.A1).T
377 dYr = numpy.matrix(numpy.ravel( HtM * dXr )).T
379 elif self._parameters["SimulationForQuantiles"] == "NonLinear":
380 Xr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A)).T
381 Yr = numpy.matrix(numpy.ravel( Hm( Xr ) )).T
385 YfQ = numpy.hstack((YfQ,Yr))
388 for quantile in self._parameters["Quantiles"]:
389 if not (0. <= float(quantile) <= 1.): continue
390 indice = int(nech * float(quantile) - 1./nech)
391 if YQ is None: YQ = YfQ[:,indice]
392 else: YQ = numpy.hstack((YQ,YfQ[:,indice]))
393 self.StoredVariables["SimulationQuantiles"].store( YQ )
394 if self._toStore("SimulatedObservationAtBackground"):
395 self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
396 if self._toStore("SimulatedObservationAtOptimum"):
397 self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
402 # ==============================================================================
403 if __name__ == "__main__":
404 print('\n AUTODIAGNOSTIC \n')