Salome HOME
f4a5116b5af230583283cf8588c7f5a67f208afc
[modules/adao.git] / src / daComposant / daAlgorithms / ParallelFunctionTest.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2023 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 numpy, copy, logging
24 from daCore import BasicObjects, PlatformInfo
25 mpr = PlatformInfo.PlatformInfo().MachinePrecision()
26 mfp = PlatformInfo.PlatformInfo().MaximumPrecision()
27
28 # ==============================================================================
29 class ElementaryAlgorithm(BasicObjects.Algorithm):
30     def __init__(self):
31         BasicObjects.Algorithm.__init__(self, "PARALLELFUNCTIONTEST")
32         self.defineRequiredParameter(
33             name     = "ShowElementarySummary",
34             default  = True,
35             typecast = bool,
36             message  = "Calcule et affiche un résumé à chaque évaluation élémentaire",
37             )
38         self.defineRequiredParameter(
39             name     = "NumberOfPrintedDigits",
40             default  = 5,
41             typecast = int,
42             message  = "Nombre de chiffres affichés pour les impressions de réels",
43             minval   = 0,
44             )
45         self.defineRequiredParameter(
46             name     = "NumberOfRepetition",
47             default  = 1,
48             typecast = int,
49             message  = "Nombre de fois où l'exécution de la fonction est répétée",
50             minval   = 1,
51             )
52         self.defineRequiredParameter(
53             name     = "ResultTitle",
54             default  = "",
55             typecast = str,
56             message  = "Titre du tableau et de la figure",
57             )
58         self.defineRequiredParameter(
59             name     = "SetDebug",
60             default  = False,
61             typecast = bool,
62             message  = "Activation du mode debug lors de l'exécution",
63             )
64         self.defineRequiredParameter(
65             name     = "StoreSupplementaryCalculations",
66             default  = [],
67             typecast = tuple,
68             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
69             listval  = [
70                 "CurrentState",
71                 "SimulatedObservationAtCurrentState",
72                 ]
73             )
74         self.requireInputArguments(
75             mandatory= ("Xb", "HO"),
76             )
77         self.setAttributes(tags=(
78             "Checking",
79             ))
80
81     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
82         self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
83         #
84         Hm = HO["Direct"].appliedTo
85         #
86         X0 = copy.copy( Xb )
87         #
88         # ----------
89         __s = self._parameters["ShowElementarySummary"]
90         __p = self._parameters["NumberOfPrintedDigits"]
91         __r = self._parameters["NumberOfRepetition"]
92         #
93         __marge = 5*u" "
94         __flech = 3*"="+"> "
95         msgs  = ("\n") # 1
96         if len(self._parameters["ResultTitle"]) > 0:
97             __rt = str(self._parameters["ResultTitle"])
98             msgs += (__marge + "====" + "="*len(__rt) + "====\n")
99             msgs += (__marge + "    " + __rt + "\n")
100             msgs += (__marge + "====" + "="*len(__rt) + "====\n")
101         else:
102             msgs += (__marge + "%s\n"%self._name)
103             msgs += (__marge + "%s\n"%("="*len(self._name),))
104         #
105         msgs += ("\n")
106         msgs += (__marge + "This test allows to analyze the (repetition of the) launch of some\n")
107         msgs += (__marge + "given simulation operator F, applied to one single vector argument x,\n")
108         msgs += (__marge + "in a parallel way.\n")
109         msgs += (__marge + "The output shows simple statistics related to its successful execution,\n")
110         msgs += (__marge + "or related to the similarities of repetition of its execution.\n")
111         msgs += ("\n")
112         msgs += (__flech + "Information before launching:\n")
113         msgs += (__marge + "-----------------------------\n")
114         msgs += ("\n")
115         msgs += (__marge + "Characteristics of input vector X, internally converted:\n")
116         msgs += (__marge + "  Type...............: %s\n")%type( X0 )
117         msgs += (__marge + "  Length of vector...: %i\n")%max(numpy.ravel( X0 ).shape)
118         msgs += (__marge + "  Minimum value......: %."+str(__p)+"e\n")%numpy.min(  X0 )
119         msgs += (__marge + "  Maximum value......: %."+str(__p)+"e\n")%numpy.max(  X0 )
120         msgs += (__marge + "  Mean of vector.....: %."+str(__p)+"e\n")%numpy.mean( X0, dtype=mfp )
121         msgs += (__marge + "  Standard error.....: %."+str(__p)+"e\n")%numpy.std(  X0, dtype=mfp )
122         msgs += (__marge + "  L2 norm of vector..: %."+str(__p)+"e\n")%numpy.linalg.norm( X0 )
123         msgs += ("\n")
124         msgs += (__marge + "%s\n\n"%("-"*75,))
125         #
126         if self._parameters["SetDebug"]:
127             CUR_LEVEL = logging.getLogger().getEffectiveLevel()
128             logging.getLogger().setLevel(logging.DEBUG)
129             if __r > 1:
130                 msgs += (__flech + "Beginning of repeated evaluation, activating debug\n")
131             else:
132                 msgs += (__flech + "Beginning of evaluation, activating debug\n")
133         else:
134             if __r > 1:
135                 msgs += (__flech + "Beginning of repeated evaluation, without activating debug\n")
136             else:
137                 msgs += (__flech + "Beginning of evaluation, without activating debug\n")
138         msgs += ("\n")
139         msgs += (__marge + "%s\n"%("-"*75,))
140         print(msgs) # 1
141         #
142         # ----------
143         HO["Direct"].disableAvoidingRedundancy()
144         # ----------
145         Ys = []
146         Xs = []
147         msgs  = (__marge + "Appending the input vector to the agument set to be evaluated in parallel\n") # 2-1
148         for i in range(__r):
149             if self._toStore("CurrentState"):
150                 self.StoredVariables["CurrentState"].store( X0 )
151             Xs.append( X0 )
152             if __s:
153                 # msgs += ("\n")
154                 if __r > 1:
155                     msgs += (__marge + "  Appending step number %i on a total of %i\n"%(i+1,__r))
156         #
157         msgs += ("\n")
158         msgs += (__marge + "%s\n\n"%("-"*75,))
159         msgs += (__flech + "Launching operator parallel evaluation for %i states\n"%__r)
160         print(msgs) # 2-1
161         #
162         Ys = Hm( Xs, argsAsSerie = True )
163         #
164         msgs  = ("\n") # 2-2
165         msgs += (__flech + "End of operator parallel evaluation for %i states\n"%__r)
166         msgs += ("\n")
167         msgs += (__marge + "%s\n"%("-"*75,))
168         print(msgs) # 2-2
169         #
170         # ----------
171         HO["Direct"].enableAvoidingRedundancy()
172         # ----------
173         #
174         msgs  = ("") # 3
175         if self._parameters["SetDebug"]:
176             if __r > 1:
177                 msgs += (__flech + "End of repeated evaluation, deactivating debug if necessary\n")
178             else:
179                 msgs += (__flech + "End of evaluation, deactivating debug if necessary\n")
180             logging.getLogger().setLevel(CUR_LEVEL)
181         else:
182             if __r > 1:
183                 msgs += (__flech + "End of repeated evaluation, without deactivating debug\n")
184             else:
185                 msgs += (__flech + "End of evaluation, without deactivating debug\n")
186         #
187         if __s or self._toStore("SimulatedObservationAtCurrentState"):
188             for i in range(self._parameters["NumberOfRepetition"]):
189                 if __s:
190                     msgs += ("\n")
191                     msgs += (__marge + "%s\n\n"%("-"*75,))
192                     if self._parameters["NumberOfRepetition"] > 1:
193                         msgs += (__flech + "Repetition step number %i on a total of %i\n"%(i+1,self._parameters["NumberOfRepetition"]))
194                 #
195                 Yn = Ys[i]
196                 if __s:
197                     msgs += ("\n")
198                     msgs += (__flech + "Information after evaluation:\n")
199                     msgs += ("\n")
200                     msgs += (__marge + "Characteristics of simulated output vector Y=F(X), to compare to others:\n")
201                     msgs += (__marge + "  Type...............: %s\n")%type( Yn )
202                     msgs += (__marge + "  Length of vector...: %i\n")%max(numpy.ravel( Yn ).shape)
203                     msgs += (__marge + "  Minimum value......: %."+str(__p)+"e\n")%numpy.min(  Yn )
204                     msgs += (__marge + "  Maximum value......: %."+str(__p)+"e\n")%numpy.max(  Yn )
205                     msgs += (__marge + "  Mean of vector.....: %."+str(__p)+"e\n")%numpy.mean( Yn, dtype=mfp )
206                     msgs += (__marge + "  Standard error.....: %."+str(__p)+"e\n")%numpy.std(  Yn, dtype=mfp )
207                     msgs += (__marge + "  L2 norm of vector..: %."+str(__p)+"e\n")%numpy.linalg.norm( Yn )
208                     #
209                 if self._toStore("SimulatedObservationAtCurrentState"):
210                     self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(Yn) )
211         #
212         msgs += ("\n")
213         msgs += (__marge + "%s\n"%("-"*75,))
214         #
215         if __r > 1:
216             msgs += ("\n")
217             msgs += (__flech + "Launching statistical summary calculation for %i states\n"%__r)
218             msgs += ("\n")
219             msgs += (__marge + "%s\n"%("-"*75,))
220             msgs += ("\n")
221             msgs += (__flech + "Statistical analysis of the outputs obtained through parallel repeated evaluations\n")
222             msgs += ("\n")
223             msgs += (__marge + "(Remark: numbers that are (about) under %.0e represent 0 to machine precision)\n"%mpr)
224             msgs += ("\n")
225             Yy = numpy.array( Ys )
226             msgs += (__marge + "Number of evaluations...........................: %i\n")%len( Ys )
227             msgs += ("\n")
228             msgs += (__marge + "Characteristics of the whole set of outputs Y:\n")
229             msgs += (__marge + "  Size of each of the outputs...................: %i\n")%Ys[0].size
230             msgs += (__marge + "  Minimum value of the whole set of outputs.....: %."+str(__p)+"e\n")%numpy.min(  Yy )
231             msgs += (__marge + "  Maximum value of the whole set of outputs.....: %."+str(__p)+"e\n")%numpy.max(  Yy )
232             msgs += (__marge + "  Mean of vector of the whole set of outputs....: %."+str(__p)+"e\n")%numpy.mean( Yy, dtype=mfp )
233             msgs += (__marge + "  Standard error of the whole set of outputs....: %."+str(__p)+"e\n")%numpy.std(  Yy, dtype=mfp )
234             msgs += ("\n")
235             Ym = numpy.mean( numpy.array( Ys ), axis=0, dtype=mfp )
236             msgs += (__marge + "Characteristics of the vector Ym, mean of the outputs Y:\n")
237             msgs += (__marge + "  Size of the mean of the outputs...............: %i\n")%Ym.size
238             msgs += (__marge + "  Minimum value of the mean of the outputs......: %."+str(__p)+"e\n")%numpy.min(  Ym )
239             msgs += (__marge + "  Maximum value of the mean of the outputs......: %."+str(__p)+"e\n")%numpy.max(  Ym )
240             msgs += (__marge + "  Mean of the mean of the outputs...............: %."+str(__p)+"e\n")%numpy.mean( Ym, dtype=mfp )
241             msgs += (__marge + "  Standard error of the mean of the outputs.....: %."+str(__p)+"e\n")%numpy.std(  Ym, dtype=mfp )
242             msgs += ("\n")
243             Ye = numpy.mean( numpy.array( Ys ) - Ym, axis=0, dtype=mfp )
244             msgs += (__marge + "Characteristics of the mean of the differences between the outputs Y and their mean Ym:\n")
245             msgs += (__marge + "  Size of the mean of the differences...........: %i\n")%Ye.size
246             msgs += (__marge + "  Minimum value of the mean of the differences..: %."+str(__p)+"e\n")%numpy.min(  Ye )
247             msgs += (__marge + "  Maximum value of the mean of the differences..: %."+str(__p)+"e\n")%numpy.max(  Ye )
248             msgs += (__marge + "  Mean of the mean of the differences...........: %."+str(__p)+"e\n")%numpy.mean( Ye, dtype=mfp )
249             msgs += (__marge + "  Standard error of the mean of the differences.: %."+str(__p)+"e\n")%numpy.std(  Ye, dtype=mfp )
250             msgs += ("\n")
251             msgs += (__marge + "%s\n"%("-"*75,))
252         #
253         msgs += ("\n")
254         msgs += (__marge + "End of the \"%s\" verification\n\n"%self._name)
255         msgs += (__marge + "%s\n"%("-"*75,))
256         print(msgs) # 3
257         #
258         self._post_run(HO)
259         return 0
260
261 # ==============================================================================
262 if __name__ == "__main__":
263     print('\n AUTODIAGNOSTIC\n')