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