]> SALOME platform Git repositories - modules/adao.git/blob - src/daComposant/daAlgorithms/TabuSearch.py
Salome HOME
Documentation and code update for PSO
[modules/adao.git] / src / daComposant / daAlgorithms / TabuSearch.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2023 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
26 # ==============================================================================
27 class ElementaryAlgorithm(BasicObjects.Algorithm):
28     def __init__(self):
29         BasicObjects.Algorithm.__init__(self, "TABUSEARCH")
30         self.defineRequiredParameter(
31             name     = "MaximumNumberOfIterations",
32             default  = 50,
33             typecast = int,
34             message  = "Nombre maximal de pas d'optimisation",
35             minval   = 1,
36             oldname  = "MaximumNumberOfSteps",
37             )
38         self.defineRequiredParameter(
39             name     = "SetSeed",
40             typecast = numpy.random.seed,
41             message  = "Graine fixée pour le générateur aléatoire",
42             )
43         self.defineRequiredParameter(
44             name     = "LengthOfTabuList",
45             default  = 50,
46             typecast = int,
47             message  = "Longueur de la liste tabou",
48             minval   = 1,
49             )
50         self.defineRequiredParameter(
51             name     = "NumberOfElementaryPerturbations",
52             default  = 1,
53             typecast = int,
54             message  = "Nombre de perturbations élémentaires pour choisir une perturbation d'état",
55             minval   = 1,
56             )
57         self.defineRequiredParameter(
58             name     = "NoiseDistribution",
59             default  = "Uniform",
60             typecast = str,
61             message  = "Distribution pour générer les perturbations d'état",
62             listval  = ["Gaussian","Uniform"],
63             )
64         self.defineRequiredParameter(
65             name     = "QualityCriterion",
66             default  = "AugmentedWeightedLeastSquares",
67             typecast = str,
68             message  = "Critère de qualité utilisé",
69             listval  = [
70                 "AugmentedWeightedLeastSquares", "AWLS", "DA",
71                 "WeightedLeastSquares", "WLS",
72                 "LeastSquares", "LS", "L2",
73                 "AbsoluteValue", "L1",
74                 "MaximumError", "ME", "Linf",
75                 ],
76             )
77         self.defineRequiredParameter(
78             name     = "NoiseHalfRange",
79             default  = [],
80             typecast = numpy.ravel,
81             message  = "Demi-amplitude des perturbations uniformes centrées d'état pour chaque composante de l'état",
82             )
83         self.defineRequiredParameter(
84             name     = "StandardDeviation",
85             default  = [],
86             typecast = numpy.ravel,
87             message  = "Ecart-type des perturbations gaussiennes d'état pour chaque composante de l'état",
88             )
89         self.defineRequiredParameter(
90             name     = "NoiseAddingProbability",
91             default  = 1.,
92             typecast = float,
93             message  = "Probabilité de perturbation d'une composante de l'état",
94             minval   = 0.,
95             maxval   = 1.,
96             )
97         self.defineRequiredParameter(
98             name     = "StoreInternalVariables",
99             default  = False,
100             typecast = bool,
101             message  = "Stockage des variables internes ou intermédiaires du calcul",
102             )
103         self.defineRequiredParameter(
104             name     = "StoreSupplementaryCalculations",
105             default  = [],
106             typecast = tuple,
107             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
108             listval  = [
109                 "Analysis",
110                 "BMA",
111                 "CostFunctionJ",
112                 "CostFunctionJb",
113                 "CostFunctionJo",
114                 "CurrentIterationNumber",
115                 "CurrentState",
116                 "Innovation",
117                 "OMA",
118                 "OMB",
119                 "SimulatedObservationAtBackground",
120                 "SimulatedObservationAtCurrentState",
121                 "SimulatedObservationAtOptimum",
122                 ]
123             )
124         self.defineRequiredParameter( # Pas de type
125             name     = "Bounds",
126             message  = "Liste des valeurs de bornes",
127             )
128         self.requireInputArguments(
129             mandatory= ("Xb", "Y", "HO", "R", "B"),
130             )
131         self.setAttributes(tags=(
132             "Optimization",
133             "NonLinear",
134             "MetaHeuristic",
135             ))
136
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)
139         #
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)
148         #
149         Hm = HO["Direct"].appliedTo
150         #
151         BI = B.getI()
152         RI = R.getI()
153         #
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
161                         _X[i] += _increment
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
167                         _X[i] += _increment
168             #
169             return _X
170         #
171         def StateInList( x, _TL ):
172             _X  = numpy.ravel( x )
173             _xInList = False
174             for state in _TL:
175                 if numpy.all(numpy.abs( _X - numpy.ravel(state) ) <= 1e-16*numpy.abs(_X)):
176                     _xInList = True
177             # if _xInList: import sys ; sys.exit()
178             return _xInList
179         #
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
184             #
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"]:
191                 if RI is None:
192                     raise ValueError("Observation error covariance matrix has to be properly defined!")
193                 Jb  = 0.
194                 Jo  = 0.5 * _Innovation.T @ (RI @ _Innovation)
195             elif QualityMeasure in ["LeastSquares","LS","L2"]:
196                 Jb  = 0.
197                 Jo  = 0.5 * _Innovation.T @ _Innovation
198             elif QualityMeasure in ["AbsoluteValue","L1"]:
199                 Jb  = 0.
200                 Jo  = numpy.sum( numpy.abs(_Innovation) )
201             elif QualityMeasure in ["MaximumError","ME", "Linf"]:
202                 Jb  = 0.
203                 Jo  = numpy.max( numpy.abs(_Innovation) )
204             #
205             J   = float( Jb ) + float( Jo )
206             #
207             return J
208         #
209         # Minimisation de la fonctionnelle
210         # --------------------------------
211         _n = 0
212         _S = Xb
213         _qualityS = CostFunction( _S, self._parameters["QualityCriterion"] )
214         _Best, _qualityBest   =   _S, _qualityS
215         _TabuList = []
216         _TabuList.append( _S )
217         while _n < self._parameters["MaximumNumberOfIterations"]:
218             _n += 1
219             if len(_TabuList) > self._parameters["LengthOfTabuList"]:
220                 _TabuList.pop(0)
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
233             #
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"):
238                 _HmX = Hm( _Best )
239                 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HmX )
240             self.StoredVariables["CostFunctionJb"].store( 0. )
241             self.StoredVariables["CostFunctionJo"].store( 0. )
242             self.StoredVariables["CostFunctionJ" ].store( _qualityBest )
243         #
244         # Obtention de l'analyse
245         # ----------------------
246         Xa = _Best
247         #
248         self.StoredVariables["Analysis"].store( Xa )
249         #
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))
259             Innovation = Y - HXb
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 )
272         #
273         self._post_run(HO)
274         return 0
275
276 # ==============================================================================
277 if __name__ == "__main__":
278     print('\n AUTODIAGNOSTIC\n')