1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2019 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, "ADJOINTTEST")
34 self.defineRequiredParameter(
35 name = "ResiduFormula",
36 default = "ScalarProduct",
38 message = "Formule de résidu utilisée",
39 listval = ["ScalarProduct"],
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(
63 typecast = numpy.random.seed,
64 message = "Graine fixée pour le générateur aléatoire",
66 self.defineRequiredParameter(
70 message = "Titre du tableau et de la figure",
72 self.defineRequiredParameter(
73 name = "StoreSupplementaryCalculations",
76 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
80 "SimulatedObservationAtCurrentState",
83 self.requireInputArguments(
84 mandatory= ("Xb", "HO" ),
88 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
89 self._pre_run(Parameters, Xb, Y, R, B, Q)
91 Hm = HO["Direct"].appliedTo
92 Ht = HO["Tangent"].appliedInXTo
93 Ha = HO["Adjoint"].appliedInXTo
96 Perturbations = [ 10**i for i in range(self._parameters["EpsilonMinimumExponent"],1) ]
97 Perturbations.reverse()
99 X = numpy.asmatrix(numpy.ravel( Xb )).T
100 NormeX = numpy.linalg.norm( X )
102 Y = numpy.asmatrix(numpy.ravel( Hm( X ) )).T
103 Y = numpy.asmatrix(numpy.ravel( Y )).T
104 NormeY = numpy.linalg.norm( Y )
105 if self._toStore("CurrentState"):
106 self.StoredVariables["CurrentState"].store( numpy.ravel(X) )
107 if self._toStore("SimulatedObservationAtCurrentState"):
108 self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(Y) )
110 if len(self._parameters["InitialDirection"]) == 0:
114 dX0.append( numpy.random.normal(0.,abs(v)) )
116 dX0.append( numpy.random.normal(0.,X.mean()) )
118 dX0 = numpy.asmatrix(numpy.ravel( self._parameters["InitialDirection"] ))
120 dX0 = float(self._parameters["AmplitudeOfInitialDirection"]) * numpy.matrix( dX0 ).T
122 # Entete des resultats
123 # --------------------
126 Remarque : les nombres inferieurs a %.0e (environ) representent un zero
127 a la precision machine.\n"""%mpr
128 if self._parameters["ResiduFormula"] == "ScalarProduct":
129 __entete = u" i Alpha ||X|| ||Y|| ||dX|| R(Alpha)"
131 On observe le residu qui est la difference de deux produits scalaires :
133 R(Alpha) = | < TangentF_X(dX) , Y > - < dX , AdjointF_X(Y) > |
135 qui doit rester constamment egal a zero a la precision du calcul.
136 On prend dX0 = Normal(0,X) et dX = Alpha*dX0. F est le code de calcul.
137 Y doit etre dans l'image de F. S'il n'est pas donne, on prend Y = F(X).\n""" + __precision
139 if len(self._parameters["ResultTitle"]) > 0:
140 __rt = unicode(self._parameters["ResultTitle"])
142 msgs += __marge + "====" + "="*len(__rt) + "====\n"
143 msgs += __marge + " " + __rt + "\n"
144 msgs += __marge + "====" + "="*len(__rt) + "====\n"
149 __nbtirets = len(__entete) + 2
150 msgs += "\n" + __marge + "-"*__nbtirets
151 msgs += "\n" + __marge + __entete
152 msgs += "\n" + __marge + "-"*__nbtirets
157 for i,amplitude in enumerate(Perturbations):
159 NormedX = numpy.linalg.norm( dX )
161 TangentFXdX = numpy.asmatrix( Ht( (X,dX) ) )
162 AdjointFXY = numpy.asmatrix( Ha( (X,Y) ) )
164 Residu = abs(float(numpy.dot( TangentFXdX.A1 , Y.A1 ) - numpy.dot( dX.A1 , AdjointFXY.A1 )))
166 msg = " %2i %5.0e %9.3e %9.3e %9.3e | %9.3e"%(i,amplitude,NormeX,NormeY,NormedX,Residu)
167 msgs += "\n" + __marge + msg
169 self.StoredVariables["Residu"].store( Residu )
171 msgs += "\n" + __marge + "-"*__nbtirets
174 # Sorties eventuelles
175 # -------------------
176 print("\nResults of adjoint check by \"%s\" formula:"%self._parameters["ResiduFormula"])
182 # ==============================================================================
183 if __name__ == "__main__":
184 print('\n AUTODIAGNOSTIC \n')