Salome HOME
Update and documentation of InputValuesTest
[modules/adao.git] / src / daComposant / daAlgorithms / SamplingTest.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2020 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 logging
24 from daCore import BasicObjects
25 import numpy, copy, itertools
26
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
29     def __init__(self):
30         BasicObjects.Algorithm.__init__(self, "SAMPLINGTEST")
31         self.defineRequiredParameter(
32             name     = "SampleAsnUplet",
33             default  = [],
34             typecast = tuple,
35             message  = "Points de calcul définis par une liste de n-uplet",
36             )
37         self.defineRequiredParameter(
38             name     = "SampleAsExplicitHyperCube",
39             default  = [],
40             typecast = tuple,
41             message  = "Points de calcul définis par un hyper-cube dont on donne la liste des échantillonages de chaque variable comme une liste",
42             )
43         self.defineRequiredParameter(
44             name     = "SampleAsMinMaxStepHyperCube",
45             default  = [],
46             typecast = tuple,
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]",
48             )
49         self.defineRequiredParameter(
50             name     = "SampleAsIndependantRandomVariables",
51             default  = [],
52             typecast = tuple,
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]",
54             )
55         self.defineRequiredParameter(
56             name     = "QualityCriterion",
57             default  = "AugmentedWeightedLeastSquares",
58             typecast = str,
59             message  = "Critère de qualité utilisé",
60             listval  = ["AugmentedWeightedLeastSquares","AWLS","AugmentedPonderatedLeastSquares","APLS","DA",
61                         "WeightedLeastSquares","WLS","PonderatedLeastSquares","PLS",
62                         "LeastSquares","LS","L2",
63                         "AbsoluteValue","L1",
64                         "MaximumError","ME"],
65             )
66         self.defineRequiredParameter(
67             name     = "SetDebug",
68             default  = False,
69             typecast = bool,
70             message  = "Activation du mode debug lors de l'exécution",
71             )
72         self.defineRequiredParameter(
73             name     = "StoreSupplementaryCalculations",
74             default  = [],
75             typecast = tuple,
76             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
77             listval  = [
78                 "CostFunctionJ",
79                 "CostFunctionJb",
80                 "CostFunctionJo",
81                 "CurrentState",
82                 "InnovationAtCurrentState",
83                 "SimulatedObservationAtCurrentState",
84                 ]
85             )
86         self.defineRequiredParameter(
87             name     = "SetSeed",
88             typecast = numpy.random.seed,
89             message  = "Graine fixée pour le générateur aléatoire",
90             )
91         self.requireInputArguments(
92             mandatory= ("Xb", "HO"),
93             )
94
95     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
96         self._pre_run(Parameters, Xb, Y, R, B, Q)
97         #
98         Hm = HO["Direct"].appliedTo
99         #
100         Xn = copy.copy( Xb )
101         #
102         # ---------------------------
103         if len(self._parameters["SampleAsnUplet"]) > 0:
104             sampleList = self._parameters["SampleAsnUplet"]
105             for i,Xx in enumerate(sampleList):
106                 if numpy.ravel(Xx).size != Xn.size:
107                     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))
108         elif len(self._parameters["SampleAsExplicitHyperCube"]) > 0:
109             sampleList = itertools.product(*list(self._parameters["SampleAsExplicitHyperCube"]))
110         elif len(self._parameters["SampleAsMinMaxStepHyperCube"]) > 0:
111             coordinatesList = []
112             for i,dim in enumerate(self._parameters["SampleAsMinMaxStepHyperCube"]):
113                 if len(dim) != 3:
114                     raise ValueError("For dimension %i, the variable definition \"%s\" is incorrect, it should be [min,max,step]."%(i,dim))
115                 else:
116                     coordinatesList.append(numpy.linspace(dim[0],dim[1],1+int((float(dim[1])-float(dim[0]))/float(dim[2]))))
117             sampleList = itertools.product(*coordinatesList)
118         elif len(self._parameters["SampleAsIndependantRandomVariables"]) > 0:
119             coordinatesList = []
120             for i,dim in enumerate(self._parameters["SampleAsIndependantRandomVariables"]):
121                 if len(dim) != 3:
122                     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))
123                 elif not( str(dim[0]) in ['normal','lognormal','uniform','weibull'] and hasattr(numpy.random,dim[0]) ):
124                     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]))
125                 else:
126                     distribution = getattr(numpy.random,str(dim[0]),'normal')
127                     parameters   = dim[1]
128                     coordinatesList.append(distribution(*dim[1], size=max(1,int(dim[2]))))
129             sampleList = itertools.product(*coordinatesList)
130         else:
131             sampleList = iter([Xn,])
132         # ----------
133         BI = B.getI()
134         RI = R.getI()
135         def CostFunction(x, HmX, QualityMeasure="AugmentedWeightedLeastSquares"):
136             if numpy.any(numpy.isnan(HmX)):
137                 _X  = numpy.nan
138                 _HX = numpy.nan
139                 Jb, Jo, J = numpy.nan, numpy.nan, numpy.nan
140             else:
141                 _X  = numpy.asmatrix(numpy.ravel( x )).T
142                 _HX = numpy.asmatrix(numpy.ravel( HmX )).T
143                 if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","AugmentedPonderatedLeastSquares","APLS","DA"]:
144                     if BI is None or RI is None:
145                         raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
146                     Jb  = 0.5 * (_X - Xb).T * BI * (_X - Xb)
147                     Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
148                 elif QualityMeasure in ["WeightedLeastSquares","WLS","PonderatedLeastSquares","PLS"]:
149                     if RI is None:
150                         raise ValueError("Observation error covariance matrix has to be properly defined!")
151                     Jb  = 0.
152                     Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
153                 elif QualityMeasure in ["LeastSquares","LS","L2"]:
154                     Jb  = 0.
155                     Jo  = 0.5 * (Y - _HX).T * (Y - _HX)
156                 elif QualityMeasure in ["AbsoluteValue","L1"]:
157                     Jb  = 0.
158                     Jo  = numpy.sum( numpy.abs(Y - _HX) )
159                 elif QualityMeasure in ["MaximumError","ME"]:
160                     Jb  = 0.
161                     Jo  = numpy.max( numpy.abs(Y - _HX) )
162                 #
163                 J   = float( Jb ) + float( Jo )
164             if self._toStore("CurrentState"):
165                 self.StoredVariables["CurrentState"].store( _X )
166             if self._toStore("InnovationAtCurrentState"):
167                 self.StoredVariables["InnovationAtCurrentState"].store( Y - _HX )
168             if self._toStore("SimulatedObservationAtCurrentState"):
169                 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
170             self.StoredVariables["CostFunctionJb"].store( Jb )
171             self.StoredVariables["CostFunctionJo"].store( Jo )
172             self.StoredVariables["CostFunctionJ" ].store( J )
173             return J, Jb, Jo
174         # ----------
175         if self._parameters["SetDebug"]:
176             CUR_LEVEL = logging.getLogger().getEffectiveLevel()
177             logging.getLogger().setLevel(logging.DEBUG)
178             print("===> Beginning of evaluation, activating debug\n")
179             print("     %s\n"%("-"*75,))
180         #
181         # ----------
182         for i,Xx in enumerate(sampleList):
183             if self._parameters["SetDebug"]:
184                 print("===> Launching evaluation for state %i"%i)
185             __Xn = numpy.asmatrix(numpy.ravel( Xx )).T
186             try:
187                 Yn = Hm( __Xn )
188             except:
189                 Yn = numpy.nan
190             #
191             J, Jb, Jo = CostFunction(__Xn,Yn,self._parameters["QualityCriterion"])
192         # ----------
193         #
194         if self._parameters["SetDebug"]:
195             print("\n     %s\n"%("-"*75,))
196             print("===> End evaluation, deactivating debug if necessary\n")
197             logging.getLogger().setLevel(CUR_LEVEL)
198         #
199         self._post_run(HO)
200         return 0
201
202 # ==============================================================================
203 if __name__ == "__main__":
204     print('\n AUTODIAGNOSTIC\n')