Salome HOME
Updating copyright date information
[modules/adao.git] / src / daComposant / daAlgorithms / 4DVAR.py
1 #-*-coding:iso-8859-1-*-
2 #
3 # Copyright (C) 2008-2016 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", "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()
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"] or \
214                "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
215                 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
216             if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"]:
217                 self.StoredVariables["IndexOfOptimum"].store( IndexMin )
218             if "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
219                 self.StoredVariables["CurrentOptimum"].store( self.StoredVariables["CurrentState"][IndexMin] )
220             if "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
221                 self.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJb"][IndexMin] )
222                 self.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJo"][IndexMin] )
223                 self.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( self.StoredVariables["CostFunctionJ" ][IndexMin] )
224             return J
225         #
226         def GradientOfCostFunction(x):
227             _X      = numpy.asmatrix(numpy.ravel( x )).T
228             GradJb  = BI * (_X - Xb)
229             GradJo  = 0.
230             for step in range(duration-1,0,-1):
231                 # Etape de récupération du dernier stockage de l'évolution
232                 _Xn = self.DirectCalculation.pop()
233                 # Etape de récupération du dernier stockage de l'innovation
234                 _YmHMX = self.DirectInnovation.pop()
235                 # Calcul des adjoints
236                 Ha = HO["Adjoint"].asMatrix(ValueForMethodForm = _Xn)
237                 Ha = Ha.reshape(_Xn.size,_YmHMX.size) # ADAO & check shape
238                 Ma = EM["Adjoint"].asMatrix(ValueForMethodForm = _Xn)
239                 Ma = Ma.reshape(_Xn.size,_Xn.size) # ADAO & check shape
240                 # Calcul du gradient par etat adjoint
241                 GradJo = GradJo + Ha * RI * _YmHMX # Equivaut pour Ha lineaire à : Ha( (_Xn, RI * _YmHMX) )
242                 GradJo = Ma * GradJo               # Equivaut pour Ma lineaire à : Ma( (_Xn, GradJo) )
243             GradJ   = numpy.asmatrix( numpy.ravel( GradJb ) - numpy.ravel( GradJo ) ).T
244             return GradJ.A1
245         #
246         # Point de démarrage de l'optimisation : Xini = Xb
247         # ------------------------------------
248         if type(Xb) is type(numpy.matrix([])):
249             Xini = Xb.A1.tolist()
250         else:
251             Xini = list(Xb)
252         #
253         # Minimisation de la fonctionnelle
254         # --------------------------------
255         nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
256         #
257         if self._parameters["Minimizer"] == "LBFGSB":
258             Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
259                 func        = CostFunction,
260                 x0          = Xini,
261                 fprime      = GradientOfCostFunction,
262                 args        = (),
263                 bounds      = Bounds,
264                 maxfun      = self._parameters["MaximumNumberOfSteps"]-1,
265                 factr       = self._parameters["CostDecrementTolerance"]*1.e14,
266                 pgtol       = self._parameters["ProjectedGradientTolerance"],
267                 iprint      = self.__iprint,
268                 )
269             nfeval = Informations['funcalls']
270             rc     = Informations['warnflag']
271         elif self._parameters["Minimizer"] == "TNC":
272             Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
273                 func        = CostFunction,
274                 x0          = Xini,
275                 fprime      = GradientOfCostFunction,
276                 args        = (),
277                 bounds      = Bounds,
278                 maxfun      = self._parameters["MaximumNumberOfSteps"],
279                 pgtol       = self._parameters["ProjectedGradientTolerance"],
280                 ftol        = self._parameters["CostDecrementTolerance"],
281                 messages    = self.__message,
282                 )
283         elif self._parameters["Minimizer"] == "CG":
284             Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
285                 f           = CostFunction,
286                 x0          = Xini,
287                 fprime      = GradientOfCostFunction,
288                 args        = (),
289                 maxiter     = self._parameters["MaximumNumberOfSteps"],
290                 gtol        = self._parameters["GradientNormTolerance"],
291                 disp        = self.__disp,
292                 full_output = True,
293                 )
294         elif self._parameters["Minimizer"] == "NCG":
295             Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
296                 f           = CostFunction,
297                 x0          = Xini,
298                 fprime      = GradientOfCostFunction,
299                 args        = (),
300                 maxiter     = self._parameters["MaximumNumberOfSteps"],
301                 avextol     = self._parameters["CostDecrementTolerance"],
302                 disp        = self.__disp,
303                 full_output = True,
304                 )
305         elif self._parameters["Minimizer"] == "BFGS":
306             Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
307                 f           = CostFunction,
308                 x0          = Xini,
309                 fprime      = GradientOfCostFunction,
310                 args        = (),
311                 maxiter     = self._parameters["MaximumNumberOfSteps"],
312                 gtol        = self._parameters["GradientNormTolerance"],
313                 disp        = self.__disp,
314                 full_output = True,
315                 )
316         else:
317             raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
318         #
319         IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
320         MinJ     = self.StoredVariables["CostFunctionJ"][IndexMin]
321         #
322         # Correction pour pallier a un bug de TNC sur le retour du Minimum
323         # ----------------------------------------------------------------
324         if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
325             Minimum = self.StoredVariables["CurrentState"][IndexMin]
326         #
327         # Obtention de l'analyse
328         # ----------------------
329         Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
330         #
331         self.StoredVariables["Analysis"].store( Xa.A1 )
332         #
333         # Calculs et/ou stockages supplémentaires
334         # ---------------------------------------
335         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
336             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
337         #
338         self._post_run(HO)
339         return 0
340
341 # ==============================================================================
342 if __name__ == "__main__":
343     print '\n AUTODIAGNOSTIC \n'