1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2014 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, PlatformInfo
25 m = PlatformInfo.SystemUsage()
26 import numpy, scipy.optimize
28 # ==============================================================================
29 class ElementaryAlgorithm(BasicObjects.Algorithm):
31 BasicObjects.Algorithm.__init__(self, "NONLINEARLEASTSQUARES")
32 self.defineRequiredParameter(
36 message = "Minimiseur utilisé",
37 listval = ["LBFGSB","TNC", "CG", "NCG", "BFGS", "LM"],
39 self.defineRequiredParameter(
40 name = "MaximumNumberOfSteps",
43 message = "Nombre maximal de pas d'optimisation",
46 self.defineRequiredParameter(
47 name = "CostDecrementTolerance",
50 message = "Diminution relative minimale du cout lors de l'arrêt",
52 self.defineRequiredParameter(
53 name = "ProjectedGradientTolerance",
56 message = "Maximum des composantes du gradient projeté lors de l'arrêt",
59 self.defineRequiredParameter(
60 name = "GradientNormTolerance",
63 message = "Maximum des composantes du gradient lors de l'arrêt",
65 self.defineRequiredParameter(
66 name = "StoreInternalVariables",
69 message = "Stockage des variables internes ou intermédiaires du calcul",
71 self.defineRequiredParameter(
72 name = "StoreSupplementaryCalculations",
75 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
76 listval = ["BMA", "OMA", "OMB", "Innovation"]
79 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
80 if logging.getLogger().level < logging.WARNING:
81 self.__iprint, self.__disp = 1, 1
82 self.__message = scipy.optimize.tnc.MSG_ALL
84 self.__iprint, self.__disp = -1, 0
85 self.__message = scipy.optimize.tnc.MSG_NONE
87 logging.debug("%s Lancement"%self._name)
88 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
90 # Paramètres de pilotage
91 # ----------------------
92 self.setParameters(Parameters)
94 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):
95 Bounds = self._parameters["Bounds"]
96 logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
100 # Correction pour pallier a un bug de TNC sur le retour du Minimum
101 if self._parameters.has_key("Minimizer") == "TNC":
102 self.setParameterValue("StoreInternalVariables",True)
104 # Opérateur d'observation
105 # -----------------------
106 Hm = HO["Direct"].appliedTo
107 Ha = HO["Adjoint"].appliedInXTo
109 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
110 # ----------------------------------------------------
111 if HO["AppliedToX"] is not None and HO["AppliedToX"].has_key("HXb"):
112 HXb = HO["AppliedToX"]["HXb"]
115 HXb = numpy.asmatrix(numpy.ravel( HXb )).T
117 # Calcul de l'innovation
118 # ----------------------
119 if Y.size != HXb.size:
120 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))
121 if max(Y.shape) != max(HXb.shape):
122 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))
125 # Précalcul des inversions de B et R
126 # ----------------------------------
128 if self._parameters["Minimizer"] == "LM":
129 RdemiI = R.choleskyI()
131 # Définition de la fonction-coût
132 # ------------------------------
134 _X = numpy.asmatrix(numpy.ravel( x )).T
136 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
138 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
139 J = float( Jb ) + float( Jo )
140 if self._parameters["StoreInternalVariables"]:
141 self.StoredVariables["CurrentState"].store( _X )
142 self.StoredVariables["CostFunctionJb"].store( Jb )
143 self.StoredVariables["CostFunctionJo"].store( Jo )
144 self.StoredVariables["CostFunctionJ" ].store( J )
147 def GradientOfCostFunction(x):
148 _X = numpy.asmatrix(numpy.ravel( x )).T
150 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
152 GradJo = - Ha( (_X, RI * (Y - _HX)) )
153 GradJ = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
156 def CostFunctionLM(x):
157 _X = numpy.asmatrix(numpy.ravel( x )).T
159 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
161 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
162 J = float( Jb ) + float( Jo )
163 if self._parameters["StoreInternalVariables"]:
164 self.StoredVariables["CurrentState"].store( _X )
165 self.StoredVariables["CostFunctionJb"].store( Jb )
166 self.StoredVariables["CostFunctionJo"].store( Jo )
167 self.StoredVariables["CostFunctionJ" ].store( J )
169 return numpy.ravel( RdemiI*(Y - _HX) )
171 def GradientOfCostFunctionLM(x):
172 _X = numpy.asmatrix(numpy.ravel( x )).T
174 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
176 GradJo = - Ha( (_X, RI * (Y - _HX)) )
177 GradJ = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
178 return - RdemiI*HO["Tangent"].asMatrix( _X )
180 # Point de démarrage de l'optimisation : Xini = Xb
181 # ------------------------------------
182 if type(Xb) is type(numpy.matrix([])):
183 Xini = Xb.A1.tolist()
187 # Minimisation de la fonctionnelle
188 # --------------------------------
189 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
191 if self._parameters["Minimizer"] == "LBFGSB":
192 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
195 fprime = GradientOfCostFunction,
198 maxfun = self._parameters["MaximumNumberOfSteps"]-1,
199 factr = self._parameters["CostDecrementTolerance"]*1.e14,
200 pgtol = self._parameters["ProjectedGradientTolerance"],
201 iprint = self.__iprint,
203 nfeval = Informations['funcalls']
204 rc = Informations['warnflag']
205 elif self._parameters["Minimizer"] == "TNC":
206 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
209 fprime = GradientOfCostFunction,
212 maxfun = self._parameters["MaximumNumberOfSteps"],
213 pgtol = self._parameters["ProjectedGradientTolerance"],
214 ftol = self._parameters["CostDecrementTolerance"],
215 messages = self.__message,
217 elif self._parameters["Minimizer"] == "CG":
218 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
221 fprime = GradientOfCostFunction,
223 maxiter = self._parameters["MaximumNumberOfSteps"],
224 gtol = self._parameters["GradientNormTolerance"],
228 elif self._parameters["Minimizer"] == "NCG":
229 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
232 fprime = GradientOfCostFunction,
234 maxiter = self._parameters["MaximumNumberOfSteps"],
235 avextol = self._parameters["CostDecrementTolerance"],
239 elif self._parameters["Minimizer"] == "BFGS":
240 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
243 fprime = GradientOfCostFunction,
245 maxiter = self._parameters["MaximumNumberOfSteps"],
246 gtol = self._parameters["GradientNormTolerance"],
250 elif self._parameters["Minimizer"] == "LM":
251 Minimum, cov_x, infodict, mesg, rc = scipy.optimize.leastsq(
252 func = CostFunctionLM,
254 Dfun = GradientOfCostFunctionLM,
256 ftol = self._parameters["CostDecrementTolerance"],
257 maxfev = self._parameters["MaximumNumberOfSteps"],
258 gtol = self._parameters["GradientNormTolerance"],
261 nfeval = infodict['nfev']
263 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
265 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
266 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
268 # Correction pour pallier a un bug de TNC sur le retour du Minimum
269 # ----------------------------------------------------------------
270 if self._parameters["StoreInternalVariables"]:
271 Minimum = self.StoredVariables["CurrentState"][IndexMin]
273 # Obtention de l'analyse
274 # ----------------------
275 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
277 self.StoredVariables["Analysis"].store( Xa.A1 )
279 # Calculs et/ou stockages supplémentaires
280 # ---------------------------------------
281 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
282 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
283 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
284 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
285 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
286 self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(Hm(Xa)) )
287 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
288 self.StoredVariables["OMB"].store( numpy.ravel(d) )
290 logging.debug("%s Nombre d'évaluation(s) de l'opérateur d'observation direct/tangent/adjoint.: %i/%i/%i"%(self._name, HO["Direct"].nbcalls(0),HO["Tangent"].nbcalls(0),HO["Adjoint"].nbcalls(0)))
291 logging.debug("%s Nombre d'appels au cache d'opérateur d'observation direct/tangent/adjoint..: %i/%i/%i"%(self._name, HO["Direct"].nbcalls(3),HO["Tangent"].nbcalls(3),HO["Adjoint"].nbcalls(3)))
292 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
293 logging.debug("%s Terminé"%self._name)
297 # ==============================================================================
298 if __name__ == "__main__":
299 print '\n AUTODIAGNOSTIC \n'