1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2019 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 coût lors de l'arrêt",
66 self.defineRequiredParameter(
67 name = "ProjectedGradientTolerance",
70 message = "Maximum des composantes du gradient projeté lors de l'arrêt",
73 self.defineRequiredParameter(
74 name = "GradientNormTolerance",
77 message = "Maximum des composantes du gradient lors de l'arrêt",
80 self.defineRequiredParameter(
81 name = "StoreInternalVariables",
84 message = "Stockage des variables internes ou intermédiaires du calcul",
86 self.defineRequiredParameter(
87 name = "StoreSupplementaryCalculations",
90 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
94 "CostFunctionJAtCurrentOptimum",
96 "CostFunctionJbAtCurrentOptimum",
98 "CostFunctionJoAtCurrentOptimum",
104 self.defineRequiredParameter( # Pas de type
106 message = "Liste des valeurs de bornes",
108 self.requireInputArguments(
109 mandatory= ("Xb", "Y", "HO", "EM", "R", "B" ),
110 optional = ("U", "CM"),
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)
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)
122 Hm = HO["Direct"].appliedControledFormTo
124 Mm = EM["Direct"].appliedControledFormTo
126 if CM is not None and "Tangent" in CM and U is not None:
127 Cm = CM["Tangent"].asMatrix(Xb)
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
138 _Un = numpy.asmatrix(numpy.ravel( U )).T
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
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.
155 # Nombre de pas identique au nombre de pas d'observations
156 # -------------------------------------------------------
157 if hasattr(Y,"stepnumber"):
158 duration = Y.stepnumber()
162 # Précalcul des inversions de B et R
163 # ----------------------------------
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é
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,]
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
187 _Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
191 if self._parameters["EstimationOf"] == "State":
192 _Xn = Mm( (_Xn, _Un) ) + CmUn(_Xn, _Un)
193 elif self._parameters["EstimationOf"] == "Parameters":
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)
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
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] )
231 def GradientOfCostFunction(x):
232 _X = numpy.asmatrix(numpy.ravel( x )).T
233 GradJb = BI * (_X - Xb)
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
251 # Point de démarrage de l'optimisation : Xini = Xb
252 # ------------------------------------
253 if isinstance(Xb, type(numpy.matrix([]))):
254 Xini = Xb.A1.tolist()
258 # Minimisation de la fonctionnelle
259 # --------------------------------
260 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
262 if self._parameters["Minimizer"] == "LBFGSB":
263 # Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
265 Minimum, J_optimal, Informations = lbfgsbhlt.fmin_l_bfgs_b(
268 fprime = GradientOfCostFunction,
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"],
276 nfeval = Informations['funcalls']
277 rc = Informations['warnflag']
278 elif self._parameters["Minimizer"] == "TNC":
279 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
282 fprime = GradientOfCostFunction,
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"],
290 elif self._parameters["Minimizer"] == "CG":
291 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
294 fprime = GradientOfCostFunction,
296 maxiter = self._parameters["MaximumNumberOfSteps"],
297 gtol = self._parameters["GradientNormTolerance"],
298 disp = self._parameters["optdisp"],
301 elif self._parameters["Minimizer"] == "NCG":
302 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
305 fprime = GradientOfCostFunction,
307 maxiter = self._parameters["MaximumNumberOfSteps"],
308 avextol = self._parameters["CostDecrementTolerance"],
309 disp = self._parameters["optdisp"],
312 elif self._parameters["Minimizer"] == "BFGS":
313 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
316 fprime = GradientOfCostFunction,
318 maxiter = self._parameters["MaximumNumberOfSteps"],
319 gtol = self._parameters["GradientNormTolerance"],
320 disp = self._parameters["optdisp"],
324 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
326 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
327 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
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]
334 # Obtention de l'analyse
335 # ----------------------
336 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
338 self.StoredVariables["Analysis"].store( Xa.A1 )
340 # Calculs et/ou stockages supplémentaires
341 # ---------------------------------------
342 if self._toStore("BMA"):
343 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
348 # ==============================================================================
349 if __name__ == "__main__":
350 print('\n AUTODIAGNOSTIC \n')