1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2023 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, "ADJOINTTEST")
32 self.defineRequiredParameter(
33 name = "ResiduFormula",
34 default = "ScalarProduct",
36 message = "Formule de résidu utilisée",
37 listval = ["ScalarProduct"],
39 self.defineRequiredParameter(
40 name = "AmplitudeOfInitialDirection",
43 message = "Amplitude de la direction initiale de la dérivée directionnelle autour du point nominal",
45 self.defineRequiredParameter(
46 name = "EpsilonMinimumExponent",
49 message = "Exposant minimal en puissance de 10 pour le multiplicateur d'incrément",
53 self.defineRequiredParameter(
54 name = "InitialDirection",
57 message = "Direction initiale de la dérivée directionnelle autour du point nominal",
59 self.defineRequiredParameter(
60 name = "NumberOfPrintedDigits",
63 message = "Nombre de chiffres affichés pour les impressions de réels",
66 self.defineRequiredParameter(
70 message = "Titre du tableau et de la figure",
72 self.defineRequiredParameter(
74 typecast = numpy.random.seed,
75 message = "Graine fixée pour le générateur aléatoire",
77 self.defineRequiredParameter(
78 name = "StoreSupplementaryCalculations",
81 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
85 "SimulatedObservationAtCurrentState",
88 self.requireInputArguments(
89 mandatory= ("Xb", "HO" ),
92 self.setAttributes(tags=(
96 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
97 self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
99 Hm = HO["Direct"].appliedTo
100 Ht = HO["Tangent"].appliedInXTo
101 Ha = HO["Adjoint"].appliedInXTo
103 X0 = numpy.ravel( Xb ).reshape((-1,1))
106 __p = self._parameters["NumberOfPrintedDigits"]
111 if len(self._parameters["ResultTitle"]) > 0:
112 __rt = str(self._parameters["ResultTitle"])
113 msgs += (__marge + "====" + "="*len(__rt) + "====\n")
114 msgs += (__marge + " " + __rt + "\n")
115 msgs += (__marge + "====" + "="*len(__rt) + "====\n")
117 msgs += (__marge + "%s\n"%self._name)
118 msgs += (__marge + "%s\n"%("="*len(self._name),))
121 msgs += (__marge + "This test allows to analyze the quality of an adjoint operator associated\n")
122 msgs += (__marge + "to some given direct operator F, applied to one single vector argument x.\n")
123 msgs += (__marge + "If the adjoint operator is approximated and not given, the test measures\n")
124 msgs += (__marge + "the quality of the automatic approximation, around an input checking point X.\n")
126 msgs += (__flech + "Information before launching:\n")
127 msgs += (__marge + "-----------------------------\n")
129 msgs += (__marge + "Characteristics of input vector X, internally converted:\n")
130 msgs += (__marge + " Type...............: %s\n")%type( X0 )
131 msgs += (__marge + " Length of vector...: %i\n")%max(numpy.ravel( X0 ).shape)
132 msgs += (__marge + " Minimum value......: %."+str(__p)+"e\n")%numpy.min( X0 )
133 msgs += (__marge + " Maximum value......: %."+str(__p)+"e\n")%numpy.max( X0 )
134 msgs += (__marge + " Mean of vector.....: %."+str(__p)+"e\n")%numpy.mean( X0, dtype=mfp )
135 msgs += (__marge + " Standard error.....: %."+str(__p)+"e\n")%numpy.std( X0, dtype=mfp )
136 msgs += (__marge + " L2 norm of vector..: %."+str(__p)+"e\n")%numpy.linalg.norm( X0 )
138 msgs += (__marge + "%s\n\n"%("-"*75,))
139 msgs += (__flech + "Numerical quality indicators:\n")
140 msgs += (__marge + "-----------------------------\n")
143 if self._parameters["ResiduFormula"] == "ScalarProduct":
144 msgs += (__marge + "Using the \"%s\" formula, one observes the residue R which is the\n"%self._parameters["ResiduFormula"])
145 msgs += (__marge + "difference of two scalar products:\n")
147 msgs += (__marge + " R(Alpha) = | < TangentF_X(dX) , Y > - < dX , AdjointF_X(Y) > |\n")
149 msgs += (__marge + "which must remain constantly equal to zero to the accuracy of the calculation.\n")
150 msgs += (__marge + "One takes dX0 = Normal(0,X) and dX = Alpha*dX0, where F is the calculation\n")
151 msgs += (__marge + "operator. If it is given, Y must be in the image of F. If it is not given,\n")
152 msgs += (__marge + "one takes Y = F(X).\n")
154 __entete = str.rstrip(" i Alpha " + \
155 str.center("||X||",2+__p+7) + \
156 str.center("||Y||",2+__p+7) + \
157 str.center("||dX||",2+__p+7) + \
158 str.center("R(Alpha)",2+__p+7))
159 __nbtirets = len(__entete) + 2
162 msgs += (__marge + "(Remark: numbers that are (about) under %.0e represent 0 to machine precision)\n"%mpr)
165 Perturbations = [ 10**i for i in range(self._parameters["EpsilonMinimumExponent"],1) ]
166 Perturbations.reverse()
168 NormeX = numpy.linalg.norm( X0 )
170 Yn = numpy.ravel( Hm( X0 ) ).reshape((-1,1))
172 Yn = numpy.ravel( Y ).reshape((-1,1))
173 NormeY = numpy.linalg.norm( Yn )
174 if self._toStore("CurrentState"):
175 self.StoredVariables["CurrentState"].store( X0 )
176 if self._toStore("SimulatedObservationAtCurrentState"):
177 self.StoredVariables["SimulatedObservationAtCurrentState"].store( Yn )
179 dX0 = NumericObjects.SetInitialDirection(
180 self._parameters["InitialDirection"],
181 self._parameters["AmplitudeOfInitialDirection"],
185 # Boucle sur les perturbations
186 # ----------------------------
188 msgs += "\n" + __marge + "-"*__nbtirets
189 msgs += "\n" + __marge + __entete
190 msgs += "\n" + __marge + "-"*__nbtirets
192 __pf = " %"+str(__p+7)+"."+str(__p)+"e"
193 __ms = " %2i %5.0e"+(__pf*4)+"\n"
194 for i,amplitude in enumerate(Perturbations):
196 NormedX = numpy.linalg.norm( dX )
198 if self._parameters["ResiduFormula"] == "ScalarProduct":
199 TangentFXdX = numpy.ravel( Ht( (X0,dX) ) )
200 AdjointFXY = numpy.ravel( Ha( (X0,Yn) ) )
202 Residu = abs(float(numpy.dot( TangentFXdX, Yn ) - numpy.dot( dX, AdjointFXY )))
204 self.StoredVariables["Residu"].store( Residu )
205 ttsep = __ms%(i,amplitude,NormeX,NormeY,NormedX,Residu)
206 msgs += __marge + ttsep
208 msgs += (__marge + "-"*__nbtirets + "\n\n")
209 msgs += (__marge + "End of the \"%s\" verification by the \"%s\" formula.\n\n"%(self._name,self._parameters["ResiduFormula"]))
210 msgs += (__marge + "%s\n"%("-"*75,))
216 # ==============================================================================
217 if __name__ == "__main__":
218 print('\n AUTODIAGNOSTIC\n')