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 if self._parameters["Minimizer"] == "LBFGSB":
210 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
213 fprime = GradientOfCostFunction,
216 maxfun = self._parameters["MaximumNumberOfSteps"]-1,
217 factr = self._parameters["CostDecrementTolerance"]*1.e14,
218 pgtol = self._parameters["ProjectedGradientTolerance"],
221 nfeval = Informations['funcalls']
222 rc = Informations['warnflag']
223 elif self._parameters["Minimizer"] == "TNC":
224 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
227 fprime = GradientOfCostFunction,
230 maxfun = self._parameters["MaximumNumberOfSteps"],
231 pgtol = self._parameters["ProjectedGradientTolerance"],
232 ftol = self._parameters["CostDecrementTolerance"],
235 elif self._parameters["Minimizer"] == "CG":
236 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
239 fprime = GradientOfCostFunction,
241 maxiter = self._parameters["MaximumNumberOfSteps"],
242 gtol = self._parameters["GradientNormTolerance"],
246 elif self._parameters["Minimizer"] == "NCG":
247 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
250 fprime = GradientOfCostFunction,
252 maxiter = self._parameters["MaximumNumberOfSteps"],
253 avextol = self._parameters["CostDecrementTolerance"],
257 elif self._parameters["Minimizer"] == "BFGS":
258 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
261 fprime = GradientOfCostFunction,
263 maxiter = self._parameters["MaximumNumberOfSteps"],
264 gtol = self._parameters["GradientNormTolerance"],
268 elif self._parameters["Minimizer"] == "LM":
269 Minimum, cov_x, infodict, mesg, rc = scipy.optimize.leastsq(
270 func = CostFunctionLM,
272 Dfun = GradientOfCostFunctionLM,
274 ftol = self._parameters["CostDecrementTolerance"],
275 maxfev = self._parameters["MaximumNumberOfSteps"],
276 gtol = self._parameters["GradientNormTolerance"],
279 nfeval = infodict['nfev']
281 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
283 StepMin = numpy.argmin( self.StoredVariables["CostFunctionJ"].valueserie() )
284 MinJ = self.StoredVariables["CostFunctionJ"].valueserie(step = StepMin)
286 # Correction pour pallier a un bug de TNC sur le retour du Minimum
287 # ----------------------------------------------------------------
288 if self._parameters["StoreInternalVariables"]:
289 Minimum = self.StoredVariables["CurrentState"].valueserie(step = StepMin)
291 # Obtention de l'analyse
292 # ----------------------
293 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
295 self.StoredVariables["Analysis"].store( Xa.A1 )
297 # Calculs et/ou stockages supplémentaires
298 # ---------------------------------------
299 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
300 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
301 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
302 self.StoredVariables["BMA"].store( numpy.ravel(Xb - Xa) )
303 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
304 self.StoredVariables["OMA"].store( numpy.ravel(Y - Hm(Xa)) )
305 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
306 self.StoredVariables["OMB"].store( numpy.ravel(d) )
308 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
309 logging.debug("%s Terminé"%self._name)
313 # ==============================================================================
314 if __name__ == "__main__":
315 print '\n AUTODIAGNOSTIC \n'