1 # -*- coding: utf-8 -*-
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
25 import numpy, copy, itertools
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
30 BasicObjects.Algorithm.__init__(self, "SAMPLINGTEST")
31 self.defineRequiredParameter(
32 name = "SampleAsnUplet",
35 message = "Points de calcul définis par une liste de n-uplet",
37 self.defineRequiredParameter(
38 name = "SampleAsExplicitHyperCube",
41 message = "Points de calcul définis par un hyper-cube dont on donne la liste des échantillonages de chaque variable comme une liste",
43 self.defineRequiredParameter(
44 name = "SampleAsMinMaxStepHyperCube",
47 message = "Points de calcul définis par un hyper-cube dont on donne la liste des échantillonages de chaque variable par un triplet [min,max,step]",
49 self.defineRequiredParameter(
50 name = "SampleAsIndependantRandomVariables",
53 message = "Points de calcul définis par un hyper-cube dont les points sur chaque axe proviennent de l'échantillonage indépendant de la variable selon la spécification ['distribution',[parametres],nombre]",
55 self.defineRequiredParameter(
56 name = "QualityCriterion",
57 default = "AugmentedWeightedLeastSquares",
59 message = "Critère de qualité utilisé",
60 listval = ["AugmentedWeightedLeastSquares","AWLS","AugmentedPonderatedLeastSquares","APLS","DA",
61 "WeightedLeastSquares","WLS","PonderatedLeastSquares","PLS",
62 "LeastSquares","LS","L2",
66 self.defineRequiredParameter(
70 message = "Activation du mode debug lors de l'exécution",
72 self.defineRequiredParameter(
73 name = "StoreSupplementaryCalculations",
76 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
77 listval = ["CostFunctionJ", "CostFunctionJb", "CostFunctionJo","CurrentState","InnovationAtCurrentState","SimulatedObservationAtCurrentState"]
79 self.defineRequiredParameter(
81 typecast = numpy.random.seed,
82 message = "Graine fixée pour le générateur aléatoire",
84 self.requireInputArguments(
85 mandatory= ("Xb", "HO"),
88 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
89 self._pre_run(Parameters, Xb, Y, R, B, Q)
91 Hm = HO["Direct"].appliedTo
95 # ---------------------------
96 if len(self._parameters["SampleAsnUplet"]) > 0:
97 sampleList = self._parameters["SampleAsnUplet"]
98 for i,Xx in enumerate(sampleList):
99 if numpy.ravel(Xx).size != Xn.size:
100 raise ValueError("The size %i of the %ith state X in the sample and %i of the checking point Xb are different, they have to be identical."%(numpy.ravel(Xx).size,i+1,Xn.size))
101 elif len(self._parameters["SampleAsExplicitHyperCube"]) > 0:
102 sampleList = itertools.product(*list(self._parameters["SampleAsExplicitHyperCube"]))
103 elif len(self._parameters["SampleAsMinMaxStepHyperCube"]) > 0:
105 for i,dim in enumerate(self._parameters["SampleAsMinMaxStepHyperCube"]):
107 raise ValueError("For dimension %i, the variable definition \"%s\" is incorrect, it should be [min,max,step]."%(i,dim))
109 coordinatesList.append(numpy.linspace(dim[0],dim[1],1+int((float(dim[1])-float(dim[0]))/float(dim[2]))))
110 sampleList = itertools.product(*coordinatesList)
111 elif len(self._parameters["SampleAsIndependantRandomVariables"]) > 0:
113 for i,dim in enumerate(self._parameters["SampleAsIndependantRandomVariables"]):
115 raise ValueError("For dimension %i, the variable definition \"%s\" is incorrect, it should be ('distribution',(parameters),length) with distribution in ['normal'(mean,std),'lognormal'(mean,sigma),'uniform'(low,high),'weibull'(shape)]."%(i,dim))
116 elif not( str(dim[0]) in ['normal','lognormal','uniform','weibull'] and hasattr(numpy.random,dim[0]) ):
117 raise ValueError("For dimension %i, the distribution name \"%s\" is not allowed, please choose in ['normal'(mean,std),'lognormal'(mean,sigma),'uniform'(low,high),'weibull'(shape)]"%(i,dim[0]))
119 distribution = getattr(numpy.random,str(dim[0]),'normal')
121 coordinatesList.append(distribution(*dim[1], size=max(1,int(dim[2]))))
122 sampleList = itertools.product(*coordinatesList)
124 sampleList = iter([Xn,])
128 def CostFunction(x, HmX, QualityMeasure="AugmentedWeightedLeastSquares"):
129 if numpy.any(numpy.isnan(HmX)):
132 Jb, Jo, J = numpy.nan, numpy.nan, numpy.nan
134 _X = numpy.asmatrix(numpy.ravel( x )).T
135 _HX = numpy.asmatrix(numpy.ravel( HmX )).T
136 if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","AugmentedPonderatedLeastSquares","APLS","DA"]:
137 if BI is None or RI is None:
138 raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
139 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
140 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
141 elif QualityMeasure in ["WeightedLeastSquares","WLS","PonderatedLeastSquares","PLS"]:
143 raise ValueError("Observation error covariance matrix has to be properly defined!")
145 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
146 elif QualityMeasure in ["LeastSquares","LS","L2"]:
148 Jo = 0.5 * (Y - _HX).T * (Y - _HX)
149 elif QualityMeasure in ["AbsoluteValue","L1"]:
151 Jo = numpy.sum( numpy.abs(Y - _HX) )
152 elif QualityMeasure in ["MaximumError","ME"]:
154 Jo = numpy.max( numpy.abs(Y - _HX) )
156 J = float( Jb ) + float( Jo )
157 if "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
158 self.StoredVariables["CurrentState"].store( _X )
159 if "InnovationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
160 self.StoredVariables["InnovationAtCurrentState"].store( Y - _HX )
161 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
162 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
163 self.StoredVariables["CostFunctionJb"].store( Jb )
164 self.StoredVariables["CostFunctionJo"].store( Jo )
165 self.StoredVariables["CostFunctionJ" ].store( J )
168 if self._parameters["SetDebug"]:
169 CUR_LEVEL = logging.getLogger().getEffectiveLevel()
170 logging.getLogger().setLevel(logging.DEBUG)
171 print("===> Beginning of evaluation, activating debug\n")
172 print(" %s\n"%("-"*75,))
175 for i,Xx in enumerate(sampleList):
176 if self._parameters["SetDebug"]:
177 print("===> Launching evaluation for state %i"%i)
178 __Xn = numpy.asmatrix(numpy.ravel( Xx )).T
184 J, Jb, Jo = CostFunction(__Xn,Yn,self._parameters["QualityCriterion"])
187 if self._parameters["SetDebug"]:
188 print("\n %s\n"%("-"*75,))
189 print("===> End evaluation, deactivating debug if necessary\n")
190 logging.getLogger().setLevel(CUR_LEVEL)
195 # ==============================================================================
196 if __name__ == "__main__":
197 print('\n AUTODIAGNOSTIC \n')