1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2024 EDF R&D
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.
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.
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
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
24 from daCore import BasicObjects, NumericObjects, PlatformInfo
25 mpr = PlatformInfo.PlatformInfo().MachinePrecision()
26 mfp = PlatformInfo.PlatformInfo().MaximumPrecision()
28 # ==============================================================================
29 class ElementaryAlgorithm(BasicObjects.Algorithm):
31 BasicObjects.Algorithm.__init__(self, "TANGENTTEST")
32 self.defineRequiredParameter(
33 name = "ResiduFormula",
36 message = "Formule de résidu utilisée",
39 self.defineRequiredParameter(
40 name = "EpsilonMinimumExponent",
43 message = "Exposant minimal en puissance de 10 pour le multiplicateur d'incrément",
47 self.defineRequiredParameter(
48 name = "InitialDirection",
51 message = "Direction initiale de la dérivée directionnelle autour du point nominal",
53 self.defineRequiredParameter(
54 name = "AmplitudeOfInitialDirection",
57 message = "Amplitude de la direction initiale de la dérivée directionnelle autour du point nominal",
59 self.defineRequiredParameter(
60 name = "AmplitudeOfTangentPerturbation",
63 message = "Amplitude de la perturbation pour le calcul de la forme tangente",
67 self.defineRequiredParameter(
69 typecast = numpy.random.seed,
70 message = "Graine fixée pour le générateur aléatoire",
72 self.defineRequiredParameter(
73 name = "NumberOfPrintedDigits",
76 message = "Nombre de chiffres affichés pour les impressions de réels",
79 self.defineRequiredParameter(
83 message = "Titre du tableau et de la figure",
85 self.defineRequiredParameter(
86 name = "StoreSupplementaryCalculations",
89 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
93 "SimulatedObservationAtCurrentState",
96 self.requireInputArguments(
97 mandatory= ("Xb", "HO"),
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)
111 Hm = HO["Direct"].appliedTo
112 Ht = HO["Tangent"].appliedInXTo
114 X0 = numpy.ravel( Xb ).reshape((-1, 1))
117 __p = self._parameters["NumberOfPrintedDigits"]
120 __flech = 3 * "=" + "> "
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")
128 msgs += (__marge + "%s\n"%self._name)
129 msgs += (__marge + "%s\n"%("=" * len(self._name),))
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")
137 msgs += (__flech + "Information before launching:\n")
138 msgs += (__marge + "-----------------------------\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 )
149 msgs += (__marge + "%s\n\n"%("-" * 75,))
150 msgs += (__flech + "Numerical quality indicators:\n")
151 msgs += (__marge + "-----------------------------\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")
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")
162 msgs += (__marge + "which must remain stable in 1+O(Alpha) until the accuracy of the\n")
163 msgs += (__marge + "calculation is reached.\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")
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")
171 __entete = u" i Alpha ||X|| ||F(X)|| | R(Alpha) |R-1|/Alpha"
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:
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"])
180 msgs += (__marge + "(Remark: numbers that are (about) under %.0e represent 0 to machine precision)\n"%mpr)
183 Perturbations = [ 10**i for i in range(self._parameters["EpsilonMinimumExponent"], 1) ]
184 Perturbations.reverse()
186 FX = numpy.ravel( Hm( X0 ) ).reshape((-1, 1))
187 NormeX = numpy.linalg.norm( X0 )
188 NormeFX = numpy.linalg.norm( FX )
191 if self._toStore("CurrentState"):
192 self.StoredVariables["CurrentState"].store( X0 )
193 if self._toStore("SimulatedObservationAtCurrentState"):
194 self.StoredVariables["SimulatedObservationAtCurrentState"].store( FX )
196 dX0 = NumericObjects.SetInitialDirection(
197 self._parameters["InitialDirection"],
198 self._parameters["AmplitudeOfInitialDirection"],
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 )
213 # Boucle sur les perturbations
214 # ----------------------------
215 __nbtirets = len(__entete) + 2
217 msgs += "\n" + __marge + "-" * __nbtirets
218 msgs += "\n" + __marge + __entete
219 msgs += "\n" + __marge + "-" * __nbtirets
221 for ip, amplitude in enumerate(Perturbations):
222 dX = amplitude * dX0.reshape((-1, 1))
224 if self._parameters["ResiduFormula"] == "Taylor":
225 FX_plus_dX = numpy.ravel( Hm( X0 + dX ) ).reshape((-1, 1))
227 Residu = numpy.linalg.norm( FX_plus_dX - FX ) / (amplitude * NormeGX)
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
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,))
238 self._post_run(HO, EM)
241 # ==============================================================================
242 if __name__ == "__main__":
243 print("\n AUTODIAGNOSTIC\n")