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