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