1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2018 EDF R&D
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.
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.
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
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
24 from daCore import BasicObjects
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
30 BasicObjects.Algorithm.__init__(self, "TABUSEARCH")
31 self.defineRequiredParameter(
32 name = "MaximumNumberOfSteps",
35 message = "Nombre maximal de pas d'optimisation",
38 self.defineRequiredParameter(
40 typecast = numpy.random.seed,
41 message = "Graine fixée pour le générateur aléatoire",
43 self.defineRequiredParameter(
44 name = "LengthOfTabuList",
47 message = "Longueur de la liste tabou",
50 self.defineRequiredParameter(
51 name = "NumberOfElementaryPerturbations",
54 message = "Nombre de perturbations élémentaires pour choisir une perturbation d'état",
57 self.defineRequiredParameter(
58 name = "NoiseDistribution",
61 message = "Distribution pour générer les perturbations d'état",
62 listval = ["Gaussian","Uniform"],
64 self.defineRequiredParameter(
65 name = "QualityCriterion",
66 default = "AugmentedWeightedLeastSquares",
68 message = "Critère de qualité utilisé",
69 listval = ["AugmentedWeightedLeastSquares","AWLS","DA",
70 "WeightedLeastSquares","WLS",
71 "LeastSquares","LS","L2",
75 self.defineRequiredParameter(
76 name = "NoiseHalfRange",
78 typecast = numpy.matrix,
79 message = "Demi-amplitude des perturbations uniformes centrées d'état pour chaque composante de l'état",
81 self.defineRequiredParameter(
82 name = "StandardDeviation",
84 typecast = numpy.matrix,
85 message = "Ecart-type des perturbations gaussiennes d'état pour chaque composante de l'état",
87 self.defineRequiredParameter(
88 name = "NoiseAddingProbability",
91 message = "Probabilité de perturbation d'une composante de l'état",
95 self.defineRequiredParameter(
96 name = "StoreInternalVariables",
99 message = "Stockage des variables internes ou intermédiaires du calcul",
101 self.defineRequiredParameter(
102 name = "StoreSupplementaryCalculations",
105 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
106 listval = ["BMA", "OMA", "OMB", "CurrentState", "CostFunctionJ", "CostFunctionJb", "CostFunctionJo", "Innovation", "SimulatedObservationAtBackground", "SimulatedObservationAtCurrentState", "SimulatedObservationAtOptimum"]
108 self.defineRequiredParameter( # Pas de type
110 message = "Liste des valeurs de bornes",
112 self.requireInputArguments(
113 mandatory= ("Xb", "Y", "HO", "R", "B"),
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)
119 if self._parameters["NoiseDistribution"] == "Uniform":
120 nrange = numpy.ravel(self._parameters["NoiseHalfRange"]) # Vecteur
121 if nrange.size != Xb.size:
122 raise ValueError("Noise generation by Uniform distribution requires range for all variable increments. The actual noise half range vector is:\n%s"%nrange)
123 elif self._parameters["NoiseDistribution"] == "Gaussian":
124 sigma = numpy.ravel(self._parameters["StandardDeviation"]) # Vecteur
125 if sigma.size != Xb.size:
126 raise ValueError("Noise generation by Gaussian distribution requires standard deviation for all variable increments. The actual standard deviation vector is:\n%s"%sigma)
128 # Opérateur d'observation
129 # -----------------------
130 Hm = HO["Direct"].appliedTo
132 # Précalcul des inversions de B et R
133 # ----------------------------------
137 # Définition de la fonction de deplacement
138 # ----------------------------------------
139 def Tweak( x, NoiseDistribution, NoiseAddingProbability ):
140 _X = numpy.matrix(numpy.ravel( x )).T
141 if NoiseDistribution == "Uniform":
142 for i in range(_X.size):
143 if NoiseAddingProbability >= numpy.random.uniform():
144 _increment = numpy.random.uniform(low=-nrange[i], high=nrange[i])
145 # On ne traite pas encore le dépassement des bornes ici
147 elif NoiseDistribution == "Gaussian":
148 for i in range(_X.size):
149 if NoiseAddingProbability >= numpy.random.uniform():
150 _increment = numpy.random.normal(loc=0., scale=sigma[i])
151 # On ne traite pas encore le dépassement des bornes ici
156 def StateInList( x, TL ):
157 _X = numpy.ravel( x )
160 if numpy.all(numpy.abs( _X - numpy.ravel(state) ) <= 1e-16*numpy.abs(_X)):
162 # if _xInList: import sys ; sys.exit()
165 # Minimisation de la fonctionnelle
166 # --------------------------------
169 # _qualityS = CostFunction( _S, self._parameters["QualityCriterion"] )
170 _qualityS = BasicObjects.CostFunction3D(
177 _SSC = self._parameters["StoreSupplementaryCalculations"],
178 _QM = self._parameters["QualityCriterion"],
179 _SSV = self.StoredVariables,
182 _Best, _qualityBest = _S, _qualityS
184 _TabuList.append( _S )
185 while _n < self._parameters["MaximumNumberOfSteps"]:
187 if len(_TabuList) > self._parameters["LengthOfTabuList"]:
189 _R = Tweak( _S, self._parameters["NoiseDistribution"], self._parameters["NoiseAddingProbability"] )
190 # _qualityR = CostFunction( _R, self._parameters["QualityCriterion"] )
191 _qualityR = BasicObjects.CostFunction3D(
198 _SSC = self._parameters["StoreSupplementaryCalculations"],
199 _QM = self._parameters["QualityCriterion"],
200 _SSV = self.StoredVariables,
203 for nbt in range(self._parameters["NumberOfElementaryPerturbations"]-1):
204 _W = Tweak( _S, self._parameters["NoiseDistribution"], self._parameters["NoiseAddingProbability"] )
205 # _qualityW = CostFunction( _W, self._parameters["QualityCriterion"] )
206 _qualityW = BasicObjects.CostFunction3D(
213 _SSC = self._parameters["StoreSupplementaryCalculations"],
214 _QM = self._parameters["QualityCriterion"],
215 _SSV = self.StoredVariables,
218 if (not StateInList(_W, _TabuList)) and ( (_qualityW < _qualityR) or StateInList(_R,_TabuList) ):
219 _R, _qualityR = _W, _qualityW
220 if (not StateInList( _R, _TabuList )) and (_qualityR < _qualityS):
221 _S, _qualityS = _R, _qualityR
222 _TabuList.append( _S )
223 if _qualityS < _qualityBest:
224 _Best, _qualityBest = _S, _qualityS
226 if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
227 self.StoredVariables["CurrentState"].store( _Best )
228 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
229 _HmX = Hm( numpy.asmatrix(numpy.ravel( _Best )).T )
230 _HmX = numpy.asmatrix(numpy.ravel( _HmX )).T
231 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HmX )
232 self.StoredVariables["CostFunctionJb"].store( 0. )
233 self.StoredVariables["CostFunctionJo"].store( 0. )
234 self.StoredVariables["CostFunctionJ" ].store( _qualityBest )
236 # Obtention de l'analyse
237 # ----------------------
238 Xa = numpy.asmatrix(numpy.ravel( _Best )).T
240 self.StoredVariables["Analysis"].store( Xa.A1 )
242 if "Innovation" in self._parameters["StoreSupplementaryCalculations"] or \
243 "OMB" in self._parameters["StoreSupplementaryCalculations"] or \
244 "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
247 if "OMA" in self._parameters["StoreSupplementaryCalculations"] or \
248 "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
251 # Calculs et/ou stockages supplémentaires
252 # ---------------------------------------
253 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
254 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
255 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
256 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
257 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
258 self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
259 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
260 self.StoredVariables["OMB"].store( numpy.ravel(d) )
261 if "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
262 self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
263 if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
264 self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
269 # ==============================================================================
270 if __name__ == "__main__":
271 print('\n AUTODIAGNOSTIC \n')