Salome HOME
Python 3 compatibility improvement (UTF-8) and data interface changes
[modules/adao.git] / src / daComposant / daAlgorithms / 4DVAR.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2017 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", "CostFunctionJb", "CostFunctionJo", "IndexOfOptimum", "CurrentOptimum", "CostFunctionJAtCurrentOptimum"]
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(Parameters)
98         #
99         # Correction pour pallier a un bug de TNC sur le retour du Minimum
100         if "Minimizer" in self._parameters and self._parameters["Minimizer"] == "TNC":
101             self.setParameterValue("StoreInternalVariables",True)
102         #
103         # Opérateurs
104         # ----------
105         Hm = HO["Direct"].appliedControledFormTo
106         #
107         Mm = EM["Direct"].appliedControledFormTo
108         #
109         if CM is not None and "Tangent" in CM and U is not None:
110             Cm = CM["Tangent"].asMatrix(Xb)
111         else:
112             Cm = None
113         #
114         def Un(_step):
115             if U is not None:
116                 if hasattr(U,"store") and 1<=_step<len(U) :
117                     _Un = numpy.asmatrix(numpy.ravel( U[_step] )).T
118                 elif hasattr(U,"store") and len(U)==1:
119                     _Un = numpy.asmatrix(numpy.ravel( U[0] )).T
120                 else:
121                     _Un = numpy.asmatrix(numpy.ravel( U )).T
122             else:
123                 _Un = None
124             return _Un
125         def CmUn(_xn,_un):
126             if Cm is not None and _un is not None: # Attention : si Cm est aussi dans M, doublon !
127                 _Cm   = Cm.reshape(_xn.size,_un.size) # ADAO & check shape
128                 _CmUn = _Cm * _un
129             else:
130                 _CmUn = 0.
131             return _CmUn
132         #
133         # Remarque : les observations sont exploitées à partir du pas de temps
134         # numéro 1, et sont utilisées dans Yo comme rangées selon ces indices.
135         # Donc le pas 0 n'est pas utilisé puisque la première étape commence
136         # avec l'observation du pas 1.
137         #
138         # Nombre de pas identique au nombre de pas d'observations
139         # -------------------------------------------------------
140         if hasattr(Y,"stepnumber"):
141             duration = Y.stepnumber()
142         else:
143             duration = 2
144         #
145         # Précalcul des inversions de B et R
146         # ----------------------------------
147         BI = B.getI()
148         RI = R.getI()
149         #
150         # Définition de la fonction-coût
151         # ------------------------------
152         self.DirectCalculation = [None,] # Le pas 0 n'est pas observé
153         self.DirectInnovation  = [None,] # Le pas 0 n'est pas observé
154         def CostFunction(x):
155             _X  = numpy.asmatrix(numpy.ravel( x )).T
156             if self._parameters["StoreInternalVariables"] or \
157                 "CurrentState" in self._parameters["StoreSupplementaryCalculations"] or \
158                 "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
159                 self.StoredVariables["CurrentState"].store( _X )
160             Jb  = 0.5 * (_X - Xb).T * BI * (_X - Xb)
161             self.DirectCalculation = [None,]
162             self.DirectInnovation  = [None,]
163             Jo  = 0.
164             _Xn = _X
165             for step in range(0,duration-1):
166                 self.DirectCalculation.append( _Xn )
167                 if hasattr(Y,"store"):
168                     _Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
169                 else:
170                     _Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
171                 _Un = Un(step)
172                 #
173                 # Etape d'évolution
174                 if self._parameters["EstimationOf"] == "State":
175                     _Xn = Mm( (_Xn, _Un) ) + CmUn(_Xn, _Un)
176                 elif self._parameters["EstimationOf"] == "Parameters":
177                     pass
178                 #
179                 if self._parameters["Bounds"] is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
180                     _Xn = numpy.max(numpy.hstack((_Xn,numpy.asmatrix(self._parameters["Bounds"])[:,0])),axis=1)
181                     _Xn = numpy.min(numpy.hstack((_Xn,numpy.asmatrix(self._parameters["Bounds"])[:,1])),axis=1)
182                 #
183                 # Etape de différence aux observations
184                 if self._parameters["EstimationOf"] == "State":
185                     _YmHMX = _Ynpu - numpy.asmatrix(numpy.ravel( Hm( (_Xn, None) ) )).T
186                 elif self._parameters["EstimationOf"] == "Parameters":
187                     _YmHMX = _Ynpu - numpy.asmatrix(numpy.ravel( Hm( (_Xn, _Un) ) )).T - CmUn(_Xn, _Un)
188                 self.DirectInnovation.append( _YmHMX )
189                 # Ajout dans la fonctionnelle d'observation
190                 Jo = Jo + _YmHMX.T * RI * _YmHMX
191             Jo  = 0.5 * Jo
192             J   = float( Jb ) + float( Jo )
193             self.StoredVariables["CostFunctionJb"].store( Jb )
194             self.StoredVariables["CostFunctionJo"].store( Jo )
195             self.StoredVariables["CostFunctionJ" ].store( J )
196             if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
197                "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
198                "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
199                 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
200             if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"]:
201                 self.StoredVariables["IndexOfOptimum"].store( IndexMin )
202             if "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
203                 self.StoredVariables["CurrentOptimum"].store( self.StoredVariables["CurrentState"][IndexMin] )
204             if "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
205                 self.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJb"][IndexMin] )
206                 self.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJo"][IndexMin] )
207                 self.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( self.StoredVariables["CostFunctionJ" ][IndexMin] )
208             return J
209         #
210         def GradientOfCostFunction(x):
211             _X      = numpy.asmatrix(numpy.ravel( x )).T
212             GradJb  = BI * (_X - Xb)
213             GradJo  = 0.
214             for step in range(duration-1,0,-1):
215                 # Etape de récupération du dernier stockage de l'évolution
216                 _Xn = self.DirectCalculation.pop()
217                 # Etape de récupération du dernier stockage de l'innovation
218                 _YmHMX = self.DirectInnovation.pop()
219                 # Calcul des adjoints
220                 Ha = HO["Adjoint"].asMatrix(ValueForMethodForm = _Xn)
221                 Ha = Ha.reshape(_Xn.size,_YmHMX.size) # ADAO & check shape
222                 Ma = EM["Adjoint"].asMatrix(ValueForMethodForm = _Xn)
223                 Ma = Ma.reshape(_Xn.size,_Xn.size) # ADAO & check shape
224                 # Calcul du gradient par etat adjoint
225                 GradJo = GradJo + Ha * RI * _YmHMX # Equivaut pour Ha lineaire à : Ha( (_Xn, RI * _YmHMX) )
226                 GradJo = Ma * GradJo               # Equivaut pour Ma lineaire à : Ma( (_Xn, GradJo) )
227             GradJ   = numpy.asmatrix( numpy.ravel( GradJb ) - numpy.ravel( GradJo ) ).T
228             return GradJ.A1
229         #
230         # Point de démarrage de l'optimisation : Xini = Xb
231         # ------------------------------------
232         if isinstance(Xb, type(numpy.matrix([]))):
233             Xini = Xb.A1.tolist()
234         else:
235             Xini = list(Xb)
236         #
237         # Minimisation de la fonctionnelle
238         # --------------------------------
239         nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
240         #
241         if self._parameters["Minimizer"] == "LBFGSB":
242             Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
243                 func        = CostFunction,
244                 x0          = Xini,
245                 fprime      = GradientOfCostFunction,
246                 args        = (),
247                 bounds      = self._parameters["Bounds"],
248                 maxfun      = self._parameters["MaximumNumberOfSteps"]-1,
249                 factr       = self._parameters["CostDecrementTolerance"]*1.e14,
250                 pgtol       = self._parameters["ProjectedGradientTolerance"],
251                 iprint      = self._parameters["optiprint"],
252                 )
253             nfeval = Informations['funcalls']
254             rc     = Informations['warnflag']
255         elif self._parameters["Minimizer"] == "TNC":
256             Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
257                 func        = CostFunction,
258                 x0          = Xini,
259                 fprime      = GradientOfCostFunction,
260                 args        = (),
261                 bounds      = self._parameters["Bounds"],
262                 maxfun      = self._parameters["MaximumNumberOfSteps"],
263                 pgtol       = self._parameters["ProjectedGradientTolerance"],
264                 ftol        = self._parameters["CostDecrementTolerance"],
265                 messages    = self._parameters["optmessages"],
266                 )
267         elif self._parameters["Minimizer"] == "CG":
268             Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
269                 f           = CostFunction,
270                 x0          = Xini,
271                 fprime      = GradientOfCostFunction,
272                 args        = (),
273                 maxiter     = self._parameters["MaximumNumberOfSteps"],
274                 gtol        = self._parameters["GradientNormTolerance"],
275                 disp        = self._parameters["optdisp"],
276                 full_output = True,
277                 )
278         elif self._parameters["Minimizer"] == "NCG":
279             Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
280                 f           = CostFunction,
281                 x0          = Xini,
282                 fprime      = GradientOfCostFunction,
283                 args        = (),
284                 maxiter     = self._parameters["MaximumNumberOfSteps"],
285                 avextol     = self._parameters["CostDecrementTolerance"],
286                 disp        = self._parameters["optdisp"],
287                 full_output = True,
288                 )
289         elif self._parameters["Minimizer"] == "BFGS":
290             Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
291                 f           = CostFunction,
292                 x0          = Xini,
293                 fprime      = GradientOfCostFunction,
294                 args        = (),
295                 maxiter     = self._parameters["MaximumNumberOfSteps"],
296                 gtol        = self._parameters["GradientNormTolerance"],
297                 disp        = self._parameters["optdisp"],
298                 full_output = True,
299                 )
300         else:
301             raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
302         #
303         IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
304         MinJ     = self.StoredVariables["CostFunctionJ"][IndexMin]
305         #
306         # Correction pour pallier a un bug de TNC sur le retour du Minimum
307         # ----------------------------------------------------------------
308         if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
309             Minimum = self.StoredVariables["CurrentState"][IndexMin]
310         #
311         # Obtention de l'analyse
312         # ----------------------
313         Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
314         #
315         self.StoredVariables["Analysis"].store( Xa.A1 )
316         #
317         # Calculs et/ou stockages supplémentaires
318         # ---------------------------------------
319         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
320             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
321         #
322         self._post_run(HO)
323         return 0
324
325 # ==============================================================================
326 if __name__ == "__main__":
327     print('\n AUTODIAGNOSTIC \n')