1 #-*-coding:iso-8859-1-*-
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",
89 listval = ["BMA", "CurrentState", "CostFunctionJ", "CostFunctionJb", "CostFunctionJo", "IndexOfOptimum", "CurrentOptimum", "CostFunctionJAtCurrentOptimum"]
91 self.defineRequiredParameter( # Pas de type
93 message = "Liste des valeurs de bornes",
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(Parameters)
99 # Correction pour pallier a un bug de TNC sur le retour du Minimum
100 if "Minimizer" in self._parameters and self._parameters["Minimizer"] == "TNC":
101 self.setParameterValue("StoreInternalVariables",True)
105 Hm = HO["Direct"].appliedControledFormTo
107 Mm = EM["Direct"].appliedControledFormTo
109 if CM is not None and "Tangent" in CM and U is not None:
110 Cm = CM["Tangent"].asMatrix(Xb)
116 if hasattr(U,"store") and 1<=_step<len(U) :
117 _Un = numpy.asmatrix(numpy.ravel( U[_step] )).T
118 elif hasattr(U,"store") and len(U)==1:
119 _Un = numpy.asmatrix(numpy.ravel( U[0] )).T
121 _Un = numpy.asmatrix(numpy.ravel( U )).T
126 if Cm is not None and _un is not None: # Attention : si Cm est aussi dans M, doublon !
127 _Cm = Cm.reshape(_xn.size,_un.size) # ADAO & check shape
133 # Remarque : les observations sont exploitées à partir du pas de temps
134 # numéro 1, et sont utilisées dans Yo comme rangées selon ces indices.
135 # Donc le pas 0 n'est pas utilisé puisque la première étape commence
136 # avec l'observation du pas 1.
138 # Nombre de pas identique au nombre de pas d'observations
139 # -------------------------------------------------------
140 if hasattr(Y,"stepnumber"):
141 duration = Y.stepnumber()
145 # Précalcul des inversions de B et R
146 # ----------------------------------
150 # Définition de la fonction-coût
151 # ------------------------------
152 self.DirectCalculation = [None,] # Le pas 0 n'est pas observé
153 self.DirectInnovation = [None,] # Le pas 0 n'est pas observé
155 _X = numpy.asmatrix(numpy.ravel( x )).T
156 if self._parameters["StoreInternalVariables"] or \
157 "CurrentState" in self._parameters["StoreSupplementaryCalculations"] or \
158 "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
159 self.StoredVariables["CurrentState"].store( _X )
160 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
161 self.DirectCalculation = [None,]
162 self.DirectInnovation = [None,]
165 for step in range(0,duration-1):
166 self.DirectCalculation.append( _Xn )
167 if hasattr(Y,"store"):
168 _Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
170 _Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
174 if self._parameters["EstimationOf"] == "State":
175 _Xn = Mm( (_Xn, _Un) ) + CmUn(_Xn, _Un)
176 elif self._parameters["EstimationOf"] == "Parameters":
179 if self._parameters["Bounds"] is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
180 _Xn = numpy.max(numpy.hstack((_Xn,numpy.asmatrix(self._parameters["Bounds"])[:,0])),axis=1)
181 _Xn = numpy.min(numpy.hstack((_Xn,numpy.asmatrix(self._parameters["Bounds"])[:,1])),axis=1)
183 # Etape de différence aux observations
184 if self._parameters["EstimationOf"] == "State":
185 _YmHMX = _Ynpu - numpy.asmatrix(numpy.ravel( Hm( (_Xn, None) ) )).T
186 elif self._parameters["EstimationOf"] == "Parameters":
187 _YmHMX = _Ynpu - numpy.asmatrix(numpy.ravel( Hm( (_Xn, _Un) ) )).T - CmUn(_Xn, _Un)
188 self.DirectInnovation.append( _YmHMX )
189 # Ajout dans la fonctionnelle d'observation
190 Jo = Jo + _YmHMX.T * RI * _YmHMX
192 J = float( Jb ) + float( Jo )
193 self.StoredVariables["CostFunctionJb"].store( Jb )
194 self.StoredVariables["CostFunctionJo"].store( Jo )
195 self.StoredVariables["CostFunctionJ" ].store( J )
196 if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
197 "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
198 "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
199 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
200 if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"]:
201 self.StoredVariables["IndexOfOptimum"].store( IndexMin )
202 if "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
203 self.StoredVariables["CurrentOptimum"].store( self.StoredVariables["CurrentState"][IndexMin] )
204 if "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
205 self.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJb"][IndexMin] )
206 self.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJo"][IndexMin] )
207 self.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( self.StoredVariables["CostFunctionJ" ][IndexMin] )
210 def GradientOfCostFunction(x):
211 _X = numpy.asmatrix(numpy.ravel( x )).T
212 GradJb = BI * (_X - Xb)
214 for step in range(duration-1,0,-1):
215 # Etape de récupération du dernier stockage de l'évolution
216 _Xn = self.DirectCalculation.pop()
217 # Etape de récupération du dernier stockage de l'innovation
218 _YmHMX = self.DirectInnovation.pop()
219 # Calcul des adjoints
220 Ha = HO["Adjoint"].asMatrix(ValueForMethodForm = _Xn)
221 Ha = Ha.reshape(_Xn.size,_YmHMX.size) # ADAO & check shape
222 Ma = EM["Adjoint"].asMatrix(ValueForMethodForm = _Xn)
223 Ma = Ma.reshape(_Xn.size,_Xn.size) # ADAO & check shape
224 # Calcul du gradient par etat adjoint
225 GradJo = GradJo + Ha * RI * _YmHMX # Equivaut pour Ha lineaire à : Ha( (_Xn, RI * _YmHMX) )
226 GradJo = Ma * GradJo # Equivaut pour Ma lineaire à : Ma( (_Xn, GradJo) )
227 GradJ = numpy.asmatrix( numpy.ravel( GradJb ) - numpy.ravel( GradJo ) ).T
230 # Point de démarrage de l'optimisation : Xini = Xb
231 # ------------------------------------
232 if type(Xb) is type(numpy.matrix([])):
233 Xini = Xb.A1.tolist()
237 # Minimisation de la fonctionnelle
238 # --------------------------------
239 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
241 if self._parameters["Minimizer"] == "LBFGSB":
242 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
245 fprime = GradientOfCostFunction,
247 bounds = self._parameters["Bounds"],
248 maxfun = self._parameters["MaximumNumberOfSteps"]-1,
249 factr = self._parameters["CostDecrementTolerance"]*1.e14,
250 pgtol = self._parameters["ProjectedGradientTolerance"],
251 iprint = self._parameters["optiprint"],
253 nfeval = Informations['funcalls']
254 rc = Informations['warnflag']
255 elif self._parameters["Minimizer"] == "TNC":
256 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
259 fprime = GradientOfCostFunction,
261 bounds = self._parameters["Bounds"],
262 maxfun = self._parameters["MaximumNumberOfSteps"],
263 pgtol = self._parameters["ProjectedGradientTolerance"],
264 ftol = self._parameters["CostDecrementTolerance"],
265 messages = self._parameters["optmessages"],
267 elif self._parameters["Minimizer"] == "CG":
268 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
271 fprime = GradientOfCostFunction,
273 maxiter = self._parameters["MaximumNumberOfSteps"],
274 gtol = self._parameters["GradientNormTolerance"],
275 disp = self._parameters["optdisp"],
278 elif self._parameters["Minimizer"] == "NCG":
279 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
282 fprime = GradientOfCostFunction,
284 maxiter = self._parameters["MaximumNumberOfSteps"],
285 avextol = self._parameters["CostDecrementTolerance"],
286 disp = self._parameters["optdisp"],
289 elif self._parameters["Minimizer"] == "BFGS":
290 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
293 fprime = GradientOfCostFunction,
295 maxiter = self._parameters["MaximumNumberOfSteps"],
296 gtol = self._parameters["GradientNormTolerance"],
297 disp = self._parameters["optdisp"],
301 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
303 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
304 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
306 # Correction pour pallier a un bug de TNC sur le retour du Minimum
307 # ----------------------------------------------------------------
308 if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
309 Minimum = self.StoredVariables["CurrentState"][IndexMin]
311 # Obtention de l'analyse
312 # ----------------------
313 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
315 self.StoredVariables["Analysis"].store( Xa.A1 )
317 # Calculs et/ou stockages supplémentaires
318 # ---------------------------------------
319 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
320 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
325 # ==============================================================================
326 if __name__ == "__main__":
327 print('\n AUTODIAGNOSTIC \n')