]> SALOME platform Git repositories - modules/adao.git/blob - src/daComposant/daAlgorithms/3DVAR.py
Salome HOME
Merge remote-tracking branch '110523-JP/new_branch_name' into V6_main
[modules/adao.git] / src / daComposant / daAlgorithms / 3DVAR.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2011  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 du préconditionnement
68         # ----------------------------
69         # Bdemi = numpy.linalg.cholesky(B)
70         #
71         # Calcul de l'innovation
72         # ----------------------
73         d  = Y - HXb
74         logging.debug("%s Innovation d = %s"%(self._name, d))
75         #
76         # Précalcul des inversion appellée dans les fonction-coût et gradient
77         # -------------------------------------------------------------------
78         BI = B.I
79         RI = R.I
80         #
81         # Définition de la fonction-coût
82         # ------------------------------
83         def CostFunction(x):
84             _X  = numpy.asmatrix(x).flatten().T
85             logging.info("%s CostFunction X  = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
86             _HX = Hm( _X )
87             _HX = numpy.asmatrix(_HX).flatten().T
88             Jb  = 0.5 * (_X - Xb).T * BI * (_X - Xb)
89             Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
90             J   = float( Jb ) + float( Jo )
91             logging.info("%s CostFunction Jb = %s"%(self._name, Jb))
92             logging.info("%s CostFunction Jo = %s"%(self._name, Jo))
93             logging.info("%s CostFunction J  = %s"%(self._name, J))
94             self.StoredVariables["CurrentState"].store( _X.A1 )
95             self.StoredVariables["CostFunctionJb"].store( Jb )
96             self.StoredVariables["CostFunctionJo"].store( Jo )
97             self.StoredVariables["CostFunctionJ" ].store( J )
98             return float( J )
99         #
100         def GradientOfCostFunction(x):
101             _X      = numpy.asmatrix(x).flatten().T
102             logging.info("%s GradientOfCostFunction X      = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
103             _HX     = Hm( _X )
104             _HX     = numpy.asmatrix(_HX).flatten().T
105             GradJb  = BI * (_X - Xb)
106             GradJo  = - Ht( (_X, RI * (Y - _HX)) )
107             GradJ   = numpy.asmatrix( GradJb ).flatten().T + numpy.asmatrix( GradJo ).flatten().T
108             logging.debug("%s GradientOfCostFunction GradJb = %s"%(self._name, numpy.asmatrix( GradJb ).flatten()))
109             logging.debug("%s GradientOfCostFunction GradJo = %s"%(self._name, numpy.asmatrix( GradJo ).flatten()))
110             logging.debug("%s GradientOfCostFunction GradJ  = %s"%(self._name, numpy.asmatrix( GradJ  ).flatten()))
111             return GradJ.A1
112         #
113         # Point de démarrage de l'optimisation : Xini = Xb
114         # ------------------------------------
115         if type(Xb) is type(numpy.matrix([])):
116             Xini = Xb.A1.tolist()
117         else:
118             Xini = list(Xb)
119         logging.debug("%s Point de démarrage Xini = %s"%(self._name, Xini))
120         #
121         # Paramètres de pilotage
122         # ----------------------
123         # Potentiels : "Bounds", "Minimizer", "MaximumNumberOfSteps"
124         if Parameters.has_key("Bounds") and (type(Parameters["Bounds"]) is type([]) or type(Parameters["Bounds"]) is type(())) and (len(Parameters["Bounds"]) > 0):
125             Bounds = Parameters["Bounds"]
126         else:
127             Bounds = None
128         MinimizerList = ["LBFGSB","TNC", "CG", "BFGS"]
129         if Parameters.has_key("Minimizer") and (Parameters["Minimizer"] in MinimizerList):
130             Minimizer = str( Parameters["Minimizer"] )
131         else:
132             Minimizer = "LBFGSB"
133         logging.debug("%s Minimiseur utilisé = %s"%(self._name, Minimizer))
134         if Parameters.has_key("MaximumNumberOfSteps") and (Parameters["MaximumNumberOfSteps"] > -1):
135             maxiter = int( Parameters["MaximumNumberOfSteps"] )
136         else:
137             maxiter = 15000
138         logging.debug("%s Nombre maximal de pas d'optimisation = %s"%(self._name, str(maxiter)))
139         #
140         # Minimisation de la fonctionnelle
141         # --------------------------------
142         if Minimizer == "LBFGSB":
143             Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
144                 func        = CostFunction,
145                 x0          = Xini,
146                 fprime      = GradientOfCostFunction,
147                 args        = (),
148                 bounds      = Bounds,
149                 maxfun      = maxiter,
150                 iprint      = iprint,
151                 factr       = 1.,
152                 )
153             logging.debug("%s %s Minimum = %s"%(self._name, Minimizer, Minimum))
154             logging.debug("%s %s Nb of F = %s"%(self._name, Minimizer, Informations['funcalls']))
155             logging.debug("%s %s RetCode = %s"%(self._name, Minimizer, Informations['warnflag']))
156         elif Minimizer == "TNC":
157             Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
158                 func        = CostFunction,
159                 x0          = Xini,
160                 fprime      = GradientOfCostFunction,
161                 args        = (),
162                 bounds      = Bounds,
163                 maxfun      = maxiter,
164                 messages    = message,
165                 )
166             logging.debug("%s %s Minimum = %s"%(self._name, Minimizer, Minimum))
167             logging.debug("%s %s Nb of F = %s"%(self._name, Minimizer, nfeval))
168             logging.debug("%s %s RetCode = %s"%(self._name, Minimizer, rc))
169         elif Minimizer == "CG":
170             Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
171                 f           = CostFunction,
172                 x0          = Xini,
173                 fprime      = GradientOfCostFunction,
174                 args        = (),
175                 maxiter     = maxiter,
176                 disp        = disp,
177                 full_output = True,
178                 )
179             logging.debug("%s %s Minimum = %s"%(self._name, Minimizer, Minimum))
180             logging.debug("%s %s Nb of F = %s"%(self._name, Minimizer, nfeval))
181             logging.debug("%s %s RetCode = %s"%(self._name, Minimizer, rc))
182         elif Minimizer == "BFGS":
183             Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
184                 f           = CostFunction,
185                 x0          = Xini,
186                 fprime      = GradientOfCostFunction,
187                 args        = (),
188                 maxiter     = maxiter,
189                 disp        = disp,
190                 full_output = True,
191                 )
192             logging.debug("%s %s Minimum = %s"%(self._name, Minimizer, Minimum))
193             logging.debug("%s %s Nb of F = %s"%(self._name, Minimizer, nfeval))
194             logging.debug("%s %s RetCode = %s"%(self._name, Minimizer, rc))
195         else:
196             raise ValueError("Error in Minimizer name: %s"%Minimizer)
197         #
198         # Calcul  de l'analyse
199         # --------------------
200         Xa = numpy.asmatrix(Minimum).T
201         logging.debug("%s Analyse Xa = %s"%(self._name, Xa))
202         #
203         self.StoredVariables["Analysis"].store( Xa.A1 )
204         self.StoredVariables["Innovation"].store( d.A1 )
205         #
206         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("MB")))
207         logging.debug("%s Terminé"%self._name)
208         #
209         return 0
210
211 # ==============================================================================
212 if __name__ == "__main__":
213     print '\n AUTODIAGNOSTIC \n'