]> SALOME platform Git repositories - modules/adao.git/blob - src/daComposant/daAlgorithms/ParticleSwarmOptimization.py
Salome HOME
Improvement of algorithms arguments validation and tests
[modules/adao.git] / src / daComposant / daAlgorithms / ParticleSwarmOptimization.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2020 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 logging
24 from daCore import BasicObjects
25 import numpy, copy
26
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
29     def __init__(self):
30         BasicObjects.Algorithm.__init__(self, "PARTICLESWARMOPTIMIZATION")
31         self.defineRequiredParameter(
32             name     = "MaximumNumberOfSteps",
33             default  = 50,
34             typecast = int,
35             message  = "Nombre maximal de pas d'optimisation",
36             minval   = 0,
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  = ["AugmentedWeightedLeastSquares","AWLS","AugmentedPonderatedLeastSquares","APLS","DA",
78                         "WeightedLeastSquares","WLS","PonderatedLeastSquares","PLS",
79                         "LeastSquares","LS","L2",
80                         "AbsoluteValue","L1",
81                         "MaximumError","ME"],
82             )
83         self.defineRequiredParameter(
84             name     = "StoreInternalVariables",
85             default  = False,
86             typecast = bool,
87             message  = "Stockage des variables internes ou intermédiaires du calcul",
88             )
89         self.defineRequiredParameter(
90             name     = "StoreSupplementaryCalculations",
91             default  = [],
92             typecast = tuple,
93             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
94             listval  = [
95                 "Analysis",
96                 "BMA",
97                 "CurrentState",
98                 "CostFunctionJ",
99                 "CostFunctionJb",
100                 "CostFunctionJo",
101                 "Innovation",
102                 "OMA",
103                 "OMB",
104                 "SimulatedObservationAtBackground",
105                 "SimulatedObservationAtCurrentState",
106                 "SimulatedObservationAtOptimum",
107                 ]
108             )
109         self.defineRequiredParameter( # Pas de type
110             name     = "BoxBounds",
111             message  = "Liste des valeurs de bornes d'incréments de paramètres",
112             )
113         self.requireInputArguments(
114             mandatory= ("Xb", "Y", "HO", "R", "B"),
115             )
116         self.setAttributes(tags=(
117             "Optimization",
118             "NonLinear",
119             "Population",
120             ))
121
122     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
123         self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
124         #
125         if ("BoxBounds" in self._parameters) and isinstance(self._parameters["BoxBounds"], (list, tuple)) and (len(self._parameters["BoxBounds"]) > 0):
126             BoxBounds = self._parameters["BoxBounds"]
127             logging.debug("%s Prise en compte des bornes d'incréments de paramètres effectuée"%(self._name,))
128         else:
129             raise ValueError("Particle Swarm Optimization requires bounds on all variables increments to be truly given (BoxBounds).")
130         BoxBounds   = numpy.array(BoxBounds)
131         if numpy.isnan(BoxBounds).any():
132             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)
133         #
134         Phig = float( self._parameters["GroupRecallRate"] )
135         Phip = 1. - Phig
136         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)))
137         #
138         # Opérateur d'observation
139         # -----------------------
140         Hm = HO["Direct"].appliedTo
141         #
142         # Précalcul des inversions de B et R
143         # ----------------------------------
144         BI = B.getI()
145         RI = R.getI()
146         #
147         # Définition de la fonction-coût
148         # ------------------------------
149         def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
150             _X  = numpy.asmatrix(numpy.ravel( x )).T
151             _HX = Hm( _X )
152             _HX = numpy.asmatrix(numpy.ravel( _HX )).T
153             #
154             if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","AugmentedPonderatedLeastSquares","APLS","DA"]:
155                 if BI is None or RI is None:
156                     raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
157                 Jb  = 0.5 * (_X - Xb).T * BI * (_X - Xb)
158                 Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
159             elif QualityMeasure in ["WeightedLeastSquares","WLS","PonderatedLeastSquares","PLS"]:
160                 if RI is None:
161                     raise ValueError("Observation error covariance matrix has to be properly defined!")
162                 Jb  = 0.
163                 Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
164             elif QualityMeasure in ["LeastSquares","LS","L2"]:
165                 Jb  = 0.
166                 Jo  = 0.5 * (Y - _HX).T * (Y - _HX)
167             elif QualityMeasure in ["AbsoluteValue","L1"]:
168                 Jb  = 0.
169                 Jo  = numpy.sum( numpy.abs(Y - _HX) )
170             elif QualityMeasure in ["MaximumError","ME"]:
171                 Jb  = 0.
172                 Jo  = numpy.max( numpy.abs(Y - _HX) )
173             #
174             J   = float( Jb ) + float( Jo )
175             #
176             return J
177         #
178         # Point de démarrage de l'optimisation : Xini = Xb
179         # ------------------------------------
180         if isinstance(Xb, type(numpy.matrix([]))):
181             Xini = Xb.A1.tolist()
182         elif Xb is not None:
183             Xini = list(Xb)
184         else:
185             Xini = numpy.zeros(len(BoxBounds[:,0]))
186         #
187         # Initialisation des bornes
188         # -------------------------
189         SpaceUp  = BoxBounds[:,1] + Xini
190         SpaceLow = BoxBounds[:,0] + Xini
191         nbparam  = len(SpaceUp)
192         #
193         # Initialisation de l'essaim
194         # --------------------------
195         NumberOfFunctionEvaluations = 0
196         LimitVelocity = numpy.abs(SpaceUp-SpaceLow)
197         #
198         PosInsect = []
199         VelocityInsect = []
200         for i in range(nbparam) :
201             PosInsect.append(numpy.random.uniform(low=SpaceLow[i], high=SpaceUp[i], size=self._parameters["NumberOfInsects"]))
202             VelocityInsect.append(numpy.random.uniform(low=-LimitVelocity[i], high=LimitVelocity[i], size=self._parameters["NumberOfInsects"]))
203         VelocityInsect = numpy.matrix(VelocityInsect)
204         PosInsect = numpy.matrix(PosInsect)
205         #
206         BestPosInsect = numpy.array(PosInsect)
207         qBestPosInsect = []
208         Best = copy.copy(SpaceLow)
209         qBest = CostFunction(Best,self._parameters["QualityCriterion"])
210         NumberOfFunctionEvaluations += 1
211         #
212         for i in range(self._parameters["NumberOfInsects"]):
213             insect  = numpy.ravel(PosInsect[:,i])
214             quality = CostFunction(insect,self._parameters["QualityCriterion"])
215             NumberOfFunctionEvaluations += 1
216             qBestPosInsect.append(quality)
217             if quality < qBest:
218                 Best  = copy.copy( insect )
219                 qBest = copy.copy( quality )
220         logging.debug("%s Initialisation, Insecte = %s, Qualité = %s"%(self._name, str(Best), str(qBest)))
221         #
222         if self._parameters["StoreInternalVariables"] or self._toStore("CurrentState"):
223             self.StoredVariables["CurrentState"].store( Best )
224         self.StoredVariables["CostFunctionJb"].store( 0. )
225         self.StoredVariables["CostFunctionJo"].store( 0. )
226         self.StoredVariables["CostFunctionJ" ].store( qBest )
227         #
228         # Minimisation de la fonctionnelle
229         # --------------------------------
230         for n in range(self._parameters["MaximumNumberOfSteps"]):
231             for i in range(self._parameters["NumberOfInsects"]) :
232                 insect  = numpy.ravel(PosInsect[:,i])
233                 rp = numpy.random.uniform(size=nbparam)
234                 rg = numpy.random.uniform(size=nbparam)
235                 for j in range(nbparam) :
236                     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])
237                     PosInsect[j,i] = PosInsect[j,i]+VelocityInsect[j,i]
238                 quality = CostFunction(insect,self._parameters["QualityCriterion"])
239                 NumberOfFunctionEvaluations += 1
240                 if quality < qBestPosInsect[i]:
241                     BestPosInsect[:,i] = copy.copy( insect )
242                     qBestPosInsect[i]  = copy.copy( quality )
243                     if quality < qBest :
244                         Best  = copy.copy( insect )
245                         qBest = copy.copy( quality )
246             logging.debug("%s Etape %i, Insecte = %s, Qualité = %s"%(self._name, n, str(Best), str(qBest)))
247             #
248             if self._parameters["StoreInternalVariables"] or self._toStore("CurrentState"):
249                 self.StoredVariables["CurrentState"].store( Best )
250             if self._toStore("SimulatedObservationAtCurrentState"):
251                 _HmX = Hm( numpy.asmatrix(numpy.ravel( Best )).T )
252                 _HmX = numpy.asmatrix(numpy.ravel( _HmX )).T
253                 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HmX )
254             self.StoredVariables["CostFunctionJb"].store( 0. )
255             self.StoredVariables["CostFunctionJo"].store( 0. )
256             self.StoredVariables["CostFunctionJ" ].store( qBest )
257             if NumberOfFunctionEvaluations > self._parameters["MaximumNumberOfFunctionEvaluations"]:
258                 logging.debug("%s Stopping search because the number %i of function evaluations is exceeding the maximum %i."%(self._name, NumberOfFunctionEvaluations, self._parameters["MaximumNumberOfFunctionEvaluations"]))
259                 break
260         #
261         # Obtention de l'analyse
262         # ----------------------
263         Xa = numpy.asmatrix(numpy.ravel( Best )).T
264         #
265         self.StoredVariables["Analysis"].store( Xa.A1 )
266         #
267         if self._toStore("Innovation") or \
268             self._toStore("OMB") or \
269             self._toStore("SimulatedObservationAtBackground"):
270             HXb = Hm(Xb)
271             d = Y - HXb
272         if self._toStore("OMA") or \
273             self._toStore("SimulatedObservationAtOptimum"):
274             HXa = Hm(Xa)
275         #
276         # Calculs et/ou stockages supplémentaires
277         # ---------------------------------------
278         if self._toStore("Innovation"):
279             self.StoredVariables["Innovation"].store( numpy.ravel(d) )
280         if self._toStore("BMA"):
281             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
282         if self._toStore("OMA"):
283             self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
284         if self._toStore("OMB"):
285             self.StoredVariables["OMB"].store( numpy.ravel(d) )
286         if self._toStore("SimulatedObservationAtBackground"):
287             self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
288         if self._toStore("SimulatedObservationAtOptimum"):
289             self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
290         #
291         self._post_run(HO)
292         return 0
293
294 # ==============================================================================
295 if __name__ == "__main__":
296     print('\n AUTODIAGNOSTIC\n')