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, "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", "Innovation"]
78 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 # Paramètres de pilotage
88 # ----------------------
89 self.setParameters(Parameters)
91 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):
92 Bounds = self._parameters["Bounds"]
93 logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
97 # Correction pour pallier a un bug de TNC sur le retour du Minimum
98 if self._parameters.has_key("Minimizer") == "TNC":
99 self.setParameterValue("StoreInternalVariables",True)
101 # Opérateur d'observation
102 # -----------------------
103 Hm = HO["Direct"].appliedTo
104 Ha = HO["Adjoint"].appliedInXTo
106 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
107 # ----------------------------------------------------
108 if HO["AppliedToX"] is not None and HO["AppliedToX"].has_key("HXb"):
109 HXb = HO["AppliedToX"]["HXb"]
112 HXb = numpy.asmatrix(numpy.ravel( HXb )).T
114 # Calcul de l'innovation
115 # ----------------------
116 if Y.size != HXb.size:
117 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))
118 if max(Y.shape) != max(HXb.shape):
119 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))
122 # Précalcul des inversions de B et R
123 # ----------------------------------
125 if self._parameters["Minimizer"] == "LM":
126 RdemiI = R.choleskyI()
128 # Définition de la fonction-coût
129 # ------------------------------
131 _X = numpy.asmatrix(numpy.ravel( x )).T
133 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
135 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
136 J = float( Jb ) + float( Jo )
137 if self._parameters["StoreInternalVariables"]:
138 self.StoredVariables["CurrentState"].store( _X )
139 self.StoredVariables["CostFunctionJb"].store( Jb )
140 self.StoredVariables["CostFunctionJo"].store( Jo )
141 self.StoredVariables["CostFunctionJ" ].store( J )
144 def GradientOfCostFunction(x):
145 _X = numpy.asmatrix(numpy.ravel( x )).T
147 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
149 GradJo = - Ha( (_X, RI * (Y - _HX)) )
150 GradJ = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
153 def CostFunctionLM(x):
154 _X = numpy.asmatrix(numpy.ravel( x )).T
156 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
158 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
159 J = float( Jb ) + float( Jo )
160 if self._parameters["StoreInternalVariables"]:
161 self.StoredVariables["CurrentState"].store( _X )
162 self.StoredVariables["CostFunctionJb"].store( Jb )
163 self.StoredVariables["CostFunctionJo"].store( Jo )
164 self.StoredVariables["CostFunctionJ" ].store( J )
166 return numpy.ravel( RdemiI*(Y - _HX) )
168 def GradientOfCostFunctionLM(x):
169 _X = numpy.asmatrix(numpy.ravel( x )).T
171 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
173 GradJo = - Ha( (_X, RI * (Y - _HX)) )
174 GradJ = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
175 return - RdemiI*HO["Tangent"].asMatrix( _X )
177 # Point de démarrage de l'optimisation : Xini = Xb
178 # ------------------------------------
179 if type(Xb) is type(numpy.matrix([])):
180 Xini = Xb.A1.tolist()
184 # Minimisation de la fonctionnelle
185 # --------------------------------
186 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
188 if self._parameters["Minimizer"] == "LBFGSB":
189 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
192 fprime = GradientOfCostFunction,
195 maxfun = self._parameters["MaximumNumberOfSteps"]-1,
196 factr = self._parameters["CostDecrementTolerance"]*1.e14,
197 pgtol = self._parameters["ProjectedGradientTolerance"],
198 iprint = self.__iprint,
200 nfeval = Informations['funcalls']
201 rc = Informations['warnflag']
202 elif self._parameters["Minimizer"] == "TNC":
203 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
206 fprime = GradientOfCostFunction,
209 maxfun = self._parameters["MaximumNumberOfSteps"],
210 pgtol = self._parameters["ProjectedGradientTolerance"],
211 ftol = self._parameters["CostDecrementTolerance"],
212 messages = self.__message,
214 elif self._parameters["Minimizer"] == "CG":
215 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
218 fprime = GradientOfCostFunction,
220 maxiter = self._parameters["MaximumNumberOfSteps"],
221 gtol = self._parameters["GradientNormTolerance"],
225 elif self._parameters["Minimizer"] == "NCG":
226 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
229 fprime = GradientOfCostFunction,
231 maxiter = self._parameters["MaximumNumberOfSteps"],
232 avextol = self._parameters["CostDecrementTolerance"],
236 elif self._parameters["Minimizer"] == "BFGS":
237 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
240 fprime = GradientOfCostFunction,
242 maxiter = self._parameters["MaximumNumberOfSteps"],
243 gtol = self._parameters["GradientNormTolerance"],
247 elif self._parameters["Minimizer"] == "LM":
248 Minimum, cov_x, infodict, mesg, rc = scipy.optimize.leastsq(
249 func = CostFunctionLM,
251 Dfun = GradientOfCostFunctionLM,
253 ftol = self._parameters["CostDecrementTolerance"],
254 maxfev = self._parameters["MaximumNumberOfSteps"],
255 gtol = self._parameters["GradientNormTolerance"],
258 nfeval = infodict['nfev']
260 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
262 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
263 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
265 # Correction pour pallier a un bug de TNC sur le retour du Minimum
266 # ----------------------------------------------------------------
267 if self._parameters["StoreInternalVariables"]:
268 Minimum = self.StoredVariables["CurrentState"][IndexMin]
270 # Obtention de l'analyse
271 # ----------------------
272 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
274 self.StoredVariables["Analysis"].store( Xa.A1 )
276 # Calculs et/ou stockages supplémentaires
277 # ---------------------------------------
278 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
279 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
280 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
281 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
282 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
283 self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(Hm(Xa)) )
284 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
285 self.StoredVariables["OMB"].store( numpy.ravel(d) )
290 # ==============================================================================
291 if __name__ == "__main__":
292 print '\n AUTODIAGNOSTIC \n'