1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2017 EDF R&D
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.
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.
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
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
24 from daCore import BasicObjects
25 import numpy, scipy.optimize
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
30 BasicObjects.Algorithm.__init__(self, "4DVAR")
31 self.defineRequiredParameter(
32 name = "ConstrainedBy",
33 default = "EstimateProjection",
35 message = "Prise en compte des contraintes",
36 listval = ["EstimateProjection"],
38 self.defineRequiredParameter(
39 name = "EstimationOf",
42 message = "Estimation d'etat ou de parametres",
43 listval = ["State", "Parameters"],
45 self.defineRequiredParameter(
49 message = "Minimiseur utilisé",
50 listval = ["LBFGSB","TNC", "CG", "NCG", "BFGS"],
52 self.defineRequiredParameter(
53 name = "MaximumNumberOfSteps",
56 message = "Nombre maximal de pas d'optimisation",
59 self.defineRequiredParameter(
60 name = "CostDecrementTolerance",
63 message = "Diminution relative minimale du cout lors de l'arrêt",
65 self.defineRequiredParameter(
66 name = "ProjectedGradientTolerance",
69 message = "Maximum des composantes du gradient projeté lors de l'arrêt",
72 self.defineRequiredParameter(
73 name = "GradientNormTolerance",
76 message = "Maximum des composantes du gradient lors de l'arrêt",
78 self.defineRequiredParameter(
79 name = "StoreInternalVariables",
82 message = "Stockage des variables internes ou intermédiaires du calcul",
84 self.defineRequiredParameter(
85 name = "StoreSupplementaryCalculations",
88 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
97 "CostFunctionJAtCurrentOptimum",
98 "CostFunctionJbAtCurrentOptimum",
99 "CostFunctionJoAtCurrentOptimum",
102 self.defineRequiredParameter( # Pas de type
104 message = "Liste des valeurs de bornes",
106 self.requireInputArguments(
107 mandatory= ("Xb", "Y", "HO", "EM", "R", "B" ),
108 optional = ("U", "CM"),
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)
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)
120 Hm = HO["Direct"].appliedControledFormTo
122 Mm = EM["Direct"].appliedControledFormTo
124 if CM is not None and "Tangent" in CM and U is not None:
125 Cm = CM["Tangent"].asMatrix(Xb)
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
136 _Un = numpy.asmatrix(numpy.ravel( U )).T
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
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.
153 # Nombre de pas identique au nombre de pas d'observations
154 # -------------------------------------------------------
155 if hasattr(Y,"stepnumber"):
156 duration = Y.stepnumber()
160 # Précalcul des inversions de B et R
161 # ----------------------------------
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é
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,]
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
185 _Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
189 if self._parameters["EstimationOf"] == "State":
190 _Xn = Mm( (_Xn, _Un) ) + CmUn(_Xn, _Un)
191 elif self._parameters["EstimationOf"] == "Parameters":
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)
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
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] )
229 def GradientOfCostFunction(x):
230 _X = numpy.asmatrix(numpy.ravel( x )).T
231 GradJb = BI * (_X - Xb)
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
249 # Point de démarrage de l'optimisation : Xini = Xb
250 # ------------------------------------
251 if isinstance(Xb, type(numpy.matrix([]))):
252 Xini = Xb.A1.tolist()
256 # Minimisation de la fonctionnelle
257 # --------------------------------
258 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
260 if self._parameters["Minimizer"] == "LBFGSB":
261 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
264 fprime = GradientOfCostFunction,
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"],
272 nfeval = Informations['funcalls']
273 rc = Informations['warnflag']
274 elif self._parameters["Minimizer"] == "TNC":
275 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
278 fprime = GradientOfCostFunction,
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"],
286 elif self._parameters["Minimizer"] == "CG":
287 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
290 fprime = GradientOfCostFunction,
292 maxiter = self._parameters["MaximumNumberOfSteps"],
293 gtol = self._parameters["GradientNormTolerance"],
294 disp = self._parameters["optdisp"],
297 elif self._parameters["Minimizer"] == "NCG":
298 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
301 fprime = GradientOfCostFunction,
303 maxiter = self._parameters["MaximumNumberOfSteps"],
304 avextol = self._parameters["CostDecrementTolerance"],
305 disp = self._parameters["optdisp"],
308 elif self._parameters["Minimizer"] == "BFGS":
309 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
312 fprime = GradientOfCostFunction,
314 maxiter = self._parameters["MaximumNumberOfSteps"],
315 gtol = self._parameters["GradientNormTolerance"],
316 disp = self._parameters["optdisp"],
320 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
322 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
323 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
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]
330 # Obtention de l'analyse
331 # ----------------------
332 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
334 self.StoredVariables["Analysis"].store( Xa.A1 )
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) )
344 # ==============================================================================
345 if __name__ == "__main__":
346 print('\n AUTODIAGNOSTIC \n')