Salome HOME
Minor improvements and fixes for internal variables
[modules/adao.git] / src / daComposant / daAlgorithms / SamplingTest.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2021 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 copy, logging, itertools
24 import numpy
25 from daCore import BasicObjects
26 from daCore.PlatformInfo import PlatformInfo
27 mfp = PlatformInfo().MaximumPrecision()
28
29 # ==============================================================================
30 class ElementaryAlgorithm(BasicObjects.Algorithm):
31     def __init__(self):
32         BasicObjects.Algorithm.__init__(self, "SAMPLINGTEST")
33         self.defineRequiredParameter(
34             name     = "SampleAsnUplet",
35             default  = [],
36             typecast = tuple,
37             message  = "Points de calcul définis par une liste de n-uplet",
38             )
39         self.defineRequiredParameter(
40             name     = "SampleAsExplicitHyperCube",
41             default  = [],
42             typecast = tuple,
43             message  = "Points de calcul définis par un hyper-cube dont on donne la liste des échantillonages de chaque variable comme une liste",
44             )
45         self.defineRequiredParameter(
46             name     = "SampleAsMinMaxStepHyperCube",
47             default  = [],
48             typecast = tuple,
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]",
50             )
51         self.defineRequiredParameter(
52             name     = "SampleAsIndependantRandomVariables",
53             default  = [],
54             typecast = tuple,
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]",
56             )
57         self.defineRequiredParameter(
58             name     = "QualityCriterion",
59             default  = "AugmentedWeightedLeastSquares",
60             typecast = str,
61             message  = "Critère de qualité utilisé",
62             listval  = ["AugmentedWeightedLeastSquares","AWLS","AugmentedPonderatedLeastSquares","APLS","DA",
63                         "WeightedLeastSquares","WLS","PonderatedLeastSquares","PLS",
64                         "LeastSquares","LS","L2",
65                         "AbsoluteValue","L1",
66                         "MaximumError","ME"],
67             )
68         self.defineRequiredParameter(
69             name     = "SetDebug",
70             default  = False,
71             typecast = bool,
72             message  = "Activation du mode debug lors de l'exécution",
73             )
74         self.defineRequiredParameter(
75             name     = "StoreSupplementaryCalculations",
76             default  = [],
77             typecast = tuple,
78             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
79             listval  = [
80                 "CostFunctionJ",
81                 "CostFunctionJb",
82                 "CostFunctionJo",
83                 "CurrentState",
84                 "InnovationAtCurrentState",
85                 "SimulatedObservationAtCurrentState",
86                 ]
87             )
88         self.defineRequiredParameter(
89             name     = "SetSeed",
90             typecast = numpy.random.seed,
91             message  = "Graine fixée pour le générateur aléatoire",
92             )
93         self.requireInputArguments(
94             mandatory= ("Xb", "HO"),
95             )
96         self.setAttributes(tags=(
97             "Checking",
98             ))
99
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)
102         #
103         Hm = HO["Direct"].appliedTo
104         #
105         X0 = numpy.ravel( Xb )
106         Y0 = numpy.ravel( Y  )
107         #
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:
117             coordinatesList = []
118             for i,dim in enumerate(self._parameters["SampleAsMinMaxStepHyperCube"]):
119                 if len(dim) != 3:
120                     raise ValueError("For dimension %i, the variable definition \"%s\" is incorrect, it should be [min,max,step]."%(i,dim))
121                 else:
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:
125             coordinatesList = []
126             for i,dim in enumerate(self._parameters["SampleAsIndependantRandomVariables"]):
127                 if len(dim) != 3:
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]))
131                 else:
132                     distribution = getattr(numpy.random,str(dim[0]),'normal')
133                     parameters   = dim[1]
134                     coordinatesList.append(distribution(*dim[1], size=max(1,int(dim[2]))))
135             sampleList = itertools.product(*coordinatesList)
136         else:
137             sampleList = iter([X0,])
138         # ----------
139         BI = B.getI()
140         RI = R.getI()
141         def CostFunction(x, HmX, QualityMeasure="AugmentedWeightedLeastSquares"):
142             if numpy.any(numpy.isnan(HmX)):
143                 _X  = numpy.nan
144                 _HX = numpy.nan
145                 Jb, Jo, J = numpy.nan, numpy.nan, numpy.nan
146             else:
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"]:
155                     if RI is None:
156                         raise ValueError("Observation error covariance matrix has to be properly defined!")
157                     Jb  = 0.
158                     Jo  = float( 0.5 * (Y0 - _HX).T * (RI * (Y0 - _HX)) )
159                 elif QualityMeasure in ["LeastSquares","LS","L2"]:
160                     Jb  = 0.
161                     Jo  = float( 0.5 * (Y0 - _HX).T @ (Y0 - _HX) )
162                 elif QualityMeasure in ["AbsoluteValue","L1"]:
163                     Jb  = 0.
164                     Jo  = float( numpy.sum( numpy.abs(Y0 - _HX), dtype=mfp ) )
165                 elif QualityMeasure in ["MaximumError","ME"]:
166                     Jb  = 0.
167                     Jo  = numpy.max( numpy.abs(Y0 - _HX) )
168                 #
169                 J   = Jb + Jo
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 )
179             return J, Jb, Jo
180         # ----------
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,))
186         #
187         # ----------
188         for i,Xx in enumerate(sampleList):
189             if self._parameters["SetDebug"]:
190                 print("===> Launching evaluation for state %i"%i)
191             try:
192                 Yy = Hm( numpy.ravel( Xx ) )
193             except:
194                 Yy = numpy.nan
195             #
196             J, Jb, Jo = CostFunction( Xx, Yy,  self._parameters["QualityCriterion"])
197         # ----------
198         #
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)
203         #
204         self._post_run(HO)
205         return 0
206
207 # ==============================================================================
208 if __name__ == "__main__":
209     print('\n AUTODIAGNOSTIC\n')