1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2013 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()
30 if logging.getLogger().level < logging.WARNING:
32 message = scipy.optimize.tnc.MSG_ALL
36 message = scipy.optimize.tnc.MSG_NONE
39 # ==============================================================================
40 class ElementaryAlgorithm(BasicObjects.Algorithm):
42 BasicObjects.Algorithm.__init__(self, "NONLINEARLEASTSQUARES")
43 self.defineRequiredParameter(
47 message = "Minimiseur utilisé",
48 listval = ["LBFGSB","TNC", "CG", "NCG", "BFGS", "LM"],
50 self.defineRequiredParameter(
51 name = "MaximumNumberOfSteps",
54 message = "Nombre maximal de pas d'optimisation",
57 self.defineRequiredParameter(
58 name = "CostDecrementTolerance",
61 message = "Diminution relative minimale du cout lors de l'arrêt",
63 self.defineRequiredParameter(
64 name = "ProjectedGradientTolerance",
67 message = "Maximum des composantes du gradient projeté lors de l'arrêt",
70 self.defineRequiredParameter(
71 name = "GradientNormTolerance",
74 message = "Maximum des composantes du gradient lors de l'arrêt",
76 self.defineRequiredParameter(
77 name = "StoreInternalVariables",
80 message = "Stockage des variables internes ou intermédiaires du calcul",
82 self.defineRequiredParameter(
83 name = "StoreSupplementaryCalculations",
86 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
87 listval = ["BMA", "OMA", "OMB", "Innovation"]
90 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
91 logging.debug("%s Lancement"%self._name)
92 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
94 # Paramètres de pilotage
95 # ----------------------
96 self.setParameters(Parameters)
98 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):
99 Bounds = self._parameters["Bounds"]
100 logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
104 # Correction pour pallier a un bug de TNC sur le retour du Minimum
105 if self._parameters.has_key("Minimizer") is "TNC":
106 self.setParameterValue("StoreInternalVariables",True)
108 # Opérateur d'observation
109 # -----------------------
110 Hm = HO["Direct"].appliedTo
111 Ha = HO["Adjoint"].appliedInXTo
113 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
114 # ----------------------------------------------------
115 if HO["AppliedToX"] is not None and HO["AppliedToX"].has_key("HXb"):
116 HXb = HO["AppliedToX"]["HXb"]
119 HXb = numpy.asmatrix(numpy.ravel( HXb )).T
121 # Calcul de l'innovation
122 # ----------------------
123 if Y.size != HXb.size:
124 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))
125 if max(Y.shape) != max(HXb.shape):
126 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))
129 # Précalcul des inversions de B et R
130 # ----------------------------------
133 # elif self._parameters["B_scalar"] is not None:
134 # BI = 1.0 / self._parameters["B_scalar"]
136 # raise ValueError("Background error covariance matrix has to be properly defined!")
140 if self._parameters["Minimizer"] == "LM":
141 RdemiI = numpy.linalg.cholesky(R).I
142 elif self._parameters["R_scalar"] is not None:
143 RI = 1.0 / self._parameters["R_scalar"]
144 if self._parameters["Minimizer"] == "LM":
146 RdemiI = 1.0 / math.sqrt( self._parameters["R_scalar"] )
148 raise ValueError("Observation error covariance matrix has to be properly defined!")
150 # Définition de la fonction-coût
151 # ------------------------------
153 _X = numpy.asmatrix(numpy.ravel( x )).T
155 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
157 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
158 J = float( Jb ) + float( Jo )
159 if self._parameters["StoreInternalVariables"]:
160 self.StoredVariables["CurrentState"].store( _X.A1 )
161 self.StoredVariables["CostFunctionJb"].store( Jb )
162 self.StoredVariables["CostFunctionJo"].store( Jo )
163 self.StoredVariables["CostFunctionJ" ].store( J )
166 def GradientOfCostFunction(x):
167 _X = numpy.asmatrix(numpy.ravel( x )).T
169 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
171 GradJo = - Ha( (_X, RI * (Y - _HX)) )
172 GradJ = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
175 def CostFunctionLM(x):
176 _X = numpy.asmatrix(numpy.ravel( x )).T
178 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
180 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
181 J = float( Jb ) + float( Jo )
182 if self._parameters["StoreInternalVariables"]:
183 self.StoredVariables["CurrentState"].store( _X.A1 )
184 self.StoredVariables["CostFunctionJb"].store( Jb )
185 self.StoredVariables["CostFunctionJo"].store( Jo )
186 self.StoredVariables["CostFunctionJ" ].store( J )
188 return numpy.ravel( RdemiI*(Y - _HX) )
190 def GradientOfCostFunctionLM(x):
191 _X = numpy.asmatrix(numpy.ravel( x )).T
193 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
195 GradJo = - Ha( (_X, RI * (Y - _HX)) )
196 GradJ = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
197 return - RdemiI*HO["Tangent"].asMatrix( _X )
199 # Point de démarrage de l'optimisation : Xini = Xb
200 # ------------------------------------
201 if type(Xb) is type(numpy.matrix([])):
202 Xini = Xb.A1.tolist()
206 # Minimisation de la fonctionnelle
207 # --------------------------------
208 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
210 if self._parameters["Minimizer"] == "LBFGSB":
211 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
214 fprime = GradientOfCostFunction,
217 maxfun = self._parameters["MaximumNumberOfSteps"]-1,
218 factr = self._parameters["CostDecrementTolerance"]*1.e14,
219 pgtol = self._parameters["ProjectedGradientTolerance"],
222 nfeval = Informations['funcalls']
223 rc = Informations['warnflag']
224 elif self._parameters["Minimizer"] == "TNC":
225 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
228 fprime = GradientOfCostFunction,
231 maxfun = self._parameters["MaximumNumberOfSteps"],
232 pgtol = self._parameters["ProjectedGradientTolerance"],
233 ftol = self._parameters["CostDecrementTolerance"],
236 elif self._parameters["Minimizer"] == "CG":
237 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
240 fprime = GradientOfCostFunction,
242 maxiter = self._parameters["MaximumNumberOfSteps"],
243 gtol = self._parameters["GradientNormTolerance"],
247 elif self._parameters["Minimizer"] == "NCG":
248 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
251 fprime = GradientOfCostFunction,
253 maxiter = self._parameters["MaximumNumberOfSteps"],
254 avextol = self._parameters["CostDecrementTolerance"],
258 elif self._parameters["Minimizer"] == "BFGS":
259 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
262 fprime = GradientOfCostFunction,
264 maxiter = self._parameters["MaximumNumberOfSteps"],
265 gtol = self._parameters["GradientNormTolerance"],
269 elif self._parameters["Minimizer"] == "LM":
270 Minimum, cov_x, infodict, mesg, rc = scipy.optimize.leastsq(
271 func = CostFunctionLM,
273 Dfun = GradientOfCostFunctionLM,
275 ftol = self._parameters["CostDecrementTolerance"],
276 maxfev = self._parameters["MaximumNumberOfSteps"],
277 gtol = self._parameters["GradientNormTolerance"],
280 nfeval = infodict['nfev']
282 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
284 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
285 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
287 # Correction pour pallier a un bug de TNC sur le retour du Minimum
288 # ----------------------------------------------------------------
289 if self._parameters["StoreInternalVariables"]:
290 Minimum = self.StoredVariables["CurrentState"][IndexMin]
292 # Obtention de l'analyse
293 # ----------------------
294 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
296 self.StoredVariables["Analysis"].store( Xa.A1 )
298 # Calculs et/ou stockages supplémentaires
299 # ---------------------------------------
300 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
301 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
302 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
303 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
304 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
305 self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(Hm(Xa)) )
306 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
307 self.StoredVariables["OMB"].store( numpy.ravel(d) )
309 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
310 logging.debug("%s Terminé"%self._name)
314 # ==============================================================================
315 if __name__ == "__main__":
316 print '\n AUTODIAGNOSTIC \n'