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",
81 self.requireInputArguments(
82 mandatory= ("Xb", "Y", "HO", "R"),
85 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
86 self._pre_run(Parameters, Xb, Y, R, B, Q)
88 # Correction pour pallier a un bug de TNC sur le retour du Minimum
89 if "Minimizer" in self._parameters and self._parameters["Minimizer"] == "TNC":
90 self.setParameterValue("StoreInternalVariables",True)
94 Hm = HO["Direct"].appliedTo
95 Ha = HO["Adjoint"].appliedInXTo
97 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
98 # ----------------------------------------------------
99 if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
100 HXb = Hm( Xb, HO["AppliedInX"]["HXb"])
103 HXb = numpy.asmatrix(numpy.ravel( HXb )).T
104 if Y.size != HXb.size:
105 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))
106 if max(Y.shape) != max(HXb.shape):
107 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))
109 # Précalcul des inversions de B et R
110 # ----------------------------------
112 if self._parameters["Minimizer"] == "LM":
113 RdemiI = R.choleskyI()
115 # Définition de la fonction-coût
116 # ------------------------------
118 _X = numpy.asmatrix(numpy.ravel( x )).T
119 if self._parameters["StoreInternalVariables"] or \
120 "CurrentState" in self._parameters["StoreSupplementaryCalculations"] or \
121 "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
122 self.StoredVariables["CurrentState"].store( _X )
124 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
125 _Innovation = Y - _HX
126 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"] or \
127 "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
128 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
129 if "InnovationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
130 self.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
133 Jo = float( 0.5 * _Innovation.T * RI * _Innovation )
136 self.StoredVariables["CostFunctionJb"].store( Jb )
137 self.StoredVariables["CostFunctionJo"].store( Jo )
138 self.StoredVariables["CostFunctionJ" ].store( J )
139 if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
140 "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
141 "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
142 "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
143 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
144 if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"]:
145 self.StoredVariables["IndexOfOptimum"].store( IndexMin )
146 if "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
147 self.StoredVariables["CurrentOptimum"].store( self.StoredVariables["CurrentState"][IndexMin] )
148 if "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
149 self.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] )
150 if "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
151 self.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJb"][IndexMin] )
152 self.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJo"][IndexMin] )
153 self.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( self.StoredVariables["CostFunctionJ" ][IndexMin] )
156 def GradientOfCostFunction(x):
157 _X = numpy.asmatrix(numpy.ravel( x )).T
159 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
161 GradJo = - Ha( (_X, RI * (Y - _HX)) )
162 GradJ = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
165 def CostFunctionLM(x):
166 _X = numpy.asmatrix(numpy.ravel( x )).T
168 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
169 _Innovation = Y - _HX
171 Jo = float( 0.5 * _Innovation.T * RI * _Innovation )
173 if self._parameters["StoreInternalVariables"] or \
174 "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
175 self.StoredVariables["CurrentState"].store( _X )
176 self.StoredVariables["CostFunctionJb"].store( Jb )
177 self.StoredVariables["CostFunctionJo"].store( Jo )
178 self.StoredVariables["CostFunctionJ" ].store( J )
180 return numpy.ravel( RdemiI*_Innovation )
182 def GradientOfCostFunctionLM(x):
183 _X = numpy.asmatrix(numpy.ravel( x )).T
185 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
187 GradJo = - Ha( (_X, RI * (Y - _HX)) )
188 GradJ = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
189 return - RdemiI*HO["Tangent"].asMatrix( _X )
191 # Point de démarrage de l'optimisation : Xini = Xb
192 # ------------------------------------
193 Xini = numpy.ravel(Xb)
195 # Minimisation de la fonctionnelle
196 # --------------------------------
197 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
199 if self._parameters["Minimizer"] == "LBFGSB":
200 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
203 fprime = GradientOfCostFunction,
205 bounds = self._parameters["Bounds"],
206 maxfun = self._parameters["MaximumNumberOfSteps"]-1,
207 factr = self._parameters["CostDecrementTolerance"]*1.e14,
208 pgtol = self._parameters["ProjectedGradientTolerance"],
209 iprint = self._parameters["optiprint"],
211 nfeval = Informations['funcalls']
212 rc = Informations['warnflag']
213 elif self._parameters["Minimizer"] == "TNC":
214 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
217 fprime = GradientOfCostFunction,
219 bounds = self._parameters["Bounds"],
220 maxfun = self._parameters["MaximumNumberOfSteps"],
221 pgtol = self._parameters["ProjectedGradientTolerance"],
222 ftol = self._parameters["CostDecrementTolerance"],
223 messages = self._parameters["optmessages"],
225 elif self._parameters["Minimizer"] == "CG":
226 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
229 fprime = GradientOfCostFunction,
231 maxiter = self._parameters["MaximumNumberOfSteps"],
232 gtol = self._parameters["GradientNormTolerance"],
233 disp = self._parameters["optdisp"],
236 elif self._parameters["Minimizer"] == "NCG":
237 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
240 fprime = GradientOfCostFunction,
242 maxiter = self._parameters["MaximumNumberOfSteps"],
243 avextol = self._parameters["CostDecrementTolerance"],
244 disp = self._parameters["optdisp"],
247 elif self._parameters["Minimizer"] == "BFGS":
248 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
251 fprime = GradientOfCostFunction,
253 maxiter = self._parameters["MaximumNumberOfSteps"],
254 gtol = self._parameters["GradientNormTolerance"],
255 disp = self._parameters["optdisp"],
258 elif self._parameters["Minimizer"] == "LM":
259 Minimum, cov_x, infodict, mesg, rc = scipy.optimize.leastsq(
260 func = CostFunctionLM,
262 Dfun = GradientOfCostFunctionLM,
264 ftol = self._parameters["CostDecrementTolerance"],
265 maxfev = self._parameters["MaximumNumberOfSteps"],
266 gtol = self._parameters["GradientNormTolerance"],
269 nfeval = infodict['nfev']
271 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
273 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
274 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
276 # Correction pour pallier a un bug de TNC sur le retour du Minimum
277 # ----------------------------------------------------------------
278 if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
279 Minimum = self.StoredVariables["CurrentState"][IndexMin]
281 # Obtention de l'analyse
282 # ----------------------
283 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
285 self.StoredVariables["Analysis"].store( Xa.A1 )
287 if "OMA" in self._parameters["StoreSupplementaryCalculations"] or \
288 "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
289 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
290 HXa = self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
291 elif "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
292 HXa = self.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
297 # Calculs et/ou stockages supplémentaires
298 # ---------------------------------------
299 if "Innovation" in self._parameters["StoreSupplementaryCalculations"] or \
300 "OMB" in self._parameters["StoreSupplementaryCalculations"]:
302 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
303 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
304 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
305 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
306 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
307 self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
308 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
309 self.StoredVariables["OMB"].store( numpy.ravel(d) )
310 if "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
311 self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
312 if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
313 self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
318 # ==============================================================================
319 if __name__ == "__main__":
320 print('\n AUTODIAGNOSTIC \n')