]> SALOME platform Git repositories - modules/adao.git/blob - src/daComposant/daAlgorithms/3DVAR.py
Salome HOME
Changing internally treatment of algorithm parameters
[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 < 30:
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
82     def run(self, Xb=None, Y=None, H=None, M=None, R=None, B=None, Q=None, Parameters=None):
83         """
84         Calcul de l'estimateur 3D-VAR
85         """
86         logging.debug("%s Lancement"%self._name)
87         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("Mo")))
88         #
89         # Paramètres de pilotage
90         # ----------------------
91         self.setParameters(Parameters)
92         #
93         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):
94             Bounds = self._parameters["Bounds"]
95             logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
96         else:
97             Bounds = None
98         #
99         # Opérateur d'observation
100         # -----------------------
101         Hm = H["Direct"].appliedTo
102         Ha = H["Adjoint"].appliedInXTo
103         #
104         # Utilisation éventuelle d'un vecteur H(Xb) précalculé
105         # ----------------------------------------------------
106         if H["AppliedToX"] is not None and H["AppliedToX"].has_key("HXb"):
107             logging.debug("%s Utilisation de HXb"%self._name)
108             HXb = H["AppliedToX"]["HXb"]
109         else:
110             logging.debug("%s Calcul de Hm(Xb)"%self._name)
111             HXb = Hm( Xb )
112         HXb = numpy.asmatrix(HXb).flatten().T
113         #
114         # Calcul de l'innovation
115         # ----------------------
116         if Y.size != HXb.size:
117             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))
118         if max(Y.shape) != max(HXb.shape):
119             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))
120         d  = Y - HXb
121         logging.debug("%s Innovation d = %s"%(self._name, d))
122         #
123         # Précalcul des inversions de B et R
124         # ----------------------------------
125         if B is not None:
126             BI = B.I
127         elif self._parameters["B_scalar"] is not None:
128             BI = 1.0 / self._parameters["B_scalar"]
129         else:
130             raise ValueError("Background error covariance matrix has to be properly defined!")
131         #
132         if R is not None:
133             RI = R.I
134         elif self._parameters["R_scalar"] is not None:
135             RI = 1.0 / self._parameters["R_scalar"]
136         else:
137             raise ValueError("Observation error covariance matrix has to be properly defined!")
138         #
139         # Définition de la fonction-coût
140         # ------------------------------
141         def CostFunction(x):
142             _X  = numpy.asmatrix(x).flatten().T
143             logging.debug("%s CostFunction X  = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
144             _HX = Hm( _X )
145             _HX = numpy.asmatrix(_HX).flatten().T
146             Jb  = 0.5 * (_X - Xb).T * BI * (_X - Xb)
147             Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
148             J   = float( Jb ) + float( Jo )
149             logging.debug("%s CostFunction Jb = %s"%(self._name, Jb))
150             logging.debug("%s CostFunction Jo = %s"%(self._name, Jo))
151             logging.debug("%s CostFunction J  = %s"%(self._name, J))
152             self.StoredVariables["CurrentState"].store( _X.A1 )
153             self.StoredVariables["CostFunctionJb"].store( Jb )
154             self.StoredVariables["CostFunctionJo"].store( Jo )
155             self.StoredVariables["CostFunctionJ" ].store( J )
156             return float( J )
157         #
158         def GradientOfCostFunction(x):
159             _X      = numpy.asmatrix(x).flatten().T
160             logging.debug("%s GradientOfCostFunction X      = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
161             _HX     = Hm( _X )
162             _HX     = numpy.asmatrix(_HX).flatten().T
163             GradJb  = BI * (_X - Xb)
164             GradJo  = - Ha( (_X, RI * (Y - _HX)) )
165             GradJ   = numpy.asmatrix( GradJb ).flatten().T + numpy.asmatrix( GradJo ).flatten().T
166             logging.debug("%s GradientOfCostFunction GradJb = %s"%(self._name, numpy.asmatrix( GradJb ).flatten()))
167             logging.debug("%s GradientOfCostFunction GradJo = %s"%(self._name, numpy.asmatrix( GradJo ).flatten()))
168             logging.debug("%s GradientOfCostFunction GradJ  = %s"%(self._name, numpy.asmatrix( GradJ  ).flatten()))
169             return GradJ.A1
170         #
171         # Point de démarrage de l'optimisation : Xini = Xb
172         # ------------------------------------
173         if type(Xb) is type(numpy.matrix([])):
174             Xini = Xb.A1.tolist()
175         else:
176             Xini = list(Xb)
177         logging.debug("%s Point de démarrage Xini = %s"%(self._name, Xini))
178         #
179         # Minimisation de la fonctionnelle
180         # --------------------------------
181         if self._parameters["Minimizer"] == "LBFGSB":
182             Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
183                 func        = CostFunction,
184                 x0          = Xini,
185                 fprime      = GradientOfCostFunction,
186                 args        = (),
187                 bounds      = Bounds,
188                 maxfun      = self._parameters["MaximumNumberOfSteps"]-1,
189                 factr       = self._parameters["CostDecrementTolerance"]*1.e14,
190                 pgtol       = self._parameters["ProjectedGradientTolerance"],
191                 iprint      = iprint,
192                 )
193             nfeval = Informations['funcalls']
194             rc     = Informations['warnflag']
195         elif self._parameters["Minimizer"] == "TNC":
196             Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
197                 func        = CostFunction,
198                 x0          = Xini,
199                 fprime      = GradientOfCostFunction,
200                 args        = (),
201                 bounds      = Bounds,
202                 maxfun      = self._parameters["MaximumNumberOfSteps"],
203                 pgtol       = self._parameters["ProjectedGradientTolerance"],
204                 ftol        = self._parameters["CostDecrementTolerance"],
205                 messages    = message,
206                 )
207         elif self._parameters["Minimizer"] == "CG":
208             Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
209                 f           = CostFunction,
210                 x0          = Xini,
211                 fprime      = GradientOfCostFunction,
212                 args        = (),
213                 maxiter     = self._parameters["MaximumNumberOfSteps"],
214                 gtol        = self._parameters["GradientNormTolerance"],
215                 disp        = disp,
216                 full_output = True,
217                 )
218         elif self._parameters["Minimizer"] == "NCG":
219             Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
220                 f           = CostFunction,
221                 x0          = Xini,
222                 fprime      = GradientOfCostFunction,
223                 args        = (),
224                 maxiter     = self._parameters["MaximumNumberOfSteps"],
225                 avextol     = self._parameters["CostDecrementTolerance"],
226                 disp        = disp,
227                 full_output = True,
228                 )
229         elif self._parameters["Minimizer"] == "BFGS":
230             Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
231                 f           = CostFunction,
232                 x0          = Xini,
233                 fprime      = GradientOfCostFunction,
234                 args        = (),
235                 maxiter     = self._parameters["MaximumNumberOfSteps"],
236                 gtol        = self._parameters["GradientNormTolerance"],
237                 disp        = disp,
238                 full_output = True,
239                 )
240         else:
241             raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
242         #
243         # Correction pour pallier a un bug de TNC sur le retour du Minimum
244         # ----------------------------------------------------------------
245         StepMin = numpy.argmin( self.StoredVariables["CostFunctionJ"].valueserie() )
246         MinJ    = self.StoredVariables["CostFunctionJ"].valueserie(step = StepMin)
247         Minimum = self.StoredVariables["CurrentState"].valueserie(step = StepMin)
248         #
249         logging.debug("%s %s Step of min cost  = %s"%(self._name, self._parameters["Minimizer"], StepMin))
250         logging.debug("%s %s Minimum cost      = %s"%(self._name, self._parameters["Minimizer"], MinJ))
251         logging.debug("%s %s Minimum state     = %s"%(self._name, self._parameters["Minimizer"], Minimum))
252         logging.debug("%s %s Nb of F           = %s"%(self._name, self._parameters["Minimizer"], nfeval))
253         logging.debug("%s %s RetCode           = %s"%(self._name, self._parameters["Minimizer"], rc))
254         #
255         # Obtention de l'analyse
256         # ----------------------
257         Xa = numpy.asmatrix(Minimum).T
258         logging.debug("%s Analyse Xa = %s"%(self._name, Xa))
259         #
260         self.StoredVariables["Analysis"].store( Xa.A1 )
261         self.StoredVariables["Innovation"].store( d.A1 )
262         #
263         # Calcul de la covariance d'analyse
264         # ---------------------------------
265         if self._parameters["CalculateAPosterioriCovariance"]:
266             Hessienne = []
267             nb = len(Xini)
268             for i in range(nb):
269                 ee = numpy.matrix(numpy.zeros(nb)).T
270                 ee[i] = 1.
271                 Hessienne.append( ( BI*ee + Ha((Xa,RI*Hm(ee))) ).A1 )
272             Hessienne = numpy.matrix( Hessienne )
273             A = Hessienne.I
274             self.StoredVariables["APosterioriCovariance"].store( A )
275         #
276         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("MB")))
277         logging.debug("%s Terminé"%self._name)
278         #
279         return 0
280
281 # ==============================================================================
282 if __name__ == "__main__":
283     print '\n AUTODIAGNOSTIC \n'