]> SALOME platform Git repositories - modules/adao.git/blob - src/daComposant/daAlgorithms/3DVAR.py
Salome HOME
Update internal settings
[modules/adao.git] / src / daComposant / daAlgorithms / 3DVAR.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2019 EDF R&D
4 #
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.
9 #
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.
14 #
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
18 #
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #
21 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
22
23 import logging
24 from daCore import BasicObjects
25 import numpy, scipy.optimize
26
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
29     def __init__(self):
30         BasicObjects.Algorithm.__init__(self, "3DVAR")
31         self.defineRequiredParameter(
32             name     = "Minimizer",
33             default  = "LBFGSB",
34             typecast = str,
35             message  = "Minimiseur utilisé",
36             listval  = ["LBFGSB","TNC", "CG", "NCG", "BFGS"],
37             )
38         self.defineRequiredParameter(
39             name     = "MaximumNumberOfSteps",
40             default  = 15000,
41             typecast = int,
42             message  = "Nombre maximal de pas d'optimisation",
43             minval   = -1,
44             )
45         self.defineRequiredParameter(
46             name     = "CostDecrementTolerance",
47             default  = 1.e-7,
48             typecast = float,
49             message  = "Diminution relative minimale du coût lors de l'arrêt",
50             minval   = 0.,
51             )
52         self.defineRequiredParameter(
53             name     = "ProjectedGradientTolerance",
54             default  = -1,
55             typecast = float,
56             message  = "Maximum des composantes du gradient projeté lors de l'arrêt",
57             minval   = -1,
58             )
59         self.defineRequiredParameter(
60             name     = "GradientNormTolerance",
61             default  = 1.e-05,
62             typecast = float,
63             message  = "Maximum des composantes du gradient lors de l'arrêt",
64             minval   = 0.,
65             )
66         self.defineRequiredParameter(
67             name     = "StoreInternalVariables",
68             default  = False,
69             typecast = bool,
70             message  = "Stockage des variables internes ou intermédiaires du calcul",
71             )
72         self.defineRequiredParameter(
73             name     = "StoreSupplementaryCalculations",
74             default  = [],
75             typecast = tuple,
76             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
77             listval  = [
78                 "APosterioriCorrelations",
79                 "APosterioriCovariance",
80                 "APosterioriStandardDeviations",
81                 "APosterioriVariances",
82                 "BMA",
83                 "CostFunctionJ",
84                 "CostFunctionJAtCurrentOptimum",
85                 "CostFunctionJb",
86                 "CostFunctionJbAtCurrentOptimum",
87                 "CostFunctionJo",
88                 "CostFunctionJoAtCurrentOptimum",
89                 "CurrentOptimum",
90                 "CurrentState",
91                 "IndexOfOptimum",
92                 "Innovation",
93                 "InnovationAtCurrentState",
94                 "MahalanobisConsistency",
95                 "OMA",
96                 "OMB",
97                 "SigmaObs2",
98                 "SimulatedObservationAtBackground",
99                 "SimulatedObservationAtCurrentOptimum",
100                 "SimulatedObservationAtCurrentState",
101                 "SimulatedObservationAtOptimum",
102                 "SimulationQuantiles",
103                 ]
104             )
105         self.defineRequiredParameter(
106             name     = "Quantiles",
107             default  = [],
108             typecast = tuple,
109             message  = "Liste des valeurs de quantiles",
110             minval   = 0.,
111             maxval   = 1.,
112             )
113         self.defineRequiredParameter(
114             name     = "SetSeed",
115             typecast = numpy.random.seed,
116             message  = "Graine fixée pour le générateur aléatoire",
117             )
118         self.defineRequiredParameter(
119             name     = "NumberOfSamplesForQuantiles",
120             default  = 100,
121             typecast = int,
122             message  = "Nombre d'échantillons simulés pour le calcul des quantiles",
123             minval   = 1,
124             )
125         self.defineRequiredParameter(
126             name     = "SimulationForQuantiles",
127             default  = "Linear",
128             typecast = str,
129             message  = "Type de simulation pour l'estimation des quantiles",
130             listval  = ["Linear", "NonLinear"]
131             )
132         self.defineRequiredParameter( # Pas de type
133             name     = "Bounds",
134             message  = "Liste des valeurs de bornes",
135             )
136         self.requireInputArguments(
137             mandatory= ("Xb", "Y", "HO", "R", "B" ),
138             )
139
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)
142         #
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)
146         #
147         # Opérateurs
148         # ----------
149         Hm = HO["Direct"].appliedTo
150         Ha = HO["Adjoint"].appliedInXTo
151         #
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"] )
156         else:
157             HXb = Hm( Xb )
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))
163         #
164         # Précalcul des inversions de B et R
165         # ----------------------------------
166         BI = B.getI()
167         RI = R.getI()
168         #
169         # Définition de la fonction-coût
170         # ------------------------------
171         def CostFunction(x):
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 )
177             _HX = Hm( _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 )
185             #
186             Jb  = float( 0.5 * (_X - Xb).T * BI * (_X - Xb) )
187             Jo  = float( 0.5 * _Innovation.T * RI * _Innovation )
188             J   = Jb + Jo
189             #
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] )
212             return J
213         #
214         def GradientOfCostFunction(x):
215             _X      = numpy.asmatrix(numpy.ravel( x )).T
216             _HX     = Hm( _X )
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
221             return GradJ.A1
222         #
223         # Point de démarrage de l'optimisation : Xini = Xb
224         # ------------------------------------
225         Xini = numpy.ravel(Xb)
226         #
227         # Minimisation de la fonctionnelle
228         # --------------------------------
229         nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
230         #
231         if self._parameters["Minimizer"] == "LBFGSB":
232             # Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
233             import lbfgsbhlt
234             Minimum, J_optimal, Informations = lbfgsbhlt.fmin_l_bfgs_b(
235                 func        = CostFunction,
236                 x0          = Xini,
237                 fprime      = GradientOfCostFunction,
238                 args        = (),
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"],
244                 )
245             nfeval = Informations['funcalls']
246             rc     = Informations['warnflag']
247         elif self._parameters["Minimizer"] == "TNC":
248             Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
249                 func        = CostFunction,
250                 x0          = Xini,
251                 fprime      = GradientOfCostFunction,
252                 args        = (),
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"],
258                 )
259         elif self._parameters["Minimizer"] == "CG":
260             Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
261                 f           = CostFunction,
262                 x0          = Xini,
263                 fprime      = GradientOfCostFunction,
264                 args        = (),
265                 maxiter     = self._parameters["MaximumNumberOfSteps"],
266                 gtol        = self._parameters["GradientNormTolerance"],
267                 disp        = self._parameters["optdisp"],
268                 full_output = True,
269                 )
270         elif self._parameters["Minimizer"] == "NCG":
271             Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
272                 f           = CostFunction,
273                 x0          = Xini,
274                 fprime      = GradientOfCostFunction,
275                 args        = (),
276                 maxiter     = self._parameters["MaximumNumberOfSteps"],
277                 avextol     = self._parameters["CostDecrementTolerance"],
278                 disp        = self._parameters["optdisp"],
279                 full_output = True,
280                 )
281         elif self._parameters["Minimizer"] == "BFGS":
282             Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
283                 f           = CostFunction,
284                 x0          = Xini,
285                 fprime      = GradientOfCostFunction,
286                 args        = (),
287                 maxiter     = self._parameters["MaximumNumberOfSteps"],
288                 gtol        = self._parameters["GradientNormTolerance"],
289                 disp        = self._parameters["optdisp"],
290                 full_output = True,
291                 )
292         else:
293             raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
294         #
295         IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
296         MinJ     = self.StoredVariables["CostFunctionJ"][IndexMin]
297         #
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]
302         #
303         # Obtention de l'analyse
304         # ----------------------
305         Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
306         #
307         self.StoredVariables["Analysis"].store( Xa.A1 )
308         #
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]
317             else:
318                 HXa = Hm( Xa )
319         #
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
328             HessienneI = []
329             nb = Xa.size
330             for i in range(nb):
331                 _ee    = numpy.matrix(numpy.zeros(nb)).T
332                 _ee[i] = 1.
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 )
337             A = HessienneI.I
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
343                 try:
344                     L = numpy.linalg.cholesky( A )
345                 except:
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 )
349         #
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"):
356             d  = Y - HXb
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
373             YfQ  = None
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
378                     Yr = HXa + dYr
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
382                 if YfQ is None:
383                     YfQ = Yr
384                 else:
385                     YfQ = numpy.hstack((YfQ,Yr))
386             YfQ.sort(axis=-1)
387             YQ = None
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) )
398         #
399         self._post_run(HO)
400         return 0
401
402 # ==============================================================================
403 if __name__ == "__main__":
404     print('\n AUTODIAGNOSTIC \n')