1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2024 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 from daCore.PlatformInfo import vfloat
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
30 BasicObjects.Algorithm.__init__(self, "TABUSEARCH")
31 self.defineRequiredParameter(
32 name = "MaximumNumberOfIterations",
35 message = "Nombre maximal de pas d'optimisation",
37 oldname = "MaximumNumberOfSteps",
39 self.defineRequiredParameter(
41 typecast = numpy.random.seed,
42 message = "Graine fixée pour le générateur aléatoire",
44 self.defineRequiredParameter(
45 name = "LengthOfTabuList",
48 message = "Longueur de la liste tabou",
51 self.defineRequiredParameter(
52 name = "NumberOfElementaryPerturbations",
55 message = "Nombre de perturbations élémentaires pour choisir une perturbation d'état",
58 self.defineRequiredParameter(
59 name = "NoiseDistribution",
62 message = "Distribution pour générer les perturbations d'état",
63 listval = ["Gaussian", "Uniform"],
65 self.defineRequiredParameter(
66 name = "QualityCriterion",
67 default = "AugmentedWeightedLeastSquares",
69 message = "Critère de qualité utilisé",
71 "AugmentedWeightedLeastSquares", "AWLS", "DA",
72 "WeightedLeastSquares", "WLS",
73 "LeastSquares", "LS", "L2",
74 "AbsoluteValue", "L1",
75 "MaximumError", "ME", "Linf",
78 self.defineRequiredParameter(
79 name = "NoiseHalfRange",
81 typecast = numpy.ravel,
82 message = "Demi-amplitude des perturbations uniformes centrées d'état pour chaque composante de l'état",
84 self.defineRequiredParameter(
85 name = "StandardDeviation",
87 typecast = numpy.ravel,
88 message = "Ecart-type des perturbations gaussiennes d'état pour chaque composante de l'état",
90 self.defineRequiredParameter(
91 name = "NoiseAddingProbability",
94 message = "Probabilité de perturbation d'une composante de l'état",
98 self.defineRequiredParameter(
99 name = "StoreInternalVariables",
102 message = "Stockage des variables internes ou intermédiaires du calcul",
104 self.defineRequiredParameter(
105 name = "StoreSupplementaryCalculations",
108 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
115 "CurrentIterationNumber",
120 "SimulatedObservationAtBackground",
121 "SimulatedObservationAtCurrentState",
122 "SimulatedObservationAtOptimum",
125 self.defineRequiredParameter( # Pas de type
127 message = "Liste des valeurs de bornes",
129 self.requireInputArguments(
130 mandatory= ("Xb", "Y", "HO", "R", "B"),
139 "NonLocalOptimization",
141 "ConvergenceOnNumbers",
145 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
146 self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
148 if self._parameters["NoiseDistribution"] == "Uniform":
149 nrange = self._parameters["NoiseHalfRange"] # Vecteur
150 if nrange.size != Xb.size:
151 raise ValueError("Noise generation by Uniform distribution requires range for all variable increments. The actual noise half range vector is:\n%s"%nrange) # noqa: E501
152 elif self._parameters["NoiseDistribution"] == "Gaussian":
153 sigma = numpy.ravel(self._parameters["StandardDeviation"]) # Vecteur
154 if sigma.size != Xb.size:
155 raise ValueError("Noise generation by Gaussian distribution requires standard deviation for all variable increments. The actual standard deviation vector is:\n%s"%sigma) # noqa: E501
157 Hm = HO["Direct"].appliedTo
162 def Tweak( x, NoiseDistribution, NoiseAddingProbability ):
163 _X = numpy.array( x, dtype=float, copy=True ).ravel().reshape((-1, 1))
164 if NoiseDistribution == "Uniform":
165 for i in range(_X.size):
166 if NoiseAddingProbability >= numpy.random.uniform():
167 _increment = numpy.random.uniform(low=-nrange[i], high=nrange[i])
168 # On ne traite pas encore le dépassement des bornes ici
170 elif NoiseDistribution == "Gaussian":
171 for i in range(_X.size):
172 if NoiseAddingProbability >= numpy.random.uniform():
173 _increment = numpy.random.normal(loc=0., scale=sigma[i])
174 # On ne traite pas encore le dépassement des bornes ici
179 def StateInList( x, _TL ):
180 _X = numpy.ravel( x )
183 if numpy.all(numpy.abs( _X - numpy.ravel(state) ) <= 1e-16 * numpy.abs(_X)):
185 # if _xInList: import sys ; sys.exit()
188 def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
189 _X = numpy.ravel( x ).reshape((-1, 1))
190 _HX = numpy.ravel( Hm( _X ) ).reshape((-1, 1))
191 _Innovation = Y - _HX
193 if QualityMeasure in ["AugmentedWeightedLeastSquares", "AWLS", "DA"]:
194 if BI is None or RI is None:
195 raise ValueError("Background and Observation error covariance matrices has to be properly defined!")
196 Jb = vfloat(0.5 * (_X - Xb).T @ (BI @ (_X - Xb)))
197 Jo = vfloat(0.5 * _Innovation.T @ (RI @ _Innovation))
198 elif QualityMeasure in ["WeightedLeastSquares", "WLS"]:
200 raise ValueError("Observation error covariance matrix has to be properly defined!")
202 Jo = vfloat(0.5 * _Innovation.T @ (RI @ _Innovation))
203 elif QualityMeasure in ["LeastSquares", "LS", "L2"]:
205 Jo = vfloat(0.5 * _Innovation.T @ _Innovation)
206 elif QualityMeasure in ["AbsoluteValue", "L1"]:
208 Jo = vfloat(numpy.sum( numpy.abs(_Innovation) ))
209 elif QualityMeasure in ["MaximumError", "ME", "Linf"]:
211 Jo = vfloat(numpy.max( numpy.abs(_Innovation) ))
217 # Minimisation de la fonctionnelle
218 # --------------------------------
221 _qualityS = CostFunction( _S, self._parameters["QualityCriterion"] )
222 _Best, _qualityBest = _S, _qualityS
224 _TabuList.append( _S )
225 while _n < self._parameters["MaximumNumberOfIterations"]:
227 if len(_TabuList) > self._parameters["LengthOfTabuList"]:
229 _R = Tweak( _S, self._parameters["NoiseDistribution"], self._parameters["NoiseAddingProbability"] )
230 _qualityR = CostFunction( _R, self._parameters["QualityCriterion"] )
231 for nbt in range(self._parameters["NumberOfElementaryPerturbations"] - 1):
232 _W = Tweak( _S, self._parameters["NoiseDistribution"], self._parameters["NoiseAddingProbability"] )
233 _qualityW = CostFunction( _W, self._parameters["QualityCriterion"] )
234 if (not StateInList(_W, _TabuList)) and ( (_qualityW < _qualityR) or StateInList(_R, _TabuList) ):
235 _R, _qualityR = _W, _qualityW
236 if (not StateInList( _R, _TabuList )) and (_qualityR < _qualityS):
237 _S, _qualityS = _R, _qualityR
238 _TabuList.append( _S )
239 if _qualityS < _qualityBest:
240 _Best, _qualityBest = _S, _qualityS
242 self.StoredVariables["CurrentIterationNumber"].store( len(self.StoredVariables["CostFunctionJ"]) )
243 if self._parameters["StoreInternalVariables"] or self._toStore("CurrentState"):
244 self.StoredVariables["CurrentState"].store( _Best )
245 if self._toStore("SimulatedObservationAtCurrentState"):
247 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HmX )
248 self.StoredVariables["CostFunctionJb"].store( 0. )
249 self.StoredVariables["CostFunctionJo"].store( 0. )
250 self.StoredVariables["CostFunctionJ" ].store( _qualityBest )
252 # Obtention de l'analyse
253 # ----------------------
256 self.StoredVariables["Analysis"].store( Xa )
258 # Calculs et/ou stockages supplémentaires
259 # ---------------------------------------
260 if self._toStore("OMA") or \
261 self._toStore("SimulatedObservationAtOptimum"):
262 HXa = Hm(Xa).reshape((-1, 1))
263 if self._toStore("Innovation") or \
264 self._toStore("OMB") or \
265 self._toStore("SimulatedObservationAtBackground"):
266 HXb = Hm(Xb).reshape((-1, 1))
268 if self._toStore("Innovation"):
269 self.StoredVariables["Innovation"].store( Innovation )
270 if self._toStore("OMB"):
271 self.StoredVariables["OMB"].store( Innovation )
272 if self._toStore("BMA"):
273 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
274 if self._toStore("OMA"):
275 self.StoredVariables["OMA"].store( Y - HXa )
276 if self._toStore("SimulatedObservationAtBackground"):
277 self.StoredVariables["SimulatedObservationAtBackground"].store( HXb )
278 if self._toStore("SimulatedObservationAtOptimum"):
279 self.StoredVariables["SimulatedObservationAtOptimum"].store( HXa )
281 self._post_run(HO, EM)
284 # ==============================================================================
285 if __name__ == "__main__":
286 print("\n AUTODIAGNOSTIC\n")