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