Salome HOME
Updating copyright date information (1)
[modules/adao.git] / src / daComposant / daAlgorithms / FunctionTest.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2018 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 sys, logging
24 from daCore import BasicObjects, PlatformInfo
25 import numpy, copy
26 mpr = PlatformInfo.PlatformInfo().MachinePrecision()
27 mfp = PlatformInfo.PlatformInfo().MaximumPrecision()
28 if sys.version_info.major > 2:
29     unicode = str
30
31 # ==============================================================================
32 class ElementaryAlgorithm(BasicObjects.Algorithm):
33     def __init__(self):
34         BasicObjects.Algorithm.__init__(self, "FUNCTIONTEST")
35         self.defineRequiredParameter(
36             name     = "NumberOfPrintedDigits",
37             default  = 5,
38             typecast = int,
39             message  = "Nombre de chiffres affichés pour les impressions de réels",
40             minval   = 0,
41             )
42         self.defineRequiredParameter(
43             name     = "NumberOfRepetition",
44             default  = 1,
45             typecast = int,
46             message  = "Nombre de fois où l'exécution de la fonction est répétée",
47             minval   = 1,
48             )
49         self.defineRequiredParameter(
50             name     = "ResultTitle",
51             default  = "",
52             typecast = str,
53             message  = "Titre du tableau et de la figure",
54             )
55         self.defineRequiredParameter(
56             name     = "SetDebug",
57             default  = False,
58             typecast = bool,
59             message  = "Activation du mode debug lors de l'exécution",
60             )
61         self.defineRequiredParameter(
62             name     = "StoreSupplementaryCalculations",
63             default  = [],
64             typecast = tuple,
65             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
66             listval  = ["CurrentState", "SimulatedObservationAtCurrentState"]
67             )
68         self.requireInputArguments(
69             mandatory= ("Xb", "HO"),
70             )
71
72     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
73         self._pre_run(Parameters, Xb, Y, R, B, Q)
74         #
75         Hm = HO["Direct"].appliedTo
76         #
77         Xn = copy.copy( Xb )
78         #
79         # ----------
80         __marge =  5*u" "
81         _p = self._parameters["NumberOfPrintedDigits"]
82         if len(self._parameters["ResultTitle"]) > 0:
83             __rt = unicode(self._parameters["ResultTitle"])
84             msgs  = u"\n"
85             msgs +=  __marge + "====" + "="*len(__rt) + "====\n"
86             msgs +=  __marge + "    " + __rt + "\n"
87             msgs +=  __marge + "====" + "="*len(__rt) + "====\n"
88             print("%s"%msgs)
89         #
90         msgs  = ("===> Information before launching:\n")
91         msgs += ("     -----------------------------\n")
92         msgs += ("     Characteristics of input vector X, internally converted:\n")
93         msgs += ("       Type...............: %s\n")%type( Xn )
94         msgs += ("       Lenght of vector...: %i\n")%max(numpy.matrix( Xn ).shape)
95         msgs += ("       Minimum value......: %."+str(_p)+"e\n")%numpy.min( Xn )
96         msgs += ("       Maximum value......: %."+str(_p)+"e\n")%numpy.max( Xn )
97         msgs += ("       Mean of vector.....: %."+str(_p)+"e\n")%numpy.mean( Xn, dtype=mfp )
98         msgs += ("       Standard error.....: %."+str(_p)+"e\n")%numpy.std( Xn, dtype=mfp )
99         msgs += ("       L2 norm of vector..: %."+str(_p)+"e\n")%numpy.linalg.norm( Xn )
100         print(msgs)
101         #
102         if self._parameters["SetDebug"]:
103             CUR_LEVEL = logging.getLogger().getEffectiveLevel()
104             logging.getLogger().setLevel(logging.DEBUG)
105             print("===> Beginning of evaluation, activating debug\n")
106         else:
107             print("===> Beginning of evaluation, without activating debug\n")
108         #
109         # ----------
110         HO["Direct"].disableAvoidingRedundancy()
111         # ----------
112         Ys = []
113         for i in range(self._parameters["NumberOfRepetition"]):
114             if "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
115                 self.StoredVariables["CurrentState"].store( numpy.ravel(Xn) )
116             print("     %s\n"%("-"*75,))
117             if self._parameters["NumberOfRepetition"] > 1:
118                 print("===> Repetition step number %i on a total of %i\n"%(i+1,self._parameters["NumberOfRepetition"]))
119             print("===> Launching direct operator evaluation\n")
120             #
121             Yn = Hm( Xn )
122             #
123             print("\n===> End of direct operator evaluation\n")
124             #
125             msgs  = ("===> Information after evaluation:\n")
126             msgs += ("\n     Characteristics of simulated output vector Y=H(X), to compare to others:\n")
127             msgs += ("       Type...............: %s\n")%type( Yn )
128             msgs += ("       Lenght of vector...: %i\n")%max(numpy.matrix( Yn ).shape)
129             msgs += ("       Minimum value......: %."+str(_p)+"e\n")%numpy.min( Yn )
130             msgs += ("       Maximum value......: %."+str(_p)+"e\n")%numpy.max( Yn )
131             msgs += ("       Mean of vector.....: %."+str(_p)+"e\n")%numpy.mean( Yn, dtype=mfp )
132             msgs += ("       Standard error.....: %."+str(_p)+"e\n")%numpy.std( Yn, dtype=mfp )
133             msgs += ("       L2 norm of vector..: %."+str(_p)+"e\n")%numpy.linalg.norm( Yn )
134             print(msgs)
135             if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
136                 self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(Yn) )
137             #
138             Ys.append( copy.copy( numpy.ravel(
139                 Yn
140                 ) ) )
141         # ----------
142         HO["Direct"].enableAvoidingRedundancy()
143         # ----------
144         #
145         print("     %s\n"%("-"*75,))
146         if self._parameters["SetDebug"]:
147             print("===> End evaluation, deactivating debug if necessary\n")
148             logging.getLogger().setLevel(CUR_LEVEL)
149         #
150         if self._parameters["NumberOfRepetition"] > 1:
151             msgs  = ("     %s\n"%("-"*75,))
152             msgs += ("\n===> Statistical analysis of the outputs obtained throught repeated evaluations\n")
153             msgs += ("\n     (Remark: numbers that are (about) under %.0e represent 0 to machine precision)\n"%mpr)
154             Yy = numpy.array( Ys )
155             msgs += ("\n     Characteristics of the whole set of outputs Y:\n")
156             msgs += ("       Number of evaluations.........................: %i\n")%len( Ys )
157             msgs += ("       Minimum value of the whole set of outputs.....: %."+str(_p)+"e\n")%numpy.min( Yy )
158             msgs += ("       Maximum value of the whole set of outputs.....: %."+str(_p)+"e\n")%numpy.max( Yy )
159             msgs += ("       Mean of vector of the whole set of outputs....: %."+str(_p)+"e\n")%numpy.mean( Yy, dtype=mfp )
160             msgs += ("       Standard error of the whole set of outputs....: %."+str(_p)+"e\n")%numpy.std( Yy, dtype=mfp )
161             Ym = numpy.mean( numpy.array( Ys ), axis=0, dtype=mfp )
162             msgs += ("\n     Characteristics of the vector Ym, mean of the outputs Y:\n")
163             msgs += ("       Size of the mean of the outputs...............: %i\n")%Ym.size
164             msgs += ("       Minimum value of the mean of the outputs......: %."+str(_p)+"e\n")%numpy.min( Ym )
165             msgs += ("       Maximum value of the mean of the outputs......: %."+str(_p)+"e\n")%numpy.max( Ym )
166             msgs += ("       Mean of the mean of the outputs...............: %."+str(_p)+"e\n")%numpy.mean( Ym, dtype=mfp )
167             msgs += ("       Standard error of the mean of the outputs.....: %."+str(_p)+"e\n")%numpy.std( Ym, dtype=mfp )
168             Ye = numpy.mean( numpy.array( Ys ) - Ym, axis=0, dtype=mfp )
169             msgs += "\n     Characteristics of the mean of the differences between the outputs Y and their mean Ym:\n"
170             msgs += ("       Size of the mean of the differences...........: %i\n")%Ym.size
171             msgs += ("       Minimum value of the mean of the differences..: %."+str(_p)+"e\n")%numpy.min( Ye )
172             msgs += ("       Maximum value of the mean of the differences..: %."+str(_p)+"e\n")%numpy.max( Ye )
173             msgs += ("       Mean of the mean of the differences...........: %."+str(_p)+"e\n")%numpy.mean( Ye, dtype=mfp )
174             msgs += ("       Standard error of the mean of the differences.: %."+str(_p)+"e\n")%numpy.std( Ye, dtype=mfp )
175             msgs += ("\n     %s\n"%("-"*75,))
176             print(msgs)
177         #
178         self._post_run(HO)
179         return 0
180
181 # ==============================================================================
182 if __name__ == "__main__":
183     print('\n AUTODIAGNOSTIC \n')