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