Salome HOME
Correcting date copyright and version name information
[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, H=None, M=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         # Paramètres de pilotage
77         # ----------------------
78         self.setParameters(Parameters)
79         #
80         # Opérateur d'observation
81         # -----------------------
82         Hm = H["Direct"].appliedTo
83         Ht = H["Tangent"].appliedInXTo
84         Ha = H["Adjoint"].appliedInXTo
85         #
86         # Construction des perturbations
87         # ------------------------------
88         Perturbations = [ 10**i for i in xrange(self._parameters["EpsilonMinimumExponent"],1) ]
89         Perturbations.reverse()
90         #
91         # Calcul du point courant
92         # -----------------------
93         X       = numpy.asmatrix(numpy.ravel( Xb )).T
94         NormeX  = numpy.linalg.norm( X )
95         if Y is None:
96             Y = numpy.asmatrix(numpy.ravel( Hm( X ) )).T
97         Y = numpy.asmatrix(numpy.ravel( Y )).T
98         NormeY = numpy.linalg.norm( Y )
99         #
100         # Fabrication de la direction de  l'incrément dX
101         # ----------------------------------------------
102         if len(self._parameters["InitialDirection"]) == 0:
103             dX0 = []
104             for v in X.A1:
105                 if abs(v) > 1.e-8:
106                     dX0.append( numpy.random.normal(0.,abs(v)) )
107                 else:
108                     dX0.append( numpy.random.normal(0.,X.mean()) )
109         else:
110             dX0 = numpy.asmatrix(numpy.ravel( self._parameters["InitialDirection"] ))
111         #
112         dX0 = float(self._parameters["AmplitudeOfInitialDirection"]) * numpy.matrix( dX0 ).T
113         #
114         # Utilisation de F(X) si aucune observation n'est donnee
115         # ------------------------------------------------------
116         #
117         # Entete des resultats
118         # --------------------
119         if self._parameters["ResiduFormula"] is "ScalarProduct":
120             __doc__ = """
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 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             """
129         else:
130             __doc__ = ""
131         #
132         msgs  = "         ====" + "="*len(self._parameters["ResultTitle"]) + "====\n"
133         msgs += "             " + self._parameters["ResultTitle"] + "\n"
134         msgs += "         ====" + "="*len(self._parameters["ResultTitle"]) + "====\n"
135         msgs += __doc__
136         #
137         msg = "  i   Alpha     ||X||       ||Y||       ||dX||        R(Alpha)  "
138         nbtirets = len(msg)
139         msgs += "\n" + "-"*nbtirets
140         msgs += "\n" + msg
141         msgs += "\n" + "-"*nbtirets
142         #
143         Normalisation= -1
144         #
145         # Boucle sur les perturbations
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" + msg
158             #
159             self.StoredVariables["CostFunctionJ"].store( Residu )
160         msgs += "\n" + "-"*nbtirets
161         msgs += "\n"
162         #
163         # Sorties eventuelles
164         # -------------------
165         print
166         print "Results of adjoint stability check:"
167         print msgs
168         #
169         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
170         logging.debug("%s Terminé"%self._name)
171         #
172         return 0
173
174 # ==============================================================================
175 if __name__ == "__main__":
176     print '\n AUTODIAGNOSTIC \n'