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