1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2017 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", "CostFunctionJ", "CostFunctionJb", "CostFunctionJo", "CurrentState", "CurrentOptimum", "IndexOfOptimum", "Innovation", "InnovationAtCurrentState", "CostFunctionJAtCurrentOptimum", "SimulatedObservationAtBackground", "SimulatedObservationAtCurrentState", "SimulatedObservationAtOptimum", "SimulatedObservationAtCurrentOptimum"]
77 self.defineRequiredParameter( # Pas de type
79 message = "Liste des valeurs de bornes",
82 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
83 self._pre_run(Parameters)
85 # Correction pour pallier a un bug de TNC sur le retour du Minimum
86 if "Minimizer" in self._parameters and self._parameters["Minimizer"] == "TNC":
87 self.setParameterValue("StoreInternalVariables",True)
91 Hm = HO["Direct"].appliedTo
92 Ha = HO["Adjoint"].appliedInXTo
94 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
95 # ----------------------------------------------------
96 if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
97 HXb = Hm( Xb, HO["AppliedInX"]["HXb"])
100 HXb = numpy.asmatrix(numpy.ravel( HXb )).T
101 if Y.size != HXb.size:
102 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))
103 if max(Y.shape) != max(HXb.shape):
104 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))
106 # Précalcul des inversions de B et R
107 # ----------------------------------
109 if self._parameters["Minimizer"] == "LM":
110 RdemiI = R.choleskyI()
112 # Définition de la fonction-coût
113 # ------------------------------
115 _X = numpy.asmatrix(numpy.ravel( x )).T
116 if self._parameters["StoreInternalVariables"] or \
117 "CurrentState" in self._parameters["StoreSupplementaryCalculations"] or \
118 "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
119 self.StoredVariables["CurrentState"].store( _X )
121 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
122 _Innovation = Y - _HX
123 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"] or \
124 "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
125 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
126 if "InnovationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
127 self.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
130 Jo = float( 0.5 * _Innovation.T * RI * _Innovation )
133 self.StoredVariables["CostFunctionJb"].store( Jb )
134 self.StoredVariables["CostFunctionJo"].store( Jo )
135 self.StoredVariables["CostFunctionJ" ].store( J )
136 if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
137 "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
138 "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
139 "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
140 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
141 if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"]:
142 self.StoredVariables["IndexOfOptimum"].store( IndexMin )
143 if "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
144 self.StoredVariables["CurrentOptimum"].store( self.StoredVariables["CurrentState"][IndexMin] )
145 if "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
146 self.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] )
147 if "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
148 self.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJb"][IndexMin] )
149 self.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJo"][IndexMin] )
150 self.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( self.StoredVariables["CostFunctionJ" ][IndexMin] )
153 def GradientOfCostFunction(x):
154 _X = numpy.asmatrix(numpy.ravel( x )).T
156 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
158 GradJo = - Ha( (_X, RI * (Y - _HX)) )
159 GradJ = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
162 def CostFunctionLM(x):
163 _X = numpy.asmatrix(numpy.ravel( x )).T
165 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
166 _Innovation = Y - _HX
168 Jo = float( 0.5 * _Innovation.T * RI * _Innovation )
170 if self._parameters["StoreInternalVariables"] or \
171 "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
172 self.StoredVariables["CurrentState"].store( _X )
173 self.StoredVariables["CostFunctionJb"].store( Jb )
174 self.StoredVariables["CostFunctionJo"].store( Jo )
175 self.StoredVariables["CostFunctionJ" ].store( J )
177 return numpy.ravel( RdemiI*_Innovation )
179 def GradientOfCostFunctionLM(x):
180 _X = numpy.asmatrix(numpy.ravel( x )).T
182 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
184 GradJo = - Ha( (_X, RI * (Y - _HX)) )
185 GradJ = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
186 return - RdemiI*HO["Tangent"].asMatrix( _X )
188 # Point de démarrage de l'optimisation : Xini = Xb
189 # ------------------------------------
190 Xini = numpy.ravel(Xb)
192 # Minimisation de la fonctionnelle
193 # --------------------------------
194 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
196 if self._parameters["Minimizer"] == "LBFGSB":
197 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
200 fprime = GradientOfCostFunction,
202 bounds = self._parameters["Bounds"],
203 maxfun = self._parameters["MaximumNumberOfSteps"]-1,
204 factr = self._parameters["CostDecrementTolerance"]*1.e14,
205 pgtol = self._parameters["ProjectedGradientTolerance"],
206 iprint = self._parameters["optiprint"],
208 nfeval = Informations['funcalls']
209 rc = Informations['warnflag']
210 elif self._parameters["Minimizer"] == "TNC":
211 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
214 fprime = GradientOfCostFunction,
216 bounds = self._parameters["Bounds"],
217 maxfun = self._parameters["MaximumNumberOfSteps"],
218 pgtol = self._parameters["ProjectedGradientTolerance"],
219 ftol = self._parameters["CostDecrementTolerance"],
220 messages = self._parameters["optmessages"],
222 elif self._parameters["Minimizer"] == "CG":
223 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
226 fprime = GradientOfCostFunction,
228 maxiter = self._parameters["MaximumNumberOfSteps"],
229 gtol = self._parameters["GradientNormTolerance"],
230 disp = self._parameters["optdisp"],
233 elif self._parameters["Minimizer"] == "NCG":
234 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
237 fprime = GradientOfCostFunction,
239 maxiter = self._parameters["MaximumNumberOfSteps"],
240 avextol = self._parameters["CostDecrementTolerance"],
241 disp = self._parameters["optdisp"],
244 elif self._parameters["Minimizer"] == "BFGS":
245 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
248 fprime = GradientOfCostFunction,
250 maxiter = self._parameters["MaximumNumberOfSteps"],
251 gtol = self._parameters["GradientNormTolerance"],
252 disp = self._parameters["optdisp"],
255 elif self._parameters["Minimizer"] == "LM":
256 Minimum, cov_x, infodict, mesg, rc = scipy.optimize.leastsq(
257 func = CostFunctionLM,
259 Dfun = GradientOfCostFunctionLM,
261 ftol = self._parameters["CostDecrementTolerance"],
262 maxfev = self._parameters["MaximumNumberOfSteps"],
263 gtol = self._parameters["GradientNormTolerance"],
266 nfeval = infodict['nfev']
268 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
270 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
271 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
273 # Correction pour pallier a un bug de TNC sur le retour du Minimum
274 # ----------------------------------------------------------------
275 if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
276 Minimum = self.StoredVariables["CurrentState"][IndexMin]
278 # Obtention de l'analyse
279 # ----------------------
280 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
282 self.StoredVariables["Analysis"].store( Xa.A1 )
284 if "OMA" in self._parameters["StoreSupplementaryCalculations"] or \
285 "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
286 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
287 HXa = self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
288 elif "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
289 HXa = self.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
294 # Calculs et/ou stockages supplémentaires
295 # ---------------------------------------
296 if "Innovation" in self._parameters["StoreSupplementaryCalculations"] or \
297 "OMB" in self._parameters["StoreSupplementaryCalculations"]:
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) - numpy.ravel(Xa) )
303 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
304 self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
305 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
306 self.StoredVariables["OMB"].store( numpy.ravel(d) )
307 if "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
308 self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
309 if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
310 self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
315 # ==============================================================================
316 if __name__ == "__main__":
317 print('\n AUTODIAGNOSTIC \n')