1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2023 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
26 # ==============================================================================
27 class ElementaryAlgorithm(BasicObjects.Algorithm):
29 BasicObjects.Algorithm.__init__(self, "TABUSEARCH")
30 self.defineRequiredParameter(
31 name = "MaximumNumberOfIterations",
34 message = "Nombre maximal de pas d'optimisation",
36 oldname = "MaximumNumberOfSteps",
38 self.defineRequiredParameter(
40 typecast = numpy.random.seed,
41 message = "Graine fixée pour le générateur aléatoire",
43 self.defineRequiredParameter(
44 name = "LengthOfTabuList",
47 message = "Longueur de la liste tabou",
50 self.defineRequiredParameter(
51 name = "NumberOfElementaryPerturbations",
54 message = "Nombre de perturbations élémentaires pour choisir une perturbation d'état",
57 self.defineRequiredParameter(
58 name = "NoiseDistribution",
61 message = "Distribution pour générer les perturbations d'état",
62 listval = ["Gaussian","Uniform"],
64 self.defineRequiredParameter(
65 name = "QualityCriterion",
66 default = "AugmentedWeightedLeastSquares",
68 message = "Critère de qualité utilisé",
70 "AugmentedWeightedLeastSquares", "AWLS", "DA",
71 "WeightedLeastSquares", "WLS",
72 "LeastSquares", "LS", "L2",
73 "AbsoluteValue", "L1",
74 "MaximumError", "ME", "Linf",
77 self.defineRequiredParameter(
78 name = "NoiseHalfRange",
80 typecast = numpy.ravel,
81 message = "Demi-amplitude des perturbations uniformes centrées d'état pour chaque composante de l'état",
83 self.defineRequiredParameter(
84 name = "StandardDeviation",
86 typecast = numpy.ravel,
87 message = "Ecart-type des perturbations gaussiennes d'état pour chaque composante de l'état",
89 self.defineRequiredParameter(
90 name = "NoiseAddingProbability",
93 message = "Probabilité de perturbation d'une composante de l'état",
97 self.defineRequiredParameter(
98 name = "StoreInternalVariables",
101 message = "Stockage des variables internes ou intermédiaires du calcul",
103 self.defineRequiredParameter(
104 name = "StoreSupplementaryCalculations",
107 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
114 "CurrentIterationNumber",
119 "SimulatedObservationAtBackground",
120 "SimulatedObservationAtCurrentState",
121 "SimulatedObservationAtOptimum",
124 self.defineRequiredParameter( # Pas de type
126 message = "Liste des valeurs de bornes",
128 self.requireInputArguments(
129 mandatory= ("Xb", "Y", "HO", "R", "B"),
131 self.setAttributes(tags=(
137 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
138 self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
140 if self._parameters["NoiseDistribution"] == "Uniform":
141 nrange = self._parameters["NoiseHalfRange"] # Vecteur
142 if nrange.size != Xb.size:
143 raise ValueError("Noise generation by Uniform distribution requires range for all variable increments. The actual noise half range vector is:\n%s"%nrange)
144 elif self._parameters["NoiseDistribution"] == "Gaussian":
145 sigma = numpy.ravel(self._parameters["StandardDeviation"]) # Vecteur
146 if sigma.size != Xb.size:
147 raise ValueError("Noise generation by Gaussian distribution requires standard deviation for all variable increments. The actual standard deviation vector is:\n%s"%sigma)
149 Hm = HO["Direct"].appliedTo
154 def Tweak( x, NoiseDistribution, NoiseAddingProbability ):
155 _X = numpy.array( x, dtype=float, copy=True ).ravel().reshape((-1,1))
156 if NoiseDistribution == "Uniform":
157 for i in range(_X.size):
158 if NoiseAddingProbability >= numpy.random.uniform():
159 _increment = numpy.random.uniform(low=-nrange[i], high=nrange[i])
160 # On ne traite pas encore le dépassement des bornes ici
162 elif NoiseDistribution == "Gaussian":
163 for i in range(_X.size):
164 if NoiseAddingProbability >= numpy.random.uniform():
165 _increment = numpy.random.normal(loc=0., scale=sigma[i])
166 # On ne traite pas encore le dépassement des bornes ici
171 def StateInList( x, _TL ):
172 _X = numpy.ravel( x )
175 if numpy.all(numpy.abs( _X - numpy.ravel(state) ) <= 1e-16*numpy.abs(_X)):
177 # if _xInList: import sys ; sys.exit()
180 def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
181 _X = numpy.ravel( x ).reshape((-1,1))
182 _HX = numpy.ravel( Hm( _X ) ).reshape((-1,1))
183 _Innovation = Y - _HX
185 if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","DA"]:
186 if BI is None or RI is None:
187 raise ValueError("Background and Observation error covariance matrices has to be properly defined!")
188 Jb = 0.5 * (_X - Xb).T @ (BI @ (_X - Xb))
189 Jo = 0.5 * _Innovation.T @ (RI @ _Innovation)
190 elif QualityMeasure in ["WeightedLeastSquares","WLS"]:
192 raise ValueError("Observation error covariance matrix has to be properly defined!")
194 Jo = 0.5 * _Innovation.T @ (RI @ _Innovation)
195 elif QualityMeasure in ["LeastSquares","LS","L2"]:
197 Jo = 0.5 * _Innovation.T @ _Innovation
198 elif QualityMeasure in ["AbsoluteValue","L1"]:
200 Jo = numpy.sum( numpy.abs(_Innovation) )
201 elif QualityMeasure in ["MaximumError","ME", "Linf"]:
203 Jo = numpy.max( numpy.abs(_Innovation) )
205 J = float( Jb ) + float( Jo )
209 # Minimisation de la fonctionnelle
210 # --------------------------------
213 _qualityS = CostFunction( _S, self._parameters["QualityCriterion"] )
214 _Best, _qualityBest = _S, _qualityS
216 _TabuList.append( _S )
217 while _n < self._parameters["MaximumNumberOfIterations"]:
219 if len(_TabuList) > self._parameters["LengthOfTabuList"]:
221 _R = Tweak( _S, self._parameters["NoiseDistribution"], self._parameters["NoiseAddingProbability"] )
222 _qualityR = CostFunction( _R, self._parameters["QualityCriterion"] )
223 for nbt in range(self._parameters["NumberOfElementaryPerturbations"]-1):
224 _W = Tweak( _S, self._parameters["NoiseDistribution"], self._parameters["NoiseAddingProbability"] )
225 _qualityW = CostFunction( _W, self._parameters["QualityCriterion"] )
226 if (not StateInList(_W, _TabuList)) and ( (_qualityW < _qualityR) or StateInList(_R,_TabuList) ):
227 _R, _qualityR = _W, _qualityW
228 if (not StateInList( _R, _TabuList )) and (_qualityR < _qualityS):
229 _S, _qualityS = _R, _qualityR
230 _TabuList.append( _S )
231 if _qualityS < _qualityBest:
232 _Best, _qualityBest = _S, _qualityS
234 self.StoredVariables["CurrentIterationNumber"].store( len(self.StoredVariables["CostFunctionJ"]) )
235 if self._parameters["StoreInternalVariables"] or self._toStore("CurrentState"):
236 self.StoredVariables["CurrentState"].store( _Best )
237 if self._toStore("SimulatedObservationAtCurrentState"):
239 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HmX )
240 self.StoredVariables["CostFunctionJb"].store( 0. )
241 self.StoredVariables["CostFunctionJo"].store( 0. )
242 self.StoredVariables["CostFunctionJ" ].store( _qualityBest )
244 # Obtention de l'analyse
245 # ----------------------
248 self.StoredVariables["Analysis"].store( Xa )
250 # Calculs et/ou stockages supplémentaires
251 # ---------------------------------------
252 if self._toStore("OMA") or \
253 self._toStore("SimulatedObservationAtOptimum"):
254 HXa = Hm(Xa).reshape((-1,1))
255 if self._toStore("Innovation") or \
256 self._toStore("OMB") or \
257 self._toStore("SimulatedObservationAtBackground"):
258 HXb = Hm(Xb).reshape((-1,1))
260 if self._toStore("Innovation"):
261 self.StoredVariables["Innovation"].store( Innovation )
262 if self._toStore("OMB"):
263 self.StoredVariables["OMB"].store( Innovation )
264 if self._toStore("BMA"):
265 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
266 if self._toStore("OMA"):
267 self.StoredVariables["OMA"].store( Y - HXa )
268 if self._toStore("SimulatedObservationAtBackground"):
269 self.StoredVariables["SimulatedObservationAtBackground"].store( HXb )
270 if self._toStore("SimulatedObservationAtOptimum"):
271 self.StoredVariables["SimulatedObservationAtOptimum"].store( HXa )
276 # ==============================================================================
277 if __name__ == "__main__":
278 print('\n AUTODIAGNOSTIC\n')