Salome HOME
Documentation review corrections
[modules/adao.git] / src / daComposant / daAlgorithms / TangentTest.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
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(tags=(
100             "Checking",
101             ))
102
103     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
104         self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
105         #
106         Hm = HO["Direct"].appliedTo
107         Ht = HO["Tangent"].appliedInXTo
108         #
109         X0      = numpy.ravel( Xb ).reshape((-1,1))
110         #
111         # ----------
112         __p = self._parameters["NumberOfPrintedDigits"]
113         #
114         __marge = 5*u" "
115         __flech = 3*"="+"> "
116         msgs  = ("\n") # 1
117         if len(self._parameters["ResultTitle"]) > 0:
118             __rt = str(self._parameters["ResultTitle"])
119             msgs += (__marge + "====" + "="*len(__rt) + "====\n")
120             msgs += (__marge + "    " + __rt + "\n")
121             msgs += (__marge + "====" + "="*len(__rt) + "====\n")
122         else:
123             msgs += (__marge + "%s\n"%self._name)
124             msgs += (__marge + "%s\n"%("="*len(self._name),))
125         #
126         msgs += ("\n")
127         msgs += (__marge + "This test allows to analyze the numerical stability of the tangent of some\n")
128         msgs += (__marge + "given simulation operator F, applied to one single vector argument x.\n")
129         msgs += (__marge + "The output shows simple statistics related to its stability for various\n")
130         msgs += (__marge + "increments, around an input checking point X.\n")
131         msgs += ("\n")
132         msgs += (__flech + "Information before launching:\n")
133         msgs += (__marge + "-----------------------------\n")
134         msgs += ("\n")
135         msgs += (__marge + "Characteristics of input vector X, internally converted:\n")
136         msgs += (__marge + "  Type...............: %s\n")%type( X0 )
137         msgs += (__marge + "  Length of vector...: %i\n")%max(numpy.ravel( X0 ).shape)
138         msgs += (__marge + "  Minimum value......: %."+str(__p)+"e\n")%numpy.min(  X0 )
139         msgs += (__marge + "  Maximum value......: %."+str(__p)+"e\n")%numpy.max(  X0 )
140         msgs += (__marge + "  Mean of vector.....: %."+str(__p)+"e\n")%numpy.mean( X0, dtype=mfp )
141         msgs += (__marge + "  Standard error.....: %."+str(__p)+"e\n")%numpy.std(  X0, dtype=mfp )
142         msgs += (__marge + "  L2 norm of vector..: %."+str(__p)+"e\n")%numpy.linalg.norm( X0 )
143         msgs += ("\n")
144         msgs += (__marge + "%s\n\n"%("-"*75,))
145         msgs += (__flech + "Numerical quality indicators:\n")
146         msgs += (__marge + "-----------------------------\n")
147         msgs += ("\n")
148         msgs += (__marge + "Using the \"%s\" formula, one observes the residue R which is the\n"%self._parameters["ResiduFormula"])
149         msgs += (__marge + "ratio of increments using the tangent linear:\n")
150         msgs += ("\n")
151         #
152         if self._parameters["ResiduFormula"] == "Taylor":
153             msgs += (__marge + "                || F(X+Alpha*dX) - F(X) ||\n")
154             msgs += (__marge + "    R(Alpha) = -----------------------------\n")
155             msgs += (__marge + "               || Alpha * TangentF_X * dX ||\n")
156             msgs += ("\n")
157             msgs += (__marge + "which must remain stable in 1+O(Alpha) until the accuracy of the\n")
158             msgs += (__marge + "calculation is reached.\n")
159             msgs += ("\n")
160             msgs += (__marge + "When |R-1|/Alpha is less than or equal to a stable value when Alpha varies,\n")
161             msgs += (__marge + "the tangent is valid, until the accuracy of the calculation is reached.\n")
162             msgs += ("\n")
163             msgs += (__marge + "If |R-1|/Alpha is very small, the code F is likely linear or quasi-linear,\n")
164             msgs += (__marge + "and the tangent is valid until computational accuracy is reached.\n")
165             #
166             __entete = u"  i   Alpha     ||X||      ||F(X)||   |     R(Alpha)    |R-1|/Alpha"
167             #
168         msgs += ("\n")
169         msgs += (__marge + "We take dX0 = Normal(0,X) and dX = Alpha*dX0. F is the calculation code.\n")
170         msgs += ("\n")
171         msgs += (__marge + "(Remark: numbers that are (about) under %.0e represent 0 to machine precision)\n"%mpr)
172         print(msgs) # 1
173         #
174         Perturbations = [ 10**i for i in range(self._parameters["EpsilonMinimumExponent"],1) ]
175         Perturbations.reverse()
176         #
177         FX      = numpy.ravel( Hm( X0 ) ).reshape((-1,1))
178         NormeX  = numpy.linalg.norm( X0 )
179         NormeFX = numpy.linalg.norm( FX )
180         if NormeFX < mpr: NormeFX = mpr
181         if self._toStore("CurrentState"):
182             self.StoredVariables["CurrentState"].store( X0 )
183         if self._toStore("SimulatedObservationAtCurrentState"):
184             self.StoredVariables["SimulatedObservationAtCurrentState"].store( FX )
185         #
186         dX0 = NumericObjects.SetInitialDirection(
187             self._parameters["InitialDirection"],
188             self._parameters["AmplitudeOfInitialDirection"],
189             X0,
190             )
191         #
192         # Calcul du gradient au point courant X pour l'incrément dX
193         # qui est le tangent en X multiplie par dX
194         # ---------------------------------------------------------
195         dX1      = float(self._parameters["AmplitudeOfTangentPerturbation"]) * dX0
196         GradFxdX = Ht( (X0, dX1) )
197         GradFxdX = numpy.ravel( GradFxdX ).reshape((-1,1))
198         GradFxdX = float(1./self._parameters["AmplitudeOfTangentPerturbation"]) * GradFxdX
199         NormeGX  = numpy.linalg.norm( GradFxdX )
200         if NormeGX < mpr: NormeGX = mpr
201         #
202         # Boucle sur les perturbations
203         # ----------------------------
204         __nbtirets = len(__entete) + 2
205         msgs  = ("") # 2
206         msgs += "\n" + __marge + "-"*__nbtirets
207         msgs += "\n" + __marge + __entete
208         msgs += "\n" + __marge + "-"*__nbtirets
209         msgs += ("\n")
210         for i,amplitude in enumerate(Perturbations):
211             dX      = amplitude * dX0.reshape((-1,1))
212             #
213             if self._parameters["ResiduFormula"] == "Taylor":
214                 FX_plus_dX  = numpy.ravel( Hm( X0 + dX ) ).reshape((-1,1))
215                 #
216                 Residu = numpy.linalg.norm( FX_plus_dX - FX ) / (amplitude * NormeGX)
217             #
218             self.StoredVariables["Residu"].store( Residu )
219             ttsep = "  %2i  %5.0e   %9.3e   %9.3e   |   %11.5e    %5.1e\n"%(i,amplitude,NormeX,NormeFX,Residu,abs(Residu-1.)/amplitude)
220             msgs += __marge + ttsep
221         #
222         msgs += (__marge + "-"*__nbtirets + "\n\n")
223         msgs += (__marge + "End of the \"%s\" verification by the \"%s\" formula.\n\n"%(self._name,self._parameters["ResiduFormula"]))
224         msgs += (__marge + "%s\n"%("-"*75,))
225         print(msgs) # 2
226         #
227         self._post_run(HO)
228         return 0
229
230 # ==============================================================================
231 if __name__ == "__main__":
232     print("\n AUTODIAGNOSTIC\n")