Salome HOME
Documentation update with features and review corrections
[modules/adao.git] / src / daComposant / daAlgorithms / TangentTest.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
24 from daCore import BasicObjects, NumericObjects, 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, "TANGENTTEST")
32         self.defineRequiredParameter(
33             name     = "ResiduFormula",
34             default  = "Taylor",
35             typecast = str,
36             message  = "Formule de résidu utilisée",
37             listval  = ["Taylor"],
38         )
39         self.defineRequiredParameter(
40             name     = "EpsilonMinimumExponent",
41             default  = -8,
42             typecast = int,
43             message  = "Exposant minimal en puissance de 10 pour le multiplicateur d'incrément",
44             minval   = -20,
45             maxval   = 0,
46         )
47         self.defineRequiredParameter(
48             name     = "InitialDirection",
49             default  = [],
50             typecast = list,
51             message  = "Direction initiale de la dérivée directionnelle autour du point nominal",
52         )
53         self.defineRequiredParameter(
54             name     = "AmplitudeOfInitialDirection",
55             default  = 1.,
56             typecast = float,
57             message  = "Amplitude de la direction initiale de la dérivée directionnelle autour du point nominal",
58         )
59         self.defineRequiredParameter(
60             name     = "AmplitudeOfTangentPerturbation",
61             default  = 1.e-2,
62             typecast = float,
63             message  = "Amplitude de la perturbation pour le calcul de la forme tangente",
64             minval   = 1.e-10,
65             maxval   = 1.,
66         )
67         self.defineRequiredParameter(
68             name     = "SetSeed",
69             typecast = numpy.random.seed,
70             message  = "Graine fixée pour le générateur aléatoire",
71         )
72         self.defineRequiredParameter(
73             name     = "NumberOfPrintedDigits",
74             default  = 5,
75             typecast = int,
76             message  = "Nombre de chiffres affichés pour les impressions de réels",
77             minval   = 0,
78         )
79         self.defineRequiredParameter(
80             name     = "ResultTitle",
81             default  = "",
82             typecast = str,
83             message  = "Titre du tableau et de la figure",
84         )
85         self.defineRequiredParameter(
86             name     = "StoreSupplementaryCalculations",
87             default  = [],
88             typecast = tuple,
89             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
90             listval  = [
91                 "CurrentState",
92                 "Residu",
93                 "SimulatedObservationAtCurrentState",
94             ]
95         )
96         self.requireInputArguments(
97             mandatory= ("Xb", "HO"),
98         )
99         self.setAttributes(
100             tags=(
101                 "Checking",
102             ),
103             features=(
104                 "DerivativeNeeded",
105             ),
106         )
107
108     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
109         self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
110         #
111         Hm = HO["Direct"].appliedTo
112         Ht = HO["Tangent"].appliedInXTo
113         #
114         X0      = numpy.ravel( Xb ).reshape((-1, 1))
115         #
116         # ----------
117         __p = self._parameters["NumberOfPrintedDigits"]
118         #
119         __marge = 5 * u" "
120         __flech = 3 * "=" + "> "
121         msgs  = ("\n")  # 1
122         if len(self._parameters["ResultTitle"]) > 0:
123             __rt = str(self._parameters["ResultTitle"])
124             msgs += (__marge + "====" + "=" * len(__rt) + "====\n")
125             msgs += (__marge + "    " + __rt + "\n")
126             msgs += (__marge + "====" + "=" * len(__rt) + "====\n")
127         else:
128             msgs += (__marge + "%s\n"%self._name)
129             msgs += (__marge + "%s\n"%("=" * len(self._name),))
130         #
131         msgs += ("\n")
132         msgs += (__marge + "This test allows to analyze the numerical stability of the tangent of some\n")
133         msgs += (__marge + "given simulation operator F, applied to one single vector argument x.\n")
134         msgs += (__marge + "The output shows simple statistics related to its stability for various\n")
135         msgs += (__marge + "increments, around an input checking point X.\n")
136         msgs += ("\n")
137         msgs += (__flech + "Information before launching:\n")
138         msgs += (__marge + "-----------------------------\n")
139         msgs += ("\n")
140         msgs += (__marge + "Characteristics of input vector X, internally converted:\n")
141         msgs += (__marge + "  Type...............: %s\n")%type( X0 )
142         msgs += (__marge + "  Length of vector...: %i\n")%max(numpy.ravel( X0 ).shape)
143         msgs += (__marge + "  Minimum value......: %." + str(__p) + "e\n")%numpy.min(  X0 )
144         msgs += (__marge + "  Maximum value......: %." + str(__p) + "e\n")%numpy.max(  X0 )
145         msgs += (__marge + "  Mean of vector.....: %." + str(__p) + "e\n")%numpy.mean( X0, dtype=mfp )
146         msgs += (__marge + "  Standard error.....: %." + str(__p) + "e\n")%numpy.std(  X0, dtype=mfp )
147         msgs += (__marge + "  L2 norm of vector..: %." + str(__p) + "e\n")%numpy.linalg.norm( X0 )
148         msgs += ("\n")
149         msgs += (__marge + "%s\n\n"%("-" * 75,))
150         msgs += (__flech + "Numerical quality indicators:\n")
151         msgs += (__marge + "-----------------------------\n")
152         msgs += ("\n")
153         msgs += (__marge + "Using the \"%s\" formula, one observes the residue R which is the\n"%self._parameters["ResiduFormula"])  # noqa: E501
154         msgs += (__marge + "ratio of increments using the tangent linear:\n")
155         msgs += ("\n")
156         #
157         if self._parameters["ResiduFormula"] == "Taylor":
158             msgs += (__marge + "                || F(X+Alpha*dX) - F(X) ||\n")
159             msgs += (__marge + "    R(Alpha) = -----------------------------\n")
160             msgs += (__marge + "               || Alpha * TangentF_X * dX ||\n")
161             msgs += ("\n")
162             msgs += (__marge + "which must remain stable in 1+O(Alpha) until the accuracy of the\n")
163             msgs += (__marge + "calculation is reached.\n")
164             msgs += ("\n")
165             msgs += (__marge + "When |R-1|/Alpha is less than or equal to a stable value when Alpha varies,\n")
166             msgs += (__marge + "the tangent is valid, until the accuracy of the calculation is reached.\n")
167             msgs += ("\n")
168             msgs += (__marge + "If |R-1|/Alpha is very small, the code F is likely linear or quasi-linear,\n")
169             msgs += (__marge + "and the tangent is valid until computational accuracy is reached.\n")
170             #
171             __entete = u"  i   Alpha     ||X||      ||F(X)||   |     R(Alpha)    |R-1|/Alpha"
172             #
173         msgs += ("\n")
174         msgs += (__marge + "We take dX0 = Normal(0,X) and dX = Alpha*dX0. F is the calculation code.\n")
175         if "DifferentialIncrement" in HO and HO["DifferentialIncrement"] is not None:
176             msgs += ("\n")
177             msgs += (__marge + "Reminder: tangent operator is obtained internally by finite differences,\n")
178             msgs += (__marge + "with a differential increment of value %.2e.\n"%HO["DifferentialIncrement"])
179         msgs += ("\n")
180         msgs += (__marge + "(Remark: numbers that are (about) under %.0e represent 0 to machine precision)\n"%mpr)
181         print(msgs)  # 1
182         #
183         Perturbations = [ 10**i for i in range(self._parameters["EpsilonMinimumExponent"], 1) ]
184         Perturbations.reverse()
185         #
186         FX      = numpy.ravel( Hm( X0 ) ).reshape((-1, 1))
187         NormeX  = numpy.linalg.norm( X0 )
188         NormeFX = numpy.linalg.norm( FX )
189         if NormeFX < mpr:
190             NormeFX = mpr
191         if self._toStore("CurrentState"):
192             self.StoredVariables["CurrentState"].store( X0 )
193         if self._toStore("SimulatedObservationAtCurrentState"):
194             self.StoredVariables["SimulatedObservationAtCurrentState"].store( FX )
195         #
196         dX0 = NumericObjects.SetInitialDirection(
197             self._parameters["InitialDirection"],
198             self._parameters["AmplitudeOfInitialDirection"],
199             X0,
200         )
201         #
202         # Calcul du gradient au point courant X pour l'incrément dX
203         # qui est le tangent en X multiplie par dX
204         # ---------------------------------------------------------
205         dX1      = float(self._parameters["AmplitudeOfTangentPerturbation"]) * dX0
206         GradFxdX = Ht( (X0, dX1) )
207         GradFxdX = numpy.ravel( GradFxdX ).reshape((-1, 1))
208         GradFxdX = float(1. / self._parameters["AmplitudeOfTangentPerturbation"]) * GradFxdX
209         NormeGX  = numpy.linalg.norm( GradFxdX )
210         if NormeGX < mpr:
211             NormeGX = mpr
212         #
213         # Boucle sur les perturbations
214         # ----------------------------
215         __nbtirets = len(__entete) + 2
216         msgs  = ("")  # 2
217         msgs += "\n" + __marge + "-" * __nbtirets
218         msgs += "\n" + __marge + __entete
219         msgs += "\n" + __marge + "-" * __nbtirets
220         msgs += ("\n")
221         for ip, amplitude in enumerate(Perturbations):
222             dX      = amplitude * dX0.reshape((-1, 1))
223             #
224             if self._parameters["ResiduFormula"] == "Taylor":
225                 FX_plus_dX  = numpy.ravel( Hm( X0 + dX ) ).reshape((-1, 1))
226                 #
227                 Residu = numpy.linalg.norm( FX_plus_dX - FX ) / (amplitude * NormeGX)
228             #
229             self.StoredVariables["Residu"].store( Residu )
230             ttsep = "  %2i  %5.0e   %9.3e   %9.3e   |   %11.5e    %5.1e\n"%(ip, amplitude, NormeX, NormeFX, Residu, abs(Residu - 1.) / amplitude)  # noqa: E501
231             msgs += __marge + ttsep
232         #
233         msgs += (__marge + "-" * __nbtirets + "\n\n")
234         msgs += (__marge + "End of the \"%s\" verification by the \"%s\" formula.\n\n"%(self._name, self._parameters["ResiduFormula"]))  # noqa: E501
235         msgs += (__marge + "%s\n"%("-" * 75,))
236         print(msgs)  # 2
237         #
238         self._post_run(HO, EM)
239         return 0
240
241 # ==============================================================================
242 if __name__ == "__main__":
243     print("\n AUTODIAGNOSTIC\n")