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