Salome HOME
Documentation update with features and review corrections
[modules/adao.git] / src / daComposant / daAlgorithms / ControledFunctionTest.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2024 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, "CONTROLEDFUNCTIONTEST")
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             optional = ("U"),
77         )
78         self.setAttributes(
79             tags=(
80                 "Checking",
81             ),
82             features=(
83                 "DerivativeFree",
84                 "ParallelFree",
85             ),
86         )
87
88     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
89         self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
90         #
91         FunctionToTest = HO["Direct"].appliedControledFormTo
92         #
93         X0 = copy.copy( Xb )
94         if U is not None:
95             if hasattr(U, "store") and len(U) > 1:
96                 Un = numpy.ravel( U[-1] ).reshape((-1, 1))
97             elif hasattr(U, "store") and len(U) == 1:
98                 Un = numpy.ravel( U[0] ).reshape((-1, 1))
99             else:
100                 Un = numpy.ravel( U ).reshape((-1, 1))
101         else:
102             Un = None
103         #
104         # ----------
105         __s = self._parameters["ShowElementarySummary"]
106         __p = self._parameters["NumberOfPrintedDigits"]
107         __r = self._parameters["NumberOfRepetition"]
108         #
109         __marge = 5 * u" "
110         __flech = 3 * "=" + "> "
111         msgs  = ("\n")  # 1
112         if len(self._parameters["ResultTitle"]) > 0:
113             __rt = str(self._parameters["ResultTitle"])
114             msgs += (__marge + "====" + "=" * len(__rt) + "====\n")
115             msgs += (__marge + "    " + __rt + "\n")
116             msgs += (__marge + "====" + "=" * len(__rt) + "====\n")
117         else:
118             msgs += (__marge + "%s\n"%self._name)
119             msgs += (__marge + "%s\n"%("=" * len(self._name),))
120         #
121         msgs += ("\n")
122         msgs += (__marge + "This test allows to analyze the (repetition of the) launch of some\n")
123         msgs += (__marge + "given simulation operator F, applied to one single vector x and to\n")
124         msgs += (__marge + "one control vector u as arguments, in a sequential way.\n")
125         msgs += (__marge + "The output shows simple statistics related to its successful execution,\n")
126         msgs += (__marge + "or related to the similarities of repetition of its execution.\n")
127         msgs += ("\n")
128         msgs += (__flech + "Information before launching:\n")
129         msgs += (__marge + "-----------------------------\n")
130         msgs += ("\n")
131         msgs += (__marge + "Characteristics of input vector X, internally converted:\n")
132         msgs += (__marge + "  Type...............: %s\n")%type( X0 )
133         msgs += (__marge + "  Length of vector...: %i\n")%max(numpy.ravel( X0 ).shape)
134         msgs += (__marge + "  Minimum value......: %." + str(__p) + "e\n")%numpy.min(  X0 )
135         msgs += (__marge + "  Maximum value......: %." + str(__p) + "e\n")%numpy.max(  X0 )
136         msgs += (__marge + "  Mean of vector.....: %." + str(__p) + "e\n")%numpy.mean( X0, dtype=mfp )
137         msgs += (__marge + "  Standard error.....: %." + str(__p) + "e\n")%numpy.std(  X0, dtype=mfp )
138         msgs += (__marge + "  L2 norm of vector..: %." + str(__p) + "e\n")%numpy.linalg.norm( X0 )
139         msgs += ("\n")
140         if Un is None:
141             msgs += (__marge + "Characteristics of control parameter U, internally converted: None\n")
142         else:
143             msgs += (__marge + "Characteristics of control parameter U, internally converted:\n")
144             msgs += (__marge + "  Type...............: %s\n")%type( Un )
145             msgs += (__marge + "  Length of vector...: %i\n")%max(numpy.ravel( Un ).shape)
146             msgs += (__marge + "  Minimum value......: %." + str(__p) + "e\n")%numpy.min(  Un )
147             msgs += (__marge + "  Maximum value......: %." + str(__p) + "e\n")%numpy.max(  Un )
148             msgs += (__marge + "  Mean of vector.....: %." + str(__p) + "e\n")%numpy.mean( Un, dtype=mfp )
149             msgs += (__marge + "  Standard error.....: %." + str(__p) + "e\n")%numpy.std(  Un, dtype=mfp )
150             msgs += (__marge + "  L2 norm of vector..: %." + str(__p) + "e\n")%numpy.linalg.norm( Un )
151         msgs += ("\n")
152         msgs += (__marge + "%s\n\n"%("-" * 75,))
153         #
154         if self._parameters["SetDebug"]:
155             CUR_LEVEL = logging.getLogger().getEffectiveLevel()
156             logging.getLogger().setLevel(logging.DEBUG)
157             if __r > 1:
158                 msgs += (__flech + "Beginning of repeated evaluation, activating debug\n")
159             else:
160                 msgs += (__flech + "Beginning of evaluation, activating debug\n")
161         else:
162             if __r > 1:
163                 msgs += (__flech + "Beginning of repeated evaluation, without activating debug\n")
164             else:
165                 msgs += (__flech + "Beginning of evaluation, without activating debug\n")
166         print(msgs)  # 1
167         #
168         # ----------
169         HO["Direct"].disableAvoidingRedundancy()
170         # ----------
171         Ys = []
172         for i in range(__r):
173             if self._toStore("CurrentState"):
174                 self.StoredVariables["CurrentState"].store( X0 )
175             if __s:
176                 msgs  = (__marge + "%s\n"%("-" * 75,))  # 2-1
177                 if __r > 1:
178                     msgs += ("\n")
179                     msgs += (__flech + "Repetition step number %i on a total of %i\n"%(i + 1, __r))
180                 msgs += ("\n")
181                 msgs += (__flech + "Launching operator sequential evaluation\n")
182                 print(msgs)  # 2-1
183             #
184             Yn = FunctionToTest( (X0, Un) )
185             #
186             if __s:
187                 msgs  = ("\n")  # 2-2
188                 msgs += (__flech + "End of operator sequential evaluation\n")
189                 msgs += ("\n")
190                 msgs += (__flech + "Information after evaluation:\n")
191                 msgs += ("\n")
192                 msgs += (__marge + "Characteristics of simulated output vector Y=F((X,U)), to compare to others:\n")
193                 msgs += (__marge + "  Type...............: %s\n")%type( Yn )
194                 msgs += (__marge + "  Length of vector...: %i\n")%max(numpy.ravel( Yn ).shape)
195                 msgs += (__marge + "  Minimum value......: %." + str(__p) + "e\n")%numpy.min(  Yn )
196                 msgs += (__marge + "  Maximum value......: %." + str(__p) + "e\n")%numpy.max(  Yn )
197                 msgs += (__marge + "  Mean of vector.....: %." + str(__p) + "e\n")%numpy.mean( Yn, dtype=mfp )
198                 msgs += (__marge + "  Standard error.....: %." + str(__p) + "e\n")%numpy.std(  Yn, dtype=mfp )
199                 msgs += (__marge + "  L2 norm of vector..: %." + str(__p) + "e\n")%numpy.linalg.norm( Yn )
200                 print(msgs)  # 2-2
201             if self._toStore("SimulatedObservationAtCurrentState"):
202                 self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(Yn) )
203             #
204             Ys.append( copy.copy( numpy.ravel(
205                 Yn
206             ) ) )
207         # ----------
208         HO["Direct"].enableAvoidingRedundancy()
209         # ----------
210         #
211         msgs  = (__marge + "%s\n\n"%("-" * 75,))  # 3
212         if self._parameters["SetDebug"]:
213             if __r > 1:
214                 msgs += (__flech + "End of repeated evaluation, deactivating debug if necessary\n")
215             else:
216                 msgs += (__flech + "End of evaluation, deactivating debug if necessary\n")
217             logging.getLogger().setLevel(CUR_LEVEL)
218         else:
219             if __r > 1:
220                 msgs += (__flech + "End of repeated evaluation, without deactivating debug\n")
221             else:
222                 msgs += (__flech + "End of evaluation, without deactivating debug\n")
223         msgs += ("\n")
224         msgs += (__marge + "%s\n"%("-" * 75,))
225         #
226         if __r > 1:
227             msgs += ("\n")
228             msgs += (__flech + "Launching statistical summary calculation for %i states\n"%__r)
229             msgs += ("\n")
230             msgs += (__marge + "%s\n"%("-" * 75,))
231             msgs += ("\n")
232             msgs += (__flech + "Statistical analysis of the outputs obtained through sequential repeated evaluations\n")  # noqa: E501
233             msgs += ("\n")
234             msgs += (__marge + "(Remark: numbers that are (about) under %.0e represent 0 to machine precision)\n"%mpr)  # noqa: E501
235             msgs += ("\n")
236             Yy = numpy.array( Ys )
237             msgs += (__marge + "Number of evaluations...........................: %i\n")%len( Ys )
238             msgs += ("\n")
239             msgs += (__marge + "Characteristics of the whole set of outputs Y:\n")
240             msgs += (__marge + "  Size of each of the outputs...................: %i\n")%Ys[0].size
241             msgs += (__marge + "  Minimum value of the whole set of outputs.....: %." + str(__p) + "e\n")%numpy.min(  Yy )  # noqa: E501
242             msgs += (__marge + "  Maximum value of the whole set of outputs.....: %." + str(__p) + "e\n")%numpy.max(  Yy )  # noqa: E501
243             msgs += (__marge + "  Mean of vector of the whole set of outputs....: %." + str(__p) + "e\n")%numpy.mean( Yy, dtype=mfp )  # noqa: E501
244             msgs += (__marge + "  Standard error of the whole set of outputs....: %." + str(__p) + "e\n")%numpy.std(  Yy, dtype=mfp )  # noqa: E501
245             msgs += ("\n")
246             Ym = numpy.mean( numpy.array( Ys ), axis=0, dtype=mfp )
247             msgs += (__marge + "Characteristics of the vector Ym, mean of the outputs Y:\n")
248             msgs += (__marge + "  Size of the mean of the outputs...............: %i\n")%Ym.size
249             msgs += (__marge + "  Minimum value of the mean of the outputs......: %." + str(__p) + "e\n")%numpy.min(  Ym )  # noqa: E501
250             msgs += (__marge + "  Maximum value of the mean of the outputs......: %." + str(__p) + "e\n")%numpy.max(  Ym )  # noqa: E501
251             msgs += (__marge + "  Mean of the mean of the outputs...............: %." + str(__p) + "e\n")%numpy.mean( Ym, dtype=mfp )  # noqa: E501
252             msgs += (__marge + "  Standard error of the mean of the outputs.....: %." + str(__p) + "e\n")%numpy.std(  Ym, dtype=mfp )  # noqa: E501
253             msgs += ("\n")
254             Ye = numpy.mean( numpy.array( Ys ) - Ym, axis=0, dtype=mfp )
255             msgs += (__marge + "Characteristics of the mean of the differences between the outputs Y and their mean Ym:\n")  # noqa: E501
256             msgs += (__marge + "  Size of the mean of the differences...........: %i\n")%Ye.size
257             msgs += (__marge + "  Minimum value of the mean of the differences..: %." + str(__p) + "e\n")%numpy.min(  Ye )  # noqa: E501
258             msgs += (__marge + "  Maximum value of the mean of the differences..: %." + str(__p) + "e\n")%numpy.max(  Ye )  # noqa: E501
259             msgs += (__marge + "  Mean of the mean of the differences...........: %." + str(__p) + "e\n")%numpy.mean( Ye, dtype=mfp )  # noqa: E501
260             msgs += (__marge + "  Standard error of the mean of the differences.: %." + str(__p) + "e\n")%numpy.std(  Ye, dtype=mfp )  # noqa: E501
261             msgs += ("\n")
262             msgs += (__marge + "%s\n"%("-" * 75,))
263         #
264         msgs += ("\n")
265         msgs += (__marge + "End of the \"%s\" verification\n\n"%self._name)
266         msgs += (__marge + "%s\n"%("-" * 75,))
267         print(msgs)  # 3
268         #
269         self._post_run(HO, EM)
270         return 0
271
272 # ==============================================================================
273 if __name__ == "__main__":
274     print("\n AUTODIAGNOSTIC\n")