1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2012 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, H=None, M=None, R=None, B=None, Q=None, Parameters=None):
92 logging.debug("%s Lancement"%self._name)
93 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
95 # Paramètres de pilotage
96 # ----------------------
97 self.setParameters(Parameters)
99 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):
100 Bounds = self._parameters["Bounds"]
101 logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
105 # Correction pour pallier a un bug de TNC sur le retour du Minimum
106 if self._parameters.has_key("Minimizer") is "TNC":
107 self.setParameterValue("StoreInternalVariables",True)
109 # Opérateur d'observation
110 # -----------------------
111 Hm = H["Direct"].appliedTo
112 Ha = H["Adjoint"].appliedInXTo
114 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
115 # ----------------------------------------------------
116 if H["AppliedToX"] is not None and H["AppliedToX"].has_key("HXb"):
117 HXb = H["AppliedToX"]["HXb"]
120 HXb = numpy.asmatrix(numpy.ravel( HXb )).T
122 # Calcul de l'innovation
123 # ----------------------
124 if Y.size != HXb.size:
125 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))
126 if max(Y.shape) != max(HXb.shape):
127 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))
130 # Précalcul des inversions de B et R
131 # ----------------------------------
134 # elif self._parameters["B_scalar"] is not None:
135 # BI = 1.0 / self._parameters["B_scalar"]
137 # raise ValueError("Background error covariance matrix has to be properly defined!")
141 if self._parameters["Minimizer"] == "LM":
142 RdemiI = numpy.linalg.cholesky(R).I
143 elif self._parameters["R_scalar"] is not None:
144 RI = 1.0 / self._parameters["R_scalar"]
145 if self._parameters["Minimizer"] == "LM":
147 RdemiI = 1.0 / math.sqrt( self._parameters["R_scalar"] )
149 raise ValueError("Observation error covariance matrix has to be properly defined!")
151 # Définition de la fonction-coût
152 # ------------------------------
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.A1 )
162 self.StoredVariables["CostFunctionJb"].store( Jb )
163 self.StoredVariables["CostFunctionJo"].store( Jo )
164 self.StoredVariables["CostFunctionJ" ].store( J )
167 def GradientOfCostFunction(x):
168 _X = numpy.asmatrix(numpy.ravel( x )).T
170 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
172 GradJo = - Ha( (_X, RI * (Y - _HX)) )
173 GradJ = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
176 def CostFunctionLM(x):
177 _X = numpy.asmatrix(numpy.ravel( x )).T
179 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
181 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
182 J = float( Jb ) + float( Jo )
183 if self._parameters["StoreInternalVariables"]:
184 self.StoredVariables["CurrentState"].store( _X.A1 )
185 self.StoredVariables["CostFunctionJb"].store( Jb )
186 self.StoredVariables["CostFunctionJo"].store( Jo )
187 self.StoredVariables["CostFunctionJ" ].store( J )
189 return numpy.ravel( RdemiI*(Y - _HX) )
191 def GradientOfCostFunctionLM(x):
192 _X = numpy.asmatrix(numpy.ravel( x )).T
194 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
196 GradJo = - Ha( (_X, RI * (Y - _HX)) )
197 GradJ = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
198 return - RdemiI*H["Tangent"].asMatrix( _X )
200 # Point de démarrage de l'optimisation : Xini = Xb
201 # ------------------------------------
202 if type(Xb) is type(numpy.matrix([])):
203 Xini = Xb.A1.tolist()
207 # Minimisation de la fonctionnelle
208 # --------------------------------
209 n0 = self.StoredVariables["CostFunctionJ"].stepnumber()
211 if self._parameters["Minimizer"] == "LBFGSB":
212 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
215 fprime = GradientOfCostFunction,
218 maxfun = self._parameters["MaximumNumberOfSteps"]-1,
219 factr = self._parameters["CostDecrementTolerance"]*1.e14,
220 pgtol = self._parameters["ProjectedGradientTolerance"],
223 nfeval = Informations['funcalls']
224 rc = Informations['warnflag']
225 elif self._parameters["Minimizer"] == "TNC":
226 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
229 fprime = GradientOfCostFunction,
232 maxfun = self._parameters["MaximumNumberOfSteps"],
233 pgtol = self._parameters["ProjectedGradientTolerance"],
234 ftol = self._parameters["CostDecrementTolerance"],
237 elif self._parameters["Minimizer"] == "CG":
238 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
241 fprime = GradientOfCostFunction,
243 maxiter = self._parameters["MaximumNumberOfSteps"],
244 gtol = self._parameters["GradientNormTolerance"],
248 elif self._parameters["Minimizer"] == "NCG":
249 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
252 fprime = GradientOfCostFunction,
254 maxiter = self._parameters["MaximumNumberOfSteps"],
255 avextol = self._parameters["CostDecrementTolerance"],
259 elif self._parameters["Minimizer"] == "BFGS":
260 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
263 fprime = GradientOfCostFunction,
265 maxiter = self._parameters["MaximumNumberOfSteps"],
266 gtol = self._parameters["GradientNormTolerance"],
270 elif self._parameters["Minimizer"] == "LM":
271 Minimum, cov_x, infodict, mesg, rc = scipy.optimize.leastsq(
272 func = CostFunctionLM,
274 Dfun = GradientOfCostFunctionLM,
276 ftol = self._parameters["CostDecrementTolerance"],
277 maxfev = self._parameters["MaximumNumberOfSteps"],
278 gtol = self._parameters["GradientNormTolerance"],
281 nfeval = infodict['nfev']
283 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
285 StepMin = numpy.argmin( self.StoredVariables["CostFunctionJ"].valueserie()[n0:] )
286 MinJ = self.StoredVariables["CostFunctionJ"].valueserie(step = StepMin)
288 # Correction pour pallier a un bug de TNC sur le retour du Minimum
289 # ----------------------------------------------------------------
290 if self._parameters["StoreInternalVariables"]:
291 Minimum = self.StoredVariables["CurrentState"].valueserie(step = StepMin)
293 # Obtention de l'analyse
294 # ----------------------
295 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
297 self.StoredVariables["Analysis"].store( Xa.A1 )
299 # Calculs et/ou stockages supplémentaires
300 # ---------------------------------------
301 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
302 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
303 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
304 self.StoredVariables["BMA"].store( numpy.ravel(Xb - Xa) )
305 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
306 self.StoredVariables["OMA"].store( numpy.ravel(Y - Hm(Xa)) )
307 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
308 self.StoredVariables["OMB"].store( numpy.ravel(d) )
310 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
311 logging.debug("%s Terminé"%self._name)
315 # ==============================================================================
316 if __name__ == "__main__":
317 print '\n AUTODIAGNOSTIC \n'