]> SALOME platform Git repositories - modules/adao.git/blob - src/daComposant/daAlgorithms/TabuSearch.py
Salome HOME
Minor source update for OM compatibility
[modules/adao.git] / src / daComposant / daAlgorithms / TabuSearch.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2024 EDF R&D
4 #
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.
9 #
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.
14 #
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
18 #
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #
21 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
22
23 import numpy
24 from daCore import BasicObjects
25 from daCore.PlatformInfo import vfloat
26
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
29     def __init__(self):
30         BasicObjects.Algorithm.__init__(self, "TABUSEARCH")
31         self.defineRequiredParameter(
32             name     = "MaximumNumberOfIterations",
33             default  = 50,
34             typecast = int,
35             message  = "Nombre maximal de pas d'optimisation",
36             minval   = 1,
37             oldname  = "MaximumNumberOfSteps",
38         )
39         self.defineRequiredParameter(
40             name     = "SetSeed",
41             typecast = numpy.random.seed,
42             message  = "Graine fixée pour le générateur aléatoire",
43         )
44         self.defineRequiredParameter(
45             name     = "LengthOfTabuList",
46             default  = 50,
47             typecast = int,
48             message  = "Longueur de la liste tabou",
49             minval   = 1,
50         )
51         self.defineRequiredParameter(
52             name     = "NumberOfElementaryPerturbations",
53             default  = 1,
54             typecast = int,
55             message  = "Nombre de perturbations élémentaires pour choisir une perturbation d'état",
56             minval   = 1,
57         )
58         self.defineRequiredParameter(
59             name     = "NoiseDistribution",
60             default  = "Uniform",
61             typecast = str,
62             message  = "Distribution pour générer les perturbations d'état",
63             listval  = ["Gaussian", "Uniform"],
64         )
65         self.defineRequiredParameter(
66             name     = "QualityCriterion",
67             default  = "AugmentedWeightedLeastSquares",
68             typecast = str,
69             message  = "Critère de qualité utilisé",
70             listval  = [
71                 "AugmentedWeightedLeastSquares", "AWLS", "DA",
72                 "WeightedLeastSquares", "WLS",
73                 "LeastSquares", "LS", "L2",
74                 "AbsoluteValue", "L1",
75                 "MaximumError", "ME", "Linf",
76             ],
77         )
78         self.defineRequiredParameter(
79             name     = "NoiseHalfRange",
80             default  = [],
81             typecast = numpy.ravel,
82             message  = "Demi-amplitude des perturbations uniformes centrées d'état pour chaque composante de l'état",
83         )
84         self.defineRequiredParameter(
85             name     = "StandardDeviation",
86             default  = [],
87             typecast = numpy.ravel,
88             message  = "Ecart-type des perturbations gaussiennes d'état pour chaque composante de l'état",
89         )
90         self.defineRequiredParameter(
91             name     = "NoiseAddingProbability",
92             default  = 1.,
93             typecast = float,
94             message  = "Probabilité de perturbation d'une composante de l'état",
95             minval   = 0.,
96             maxval   = 1.,
97         )
98         self.defineRequiredParameter(
99             name     = "StoreInternalVariables",
100             default  = False,
101             typecast = bool,
102             message  = "Stockage des variables internes ou intermédiaires du calcul",
103         )
104         self.defineRequiredParameter(
105             name     = "StoreSupplementaryCalculations",
106             default  = [],
107             typecast = tuple,
108             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
109             listval  = [
110                 "Analysis",
111                 "BMA",
112                 "CostFunctionJ",
113                 "CostFunctionJb",
114                 "CostFunctionJo",
115                 "CurrentIterationNumber",
116                 "CurrentState",
117                 "Innovation",
118                 "OMA",
119                 "OMB",
120                 "SimulatedObservationAtBackground",
121                 "SimulatedObservationAtCurrentState",
122                 "SimulatedObservationAtOptimum",
123             ]
124         )
125         self.defineRequiredParameter(  # Pas de type
126             name     = "Bounds",
127             message  = "Liste des valeurs de bornes",
128         )
129         self.requireInputArguments(
130             mandatory= ("Xb", "Y", "HO", "R", "B"),
131         )
132         self.setAttributes(
133             tags=(
134                 "Optimization",
135                 "NonLinear",
136                 "MetaHeuristic",
137             ),
138             features=(
139                 "NonLocalOptimization",
140                 "DerivativeFree",
141                 "ConvergenceOnNumbers",
142             ),
143         )
144
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)
147         #
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
156         #
157         Hm = HO["Direct"].appliedTo
158         #
159         BI = B.getI()
160         RI = R.getI()
161
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
169                         _X[i] += _increment
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
175                         _X[i] += _increment
176             #
177             return _X
178
179         def StateInList( x, _TL ):
180             _X  = numpy.ravel( x )
181             _xInList = False
182             for state in _TL:
183                 if numpy.all(numpy.abs( _X - numpy.ravel(state) ) <= 1e-16 * numpy.abs(_X)):
184                     _xInList = True
185             # if _xInList: import sys ; sys.exit()
186             return _xInList
187
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
192             #
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"]:
199                 if RI is None:
200                     raise ValueError("Observation error covariance matrix has to be properly defined!")
201                 Jb  = 0.
202                 Jo  = vfloat(0.5 * _Innovation.T @ (RI @ _Innovation))
203             elif QualityMeasure in ["LeastSquares", "LS", "L2"]:
204                 Jb  = 0.
205                 Jo  = vfloat(0.5 * _Innovation.T @ _Innovation)
206             elif QualityMeasure in ["AbsoluteValue", "L1"]:
207                 Jb  = 0.
208                 Jo  = vfloat(numpy.sum( numpy.abs(_Innovation) ))
209             elif QualityMeasure in ["MaximumError", "ME", "Linf"]:
210                 Jb  = 0.
211                 Jo  = vfloat(numpy.max( numpy.abs(_Innovation) ))
212             #
213             J   = Jb + Jo
214             #
215             return J
216         #
217         # Minimisation de la fonctionnelle
218         # --------------------------------
219         _n = 0
220         _S = Xb
221         _qualityS = CostFunction( _S, self._parameters["QualityCriterion"] )
222         _Best, _qualityBest = _S, _qualityS
223         _TabuList = []
224         _TabuList.append( _S )
225         while _n < self._parameters["MaximumNumberOfIterations"]:
226             _n += 1
227             if len(_TabuList) > self._parameters["LengthOfTabuList"]:
228                 _TabuList.pop(0)
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
241             #
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"):
246                 _HmX = Hm( _Best )
247                 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HmX )
248             self.StoredVariables["CostFunctionJb"].store( 0. )
249             self.StoredVariables["CostFunctionJo"].store( 0. )
250             self.StoredVariables["CostFunctionJ" ].store( _qualityBest )
251         #
252         # Obtention de l'analyse
253         # ----------------------
254         Xa = _Best
255         #
256         self.StoredVariables["Analysis"].store( Xa )
257         #
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))
267             Innovation = Y - HXb
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 )
280         #
281         self._post_run(HO, EM)
282         return 0
283
284 # ==============================================================================
285 if __name__ == "__main__":
286     print("\n AUTODIAGNOSTIC\n")