Salome HOME
Updating version and copyright date information
[modules/adao.git] / src / daComposant / daAlgorithms / TangentTest.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2021 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 sys, logging
24 from daCore import BasicObjects, PlatformInfo
25 import numpy, math
26 mpr = PlatformInfo.PlatformInfo().MachinePrecision()
27 if sys.version_info.major > 2:
28     unicode = str
29
30 # ==============================================================================
31 class ElementaryAlgorithm(BasicObjects.Algorithm):
32     def __init__(self):
33         BasicObjects.Algorithm.__init__(self, "TANGENTTEST")
34         self.defineRequiredParameter(
35             name     = "ResiduFormula",
36             default  = "Taylor",
37             typecast = str,
38             message  = "Formule de résidu utilisée",
39             listval  = ["Taylor"],
40             )
41         self.defineRequiredParameter(
42             name     = "EpsilonMinimumExponent",
43             default  = -8,
44             typecast = int,
45             message  = "Exposant minimal en puissance de 10 pour le multiplicateur d'incrément",
46             minval   = -20,
47             maxval   = 0,
48             )
49         self.defineRequiredParameter(
50             name     = "InitialDirection",
51             default  = [],
52             typecast = list,
53             message  = "Direction initiale de la dérivée directionnelle autour du point nominal",
54             )
55         self.defineRequiredParameter(
56             name     = "AmplitudeOfInitialDirection",
57             default  = 1.,
58             typecast = float,
59             message  = "Amplitude de la direction initiale de la dérivée directionnelle autour du point nominal",
60             )
61         self.defineRequiredParameter(
62             name     = "AmplitudeOfTangentPerturbation",
63             default  = 1.e-2,
64             typecast = float,
65             message  = "Amplitude de la perturbation pour le calcul de la forme tangente",
66             minval   = 1.e-10,
67             maxval   = 1.,
68             )
69         self.defineRequiredParameter(
70             name     = "SetSeed",
71             typecast = numpy.random.seed,
72             message  = "Graine fixée pour le générateur aléatoire",
73             )
74         self.defineRequiredParameter(
75             name     = "ResultTitle",
76             default  = "",
77             typecast = str,
78             message  = "Titre du tableau et de la figure",
79             )
80         self.defineRequiredParameter(
81             name     = "StoreSupplementaryCalculations",
82             default  = [],
83             typecast = tuple,
84             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
85             listval  = [
86                 "CurrentState",
87                 "Residu",
88                 "SimulatedObservationAtCurrentState",
89                 ]
90             )
91         self.requireInputArguments(
92             mandatory= ("Xb", "HO"),
93             )
94         self.setAttributes(tags=(
95             "Checking",
96             ))
97
98     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
99         self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
100         #
101         Hm = HO["Direct"].appliedTo
102         Ht = HO["Tangent"].appliedInXTo
103         #
104         # Construction des perturbations
105         # ------------------------------
106         Perturbations = [ 10**i for i in range(self._parameters["EpsilonMinimumExponent"],1) ]
107         Perturbations.reverse()
108         #
109         # Calcul du point courant
110         # -----------------------
111         Xn      = numpy.asmatrix(numpy.ravel( Xb )).T
112         FX      = numpy.asmatrix(numpy.ravel( Hm( Xn ) )).T
113         NormeX  = numpy.linalg.norm( Xn )
114         NormeFX = numpy.linalg.norm( FX )
115         if self._toStore("CurrentState"):
116             self.StoredVariables["CurrentState"].store( numpy.ravel(Xn) )
117         if self._toStore("SimulatedObservationAtCurrentState"):
118             self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(FX) )
119         #
120         # Fabrication de la direction de l'increment dX
121         # ---------------------------------------------
122         if len(self._parameters["InitialDirection"]) == 0:
123             dX0 = []
124             for v in Xn.A1:
125                 if abs(v) > 1.e-8:
126                     dX0.append( numpy.random.normal(0.,abs(v)) )
127                 else:
128                     dX0.append( numpy.random.normal(0.,Xn.mean()) )
129         else:
130             dX0 = numpy.ravel( self._parameters["InitialDirection"] )
131         #
132         dX0 = float(self._parameters["AmplitudeOfInitialDirection"]) * numpy.matrix( dX0 ).T
133         #
134         # Calcul du gradient au point courant X pour l'increment dX
135         # qui est le tangent en X multiplie par dX
136         # ---------------------------------------------------------
137         dX1      = float(self._parameters["AmplitudeOfTangentPerturbation"]) * dX0
138         GradFxdX = Ht( (Xn, dX1) )
139         GradFxdX = numpy.asmatrix(numpy.ravel( GradFxdX )).T
140         GradFxdX = float(1./self._parameters["AmplitudeOfTangentPerturbation"]) * GradFxdX
141         NormeGX  = numpy.linalg.norm( GradFxdX )
142         #
143         # Entete des resultats
144         # --------------------
145         __marge =  12*u" "
146         __precision = u"""
147             Remarque : les nombres inferieurs a %.0e (environ) representent un zero
148                        a la precision machine.\n"""%mpr
149         if self._parameters["ResiduFormula"] == "Taylor":
150             __entete = u"  i   Alpha     ||X||      ||F(X)||   |     R(Alpha)    |R-1|/Alpha"
151             __msgdoc = u"""
152             On observe le residu provenant du rapport d'increments utilisant le
153             lineaire tangent :
154
155                           || F(X+Alpha*dX) - F(X) ||
156               R(Alpha) = -----------------------------
157                          || Alpha * TangentF_X * dX ||
158
159             qui doit rester stable en 1+O(Alpha) jusqu'a ce que l'on atteigne la
160             precision du calcul.
161
162             Lorsque |R-1|/Alpha est inferieur ou egal a une valeur stable
163             lorsque Alpha varie, le tangent est valide, jusqu'a ce que l'on
164             atteigne la precision du calcul.
165
166             Si |R-1|/Alpha est tres faible, le code F est vraisemblablement
167             lineaire ou quasi-lineaire, et le tangent est valide jusqu'a ce que
168             l'on atteigne la precision du calcul.
169
170             On prend dX0 = Normal(0,X) et dX = Alpha*dX0. F est le code de calcul.\n""" + __precision
171         #
172         if len(self._parameters["ResultTitle"]) > 0:
173             __rt = unicode(self._parameters["ResultTitle"])
174             msgs  = u"\n"
175             msgs += __marge + "====" + "="*len(__rt) + "====\n"
176             msgs += __marge + "    " + __rt + "\n"
177             msgs += __marge + "====" + "="*len(__rt) + "====\n"
178         else:
179             msgs  = u""
180         msgs += __msgdoc
181         #
182         __nbtirets = len(__entete) + 2
183         msgs += "\n" + __marge + "-"*__nbtirets
184         msgs += "\n" + __marge + __entete
185         msgs += "\n" + __marge + "-"*__nbtirets
186         #
187         # Boucle sur les perturbations
188         # ----------------------------
189         for i,amplitude in enumerate(Perturbations):
190             dX      = amplitude * dX0
191             #
192             if self._parameters["ResiduFormula"] == "Taylor":
193                 FX_plus_dX  = numpy.asmatrix(numpy.ravel( Hm( Xn + dX ) )).T
194                 #
195                 Residu = numpy.linalg.norm( FX_plus_dX - FX ) / (amplitude * NormeGX)
196                 #
197                 self.StoredVariables["Residu"].store( Residu )
198                 msg = "  %2i  %5.0e   %9.3e   %9.3e   |   %11.5e    %5.1e"%(i,amplitude,NormeX,NormeFX,Residu,abs(Residu-1.)/amplitude)
199                 msgs += "\n" + __marge + msg
200         #
201         msgs += "\n" + __marge + "-"*__nbtirets
202         msgs += "\n"
203         #
204         # Sorties eventuelles
205         # -------------------
206         print("\nResults of tangent check by \"%s\" formula:"%self._parameters["ResiduFormula"])
207         print(msgs)
208         #
209         self._post_run(HO)
210         return 0
211
212 # ==============================================================================
213 if __name__ == "__main__":
214     print('\n AUTODIAGNOSTIC\n')