Salome HOME
Documentation update with features and review corrections
[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             ),
142         )
143
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)
146         #
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
155         #
156         Hm = HO["Direct"].appliedTo
157         #
158         BI = B.getI()
159         RI = R.getI()
160
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
168                         _X[i] += _increment
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
174                         _X[i] += _increment
175             #
176             return _X
177
178         def StateInList( x, _TL ):
179             _X  = numpy.ravel( x )
180             _xInList = False
181             for state in _TL:
182                 if numpy.all(numpy.abs( _X - numpy.ravel(state) ) <= 1e-16 * numpy.abs(_X)):
183                     _xInList = True
184             # if _xInList: import sys ; sys.exit()
185             return _xInList
186
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
191             #
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"]:
198                 if RI is None:
199                     raise ValueError("Observation error covariance matrix has to be properly defined!")
200                 Jb  = 0.
201                 Jo  = vfloat(0.5 * _Innovation.T @ (RI @ _Innovation))
202             elif QualityMeasure in ["LeastSquares", "LS", "L2"]:
203                 Jb  = 0.
204                 Jo  = vfloat(0.5 * _Innovation.T @ _Innovation)
205             elif QualityMeasure in ["AbsoluteValue", "L1"]:
206                 Jb  = 0.
207                 Jo  = vfloat(numpy.sum( numpy.abs(_Innovation) ))
208             elif QualityMeasure in ["MaximumError", "ME", "Linf"]:
209                 Jb  = 0.
210                 Jo  = vfloat(numpy.max( numpy.abs(_Innovation) ))
211             #
212             J   = Jb + Jo
213             #
214             return J
215         #
216         # Minimisation de la fonctionnelle
217         # --------------------------------
218         _n = 0
219         _S = Xb
220         _qualityS = CostFunction( _S, self._parameters["QualityCriterion"] )
221         _Best, _qualityBest = _S, _qualityS
222         _TabuList = []
223         _TabuList.append( _S )
224         while _n < self._parameters["MaximumNumberOfIterations"]:
225             _n += 1
226             if len(_TabuList) > self._parameters["LengthOfTabuList"]:
227                 _TabuList.pop(0)
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
240             #
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"):
245                 _HmX = Hm( _Best )
246                 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HmX )
247             self.StoredVariables["CostFunctionJb"].store( 0. )
248             self.StoredVariables["CostFunctionJo"].store( 0. )
249             self.StoredVariables["CostFunctionJ" ].store( _qualityBest )
250         #
251         # Obtention de l'analyse
252         # ----------------------
253         Xa = _Best
254         #
255         self.StoredVariables["Analysis"].store( Xa )
256         #
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))
266             Innovation = Y - HXb
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 )
279         #
280         self._post_run(HO, EM)
281         return 0
282
283 # ==============================================================================
284 if __name__ == "__main__":
285     print("\n AUTODIAGNOSTIC\n")