1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2021 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, PlatformInfo
26 mpr = PlatformInfo.PlatformInfo().MachinePrecision()
27 if sys.version_info.major > 2:
30 # ==============================================================================
31 class ElementaryAlgorithm(BasicObjects.Algorithm):
33 BasicObjects.Algorithm.__init__(self, "TANGENTTEST")
34 self.defineRequiredParameter(
35 name = "ResiduFormula",
38 message = "Formule de résidu utilisée",
41 self.defineRequiredParameter(
42 name = "EpsilonMinimumExponent",
45 message = "Exposant minimal en puissance de 10 pour le multiplicateur d'incrément",
49 self.defineRequiredParameter(
50 name = "InitialDirection",
53 message = "Direction initiale de la dérivée directionnelle autour du point nominal",
55 self.defineRequiredParameter(
56 name = "AmplitudeOfInitialDirection",
59 message = "Amplitude de la direction initiale de la dérivée directionnelle autour du point nominal",
61 self.defineRequiredParameter(
62 name = "AmplitudeOfTangentPerturbation",
65 message = "Amplitude de la perturbation pour le calcul de la forme tangente",
69 self.defineRequiredParameter(
71 typecast = numpy.random.seed,
72 message = "Graine fixée pour le générateur aléatoire",
74 self.defineRequiredParameter(
78 message = "Titre du tableau et de la figure",
80 self.defineRequiredParameter(
81 name = "StoreSupplementaryCalculations",
84 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
88 "SimulatedObservationAtCurrentState",
91 self.requireInputArguments(
92 mandatory= ("Xb", "HO"),
94 self.setAttributes(tags=(
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)
101 Hm = HO["Direct"].appliedTo
102 Ht = HO["Tangent"].appliedInXTo
104 # Construction des perturbations
105 # ------------------------------
106 Perturbations = [ 10**i for i in range(self._parameters["EpsilonMinimumExponent"],1) ]
107 Perturbations.reverse()
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) )
120 # Fabrication de la direction de l'increment dX
121 # ---------------------------------------------
122 if len(self._parameters["InitialDirection"]) == 0:
126 dX0.append( numpy.random.normal(0.,abs(v)) )
128 dX0.append( numpy.random.normal(0.,Xn.mean()) )
130 dX0 = numpy.ravel( self._parameters["InitialDirection"] )
132 dX0 = float(self._parameters["AmplitudeOfInitialDirection"]) * numpy.matrix( dX0 ).T
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 )
143 # Entete des resultats
144 # --------------------
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"
152 On observe le residu provenant du rapport d'increments utilisant le
155 || F(X+Alpha*dX) - F(X) ||
156 R(Alpha) = -----------------------------
157 || Alpha * TangentF_X * dX ||
159 qui doit rester stable en 1+O(Alpha) jusqu'a ce que l'on atteigne la
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.
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.
170 On prend dX0 = Normal(0,X) et dX = Alpha*dX0. F est le code de calcul.\n""" + __precision
172 if len(self._parameters["ResultTitle"]) > 0:
173 __rt = unicode(self._parameters["ResultTitle"])
175 msgs += __marge + "====" + "="*len(__rt) + "====\n"
176 msgs += __marge + " " + __rt + "\n"
177 msgs += __marge + "====" + "="*len(__rt) + "====\n"
182 __nbtirets = len(__entete) + 2
183 msgs += "\n" + __marge + "-"*__nbtirets
184 msgs += "\n" + __marge + __entete
185 msgs += "\n" + __marge + "-"*__nbtirets
187 # Boucle sur les perturbations
188 # ----------------------------
189 for i,amplitude in enumerate(Perturbations):
192 if self._parameters["ResiduFormula"] == "Taylor":
193 FX_plus_dX = numpy.asmatrix(numpy.ravel( Hm( Xn + dX ) )).T
195 Residu = numpy.linalg.norm( FX_plus_dX - FX ) / (amplitude * NormeGX)
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
201 msgs += "\n" + __marge + "-"*__nbtirets
204 # Sorties eventuelles
205 # -------------------
206 print("\nResults of tangent check by \"%s\" formula:"%self._parameters["ResiduFormula"])
212 # ==============================================================================
213 if __name__ == "__main__":
214 print('\n AUTODIAGNOSTIC\n')