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