]> SALOME platform Git repositories - modules/adao.git/blob - src/daComposant/daAlgorithms/4DVAR.py
Salome HOME
Minor source corrections for calculation precision control
[modules/adao.git] / src / daComposant / daAlgorithms / 4DVAR.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2015 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 #  Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
22
23 import logging
24 from daCore import BasicObjects
25 import numpy, scipy.optimize
26
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
29     def __init__(self):
30         BasicObjects.Algorithm.__init__(self, "4DVAR")
31         self.defineRequiredParameter(
32             name     = "ConstrainedBy",
33             default  = "EstimateProjection",
34             typecast = str,
35             message  = "Prise en compte des contraintes",
36             listval  = ["EstimateProjection"],
37             )
38         self.defineRequiredParameter(
39             name     = "EstimationOf",
40             default  = "State",
41             typecast = str,
42             message  = "Estimation d'etat ou de parametres",
43             listval  = ["State", "Parameters"],
44             )
45         self.defineRequiredParameter(
46             name     = "Minimizer",
47             default  = "LBFGSB",
48             typecast = str,
49             message  = "Minimiseur utilisé",
50             listval  = ["LBFGSB","TNC", "CG", "NCG", "BFGS"],
51             )
52         self.defineRequiredParameter(
53             name     = "MaximumNumberOfSteps",
54             default  = 15000,
55             typecast = int,
56             message  = "Nombre maximal de pas d'optimisation",
57             minval   = -1,
58             )
59         self.defineRequiredParameter(
60             name     = "CostDecrementTolerance",
61             default  = 1.e-7,
62             typecast = float,
63             message  = "Diminution relative minimale du cout lors de l'arrêt",
64             )
65         self.defineRequiredParameter(
66             name     = "ProjectedGradientTolerance",
67             default  = -1,
68             typecast = float,
69             message  = "Maximum des composantes du gradient projeté lors de l'arrêt",
70             minval   = -1,
71             )
72         self.defineRequiredParameter(
73             name     = "GradientNormTolerance",
74             default  = 1.e-05,
75             typecast = float,
76             message  = "Maximum des composantes du gradient lors de l'arrêt",
77             )
78         self.defineRequiredParameter(
79             name     = "StoreInternalVariables",
80             default  = False,
81             typecast = bool,
82             message  = "Stockage des variables internes ou intermédiaires du calcul",
83             )
84         self.defineRequiredParameter(
85             name     = "StoreSupplementaryCalculations",
86             default  = [],
87             typecast = tuple,
88             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
89             listval  = ["BMA", "CurrentState", "CostFunctionJ"]
90             )
91         self.defineRequiredParameter( # Pas de type
92             name     = "Bounds",
93             message  = "Liste des valeurs de bornes",
94             )
95
96     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
97         self._pre_run()
98         if logging.getLogger().level < logging.WARNING:
99             self.__iprint, self.__disp = 1, 1
100             self.__message = scipy.optimize.tnc.MSG_ALL
101         else:
102             self.__iprint, self.__disp = -1, 0
103             self.__message = scipy.optimize.tnc.MSG_NONE
104         #
105         # Paramètres de pilotage
106         # ----------------------
107         self.setParameters(Parameters)
108         #
109         if self._parameters.has_key("Bounds") and (type(self._parameters["Bounds"]) is type([]) or type(self._parameters["Bounds"]) is type(())) and (len(self._parameters["Bounds"]) > 0):
110             Bounds = self._parameters["Bounds"]
111             logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
112         else:
113             Bounds = None
114         #
115         # Correction pour pallier a un bug de TNC sur le retour du Minimum
116         if self._parameters.has_key("Minimizer") == "TNC":
117             self.setParameterValue("StoreInternalVariables",True)
118         #
119         # Opérateurs
120         # ----------
121         Hm = HO["Direct"].appliedControledFormTo
122         #
123         Mm = EM["Direct"].appliedControledFormTo
124         #
125         if CM is not None and CM.has_key("Tangent") and U is not None:
126             Cm = CM["Tangent"].asMatrix(Xb)
127         else:
128             Cm = None
129         #
130         def Un(_step):
131             if U is not None:
132                 if hasattr(U,"store") and 1<=_step<len(U) :
133                     _Un = numpy.asmatrix(numpy.ravel( U[_step] )).T
134                 elif hasattr(U,"store") and len(U)==1:
135                     _Un = numpy.asmatrix(numpy.ravel( U[0] )).T
136                 else:
137                     _Un = numpy.asmatrix(numpy.ravel( U )).T
138             else:
139                 _Un = None
140             return _Un
141         def CmUn(_xn,_un):
142             if Cm is not None and _un is not None: # Attention : si Cm est aussi dans M, doublon !
143                 _Cm   = Cm.reshape(_xn.size,_un.size) # ADAO & check shape
144                 _CmUn = _Cm * _un
145             else:
146                 _CmUn = 0.
147             return _CmUn
148         #
149         # Remarque : les observations sont exploitées à partir du pas de temps
150         # numéro 1, et sont utilisées dans Yo comme rangées selon ces indices.
151         # Donc le pas 0 n'est pas utilisé puisque la première étape commence
152         # avec l'observation du pas 1.
153         #
154         # Nombre de pas identique au nombre de pas d'observations
155         # -------------------------------------------------------
156         if hasattr(Y,"stepnumber"):
157             duration = Y.stepnumber()
158         else:
159             duration = 2
160         #
161         # Précalcul des inversions de B et R
162         # ----------------------------------
163         BI = B.getI()
164         RI = R.getI()
165         #
166         # Définition de la fonction-coût
167         # ------------------------------
168         self.DirectCalculation = [None,] # Le pas 0 n'est pas observé
169         self.DirectInnovation  = [None,] # Le pas 0 n'est pas observé
170         def CostFunction(x):
171             _X  = numpy.asmatrix(numpy.ravel( x )).T
172             if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
173                 self.StoredVariables["CurrentState"].store( _X )
174             Jb  = 0.5 * (_X - Xb).T * BI * (_X - Xb)
175             self.DirectCalculation = [None,]
176             self.DirectInnovation  = [None,]
177             Jo  = 0.
178             _Xn = _X
179             for step in range(0,duration-1):
180                 self.DirectCalculation.append( _Xn )
181                 if hasattr(Y,"store"):
182                     _Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
183                 else:
184                     _Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
185                 _Un = Un(step)
186                 #
187                 # Etape d'évolution
188                 if self._parameters["EstimationOf"] == "State":
189                     _Xn = Mm( (_Xn, _Un) ) + CmUn(_Xn, _Un)
190                 elif self._parameters["EstimationOf"] == "Parameters":
191                     pass
192                 #
193                 if Bounds is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
194                     _Xn = numpy.max(numpy.hstack((_Xn,numpy.asmatrix(Bounds)[:,0])),axis=1)
195                     _Xn = numpy.min(numpy.hstack((_Xn,numpy.asmatrix(Bounds)[:,1])),axis=1)
196                 #
197                 # Etape de différence aux observations
198                 if self._parameters["EstimationOf"] == "State":
199                     _YmHMX = _Ynpu - numpy.asmatrix(numpy.ravel( Hm( (_Xn, None) ) )).T
200                 elif self._parameters["EstimationOf"] == "Parameters":
201                     _YmHMX = _Ynpu - numpy.asmatrix(numpy.ravel( Hm( (_Xn, _Un) ) )).T - CmUn(_Xn, _Un)
202                 self.DirectInnovation.append( _YmHMX )
203                 # Ajout dans la fonctionnelle d'observation
204                 Jo = Jo + _YmHMX.T * RI * _YmHMX
205             Jo  = 0.5 * Jo
206             J   = float( Jb ) + float( Jo )
207             self.StoredVariables["CostFunctionJb"].store( Jb )
208             self.StoredVariables["CostFunctionJo"].store( Jo )
209             self.StoredVariables["CostFunctionJ" ].store( J )
210             return J
211         #
212         def GradientOfCostFunction(x):
213             _X      = numpy.asmatrix(numpy.ravel( x )).T
214             GradJb  = BI * (_X - Xb)
215             GradJo  = 0.
216             for step in range(duration-1,0,-1):
217                 # Etape de récupération du dernier stockage de l'évolution
218                 _Xn = self.DirectCalculation.pop()
219                 # Etape de récupération du dernier stockage de l'innovation
220                 _YmHMX = self.DirectInnovation.pop()
221                 # Calcul des adjoints
222                 Ha = HO["Adjoint"].asMatrix(ValueForMethodForm = _Xn)
223                 Ha = Ha.reshape(_Xn.size,_YmHMX.size) # ADAO & check shape
224                 Ma = EM["Adjoint"].asMatrix(ValueForMethodForm = _Xn)
225                 Ma = Ma.reshape(_Xn.size,_Xn.size) # ADAO & check shape
226                 # Calcul du gradient par etat adjoint
227                 GradJo = GradJo + Ha * RI * _YmHMX # Equivaut pour Ha lineaire à : Ha( (_Xn, RI * _YmHMX) )
228                 GradJo = Ma * GradJo               # Equivaut pour Ma lineaire à : Ma( (_Xn, GradJo) )
229             GradJ   = numpy.asmatrix( numpy.ravel( GradJb ) - numpy.ravel( GradJo ) ).T
230             return GradJ.A1
231         #
232         # Point de démarrage de l'optimisation : Xini = Xb
233         # ------------------------------------
234         if type(Xb) is type(numpy.matrix([])):
235             Xini = Xb.A1.tolist()
236         else:
237             Xini = list(Xb)
238         #
239         # Minimisation de la fonctionnelle
240         # --------------------------------
241         nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
242         #
243         if self._parameters["Minimizer"] == "LBFGSB":
244             Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
245                 func        = CostFunction,
246                 x0          = Xini,
247                 fprime      = GradientOfCostFunction,
248                 args        = (),
249                 bounds      = Bounds,
250                 maxfun      = self._parameters["MaximumNumberOfSteps"]-1,
251                 factr       = self._parameters["CostDecrementTolerance"]*1.e14,
252                 pgtol       = self._parameters["ProjectedGradientTolerance"],
253                 iprint      = self.__iprint,
254                 )
255             nfeval = Informations['funcalls']
256             rc     = Informations['warnflag']
257         elif self._parameters["Minimizer"] == "TNC":
258             Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
259                 func        = CostFunction,
260                 x0          = Xini,
261                 fprime      = GradientOfCostFunction,
262                 args        = (),
263                 bounds      = Bounds,
264                 maxfun      = self._parameters["MaximumNumberOfSteps"],
265                 pgtol       = self._parameters["ProjectedGradientTolerance"],
266                 ftol        = self._parameters["CostDecrementTolerance"],
267                 messages    = self.__message,
268                 )
269         elif self._parameters["Minimizer"] == "CG":
270             Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
271                 f           = CostFunction,
272                 x0          = Xini,
273                 fprime      = GradientOfCostFunction,
274                 args        = (),
275                 maxiter     = self._parameters["MaximumNumberOfSteps"],
276                 gtol        = self._parameters["GradientNormTolerance"],
277                 disp        = self.__disp,
278                 full_output = True,
279                 )
280         elif self._parameters["Minimizer"] == "NCG":
281             Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
282                 f           = CostFunction,
283                 x0          = Xini,
284                 fprime      = GradientOfCostFunction,
285                 args        = (),
286                 maxiter     = self._parameters["MaximumNumberOfSteps"],
287                 avextol     = self._parameters["CostDecrementTolerance"],
288                 disp        = self.__disp,
289                 full_output = True,
290                 )
291         elif self._parameters["Minimizer"] == "BFGS":
292             Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
293                 f           = CostFunction,
294                 x0          = Xini,
295                 fprime      = GradientOfCostFunction,
296                 args        = (),
297                 maxiter     = self._parameters["MaximumNumberOfSteps"],
298                 gtol        = self._parameters["GradientNormTolerance"],
299                 disp        = self.__disp,
300                 full_output = True,
301                 )
302         else:
303             raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
304         #
305         IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
306         MinJ     = self.StoredVariables["CostFunctionJ"][IndexMin]
307         #
308         # Correction pour pallier a un bug de TNC sur le retour du Minimum
309         # ----------------------------------------------------------------
310         if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
311             Minimum = self.StoredVariables["CurrentState"][IndexMin]
312         #
313         # Obtention de l'analyse
314         # ----------------------
315         Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
316         #
317         self.StoredVariables["Analysis"].store( Xa.A1 )
318         #
319         # Calculs et/ou stockages supplémentaires
320         # ---------------------------------------
321         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
322             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
323         #
324         self._post_run(HO)
325         return 0
326
327 # ==============================================================================
328 if __name__ == "__main__":
329     print '\n AUTODIAGNOSTIC \n'