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