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