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",
144 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
145 self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
147 if self._parameters["NoiseDistribution"] == "Uniform":
148 nrange = self._parameters["NoiseHalfRange"] # Vecteur
149 if nrange.size != Xb.size:
150 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
151 elif self._parameters["NoiseDistribution"] == "Gaussian":
152 sigma = numpy.ravel(self._parameters["StandardDeviation"]) # Vecteur
153 if sigma.size != Xb.size:
154 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
156 Hm = HO["Direct"].appliedTo
161 def Tweak( x, NoiseDistribution, NoiseAddingProbability ):
162 _X = numpy.array( x, dtype=float, copy=True ).ravel().reshape((-1, 1))
163 if NoiseDistribution == "Uniform":
164 for i in range(_X.size):
165 if NoiseAddingProbability >= numpy.random.uniform():
166 _increment = numpy.random.uniform(low=-nrange[i], high=nrange[i])
167 # On ne traite pas encore le dépassement des bornes ici
169 elif NoiseDistribution == "Gaussian":
170 for i in range(_X.size):
171 if NoiseAddingProbability >= numpy.random.uniform():
172 _increment = numpy.random.normal(loc=0., scale=sigma[i])
173 # On ne traite pas encore le dépassement des bornes ici
178 def StateInList( x, _TL ):
179 _X = numpy.ravel( x )
182 if numpy.all(numpy.abs( _X - numpy.ravel(state) ) <= 1e-16 * numpy.abs(_X)):
184 # if _xInList: import sys ; sys.exit()
187 def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
188 _X = numpy.ravel( x ).reshape((-1, 1))
189 _HX = numpy.ravel( Hm( _X ) ).reshape((-1, 1))
190 _Innovation = Y - _HX
192 if QualityMeasure in ["AugmentedWeightedLeastSquares", "AWLS", "DA"]:
193 if BI is None or RI is None:
194 raise ValueError("Background and Observation error covariance matrices has to be properly defined!")
195 Jb = vfloat(0.5 * (_X - Xb).T @ (BI @ (_X - Xb)))
196 Jo = vfloat(0.5 * _Innovation.T @ (RI @ _Innovation))
197 elif QualityMeasure in ["WeightedLeastSquares", "WLS"]:
199 raise ValueError("Observation error covariance matrix has to be properly defined!")
201 Jo = vfloat(0.5 * _Innovation.T @ (RI @ _Innovation))
202 elif QualityMeasure in ["LeastSquares", "LS", "L2"]:
204 Jo = vfloat(0.5 * _Innovation.T @ _Innovation)
205 elif QualityMeasure in ["AbsoluteValue", "L1"]:
207 Jo = vfloat(numpy.sum( numpy.abs(_Innovation) ))
208 elif QualityMeasure in ["MaximumError", "ME", "Linf"]:
210 Jo = vfloat(numpy.max( numpy.abs(_Innovation) ))
216 # Minimisation de la fonctionnelle
217 # --------------------------------
220 _qualityS = CostFunction( _S, self._parameters["QualityCriterion"] )
221 _Best, _qualityBest = _S, _qualityS
223 _TabuList.append( _S )
224 while _n < self._parameters["MaximumNumberOfIterations"]:
226 if len(_TabuList) > self._parameters["LengthOfTabuList"]:
228 _R = Tweak( _S, self._parameters["NoiseDistribution"], self._parameters["NoiseAddingProbability"] )
229 _qualityR = CostFunction( _R, self._parameters["QualityCriterion"] )
230 for nbt in range(self._parameters["NumberOfElementaryPerturbations"] - 1):
231 _W = Tweak( _S, self._parameters["NoiseDistribution"], self._parameters["NoiseAddingProbability"] )
232 _qualityW = CostFunction( _W, self._parameters["QualityCriterion"] )
233 if (not StateInList(_W, _TabuList)) and ( (_qualityW < _qualityR) or StateInList(_R, _TabuList) ):
234 _R, _qualityR = _W, _qualityW
235 if (not StateInList( _R, _TabuList )) and (_qualityR < _qualityS):
236 _S, _qualityS = _R, _qualityR
237 _TabuList.append( _S )
238 if _qualityS < _qualityBest:
239 _Best, _qualityBest = _S, _qualityS
241 self.StoredVariables["CurrentIterationNumber"].store( len(self.StoredVariables["CostFunctionJ"]) )
242 if self._parameters["StoreInternalVariables"] or self._toStore("CurrentState"):
243 self.StoredVariables["CurrentState"].store( _Best )
244 if self._toStore("SimulatedObservationAtCurrentState"):
246 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HmX )
247 self.StoredVariables["CostFunctionJb"].store( 0. )
248 self.StoredVariables["CostFunctionJo"].store( 0. )
249 self.StoredVariables["CostFunctionJ" ].store( _qualityBest )
251 # Obtention de l'analyse
252 # ----------------------
255 self.StoredVariables["Analysis"].store( Xa )
257 # Calculs et/ou stockages supplémentaires
258 # ---------------------------------------
259 if self._toStore("OMA") or \
260 self._toStore("SimulatedObservationAtOptimum"):
261 HXa = Hm(Xa).reshape((-1, 1))
262 if self._toStore("Innovation") or \
263 self._toStore("OMB") or \
264 self._toStore("SimulatedObservationAtBackground"):
265 HXb = Hm(Xb).reshape((-1, 1))
267 if self._toStore("Innovation"):
268 self.StoredVariables["Innovation"].store( Innovation )
269 if self._toStore("OMB"):
270 self.StoredVariables["OMB"].store( Innovation )
271 if self._toStore("BMA"):
272 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
273 if self._toStore("OMA"):
274 self.StoredVariables["OMA"].store( Y - HXa )
275 if self._toStore("SimulatedObservationAtBackground"):
276 self.StoredVariables["SimulatedObservationAtBackground"].store( HXb )
277 if self._toStore("SimulatedObservationAtOptimum"):
278 self.StoredVariables["SimulatedObservationAtOptimum"].store( HXa )
280 self._post_run(HO, EM)
283 # ==============================================================================
284 if __name__ == "__main__":
285 print("\n AUTODIAGNOSTIC\n")