Salome HOME
Python 3 compatibility improvement (UTF-8) and data interface changes
[modules/adao.git] / src / daComposant / daAlgorithms / TabuSearch.py
1 # -*- coding: utf-8 -*-
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
26
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
29     def __init__(self):
30         BasicObjects.Algorithm.__init__(self, "TABUSEARCH")
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     = "LengthOfTabuList",
45             default  = 50,
46             typecast = int,
47             message  = "Longueur de la liste tabou",
48             minval   = 1,
49             )
50         self.defineRequiredParameter(
51             name     = "NumberOfElementaryPerturbations",
52             default  = 1,
53             typecast = int,
54             message  = "Nombre de perturbations élémentaires pour choisir une perturbation d'état",
55             minval   = 1,
56             )
57         self.defineRequiredParameter(
58             name     = "NoiseDistribution",
59             default  = "Uniform",
60             typecast = str,
61             message  = "Distribution pour générer les perturbations d'état",
62             listval  = ["Gaussian","Uniform"],
63             )
64         self.defineRequiredParameter(
65             name     = "QualityCriterion",
66             default  = "AugmentedWeightedLeastSquares",
67             typecast = str,
68             message  = "Critère de qualité utilisé",
69             listval  = ["AugmentedWeightedLeastSquares","AWLS","DA",
70                         "WeightedLeastSquares","WLS",
71                         "LeastSquares","LS","L2",
72                         "AbsoluteValue","L1",
73                         "MaximumError","ME"],
74             )
75         self.defineRequiredParameter(
76             name     = "NoiseHalfRange",
77             default  = [],
78             typecast = numpy.matrix,
79             message  = "Demi-amplitude des perturbations uniformes centrées d'état pour chaque composante de l'état",
80             )
81         self.defineRequiredParameter(
82             name     = "StandardDeviation",
83             default  = [],
84             typecast = numpy.matrix,
85             message  = "Ecart-type des perturbations gaussiennes d'état pour chaque composante de l'état",
86             )
87         self.defineRequiredParameter(
88             name     = "NoiseAddingProbability",
89             default  = 1.,
90             typecast = float,
91             message  = "Probabilité de perturbation d'une composante de l'état",
92             minval   = 0.,
93             maxval   = 1.,
94             )
95         self.defineRequiredParameter(
96             name     = "StoreInternalVariables",
97             default  = False,
98             typecast = bool,
99             message  = "Stockage des variables internes ou intermédiaires du calcul",
100             )
101         self.defineRequiredParameter(
102             name     = "StoreSupplementaryCalculations",
103             default  = [],
104             typecast = tuple,
105             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
106             listval  = ["BMA", "OMA", "OMB", "CurrentState", "CostFunctionJ", "CostFunctionJb", "CostFunctionJo", "Innovation", "SimulatedObservationAtBackground", "SimulatedObservationAtCurrentState", "SimulatedObservationAtOptimum"]
107             )
108         self.defineRequiredParameter( # Pas de type
109             name     = "Bounds",
110             message  = "Liste des valeurs de bornes",
111             )
112
113     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
114         self._pre_run(Parameters)
115         #
116         if self._parameters["NoiseDistribution"] == "Uniform":
117             nrange = numpy.ravel(self._parameters["NoiseHalfRange"]) # Vecteur
118             if nrange.size != Xb.size:
119                 raise ValueError("Noise generation by Uniform distribution requires range for all variable increments. The actual noise half range vector is:\n%s"%nrange)
120         elif self._parameters["NoiseDistribution"] == "Gaussian":
121             sigma = numpy.ravel(self._parameters["StandardDeviation"]) # Vecteur
122             if sigma.size != Xb.size:
123                 raise ValueError("Noise generation by Gaussian distribution requires standard deviation for all variable increments. The actual standard deviation vector is:\n%s"%sigma)
124         #
125         # Opérateur d'observation
126         # -----------------------
127         Hm = HO["Direct"].appliedTo
128         #
129         # Précalcul des inversions de B et R
130         # ----------------------------------
131         BI = B.getI()
132         RI = R.getI()
133         #
134         # Définition de la fonction de deplacement
135         # ----------------------------------------
136         def Tweak( x, NoiseDistribution, NoiseAddingProbability ):
137             _X  = numpy.matrix(numpy.ravel( x )).T
138             if NoiseDistribution == "Uniform":
139                 for i in range(_X.size):
140                     if NoiseAddingProbability >= numpy.random.uniform():
141                         _increment = numpy.random.uniform(low=-nrange[i], high=nrange[i])
142                         # On ne traite pas encore le dépassement des bornes ici
143                         _X[i] += _increment
144             elif NoiseDistribution == "Gaussian":
145                 for i in range(_X.size):
146                     if NoiseAddingProbability >= numpy.random.uniform():
147                         _increment = numpy.random.normal(loc=0., scale=sigma[i])
148                         # On ne traite pas encore le dépassement des bornes ici
149                         _X[i] += _increment
150             #
151             return _X
152         #
153         def StateInList( x, TL ):
154             _X  = numpy.ravel( x )
155             _xInList = False
156             for state in TL:
157                 if numpy.all(numpy.abs( _X - numpy.ravel(state) ) <= 1e-16*numpy.abs(_X)):
158                     _xInList = True
159             # if _xInList: import sys ; sys.exit()
160             return _xInList
161         #
162         # Minimisation de la fonctionnelle
163         # --------------------------------
164         _n = 0
165         _S = Xb
166         # _qualityS = CostFunction( _S, self._parameters["QualityCriterion"] )
167         _qualityS = BasicObjects.CostFunction3D(
168                    _S,
169             _Hm  = Hm,
170             _BI  = BI,
171             _RI  = RI,
172             _Xb  = Xb,
173             _Y   = Y,
174             _SSC = self._parameters["StoreSupplementaryCalculations"],
175             _QM  = self._parameters["QualityCriterion"],
176             _SSV = self.StoredVariables,
177             _sSc = False,
178             )
179         _Best, _qualityBest   =   _S, _qualityS
180         _TabuList = []
181         _TabuList.append( _S )
182         while _n < self._parameters["MaximumNumberOfSteps"]:
183             _n += 1
184             if len(_TabuList) > self._parameters["LengthOfTabuList"]:
185                 _TabuList.pop(0)
186             _R = Tweak( _S, self._parameters["NoiseDistribution"], self._parameters["NoiseAddingProbability"] )
187             # _qualityR = CostFunction( _R, self._parameters["QualityCriterion"] )
188             _qualityR = BasicObjects.CostFunction3D(
189                        _R,
190                 _Hm  = Hm,
191                 _BI  = BI,
192                 _RI  = RI,
193                 _Xb  = Xb,
194                 _Y   = Y,
195                 _SSC = self._parameters["StoreSupplementaryCalculations"],
196                 _QM  = self._parameters["QualityCriterion"],
197                 _SSV = self.StoredVariables,
198                 _sSc = False,
199                 )
200             for nbt in range(self._parameters["NumberOfElementaryPerturbations"]-1):
201                 _W = Tweak( _S, self._parameters["NoiseDistribution"], self._parameters["NoiseAddingProbability"] )
202                 # _qualityW = CostFunction( _W, self._parameters["QualityCriterion"] )
203                 _qualityW = BasicObjects.CostFunction3D(
204                            _W,
205                     _Hm  = Hm,
206                     _BI  = BI,
207                     _RI  = RI,
208                     _Xb  = Xb,
209                     _Y   = Y,
210                     _SSC = self._parameters["StoreSupplementaryCalculations"],
211                     _QM  = self._parameters["QualityCriterion"],
212                     _SSV = self.StoredVariables,
213                     _sSc = False,
214                     )
215                 if (not StateInList(_W, _TabuList)) and ( (_qualityW < _qualityR) or StateInList(_R,_TabuList) ):
216                     _R, _qualityR   =   _W, _qualityW
217             if (not StateInList( _R, _TabuList )) and (_qualityR < _qualityS):
218                 _S, _qualityS   =   _R, _qualityR
219                 _TabuList.append( _S )
220             if _qualityS < _qualityBest:
221                 _Best, _qualityBest   =   _S, _qualityS
222             #
223             if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
224                 self.StoredVariables["CurrentState"].store( _Best )
225             if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
226                 _HmX = Hm( numpy.asmatrix(numpy.ravel( _Best )).T )
227                 _HmX = numpy.asmatrix(numpy.ravel( _HmX )).T
228                 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HmX )
229             self.StoredVariables["CostFunctionJb"].store( 0. )
230             self.StoredVariables["CostFunctionJo"].store( 0. )
231             self.StoredVariables["CostFunctionJ" ].store( _qualityBest )
232         #
233         # Obtention de l'analyse
234         # ----------------------
235         Xa = numpy.asmatrix(numpy.ravel( _Best )).T
236         #
237         self.StoredVariables["Analysis"].store( Xa.A1 )
238         #
239         if "Innovation"                       in self._parameters["StoreSupplementaryCalculations"] or \
240            "OMB"                              in self._parameters["StoreSupplementaryCalculations"] or \
241            "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
242             HXb = Hm(Xb)
243             d = Y - HXb
244         if "OMA"                           in self._parameters["StoreSupplementaryCalculations"] or \
245            "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
246             HXa = Hm(Xa)
247         #
248         # Calculs et/ou stockages supplémentaires
249         # ---------------------------------------
250         if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
251             self.StoredVariables["Innovation"].store( numpy.ravel(d) )
252         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
253             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
254         if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
255             self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
256         if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
257             self.StoredVariables["OMB"].store( numpy.ravel(d) )
258         if "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
259             self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
260         if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
261             self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
262         #
263         self._post_run(HO)
264         return 0
265
266 # ==============================================================================
267 if __name__ == "__main__":
268     print('\n AUTODIAGNOSTIC \n')