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