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