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):
98 if logging.getLogger().level < logging.WARNING:
99 self.__iprint, self.__disp = 1, 1
100 self.__message = scipy.optimize.tnc.MSG_ALL
102 self.__iprint, self.__disp = -1, 0
103 self.__message = scipy.optimize.tnc.MSG_NONE
105 # Paramètres de pilotage
106 # ----------------------
107 self.setParameters(Parameters)
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,))
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)
121 Hm = HO["Direct"].appliedControledFormTo
123 Mm = EM["Direct"].appliedControledFormTo
125 if CM is not None and CM.has_key("Tangent") and U is not None:
126 Cm = CM["Tangent"].asMatrix(Xb)
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
137 _Un = numpy.asmatrix(numpy.ravel( U )).T
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
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.
154 # Nombre de pas identique au nombre de pas d'observations
155 # -------------------------------------------------------
156 if hasattr(Y,"stepnumber"):
157 duration = Y.stepnumber()
161 # Précalcul des inversions de B et R
162 # ----------------------------------
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é
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,]
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
186 _Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
190 if self._parameters["EstimationOf"] == "State":
191 _Xn = Mm( (_Xn, _Un) ) + CmUn(_Xn, _Un)
192 elif self._parameters["EstimationOf"] == "Parameters":
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)
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
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] )
226 def GradientOfCostFunction(x):
227 _X = numpy.asmatrix(numpy.ravel( x )).T
228 GradJb = BI * (_X - Xb)
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
246 # Point de démarrage de l'optimisation : Xini = Xb
247 # ------------------------------------
248 if type(Xb) is type(numpy.matrix([])):
249 Xini = Xb.A1.tolist()
253 # Minimisation de la fonctionnelle
254 # --------------------------------
255 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
257 if self._parameters["Minimizer"] == "LBFGSB":
258 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
261 fprime = GradientOfCostFunction,
264 maxfun = self._parameters["MaximumNumberOfSteps"]-1,
265 factr = self._parameters["CostDecrementTolerance"]*1.e14,
266 pgtol = self._parameters["ProjectedGradientTolerance"],
267 iprint = self.__iprint,
269 nfeval = Informations['funcalls']
270 rc = Informations['warnflag']
271 elif self._parameters["Minimizer"] == "TNC":
272 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
275 fprime = GradientOfCostFunction,
278 maxfun = self._parameters["MaximumNumberOfSteps"],
279 pgtol = self._parameters["ProjectedGradientTolerance"],
280 ftol = self._parameters["CostDecrementTolerance"],
281 messages = self.__message,
283 elif self._parameters["Minimizer"] == "CG":
284 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
287 fprime = GradientOfCostFunction,
289 maxiter = self._parameters["MaximumNumberOfSteps"],
290 gtol = self._parameters["GradientNormTolerance"],
294 elif self._parameters["Minimizer"] == "NCG":
295 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
298 fprime = GradientOfCostFunction,
300 maxiter = self._parameters["MaximumNumberOfSteps"],
301 avextol = self._parameters["CostDecrementTolerance"],
305 elif self._parameters["Minimizer"] == "BFGS":
306 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
309 fprime = GradientOfCostFunction,
311 maxiter = self._parameters["MaximumNumberOfSteps"],
312 gtol = self._parameters["GradientNormTolerance"],
317 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
319 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
320 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
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]
327 # Obtention de l'analyse
328 # ----------------------
329 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
331 self.StoredVariables["Analysis"].store( Xa.A1 )
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) )
341 # ==============================================================================
342 if __name__ == "__main__":
343 print '\n AUTODIAGNOSTIC \n'