]> SALOME platform Git repositories - modules/adao.git/blob - src/daComposant/daNumerics/ApproximatedDerivatives.py
Salome HOME
71334404a6365757f0a7cd8dc5174f1d861a0f03
[modules/adao.git] / src / daComposant / daNumerics / ApproximatedDerivatives.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2015 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 __doc__ = """
24     Définit les versions approximées des opérateurs tangents et adjoints.
25 """
26 __author__ = "Jean-Philippe ARGAUD"
27
28 import os, numpy, time, copy, types, sys
29 import logging
30 from daCore.BasicObjects import Operator
31 # logging.getLogger().setLevel(logging.DEBUG)
32
33 # ==============================================================================
34 def ExecuteFunction( (X, funcrepr) ):
35     __X = numpy.asmatrix(numpy.ravel( X )).T
36     __sys_path_tmp = sys.path ; sys.path.insert(0,funcrepr["__userFunction__path"])
37     __module = __import__(funcrepr["__userFunction__modl"], globals(), locals(), [])
38     __fonction = getattr(__module,funcrepr["__userFunction__name"])
39     sys.path = __sys_path_tmp ; del __sys_path_tmp
40     __HX  = __fonction( __X )
41     return numpy.ravel( __HX )
42
43 # ==============================================================================
44 class FDApproximation(object):
45     """
46     Cette classe sert d'interface pour définir les opérateurs approximés. A la
47     création d'un objet, en fournissant une fonction "Function", on obtient un
48     objet qui dispose de 3 méthodes "DirectOperator", "TangentOperator" et
49     "AdjointOperator". On contrôle l'approximation DF avec l'incrément
50     multiplicatif "increment" valant par défaut 1%, ou avec l'incrément fixe
51     "dX" qui sera multiplié par "increment" (donc en %), et on effectue de DF
52     centrées si le booléen "centeredDF" est vrai.
53     """
54     def __init__(self,
55             Function              = None,
56             centeredDF            = False,
57             increment             = 0.01,
58             dX                    = None,
59             avoidingRedundancy    = True,
60             toleranceInRedundancy = 1.e-18,
61             lenghtOfRedundancy    = -1,
62             mpEnabled             = False,
63             mpWorkers             = None,
64             ):
65         if mpEnabled:
66             try:
67                 import multiprocessing
68                 self.__mpEnabled = True
69             except ImportError:
70                 self.__mpEnabled = False
71         else:
72             self.__mpEnabled = False
73         self.__mpWorkers = mpWorkers
74         if self.__mpWorkers is not None and self.__mpWorkers < 1:
75             self.__mpWorkers = None
76         logging.debug("FDA Calculs en multiprocessing : %s (nombre de processus : %s)"%(self.__mpEnabled,self.__mpWorkers))
77         #
78         if self.__mpEnabled:
79             if isinstance(Function,types.FunctionType):
80                 logging.debug("FDA Calculs en multiprocessing : FunctionType")
81                 self.__userFunction__name = Function.__name__
82                 try:
83                     mod = os.path.join(Function.__globals__['filepath'],Function.__globals__['filename'])
84                 except:
85                     mod = os.path.abspath(Function.__globals__['__file__'])
86                 if not os.path.isfile(mod):
87                     raise ImportError("No user defined function or method found with the name %s"%(mod,))
88                 self.__userFunction__modl = os.path.basename(mod).replace('.pyc','').replace('.pyo','').replace('.py','')
89                 self.__userFunction__path = os.path.dirname(mod)
90                 del mod
91                 self.__userOperator = Operator( fromMethod = Function )
92                 self.__userFunction = self.__userOperator.appliedTo # Pour le calcul Direct
93             elif isinstance(Function,types.MethodType):
94                 logging.debug("FDA Calculs en multiprocessing : MethodType")
95                 self.__userFunction__name = Function.__name__
96                 try:
97                     mod = os.path.join(Function.__globals__['filepath'],Function.__globals__['filename'])
98                 except:
99                     mod = os.path.abspath(Function.im_func.__globals__['__file__'])
100                 if not os.path.isfile(mod):
101                     raise ImportError("No user defined function or method found with the name %s"%(mod,))
102                 self.__userFunction__modl = os.path.basename(mod).replace('.pyc','').replace('.pyo','').replace('.py','')
103                 self.__userFunction__path = os.path.dirname(mod)
104                 del mod
105                 self.__userOperator = Operator( fromMethod = Function )
106                 self.__userFunction = self.__userOperator.appliedTo # Pour le calcul Direct
107             else:
108                 raise TypeError("User defined function or method has to be provided for finite differences approximation.")
109         else:
110             self.__userOperator = Operator( fromMethod = Function )
111             self.__userFunction = self.__userOperator.appliedTo
112         #
113         self.__centeredDF = bool(centeredDF)
114         if avoidingRedundancy:
115             self.__avoidRC = True
116             self.__tolerBP = float(toleranceInRedundancy)
117             self.__lenghtRJ = int(lenghtOfRedundancy)
118             self.__listJPCP = [] # Jacobian Previous Calculated Points
119             self.__listJPCI = [] # Jacobian Previous Calculated Increment
120             self.__listJPCR = [] # Jacobian Previous Calculated Results
121             self.__listJPPN = [] # Jacobian Previous Calculated Point Norms
122             self.__listJPIN = [] # Jacobian Previous Calculated Increment Norms
123         else:
124             self.__avoidRC = False
125         if float(increment) <> 0.:
126             self.__increment  = float(increment)
127         else:
128             self.__increment  = 0.01
129         if dX is None:  
130             self.__dX     = None
131         else:
132             self.__dX     = numpy.asmatrix(numpy.ravel( dX )).T
133         logging.debug("FDA Reduction des doublons de calcul : %s"%self.__avoidRC)
134         if self.__avoidRC:
135             logging.debug("FDA Tolerance de determination des doublons : %.2e"%self.__tolerBP)
136
137     # ---------------------------------------------------------
138     def __doublon__(self, e, l, n, v=None):
139         __ac, __iac = False, -1
140         for i in xrange(len(l)-1,-1,-1):
141             if numpy.linalg.norm(e - l[i]) < self.__tolerBP * n[i]:
142                 __ac, __iac = True, i
143                 if v is not None: logging.debug("FDA Cas%s déja calculé, récupération du doublon %i"%(v,__iac))
144                 break
145         return __ac, __iac
146
147     # ---------------------------------------------------------
148     def DirectOperator(self, X ):
149         """
150         Calcul du direct à l'aide de la fonction fournie.
151         """
152         logging.debug("FDA Calcul DirectOperator (explicite)")
153         _X = numpy.asmatrix(numpy.ravel( X )).T
154         _HX = numpy.ravel(self.__userFunction( _X ))
155         #
156         return _HX
157
158     # ---------------------------------------------------------
159     def TangentMatrix(self, X ):
160         """
161         Calcul de l'opérateur tangent comme la Jacobienne par différences finies,
162         c'est-à-dire le gradient de H en X. On utilise des différences finies
163         directionnelles autour du point X. X est un numpy.matrix.
164         
165         Différences finies centrées (approximation d'ordre 2):
166         1/ Pour chaque composante i de X, on ajoute et on enlève la perturbation
167            dX[i] à la  composante X[i], pour composer X_plus_dXi et X_moins_dXi, et
168            on calcule les réponses HX_plus_dXi = H( X_plus_dXi ) et HX_moins_dXi =
169            H( X_moins_dXi )
170         2/ On effectue les différences (HX_plus_dXi-HX_moins_dXi) et on divise par
171            le pas 2*dXi
172         3/ Chaque résultat, par composante, devient une colonne de la Jacobienne
173         
174         Différences finies non centrées (approximation d'ordre 1):
175         1/ Pour chaque composante i de X, on ajoute la perturbation dX[i] à la 
176            composante X[i] pour composer X_plus_dXi, et on calcule la réponse
177            HX_plus_dXi = H( X_plus_dXi )
178         2/ On calcule la valeur centrale HX = H(X)
179         3/ On effectue les différences (HX_plus_dXi-HX) et on divise par
180            le pas dXi
181         4/ Chaque résultat, par composante, devient une colonne de la Jacobienne
182         
183         """
184         logging.debug("FDA Calcul de la Jacobienne")
185         logging.debug("FDA   Incrément de............: %s*X"%float(self.__increment))
186         logging.debug("FDA   Approximation centrée...: %s"%(self.__centeredDF))
187         #
188         if X is None or len(X)==0:
189             raise ValueError("Nominal point X for approximate derivatives can not be None or void (X=%s)."%(str(X),))
190         #
191         _X = numpy.asmatrix(numpy.ravel( X )).T
192         #
193         if self.__dX is None:
194             _dX  = self.__increment * _X
195         else:
196             _dX = numpy.asmatrix(numpy.ravel( self.__dX )).T
197         #
198         if (_dX == 0.).any():
199             moyenne = _dX.mean()
200             if moyenne == 0.:
201                 _dX = numpy.where( _dX == 0., float(self.__increment), _dX )
202             else:
203                 _dX = numpy.where( _dX == 0., moyenne, _dX )
204         #
205         __alreadyCalculated  = False
206         if self.__avoidRC:
207             __bidon, __alreadyCalculatedP = self.__doublon__(_X,  self.__listJPCP, self.__listJPPN, None)
208             __bidon, __alreadyCalculatedI = self.__doublon__(_dX, self.__listJPCI, self.__listJPIN, None)
209             if __alreadyCalculatedP == __alreadyCalculatedI > -1:
210                 __alreadyCalculated, __i = True, __alreadyCalculatedP
211                 logging.debug("FDA Cas J déja calculé, récupération du doublon %i"%__i)
212         #
213         if __alreadyCalculated:
214             logging.debug("FDA   Calcul Jacobienne (par récupération du doublon %i)"%__i)
215             _Jacobienne = self.__listJPCR[__i]
216         else:
217             logging.debug("FDA   Calcul Jacobienne (explicite)")
218             if self.__centeredDF:
219                 #
220                 if self.__mpEnabled:
221                     funcrepr = {
222                         "__userFunction__path" : self.__userFunction__path,
223                         "__userFunction__modl" : self.__userFunction__modl,
224                         "__userFunction__name" : self.__userFunction__name,
225                     }
226                     _jobs = []
227                     for i in range( len(_dX) ):
228                         _dXi            = _dX[i]
229                         _X_plus_dXi     = numpy.array( _X.A1, dtype=float )
230                         _X_plus_dXi[i]  = _X[i] + _dXi
231                         _X_moins_dXi    = numpy.array( _X.A1, dtype=float )
232                         _X_moins_dXi[i] = _X[i] - _dXi
233                         #
234                         _jobs.append( (_X_plus_dXi,  funcrepr) )
235                         _jobs.append( (_X_moins_dXi, funcrepr) )
236                     #
237                     import multiprocessing
238                     self.__pool = multiprocessing.Pool(self.__mpWorkers)
239                     _HX_plusmoins_dX = self.__pool.map( ExecuteFunction, _jobs )
240                     self.__pool.close()
241                     self.__pool.join()
242                     #
243                     _Jacobienne  = []
244                     for i in range( len(_dX) ):
245                         _Jacobienne.append( numpy.ravel( _HX_plusmoins_dX[2*i] - _HX_plusmoins_dX[2*i+1] ) / (2.*_dX[i]) )
246                 else:
247                     _Jacobienne  = []
248                     for i in range( _dX.size ):
249                         _dXi            = _dX[i]
250                         _X_plus_dXi     = numpy.array( _X.A1, dtype=float )
251                         _X_plus_dXi[i]  = _X[i] + _dXi
252                         _X_moins_dXi    = numpy.array( _X.A1, dtype=float )
253                         _X_moins_dXi[i] = _X[i] - _dXi
254                         #
255                         _HX_plus_dXi    = self.DirectOperator( _X_plus_dXi )
256                         _HX_moins_dXi   = self.DirectOperator( _X_moins_dXi )
257                         #
258                         _Jacobienne.append( numpy.ravel( _HX_plus_dXi - _HX_moins_dXi ) / (2.*_dXi) )
259                 #
260             else:
261                 #
262                 if self.__mpEnabled:
263                     _HX_plus_dX = []
264                     funcrepr = {
265                         "__userFunction__path" : self.__userFunction__path,
266                         "__userFunction__modl" : self.__userFunction__modl,
267                         "__userFunction__name" : self.__userFunction__name,
268                     }
269                     _jobs = []
270                     _jobs.append( (_X.A1, funcrepr) )
271                     for i in range( len(_dX) ):
272                         _X_plus_dXi    = numpy.array( _X.A1, dtype=float )
273                         _X_plus_dXi[i] = _X[i] + _dX[i]
274                         #
275                         _jobs.append( (_X_plus_dXi, funcrepr) )
276                     #
277                     import multiprocessing
278                     self.__pool = multiprocessing.Pool(self.__mpWorkers)
279                     _HX_plus_dX = self.__pool.map( ExecuteFunction, _jobs )
280                     self.__pool.close()
281                     self.__pool.join()
282                     #
283                     _HX = _HX_plus_dX.pop(0)
284                     #
285                     _Jacobienne = []
286                     for i in range( len(_dX) ):
287                         _Jacobienne.append( numpy.ravel(( _HX_plus_dX[i] - _HX ) / _dX[i]) )
288                 else:
289                     _Jacobienne  = []
290                     _HX = self.DirectOperator( _X )
291                     for i in range( _dX.size ):
292                         _dXi            = _dX[i]
293                         _X_plus_dXi     = numpy.array( _X.A1, dtype=float )
294                         _X_plus_dXi[i]  = _X[i] + _dXi
295                         #
296                         _HX_plus_dXi = self.DirectOperator( _X_plus_dXi )
297                         #
298                         _Jacobienne.append( numpy.ravel(( _HX_plus_dXi - _HX ) / _dXi) )
299                 #
300             #
301             _Jacobienne = numpy.matrix( numpy.vstack( _Jacobienne ) ).T
302             if self.__avoidRC:
303                 if self.__lenghtRJ < 0: self.__lenghtRJ = 2 * _X.size
304                 while len(self.__listJPCP) > self.__lenghtRJ:
305                     self.__listJPCP.pop(0)
306                     self.__listJPCI.pop(0)
307                     self.__listJPCR.pop(0)
308                     self.__listJPPN.pop(0)
309                     self.__listJPIN.pop(0)
310                 self.__listJPCP.append( copy.copy(_X) )
311                 self.__listJPCI.append( copy.copy(_dX) )
312                 self.__listJPCR.append( copy.copy(_Jacobienne) )
313                 self.__listJPPN.append( numpy.linalg.norm(_X) )
314                 self.__listJPIN.append( numpy.linalg.norm(_Jacobienne) )
315         #
316         logging.debug("FDA Fin du calcul de la Jacobienne")
317         #
318         return _Jacobienne
319
320     # ---------------------------------------------------------
321     def TangentOperator(self, (X, dX) ):
322         """
323         Calcul du tangent à l'aide de la Jacobienne.
324         """
325         _Jacobienne = self.TangentMatrix( X )
326         if dX is None or len(dX) == 0:
327             #
328             # Calcul de la forme matricielle si le second argument est None
329             # -------------------------------------------------------------
330             return _Jacobienne
331         else:
332             #
333             # Calcul de la valeur linéarisée de H en X appliqué à dX
334             # ------------------------------------------------------
335             _dX = numpy.asmatrix(numpy.ravel( dX )).T
336             _HtX = numpy.dot(_Jacobienne, _dX)
337             return _HtX.A1
338
339     # ---------------------------------------------------------
340     def AdjointOperator(self, (X, Y) ):
341         """
342         Calcul de l'adjoint à l'aide de la Jacobienne.
343         """
344         _JacobienneT = self.TangentMatrix( X ).T
345         if Y is None or len(Y) == 0:
346             #
347             # Calcul de la forme matricielle si le second argument est None
348             # -------------------------------------------------------------
349             return _JacobienneT
350         else:
351             #
352             # Calcul de la valeur de l'adjoint en X appliqué à Y
353             # --------------------------------------------------
354             _Y = numpy.asmatrix(numpy.ravel( Y )).T
355             _HaY = numpy.dot(_JacobienneT, _Y)
356             return _HaY.A1
357
358 # ==============================================================================
359 if __name__ == "__main__":
360     print '\n AUTODIAGNOSTIC \n'