]> SALOME platform Git repositories - modules/adao.git/blob - src/daComposant/daAlgorithms/4DVAR.py
Salome HOME
Documentation and source observer improvements for checking algorithms
[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", "IndexOfOptimum", "CurrentOptimum"]
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 \
173                 "CurrentState" in self._parameters["StoreSupplementaryCalculations"] or \
174                 "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
175                 self.StoredVariables["CurrentState"].store( _X )
176             Jb  = 0.5 * (_X - Xb).T * BI * (_X - Xb)
177             self.DirectCalculation = [None,]
178             self.DirectInnovation  = [None,]
179             Jo  = 0.
180             _Xn = _X
181             for step in range(0,duration-1):
182                 self.DirectCalculation.append( _Xn )
183                 if hasattr(Y,"store"):
184                     _Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
185                 else:
186                     _Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
187                 _Un = Un(step)
188                 #
189                 # Etape d'évolution
190                 if self._parameters["EstimationOf"] == "State":
191                     _Xn = Mm( (_Xn, _Un) ) + CmUn(_Xn, _Un)
192                 elif self._parameters["EstimationOf"] == "Parameters":
193                     pass
194                 #
195                 if Bounds is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
196                     _Xn = numpy.max(numpy.hstack((_Xn,numpy.asmatrix(Bounds)[:,0])),axis=1)
197                     _Xn = numpy.min(numpy.hstack((_Xn,numpy.asmatrix(Bounds)[:,1])),axis=1)
198                 #
199                 # Etape de différence aux observations
200                 if self._parameters["EstimationOf"] == "State":
201                     _YmHMX = _Ynpu - numpy.asmatrix(numpy.ravel( Hm( (_Xn, None) ) )).T
202                 elif self._parameters["EstimationOf"] == "Parameters":
203                     _YmHMX = _Ynpu - numpy.asmatrix(numpy.ravel( Hm( (_Xn, _Un) ) )).T - CmUn(_Xn, _Un)
204                 self.DirectInnovation.append( _YmHMX )
205                 # Ajout dans la fonctionnelle d'observation
206                 Jo = Jo + _YmHMX.T * RI * _YmHMX
207             Jo  = 0.5 * Jo
208             J   = float( Jb ) + float( Jo )
209             self.StoredVariables["CostFunctionJb"].store( Jb )
210             self.StoredVariables["CostFunctionJo"].store( Jo )
211             self.StoredVariables["CostFunctionJ" ].store( J )
212             if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
213                "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
214                 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
215             if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"]:
216                 self.StoredVariables["IndexOfOptimum"].store( IndexMin )
217             if "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
218                 self.StoredVariables["CurrentOptimum"].store( self.StoredVariables["CurrentState"][IndexMin] )
219             return J
220         #
221         def GradientOfCostFunction(x):
222             _X      = numpy.asmatrix(numpy.ravel( x )).T
223             GradJb  = BI * (_X - Xb)
224             GradJo  = 0.
225             for step in range(duration-1,0,-1):
226                 # Etape de récupération du dernier stockage de l'évolution
227                 _Xn = self.DirectCalculation.pop()
228                 # Etape de récupération du dernier stockage de l'innovation
229                 _YmHMX = self.DirectInnovation.pop()
230                 # Calcul des adjoints
231                 Ha = HO["Adjoint"].asMatrix(ValueForMethodForm = _Xn)
232                 Ha = Ha.reshape(_Xn.size,_YmHMX.size) # ADAO & check shape
233                 Ma = EM["Adjoint"].asMatrix(ValueForMethodForm = _Xn)
234                 Ma = Ma.reshape(_Xn.size,_Xn.size) # ADAO & check shape
235                 # Calcul du gradient par etat adjoint
236                 GradJo = GradJo + Ha * RI * _YmHMX # Equivaut pour Ha lineaire à : Ha( (_Xn, RI * _YmHMX) )
237                 GradJo = Ma * GradJo               # Equivaut pour Ma lineaire à : Ma( (_Xn, GradJo) )
238             GradJ   = numpy.asmatrix( numpy.ravel( GradJb ) - numpy.ravel( GradJo ) ).T
239             return GradJ.A1
240         #
241         # Point de démarrage de l'optimisation : Xini = Xb
242         # ------------------------------------
243         if type(Xb) is type(numpy.matrix([])):
244             Xini = Xb.A1.tolist()
245         else:
246             Xini = list(Xb)
247         #
248         # Minimisation de la fonctionnelle
249         # --------------------------------
250         nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
251         #
252         if self._parameters["Minimizer"] == "LBFGSB":
253             Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
254                 func        = CostFunction,
255                 x0          = Xini,
256                 fprime      = GradientOfCostFunction,
257                 args        = (),
258                 bounds      = Bounds,
259                 maxfun      = self._parameters["MaximumNumberOfSteps"]-1,
260                 factr       = self._parameters["CostDecrementTolerance"]*1.e14,
261                 pgtol       = self._parameters["ProjectedGradientTolerance"],
262                 iprint      = self.__iprint,
263                 )
264             nfeval = Informations['funcalls']
265             rc     = Informations['warnflag']
266         elif self._parameters["Minimizer"] == "TNC":
267             Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
268                 func        = CostFunction,
269                 x0          = Xini,
270                 fprime      = GradientOfCostFunction,
271                 args        = (),
272                 bounds      = Bounds,
273                 maxfun      = self._parameters["MaximumNumberOfSteps"],
274                 pgtol       = self._parameters["ProjectedGradientTolerance"],
275                 ftol        = self._parameters["CostDecrementTolerance"],
276                 messages    = self.__message,
277                 )
278         elif self._parameters["Minimizer"] == "CG":
279             Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
280                 f           = CostFunction,
281                 x0          = Xini,
282                 fprime      = GradientOfCostFunction,
283                 args        = (),
284                 maxiter     = self._parameters["MaximumNumberOfSteps"],
285                 gtol        = self._parameters["GradientNormTolerance"],
286                 disp        = self.__disp,
287                 full_output = True,
288                 )
289         elif self._parameters["Minimizer"] == "NCG":
290             Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
291                 f           = CostFunction,
292                 x0          = Xini,
293                 fprime      = GradientOfCostFunction,
294                 args        = (),
295                 maxiter     = self._parameters["MaximumNumberOfSteps"],
296                 avextol     = self._parameters["CostDecrementTolerance"],
297                 disp        = self.__disp,
298                 full_output = True,
299                 )
300         elif self._parameters["Minimizer"] == "BFGS":
301             Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
302                 f           = CostFunction,
303                 x0          = Xini,
304                 fprime      = GradientOfCostFunction,
305                 args        = (),
306                 maxiter     = self._parameters["MaximumNumberOfSteps"],
307                 gtol        = self._parameters["GradientNormTolerance"],
308                 disp        = self.__disp,
309                 full_output = True,
310                 )
311         else:
312             raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
313         #
314         IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
315         MinJ     = self.StoredVariables["CostFunctionJ"][IndexMin]
316         #
317         # Correction pour pallier a un bug de TNC sur le retour du Minimum
318         # ----------------------------------------------------------------
319         if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
320             Minimum = self.StoredVariables["CurrentState"][IndexMin]
321         #
322         # Obtention de l'analyse
323         # ----------------------
324         Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
325         #
326         self.StoredVariables["Analysis"].store( Xa.A1 )
327         #
328         # Calculs et/ou stockages supplémentaires
329         # ---------------------------------------
330         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
331             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
332         #
333         self._post_run(HO)
334         return 0
335
336 # ==============================================================================
337 if __name__ == "__main__":
338     print '\n AUTODIAGNOSTIC \n'