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 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))
79 if isinstance(Function,types.FunctionType):
80 logging.debug("FDA Calculs en multiprocessing : FunctionType")
81 self.__userFunction__name = Function.__name__
83 mod = os.path.join(Function.__globals__['filepath'],Function.__globals__['filename'])
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)
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__
97 mod = os.path.join(Function.__globals__['filepath'],Function.__globals__['filename'])
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)
105 self.__userOperator = Operator( fromMethod = Function )
106 self.__userFunction = self.__userOperator.appliedTo # Pour le calcul Direct
108 raise TypeError("User defined function or method has to be provided for finite differences approximation.")
110 self.__userOperator = Operator( fromMethod = Function )
111 self.__userFunction = self.__userOperator.appliedTo
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
124 self.__avoidRC = False
125 if float(increment) <> 0.:
126 self.__increment = float(increment)
128 self.__increment = 0.01
132 self.__dX = numpy.asmatrix(numpy.ravel( dX )).T
133 logging.debug("FDA Reduction des doublons de calcul : %s"%self.__avoidRC)
135 logging.debug("FDA Tolerance de determination des doublons : %.2e"%self.__tolerBP)
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))
147 # ---------------------------------------------------------
148 def DirectOperator(self, X ):
150 Calcul du direct à l'aide de la fonction fournie.
152 logging.debug("FDA Calcul DirectOperator (explicite)")
153 _X = numpy.asmatrix(numpy.ravel( X )).T
154 _HX = numpy.ravel(self.__userFunction( _X ))
158 # ---------------------------------------------------------
159 def TangentMatrix(self, X ):
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.
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 =
170 2/ On effectue les différences (HX_plus_dXi-HX_moins_dXi) et on divise par
172 3/ Chaque résultat, par composante, devient une colonne de la Jacobienne
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
181 4/ Chaque résultat, par composante, devient une colonne de la Jacobienne
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))
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),))
191 _X = numpy.asmatrix(numpy.ravel( X )).T
193 if self.__dX is None:
194 _dX = self.__increment * _X
196 _dX = numpy.asmatrix(numpy.ravel( self.__dX )).T
198 if (_dX == 0.).any():
201 _dX = numpy.where( _dX == 0., float(self.__increment), _dX )
203 _dX = numpy.where( _dX == 0., moyenne, _dX )
205 __alreadyCalculated = False
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)
213 if __alreadyCalculated:
214 logging.debug("FDA Calcul Jacobienne (par récupération du doublon %i)"%__i)
215 _Jacobienne = self.__listJPCR[__i]
217 logging.debug("FDA Calcul Jacobienne (explicite)")
218 if self.__centeredDF:
222 "__userFunction__path" : self.__userFunction__path,
223 "__userFunction__modl" : self.__userFunction__modl,
224 "__userFunction__name" : self.__userFunction__name,
227 for i in range( len(_dX) ):
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
234 _jobs.append( (_X_plus_dXi, funcrepr) )
235 _jobs.append( (_X_moins_dXi, funcrepr) )
237 import multiprocessing
238 self.__pool = multiprocessing.Pool(self.__mpWorkers)
239 _HX_plusmoins_dX = self.__pool.map( ExecuteFunction, _jobs )
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]) )
248 for i in range( _dX.size ):
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
255 _HX_plus_dXi = self.DirectOperator( _X_plus_dXi )
256 _HX_moins_dXi = self.DirectOperator( _X_moins_dXi )
258 _Jacobienne.append( numpy.ravel( _HX_plus_dXi - _HX_moins_dXi ) / (2.*_dXi) )
265 "__userFunction__path" : self.__userFunction__path,
266 "__userFunction__modl" : self.__userFunction__modl,
267 "__userFunction__name" : self.__userFunction__name,
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]
275 _jobs.append( (_X_plus_dXi, funcrepr) )
277 import multiprocessing
278 self.__pool = multiprocessing.Pool(self.__mpWorkers)
279 _HX_plus_dX = self.__pool.map( ExecuteFunction, _jobs )
283 _HX = _HX_plus_dX.pop(0)
286 for i in range( len(_dX) ):
287 _Jacobienne.append( numpy.ravel(( _HX_plus_dX[i] - _HX ) / _dX[i]) )
290 _HX = self.DirectOperator( _X )
291 for i in range( _dX.size ):
293 _X_plus_dXi = numpy.array( _X.A1, dtype=float )
294 _X_plus_dXi[i] = _X[i] + _dXi
296 _HX_plus_dXi = self.DirectOperator( _X_plus_dXi )
298 _Jacobienne.append( numpy.ravel(( _HX_plus_dXi - _HX ) / _dXi) )
301 _Jacobienne = numpy.matrix( numpy.vstack( _Jacobienne ) ).T
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) )
316 logging.debug("FDA Fin du calcul de la Jacobienne")
320 # ---------------------------------------------------------
321 def TangentOperator(self, (X, dX) ):
323 Calcul du tangent à l'aide de la Jacobienne.
325 _Jacobienne = self.TangentMatrix( X )
326 if dX is None or len(dX) == 0:
328 # Calcul de la forme matricielle si le second argument est None
329 # -------------------------------------------------------------
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)
339 # ---------------------------------------------------------
340 def AdjointOperator(self, (X, Y) ):
342 Calcul de l'adjoint à l'aide de la Jacobienne.
344 _JacobienneT = self.TangentMatrix( X ).T
345 if Y is None or len(Y) == 0:
347 # Calcul de la forme matricielle si le second argument est None
348 # -------------------------------------------------------------
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)
358 # ==============================================================================
359 if __name__ == "__main__":
360 print '\n AUTODIAGNOSTIC \n'