]> SALOME platform Git repositories - modules/adao.git/blob - src/daComposant/daAlgorithms/3DVAR.py
Salome HOME
Mise à jour de la bibliothèque
[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, Parameters=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         HXb = numpy.asmatrix(HXb).flatten().T
68         #
69         # Calcul du préconditionnement
70         # ----------------------------
71         # Bdemi = numpy.linalg.cholesky(B)
72         #
73         # Calcul de l'innovation
74         # ----------------------
75         d  = Y - HXb
76         logging.debug("%s Innovation d = %s"%(self._name, d))
77         #
78         # Précalcul des inversion appellée dans les fonction-coût et gradient
79         # -------------------------------------------------------------------
80         BI = B.I
81         RI = R.I
82         #
83         # Définition de la fonction-coût
84         # ------------------------------
85         def CostFunction(x):
86             _X  = numpy.asmatrix(x).flatten().T
87             logging.info("%s CostFunction X  = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
88             _HX = Hm( _X )
89             _HX = numpy.asmatrix(_HX).flatten().T
90             Jb  = 0.5 * (_X - Xb).T * BI * (_X - Xb)
91             Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
92             J   = float( Jb ) + float( Jo )
93             logging.info("%s CostFunction Jb = %s"%(self._name, Jb))
94             logging.info("%s CostFunction Jo = %s"%(self._name, Jo))
95             logging.info("%s CostFunction J  = %s"%(self._name, J))
96             self.StoredVariables["CurrentState"].store( _X.A1 )
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             return GradJ.A1
114         #
115         # Point de démarrage de l'optimisation : Xini = Xb
116         # ------------------------------------
117         if type(Xb) is type(numpy.matrix([])):
118             Xini = Xb.A1.tolist()
119         else:
120             Xini = list(Xb)
121         logging.debug("%s Point de démarrage Xini = %s"%(self._name, Xini))
122         #
123         # Paramètres de pilotage
124         # ----------------------
125         if Parameters.has_key("Bounds") and (type(Parameters["Bounds"]) is type([]) or type(Parameters["Bounds"]) is type(())) and (len(Parameters["Bounds"]) > 0):
126             Bounds = Parameters["Bounds"]
127         else:
128             Bounds = None
129         MinimizerList = ["LBFGSB","TNC", "CG", "BFGS"]
130         if Parameters.has_key("Minimizer") and (Parameters["Minimizer"] in MinimizerList):
131             Minimizer = str( Parameters["Minimizer"] )
132         else:
133             Minimizer = "LBFGSB"
134         logging.debug("%s Minimiseur utilisé = %s"%(self._name, Minimizer))
135         if Parameters.has_key("MaximumNumberOfSteps") and (Parameters["MaximumNumberOfSteps"] > -1):
136             maxiter = int( Parameters["MaximumNumberOfSteps"] )
137         else:
138             maxiter = 15000
139         logging.debug("%s Nombre maximal de pas d'optimisation = %s"%(self._name, maxiter))
140         #
141         # Minimisation de la fonctionnelle
142         # --------------------------------
143         if Minimizer == "LBFGSB":
144             Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
145                 func        = CostFunction,
146                 x0          = Xini,
147                 fprime      = GradientOfCostFunction,
148                 args        = (),
149                 bounds      = Bounds,
150                 maxfun      = maxiter,
151                 iprint      = iprint,
152                 factr       = 1.,
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'