Salome HOME
Adding adjoint checker and internal tests
[modules/adao.git] / src / daComposant / daAlgorithms / AdjointTest.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2012 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
22 import logging
23 from daCore import BasicObjects, PlatformInfo
24 m = PlatformInfo.SystemUsage()
25
26 import numpy
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
71     def run(self, Xb=None, Y=None, H=None, M=None, R=None, B=None, Q=None, Parameters=None):
72         logging.debug("%s Lancement"%self._name)
73         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("Mo")))
74         #
75         # Paramètres de pilotage
76         # ----------------------
77         self.setParameters(Parameters)
78         #
79         # Opérateur d'observation
80         # -----------------------
81         Hm = H["Direct"].appliedTo
82         Ht = H["Tangent"].appliedInXTo
83         Ha = H["Adjoint"].appliedInXTo
84         #
85         # Construction des perturbations
86         # ------------------------------
87         Perturbations = [ 10**i for i in xrange(self._parameters["EpsilonMinimumExponent"],1) ]
88         Perturbations.reverse()
89         #
90         # Calcul du point courant
91         # -----------------------
92         X       = numpy.asmatrix(Xb).flatten().T
93         NormeX  = numpy.linalg.norm( X )
94         if Y is None:
95             Y = numpy.asmatrix( Hm( X ) ).flatten().T
96         Y = numpy.asmatrix(Y).flatten().T
97         NormeY = numpy.linalg.norm( Y )
98         #
99         # Fabrication de la direction de  l'incrément dX
100         # ----------------------------------------------
101         if len(self._parameters["InitialDirection"]) == 0:
102             dX0 = []
103             for v in X.A1:
104                 if abs(v) > 1.e-8:
105                     dX0.append( numpy.random.normal(0.,abs(v)) )
106                 else:
107                     dX0.append( numpy.random.normal(0.,X.mean()) )
108         else:
109             dX0 = numpy.asmatrix(self._parameters["InitialDirection"]).flatten()
110         #
111         dX0 = float(self._parameters["AmplitudeOfInitialDirection"]) * numpy.matrix( dX0 ).T
112         #
113         # Utilisation de F(X) si aucune observation n'est donnee
114         # ------------------------------------------------------
115         #
116         # Entete des resultats
117         # --------------------
118         if self._parameters["ResiduFormula"] is "ScalarProduct":
119             __doc__ = """
120             On observe le residu qui est la difference de deux produits scalaires :
121             
122               R(Alpha) = | < TangentF_X(dX) , Y > - < dX , AdjointF_X(Y) > |
123             
124             qui doit rester constamment egal zero a la precision du calcul.
125             On prend dX0 = Normal(0,X) et dX = Alpha*dX0. F est le code de calcul.
126             Y doit etre dans l'image de F. S'il n'est pas donne, on prend Y = F(X).
127             """
128         else:
129             __doc__ = ""
130         #
131         msgs  = "         ====" + "="*len(self._parameters["ResultTitle"]) + "====\n"
132         msgs += "             " + self._parameters["ResultTitle"] + "\n"
133         msgs += "         ====" + "="*len(self._parameters["ResultTitle"]) + "====\n"
134         msgs += __doc__
135         #
136         msg = "  i   Alpha     ||X||       ||Y||       ||dX||        R(Alpha)  "
137         nbtirets = len(msg)
138         msgs += "\n" + "-"*nbtirets
139         msgs += "\n" + msg
140         msgs += "\n" + "-"*nbtirets
141         #
142         Normalisation= -1
143         #
144         # Boucle sur les perturbations
145         # ----------------------------
146         for i,amplitude in enumerate(Perturbations):
147             logging.debug("%s Etape de calcul numéro %i, avec la perturbation %8.3e"%(self._name, i, amplitude))
148             #
149             dX          = amplitude * dX0
150             NormedX     = numpy.linalg.norm( dX )
151             #
152             TangentFXdX = numpy.asmatrix( Ht( (X,dX) ) )
153             AdjointFXY  = numpy.asmatrix( Ha( (X,Y)  ) )
154             #
155             Residu = abs(float(numpy.dot( TangentFXdX.A1 , Y.A1 ) - numpy.dot( dX.A1 , AdjointFXY.A1 )))
156             #
157             msg = "  %2i  %5.0e   %9.3e   %9.3e   %9.3e   |  %9.3e"%(i,amplitude,NormeX,NormeY,NormedX,Residu)
158             msgs += "\n" + msg
159             #
160             self.StoredVariables["CostFunctionJ"].store( Residu )
161         msgs += "\n" + "-"*nbtirets
162         msgs += "\n"
163         #
164         # Sorties eventuelles
165         # -------------------
166         logging.debug("%s Résultats :\n%s"%(self._name, msgs))
167         print
168         print "Results of adjoint stability check:"
169         print msgs
170         #
171         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("Mo")))
172         logging.debug("%s Terminé"%self._name)
173         #
174         return 0
175
176 # ==============================================================================
177 if __name__ == "__main__":
178     print '\n AUTODIAGNOSTIC \n'