Salome HOME
Code improvements, review and simplifications (2)
[modules/adao.git] / src / daComposant / daCore / NumericObjects.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2022 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 objets numériques génériques.
25 """
26 __author__ = "Jean-Philippe ARGAUD"
27
28 import os, copy, types, sys, logging, numpy
29 from daCore.BasicObjects import Operator, Covariance, PartialAlgorithm
30 from daCore.PlatformInfo import PlatformInfo
31 mpr = PlatformInfo().MachinePrecision()
32 mfp = PlatformInfo().MaximumPrecision()
33 # logging.getLogger().setLevel(logging.DEBUG)
34
35 # ==============================================================================
36 def ExecuteFunction( triplet ):
37     assert len(triplet) == 3, "Incorrect number of arguments"
38     X, xArgs, funcrepr = triplet
39     __X = numpy.ravel( X ).reshape((-1,1))
40     __sys_path_tmp = sys.path ; sys.path.insert(0,funcrepr["__userFunction__path"])
41     __module = __import__(funcrepr["__userFunction__modl"], globals(), locals(), [])
42     __fonction = getattr(__module,funcrepr["__userFunction__name"])
43     sys.path = __sys_path_tmp ; del __sys_path_tmp
44     if isinstance(xArgs, dict):
45         __HX  = __fonction( __X, **xArgs )
46     else:
47         __HX  = __fonction( __X )
48     return numpy.ravel( __HX )
49
50 # ==============================================================================
51 class FDApproximation(object):
52     """
53     Cette classe sert d'interface pour définir les opérateurs approximés. A la
54     création d'un objet, en fournissant une fonction "Function", on obtient un
55     objet qui dispose de 3 méthodes "DirectOperator", "TangentOperator" et
56     "AdjointOperator". On contrôle l'approximation DF avec l'incrément
57     multiplicatif "increment" valant par défaut 1%, ou avec l'incrément fixe
58     "dX" qui sera multiplié par "increment" (donc en %), et on effectue de DF
59     centrées si le booléen "centeredDF" est vrai.
60     """
61     def __init__(self,
62             name                  = "FDApproximation",
63             Function              = None,
64             centeredDF            = False,
65             increment             = 0.01,
66             dX                    = None,
67             extraArguments        = None,
68             reducingMemoryUse     = False,
69             avoidingRedundancy    = True,
70             toleranceInRedundancy = 1.e-18,
71             lenghtOfRedundancy    = -1,
72             mpEnabled             = False,
73             mpWorkers             = None,
74             mfEnabled             = False,
75             ):
76         self.__name = str(name)
77         self.__extraArgs = extraArguments
78         #
79         if mpEnabled:
80             try:
81                 import multiprocessing
82                 self.__mpEnabled = True
83             except ImportError:
84                 self.__mpEnabled = False
85         else:
86             self.__mpEnabled = False
87         self.__mpWorkers = mpWorkers
88         if self.__mpWorkers is not None and self.__mpWorkers < 1:
89             self.__mpWorkers = None
90         logging.debug("FDA Calculs en multiprocessing : %s (nombre de processus : %s)"%(self.__mpEnabled,self.__mpWorkers))
91         #
92         self.__mfEnabled = bool(mfEnabled)
93         logging.debug("FDA Calculs en multifonctions : %s"%(self.__mfEnabled,))
94         #
95         self.__rmEnabled = bool(reducingMemoryUse)
96         logging.debug("FDA Calculs avec réduction mémoire : %s"%(self.__rmEnabled,))
97         #
98         if avoidingRedundancy:
99             self.__avoidRC = True
100             self.__tolerBP = float(toleranceInRedundancy)
101             self.__lenghtRJ = int(lenghtOfRedundancy)
102             self.__listJPCP = [] # Jacobian Previous Calculated Points
103             self.__listJPCI = [] # Jacobian Previous Calculated Increment
104             self.__listJPCR = [] # Jacobian Previous Calculated Results
105             self.__listJPPN = [] # Jacobian Previous Calculated Point Norms
106             self.__listJPIN = [] # Jacobian Previous Calculated Increment Norms
107         else:
108             self.__avoidRC = False
109         logging.debug("FDA Calculs avec réduction des doublons : %s"%self.__avoidRC)
110         if self.__avoidRC:
111             logging.debug("FDA Tolérance de détermination des doublons : %.2e"%self.__tolerBP)
112         #
113         if self.__mpEnabled:
114             if isinstance(Function,types.FunctionType):
115                 logging.debug("FDA Calculs en multiprocessing : FunctionType")
116                 self.__userFunction__name = Function.__name__
117                 try:
118                     mod = os.path.join(Function.__globals__['filepath'],Function.__globals__['filename'])
119                 except:
120                     mod = os.path.abspath(Function.__globals__['__file__'])
121                 if not os.path.isfile(mod):
122                     raise ImportError("No user defined function or method found with the name %s"%(mod,))
123                 self.__userFunction__modl = os.path.basename(mod).replace('.pyc','').replace('.pyo','').replace('.py','')
124                 self.__userFunction__path = os.path.dirname(mod)
125                 del mod
126                 self.__userOperator = Operator( name = self.__name, fromMethod = Function, avoidingRedundancy = self.__avoidRC, inputAsMultiFunction = self.__mfEnabled, extraArguments = self.__extraArgs )
127                 self.__userFunction = self.__userOperator.appliedTo # Pour le calcul Direct
128             elif isinstance(Function,types.MethodType):
129                 logging.debug("FDA Calculs en multiprocessing : MethodType")
130                 self.__userFunction__name = Function.__name__
131                 try:
132                     mod = os.path.join(Function.__globals__['filepath'],Function.__globals__['filename'])
133                 except:
134                     mod = os.path.abspath(Function.__func__.__globals__['__file__'])
135                 if not os.path.isfile(mod):
136                     raise ImportError("No user defined function or method found with the name %s"%(mod,))
137                 self.__userFunction__modl = os.path.basename(mod).replace('.pyc','').replace('.pyo','').replace('.py','')
138                 self.__userFunction__path = os.path.dirname(mod)
139                 del mod
140                 self.__userOperator = Operator( name = self.__name, fromMethod = Function, avoidingRedundancy = self.__avoidRC, inputAsMultiFunction = self.__mfEnabled, extraArguments = self.__extraArgs )
141                 self.__userFunction = self.__userOperator.appliedTo # Pour le calcul Direct
142             else:
143                 raise TypeError("User defined function or method has to be provided for finite differences approximation.")
144         else:
145             self.__userOperator = Operator( name = self.__name, fromMethod = Function, avoidingRedundancy = self.__avoidRC, inputAsMultiFunction = self.__mfEnabled, extraArguments = self.__extraArgs )
146             self.__userFunction = self.__userOperator.appliedTo
147         #
148         self.__centeredDF = bool(centeredDF)
149         if abs(float(increment)) > 1.e-15:
150             self.__increment  = float(increment)
151         else:
152             self.__increment  = 0.01
153         if dX is None:
154             self.__dX     = None
155         else:
156             self.__dX     = numpy.ravel( dX )
157
158     # ---------------------------------------------------------
159     def __doublon__(self, e, l, n, v=None):
160         __ac, __iac = False, -1
161         for i in range(len(l)-1,-1,-1):
162             if numpy.linalg.norm(e - l[i]) < self.__tolerBP * n[i]:
163                 __ac, __iac = True, i
164                 if v is not None: logging.debug("FDA Cas%s déja calculé, récupération du doublon %i"%(v,__iac))
165                 break
166         return __ac, __iac
167
168     # ---------------------------------------------------------
169     def __listdotwith__(self, __LMatrix, __dotWith = None, __dotTWith = None):
170         "Produit incrémental d'une matrice liste de colonnes avec un vecteur"
171         if not isinstance(__LMatrix, (list,tuple)):
172             raise TypeError("Columnwise list matrix has not the proper type: %s"%type(__LMatrix))
173         if __dotWith is not None:
174             __Idwx = numpy.ravel( __dotWith )
175             assert len(__LMatrix) == __Idwx.size, "Incorrect size of elements"
176             __Produit = numpy.zeros(__LMatrix[0].size)
177             for i, col in enumerate(__LMatrix):
178                 __Produit += float(__Idwx[i]) * col
179             return __Produit
180         elif __dotTWith is not None:
181             _Idwy = numpy.ravel( __dotTWith ).T
182             assert __LMatrix[0].size == _Idwy.size, "Incorrect size of elements"
183             __Produit = numpy.zeros(len(__LMatrix))
184             for i, col in enumerate(__LMatrix):
185                 __Produit[i] = float( _Idwy @ col)
186             return __Produit
187         else:
188             __Produit = None
189         return __Produit
190
191     # ---------------------------------------------------------
192     def DirectOperator(self, X, **extraArgs ):
193         """
194         Calcul du direct à l'aide de la fonction fournie.
195
196         NB : les extraArgs sont là pour assurer la compatibilité d'appel, mais
197         ne doivent pas être données ici à la fonction utilisateur.
198         """
199         logging.debug("FDA Calcul DirectOperator (explicite)")
200         if self.__mfEnabled:
201             _HX = self.__userFunction( X, argsAsSerie = True )
202         else:
203             _HX = numpy.ravel(self.__userFunction( numpy.ravel(X) ))
204         #
205         return _HX
206
207     # ---------------------------------------------------------
208     def TangentMatrix(self, X, dotWith = None, dotTWith = None ):
209         """
210         Calcul de l'opérateur tangent comme la Jacobienne par différences finies,
211         c'est-à-dire le gradient de H en X. On utilise des différences finies
212         directionnelles autour du point X. X est un numpy.ndarray.
213
214         Différences finies centrées (approximation d'ordre 2):
215         1/ Pour chaque composante i de X, on ajoute et on enlève la perturbation
216            dX[i] à la  composante X[i], pour composer X_plus_dXi et X_moins_dXi, et
217            on calcule les réponses HX_plus_dXi = H( X_plus_dXi ) et HX_moins_dXi =
218            H( X_moins_dXi )
219         2/ On effectue les différences (HX_plus_dXi-HX_moins_dXi) et on divise par
220            le pas 2*dXi
221         3/ Chaque résultat, par composante, devient une colonne de la Jacobienne
222
223         Différences finies non centrées (approximation d'ordre 1):
224         1/ Pour chaque composante i de X, on ajoute la perturbation dX[i] à la
225            composante X[i] pour composer X_plus_dXi, et on calcule la réponse
226            HX_plus_dXi = H( X_plus_dXi )
227         2/ On calcule la valeur centrale HX = H(X)
228         3/ On effectue les différences (HX_plus_dXi-HX) et on divise par
229            le pas dXi
230         4/ Chaque résultat, par composante, devient une colonne de la Jacobienne
231
232         """
233         logging.debug("FDA Début du calcul de la Jacobienne")
234         logging.debug("FDA   Incrément de............: %s*X"%float(self.__increment))
235         logging.debug("FDA   Approximation centrée...: %s"%(self.__centeredDF))
236         #
237         if X is None or len(X)==0:
238             raise ValueError("Nominal point X for approximate derivatives can not be None or void (given X: %s)."%(str(X),))
239         #
240         _X = numpy.ravel( X )
241         #
242         if self.__dX is None:
243             _dX  = self.__increment * _X
244         else:
245             _dX = numpy.ravel( self.__dX )
246         assert len(_X) == len(_dX), "Inconsistent dX increment length with respect to the X one"
247         assert _X.size == _dX.size, "Inconsistent dX increment size with respect to the X one"
248         #
249         if (_dX == 0.).any():
250             moyenne = _dX.mean()
251             if moyenne == 0.:
252                 _dX = numpy.where( _dX == 0., float(self.__increment), _dX )
253             else:
254                 _dX = numpy.where( _dX == 0., moyenne, _dX )
255         #
256         __alreadyCalculated  = False
257         if self.__avoidRC:
258             __bidon, __alreadyCalculatedP = self.__doublon__(_X,  self.__listJPCP, self.__listJPPN, None)
259             __bidon, __alreadyCalculatedI = self.__doublon__(_dX, self.__listJPCI, self.__listJPIN, None)
260             if __alreadyCalculatedP == __alreadyCalculatedI > -1:
261                 __alreadyCalculated, __i = True, __alreadyCalculatedP
262                 logging.debug("FDA Cas J déjà calculé, récupération du doublon %i"%__i)
263         #
264         if __alreadyCalculated:
265             logging.debug("FDA   Calcul Jacobienne (par récupération du doublon %i)"%__i)
266             _Jacobienne = self.__listJPCR[__i]
267             logging.debug("FDA Fin du calcul de la Jacobienne")
268             if dotWith is not None:
269                 return numpy.dot(_Jacobienne,   numpy.ravel( dotWith ))
270             elif dotTWith is not None:
271                 return numpy.dot(_Jacobienne.T, numpy.ravel( dotTWith ))
272         else:
273             logging.debug("FDA   Calcul Jacobienne (explicite)")
274             if self.__centeredDF:
275                 #
276                 if self.__mpEnabled and not self.__mfEnabled:
277                     funcrepr = {
278                         "__userFunction__path" : self.__userFunction__path,
279                         "__userFunction__modl" : self.__userFunction__modl,
280                         "__userFunction__name" : self.__userFunction__name,
281                     }
282                     _jobs = []
283                     for i in range( len(_dX) ):
284                         _dXi            = _dX[i]
285                         _X_plus_dXi     = numpy.array( _X, dtype=float )
286                         _X_plus_dXi[i]  = _X[i] + _dXi
287                         _X_moins_dXi    = numpy.array( _X, dtype=float )
288                         _X_moins_dXi[i] = _X[i] - _dXi
289                         #
290                         _jobs.append( (_X_plus_dXi,  self.__extraArgs, funcrepr) )
291                         _jobs.append( (_X_moins_dXi, self.__extraArgs, funcrepr) )
292                     #
293                     import multiprocessing
294                     self.__pool = multiprocessing.Pool(self.__mpWorkers)
295                     _HX_plusmoins_dX = self.__pool.map( ExecuteFunction, _jobs )
296                     self.__pool.close()
297                     self.__pool.join()
298                     #
299                     _Jacobienne  = []
300                     for i in range( len(_dX) ):
301                         _Jacobienne.append( numpy.ravel( _HX_plusmoins_dX[2*i] - _HX_plusmoins_dX[2*i+1] ) / (2.*_dX[i]) )
302                     #
303                 elif self.__mfEnabled:
304                     _xserie = []
305                     for i in range( len(_dX) ):
306                         _dXi            = _dX[i]
307                         _X_plus_dXi     = numpy.array( _X, dtype=float )
308                         _X_plus_dXi[i]  = _X[i] + _dXi
309                         _X_moins_dXi    = numpy.array( _X, dtype=float )
310                         _X_moins_dXi[i] = _X[i] - _dXi
311                         #
312                         _xserie.append( _X_plus_dXi )
313                         _xserie.append( _X_moins_dXi )
314                     #
315                     _HX_plusmoins_dX = self.DirectOperator( _xserie )
316                      #
317                     _Jacobienne  = []
318                     for i in range( len(_dX) ):
319                         _Jacobienne.append( numpy.ravel( _HX_plusmoins_dX[2*i] - _HX_plusmoins_dX[2*i+1] ) / (2.*_dX[i]) )
320                     #
321                 else:
322                     _Jacobienne  = []
323                     for i in range( _dX.size ):
324                         _dXi            = _dX[i]
325                         _X_plus_dXi     = numpy.array( _X, dtype=float )
326                         _X_plus_dXi[i]  = _X[i] + _dXi
327                         _X_moins_dXi    = numpy.array( _X, dtype=float )
328                         _X_moins_dXi[i] = _X[i] - _dXi
329                         #
330                         _HX_plus_dXi    = self.DirectOperator( _X_plus_dXi )
331                         _HX_moins_dXi   = self.DirectOperator( _X_moins_dXi )
332                         #
333                         _Jacobienne.append( numpy.ravel( _HX_plus_dXi - _HX_moins_dXi ) / (2.*_dXi) )
334                 #
335             else:
336                 #
337                 if self.__mpEnabled and not self.__mfEnabled:
338                     funcrepr = {
339                         "__userFunction__path" : self.__userFunction__path,
340                         "__userFunction__modl" : self.__userFunction__modl,
341                         "__userFunction__name" : self.__userFunction__name,
342                     }
343                     _jobs = []
344                     _jobs.append( (_X, self.__extraArgs, funcrepr) )
345                     for i in range( len(_dX) ):
346                         _X_plus_dXi    = numpy.array( _X, dtype=float )
347                         _X_plus_dXi[i] = _X[i] + _dX[i]
348                         #
349                         _jobs.append( (_X_plus_dXi, self.__extraArgs, funcrepr) )
350                     #
351                     import multiprocessing
352                     self.__pool = multiprocessing.Pool(self.__mpWorkers)
353                     _HX_plus_dX = self.__pool.map( ExecuteFunction, _jobs )
354                     self.__pool.close()
355                     self.__pool.join()
356                     #
357                     _HX = _HX_plus_dX.pop(0)
358                     #
359                     _Jacobienne = []
360                     for i in range( len(_dX) ):
361                         _Jacobienne.append( numpy.ravel(( _HX_plus_dX[i] - _HX ) / _dX[i]) )
362                     #
363                 elif self.__mfEnabled:
364                     _xserie = []
365                     _xserie.append( _X )
366                     for i in range( len(_dX) ):
367                         _X_plus_dXi    = numpy.array( _X, dtype=float )
368                         _X_plus_dXi[i] = _X[i] + _dX[i]
369                         #
370                         _xserie.append( _X_plus_dXi )
371                     #
372                     _HX_plus_dX = self.DirectOperator( _xserie )
373                     #
374                     _HX = _HX_plus_dX.pop(0)
375                     #
376                     _Jacobienne = []
377                     for i in range( len(_dX) ):
378                         _Jacobienne.append( numpy.ravel(( _HX_plus_dX[i] - _HX ) / _dX[i]) )
379                    #
380                 else:
381                     _Jacobienne  = []
382                     _HX = self.DirectOperator( _X )
383                     for i in range( _dX.size ):
384                         _dXi            = _dX[i]
385                         _X_plus_dXi     = numpy.array( _X, dtype=float )
386                         _X_plus_dXi[i]  = _X[i] + _dXi
387                         #
388                         _HX_plus_dXi = self.DirectOperator( _X_plus_dXi )
389                         #
390                         _Jacobienne.append( numpy.ravel(( _HX_plus_dXi - _HX ) / _dXi) )
391             #
392             if (dotWith is not None) or (dotTWith is not None):
393                 __Produit = self.__listdotwith__(_Jacobienne, dotWith, dotTWith)
394             else:
395                 __Produit = None
396             if __Produit is None or self.__avoidRC:
397                 _Jacobienne = numpy.transpose( numpy.vstack( _Jacobienne ) )
398                 if self.__avoidRC:
399                     if self.__lenghtRJ < 0: self.__lenghtRJ = 2 * _X.size
400                     while len(self.__listJPCP) > self.__lenghtRJ:
401                         self.__listJPCP.pop(0)
402                         self.__listJPCI.pop(0)
403                         self.__listJPCR.pop(0)
404                         self.__listJPPN.pop(0)
405                         self.__listJPIN.pop(0)
406                     self.__listJPCP.append( copy.copy(_X) )
407                     self.__listJPCI.append( copy.copy(_dX) )
408                     self.__listJPCR.append( copy.copy(_Jacobienne) )
409                     self.__listJPPN.append( numpy.linalg.norm(_X) )
410                     self.__listJPIN.append( numpy.linalg.norm(_Jacobienne) )
411             logging.debug("FDA Fin du calcul de la Jacobienne")
412             if __Produit is not None:
413                 return __Produit
414         #
415         return _Jacobienne
416
417     # ---------------------------------------------------------
418     def TangentOperator(self, paire, **extraArgs ):
419         """
420         Calcul du tangent à l'aide de la Jacobienne.
421
422         NB : les extraArgs sont là pour assurer la compatibilité d'appel, mais
423         ne doivent pas être données ici à la fonction utilisateur.
424         """
425         if self.__mfEnabled:
426             assert len(paire) == 1, "Incorrect length of arguments"
427             _paire = paire[0]
428             assert len(_paire) == 2, "Incorrect number of arguments"
429         else:
430             assert len(paire) == 2, "Incorrect number of arguments"
431             _paire = paire
432         X, dX = _paire
433         if dX is None or len(dX) == 0:
434             #
435             # Calcul de la forme matricielle si le second argument est None
436             # -------------------------------------------------------------
437             _Jacobienne = self.TangentMatrix( X )
438             if self.__mfEnabled: return [_Jacobienne,]
439             else:                return _Jacobienne
440         else:
441             #
442             # Calcul de la valeur linéarisée de H en X appliqué à dX
443             # ------------------------------------------------------
444             _HtX = self.TangentMatrix( X, dotWith = dX )
445             if self.__mfEnabled: return [_HtX,]
446             else:                return _HtX
447
448     # ---------------------------------------------------------
449     def AdjointOperator(self, paire, **extraArgs ):
450         """
451         Calcul de l'adjoint à l'aide de la Jacobienne.
452
453         NB : les extraArgs sont là pour assurer la compatibilité d'appel, mais
454         ne doivent pas être données ici à la fonction utilisateur.
455         """
456         if self.__mfEnabled:
457             assert len(paire) == 1, "Incorrect length of arguments"
458             _paire = paire[0]
459             assert len(_paire) == 2, "Incorrect number of arguments"
460         else:
461             assert len(paire) == 2, "Incorrect number of arguments"
462             _paire = paire
463         X, Y = _paire
464         if Y is None or len(Y) == 0:
465             #
466             # Calcul de la forme matricielle si le second argument est None
467             # -------------------------------------------------------------
468             _JacobienneT = self.TangentMatrix( X ).T
469             if self.__mfEnabled: return [_JacobienneT,]
470             else:                return _JacobienneT
471         else:
472             #
473             # Calcul de la valeur de l'adjoint en X appliqué à Y
474             # --------------------------------------------------
475             _HaY = self.TangentMatrix( X, dotTWith = Y )
476             if self.__mfEnabled: return [_HaY,]
477             else:                return _HaY
478
479 # ==============================================================================
480 def EnsembleOfCenteredPerturbations( __bgcenter, __bgcovariance, __nbmembers ):
481     "Génération d'un ensemble de taille __nbmembers-1 d'états aléatoires centrés"
482     #
483     __bgcenter = numpy.ravel(__bgcenter)[:,None]
484     if __nbmembers < 1:
485         raise ValueError("Number of members has to be strictly more than 1 (given number: %s)."%(str(__nbmembers),))
486     #
487     if __bgcovariance is None:
488         _Perturbations = numpy.tile( __bgcenter, __nbmembers)
489     else:
490         _Z = numpy.random.multivariate_normal(numpy.zeros(__bgcenter.size), __bgcovariance, size=__nbmembers).T
491         _Perturbations = numpy.tile( __bgcenter, __nbmembers) + _Z
492     #
493     return _Perturbations
494
495 # ==============================================================================
496 def EnsembleOfBackgroundPerturbations( __bgcenter, __bgcovariance, __nbmembers, __withSVD = True):
497     "Génération d'un ensemble de taille __nbmembers-1 d'états aléatoires centrés"
498     def __CenteredRandomAnomalies(Zr, N):
499         """
500         Génère une matrice de N anomalies aléatoires centrées sur Zr selon les
501         notes manuscrites de MB et conforme au code de PS avec eps = -1
502         """
503         eps = -1
504         Q = numpy.identity(N-1)-numpy.ones((N-1,N-1))/numpy.sqrt(N)/(numpy.sqrt(N)-eps)
505         Q = numpy.concatenate((Q, [eps*numpy.ones(N-1)/numpy.sqrt(N)]), axis=0)
506         R, _ = numpy.linalg.qr(numpy.random.normal(size = (N-1,N-1)))
507         Q = numpy.dot(Q,R)
508         Zr = numpy.dot(Q,Zr)
509         return Zr.T
510     #
511     __bgcenter = numpy.ravel(__bgcenter).reshape((-1,1))
512     if __nbmembers < 1:
513         raise ValueError("Number of members has to be strictly more than 1 (given number: %s)."%(str(__nbmembers),))
514     if __bgcovariance is None:
515         _Perturbations = numpy.tile( __bgcenter, __nbmembers)
516     else:
517         if __withSVD:
518             _U, _s, _V = numpy.linalg.svd(__bgcovariance, full_matrices=False)
519             _nbctl = __bgcenter.size
520             if __nbmembers > _nbctl:
521                 _Z = numpy.concatenate((numpy.dot(
522                     numpy.diag(numpy.sqrt(_s[:_nbctl])), _V[:_nbctl]),
523                     numpy.random.multivariate_normal(numpy.zeros(_nbctl),__bgcovariance,__nbmembers-1-_nbctl)), axis = 0)
524             else:
525                 _Z = numpy.dot(numpy.diag(numpy.sqrt(_s[:__nbmembers-1])), _V[:__nbmembers-1])
526             _Zca = __CenteredRandomAnomalies(_Z, __nbmembers)
527             _Perturbations = __bgcenter + _Zca
528         else:
529             if max(abs(__bgcovariance.flatten())) > 0:
530                 _nbctl = __bgcenter.size
531                 _Z = numpy.random.multivariate_normal(numpy.zeros(_nbctl),__bgcovariance,__nbmembers-1)
532                 _Zca = __CenteredRandomAnomalies(_Z, __nbmembers)
533                 _Perturbations = __bgcenter + _Zca
534             else:
535                 _Perturbations = numpy.tile( __bgcenter, __nbmembers)
536     #
537     return _Perturbations
538
539 # ==============================================================================
540 def EnsembleMean( __Ensemble ):
541     "Renvoie la moyenne empirique d'un ensemble"
542     return numpy.asarray(__Ensemble).mean(axis=1, dtype=mfp).astype('float').reshape((-1,1))
543
544 # ==============================================================================
545 def EnsembleOfAnomalies( __Ensemble, __OptMean = None, __Normalisation = 1.):
546     "Renvoie les anomalies centrées à partir d'un ensemble"
547     if __OptMean is None:
548         __Em = EnsembleMean( __Ensemble )
549     else:
550         __Em = numpy.ravel( __OptMean ).reshape((-1,1))
551     #
552     return __Normalisation * (numpy.asarray( __Ensemble ) - __Em)
553
554 # ==============================================================================
555 def EnsembleErrorCovariance( __Ensemble, __quick = False ):
556     "Renvoie l'estimation empirique de la covariance d'ensemble"
557     if __quick:
558         # Covariance rapide mais rarement définie positive
559         __Covariance = numpy.cov( __Ensemble )
560     else:
561         # Résultat souvent identique à numpy.cov, mais plus robuste
562         __n, __m = numpy.asarray( __Ensemble ).shape
563         __Anomalies = EnsembleOfAnomalies( __Ensemble )
564         # Estimation empirique
565         __Covariance = ( __Anomalies @ __Anomalies.T ) / (__m-1)
566         # Assure la symétrie
567         __Covariance = ( __Covariance + __Covariance.T ) * 0.5
568         # Assure la positivité
569         __epsilon    = mpr*numpy.trace( __Covariance )
570         __Covariance = __Covariance + __epsilon * numpy.identity(__n)
571     #
572     return __Covariance
573
574 # ==============================================================================
575 def EnsemblePerturbationWithGivenCovariance(
576         __Ensemble,
577         __Covariance,
578         __Seed = None,
579         ):
580     "Ajout d'une perturbation à chaque membre d'un ensemble selon une covariance prescrite"
581     if hasattr(__Covariance,"assparsematrix"):
582         if (abs(__Ensemble).mean() > mpr) and (abs(__Covariance.assparsematrix())/abs(__Ensemble).mean() < mpr).all():
583             # Traitement d'une covariance nulle ou presque
584             return __Ensemble
585         if (abs(__Ensemble).mean() <= mpr) and (abs(__Covariance.assparsematrix()) < mpr).all():
586             # Traitement d'une covariance nulle ou presque
587             return __Ensemble
588     else:
589         if (abs(__Ensemble).mean() > mpr) and (abs(__Covariance)/abs(__Ensemble).mean() < mpr).all():
590             # Traitement d'une covariance nulle ou presque
591             return __Ensemble
592         if (abs(__Ensemble).mean() <= mpr) and (abs(__Covariance) < mpr).all():
593             # Traitement d'une covariance nulle ou presque
594             return __Ensemble
595     #
596     __n, __m = __Ensemble.shape
597     if __Seed is not None: numpy.random.seed(__Seed)
598     #
599     if hasattr(__Covariance,"isscalar") and __Covariance.isscalar():
600         # Traitement d'une covariance multiple de l'identité
601         __zero = 0.
602         __std  = numpy.sqrt(__Covariance.assparsematrix())
603         __Ensemble += numpy.random.normal(__zero, __std, size=(__m,__n)).T
604     #
605     elif hasattr(__Covariance,"isvector") and __Covariance.isvector():
606         # Traitement d'une covariance diagonale avec variances non identiques
607         __zero = numpy.zeros(__n)
608         __std  = numpy.sqrt(__Covariance.assparsematrix())
609         __Ensemble += numpy.asarray([numpy.random.normal(__zero, __std) for i in range(__m)]).T
610     #
611     elif hasattr(__Covariance,"ismatrix") and __Covariance.ismatrix():
612         # Traitement d'une covariance pleine
613         __Ensemble += numpy.random.multivariate_normal(numpy.zeros(__n), __Covariance.asfullmatrix(__n), size=__m).T
614     #
615     elif isinstance(__Covariance, numpy.ndarray):
616         # Traitement d'une covariance numpy pleine, sachant qu'on arrive ici en dernier
617         __Ensemble += numpy.random.multivariate_normal(numpy.zeros(__n), __Covariance, size=__m).T
618     #
619     else:
620         raise ValueError("Error in ensemble perturbation with inadequate covariance specification")
621     #
622     return __Ensemble
623
624 # ==============================================================================
625 def CovarianceInflation(
626         __InputCovOrEns,
627         __InflationType   = None,
628         __InflationFactor = None,
629         __BackgroundCov   = None,
630         ):
631     """
632     Inflation applicable soit sur Pb ou Pa, soit sur les ensembles EXb ou EXa
633
634     Synthèse : Hunt 2007, section 2.3.5
635     """
636     if __InflationFactor is None:
637         return __InputCovOrEns
638     else:
639         __InflationFactor = float(__InflationFactor)
640     #
641     if __InflationType in ["MultiplicativeOnAnalysisCovariance", "MultiplicativeOnBackgroundCovariance"]:
642         if __InflationFactor < 1.:
643             raise ValueError("Inflation factor for multiplicative inflation has to be greater or equal than 1.")
644         if __InflationFactor < 1.+mpr:
645             return __InputCovOrEns
646         __OutputCovOrEns = __InflationFactor**2 * __InputCovOrEns
647     #
648     elif __InflationType in ["MultiplicativeOnAnalysisAnomalies", "MultiplicativeOnBackgroundAnomalies"]:
649         if __InflationFactor < 1.:
650             raise ValueError("Inflation factor for multiplicative inflation has to be greater or equal than 1.")
651         if __InflationFactor < 1.+mpr:
652             return __InputCovOrEns
653         __InputCovOrEnsMean = __InputCovOrEns.mean(axis=1, dtype=mfp).astype('float')
654         __OutputCovOrEns = __InputCovOrEnsMean[:,numpy.newaxis] \
655             + __InflationFactor * (__InputCovOrEns - __InputCovOrEnsMean[:,numpy.newaxis])
656     #
657     elif __InflationType in ["AdditiveOnAnalysisCovariance", "AdditiveOnBackgroundCovariance"]:
658         if __InflationFactor < 0.:
659             raise ValueError("Inflation factor for additive inflation has to be greater or equal than 0.")
660         if __InflationFactor < mpr:
661             return __InputCovOrEns
662         __n, __m = numpy.asarray(InputCovOrEns).shape
663         if __n != __m:
664             raise ValueError("Additive inflation can only be applied to squared (covariance) matrix.")
665         __OutputCovOrEns = (1. - __InflationFactor) * __InputCovOrEns + __InflationFactor * numpy.identity(__n)
666     #
667     elif __InflationType == "HybridOnBackgroundCovariance":
668         if __InflationFactor < 0.:
669             raise ValueError("Inflation factor for hybrid inflation has to be greater or equal than 0.")
670         if __InflationFactor < mpr:
671             return __InputCovOrEns
672         __n, __m = numpy.asarray(InputCovOrEns).shape
673         if __n != __m:
674             raise ValueError("Additive inflation can only be applied to squared (covariance) matrix.")
675         if __BackgroundCov is None:
676             raise ValueError("Background covariance matrix B has to be given for hybrid inflation.")
677         if __InputCovOrEns.shape != __BackgroundCov.shape:
678             raise ValueError("Ensemble covariance matrix has to be of same size than background covariance matrix B.")
679         __OutputCovOrEns = (1. - __InflationFactor) * __InputCovOrEns + __InflationFactor * __BackgroundCov
680     #
681     elif __InflationType == "Relaxation":
682         raise NotImplementedError("InflationType Relaxation")
683     #
684     else:
685         raise ValueError("Error in inflation type, '%s' is not a valid keyword."%InflationType)
686     #
687     return __OutputCovOrEns
688
689 # ==============================================================================
690 def HessienneEstimation(__selfA, __nb, __HaM, __HtM, __BI, __RI):
691     "Estimation de la Hessienne"
692     #
693     __HessienneI = []
694     for i in range(int(__nb)):
695         __ee    = numpy.zeros((__nb,1))
696         __ee[i] = 1.
697         __HtEE  = numpy.dot(__HtM,__ee).reshape((-1,1))
698         __HessienneI.append( numpy.ravel( __BI * __ee + __HaM * (__RI * __HtEE) ) )
699     #
700     __A = numpy.linalg.inv(numpy.array( __HessienneI ))
701     __A = (__A + __A.T) * 0.5 # Symétrie
702     __A = __A + mpr*numpy.trace( __A ) * numpy.identity(__nb) # Positivité
703     #
704     if min(__A.shape) != max(__A.shape):
705         raise ValueError("The %s a posteriori covariance matrix A is of shape %s, despites it has to be a squared matrix. There is an error in the observation operator, please check it."%(__selfA._name,str(__A.shape)))
706     if (numpy.diag(__A) < 0).any():
707         raise ValueError("The %s a posteriori covariance matrix A has at least one negative value on its diagonal. There is an error in the observation operator, please check it."%(__selfA._name,))
708     if logging.getLogger().level < logging.WARNING: # La vérification n'a lieu qu'en debug
709         try:
710             numpy.linalg.cholesky( __A )
711         except:
712             raise ValueError("The %s a posteriori covariance matrix A is not symmetric positive-definite. Please check your a priori covariances and your observation operator."%(__selfA._name,))
713     #
714     return __A
715
716 # ==============================================================================
717 def QuantilesEstimations(selfA, A, Xa, HXa = None, Hm = None, HtM = None):
718     "Estimation des quantiles a posteriori à partir de A>0 (selfA est modifié)"
719     nbsamples = selfA._parameters["NumberOfSamplesForQuantiles"]
720     #
721     # Traitement des bornes
722     if "StateBoundsForQuantiles" in selfA._parameters:
723         LBounds = selfA._parameters["StateBoundsForQuantiles"] # Prioritaire
724     elif "Bounds" in selfA._parameters:
725         LBounds = selfA._parameters["Bounds"]  # Défaut raisonnable
726     else:
727         LBounds = None
728     if LBounds is not None:
729         LBounds = ForceNumericBounds( LBounds )
730     __Xa = numpy.ravel(Xa)
731     #
732     # Échantillonnage des états
733     YfQ  = None
734     EXr  = None
735     for i in range(nbsamples):
736         if selfA._parameters["SimulationForQuantiles"] == "Linear" and HtM is not None and HXa is not None:
737             dXr = (numpy.random.multivariate_normal(__Xa,A) - __Xa).reshape((-1,1))
738             if LBounds is not None: # "EstimateProjection" par défaut
739                 dXr = numpy.max(numpy.hstack((dXr,LBounds[:,0].reshape((-1,1))) - __Xa.reshape((-1,1))),axis=1)
740                 dXr = numpy.min(numpy.hstack((dXr,LBounds[:,1].reshape((-1,1))) - __Xa.reshape((-1,1))),axis=1)
741             dYr = HtM @ dXr
742             Yr = HXa.reshape((-1,1)) + dYr
743             if selfA._toStore("SampledStateForQuantiles"): Xr = __Xa + numpy.ravel(dXr)
744         elif selfA._parameters["SimulationForQuantiles"] == "NonLinear" and Hm is not None:
745             Xr = numpy.random.multivariate_normal(__Xa,A)
746             if LBounds is not None: # "EstimateProjection" par défaut
747                 Xr = numpy.max(numpy.hstack((Xr.reshape((-1,1)),LBounds[:,0].reshape((-1,1)))),axis=1)
748                 Xr = numpy.min(numpy.hstack((Xr.reshape((-1,1)),LBounds[:,1].reshape((-1,1)))),axis=1)
749             Yr = numpy.asarray(Hm( Xr ))
750         else:
751             raise ValueError("Quantile simulations has only to be Linear or NonLinear.")
752         #
753         if YfQ is None:
754             YfQ = Yr.reshape((-1,1))
755             if selfA._toStore("SampledStateForQuantiles"): EXr = Xr.reshape((-1,1))
756         else:
757             YfQ = numpy.hstack((YfQ,Yr.reshape((-1,1))))
758             if selfA._toStore("SampledStateForQuantiles"): EXr = numpy.hstack((EXr,Xr.reshape((-1,1))))
759     #
760     # Extraction des quantiles
761     YfQ.sort(axis=-1)
762     YQ = None
763     for quantile in selfA._parameters["Quantiles"]:
764         if not (0. <= float(quantile) <= 1.): continue
765         indice = int(nbsamples * float(quantile) - 1./nbsamples)
766         if YQ is None: YQ = YfQ[:,indice].reshape((-1,1))
767         else:          YQ = numpy.hstack((YQ,YfQ[:,indice].reshape((-1,1))))
768     if YQ is not None: # Liste non vide de quantiles
769         selfA.StoredVariables["SimulationQuantiles"].store( YQ )
770     if selfA._toStore("SampledStateForQuantiles"):
771         selfA.StoredVariables["SampledStateForQuantiles"].store( EXr )
772     #
773     return 0
774
775 # ==============================================================================
776 def ForceNumericBounds( __Bounds ):
777     "Force les bornes à être des valeurs numériques, sauf si globalement None"
778     # Conserve une valeur par défaut à None s'il n'y a pas de bornes
779     if __Bounds is None: return None
780     # Converti toutes les bornes individuelles None à +/- l'infini
781     __Bounds = numpy.asarray( __Bounds, dtype=float )
782     if len(__Bounds.shape) != 2 or min(__Bounds.shape) <= 0 or __Bounds.shape[1] != 2:
783         raise ValueError("Incorrectly shaped bounds data")
784     __Bounds[numpy.isnan(__Bounds[:,0]),0] = -sys.float_info.max
785     __Bounds[numpy.isnan(__Bounds[:,1]),1] =  sys.float_info.max
786     return __Bounds
787
788 # ==============================================================================
789 def RecentredBounds( __Bounds, __Center, __Scale = None):
790     "Recentre les bornes autour de 0, sauf si globalement None"
791     # Conserve une valeur par défaut à None s'il n'y a pas de bornes
792     if __Bounds is None: return None
793     if __Scale is None:
794         # Recentre les valeurs numériques de bornes
795         return ForceNumericBounds( __Bounds ) - numpy.ravel( __Center ).reshape((-1,1))
796     else:
797         # Recentre les valeurs numériques de bornes et change l'échelle par une matrice
798         return __Scale @ (ForceNumericBounds( __Bounds ) - numpy.ravel( __Center ).reshape((-1,1)))
799
800 # ==============================================================================
801 def ApplyBounds( __Vector, __Bounds, __newClip = True):
802     "Applique des bornes numériques à un point"
803     # Conserve une valeur par défaut s'il n'y a pas de bornes
804     if __Bounds is None: return __Vector
805     #
806     if not isinstance(__Vector, numpy.ndarray): # Is an array
807         raise ValueError("Incorrect array definition of vector data")
808     if not isinstance(__Bounds, numpy.ndarray): # Is an array
809         raise ValueError("Incorrect array definition of bounds data")
810     if 2*__Vector.size != __Bounds.size: # Is a 2 column array of vector lenght
811         raise ValueError("Incorrect bounds number (%i) to be applied for this vector (of size %i)"%(__Bounds.size,__Vector.size))
812     if len(__Bounds.shape) != 2 or min(__Bounds.shape) <= 0 or __Bounds.shape[1] != 2:
813         raise ValueError("Incorrectly shaped bounds data")
814     #
815     if __newClip:
816         __Vector = __Vector.clip(
817             __Bounds[:,0].reshape(__Vector.shape),
818             __Bounds[:,1].reshape(__Vector.shape),
819             )
820     else:
821         __Vector = numpy.max(numpy.hstack((__Vector.reshape((-1,1)),numpy.asmatrix(__Bounds)[:,0])),axis=1)
822         __Vector = numpy.min(numpy.hstack((__Vector.reshape((-1,1)),numpy.asmatrix(__Bounds)[:,1])),axis=1)
823         __Vector = numpy.asarray(__Vector)
824     #
825     return __Vector
826
827 # ==============================================================================
828 def Apply3DVarRecentringOnEnsemble(__EnXn, __EnXf, __Ynpu, __HO, __R, __B, __Betaf):
829     "Recentre l'ensemble Xn autour de l'analyse 3DVAR"
830     #
831     Xf = EnsembleMean( __EnXf )
832     Pf = Covariance( asCovariance=EnsembleErrorCovariance(__EnXf) )
833     Pf = (1 - __Betaf) * __B.asfullmatrix(Xf.size) + __Betaf * Pf
834     #
835     selfB = PartialAlgorithm("3DVAR")
836     selfB._parameters["Minimizer"] = "LBFGSB"
837     selfB._parameters["MaximumNumberOfSteps"] = 15000
838     selfB._parameters["CostDecrementTolerance"] = 1.e-7
839     selfB._parameters["ProjectedGradientTolerance"] = -1
840     selfB._parameters["GradientNormTolerance"] = 1.e-05
841     selfB._parameters["StoreInternalVariables"] = False
842     selfB._parameters["optiprint"] = -1
843     selfB._parameters["optdisp"] = 0
844     selfB._parameters["Bounds"] = None
845     selfB._parameters["InitializationPoint"] = Xf
846     from daAlgorithms.Atoms import std3dvar
847     std3dvar.std3dvar(selfB, Xf, __Ynpu, __HO, __R, Pf)
848     Xa = selfB.get("Analysis")[-1].reshape((-1,1))
849     del selfB
850     #
851     return Xa + EnsembleOfAnomalies( __EnXn )
852
853 # ==============================================================================
854 def multiXOsteps(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, oneCycle):
855     """
856     Prévision multi-pas avec une correction par pas en X (multi-méthodes)
857     """
858     #
859     # Initialisation
860     # --------------
861     if selfA._parameters["EstimationOf"] == "State":
862         if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
863             Xn = numpy.asarray(Xb)
864             selfA.StoredVariables["Analysis"].store( Xn )
865             if selfA._toStore("APosterioriCovariance"):
866                 if hasattr(B,"asfullmatrix"):
867                     selfA.StoredVariables["APosterioriCovariance"].store( B.asfullmatrix(Xn.size) )
868                 else:
869                     selfA.StoredVariables["APosterioriCovariance"].store( B )
870             if selfA._toStore("ForecastState"):
871                 selfA.StoredVariables["ForecastState"].store( Xn )
872             selfA._setInternalState("seed", numpy.random.get_state())
873         elif selfA._parameters["nextStep"]:
874             Xn = selfA._getInternalState("Xn")
875     else:
876         Xn = numpy.asarray(Xb)
877     #
878     if hasattr(Y,"stepnumber"):
879         duration = Y.stepnumber()
880     else:
881         duration = 2
882     #
883     # Multi-steps
884     # -----------
885     for step in range(duration-1):
886         if hasattr(Y,"store"):
887             Ynpu = numpy.asarray( Y[step+1] ).reshape((-1,1))
888         else:
889             Ynpu = numpy.asarray( Y ).reshape((-1,1))
890         #
891         if U is not None:
892             if hasattr(U,"store") and len(U)>1:
893                 Un = numpy.asarray( U[step] ).reshape((-1,1))
894             elif hasattr(U,"store") and len(U)==1:
895                 Un = numpy.asarray( U[0] ).reshape((-1,1))
896             else:
897                 Un = numpy.asarray( U ).reshape((-1,1))
898         else:
899             Un = None
900         #
901         if selfA._parameters["EstimationOf"] == "State": # Forecast
902             M = EM["Direct"].appliedControledFormTo
903             if CM is not None and "Tangent" in CM and Un is not None:
904                 Cm = CM["Tangent"].asMatrix(Xn)
905             else:
906                 Cm = None
907             #
908             Xn_predicted = M( (Xn, Un) )
909             if selfA._toStore("ForecastState"):
910                 selfA.StoredVariables["ForecastState"].store( Xn_predicted )
911             if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
912                 Cm = Cm.reshape(Xn.size,Un.size) # ADAO & check shape
913                 Xn_predicted = Xn_predicted + Cm @ Un
914         elif selfA._parameters["EstimationOf"] == "Parameters": # No forecast
915             # --- > Par principe, M = Id, Q = 0
916             Xn_predicted = Xn
917         Xn_predicted = numpy.asarray(Xn_predicted).reshape((-1,1))
918         #
919         oneCycle(selfA, Xn_predicted, Ynpu, HO, R, B) # Correct
920         #
921         Xn = selfA.StoredVariables["Analysis"][-1]
922         #--------------------------
923         selfA._setInternalState("Xn", Xn)
924     #
925     return 0
926
927 # ==============================================================================
928 if __name__ == "__main__":
929     print('\n AUTODIAGNOSTIC\n')