Salome HOME
Range and dictionary key handling improvement
[modules/adao.git] / src / daComposant / daAlgorithms / AdjointTest.py
1 #-*-coding:iso-8859-1-*-
2 #
3 # Copyright (C) 2008-2017 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 logging
24 from daCore import BasicObjects, PlatformInfo
25 import numpy
26 mpr = PlatformInfo.PlatformInfo().MachinePrecision()
27
28 # ==============================================================================
29 class ElementaryAlgorithm(BasicObjects.Algorithm):
30     def __init__(self):
31         BasicObjects.Algorithm.__init__(self, "ADJOINTTEST")
32         self.defineRequiredParameter(
33             name     = "ResiduFormula",
34             default  = "ScalarProduct",
35             typecast = str,
36             message  = "Formule de résidu utilisée",
37             listval  = ["ScalarProduct"],
38             )
39         self.defineRequiredParameter(
40             name     = "EpsilonMinimumExponent",
41             default  = -8,
42             typecast = int,
43             message  = "Exposant minimal en puissance de 10 pour le multiplicateur d'incrément",
44             minval   = -20,
45             maxval   = 0,
46             )
47         self.defineRequiredParameter(
48             name     = "InitialDirection",
49             default  = [],
50             typecast = list,
51             message  = "Direction initiale de la dérivée directionnelle autour du point nominal",
52             )
53         self.defineRequiredParameter(
54             name     = "AmplitudeOfInitialDirection",
55             default  = 1.,
56             typecast = float,
57             message  = "Amplitude de la direction initiale de la dérivée directionnelle autour du point nominal",
58             )
59         self.defineRequiredParameter(
60             name     = "SetSeed",
61             typecast = numpy.random.seed,
62             message  = "Graine fixée pour le générateur aléatoire",
63             )
64         self.defineRequiredParameter(
65             name     = "ResultTitle",
66             default  = "",
67             typecast = str,
68             message  = "Titre du tableau et de la figure",
69             )
70         self.defineRequiredParameter(
71             name     = "StoreSupplementaryCalculations",
72             default  = [],
73             typecast = tuple,
74             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
75             listval  = ["CurrentState", "Residu", "SimulatedObservationAtCurrentState"]
76             )
77
78     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
79         self._pre_run(Parameters)
80         #
81         Hm = HO["Direct"].appliedTo
82         Ht = HO["Tangent"].appliedInXTo
83         Ha = HO["Adjoint"].appliedInXTo
84         #
85         # ----------
86         Perturbations = [ 10**i for i in range(self._parameters["EpsilonMinimumExponent"],1) ]
87         Perturbations.reverse()
88         #
89         X       = numpy.asmatrix(numpy.ravel( Xb )).T
90         NormeX  = numpy.linalg.norm( X )
91         if Y is None:
92             Y = numpy.asmatrix(numpy.ravel( Hm( X ) )).T
93         Y = numpy.asmatrix(numpy.ravel( Y )).T
94         NormeY = numpy.linalg.norm( Y )
95         if "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
96             self.StoredVariables["CurrentState"].store( numpy.ravel(X) )
97         if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
98             self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(Y) )
99         #
100         if len(self._parameters["InitialDirection"]) == 0:
101             dX0 = []
102             for v in X.A1:
103                 if abs(v) > 1.e-8:
104                     dX0.append( numpy.random.normal(0.,abs(v)) )
105                 else:
106                     dX0.append( numpy.random.normal(0.,X.mean()) )
107         else:
108             dX0 = numpy.asmatrix(numpy.ravel( self._parameters["InitialDirection"] ))
109         #
110         dX0 = float(self._parameters["AmplitudeOfInitialDirection"]) * numpy.matrix( dX0 ).T
111         #
112         # Entete des resultats
113         # --------------------
114         __marge =  12*" "
115         __precision = """
116             Remarque : les nombres inferieurs a %.0e (environ) representent un zero
117                        a la precision machine.\n"""%mpr
118         if self._parameters["ResiduFormula"] == "ScalarProduct":
119             __entete = "  i   Alpha     ||X||       ||Y||       ||dX||        R(Alpha)  "
120             __msgdoc = """
121             On observe le residu qui est la difference de deux produits scalaires :
122
123               R(Alpha) = | < TangentF_X(dX) , Y > - < dX , AdjointF_X(Y) > |
124
125             qui doit rester constamment egal a zero a la precision du calcul.
126             On prend dX0 = Normal(0,X) et dX = Alpha*dX0. F est le code de calcul.
127             Y doit etre dans l'image de F. S'il n'est pas donne, on prend Y = F(X).
128             """ + __precision
129         #
130         if len(self._parameters["ResultTitle"]) > 0:
131             msgs  = "\n"
132             msgs += __marge + "====" + "="*len(self._parameters["ResultTitle"]) + "====\n"
133             msgs += __marge + "    " + self._parameters["ResultTitle"] + "\n"
134             msgs += __marge + "====" + "="*len(self._parameters["ResultTitle"]) + "====\n"
135         else:
136             msgs  = ""
137         msgs += __msgdoc
138         #
139         __nbtirets = len(__entete)
140         msgs += "\n" + __marge + "-"*__nbtirets
141         msgs += "\n" + __marge + __entete
142         msgs += "\n" + __marge + "-"*__nbtirets
143         #
144         Normalisation= -1
145         #
146         # ----------
147         for i,amplitude in enumerate(Perturbations):
148             dX          = amplitude * dX0
149             NormedX     = numpy.linalg.norm( dX )
150             #
151             TangentFXdX = numpy.asmatrix( Ht( (X,dX) ) )
152             AdjointFXY  = numpy.asmatrix( Ha( (X,Y)  ) )
153             #
154             Residu = abs(float(numpy.dot( TangentFXdX.A1 , Y.A1 ) - numpy.dot( dX.A1 , AdjointFXY.A1 )))
155             #
156             msg = "  %2i  %5.0e   %9.3e   %9.3e   %9.3e   |  %9.3e"%(i,amplitude,NormeX,NormeY,NormedX,Residu)
157             msgs += "\n" + __marge + msg
158             #
159             self.StoredVariables["Residu"].store( Residu )
160         #
161         msgs += "\n" + __marge + "-"*__nbtirets
162         msgs += "\n"
163         #
164         # Sorties eventuelles
165         # -------------------
166         print("\nResults of adjoint check by \"%s\" formula:"%self._parameters["ResiduFormula"])
167         print(msgs)
168         #
169         self._post_run(HO)
170         return 0
171
172 # ==============================================================================
173 if __name__ == "__main__":
174     print('\n AUTODIAGNOSTIC \n')