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