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",
86 "InnovationAtCurrentState",
87 "CostFunctionJAtCurrentOptimum",
88 "CostFunctionJbAtCurrentOptimum",
89 "CostFunctionJoAtCurrentOptimum",
90 "SimulatedObservationAtBackground",
91 "SimulatedObservationAtCurrentState",
92 "SimulatedObservationAtOptimum",
93 "SimulatedObservationAtCurrentOptimum",
96 self.defineRequiredParameter( # Pas de type
98 message = "Liste des valeurs de bornes",
100 self.requireInputArguments(
101 mandatory= ("Xb", "Y", "HO", "R"),
104 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
105 self._pre_run(Parameters, Xb, Y, R, B, Q)
107 # Correction pour pallier a un bug de TNC sur le retour du Minimum
108 if "Minimizer" in self._parameters and self._parameters["Minimizer"] == "TNC":
109 self.setParameterValue("StoreInternalVariables",True)
113 Hm = HO["Direct"].appliedTo
114 Ha = HO["Adjoint"].appliedInXTo
116 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
117 # ----------------------------------------------------
118 if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
119 HXb = Hm( Xb, HO["AppliedInX"]["HXb"])
122 HXb = numpy.asmatrix(numpy.ravel( HXb )).T
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))
128 # Précalcul des inversions de B et R
129 # ----------------------------------
131 if self._parameters["Minimizer"] == "LM":
132 RdemiI = R.choleskyI()
134 # Définition de la fonction-coût
135 # ------------------------------
137 _X = numpy.asmatrix(numpy.ravel( x )).T
138 if self._parameters["StoreInternalVariables"] or \
139 "CurrentState" in self._parameters["StoreSupplementaryCalculations"] or \
140 "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
141 self.StoredVariables["CurrentState"].store( _X )
143 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
144 _Innovation = Y - _HX
145 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"] or \
146 "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
147 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
148 if "InnovationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
149 self.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
152 Jo = float( 0.5 * _Innovation.T * RI * _Innovation )
155 self.StoredVariables["CostFunctionJb"].store( Jb )
156 self.StoredVariables["CostFunctionJo"].store( Jo )
157 self.StoredVariables["CostFunctionJ" ].store( J )
158 if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
159 "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
160 "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
161 "CostFunctionJbAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
162 "CostFunctionJoAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
163 "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
164 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
165 if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"]:
166 self.StoredVariables["IndexOfOptimum"].store( IndexMin )
167 if "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
168 self.StoredVariables["CurrentOptimum"].store( self.StoredVariables["CurrentState"][IndexMin] )
169 if "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
170 self.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] )
171 if "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
172 self.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( self.StoredVariables["CostFunctionJ" ][IndexMin] )
173 if "CostFunctionJbAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
174 self.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJb"][IndexMin] )
175 if "CostFunctionJoAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
176 self.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJo"][IndexMin] )
179 def GradientOfCostFunction(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
188 def CostFunctionLM(x):
189 _X = numpy.asmatrix(numpy.ravel( x )).T
191 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
192 _Innovation = Y - _HX
194 Jo = float( 0.5 * _Innovation.T * RI * _Innovation )
196 if self._parameters["StoreInternalVariables"] or \
197 "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
198 self.StoredVariables["CurrentState"].store( _X )
199 self.StoredVariables["CostFunctionJb"].store( Jb )
200 self.StoredVariables["CostFunctionJo"].store( Jo )
201 self.StoredVariables["CostFunctionJ" ].store( J )
203 return numpy.ravel( RdemiI*_Innovation )
205 def GradientOfCostFunctionLM(x):
206 _X = numpy.asmatrix(numpy.ravel( x )).T
208 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
210 GradJo = - Ha( (_X, RI * (Y - _HX)) )
211 GradJ = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
212 return - RdemiI*HO["Tangent"].asMatrix( _X )
214 # Point de démarrage de l'optimisation : Xini = Xb
215 # ------------------------------------
216 Xini = numpy.ravel(Xb)
218 # Minimisation de la fonctionnelle
219 # --------------------------------
220 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
222 if self._parameters["Minimizer"] == "LBFGSB":
223 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
226 fprime = GradientOfCostFunction,
228 bounds = self._parameters["Bounds"],
229 maxfun = self._parameters["MaximumNumberOfSteps"]-1,
230 factr = self._parameters["CostDecrementTolerance"]*1.e14,
231 pgtol = self._parameters["ProjectedGradientTolerance"],
232 iprint = self._parameters["optiprint"],
234 nfeval = Informations['funcalls']
235 rc = Informations['warnflag']
236 elif self._parameters["Minimizer"] == "TNC":
237 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
240 fprime = GradientOfCostFunction,
242 bounds = self._parameters["Bounds"],
243 maxfun = self._parameters["MaximumNumberOfSteps"],
244 pgtol = self._parameters["ProjectedGradientTolerance"],
245 ftol = self._parameters["CostDecrementTolerance"],
246 messages = self._parameters["optmessages"],
248 elif self._parameters["Minimizer"] == "CG":
249 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
252 fprime = GradientOfCostFunction,
254 maxiter = self._parameters["MaximumNumberOfSteps"],
255 gtol = self._parameters["GradientNormTolerance"],
256 disp = self._parameters["optdisp"],
259 elif self._parameters["Minimizer"] == "NCG":
260 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
263 fprime = GradientOfCostFunction,
265 maxiter = self._parameters["MaximumNumberOfSteps"],
266 avextol = self._parameters["CostDecrementTolerance"],
267 disp = self._parameters["optdisp"],
270 elif self._parameters["Minimizer"] == "BFGS":
271 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
274 fprime = GradientOfCostFunction,
276 maxiter = self._parameters["MaximumNumberOfSteps"],
277 gtol = self._parameters["GradientNormTolerance"],
278 disp = self._parameters["optdisp"],
281 elif self._parameters["Minimizer"] == "LM":
282 Minimum, cov_x, infodict, mesg, rc = scipy.optimize.leastsq(
283 func = CostFunctionLM,
285 Dfun = GradientOfCostFunctionLM,
287 ftol = self._parameters["CostDecrementTolerance"],
288 maxfev = self._parameters["MaximumNumberOfSteps"],
289 gtol = self._parameters["GradientNormTolerance"],
292 nfeval = infodict['nfev']
294 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
296 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
297 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
299 # Correction pour pallier a un bug de TNC sur le retour du Minimum
300 # ----------------------------------------------------------------
301 if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
302 Minimum = self.StoredVariables["CurrentState"][IndexMin]
304 # Obtention de l'analyse
305 # ----------------------
306 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
308 self.StoredVariables["Analysis"].store( Xa.A1 )
310 if "OMA" in self._parameters["StoreSupplementaryCalculations"] or \
311 "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
312 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
313 HXa = self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
314 elif "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
315 HXa = self.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
320 # Calculs et/ou stockages supplémentaires
321 # ---------------------------------------
322 if "Innovation" in self._parameters["StoreSupplementaryCalculations"] or \
323 "OMB" in self._parameters["StoreSupplementaryCalculations"]:
325 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
326 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
327 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
328 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
329 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
330 self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
331 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
332 self.StoredVariables["OMB"].store( numpy.ravel(d) )
333 if "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
334 self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
335 if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
336 self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
341 # ==============================================================================
342 if __name__ == "__main__":
343 print('\n AUTODIAGNOSTIC \n')