]> SALOME platform Git repositories - modules/adao.git/blob - src/daComposant/daAlgorithms/3DVAR.py
Salome HOME
Unified management of supplementary variables to calculate or store
[modules/adao.git] / src / daComposant / daAlgorithms / 3DVAR.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2012 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, PlatformInfo
25 m = PlatformInfo.SystemUsage()
26
27 import numpy
28 import scipy.optimize
29
30 if logging.getLogger().level < logging.WARNING:
31     iprint  = 1
32     message = scipy.optimize.tnc.MSG_ALL
33     disp    = 1
34 else:
35     iprint  = -1
36     message = scipy.optimize.tnc.MSG_NONE
37     disp    = 0
38
39 # ==============================================================================
40 class ElementaryAlgorithm(BasicObjects.Algorithm):
41     def __init__(self):
42         BasicObjects.Algorithm.__init__(self, "3DVAR")
43         self.defineRequiredParameter(
44             name     = "Minimizer",
45             default  = "LBFGSB",
46             typecast = str,
47             message  = "Minimiseur utilisé",
48             listval  = ["LBFGSB","TNC", "CG", "NCG", "BFGS"],
49             )
50         self.defineRequiredParameter(
51             name     = "MaximumNumberOfSteps",
52             default  = 15000,
53             typecast = int,
54             message  = "Nombre maximal de pas d'optimisation",
55             minval   = -1,
56             )
57         self.defineRequiredParameter(
58             name     = "CostDecrementTolerance",
59             default  = 1.e-7,
60             typecast = float,
61             message  = "Diminution relative minimale du cout lors de l'arrêt",
62             )
63         self.defineRequiredParameter(
64             name     = "ProjectedGradientTolerance",
65             default  = -1,
66             typecast = float,
67             message  = "Maximum des composantes du gradient projeté lors de l'arrêt",
68             minval   = -1,
69             )
70         self.defineRequiredParameter(
71             name     = "GradientNormTolerance",
72             default  = 1.e-05,
73             typecast = float,
74             message  = "Maximum des composantes du gradient lors de l'arrêt",
75             )
76         self.defineRequiredParameter(
77             name     = "StoreInternalVariables",
78             default  = False,
79             typecast = bool,
80             message  = "Stockage des variables internes ou intermédiaires du calcul",
81             )
82         self.defineRequiredParameter(
83             name     = "StoreSupplementaryCalculations",
84             default  = [],
85             typecast = tuple,
86             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
87             listval  = ["APosterioriCovariance", "BMA", "OMA", "OMB", "Innovation", "SigmaObs2"]
88             )
89
90     def run(self, Xb=None, Y=None, H=None, M=None, R=None, B=None, Q=None, Parameters=None):
91         """
92         Calcul de l'estimateur 3D-VAR
93         """
94         logging.debug("%s Lancement"%self._name)
95         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
96         #
97         # Paramètres de pilotage
98         # ----------------------
99         self.setParameters(Parameters)
100         #
101         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):
102             Bounds = self._parameters["Bounds"]
103             logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
104         else:
105             Bounds = None
106         #
107         # Correction pour pallier a un bug de TNC sur le retour du Minimum
108         if self._parameters.has_key("Minimizer") is "TNC":
109             self.setParameterValue("StoreInternalVariables",True)
110         #
111         # Opérateur d'observation
112         # -----------------------
113         Hm = H["Direct"].appliedTo
114         Ha = H["Adjoint"].appliedInXTo
115         #
116         # Utilisation éventuelle d'un vecteur H(Xb) précalculé
117         # ----------------------------------------------------
118         if H["AppliedToX"] is not None and H["AppliedToX"].has_key("HXb"):
119             logging.debug("%s Utilisation de HXb"%self._name)
120             HXb = H["AppliedToX"]["HXb"]
121         else:
122             logging.debug("%s Calcul de Hm(Xb)"%self._name)
123             HXb = Hm( Xb )
124         HXb = numpy.asmatrix(HXb).flatten().T
125         #
126         # Calcul de l'innovation
127         # ----------------------
128         if Y.size != HXb.size:
129             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))
130         if max(Y.shape) != max(HXb.shape):
131             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))
132         d  = Y - HXb
133         logging.debug("%s Innovation d = %s"%(self._name, d))
134         #
135         # Précalcul des inversions de B et R
136         # ----------------------------------
137         if B is not None:
138             BI = B.I
139         elif self._parameters["B_scalar"] is not None:
140             BI = 1.0 / self._parameters["B_scalar"]
141         else:
142             raise ValueError("Background error covariance matrix has to be properly defined!")
143         #
144         if R is not None:
145             RI = R.I
146         elif self._parameters["R_scalar"] is not None:
147             RI = 1.0 / self._parameters["R_scalar"]
148         else:
149             raise ValueError("Observation error covariance matrix has to be properly defined!")
150         #
151         # Définition de la fonction-coût
152         # ------------------------------
153         def CostFunction(x):
154             _X  = numpy.asmatrix(x).flatten().T
155             logging.debug("%s CostFunction X  = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
156             _HX = Hm( _X )
157             _HX = numpy.asmatrix(_HX).flatten().T
158             Jb  = 0.5 * (_X - Xb).T * BI * (_X - Xb)
159             Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
160             J   = float( Jb ) + float( Jo )
161             logging.debug("%s CostFunction Jb = %s"%(self._name, Jb))
162             logging.debug("%s CostFunction Jo = %s"%(self._name, Jo))
163             logging.debug("%s CostFunction J  = %s"%(self._name, J))
164             if self._parameters["StoreInternalVariables"]:
165                 self.StoredVariables["CurrentState"].store( _X.A1 )
166             self.StoredVariables["CostFunctionJb"].store( Jb )
167             self.StoredVariables["CostFunctionJo"].store( Jo )
168             self.StoredVariables["CostFunctionJ" ].store( J )
169             return float( J )
170         #
171         def GradientOfCostFunction(x):
172             _X      = numpy.asmatrix(x).flatten().T
173             logging.debug("%s GradientOfCostFunction X      = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
174             _HX     = Hm( _X )
175             _HX     = numpy.asmatrix(_HX).flatten().T
176             GradJb  = BI * (_X - Xb)
177             GradJo  = - Ha( (_X, RI * (Y - _HX)) )
178             GradJ   = numpy.asmatrix( GradJb ).flatten().T + numpy.asmatrix( GradJo ).flatten().T
179             logging.debug("%s GradientOfCostFunction GradJb = %s"%(self._name, numpy.asmatrix( GradJb ).flatten()))
180             logging.debug("%s GradientOfCostFunction GradJo = %s"%(self._name, numpy.asmatrix( GradJo ).flatten()))
181             logging.debug("%s GradientOfCostFunction GradJ  = %s"%(self._name, numpy.asmatrix( GradJ  ).flatten()))
182             return GradJ.A1
183         #
184         # Point de démarrage de l'optimisation : Xini = Xb
185         # ------------------------------------
186         if type(Xb) is type(numpy.matrix([])):
187             Xini = Xb.A1.tolist()
188         else:
189             Xini = list(Xb)
190         logging.debug("%s Point de démarrage Xini = %s"%(self._name, Xini))
191         #
192         # Minimisation de la fonctionnelle
193         # --------------------------------
194         if self._parameters["Minimizer"] == "LBFGSB":
195             Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
196                 func        = CostFunction,
197                 x0          = Xini,
198                 fprime      = GradientOfCostFunction,
199                 args        = (),
200                 bounds      = Bounds,
201                 maxfun      = self._parameters["MaximumNumberOfSteps"]-1,
202                 factr       = self._parameters["CostDecrementTolerance"]*1.e14,
203                 pgtol       = self._parameters["ProjectedGradientTolerance"],
204                 iprint      = iprint,
205                 )
206             nfeval = Informations['funcalls']
207             rc     = Informations['warnflag']
208         elif self._parameters["Minimizer"] == "TNC":
209             Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
210                 func        = CostFunction,
211                 x0          = Xini,
212                 fprime      = GradientOfCostFunction,
213                 args        = (),
214                 bounds      = Bounds,
215                 maxfun      = self._parameters["MaximumNumberOfSteps"],
216                 pgtol       = self._parameters["ProjectedGradientTolerance"],
217                 ftol        = self._parameters["CostDecrementTolerance"],
218                 messages    = message,
219                 )
220         elif self._parameters["Minimizer"] == "CG":
221             Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
222                 f           = CostFunction,
223                 x0          = Xini,
224                 fprime      = GradientOfCostFunction,
225                 args        = (),
226                 maxiter     = self._parameters["MaximumNumberOfSteps"],
227                 gtol        = self._parameters["GradientNormTolerance"],
228                 disp        = disp,
229                 full_output = True,
230                 )
231         elif self._parameters["Minimizer"] == "NCG":
232             Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
233                 f           = CostFunction,
234                 x0          = Xini,
235                 fprime      = GradientOfCostFunction,
236                 args        = (),
237                 maxiter     = self._parameters["MaximumNumberOfSteps"],
238                 avextol     = self._parameters["CostDecrementTolerance"],
239                 disp        = disp,
240                 full_output = True,
241                 )
242         elif self._parameters["Minimizer"] == "BFGS":
243             Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
244                 f           = CostFunction,
245                 x0          = Xini,
246                 fprime      = GradientOfCostFunction,
247                 args        = (),
248                 maxiter     = self._parameters["MaximumNumberOfSteps"],
249                 gtol        = self._parameters["GradientNormTolerance"],
250                 disp        = disp,
251                 full_output = True,
252                 )
253         else:
254             raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
255         #
256         StepMin = numpy.argmin( self.StoredVariables["CostFunctionJ"].valueserie() )
257         MinJ    = self.StoredVariables["CostFunctionJ"].valueserie(step = StepMin)
258         #
259         # Correction pour pallier a un bug de TNC sur le retour du Minimum
260         # ----------------------------------------------------------------
261         if self._parameters["StoreInternalVariables"]:
262             Minimum = self.StoredVariables["CurrentState"].valueserie(step = StepMin)
263         #
264         logging.debug("%s %s Step of min cost  = %s"%(self._name, self._parameters["Minimizer"], StepMin))
265         logging.debug("%s %s Minimum cost      = %s"%(self._name, self._parameters["Minimizer"], MinJ))
266         logging.debug("%s %s Minimum state     = %s"%(self._name, self._parameters["Minimizer"], Minimum))
267         logging.debug("%s %s Nb of F           = %s"%(self._name, self._parameters["Minimizer"], nfeval))
268         logging.debug("%s %s RetCode           = %s"%(self._name, self._parameters["Minimizer"], rc))
269         #
270         # Obtention de l'analyse
271         # ----------------------
272         Xa = numpy.asmatrix(Minimum).flatten().T
273         logging.debug("%s Analyse Xa = %s"%(self._name, Xa))
274         #
275         self.StoredVariables["Analysis"].store( Xa.A1 )
276         #
277         # Calcul de la covariance d'analyse
278         # ---------------------------------
279         if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
280             HessienneI = []
281             nb = len(Xini)
282             for i in range(nb):
283                 _ee    = numpy.matrix(numpy.zeros(nb)).T
284                 _ee[i] = 1.
285                 _HmEE  = Hm(_ee)
286                 _HmEE  = numpy.asmatrix(_HmEE).flatten().T
287                 HessienneI.append( ( BI*_ee + Ha((Xa,RI*_HmEE)) ).A1 )
288             HessienneI = numpy.matrix( HessienneI )
289             A = HessienneI.I
290             if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
291                 try:
292                     L = numpy.linalg.cholesky( A )
293                 except:
294                     raise ValueError("The 3DVAR a posteriori covariance matrix A is not symmetric positive-definite. Check your B and R a priori covariances.")
295             self.StoredVariables["APosterioriCovariance"].store( A )
296         #
297         # Calculs et/ou stockages supplémentaires
298         # ---------------------------------------
299         if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
300             self.StoredVariables["Innovation"].store( numpy.asmatrix(d).flatten().A1 )
301         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
302             self.StoredVariables["BMA"].store( numpy.asmatrix(Xb - Xa).flatten().A1 )
303         if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
304             self.StoredVariables["OMA"].store( numpy.asmatrix(Y - Hm(Xa)).flatten().A1 )
305         if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
306             self.StoredVariables["OMB"].store( numpy.asmatrix(d).flatten().A1 )
307         if "SigmaObs2" in self._parameters["StoreSupplementaryCalculations"]:
308             self.StoredVariables["SigmaObs2"].store( float( (d.T * (Y-Hm(Xa))) / R.trace() ) )
309         #
310         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
311         logging.debug("%s Terminé"%self._name)
312         #
313         return 0
314
315 # ==============================================================================
316 if __name__ == "__main__":
317     print '\n AUTODIAGNOSTIC \n'