Salome HOME
b14133db85b03d5b95a0d4effcb4f61414a6e1e1
[modules/adao.git] / src / daComposant / daAlgorithms / SamplingTest.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2014 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 = list,
35             message  = "Points de calcul définis par une liste de n-uplet",
36             )
37         self.defineRequiredParameter(
38             name     = "SampleAsExplicitHyperCube",
39             default  = [],
40             typecast = list,
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 = list,
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     = "SetDebug",
51             default  = False,
52             typecast = bool,
53             message  = "Activation du mode debug lors de l'exécution",
54             )
55         self.defineRequiredParameter(
56             name     = "StoreSupplementaryCalculations",
57             default  = [],
58             typecast = tuple,
59             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
60             listval  = ["CostFunctionJ","CurrentState","Innovation","ObservedState"]
61             )
62
63     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
64         self._pre_run()
65         #
66         self.setParameters(Parameters)
67         #
68         Hm = HO["Direct"].appliedTo
69         #
70         Xn = copy.copy( Xb )
71         #
72         # ---------------------------
73         if len(self._parameters["SampleAsnUplet"]) > 0:
74             sampleList = self._parameters["SampleAsnUplet"]
75             for i,Xx in enumerate(sampleList):
76                 if numpy.ravel(Xx).size != Xn.size:
77                     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))
78         elif len(self._parameters["SampleAsExplicitHyperCube"]) > 0:
79             sampleList = itertools.product(*list(self._parameters["SampleAsExplicitHyperCube"]))
80         elif len(self._parameters["SampleAsMinMaxStepHyperCube"]) > 0:
81             coordinatesList = []
82             for i,dim in enumerate(self._parameters["SampleAsMinMaxStepHyperCube"]):
83                 if len(dim) != 3:
84                     raise ValueError("For dimension %i, the variable definition %s is incorrect, it should be [min,max,step]."%(i,dim))
85                 else:
86                     coordinatesList.append(numpy.linspace(*dim))
87             sampleList = itertools.product(*coordinatesList)
88         else:
89             sampleList = iter([Xn,])
90         # ----------
91         BI = B.getI()
92         RI = R.getI()
93         def CostFunction(x,HmX):
94             if numpy.any(numpy.isnan(HmX)):
95                 _X  = numpy.nan
96                 _HX = numpy.nan
97                 Jb, Jo, J = numpy.nan, numpy.nan, numpy.nan
98             else:
99                 _X  = numpy.asmatrix(numpy.ravel( x )).T
100                 _HX = numpy.asmatrix(numpy.ravel( HmX )).T
101                 Jb  = 0.5 * (_X - Xb).T * BI * (_X - Xb)
102                 Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
103                 J   = float( Jb ) + float( Jo )
104             if "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
105                 self.StoredVariables["CurrentState"].store( _X )
106             if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
107                 self.StoredVariables["Innovation"].store( Y - _HX )
108             if "ObservedState" in self._parameters["StoreSupplementaryCalculations"]:
109                 self.StoredVariables["ObservedState"].store( _HX )
110             self.StoredVariables["CostFunctionJb"].store( Jb )
111             self.StoredVariables["CostFunctionJo"].store( Jo )
112             self.StoredVariables["CostFunctionJ" ].store( J )
113             return J, Jb, Jo
114         # ----------
115         if self._parameters["SetDebug"]:
116             CUR_LEVEL = logging.getLogger().getEffectiveLevel()
117             logging.getLogger().setLevel(logging.DEBUG)
118             print("===> Beginning of evaluation, activating debug\n")
119             print("     %s\n"%("-"*75,))
120         #
121         # ----------
122         for i,Xx in enumerate(sampleList):
123             if self._parameters["SetDebug"]:
124                 print("===> Launching evaluation for state %i"%i)
125             __Xn = numpy.asmatrix(numpy.ravel( Xx )).T
126             try:
127                 Yn = Hm( __Xn )
128             except:
129                 Yn = numpy.nan
130             #
131             J, Jb, Jo = CostFunction(__Xn,Yn)
132         # ----------
133         #
134         if self._parameters["SetDebug"]:
135             print("\n     %s\n"%("-"*75,))
136             print("===> End evaluation, deactivating debug if necessary\n")
137             logging.getLogger().setLevel(CUR_LEVEL)
138         #
139         self._post_run(HO)
140         return 0
141
142 # ==============================================================================
143 if __name__ == "__main__":
144     print '\n AUTODIAGNOSTIC \n'