Salome HOME
Improvement of algorithms arguments validation and tests
[modules/adao.git] / src / daComposant / daAlgorithms / AdjointTest.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2020 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
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, "ADJOINTTEST")
34         self.defineRequiredParameter(
35             name     = "ResiduFormula",
36             default  = "ScalarProduct",
37             typecast = str,
38             message  = "Formule de résidu utilisée",
39             listval  = ["ScalarProduct"],
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     = "SetSeed",
63             typecast = numpy.random.seed,
64             message  = "Graine fixée pour le générateur aléatoire",
65             )
66         self.defineRequiredParameter(
67             name     = "ResultTitle",
68             default  = "",
69             typecast = str,
70             message  = "Titre du tableau et de la figure",
71             )
72         self.defineRequiredParameter(
73             name     = "StoreSupplementaryCalculations",
74             default  = [],
75             typecast = tuple,
76             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
77             listval  = [
78                 "CurrentState",
79                 "Residu",
80                 "SimulatedObservationAtCurrentState",
81                 ]
82             )
83         self.requireInputArguments(
84             mandatory= ("Xb", "HO" ),
85             optional = ("Y", ),
86             )
87         self.setAttributes(tags=(
88             "Checking",
89             ))
90
91     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
92         self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
93         #
94         Hm = HO["Direct"].appliedTo
95         Ht = HO["Tangent"].appliedInXTo
96         Ha = HO["Adjoint"].appliedInXTo
97         #
98         # ----------
99         Perturbations = [ 10**i for i in range(self._parameters["EpsilonMinimumExponent"],1) ]
100         Perturbations.reverse()
101         #
102         X       = numpy.asmatrix(numpy.ravel( Xb )).T
103         NormeX  = numpy.linalg.norm( X )
104         if Y is None:
105             Y = numpy.asmatrix(numpy.ravel( Hm( X ) )).T
106         Y = numpy.asmatrix(numpy.ravel( Y )).T
107         NormeY = numpy.linalg.norm( Y )
108         if self._toStore("CurrentState"):
109             self.StoredVariables["CurrentState"].store( numpy.ravel(X) )
110         if self._toStore("SimulatedObservationAtCurrentState"):
111             self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(Y) )
112         #
113         if len(self._parameters["InitialDirection"]) == 0:
114             dX0 = []
115             for v in X.A1:
116                 if abs(v) > 1.e-8:
117                     dX0.append( numpy.random.normal(0.,abs(v)) )
118                 else:
119                     dX0.append( numpy.random.normal(0.,X.mean()) )
120         else:
121             dX0 = numpy.asmatrix(numpy.ravel( self._parameters["InitialDirection"] ))
122         #
123         dX0 = float(self._parameters["AmplitudeOfInitialDirection"]) * numpy.matrix( dX0 ).T
124         #
125         # Entete des resultats
126         # --------------------
127         __marge =  12*u" "
128         __precision = u"""
129             Remarque : les nombres inferieurs a %.0e (environ) representent un zero
130                        a la precision machine.\n"""%mpr
131         if self._parameters["ResiduFormula"] == "ScalarProduct":
132             __entete = u"  i   Alpha     ||X||       ||Y||       ||dX||        R(Alpha)"
133             __msgdoc = u"""
134             On observe le residu qui est la difference de deux produits scalaires :
135
136               R(Alpha) = | < TangentF_X(dX) , Y > - < dX , AdjointF_X(Y) > |
137
138             qui doit rester constamment egal a zero a la precision du calcul.
139             On prend dX0 = Normal(0,X) et dX = Alpha*dX0. F est le code de calcul.
140             Y doit etre dans l'image de F. S'il n'est pas donne, on prend Y = F(X).\n""" + __precision
141         #
142         if len(self._parameters["ResultTitle"]) > 0:
143             __rt = unicode(self._parameters["ResultTitle"])
144             msgs  = u"\n"
145             msgs += __marge + "====" + "="*len(__rt) + "====\n"
146             msgs += __marge + "    " + __rt + "\n"
147             msgs += __marge + "====" + "="*len(__rt) + "====\n"
148         else:
149             msgs  = u""
150         msgs += __msgdoc
151         #
152         __nbtirets = len(__entete) + 2
153         msgs += "\n" + __marge + "-"*__nbtirets
154         msgs += "\n" + __marge + __entete
155         msgs += "\n" + __marge + "-"*__nbtirets
156         #
157         Normalisation= -1
158         #
159         # ----------
160         for i,amplitude in enumerate(Perturbations):
161             dX          = amplitude * dX0
162             NormedX     = numpy.linalg.norm( dX )
163             #
164             TangentFXdX = numpy.asmatrix( Ht( (X,dX) ) )
165             AdjointFXY  = numpy.asmatrix( Ha( (X,Y)  ) )
166             #
167             Residu = abs(float(numpy.dot( TangentFXdX.A1 , Y.A1 ) - numpy.dot( dX.A1 , AdjointFXY.A1 )))
168             #
169             msg = "  %2i  %5.0e   %9.3e   %9.3e   %9.3e   |  %9.3e"%(i,amplitude,NormeX,NormeY,NormedX,Residu)
170             msgs += "\n" + __marge + msg
171             #
172             self.StoredVariables["Residu"].store( Residu )
173         #
174         msgs += "\n" + __marge + "-"*__nbtirets
175         msgs += "\n"
176         #
177         # Sorties eventuelles
178         # -------------------
179         print("\nResults of adjoint check by \"%s\" formula:"%self._parameters["ResiduFormula"])
180         print(msgs)
181         #
182         self._post_run(HO)
183         return 0
184
185 # ==============================================================================
186 if __name__ == "__main__":
187     print('\n AUTODIAGNOSTIC\n')