1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2015 EDF R&D
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.
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.
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
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
24 Définit les versions approximées des opérateurs tangents et adjoints.
26 __author__ = "Jean-Philippe ARGAUD"
28 import os, numpy, time, copy, types, sys
30 from daCore.BasicObjects import Operator
31 # logging.getLogger().setLevel(logging.DEBUG)
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 )
43 # ==============================================================================
44 class FDApproximation(object):
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.
59 avoidingRedundancy = True,
60 toleranceInRedundancy = 1.e-18,
61 lenghtOfRedundancy = -1,
67 import multiprocessing
68 self.__mpEnabled = True
70 self.__mpEnabled = False
72 self.__mpEnabled = False
73 self.__mpWorkers = mpWorkers
74 logging.debug("FDA Calculs en multiprocessing : %s (nombre de processus : %s)"%(self.__mpEnabled,self.__mpWorkers))
77 if isinstance(Function,types.FunctionType):
78 logging.debug("FDA Calculs en multiprocessing : FunctionType")
79 self.__userFunction__name = Function.__name__
81 mod = os.path.join(Function.__globals__['filepath'],Function.__globals__['filename'])
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)
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__
95 mod = os.path.join(Function.__globals__['filepath'],Function.__globals__['filename'])
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)
103 self.__userOperator = Operator( fromMethod = Function )
104 self.__userFunction = self.__userOperator.appliedTo # Pour le calcul Direct
106 raise TypeError("User defined function or method has to be provided for finite differences approximation.")
108 self.__userOperator = Operator( fromMethod = Function )
109 self.__userFunction = self.__userOperator.appliedTo
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
122 self.__avoidRC = False
123 if float(increment) <> 0.:
124 self.__increment = float(increment)
126 self.__increment = 0.01
130 self.__dX = numpy.asmatrix(numpy.ravel( dX )).T
131 logging.debug("FDA Reduction des doublons de calcul : %s"%self.__avoidRC)
133 logging.debug("FDA Tolerance de determination des doublons : %.2e"%self.__tolerBP)
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))
145 # ---------------------------------------------------------
146 def DirectOperator(self, X ):
148 Calcul du direct à l'aide de la fonction fournie.
150 logging.debug("FDA Calcul DirectOperator (explicite)")
151 _X = numpy.asmatrix(numpy.ravel( X )).T
152 _HX = numpy.ravel(self.__userFunction( _X ))
156 # ---------------------------------------------------------
157 def TangentMatrix(self, X ):
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.
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 =
168 2/ On effectue les différences (HX_plus_dXi-HX_moins_dXi) et on divise par
170 3/ Chaque résultat, par composante, devient une colonne de la Jacobienne
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
179 4/ Chaque résultat, par composante, devient une colonne de la Jacobienne
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))
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),))
189 _X = numpy.asmatrix(numpy.ravel( X )).T
191 if self.__dX is None:
192 _dX = self.__increment * _X
194 _dX = numpy.asmatrix(numpy.ravel( self.__dX )).T
196 if (_dX == 0.).any():
199 _dX = numpy.where( _dX == 0., float(self.__increment), _dX )
201 _dX = numpy.where( _dX == 0., moyenne, _dX )
203 __alreadyCalculated = False
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)
211 if __alreadyCalculated:
212 logging.debug("FDA Calcul Jacobienne (par récupération du doublon %i)"%__i)
213 _Jacobienne = self.__listJPCR[__i]
215 logging.debug("FDA Calcul Jacobienne (explicite)")
216 if self.__centeredDF:
220 "__userFunction__path" : self.__userFunction__path,
221 "__userFunction__modl" : self.__userFunction__modl,
222 "__userFunction__name" : self.__userFunction__name,
225 for i in range( len(_dX) ):
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
232 _jobs.append( (_X_plus_dXi, funcrepr) )
233 _jobs.append( (_X_moins_dXi, funcrepr) )
235 import multiprocessing
236 self.__pool = multiprocessing.Pool(self.__mpWorkers)
237 _HX_plusmoins_dX = self.__pool.map( ExecuteFunction, _jobs )
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]) )
246 for i in range( _dX.size ):
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
253 _HX_plus_dXi = self.DirectOperator( _X_plus_dXi )
254 _HX_moins_dXi = self.DirectOperator( _X_moins_dXi )
256 _Jacobienne.append( numpy.ravel( _HX_plus_dXi - _HX_moins_dXi ) / (2.*_dXi) )
263 "__userFunction__path" : self.__userFunction__path,
264 "__userFunction__modl" : self.__userFunction__modl,
265 "__userFunction__name" : self.__userFunction__name,
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]
273 _jobs.append( (_X_plus_dXi, funcrepr) )
275 import multiprocessing
276 self.__pool = multiprocessing.Pool(self.__mpWorkers)
277 _HX_plus_dX = self.__pool.map( ExecuteFunction, _jobs )
281 _HX = _HX_plus_dX.pop(0)
284 for i in range( len(_dX) ):
285 _Jacobienne.append( numpy.ravel(( _HX_plus_dX[i] - _HX ) / _dX[i]) )
288 _HX = self.DirectOperator( _X )
289 for i in range( _dX.size ):
291 _X_plus_dXi = numpy.array( _X.A1, dtype=float )
292 _X_plus_dXi[i] = _X[i] + _dXi
294 _HX_plus_dXi = self.DirectOperator( _X_plus_dXi )
296 _Jacobienne.append( numpy.ravel(( _HX_plus_dXi - _HX ) / _dXi) )
299 _Jacobienne = numpy.matrix( numpy.vstack( _Jacobienne ) ).T
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) )
314 logging.debug("FDA Fin du calcul de la Jacobienne")
318 # ---------------------------------------------------------
319 def TangentOperator(self, (X, dX) ):
321 Calcul du tangent à l'aide de la Jacobienne.
323 _Jacobienne = self.TangentMatrix( X )
324 if dX is None or len(dX) == 0:
326 # Calcul de la forme matricielle si le second argument est None
327 # -------------------------------------------------------------
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)
337 # ---------------------------------------------------------
338 def AdjointOperator(self, (X, Y) ):
340 Calcul de l'adjoint à l'aide de la Jacobienne.
342 _JacobienneT = self.TangentMatrix( X ).T
343 if Y is None or len(Y) == 0:
345 # Calcul de la forme matricielle si le second argument est None
346 # -------------------------------------------------------------
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)
356 # ==============================================================================
357 if __name__ == "__main__":
358 print '\n AUTODIAGNOSTIC \n'