Salome HOME
6210227822e4cbe018a6386b3d29f0ea533284cb
[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)
42         self._name = "3DVAR"
43         logging.debug("%s Initialisation"%self._name)
44
45     def run(self, Xb=None, Y=None, H=None, M=None, R=None, B=None, Q=None, Parameters=None):
46         """
47         Calcul de l'estimateur 3D-VAR
48         """
49         logging.debug("%s Lancement"%self._name)
50         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("Mo")))
51         #
52         # Opérateur d'observation
53         # -----------------------
54         Hm = H["Direct"].appliedTo
55         Ht = H["Adjoint"].appliedInXTo
56         #
57         # Utilisation éventuelle d'un vecteur H(Xb) précalculé
58         # ----------------------------------------------------
59         if H["AppliedToX"] is not None and H["AppliedToX"].has_key("HXb"):
60             logging.debug("%s Utilisation de HXb"%self._name)
61             HXb = H["AppliedToX"]["HXb"]
62         else:
63             logging.debug("%s Calcul de Hm(Xb)"%self._name)
64             HXb = Hm( Xb )
65         HXb = numpy.asmatrix(HXb).flatten().T
66         #
67         # Calcul de l'innovation
68         # ----------------------
69         if Y.size != HXb.size:
70             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))
71         if max(Y.shape) != max(HXb.shape):
72             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))
73         d  = Y - HXb
74         logging.debug("%s Innovation d = %s"%(self._name, d))
75         #
76         # Précalcul des inversions de B et R
77         # ----------------------------------
78         if B is not None:
79             BI = B.I
80         elif Parameters["B_scalar"] is not None:
81             BI = 1.0 / Parameters["B_scalar"]
82         #
83         if R is not None:
84             RI = R.I
85         elif Parameters["R_scalar"] is not None:
86             RI = 1.0 / Parameters["R_scalar"]
87         #
88         # Définition de la fonction-coût
89         # ------------------------------
90         def CostFunction(x):
91             _X  = numpy.asmatrix(x).flatten().T
92             logging.debug("%s CostFunction X  = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
93             _HX = Hm( _X )
94             _HX = numpy.asmatrix(_HX).flatten().T
95             Jb  = 0.5 * (_X - Xb).T * BI * (_X - Xb)
96             Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
97             J   = float( Jb ) + float( Jo )
98             logging.debug("%s CostFunction Jb = %s"%(self._name, Jb))
99             logging.debug("%s CostFunction Jo = %s"%(self._name, Jo))
100             logging.debug("%s CostFunction J  = %s"%(self._name, J))
101             self.StoredVariables["CurrentState"].store( _X.A1 )
102             self.StoredVariables["CostFunctionJb"].store( Jb )
103             self.StoredVariables["CostFunctionJo"].store( Jo )
104             self.StoredVariables["CostFunctionJ" ].store( J )
105             return float( J )
106         #
107         def GradientOfCostFunction(x):
108             _X      = numpy.asmatrix(x).flatten().T
109             logging.debug("%s GradientOfCostFunction X      = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
110             _HX     = Hm( _X )
111             _HX     = numpy.asmatrix(_HX).flatten().T
112             GradJb  = BI * (_X - Xb)
113             GradJo  = - Ht( (_X, RI * (Y - _HX)) )
114             GradJ   = numpy.asmatrix( GradJb ).flatten().T + numpy.asmatrix( GradJo ).flatten().T
115             logging.debug("%s GradientOfCostFunction GradJb = %s"%(self._name, numpy.asmatrix( GradJb ).flatten()))
116             logging.debug("%s GradientOfCostFunction GradJo = %s"%(self._name, numpy.asmatrix( GradJo ).flatten()))
117             logging.debug("%s GradientOfCostFunction GradJ  = %s"%(self._name, numpy.asmatrix( GradJ  ).flatten()))
118             return GradJ.A1
119         #
120         # Point de démarrage de l'optimisation : Xini = Xb
121         # ------------------------------------
122         if type(Xb) is type(numpy.matrix([])):
123             Xini = Xb.A1.tolist()
124         else:
125             Xini = list(Xb)
126         logging.debug("%s Point de démarrage Xini = %s"%(self._name, Xini))
127         #
128         # Paramètres de pilotage
129         # ----------------------
130         # Potentiels : "Bounds", "Minimizer", "MaximumNumberOfSteps", "ProjectedGradientTolerance", "GradientNormTolerance", "InnerMinimizer", "CalculateAPosterioriCovariance"
131         if Parameters.has_key("Bounds") and (type(Parameters["Bounds"]) is type([]) or type(Parameters["Bounds"]) is type(())) and (len(Parameters["Bounds"]) > 0):
132             Bounds = Parameters["Bounds"]
133         else:
134             Bounds = None
135         MinimizerList = ["LBFGSB","TNC", "CG", "NCG", "BFGS"]
136         if Parameters.has_key("Minimizer") and (Parameters["Minimizer"] in MinimizerList):
137             Minimizer = str( Parameters["Minimizer"] )
138         else:
139             Minimizer = "LBFGSB"
140             logging.warning("%s Unknown or undefined minimizer, replaced by the default one \"%s\""%(self._name,Minimizer))
141         logging.debug("%s Minimiseur utilisé = %s"%(self._name, Minimizer))
142         if Parameters.has_key("MaximumNumberOfSteps") and (Parameters["MaximumNumberOfSteps"] > -1):
143             maxiter = int( Parameters["MaximumNumberOfSteps"] )
144         else:
145             maxiter = 15000
146         logging.debug("%s Nombre maximal de pas d'optimisation = %s"%(self._name, str(maxiter)))
147         if Parameters.has_key("CostDecrementTolerance") and (Parameters["CostDecrementTolerance"] > 0):
148             ftol  = float(Parameters["CostDecrementTolerance"])
149             factr = ftol * 1.e14
150         else:
151             ftol  = 1.e-7
152             factr = ftol * 1.e14
153         logging.debug("%s Diminution relative minimale du cout lors de l'arret = %s"%(self._name, str(1./factr)))
154         if Parameters.has_key("ProjectedGradientTolerance") and (Parameters["ProjectedGradientTolerance"] > -1):
155             pgtol = float(Parameters["ProjectedGradientTolerance"])
156         else:
157             pgtol = -1
158         logging.debug("%s Maximum des composantes du gradient projete lors de l'arret = %s"%(self._name, str(pgtol)))
159         if Parameters.has_key("GradientNormTolerance") and (Parameters["GradientNormTolerance"] > -1):
160             gtol = float(Parameters["GradientNormTolerance"])
161         else:
162             gtol = 1.e-05
163         logging.debug("%s Maximum des composantes du gradient lors de l'arret = %s"%(self._name, str(gtol)))
164         InnerMinimizerList = ["CG", "NCG", "BFGS"]
165         if Parameters.has_key("InnerMinimizer") and (Parameters["InnerMinimizer"] in InnerMinimizerList):
166             InnerMinimizer = str( Parameters["InnerMinimizer"] )
167         else:
168             InnerMinimizer = "BFGS"
169         logging.debug("%s Minimiseur interne utilisé = %s"%(self._name, InnerMinimizer))
170         if Parameters.has_key("CalculateAPosterioriCovariance"):
171             CalculateAPosterioriCovariance = bool(Parameters["CalculateAPosterioriCovariance"])
172         else:
173             CalculateAPosterioriCovariance = False
174         logging.debug("%s Calcul de la covariance a posteriori = %s"%(self._name, CalculateAPosterioriCovariance))
175         #
176         # Minimisation de la fonctionnelle
177         # --------------------------------
178         if Minimizer == "LBFGSB":
179             Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
180                 func        = CostFunction,
181                 x0          = Xini,
182                 fprime      = GradientOfCostFunction,
183                 args        = (),
184                 bounds      = Bounds,
185                 maxfun      = maxiter-1,
186                 factr       = factr,
187                 pgtol       = pgtol,
188                 iprint      = iprint,
189                 )
190             nfeval = Informations['funcalls']
191             rc     = Informations['warnflag']
192         elif Minimizer == "TNC":
193             Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
194                 func        = CostFunction,
195                 x0          = Xini,
196                 fprime      = GradientOfCostFunction,
197                 args        = (),
198                 bounds      = Bounds,
199                 maxfun      = maxiter,
200                 pgtol       = pgtol,
201                 ftol        = ftol,
202                 messages    = message,
203                 )
204         elif Minimizer == "CG":
205             Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
206                 f           = CostFunction,
207                 x0          = Xini,
208                 fprime      = GradientOfCostFunction,
209                 args        = (),
210                 maxiter     = maxiter,
211                 gtol        = gtol,
212                 disp        = disp,
213                 full_output = True,
214                 )
215         elif Minimizer == "NCG":
216             Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
217                 f           = CostFunction,
218                 x0          = Xini,
219                 fprime      = GradientOfCostFunction,
220                 args        = (),
221                 maxiter     = maxiter,
222                 avextol     = ftol,
223                 disp        = disp,
224                 full_output = True,
225                 )
226         elif Minimizer == "BFGS":
227             Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
228                 f           = CostFunction,
229                 x0          = Xini,
230                 fprime      = GradientOfCostFunction,
231                 args        = (),
232                 maxiter     = maxiter,
233                 gtol        = gtol,
234                 disp        = disp,
235                 full_output = True,
236                 )
237         else:
238             raise ValueError("Error in Minimizer name: %s"%Minimizer)
239         #
240         # Correction pour pallier a un bug de TNC sur le retour du Minimum
241         # ----------------------------------------------------------------
242         StepMin = numpy.argmin( self.StoredVariables["CostFunctionJ"].valueserie() )
243         MinJ    = self.StoredVariables["CostFunctionJ"].valueserie(step = StepMin)
244         Minimum = self.StoredVariables["CurrentState"].valueserie(step = StepMin)
245         #
246         logging.debug("%s %s Step of min cost  = %s"%(self._name, Minimizer, StepMin))
247         logging.debug("%s %s Minimum cost      = %s"%(self._name, Minimizer, MinJ))
248         logging.debug("%s %s Minimum state     = %s"%(self._name, Minimizer, Minimum))
249         logging.debug("%s %s Nb of F           = %s"%(self._name, Minimizer, nfeval))
250         logging.debug("%s %s RetCode           = %s"%(self._name, Minimizer, rc))
251         #
252         # Calcul  de l'analyse
253         # --------------------
254         Xa = numpy.asmatrix(Minimum).T
255         logging.debug("%s Analyse Xa = %s"%(self._name, Xa))
256         #
257         self.StoredVariables["Analysis"].store( Xa.A1 )
258         self.StoredVariables["Innovation"].store( d.A1 )
259         #
260         # Calcul de la covariance d'analyse
261         # ---------------------------------
262         if CalculateAPosterioriCovariance:
263             Hessienne = []
264             nb = len(Xini)
265             for i in range(nb):
266                 ee = numpy.matrix(numpy.zeros(nb)).T
267                 ee[i] = 1.
268                 Hessienne.append( ( BI*ee + Ht((Xa,RI*Hm(ee))) ).A1 )
269             Hessienne = numpy.matrix( Hessienne )
270             A = Hessienne.I
271             self.StoredVariables["APosterioriCovariance"].store( A )
272         #
273         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("MB")))
274         logging.debug("%s Terminé"%self._name)
275         #
276         return 0
277
278 # ==============================================================================
279 if __name__ == "__main__":
280     print '\n AUTODIAGNOSTIC \n'