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