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, "NONLINEARLEASTSQUARES")
31 self.defineRequiredParameter(
35 message = "Minimiseur utilisé",
36 listval = ["LBFGSB","TNC", "CG", "NCG", "BFGS", "LM"],
38 self.defineRequiredParameter(
39 name = "MaximumNumberOfSteps",
42 message = "Nombre maximal de pas d'optimisation",
45 self.defineRequiredParameter(
46 name = "CostDecrementTolerance",
49 message = "Diminution relative minimale du cout lors de l'arrêt",
51 self.defineRequiredParameter(
52 name = "ProjectedGradientTolerance",
55 message = "Maximum des composantes du gradient projeté lors de l'arrêt",
58 self.defineRequiredParameter(
59 name = "GradientNormTolerance",
62 message = "Maximum des composantes du gradient lors de l'arrêt",
64 self.defineRequiredParameter(
65 name = "StoreInternalVariables",
68 message = "Stockage des variables internes ou intermédiaires du calcul",
70 self.defineRequiredParameter(
71 name = "StoreSupplementaryCalculations",
74 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
75 listval = ["BMA", "OMA", "OMB", "CurrentState", "CostFunctionJ", "CostFunctionJb", "CostFunctionJo", "Innovation", "SimulatedObservationAtCurrentState", "SimulatedObservationAtOptimum"]
77 self.defineRequiredParameter( # Pas de type
79 message = "Liste des valeurs de bornes",
82 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
84 if logging.getLogger().level < logging.WARNING:
85 self.__iprint, self.__disp = 1, 1
86 self.__message = scipy.optimize.tnc.MSG_ALL
88 self.__iprint, self.__disp = -1, 0
89 self.__message = scipy.optimize.tnc.MSG_NONE
91 # Paramètres de pilotage
92 # ----------------------
93 self.setParameters(Parameters)
95 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):
96 Bounds = self._parameters["Bounds"]
97 logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
101 # Correction pour pallier a un bug de TNC sur le retour du Minimum
102 if self._parameters.has_key("Minimizer") == "TNC":
103 self.setParameterValue("StoreInternalVariables",True)
107 Hm = HO["Direct"].appliedTo
108 Ha = HO["Adjoint"].appliedInXTo
110 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
111 # ----------------------------------------------------
112 if HO["AppliedToX"] is not None and HO["AppliedToX"].has_key("HXb"):
113 HXb = Hm( Xb, HO["AppliedToX"]["HXb"])
116 HXb = numpy.asmatrix(numpy.ravel( HXb )).T
118 # Calcul de l'innovation
119 # ----------------------
120 if Y.size != HXb.size:
121 raise ValueError("The size %i of observations Y and %i of observed calculation H(X) are different, they have to be identical."%(Y.size,HXb.size))
122 if max(Y.shape) != max(HXb.shape):
123 raise ValueError("The shapes %s of observations Y and %s of observed calculation H(X) are different, they have to be identical."%(Y.shape,HXb.shape))
126 # Précalcul des inversions de B et R
127 # ----------------------------------
129 if self._parameters["Minimizer"] == "LM":
130 RdemiI = R.choleskyI()
132 # Définition de la fonction-coût
133 # ------------------------------
135 _X = numpy.asmatrix(numpy.ravel( x )).T
136 if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
137 self.StoredVariables["CurrentState"].store( _X )
139 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
140 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
141 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
143 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
144 J = float( Jb ) + float( Jo )
145 self.StoredVariables["CostFunctionJb"].store( Jb )
146 self.StoredVariables["CostFunctionJo"].store( Jo )
147 self.StoredVariables["CostFunctionJ" ].store( J )
150 def GradientOfCostFunction(x):
151 _X = numpy.asmatrix(numpy.ravel( x )).T
153 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
155 GradJo = - Ha( (_X, RI * (Y - _HX)) )
156 GradJ = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
159 def CostFunctionLM(x):
160 _X = numpy.asmatrix(numpy.ravel( x )).T
162 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
164 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
165 J = float( Jb ) + float( Jo )
166 if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
167 self.StoredVariables["CurrentState"].store( _X )
168 self.StoredVariables["CostFunctionJb"].store( Jb )
169 self.StoredVariables["CostFunctionJo"].store( Jo )
170 self.StoredVariables["CostFunctionJ" ].store( J )
172 return numpy.ravel( RdemiI*(Y - _HX) )
174 def GradientOfCostFunctionLM(x):
175 _X = numpy.asmatrix(numpy.ravel( x )).T
177 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
179 GradJo = - Ha( (_X, RI * (Y - _HX)) )
180 GradJ = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
181 return - RdemiI*HO["Tangent"].asMatrix( _X )
183 # Point de démarrage de l'optimisation : Xini = Xb
184 # ------------------------------------
185 if type(Xb) is type(numpy.matrix([])):
186 Xini = Xb.A1.tolist()
190 # Minimisation de la fonctionnelle
191 # --------------------------------
192 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
194 if self._parameters["Minimizer"] == "LBFGSB":
195 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
198 fprime = GradientOfCostFunction,
201 maxfun = self._parameters["MaximumNumberOfSteps"]-1,
202 factr = self._parameters["CostDecrementTolerance"]*1.e14,
203 pgtol = self._parameters["ProjectedGradientTolerance"],
204 iprint = self.__iprint,
206 nfeval = Informations['funcalls']
207 rc = Informations['warnflag']
208 elif self._parameters["Minimizer"] == "TNC":
209 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
212 fprime = GradientOfCostFunction,
215 maxfun = self._parameters["MaximumNumberOfSteps"],
216 pgtol = self._parameters["ProjectedGradientTolerance"],
217 ftol = self._parameters["CostDecrementTolerance"],
218 messages = self.__message,
220 elif self._parameters["Minimizer"] == "CG":
221 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
224 fprime = GradientOfCostFunction,
226 maxiter = self._parameters["MaximumNumberOfSteps"],
227 gtol = self._parameters["GradientNormTolerance"],
231 elif self._parameters["Minimizer"] == "NCG":
232 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
235 fprime = GradientOfCostFunction,
237 maxiter = self._parameters["MaximumNumberOfSteps"],
238 avextol = self._parameters["CostDecrementTolerance"],
242 elif self._parameters["Minimizer"] == "BFGS":
243 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
246 fprime = GradientOfCostFunction,
248 maxiter = self._parameters["MaximumNumberOfSteps"],
249 gtol = self._parameters["GradientNormTolerance"],
253 elif self._parameters["Minimizer"] == "LM":
254 Minimum, cov_x, infodict, mesg, rc = scipy.optimize.leastsq(
255 func = CostFunctionLM,
257 Dfun = GradientOfCostFunctionLM,
259 ftol = self._parameters["CostDecrementTolerance"],
260 maxfev = self._parameters["MaximumNumberOfSteps"],
261 gtol = self._parameters["GradientNormTolerance"],
264 nfeval = infodict['nfev']
266 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
268 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
269 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
271 # Correction pour pallier a un bug de TNC sur le retour du Minimum
272 # ----------------------------------------------------------------
273 if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
274 Minimum = self.StoredVariables["CurrentState"][IndexMin]
276 # Obtention de l'analyse
277 # ----------------------
278 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
280 self.StoredVariables["Analysis"].store( Xa.A1 )
282 if "OMA" in self._parameters["StoreSupplementaryCalculations"] or \
283 "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
287 # Calculs et/ou stockages supplémentaires
288 # ---------------------------------------
289 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
290 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
291 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
292 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
293 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
294 self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
295 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
296 self.StoredVariables["OMB"].store( numpy.ravel(d) )
297 if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
298 self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
303 # ==============================================================================
304 if __name__ == "__main__":
305 print '\n AUTODIAGNOSTIC \n'