Salome HOME
Documentation minor corrections and improvements
[modules/adao.git] / src / daComposant / daAlgorithms / ParticleSwarmOptimization.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2014 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   = 1,
37             )
38         self.defineRequiredParameter(
39             name     = "SetSeed",
40             typecast = numpy.random.seed,
41             message  = "Graine fixée pour le générateur aléatoire",
42             )
43         self.defineRequiredParameter(
44             name     = "NumberOfInsects",
45             default  = 100,
46             typecast = int,
47             message  = "Nombre d'insectes dans l'essaim",
48             minval   = -1,
49             )
50         self.defineRequiredParameter(
51             name     = "SwarmVelocity",
52             default  = 1.,
53             typecast = float,
54             message  = "Vitesse de groupe imposée par l'essaim",
55             minval   = 0.,
56             )
57         self.defineRequiredParameter(
58             name     = "GroupRecallRate",
59             default  = 0.5,
60             typecast = float,
61             message  = "Taux de rappel au meilleur insecte du groupe (entre 0 et 1)",
62             minval   = 0.,
63             maxval   = 1.,
64             )
65         self.defineRequiredParameter(
66             name     = "QualityCriterion",
67             default  = "AugmentedWeightedLeastSquares",
68             typecast = str,
69             message  = "Critère de qualité utilisé",
70             listval  = ["AugmentedWeightedLeastSquares","AWLS","AugmentedPonderatedLeastSquares","APLS","DA",
71                         "WeightedLeastSquares","WLS","PonderatedLeastSquares","PLS",
72                         "LeastSquares","LS","L2",
73                         "AbsoluteValue","L1",
74                         "MaximumError","ME"],
75             )
76         self.defineRequiredParameter(
77             name     = "StoreInternalVariables",
78             default  = False,
79             typecast = bool,
80             message  = "Stockage des variables internes ou intermédiaires du calcul",
81             )
82         self.defineRequiredParameter(
83             name     = "StoreSupplementaryCalculations",
84             default  = [],
85             typecast = tuple,
86             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
87             listval  = ["BMA", "OMA", "OMB", "Innovation"]
88             )
89
90     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
91         self._pre_run()
92         #
93         # Paramètres de pilotage
94         # ----------------------
95         self.setParameters(Parameters)
96         #
97         if self._parameters.has_key("BoxBounds") and (type(self._parameters["BoxBounds"]) is type([]) or type(self._parameters["BoxBounds"]) is type(())) and (len(self._parameters["BoxBounds"]) > 0):
98             BoxBounds = self._parameters["BoxBounds"]
99             logging.debug("%s Prise en compte des bornes d'incréments de paramètres effectuee"%(self._name,))
100         else:
101             raise ValueError("Particle Swarm Optimization requires bounds on all variables to be given.")
102         BoxBounds   = numpy.array(BoxBounds)
103         if numpy.isnan(BoxBounds).any():
104             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)
105         #
106         Phig = float( self._parameters["GroupRecallRate"] )
107         Phip = 1. - Phig
108         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)))
109         #
110         # Opérateur d'observation
111         # -----------------------
112         Hm = HO["Direct"].appliedTo
113         #
114         # Précalcul des inversions de B et R
115         # ----------------------------------
116         BI = B.getI()
117         RI = R.getI()
118         #
119         # Définition de la fonction-coût
120         # ------------------------------
121         def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
122             _X  = numpy.asmatrix(numpy.ravel( x )).T
123             _HX = Hm( _X )
124             _HX = numpy.asmatrix(numpy.ravel( _HX )).T
125             #
126             if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","AugmentedPonderatedLeastSquares","APLS","DA"]:
127                 if BI is None or RI is None:
128                     raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
129                 Jb  = 0.5 * (_X - Xb).T * BI * (_X - Xb)
130                 Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
131                 J   = float( Jb ) + float( Jo )
132             elif QualityMeasure in ["WeightedLeastSquares","WLS","PonderatedLeastSquares","PLS"]:
133                 if RI is None:
134                     raise ValueError("Observation error covariance matrix has to be properly defined!")
135                 Jb  = 0.
136                 Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
137                 J   = float( Jb ) + float( Jo )
138             elif QualityMeasure in ["LeastSquares","LS","L2"]:
139                 Jb  = 0.
140                 Jo  = 0.5 * (Y - _HX).T * (Y - _HX)
141                 J   = float( Jb ) + float( Jo )
142             elif QualityMeasure in ["AbsoluteValue","L1"]:
143                 Jb  = 0.
144                 Jo  = numpy.sum( numpy.abs(Y - _HX) )
145                 J   = float( Jb ) + float( Jo )
146             elif QualityMeasure in ["MaximumError","ME"]:
147                 Jb  = 0.
148                 Jo  = numpy.max( numpy.abs(Y - _HX) )
149                 J   = float( Jb ) + float( Jo )
150             #
151             return J
152         #
153         # Point de démarrage de l'optimisation : Xini = Xb
154         # ------------------------------------
155         if type(Xb) is type(numpy.matrix([])):
156             Xini = Xb.A1.tolist()
157         elif Xb is not None:
158             Xini = list(Xb)
159         else:
160             Xini = numpy.zeros(len(BoxBounds[:,0]))
161         #
162         # Initialisation des bornes
163         # -------------------------
164         SpaceUp  = BoxBounds[:,1] + Xini
165         SpaceLow = BoxBounds[:,0] + Xini
166         nbparam  = len(SpaceUp)
167         #
168         # Initialisation de l'essaim
169         # --------------------------
170         LimitVelocity = numpy.abs(SpaceUp-SpaceLow)
171         #
172         PosInsect = []
173         VelocityInsect = []
174         for i in range(nbparam) :
175             PosInsect.append(numpy.random.uniform(low=SpaceLow[i], high=SpaceUp[i], size=self._parameters["NumberOfInsects"]))
176             VelocityInsect.append(numpy.random.uniform(low=-LimitVelocity[i], high=LimitVelocity[i], size=self._parameters["NumberOfInsects"]))
177         VelocityInsect = numpy.matrix(VelocityInsect)
178         PosInsect = numpy.matrix(PosInsect)
179         #
180         BestPosInsect = numpy.array(PosInsect)
181         qBestPosInsect = []
182         Best = copy.copy(SpaceLow)
183         qBest = CostFunction(Best,self._parameters["QualityCriterion"])
184         #
185         for i in range(self._parameters["NumberOfInsects"]):
186             insect  = numpy.array(PosInsect[:,i].A1)
187             quality = CostFunction(insect,self._parameters["QualityCriterion"])
188             qBestPosInsect.append(quality)
189             if quality < qBest:
190                 Best  = insect
191                 qBest = quality
192         #
193         # Minimisation de la fonctionnelle
194         # --------------------------------
195         for n in range(self._parameters["MaximumNumberOfSteps"]):
196             for i in range(self._parameters["NumberOfInsects"]) :
197                 insect  = PosInsect[:,i]
198                 rp = numpy.random.uniform(size=nbparam)
199                 rg = numpy.random.uniform(size=nbparam)
200                 for j in range(nbparam) :
201                     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])
202                     PosInsect[j,i] = PosInsect[j,i]+VelocityInsect[j,i]
203                 quality = CostFunction(insect,self._parameters["QualityCriterion"])
204                 if quality < qBestPosInsect[i]:
205                     BestPosInsect[:,i] = numpy.ravel( insect )
206                     if quality < qBest :
207                         Best  = numpy.ravel( insect )
208                         qBest = quality
209             #
210             if self._parameters["StoreInternalVariables"]:
211                 self.StoredVariables["CurrentState"].store( Best )
212             self.StoredVariables["CostFunctionJb"].store( 0. )
213             self.StoredVariables["CostFunctionJo"].store( 0. )
214             self.StoredVariables["CostFunctionJ" ].store( qBest )
215         #
216         # Obtention de l'analyse
217         # ----------------------
218         Xa = numpy.asmatrix(numpy.ravel( Best )).T
219         #
220         self.StoredVariables["Analysis"].store( Xa.A1 )
221         #
222         # Calculs et/ou stockages supplémentaires
223         # ---------------------------------------
224         if "Innovation" in self._parameters["StoreSupplementaryCalculations"] or "OMB" in self._parameters["StoreSupplementaryCalculations"]:
225             d = Y - Hm(Xb)
226         if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
227             self.StoredVariables["Innovation"].store( numpy.ravel(d) )
228         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
229             self.StoredVariables["BMA"].store( numpy.ravel(Xb - Xa) )
230         if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
231             self.StoredVariables["OMA"].store( numpy.ravel(Y - Hm(Xa)) )
232         if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
233             self.StoredVariables["OMB"].store( numpy.ravel(d) )
234         #
235         self._post_run(HO)
236         return 0
237
238 # ==============================================================================
239 if __name__ == "__main__":
240     print '\n AUTODIAGNOSTIC \n'