Salome HOME
1a0402d9256d0e4e9c9230abfc9e8bac168b5b4e
[modules/adao.git] / src / daComposant / daAlgorithms / ParticleSwarmOptimization.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2022 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, logging, copy
24 from daCore import BasicObjects
25
26 # ==============================================================================
27 class ElementaryAlgorithm(BasicObjects.Algorithm):
28     def __init__(self):
29         BasicObjects.Algorithm.__init__(self, "PARTICLESWARMOPTIMIZATION")
30         self.defineRequiredParameter(
31             name     = "MaximumNumberOfIterations",
32             default  = 50,
33             typecast = int,
34             message  = "Nombre maximal de pas d'optimisation",
35             minval   = 0,
36             oldname  = "MaximumNumberOfSteps",
37             )
38         self.defineRequiredParameter(
39             name     = "MaximumNumberOfFunctionEvaluations",
40             default  = 15000,
41             typecast = int,
42             message  = "Nombre maximal d'évaluations de la fonction",
43             minval   = -1,
44             )
45         self.defineRequiredParameter(
46             name     = "SetSeed",
47             typecast = numpy.random.seed,
48             message  = "Graine fixée pour le générateur aléatoire",
49             )
50         self.defineRequiredParameter(
51             name     = "NumberOfInsects",
52             default  = 100,
53             typecast = int,
54             message  = "Nombre d'insectes dans l'essaim",
55             minval   = -1,
56             )
57         self.defineRequiredParameter(
58             name     = "SwarmVelocity",
59             default  = 1.,
60             typecast = float,
61             message  = "Vitesse de groupe imposée par l'essaim",
62             minval   = 0.,
63             )
64         self.defineRequiredParameter(
65             name     = "GroupRecallRate",
66             default  = 0.5,
67             typecast = float,
68             message  = "Taux de rappel au meilleur insecte du groupe (entre 0 et 1)",
69             minval   = 0.,
70             maxval   = 1.,
71             )
72         self.defineRequiredParameter(
73             name     = "QualityCriterion",
74             default  = "AugmentedWeightedLeastSquares",
75             typecast = str,
76             message  = "Critère de qualité utilisé",
77             listval  = [
78                 "AugmentedWeightedLeastSquares", "AWLS", "DA",
79                 "WeightedLeastSquares", "WLS",
80                 "LeastSquares", "LS", "L2",
81                 "AbsoluteValue", "L1",
82                 "MaximumError", "ME",
83                 ],
84             )
85         self.defineRequiredParameter(
86             name     = "StoreInternalVariables",
87             default  = False,
88             typecast = bool,
89             message  = "Stockage des variables internes ou intermédiaires du calcul",
90             )
91         self.defineRequiredParameter(
92             name     = "StoreSupplementaryCalculations",
93             default  = [],
94             typecast = tuple,
95             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
96             listval  = [
97                 "Analysis",
98                 "BMA",
99                 "CostFunctionJ",
100                 "CostFunctionJb",
101                 "CostFunctionJo",
102                 "CurrentIterationNumber",
103                 "CurrentState",
104                 "Innovation",
105                 "OMA",
106                 "OMB",
107                 "SimulatedObservationAtBackground",
108                 "SimulatedObservationAtCurrentState",
109                 "SimulatedObservationAtOptimum",
110                 ]
111             )
112         self.defineRequiredParameter( # Pas de type
113             name     = "BoxBounds",
114             message  = "Liste des valeurs de bornes d'incréments de paramètres",
115             )
116         self.requireInputArguments(
117             mandatory= ("Xb", "Y", "HO", "R", "B"),
118             )
119         self.setAttributes(tags=(
120             "Optimization",
121             "NonLinear",
122             "MetaHeuristic",
123             "Population",
124             ))
125
126     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
127         self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
128         #
129         if ("BoxBounds" in self._parameters) and isinstance(self._parameters["BoxBounds"], (list, tuple)) and (len(self._parameters["BoxBounds"]) > 0):
130             BoxBounds = self._parameters["BoxBounds"]
131             logging.debug("%s Prise en compte des bornes d'incréments de paramètres effectuée"%(self._name,))
132         else:
133             raise ValueError("Particle Swarm Optimization requires bounds on all variables increments to be truly given (BoxBounds).")
134         BoxBounds   = numpy.array(BoxBounds)
135         if numpy.isnan(BoxBounds).any():
136             raise ValueError("Particle Swarm Optimization requires bounds on all variables increments to be truly given (BoxBounds), \"None\" is not allowed. The actual increments bounds are:\n%s"%BoxBounds)
137         #
138         Phig = float( self._parameters["GroupRecallRate"] )
139         Phip = 1. - Phig
140         logging.debug("%s Taux de rappel au meilleur insecte du groupe (entre 0 et 1) = %s et à la meilleure position précédente (son complémentaire à 1) = %s"%(self._name, str(Phig), str(Phip)))
141         #
142         Hm = HO["Direct"].appliedTo
143         #
144         BI = B.getI()
145         RI = R.getI()
146         #
147         def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
148             _X  = numpy.ravel( x ).reshape((-1,1))
149             _HX = numpy.ravel( Hm( _X ) ).reshape((-1,1))
150             _Innovation = Y - _HX
151             #
152             if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","DA"]:
153                 if BI is None or RI is None:
154                     raise ValueError("Background and Observation error covariance matrices has to be properly defined!")
155                 Jb  = 0.5 * (_X - Xb).T @ (BI @ (_X - Xb))
156                 Jo  = 0.5 * _Innovation.T @ (RI @ _Innovation)
157             elif QualityMeasure in ["WeightedLeastSquares","WLS"]:
158                 if RI is None:
159                     raise ValueError("Observation error covariance matrix has to be properly defined!")
160                 Jb  = 0.
161                 Jo  = 0.5 * _Innovation.T @ (RI @ _Innovation)
162             elif QualityMeasure in ["LeastSquares","LS","L2"]:
163                 Jb  = 0.
164                 Jo  = 0.5 * _Innovation.T @ _Innovation
165             elif QualityMeasure in ["AbsoluteValue","L1"]:
166                 Jb  = 0.
167                 Jo  = numpy.sum( numpy.abs(_Innovation) )
168             elif QualityMeasure in ["MaximumError","ME"]:
169                 Jb  = 0.
170                 Jo  = numpy.max( numpy.abs(_Innovation) )
171             #
172             J   = float( Jb ) + float( Jo )
173             #
174             return J
175         #
176         if Xb is not None:
177             Xini = numpy.ravel(Xb)
178         else:
179             Xini = numpy.zeros(len(BoxBounds[:,0]))
180         #
181         SpaceUp  = BoxBounds[:,1] + Xini
182         SpaceLow = BoxBounds[:,0] + Xini
183         nbparam  = len(SpaceUp)
184         #
185         # Initialisation de l'essaim
186         # --------------------------
187         NumberOfFunctionEvaluations = 0
188         LimitVelocity = numpy.abs(SpaceUp-SpaceLow)
189         #
190         PosInsect = []
191         VelocityInsect = []
192         for i in range(nbparam) :
193             PosInsect.append(numpy.random.uniform(low=SpaceLow[i], high=SpaceUp[i], size=self._parameters["NumberOfInsects"]))
194             VelocityInsect.append(numpy.random.uniform(low=-LimitVelocity[i], high=LimitVelocity[i], size=self._parameters["NumberOfInsects"]))
195         VelocityInsect = numpy.array(VelocityInsect)
196         PosInsect = numpy.array(PosInsect)
197         #
198         BestPosInsect = numpy.array(PosInsect)
199         qBestPosInsect = []
200         _Best = copy.copy(SpaceLow)
201         _qualityBest = CostFunction(_Best,self._parameters["QualityCriterion"])
202         NumberOfFunctionEvaluations += 1
203         #
204         for i in range(self._parameters["NumberOfInsects"]):
205             insect  = numpy.ravel(PosInsect[:,i])
206             quality = CostFunction(insect,self._parameters["QualityCriterion"])
207             NumberOfFunctionEvaluations += 1
208             qBestPosInsect.append(quality)
209             if quality < _qualityBest:
210                 _Best  = copy.copy( insect )
211                 _qualityBest = copy.copy( quality )
212         logging.debug("%s Initialisation, Insecte = %s, Qualité = %s"%(self._name, str(_Best), str(_qualityBest)))
213         #
214         self.StoredVariables["CurrentIterationNumber"].store( len(self.StoredVariables["CostFunctionJ"]) )
215         if self._parameters["StoreInternalVariables"] or self._toStore("CurrentState"):
216             self.StoredVariables["CurrentState"].store( _Best )
217         self.StoredVariables["CostFunctionJb"].store( 0. )
218         self.StoredVariables["CostFunctionJo"].store( 0. )
219         self.StoredVariables["CostFunctionJ" ].store( _qualityBest )
220         #
221         # Minimisation de la fonctionnelle
222         # --------------------------------
223         for n in range(self._parameters["MaximumNumberOfIterations"]):
224             for i in range(self._parameters["NumberOfInsects"]) :
225                 insect  = numpy.ravel(PosInsect[:,i])
226                 rp = numpy.random.uniform(size=nbparam)
227                 rg = numpy.random.uniform(size=nbparam)
228                 for j in range(nbparam) :
229                     VelocityInsect[j,i] = self._parameters["SwarmVelocity"]*VelocityInsect[j,i] +  Phip*rp[j]*(BestPosInsect[j,i]-PosInsect[j,i]) +  Phig*rg[j]*(_Best[j]-PosInsect[j,i])
230                     PosInsect[j,i] = PosInsect[j,i]+VelocityInsect[j,i]
231                 quality = CostFunction(insect,self._parameters["QualityCriterion"])
232                 NumberOfFunctionEvaluations += 1
233                 if quality < qBestPosInsect[i]:
234                     BestPosInsect[:,i] = copy.copy( insect )
235                     qBestPosInsect[i]  = copy.copy( quality )
236                     if quality < _qualityBest :
237                         _Best  = copy.copy( insect )
238                         _qualityBest = copy.copy( quality )
239             logging.debug("%s Etape %i, Insecte = %s, Qualité = %s"%(self._name, n, str(_Best), str(_qualityBest)))
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             if NumberOfFunctionEvaluations > self._parameters["MaximumNumberOfFunctionEvaluations"]:
251                 logging.debug("%s Stopping search because the number %i of function evaluations is exceeding the maximum %i."%(self._name, NumberOfFunctionEvaluations, self._parameters["MaximumNumberOfFunctionEvaluations"]))
252                 break
253         #
254         # Obtention de l'analyse
255         # ----------------------
256         Xa = _Best
257         #
258         self.StoredVariables["Analysis"].store( Xa )
259         #
260         # Calculs et/ou stockages supplémentaires
261         # ---------------------------------------
262         if self._toStore("OMA") or \
263             self._toStore("SimulatedObservationAtOptimum"):
264             HXa = Hm(Xa)
265         if self._toStore("Innovation") or \
266             self._toStore("OMB") or \
267             self._toStore("SimulatedObservationAtBackground"):
268             HXb = Hm(Xb)
269             Innovation = Y - HXb
270         if self._toStore("Innovation"):
271             self.StoredVariables["Innovation"].store( Innovation )
272         if self._toStore("OMB"):
273             self.StoredVariables["OMB"].store( Innovation )
274         if self._toStore("BMA"):
275             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
276         if self._toStore("OMA"):
277             self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
278         if self._toStore("SimulatedObservationAtBackground"):
279             self.StoredVariables["SimulatedObservationAtBackground"].store( HXb )
280         if self._toStore("SimulatedObservationAtOptimum"):
281             self.StoredVariables["SimulatedObservationAtOptimum"].store( HXa )
282         #
283         self._post_run(HO)
284         return 0
285
286 # ==============================================================================
287 if __name__ == "__main__":
288     print('\n AUTODIAGNOSTIC\n')