1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2017 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",
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)
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)
125 # Opérateur d'observation
126 # -----------------------
127 Hm = HO["Direct"].appliedTo
129 # Précalcul des inversions de B et R
130 # ----------------------------------
134 # Définition de la fonction de deplacement
135 # ----------------------------------------
136 def Tweak( x, NoiseDistribution, NoiseAddingProbability ):
137 _X = numpy.asmatrix(numpy.ravel( x )).T
138 if NoiseDistribution == "Uniform":
139 for i in xrange(_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
144 elif NoiseDistribution == "Gaussian":
145 for i in xrange(_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
153 def StateInList( x, TL ):
154 _X = numpy.ravel( x )
157 if numpy.all(numpy.abs( _X - numpy.ravel(state) ) <= 1e-16*numpy.abs(_X)):
159 # if _xInList: import sys ; sys.exit()
162 # Minimisation de la fonctionnelle
163 # --------------------------------
166 # _qualityS = CostFunction( _S, self._parameters["QualityCriterion"] )
167 _qualityS = BasicObjects.CostFunction3D(
174 _SSC = self._parameters["StoreSupplementaryCalculations"],
175 _QM = self._parameters["QualityCriterion"],
176 _SSV = self.StoredVariables,
179 _Best, _qualityBest = _S, _qualityS
181 _TabuList.append( _S )
182 while _n < self._parameters["MaximumNumberOfSteps"]:
184 if len(_TabuList) > self._parameters["LengthOfTabuList"]:
186 _R = Tweak( _S, self._parameters["NoiseDistribution"], self._parameters["NoiseAddingProbability"] )
187 # _qualityR = CostFunction( _R, self._parameters["QualityCriterion"] )
188 _qualityR = BasicObjects.CostFunction3D(
195 _SSC = self._parameters["StoreSupplementaryCalculations"],
196 _QM = self._parameters["QualityCriterion"],
197 _SSV = self.StoredVariables,
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(
210 _SSC = self._parameters["StoreSupplementaryCalculations"],
211 _QM = self._parameters["QualityCriterion"],
212 _SSV = self.StoredVariables,
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
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 )
233 # Obtention de l'analyse
234 # ----------------------
235 Xa = numpy.asmatrix(numpy.ravel( _Best )).T
237 self.StoredVariables["Analysis"].store( Xa.A1 )
239 if "Innovation" in self._parameters["StoreSupplementaryCalculations"] or \
240 "OMB" in self._parameters["StoreSupplementaryCalculations"] or \
241 "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
244 if "OMA" in self._parameters["StoreSupplementaryCalculations"] or \
245 "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
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) )
266 # ==============================================================================
267 if __name__ == "__main__":
268 print '\n AUTODIAGNOSTIC \n'