Salome HOME
Initial Commit
[modules/adao.git] / src / daComposant / daAlgorithms / 3DVAR.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2009  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 __doc__ = """
22     Algorithme variationnel statique (3D-VAR)
23 """
24 __author__ = "Jean-Philippe ARGAUD - Mars 2009"
25
26 import sys ; sys.path.insert(0, "../daCore")
27 import logging
28 import Persistence
29 from BasicObjects import Algorithm
30 import PlatformInfo ; m = PlatformInfo.SystemUsage()
31
32 import numpy
33 import scipy.optimize
34
35 if logging.getLogger().level < 30:
36     iprint  = 1
37     message = scipy.optimize.tnc.MSG_ALL
38     disp    = 1
39 else:
40     iprint  = -1
41     message = scipy.optimize.tnc.MSG_NONE
42     disp    = 0
43
44 # ==============================================================================
45 class ElementaryAlgorithm(Algorithm):
46     def __init__(self):
47         Algorithm.__init__(self)
48         self._name = "3DVAR"
49         logging.debug("%s Initialisation"%self._name)
50
51     def run(self, Xb=None, Y=None, H=None, M=None, R=None, B=None, Q=None, Par=None):
52         """
53         Calcul de l'estimateur 3D-VAR
54         """
55         logging.debug("%s Lancement"%self._name)
56         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("Mo")))
57         #
58         Hm = H["Direct"].appliedTo
59         Ht = H["Adjoint"].appliedInXTo
60         #
61         # Utilisation éventuelle d'un vecteur H(Xb) précalculé
62         # ----------------------------------------------------
63         if H["AppliedToX"] is not None and H["AppliedToX"].has_key("HXb"):
64             logging.debug("%s Utilisation de HXb"%self._name)
65             HXb = H["AppliedToX"]["HXb"]
66         else:
67             logging.debug("%s Calcul de Hm(Xb)"%self._name)
68             HXb = Hm( Xb )
69         #
70         # Calcul du préconditionnement
71         # ----------------------------
72         # Bdemi = numpy.linalg.cholesky(B)
73         #
74         # Calcul de l'innovation
75         # ----------------------
76         d  = Y - HXb
77         logging.debug("%s Innovation d = %s"%(self._name, d))
78         #
79         # Précalcul des inversion appellée dans les fonction-coût et gradient
80         # -------------------------------------------------------------------
81         BI = B.I
82         RI = R.I
83         #
84         # Définition de la fonction-coût
85         # ------------------------------
86         def CostFunction(x):
87             _X  = numpy.asmatrix(x).flatten().T
88             logging.info("%s CostFunction X  = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
89             _HX = Hm( _X )
90             _HX = numpy.asmatrix(_HX).flatten().T
91             Jb  = 0.5 * (_X - Xb).T * BI * (_X - Xb)
92             Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
93             J   = float( Jb ) + float( Jo )
94             logging.info("%s CostFunction Jb = %s"%(self._name, Jb))
95             logging.info("%s CostFunction Jo = %s"%(self._name, Jo))
96             logging.info("%s CostFunction J  = %s"%(self._name, J))
97             self.StoredVariables["CostFunctionJb"].store( Jb )
98             self.StoredVariables["CostFunctionJo"].store( Jo )
99             self.StoredVariables["CostFunctionJ" ].store( J )
100             return float( J )
101         #
102         def GradientOfCostFunction(x):
103             _X      = numpy.asmatrix(x).flatten().T
104             logging.info("%s GradientOfCostFunction X      = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
105             _HX     = Hm( _X )
106             _HX     = numpy.asmatrix(_HX).flatten().T
107             GradJb  = BI * (_X - Xb)
108             GradJo  = - Ht( (_X, RI * (Y - _HX)) )
109             GradJ   = numpy.asmatrix( GradJb ).flatten().T + numpy.asmatrix( GradJo ).flatten().T
110             logging.debug("%s GradientOfCostFunction GradJb = %s"%(self._name, numpy.asmatrix( GradJb ).flatten()))
111             logging.debug("%s GradientOfCostFunction GradJo = %s"%(self._name, numpy.asmatrix( GradJo ).flatten()))
112             logging.debug("%s GradientOfCostFunction GradJ  = %s"%(self._name, numpy.asmatrix( GradJ  ).flatten()))
113             # self.StoredVariables["GradientOfCostFunctionJb"].store( Jb )
114             # self.StoredVariables["GradientOfCostFunctionJo"].store( Jo )
115             # self.StoredVariables["GradientOfCostFunctionJ" ].store( J )
116             return GradJ.A1
117         #
118         # Point de démarrage de l'optimisation : Xini = Xb
119         # ------------------------------------
120         if type(Xb) is type(numpy.matrix([])):
121             Xini = Xb.A1.tolist()
122         else:
123             Xini = list(Xb)
124         logging.debug("%s Point de démarrage Xini = %s"%(self._name, Xini))
125         #
126         # Paramètres de pilotage
127         # ----------------------
128         if Par.has_key("Bounds") and (type(Par["Bounds"]) is type([]) or type(Par["Bounds"]) is type(())) and (len(Par["Bounds"]) > 0):
129             Bounds = Par["Bounds"]
130         else:
131             Bounds = None
132         MinimizerList = ["LBFGSB","TNC", "CG", "BFGS"]
133         if Par.has_key("Minimizer") and (Par["Minimizer"] in MinimizerList):
134             Minimizer = str( Par["Minimizer"] )
135         else:
136             Minimizer = "LBFGSB"
137         logging.debug("%s Minimiseur utilisé = %s"%(self._name, Minimizer))
138         if Par.has_key("MaximumNumberOfSteps") and (Par["MaximumNumberOfSteps"] > -1):
139             maxiter = int( Par["MaximumNumberOfSteps"] )
140         else:
141             maxiter = 15000
142         logging.debug("%s Nombre maximal de pas d'optimisation = %s"%(self._name, maxiter))
143         #
144         # Minimisation de la fonctionnelle
145         # --------------------------------
146         if Minimizer == "LBFGSB":
147             Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
148                 func        = CostFunction,
149                 x0          = Xini,
150                 fprime      = GradientOfCostFunction,
151                 args        = (),
152                 bounds      = Bounds,
153                 maxfun      = maxiter,
154                 iprint      = iprint,
155                 )
156             logging.debug("%s %s Minimum = %s"%(self._name, Minimizer, Minimum))
157             logging.debug("%s %s Nb of F = %s"%(self._name, Minimizer, Informations['funcalls']))
158             logging.debug("%s %s RetCode = %s"%(self._name, Minimizer, Informations['warnflag']))
159         elif Minimizer == "TNC":
160             Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
161                 func        = CostFunction,
162                 x0          = Xini,
163                 fprime      = GradientOfCostFunction,
164                 args        = (),
165                 bounds      = Bounds,
166                 maxfun      = maxiter,
167                 messages    = message,
168                 )
169             logging.debug("%s %s Minimum = %s"%(self._name, Minimizer, Minimum))
170             logging.debug("%s %s Nb of F = %s"%(self._name, Minimizer, nfeval))
171             logging.debug("%s %s RetCode = %s"%(self._name, Minimizer, rc))
172         elif Minimizer == "CG":
173             Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
174                 f           = CostFunction,
175                 x0          = Xini,
176                 fprime      = GradientOfCostFunction,
177                 args        = (),
178                 maxiter     = maxiter,
179                 disp        = disp,
180                 full_output = True,
181                 )
182             logging.debug("%s %s Minimum = %s"%(self._name, Minimizer, Minimum))
183             logging.debug("%s %s Nb of F = %s"%(self._name, Minimizer, nfeval))
184             logging.debug("%s %s RetCode = %s"%(self._name, Minimizer, rc))
185         elif Minimizer == "BFGS":
186             Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
187                 f           = CostFunction,
188                 x0          = Xini,
189                 fprime      = GradientOfCostFunction,
190                 args        = (),
191                 maxiter     = maxiter,
192                 disp        = disp,
193                 full_output = True,
194                 )
195             logging.debug("%s %s Minimum = %s"%(self._name, Minimizer, Minimum))
196             logging.debug("%s %s Nb of F = %s"%(self._name, Minimizer, nfeval))
197             logging.debug("%s %s RetCode = %s"%(self._name, Minimizer, rc))
198         else:
199             raise ValueError("Error in Minimizer name: %s"%Minimizer)
200         #
201         # Calcul  de l'analyse
202         # --------------------
203         Xa = numpy.asmatrix(Minimum).T
204         logging.debug("%s Analyse Xa = %s"%(self._name, Xa))
205         #
206         self.StoredVariables["Analysis"].store( Xa.A1 )
207         self.StoredVariables["Innovation"].store( d.A1 )
208         #
209         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("MB")))
210         logging.debug("%s Terminé"%self._name)
211         #
212         return 0
213
214 # ==============================================================================
215 if __name__ == "__main__":
216     print '\n AUTODIAGNOSTIC \n'