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