1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2015 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"]
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 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
173 self.DirectCalculation = [None,]
174 self.DirectInnovation = [None,]
177 for step in range(0,duration-1):
178 self.DirectCalculation.append( _Xn )
179 if hasattr(Y,"store"):
180 _Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
182 _Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
186 if self._parameters["EstimationOf"] == "State":
187 _Xn = Mm( (_Xn, _Un) ) + CmUn(_Xn, _Un)
188 elif self._parameters["EstimationOf"] == "Parameters":
191 if Bounds is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
192 _Xn = numpy.max(numpy.hstack((_Xn,numpy.asmatrix(Bounds)[:,0])),axis=1)
193 _Xn = numpy.min(numpy.hstack((_Xn,numpy.asmatrix(Bounds)[:,1])),axis=1)
195 # Etape de différence aux observations
196 if self._parameters["EstimationOf"] == "State":
197 _YmHMX = _Ynpu - numpy.asmatrix(numpy.ravel( Hm( (_Xn, None) ) )).T
198 elif self._parameters["EstimationOf"] == "Parameters":
199 _YmHMX = _Ynpu - numpy.asmatrix(numpy.ravel( Hm( (_Xn, _Un) ) )).T - CmUn(_Xn, _Un)
200 self.DirectInnovation.append( _YmHMX )
201 # Ajout dans la fonctionnelle d'observation
202 Jo = Jo + _YmHMX.T * RI * _YmHMX
204 J = float( Jb ) + float( Jo )
205 if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
206 self.StoredVariables["CurrentState"].store( _X )
207 self.StoredVariables["CostFunctionJb"].store( Jb )
208 self.StoredVariables["CostFunctionJo"].store( Jo )
209 self.StoredVariables["CostFunctionJ" ].store( J )
212 def GradientOfCostFunction(x):
213 _X = numpy.asmatrix(numpy.ravel( x )).T
214 GradJb = BI * (_X - Xb)
216 for step in range(duration-1,0,-1):
217 # Etape de récupération du dernier stockage de l'évolution
218 _Xn = self.DirectCalculation.pop()
219 # Etape de récupération du dernier stockage de l'innovation
220 _YmHMX = self.DirectInnovation.pop()
221 # Calcul des adjoints
222 Ha = HO["Adjoint"].asMatrix(ValueForMethodForm = _Xn)
223 Ha = Ha.reshape(_Xn.size,_YmHMX.size) # ADAO & check shape
224 Ma = EM["Adjoint"].asMatrix(ValueForMethodForm = _Xn)
225 Ma = Ma.reshape(_Xn.size,_Xn.size) # ADAO & check shape
226 # Calcul du gradient par etat adjoint
227 GradJo = GradJo + Ha * RI * _YmHMX # Equivaut pour Ha lineaire à : Ha( (_Xn, RI * _YmHMX) )
228 GradJo = Ma * GradJo # Equivaut pour Ma lineaire à : Ma( (_Xn, GradJo) )
229 GradJ = numpy.asmatrix( numpy.ravel( GradJb ) - numpy.ravel( GradJo ) ).T
232 # Point de démarrage de l'optimisation : Xini = Xb
233 # ------------------------------------
234 if type(Xb) is type(numpy.matrix([])):
235 Xini = Xb.A1.tolist()
239 # Minimisation de la fonctionnelle
240 # --------------------------------
241 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
243 if self._parameters["Minimizer"] == "LBFGSB":
244 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
247 fprime = GradientOfCostFunction,
250 maxfun = self._parameters["MaximumNumberOfSteps"]-1,
251 factr = self._parameters["CostDecrementTolerance"]*1.e14,
252 pgtol = self._parameters["ProjectedGradientTolerance"],
253 iprint = self.__iprint,
255 nfeval = Informations['funcalls']
256 rc = Informations['warnflag']
257 elif self._parameters["Minimizer"] == "TNC":
258 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
261 fprime = GradientOfCostFunction,
264 maxfun = self._parameters["MaximumNumberOfSteps"],
265 pgtol = self._parameters["ProjectedGradientTolerance"],
266 ftol = self._parameters["CostDecrementTolerance"],
267 messages = self.__message,
269 elif self._parameters["Minimizer"] == "CG":
270 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
273 fprime = GradientOfCostFunction,
275 maxiter = self._parameters["MaximumNumberOfSteps"],
276 gtol = self._parameters["GradientNormTolerance"],
280 elif self._parameters["Minimizer"] == "NCG":
281 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
284 fprime = GradientOfCostFunction,
286 maxiter = self._parameters["MaximumNumberOfSteps"],
287 avextol = self._parameters["CostDecrementTolerance"],
291 elif self._parameters["Minimizer"] == "BFGS":
292 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
295 fprime = GradientOfCostFunction,
297 maxiter = self._parameters["MaximumNumberOfSteps"],
298 gtol = self._parameters["GradientNormTolerance"],
303 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
305 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
306 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
308 # Correction pour pallier a un bug de TNC sur le retour du Minimum
309 # ----------------------------------------------------------------
310 if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
311 Minimum = self.StoredVariables["CurrentState"][IndexMin]
313 # Obtention de l'analyse
314 # ----------------------
315 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
317 self.StoredVariables["Analysis"].store( Xa.A1 )
319 # Calculs et/ou stockages supplémentaires
320 # ---------------------------------------
321 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
322 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
327 # ==============================================================================
328 if __name__ == "__main__":
329 print '\n AUTODIAGNOSTIC \n'