Salome HOME
Compatibility fix for algorithm output variables clarity
[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                 "Analysis",
79                 "APosterioriCorrelations",
80                 "APosterioriCovariance",
81                 "APosterioriStandardDeviations",
82                 "APosterioriVariances",
83                 "BMA",
84                 "CostFunctionJ",
85                 "CostFunctionJAtCurrentOptimum",
86                 "CostFunctionJb",
87                 "CostFunctionJbAtCurrentOptimum",
88                 "CostFunctionJo",
89                 "CostFunctionJoAtCurrentOptimum",
90                 "CurrentOptimum",
91                 "CurrentState",
92                 "IndexOfOptimum",
93                 "Innovation",
94                 "InnovationAtCurrentState",
95                 "JacobianMatrixAtBackground",
96                 "JacobianMatrixAtOptimum",
97                 "KalmanGainAtOptimum",
98                 "MahalanobisConsistency",
99                 "OMA",
100                 "OMB",
101                 "SigmaObs2",
102                 "SimulatedObservationAtBackground",
103                 "SimulatedObservationAtCurrentOptimum",
104                 "SimulatedObservationAtCurrentState",
105                 "SimulatedObservationAtOptimum",
106                 "SimulationQuantiles",
107                 ]
108             )
109         self.defineRequiredParameter(
110             name     = "Quantiles",
111             default  = [],
112             typecast = tuple,
113             message  = "Liste des valeurs de quantiles",
114             minval   = 0.,
115             maxval   = 1.,
116             )
117         self.defineRequiredParameter(
118             name     = "SetSeed",
119             typecast = numpy.random.seed,
120             message  = "Graine fixée pour le générateur aléatoire",
121             )
122         self.defineRequiredParameter(
123             name     = "NumberOfSamplesForQuantiles",
124             default  = 100,
125             typecast = int,
126             message  = "Nombre d'échantillons simulés pour le calcul des quantiles",
127             minval   = 1,
128             )
129         self.defineRequiredParameter(
130             name     = "SimulationForQuantiles",
131             default  = "Linear",
132             typecast = str,
133             message  = "Type de simulation pour l'estimation des quantiles",
134             listval  = ["Linear", "NonLinear"]
135             )
136         self.defineRequiredParameter( # Pas de type
137             name     = "Bounds",
138             message  = "Liste des valeurs de bornes",
139             )
140         self.requireInputArguments(
141             mandatory= ("Xb", "Y", "HO", "R", "B" ),
142             )
143
144     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
145         self._pre_run(Parameters, Xb, Y, R, B, Q)
146         #
147         # Correction pour pallier a un bug de TNC sur le retour du Minimum
148         if "Minimizer" in self._parameters and self._parameters["Minimizer"] == "TNC":
149             self.setParameterValue("StoreInternalVariables",True)
150         #
151         # Opérateurs
152         # ----------
153         Hm = HO["Direct"].appliedTo
154         Ha = HO["Adjoint"].appliedInXTo
155         #
156         # Utilisation éventuelle d'un vecteur H(Xb) précalculé
157         # ----------------------------------------------------
158         if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
159             HXb = Hm( Xb, HO["AppliedInX"]["HXb"] )
160         else:
161             HXb = Hm( Xb )
162         HXb = numpy.asmatrix(numpy.ravel( HXb )).T
163         if Y.size != HXb.size:
164             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))
165         if max(Y.shape) != max(HXb.shape):
166             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))
167         #
168         if self._toStore("JacobianMatrixAtBackground"):
169             HtMb = HO["Tangent"].asMatrix(ValueForMethodForm = Xb)
170             HtMb = HtMb.reshape(Y.size,Xb.size) # ADAO & check shape
171             self.StoredVariables["JacobianMatrixAtBackground"].store( HtMb )
172         #
173         # Précalcul des inversions de B et R
174         # ----------------------------------
175         BI = B.getI()
176         RI = R.getI()
177         #
178         # Définition de la fonction-coût
179         # ------------------------------
180         def CostFunction(x):
181             _X  = numpy.asmatrix(numpy.ravel( x )).T
182             if self._parameters["StoreInternalVariables"] or \
183                 self._toStore("CurrentState") or \
184                 self._toStore("CurrentOptimum"):
185                 self.StoredVariables["CurrentState"].store( _X )
186             _HX = Hm( _X )
187             _HX = numpy.asmatrix(numpy.ravel( _HX )).T
188             _Innovation = Y - _HX
189             if self._toStore("SimulatedObservationAtCurrentState") or \
190                 self._toStore("SimulatedObservationAtCurrentOptimum"):
191                 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
192             if self._toStore("InnovationAtCurrentState"):
193                 self.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
194             #
195             Jb  = float( 0.5 * (_X - Xb).T * BI * (_X - Xb) )
196             Jo  = float( 0.5 * _Innovation.T * RI * _Innovation )
197             J   = Jb + Jo
198             #
199             self.StoredVariables["CostFunctionJb"].store( Jb )
200             self.StoredVariables["CostFunctionJo"].store( Jo )
201             self.StoredVariables["CostFunctionJ" ].store( J )
202             if self._toStore("IndexOfOptimum") or \
203                 self._toStore("CurrentOptimum") or \
204                 self._toStore("CostFunctionJAtCurrentOptimum") or \
205                 self._toStore("CostFunctionJbAtCurrentOptimum") or \
206                 self._toStore("CostFunctionJoAtCurrentOptimum") or \
207                 self._toStore("SimulatedObservationAtCurrentOptimum"):
208                 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
209             if self._toStore("IndexOfOptimum"):
210                 self.StoredVariables["IndexOfOptimum"].store( IndexMin )
211             if self._toStore("CurrentOptimum"):
212                 self.StoredVariables["CurrentOptimum"].store( self.StoredVariables["CurrentState"][IndexMin] )
213             if self._toStore("SimulatedObservationAtCurrentOptimum"):
214                 self.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] )
215             if self._toStore("CostFunctionJbAtCurrentOptimum"):
216                 self.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJb"][IndexMin] )
217             if self._toStore("CostFunctionJoAtCurrentOptimum"):
218                 self.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJo"][IndexMin] )
219             if self._toStore("CostFunctionJAtCurrentOptimum"):
220                 self.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( self.StoredVariables["CostFunctionJ" ][IndexMin] )
221             return J
222         #
223         def GradientOfCostFunction(x):
224             _X      = numpy.asmatrix(numpy.ravel( x )).T
225             _HX     = Hm( _X )
226             _HX     = numpy.asmatrix(numpy.ravel( _HX )).T
227             GradJb  = BI * (_X - Xb)
228             GradJo  = - Ha( (_X, RI * (Y - _HX)) )
229             GradJ   = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
230             return GradJ.A1
231         #
232         # Point de démarrage de l'optimisation : Xini = Xb
233         # ------------------------------------
234         Xini = numpy.ravel(Xb)
235         #
236         # Minimisation de la fonctionnelle
237         # --------------------------------
238         nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
239         #
240         if self._parameters["Minimizer"] == "LBFGSB":
241             # Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
242             import lbfgsbhlt
243             Minimum, J_optimal, Informations = lbfgsbhlt.fmin_l_bfgs_b(
244                 func        = CostFunction,
245                 x0          = Xini,
246                 fprime      = GradientOfCostFunction,
247                 args        = (),
248                 bounds      = self._parameters["Bounds"],
249                 maxfun      = self._parameters["MaximumNumberOfSteps"]-1,
250                 factr       = self._parameters["CostDecrementTolerance"]*1.e14,
251                 pgtol       = self._parameters["ProjectedGradientTolerance"],
252                 iprint      = self._parameters["optiprint"],
253                 )
254             nfeval = Informations['funcalls']
255             rc     = Informations['warnflag']
256         elif self._parameters["Minimizer"] == "TNC":
257             Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
258                 func        = CostFunction,
259                 x0          = Xini,
260                 fprime      = GradientOfCostFunction,
261                 args        = (),
262                 bounds      = self._parameters["Bounds"],
263                 maxfun      = self._parameters["MaximumNumberOfSteps"],
264                 pgtol       = self._parameters["ProjectedGradientTolerance"],
265                 ftol        = self._parameters["CostDecrementTolerance"],
266                 messages    = self._parameters["optmessages"],
267                 )
268         elif self._parameters["Minimizer"] == "CG":
269             Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
270                 f           = CostFunction,
271                 x0          = Xini,
272                 fprime      = GradientOfCostFunction,
273                 args        = (),
274                 maxiter     = self._parameters["MaximumNumberOfSteps"],
275                 gtol        = self._parameters["GradientNormTolerance"],
276                 disp        = self._parameters["optdisp"],
277                 full_output = True,
278                 )
279         elif self._parameters["Minimizer"] == "NCG":
280             Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
281                 f           = CostFunction,
282                 x0          = Xini,
283                 fprime      = GradientOfCostFunction,
284                 args        = (),
285                 maxiter     = self._parameters["MaximumNumberOfSteps"],
286                 avextol     = self._parameters["CostDecrementTolerance"],
287                 disp        = self._parameters["optdisp"],
288                 full_output = True,
289                 )
290         elif self._parameters["Minimizer"] == "BFGS":
291             Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
292                 f           = CostFunction,
293                 x0          = Xini,
294                 fprime      = GradientOfCostFunction,
295                 args        = (),
296                 maxiter     = self._parameters["MaximumNumberOfSteps"],
297                 gtol        = self._parameters["GradientNormTolerance"],
298                 disp        = self._parameters["optdisp"],
299                 full_output = True,
300                 )
301         else:
302             raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
303         #
304         IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
305         MinJ     = self.StoredVariables["CostFunctionJ"][IndexMin]
306         #
307         # Correction pour pallier a un bug de TNC sur le retour du Minimum
308         # ----------------------------------------------------------------
309         if self._parameters["StoreInternalVariables"] or self._toStore("CurrentState"):
310             Minimum = self.StoredVariables["CurrentState"][IndexMin]
311         #
312         # Obtention de l'analyse
313         # ----------------------
314         Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
315         #
316         self.StoredVariables["Analysis"].store( Xa.A1 )
317         #
318         if self._toStore("OMA") or \
319             self._toStore("SigmaObs2") or \
320             self._toStore("SimulationQuantiles") or \
321             self._toStore("SimulatedObservationAtOptimum"):
322             if self._toStore("SimulatedObservationAtCurrentState"):
323                 HXa = self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
324             elif self._toStore("SimulatedObservationAtCurrentOptimum"):
325                 HXa = self.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
326             else:
327                 HXa = Hm( Xa )
328         #
329         # Calcul de la covariance d'analyse
330         # ---------------------------------
331         if self._toStore("APosterioriCovariance") or \
332             self._toStore("SimulationQuantiles") or \
333             self._toStore("JacobianMatrixAtOptimum") or \
334             self._toStore("KalmanGainAtOptimum"):
335             HtM = HO["Tangent"].asMatrix(ValueForMethodForm = Xa)
336             HtM = HtM.reshape(Y.size,Xa.size) # ADAO & check shape
337         if self._toStore("APosterioriCovariance") or \
338             self._toStore("SimulationQuantiles") or \
339             self._toStore("KalmanGainAtOptimum"):
340             HaM = HO["Adjoint"].asMatrix(ValueForMethodForm = Xa)
341             HaM = HaM.reshape(Xa.size,Y.size) # ADAO & check shape
342         if self._toStore("APosterioriCovariance") or \
343             self._toStore("SimulationQuantiles"):
344             HessienneI = []
345             nb = Xa.size
346             for i in range(nb):
347                 _ee    = numpy.matrix(numpy.zeros(nb)).T
348                 _ee[i] = 1.
349                 _HtEE  = numpy.dot(HtM,_ee)
350                 _HtEE  = numpy.asmatrix(numpy.ravel( _HtEE )).T
351                 HessienneI.append( numpy.ravel( BI*_ee + HaM * (RI * _HtEE) ) )
352             HessienneI = numpy.matrix( HessienneI )
353             A = HessienneI.I
354             if min(A.shape) != max(A.shape):
355                 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)))
356             if (numpy.diag(A) < 0).any():
357                 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,))
358             if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
359                 try:
360                     L = numpy.linalg.cholesky( A )
361                 except:
362                     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,))
363         if self._toStore("APosterioriCovariance"):
364             self.StoredVariables["APosterioriCovariance"].store( A )
365         if self._toStore("JacobianMatrixAtOptimum"):
366             self.StoredVariables["JacobianMatrixAtOptimum"].store( HtM )
367         if self._toStore("KalmanGainAtOptimum"):
368             if   (Y.size <= Xb.size): KG  = B * HaM * (R + numpy.dot(HtM, B * HaM)).I
369             elif (Y.size >  Xb.size): KG = (BI + numpy.dot(HaM, RI * HtM)).I * HaM * RI
370             self.StoredVariables["KalmanGainAtOptimum"].store( KG )
371         #
372         # Calculs et/ou stockages supplémentaires
373         # ---------------------------------------
374         if self._toStore("Innovation") or \
375             self._toStore("SigmaObs2") or \
376             self._toStore("MahalanobisConsistency") or \
377             self._toStore("OMB"):
378             d  = Y - HXb
379         if self._toStore("Innovation"):
380             self.StoredVariables["Innovation"].store( numpy.ravel(d) )
381         if self._toStore("BMA"):
382             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
383         if self._toStore("OMA"):
384             self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
385         if self._toStore("OMB"):
386             self.StoredVariables["OMB"].store( numpy.ravel(d) )
387         if self._toStore("SigmaObs2"):
388             TraceR = R.trace(Y.size)
389             self.StoredVariables["SigmaObs2"].store( float( (d.T * (numpy.asmatrix(numpy.ravel(Y)).T-numpy.asmatrix(numpy.ravel(HXa)).T)) ) / TraceR )
390         if self._toStore("MahalanobisConsistency"):
391             self.StoredVariables["MahalanobisConsistency"].store( float( 2.*MinJ/d.size ) )
392         if self._toStore("SimulationQuantiles"):
393             nech = self._parameters["NumberOfSamplesForQuantiles"]
394             HXa  = numpy.matrix(numpy.ravel( HXa )).T
395             YfQ  = None
396             for i in range(nech):
397                 if self._parameters["SimulationForQuantiles"] == "Linear":
398                     dXr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A) - Xa.A1).T
399                     dYr = numpy.matrix(numpy.ravel( HtM * dXr )).T
400                     Yr = HXa + dYr
401                 elif self._parameters["SimulationForQuantiles"] == "NonLinear":
402                     Xr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A)).T
403                     Yr = numpy.matrix(numpy.ravel( Hm( Xr ) )).T
404                 if YfQ is None:
405                     YfQ = Yr
406                 else:
407                     YfQ = numpy.hstack((YfQ,Yr))
408             YfQ.sort(axis=-1)
409             YQ = None
410             for quantile in self._parameters["Quantiles"]:
411                 if not (0. <= float(quantile) <= 1.): continue
412                 indice = int(nech * float(quantile) - 1./nech)
413                 if YQ is None: YQ = YfQ[:,indice]
414                 else:          YQ = numpy.hstack((YQ,YfQ[:,indice]))
415             self.StoredVariables["SimulationQuantiles"].store( YQ )
416         if self._toStore("SimulatedObservationAtBackground"):
417             self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
418         if self._toStore("SimulatedObservationAtOptimum"):
419             self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
420         #
421         self._post_run(HO)
422         return 0
423
424 # ==============================================================================
425 if __name__ == "__main__":
426     print('\n AUTODIAGNOSTIC \n')