1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2021 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
23 import copy, logging, itertools
25 from daCore import BasicObjects
26 from daCore.PlatformInfo import PlatformInfo
27 mfp = PlatformInfo().MaximumPrecision()
29 # ==============================================================================
30 class ElementaryAlgorithm(BasicObjects.Algorithm):
32 BasicObjects.Algorithm.__init__(self, "SAMPLINGTEST")
33 self.defineRequiredParameter(
34 name = "SampleAsnUplet",
37 message = "Points de calcul définis par une liste de n-uplet",
39 self.defineRequiredParameter(
40 name = "SampleAsExplicitHyperCube",
43 message = "Points de calcul définis par un hyper-cube dont on donne la liste des échantillonages de chaque variable comme une liste",
45 self.defineRequiredParameter(
46 name = "SampleAsMinMaxStepHyperCube",
49 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]",
51 self.defineRequiredParameter(
52 name = "SampleAsIndependantRandomVariables",
55 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]",
57 self.defineRequiredParameter(
58 name = "QualityCriterion",
59 default = "AugmentedWeightedLeastSquares",
61 message = "Critère de qualité utilisé",
62 listval = ["AugmentedWeightedLeastSquares","AWLS","AugmentedPonderatedLeastSquares","APLS","DA",
63 "WeightedLeastSquares","WLS","PonderatedLeastSquares","PLS",
64 "LeastSquares","LS","L2",
68 self.defineRequiredParameter(
72 message = "Activation du mode debug lors de l'exécution",
74 self.defineRequiredParameter(
75 name = "StoreSupplementaryCalculations",
78 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
84 "InnovationAtCurrentState",
85 "SimulatedObservationAtCurrentState",
88 self.defineRequiredParameter(
90 typecast = numpy.random.seed,
91 message = "Graine fixée pour le générateur aléatoire",
93 self.requireInputArguments(
94 mandatory= ("Xb", "HO"),
96 self.setAttributes(tags=(
100 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
101 self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
103 Hm = HO["Direct"].appliedTo
105 X0 = numpy.ravel( Xb )
106 Y0 = numpy.ravel( Y )
108 # ---------------------------
109 if len(self._parameters["SampleAsnUplet"]) > 0:
110 sampleList = self._parameters["SampleAsnUplet"]
111 for i,Xx in enumerate(sampleList):
112 if numpy.ravel(Xx).size != X0.size:
113 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,X0.size))
114 elif len(self._parameters["SampleAsExplicitHyperCube"]) > 0:
115 sampleList = itertools.product(*list(self._parameters["SampleAsExplicitHyperCube"]))
116 elif len(self._parameters["SampleAsMinMaxStepHyperCube"]) > 0:
118 for i,dim in enumerate(self._parameters["SampleAsMinMaxStepHyperCube"]):
120 raise ValueError("For dimension %i, the variable definition \"%s\" is incorrect, it should be [min,max,step]."%(i,dim))
122 coordinatesList.append(numpy.linspace(dim[0],dim[1],1+int((float(dim[1])-float(dim[0]))/float(dim[2]))))
123 sampleList = itertools.product(*coordinatesList)
124 elif len(self._parameters["SampleAsIndependantRandomVariables"]) > 0:
126 for i,dim in enumerate(self._parameters["SampleAsIndependantRandomVariables"]):
128 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))
129 elif not( str(dim[0]) in ['normal','lognormal','uniform','weibull'] and hasattr(numpy.random,dim[0]) ):
130 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]))
132 distribution = getattr(numpy.random,str(dim[0]),'normal')
134 coordinatesList.append(distribution(*dim[1], size=max(1,int(dim[2]))))
135 sampleList = itertools.product(*coordinatesList)
137 sampleList = iter([X0,])
141 def CostFunction(x, HmX, QualityMeasure="AugmentedWeightedLeastSquares"):
142 if numpy.any(numpy.isnan(HmX)):
145 Jb, Jo, J = numpy.nan, numpy.nan, numpy.nan
147 _X = numpy.ravel( x )
148 _HX = numpy.ravel( HmX )
149 if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","AugmentedPonderatedLeastSquares","APLS","DA"]:
150 if BI is None or RI is None:
151 raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
152 Jb = float( 0.5 * (_X - X0).T * (BI * (_X - X0)) )
153 Jo = float( 0.5 * (Y0 - _HX).T * (RI * (Y0 - _HX)) )
154 elif QualityMeasure in ["WeightedLeastSquares","WLS","PonderatedLeastSquares","PLS"]:
156 raise ValueError("Observation error covariance matrix has to be properly defined!")
158 Jo = float( 0.5 * (Y0 - _HX).T * (RI * (Y0 - _HX)) )
159 elif QualityMeasure in ["LeastSquares","LS","L2"]:
161 Jo = float( 0.5 * (Y0 - _HX).T @ (Y0 - _HX) )
162 elif QualityMeasure in ["AbsoluteValue","L1"]:
164 Jo = float( numpy.sum( numpy.abs(Y0 - _HX), dtype=mfp ) )
165 elif QualityMeasure in ["MaximumError","ME"]:
167 Jo = numpy.max( numpy.abs(Y0 - _HX) )
170 if self._toStore("CurrentState"):
171 self.StoredVariables["CurrentState"].store( _X )
172 if self._toStore("InnovationAtCurrentState"):
173 self.StoredVariables["InnovationAtCurrentState"].store( Y0 - _HX )
174 if self._toStore("SimulatedObservationAtCurrentState"):
175 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
176 self.StoredVariables["CostFunctionJb"].store( Jb )
177 self.StoredVariables["CostFunctionJo"].store( Jo )
178 self.StoredVariables["CostFunctionJ" ].store( J )
181 if self._parameters["SetDebug"]:
182 CUR_LEVEL = logging.getLogger().getEffectiveLevel()
183 logging.getLogger().setLevel(logging.DEBUG)
184 print("===> Beginning of evaluation, activating debug\n")
185 print(" %s\n"%("-"*75,))
188 for i,Xx in enumerate(sampleList):
189 if self._parameters["SetDebug"]:
190 print("===> Launching evaluation for state %i"%i)
192 Yy = Hm( numpy.ravel( Xx ) )
196 J, Jb, Jo = CostFunction( Xx, Yy, self._parameters["QualityCriterion"])
199 if self._parameters["SetDebug"]:
200 print("\n %s\n"%("-"*75,))
201 print("===> End evaluation, deactivating debug if necessary\n")
202 logging.getLogger().setLevel(CUR_LEVEL)
207 # ==============================================================================
208 if __name__ == "__main__":
209 print('\n AUTODIAGNOSTIC\n')