Salome HOME
Minor improvements for internal variables
[modules/adao.git] / src / daComposant / daCore / NumericObjects.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2021 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, time, copy, types, sys, logging
29 import math, numpy, scipy, scipy.optimize
30 from daCore.BasicObjects import Operator
31 from daCore.PlatformInfo import PlatformInfo
32 mpr = PlatformInfo().MachinePrecision()
33 mfp = PlatformInfo().MaximumPrecision()
34 # logging.getLogger().setLevel(logging.DEBUG)
35
36 # ==============================================================================
37 def ExecuteFunction( paire ):
38     assert len(paire) == 2, "Incorrect number of arguments"
39     X, funcrepr = paire
40     __X = numpy.asmatrix(numpy.ravel( X )).T
41     __sys_path_tmp = sys.path ; sys.path.insert(0,funcrepr["__userFunction__path"])
42     __module = __import__(funcrepr["__userFunction__modl"], globals(), locals(), [])
43     __fonction = getattr(__module,funcrepr["__userFunction__name"])
44     sys.path = __sys_path_tmp ; del __sys_path_tmp
45     __HX  = __fonction( __X )
46     return numpy.ravel( __HX )
47
48 # ==============================================================================
49 class FDApproximation(object):
50     """
51     Cette classe sert d'interface pour définir les opérateurs approximés. A la
52     création d'un objet, en fournissant une fonction "Function", on obtient un
53     objet qui dispose de 3 méthodes "DirectOperator", "TangentOperator" et
54     "AdjointOperator". On contrôle l'approximation DF avec l'incrément
55     multiplicatif "increment" valant par défaut 1%, ou avec l'incrément fixe
56     "dX" qui sera multiplié par "increment" (donc en %), et on effectue de DF
57     centrées si le booléen "centeredDF" est vrai.
58     """
59     def __init__(self,
60             name                  = "FDApproximation",
61             Function              = None,
62             centeredDF            = False,
63             increment             = 0.01,
64             dX                    = None,
65             avoidingRedundancy    = True,
66             toleranceInRedundancy = 1.e-18,
67             lenghtOfRedundancy    = -1,
68             mpEnabled             = False,
69             mpWorkers             = None,
70             mfEnabled             = False,
71             ):
72         self.__name = str(name)
73         if mpEnabled:
74             try:
75                 import multiprocessing
76                 self.__mpEnabled = True
77             except ImportError:
78                 self.__mpEnabled = False
79         else:
80             self.__mpEnabled = False
81         self.__mpWorkers = mpWorkers
82         if self.__mpWorkers is not None and self.__mpWorkers < 1:
83             self.__mpWorkers = None
84         logging.debug("FDA Calculs en multiprocessing : %s (nombre de processus : %s)"%(self.__mpEnabled,self.__mpWorkers))
85         #
86         if mfEnabled:
87             self.__mfEnabled = True
88         else:
89             self.__mfEnabled = False
90         logging.debug("FDA Calculs en multifonctions : %s"%(self.__mfEnabled,))
91         #
92         if avoidingRedundancy:
93             self.__avoidRC = True
94             self.__tolerBP = float(toleranceInRedundancy)
95             self.__lenghtRJ = int(lenghtOfRedundancy)
96             self.__listJPCP = [] # Jacobian Previous Calculated Points
97             self.__listJPCI = [] # Jacobian Previous Calculated Increment
98             self.__listJPCR = [] # Jacobian Previous Calculated Results
99             self.__listJPPN = [] # Jacobian Previous Calculated Point Norms
100             self.__listJPIN = [] # Jacobian Previous Calculated Increment Norms
101         else:
102             self.__avoidRC = False
103         #
104         if self.__mpEnabled:
105             if isinstance(Function,types.FunctionType):
106                 logging.debug("FDA Calculs en multiprocessing : FunctionType")
107                 self.__userFunction__name = Function.__name__
108                 try:
109                     mod = os.path.join(Function.__globals__['filepath'],Function.__globals__['filename'])
110                 except:
111                     mod = os.path.abspath(Function.__globals__['__file__'])
112                 if not os.path.isfile(mod):
113                     raise ImportError("No user defined function or method found with the name %s"%(mod,))
114                 self.__userFunction__modl = os.path.basename(mod).replace('.pyc','').replace('.pyo','').replace('.py','')
115                 self.__userFunction__path = os.path.dirname(mod)
116                 del mod
117                 self.__userOperator = Operator( name = self.__name, fromMethod = Function, avoidingRedundancy = self.__avoidRC, inputAsMultiFunction = self.__mfEnabled )
118                 self.__userFunction = self.__userOperator.appliedTo # Pour le calcul Direct
119             elif isinstance(Function,types.MethodType):
120                 logging.debug("FDA Calculs en multiprocessing : MethodType")
121                 self.__userFunction__name = Function.__name__
122                 try:
123                     mod = os.path.join(Function.__globals__['filepath'],Function.__globals__['filename'])
124                 except:
125                     mod = os.path.abspath(Function.__func__.__globals__['__file__'])
126                 if not os.path.isfile(mod):
127                     raise ImportError("No user defined function or method found with the name %s"%(mod,))
128                 self.__userFunction__modl = os.path.basename(mod).replace('.pyc','').replace('.pyo','').replace('.py','')
129                 self.__userFunction__path = os.path.dirname(mod)
130                 del mod
131                 self.__userOperator = Operator( name = self.__name, fromMethod = Function, avoidingRedundancy = self.__avoidRC, inputAsMultiFunction = self.__mfEnabled )
132                 self.__userFunction = self.__userOperator.appliedTo # Pour le calcul Direct
133             else:
134                 raise TypeError("User defined function or method has to be provided for finite differences approximation.")
135         else:
136             self.__userOperator = Operator( name = self.__name, fromMethod = Function, avoidingRedundancy = self.__avoidRC, inputAsMultiFunction = self.__mfEnabled )
137             self.__userFunction = self.__userOperator.appliedTo
138         #
139         self.__centeredDF = bool(centeredDF)
140         if abs(float(increment)) > 1.e-15:
141             self.__increment  = float(increment)
142         else:
143             self.__increment  = 0.01
144         if dX is None:
145             self.__dX     = None
146         else:
147             self.__dX     = numpy.asmatrix(numpy.ravel( dX )).T
148         logging.debug("FDA Reduction des doublons de calcul : %s"%self.__avoidRC)
149         if self.__avoidRC:
150             logging.debug("FDA Tolerance de determination des doublons : %.2e"%self.__tolerBP)
151
152     # ---------------------------------------------------------
153     def __doublon__(self, e, l, n, v=None):
154         __ac, __iac = False, -1
155         for i in range(len(l)-1,-1,-1):
156             if numpy.linalg.norm(e - l[i]) < self.__tolerBP * n[i]:
157                 __ac, __iac = True, i
158                 if v is not None: logging.debug("FDA Cas%s déja calculé, récupération du doublon %i"%(v,__iac))
159                 break
160         return __ac, __iac
161
162     # ---------------------------------------------------------
163     def DirectOperator(self, X ):
164         """
165         Calcul du direct à l'aide de la fonction fournie.
166         """
167         logging.debug("FDA Calcul DirectOperator (explicite)")
168         if self.__mfEnabled:
169             _HX = self.__userFunction( X, argsAsSerie = True )
170         else:
171             _X = numpy.asmatrix(numpy.ravel( X )).T
172             _HX = numpy.ravel(self.__userFunction( _X ))
173         #
174         return _HX
175
176     # ---------------------------------------------------------
177     def TangentMatrix(self, X ):
178         """
179         Calcul de l'opérateur tangent comme la Jacobienne par différences finies,
180         c'est-à-dire le gradient de H en X. On utilise des différences finies
181         directionnelles autour du point X. X est un numpy.matrix.
182
183         Différences finies centrées (approximation d'ordre 2):
184         1/ Pour chaque composante i de X, on ajoute et on enlève la perturbation
185            dX[i] à la  composante X[i], pour composer X_plus_dXi et X_moins_dXi, et
186            on calcule les réponses HX_plus_dXi = H( X_plus_dXi ) et HX_moins_dXi =
187            H( X_moins_dXi )
188         2/ On effectue les différences (HX_plus_dXi-HX_moins_dXi) et on divise par
189            le pas 2*dXi
190         3/ Chaque résultat, par composante, devient une colonne de la Jacobienne
191
192         Différences finies non centrées (approximation d'ordre 1):
193         1/ Pour chaque composante i de X, on ajoute la perturbation dX[i] à la
194            composante X[i] pour composer X_plus_dXi, et on calcule la réponse
195            HX_plus_dXi = H( X_plus_dXi )
196         2/ On calcule la valeur centrale HX = H(X)
197         3/ On effectue les différences (HX_plus_dXi-HX) et on divise par
198            le pas dXi
199         4/ Chaque résultat, par composante, devient une colonne de la Jacobienne
200
201         """
202         logging.debug("FDA Début du calcul de la Jacobienne")
203         logging.debug("FDA   Incrément de............: %s*X"%float(self.__increment))
204         logging.debug("FDA   Approximation centrée...: %s"%(self.__centeredDF))
205         #
206         if X is None or len(X)==0:
207             raise ValueError("Nominal point X for approximate derivatives can not be None or void (given X: %s)."%(str(X),))
208         #
209         _X = numpy.asmatrix(numpy.ravel( X )).T
210         #
211         if self.__dX is None:
212             _dX  = self.__increment * _X
213         else:
214             _dX = numpy.asmatrix(numpy.ravel( self.__dX )).T
215         #
216         if (_dX == 0.).any():
217             moyenne = _dX.mean()
218             if moyenne == 0.:
219                 _dX = numpy.where( _dX == 0., float(self.__increment), _dX )
220             else:
221                 _dX = numpy.where( _dX == 0., moyenne, _dX )
222         #
223         __alreadyCalculated  = False
224         if self.__avoidRC:
225             __bidon, __alreadyCalculatedP = self.__doublon__(_X,  self.__listJPCP, self.__listJPPN, None)
226             __bidon, __alreadyCalculatedI = self.__doublon__(_dX, self.__listJPCI, self.__listJPIN, None)
227             if __alreadyCalculatedP == __alreadyCalculatedI > -1:
228                 __alreadyCalculated, __i = True, __alreadyCalculatedP
229                 logging.debug("FDA Cas J déja calculé, récupération du doublon %i"%__i)
230         #
231         if __alreadyCalculated:
232             logging.debug("FDA   Calcul Jacobienne (par récupération du doublon %i)"%__i)
233             _Jacobienne = self.__listJPCR[__i]
234         else:
235             logging.debug("FDA   Calcul Jacobienne (explicite)")
236             if self.__centeredDF:
237                 #
238                 if self.__mpEnabled and not self.__mfEnabled:
239                     funcrepr = {
240                         "__userFunction__path" : self.__userFunction__path,
241                         "__userFunction__modl" : self.__userFunction__modl,
242                         "__userFunction__name" : self.__userFunction__name,
243                     }
244                     _jobs = []
245                     for i in range( len(_dX) ):
246                         _dXi            = _dX[i]
247                         _X_plus_dXi     = numpy.array( _X.A1, dtype=float )
248                         _X_plus_dXi[i]  = _X[i] + _dXi
249                         _X_moins_dXi    = numpy.array( _X.A1, dtype=float )
250                         _X_moins_dXi[i] = _X[i] - _dXi
251                         #
252                         _jobs.append( (_X_plus_dXi,  funcrepr) )
253                         _jobs.append( (_X_moins_dXi, funcrepr) )
254                     #
255                     import multiprocessing
256                     self.__pool = multiprocessing.Pool(self.__mpWorkers)
257                     _HX_plusmoins_dX = self.__pool.map( ExecuteFunction, _jobs )
258                     self.__pool.close()
259                     self.__pool.join()
260                     #
261                     _Jacobienne  = []
262                     for i in range( len(_dX) ):
263                         _Jacobienne.append( numpy.ravel( _HX_plusmoins_dX[2*i] - _HX_plusmoins_dX[2*i+1] ) / (2.*_dX[i]) )
264                     #
265                 elif self.__mfEnabled:
266                     _xserie = []
267                     for i in range( len(_dX) ):
268                         _dXi            = _dX[i]
269                         _X_plus_dXi     = numpy.array( _X.A1, dtype=float )
270                         _X_plus_dXi[i]  = _X[i] + _dXi
271                         _X_moins_dXi    = numpy.array( _X.A1, dtype=float )
272                         _X_moins_dXi[i] = _X[i] - _dXi
273                         #
274                         _xserie.append( _X_plus_dXi )
275                         _xserie.append( _X_moins_dXi )
276                     #
277                     _HX_plusmoins_dX = self.DirectOperator( _xserie )
278                      #
279                     _Jacobienne  = []
280                     for i in range( len(_dX) ):
281                         _Jacobienne.append( numpy.ravel( _HX_plusmoins_dX[2*i] - _HX_plusmoins_dX[2*i+1] ) / (2.*_dX[i]) )
282                     #
283                 else:
284                     _Jacobienne  = []
285                     for i in range( _dX.size ):
286                         _dXi            = _dX[i]
287                         _X_plus_dXi     = numpy.array( _X.A1, dtype=float )
288                         _X_plus_dXi[i]  = _X[i] + _dXi
289                         _X_moins_dXi    = numpy.array( _X.A1, dtype=float )
290                         _X_moins_dXi[i] = _X[i] - _dXi
291                         #
292                         _HX_plus_dXi    = self.DirectOperator( _X_plus_dXi )
293                         _HX_moins_dXi   = self.DirectOperator( _X_moins_dXi )
294                         #
295                         _Jacobienne.append( numpy.ravel( _HX_plus_dXi - _HX_moins_dXi ) / (2.*_dXi) )
296                 #
297             else:
298                 #
299                 if self.__mpEnabled and not self.__mfEnabled:
300                     funcrepr = {
301                         "__userFunction__path" : self.__userFunction__path,
302                         "__userFunction__modl" : self.__userFunction__modl,
303                         "__userFunction__name" : self.__userFunction__name,
304                     }
305                     _jobs = []
306                     _jobs.append( (_X.A1, funcrepr) )
307                     for i in range( len(_dX) ):
308                         _X_plus_dXi    = numpy.array( _X.A1, dtype=float )
309                         _X_plus_dXi[i] = _X[i] + _dX[i]
310                         #
311                         _jobs.append( (_X_plus_dXi, funcrepr) )
312                     #
313                     import multiprocessing
314                     self.__pool = multiprocessing.Pool(self.__mpWorkers)
315                     _HX_plus_dX = self.__pool.map( ExecuteFunction, _jobs )
316                     self.__pool.close()
317                     self.__pool.join()
318                     #
319                     _HX = _HX_plus_dX.pop(0)
320                     #
321                     _Jacobienne = []
322                     for i in range( len(_dX) ):
323                         _Jacobienne.append( numpy.ravel(( _HX_plus_dX[i] - _HX ) / _dX[i]) )
324                     #
325                 elif self.__mfEnabled:
326                     _xserie = []
327                     _xserie.append( _X.A1 )
328                     for i in range( len(_dX) ):
329                         _X_plus_dXi    = numpy.array( _X.A1, dtype=float )
330                         _X_plus_dXi[i] = _X[i] + _dX[i]
331                         #
332                         _xserie.append( _X_plus_dXi )
333                     #
334                     _HX_plus_dX = self.DirectOperator( _xserie )
335                     #
336                     _HX = _HX_plus_dX.pop(0)
337                     #
338                     _Jacobienne = []
339                     for i in range( len(_dX) ):
340                         _Jacobienne.append( numpy.ravel(( _HX_plus_dX[i] - _HX ) / _dX[i]) )
341                    #
342                 else:
343                     _Jacobienne  = []
344                     _HX = self.DirectOperator( _X )
345                     for i in range( _dX.size ):
346                         _dXi            = _dX[i]
347                         _X_plus_dXi     = numpy.array( _X.A1, dtype=float )
348                         _X_plus_dXi[i]  = _X[i] + _dXi
349                         #
350                         _HX_plus_dXi = self.DirectOperator( _X_plus_dXi )
351                         #
352                         _Jacobienne.append( numpy.ravel(( _HX_plus_dXi - _HX ) / _dXi) )
353                 #
354             #
355             _Jacobienne = numpy.asmatrix( numpy.vstack( _Jacobienne ) ).T
356             if self.__avoidRC:
357                 if self.__lenghtRJ < 0: self.__lenghtRJ = 2 * _X.size
358                 while len(self.__listJPCP) > self.__lenghtRJ:
359                     self.__listJPCP.pop(0)
360                     self.__listJPCI.pop(0)
361                     self.__listJPCR.pop(0)
362                     self.__listJPPN.pop(0)
363                     self.__listJPIN.pop(0)
364                 self.__listJPCP.append( copy.copy(_X) )
365                 self.__listJPCI.append( copy.copy(_dX) )
366                 self.__listJPCR.append( copy.copy(_Jacobienne) )
367                 self.__listJPPN.append( numpy.linalg.norm(_X) )
368                 self.__listJPIN.append( numpy.linalg.norm(_Jacobienne) )
369         #
370         logging.debug("FDA Fin du calcul de la Jacobienne")
371         #
372         return _Jacobienne
373
374     # ---------------------------------------------------------
375     def TangentOperator(self, paire ):
376         """
377         Calcul du tangent à l'aide de la Jacobienne.
378         """
379         if self.__mfEnabled:
380             assert len(paire) == 1, "Incorrect lenght of arguments"
381             _paire = paire[0]
382             assert len(_paire) == 2, "Incorrect number of arguments"
383         else:
384             assert len(paire) == 2, "Incorrect number of arguments"
385             _paire = paire
386         X, dX = _paire
387         _Jacobienne = self.TangentMatrix( X )
388         if dX is None or len(dX) == 0:
389             #
390             # Calcul de la forme matricielle si le second argument est None
391             # -------------------------------------------------------------
392             if self.__mfEnabled: return [_Jacobienne,]
393             else:                return _Jacobienne
394         else:
395             #
396             # Calcul de la valeur linéarisée de H en X appliqué à dX
397             # ------------------------------------------------------
398             _dX = numpy.asmatrix(numpy.ravel( dX )).T
399             _HtX = numpy.dot(_Jacobienne, _dX)
400             if self.__mfEnabled: return [_HtX.A1,]
401             else:                return _HtX.A1
402
403     # ---------------------------------------------------------
404     def AdjointOperator(self, paire ):
405         """
406         Calcul de l'adjoint à l'aide de la Jacobienne.
407         """
408         if self.__mfEnabled:
409             assert len(paire) == 1, "Incorrect lenght of arguments"
410             _paire = paire[0]
411             assert len(_paire) == 2, "Incorrect number of arguments"
412         else:
413             assert len(paire) == 2, "Incorrect number of arguments"
414             _paire = paire
415         X, Y = _paire
416         _JacobienneT = self.TangentMatrix( X ).T
417         if Y is None or len(Y) == 0:
418             #
419             # Calcul de la forme matricielle si le second argument est None
420             # -------------------------------------------------------------
421             if self.__mfEnabled: return [_JacobienneT,]
422             else:                return _JacobienneT
423         else:
424             #
425             # Calcul de la valeur de l'adjoint en X appliqué à Y
426             # --------------------------------------------------
427             _Y = numpy.asmatrix(numpy.ravel( Y )).T
428             _HaY = numpy.dot(_JacobienneT, _Y)
429             if self.__mfEnabled: return [_HaY.A1,]
430             else:                return _HaY.A1
431
432 # ==============================================================================
433 def mmqr(
434         func     = None,
435         x0       = None,
436         fprime   = None,
437         bounds   = None,
438         quantile = 0.5,
439         maxfun   = 15000,
440         toler    = 1.e-06,
441         y        = None,
442         ):
443     """
444     Implémentation informatique de l'algorithme MMQR, basée sur la publication :
445     David R. Hunter, Kenneth Lange, "Quantile Regression via an MM Algorithm",
446     Journal of Computational and Graphical Statistics, 9, 1, pp.60-77, 2000.
447     """
448     #
449     # Recuperation des donnees et informations initiales
450     # --------------------------------------------------
451     variables = numpy.ravel( x0 )
452     mesures   = numpy.ravel( y )
453     increment = sys.float_info[0]
454     p         = variables.size
455     n         = mesures.size
456     quantile  = float(quantile)
457     #
458     # Calcul des parametres du MM
459     # ---------------------------
460     tn      = float(toler) / n
461     e0      = -tn / math.log(tn)
462     epsilon = (e0-tn)/(1+math.log(e0))
463     #
464     # Calculs d'initialisation
465     # ------------------------
466     residus  = mesures - numpy.ravel( func( variables ) )
467     poids    = 1./(epsilon+numpy.abs(residus))
468     veps     = 1. - 2. * quantile - residus * poids
469     lastsurrogate = -numpy.sum(residus*veps) - (1.-2.*quantile)*numpy.sum(residus)
470     iteration = 0
471     #
472     # Recherche iterative
473     # -------------------
474     while (increment > toler) and (iteration < maxfun) :
475         iteration += 1
476         #
477         Derivees  = numpy.array(fprime(variables))
478         Derivees  = Derivees.reshape(n,p) # Necessaire pour remettre en place la matrice si elle passe par des tuyaux YACS
479         DeriveesT = Derivees.transpose()
480         M         =   numpy.dot( DeriveesT , (numpy.array(numpy.matrix(p*[poids,]).T)*Derivees) )
481         SM        =   numpy.transpose(numpy.dot( DeriveesT , veps ))
482         step      = - numpy.linalg.lstsq( M, SM, rcond=-1 )[0]
483         #
484         variables = variables + step
485         if bounds is not None:
486             # Attention : boucle infinie à éviter si un intervalle est trop petit
487             while( (variables < numpy.ravel(numpy.asmatrix(bounds)[:,0])).any() or (variables > numpy.ravel(numpy.asmatrix(bounds)[:,1])).any() ):
488                 step      = step/2.
489                 variables = variables - step
490         residus   = mesures - numpy.ravel( func(variables) )
491         surrogate = numpy.sum(residus**2 * poids) + (4.*quantile-2.) * numpy.sum(residus)
492         #
493         while ( (surrogate > lastsurrogate) and ( max(list(numpy.abs(step))) > 1.e-16 ) ) :
494             step      = step/2.
495             variables = variables - step
496             residus   = mesures - numpy.ravel( func(variables) )
497             surrogate = numpy.sum(residus**2 * poids) + (4.*quantile-2.) * numpy.sum(residus)
498         #
499         increment     = lastsurrogate-surrogate
500         poids         = 1./(epsilon+numpy.abs(residus))
501         veps          = 1. - 2. * quantile - residus * poids
502         lastsurrogate = -numpy.sum(residus * veps) - (1.-2.*quantile)*numpy.sum(residus)
503     #
504     # Mesure d'écart
505     # --------------
506     Ecart = quantile * numpy.sum(residus) - numpy.sum( residus[residus<0] )
507     #
508     return variables, Ecart, [n,p,iteration,increment,0]
509
510 # ==============================================================================
511 def EnsembleOfCenteredPerturbations( _bgcenter, _bgcovariance, _nbmembers ):
512     "Génération d'un ensemble de taille _nbmembers-1 d'états aléatoires centrés"
513     #
514     _bgcenter = numpy.ravel(_bgcenter)[:,None]
515     if _nbmembers < 1:
516         raise ValueError("Number of members has to be strictly more than 1 (given number: %s)."%(str(_nbmembers),))
517     #
518     if _bgcovariance is None:
519         BackgroundEnsemble = numpy.tile( _bgcenter, _nbmembers)
520     else:
521         _Z = numpy.random.multivariate_normal(numpy.zeros(_bgcenter.size), _bgcovariance, size=_nbmembers).T
522         BackgroundEnsemble = numpy.tile( _bgcenter, _nbmembers) + _Z
523     #
524     return BackgroundEnsemble
525
526 # ==============================================================================
527 def EnsembleOfBackgroundPerturbations( _bgcenter, _bgcovariance, _nbmembers, _withSVD = True):
528     "Génération d'un ensemble de taille _nbmembers-1 d'états aléatoires centrés"
529     def __CenteredRandomAnomalies(Zr, N):
530         """
531         Génère une matrice de N anomalies aléatoires centrées sur Zr selon les
532         notes manuscrites de MB et conforme au code de PS avec eps = -1
533         """
534         eps = -1
535         Q = numpy.eye(N-1)-numpy.ones((N-1,N-1))/numpy.sqrt(N)/(numpy.sqrt(N)-eps)
536         Q = numpy.concatenate((Q, [eps*numpy.ones(N-1)/numpy.sqrt(N)]), axis=0)
537         R, _ = numpy.linalg.qr(numpy.random.normal(size = (N-1,N-1)))
538         Q = numpy.dot(Q,R)
539         Zr = numpy.dot(Q,Zr)
540         return Zr.T
541     #
542     _bgcenter = numpy.ravel(_bgcenter)[:,None]
543     if _nbmembers < 1:
544         raise ValueError("Number of members has to be strictly more than 1 (given number: %s)."%(str(_nbmembers),))
545     if _bgcovariance is None:
546         BackgroundEnsemble = numpy.tile( _bgcenter, _nbmembers)
547     else:
548         if _withSVD:
549             U, s, V = numpy.linalg.svd(_bgcovariance, full_matrices=False)
550             _nbctl = _bgcenter.size
551             if _nbmembers > _nbctl:
552                 _Z = numpy.concatenate((numpy.dot(
553                     numpy.diag(numpy.sqrt(s[:_nbctl])), V[:_nbctl]),
554                     numpy.random.multivariate_normal(numpy.zeros(_nbctl),_bgcovariance,_nbmembers-1-_nbctl)), axis = 0)
555             else:
556                 _Z = numpy.dot(numpy.diag(numpy.sqrt(s[:_nbmembers-1])), V[:_nbmembers-1])
557             _Zca = __CenteredRandomAnomalies(_Z, _nbmembers)
558             BackgroundEnsemble = _bgcenter + _Zca
559         else:
560             if max(abs(_bgcovariance.flatten())) > 0:
561                 _nbctl = _bgcenter.size
562                 _Z = numpy.random.multivariate_normal(numpy.zeros(_nbctl),_bgcovariance,_nbmembers-1)
563                 _Zca = __CenteredRandomAnomalies(_Z, _nbmembers)
564                 BackgroundEnsemble = _bgcenter + _Zca
565             else:
566                 BackgroundEnsemble = numpy.tile( _bgcenter, _nbmembers)
567     #
568     return BackgroundEnsemble
569
570 # ==============================================================================
571 def EnsembleOfAnomalies( _ensemble, _optmean = None):
572     "Renvoie les anomalies centrées à partir d'un ensemble TailleEtat*NbMembres"
573     if _optmean is None:
574         Em = numpy.asarray(_ensemble).mean(axis=1, dtype=mfp).astype('float')[:,numpy.newaxis]
575     else:
576         Em = numpy.ravel(_optmean)[:,numpy.newaxis]
577     #
578     return numpy.asarray(_ensemble) - Em
579
580 # ==============================================================================
581 def CovarianceInflation(
582         InputCovOrEns,
583         InflationType   = None,
584         InflationFactor = None,
585         BackgroundCov   = None,
586         ):
587     """
588     Inflation applicable soit sur Pb ou Pa, soit sur les ensembles EXb ou EXa
589
590     Synthèse : Hunt 2007, section 2.3.5
591     """
592     if InflationFactor is None:
593         return InputCovOrEns
594     else:
595         InflationFactor = float(InflationFactor)
596     #
597     if InflationType in ["MultiplicativeOnAnalysisCovariance", "MultiplicativeOnBackgroundCovariance"]:
598         if InflationFactor < 1.:
599             raise ValueError("Inflation factor for multiplicative inflation has to be greater or equal than 1.")
600         if InflationFactor < 1.+mpr:
601             return InputCovOrEns
602         OutputCovOrEns = InflationFactor**2 * InputCovOrEns
603     #
604     elif InflationType in ["MultiplicativeOnAnalysisAnomalies", "MultiplicativeOnBackgroundAnomalies"]:
605         if InflationFactor < 1.:
606             raise ValueError("Inflation factor for multiplicative inflation has to be greater or equal than 1.")
607         if InflationFactor < 1.+mpr:
608             return InputCovOrEns
609         InputCovOrEnsMean = InputCovOrEns.mean(axis=1, dtype=mfp).astype('float')
610         OutputCovOrEns = InputCovOrEnsMean[:,numpy.newaxis] \
611             + InflationFactor * (InputCovOrEns - InputCovOrEnsMean[:,numpy.newaxis])
612     #
613     elif InflationType in ["AdditiveOnBackgroundCovariance", "AdditiveOnAnalysisCovariance"]:
614         if InflationFactor < 0.:
615             raise ValueError("Inflation factor for additive inflation has to be greater or equal than 0.")
616         if InflationFactor < mpr:
617             return InputCovOrEns
618         __n, __m = numpy.asarray(InputCovOrEns).shape
619         if __n != __m:
620             raise ValueError("Additive inflation can only be applied to squared (covariance) matrix.")
621         OutputCovOrEns = (1. - InflationFactor) * InputCovOrEns + InflationFactor * numpy.eye(__n)
622     #
623     elif InflationType == "HybridOnBackgroundCovariance":
624         if InflationFactor < 0.:
625             raise ValueError("Inflation factor for hybrid inflation has to be greater or equal than 0.")
626         if InflationFactor < mpr:
627             return InputCovOrEns
628         __n, __m = numpy.asarray(InputCovOrEns).shape
629         if __n != __m:
630             raise ValueError("Additive inflation can only be applied to squared (covariance) matrix.")
631         if BackgroundCov is None:
632             raise ValueError("Background covariance matrix B has to be given for hybrid inflation.")
633         if InputCovOrEns.shape != BackgroundCov.shape:
634             raise ValueError("Ensemble covariance matrix has to be of same size than background covariance matrix B.")
635         OutputCovOrEns = (1. - InflationFactor) * InputCovOrEns + InflationFactor * BackgroundCov
636     #
637     elif InflationType == "Relaxation":
638         raise NotImplementedError("InflationType Relaxation")
639     #
640     else:
641         raise ValueError("Error in inflation type, '%s' is not a valid keyword."%InflationType)
642     #
643     return OutputCovOrEns
644
645 # ==============================================================================
646 def senkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, VariantM="KalmanFilterFormula"):
647     """
648     Stochastic EnKF (Envensen 1994, Burgers 1998)
649
650     selfA est identique au "self" d'algorithme appelant et contient les
651     valeurs.
652     """
653     if selfA._parameters["EstimationOf"] == "Parameters":
654         selfA._parameters["StoreInternalVariables"] = True
655     #
656     # Opérateurs
657     # ----------
658     H = HO["Direct"].appliedControledFormTo
659     #
660     if selfA._parameters["EstimationOf"] == "State":
661         M = EM["Direct"].appliedControledFormTo
662     #
663     if CM is not None and "Tangent" in CM and U is not None:
664         Cm = CM["Tangent"].asMatrix(Xb)
665     else:
666         Cm = None
667     #
668     # Nombre de pas identique au nombre de pas d'observations
669     # -------------------------------------------------------
670     if hasattr(Y,"stepnumber"):
671         duration = Y.stepnumber()
672         __p = numpy.cumprod(Y.shape())[-1]
673     else:
674         duration = 2
675         __p = numpy.array(Y).size
676     #
677     # Précalcul des inversions de B et R
678     # ----------------------------------
679     if selfA._parameters["StoreInternalVariables"] \
680         or selfA._toStore("CostFunctionJ") \
681         or selfA._toStore("CostFunctionJb") \
682         or selfA._toStore("CostFunctionJo") \
683         or selfA._toStore("CurrentOptimum") \
684         or selfA._toStore("APosterioriCovariance"):
685         BI = B.getI()
686         RI = R.getI()
687     #
688     # Initialisation
689     # --------------
690     __n = Xb.size
691     __m = selfA._parameters["NumberOfMembers"]
692     if hasattr(B,"asfullmatrix"): Pn = B.asfullmatrix(__n)
693     else:                         Pn = B
694     if hasattr(R,"asfullmatrix"): Rn = R.asfullmatrix(__p)
695     else:                         Rn = R
696     if hasattr(Q,"asfullmatrix"): Qn = Q.asfullmatrix(__n)
697     else:                         Qn = Q
698     Xn = numpy.asmatrix(numpy.dot( Xb.reshape((__n,1)), numpy.ones((1,__m)) ))
699     #
700     if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
701         selfA.StoredVariables["Analysis"].store( numpy.ravel(Xb) )
702         if selfA._toStore("APosterioriCovariance"):
703             selfA.StoredVariables["APosterioriCovariance"].store( Pn )
704             covarianceXa = Pn
705     #
706     previousJMinimum = numpy.finfo(float).max
707     #
708     # Predimensionnement
709     Xn_predicted = numpy.asmatrix(numpy.zeros((__n,__m)))
710     HX_predicted = numpy.asmatrix(numpy.zeros((__p,__m)))
711     #
712     for step in range(duration-1):
713         if hasattr(Y,"store"):
714             Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
715         else:
716             Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
717         #
718         if U is not None:
719             if hasattr(U,"store") and len(U)>1:
720                 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
721             elif hasattr(U,"store") and len(U)==1:
722                 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
723             else:
724                 Un = numpy.asmatrix(numpy.ravel( U )).T
725         else:
726             Un = None
727         #
728         if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
729             Xn = CovarianceInflation( Xn,
730                 selfA._parameters["InflationType"],
731                 selfA._parameters["InflationFactor"],
732                 )
733         #
734         if selfA._parameters["EstimationOf"] == "State": # Forecast + Q and observation of forecast
735             EMX = M( [(Xn[:,i], Un) for i in range(__m)], argsAsSerie = True )
736             for i in range(__m):
737                 qi = numpy.random.multivariate_normal(numpy.zeros(__n), Qn)
738                 Xn_predicted[:,i] = (numpy.ravel( EMX[i] ) + qi).reshape((__n,-1))
739             HX_predicted = H( [(Xn_predicted[:,i], Un) for i in range(__m)],
740                 argsAsSerie = True,
741                 returnSerieAsArrayMatrix = True )
742             if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
743                 Cm = Cm.reshape(__n,Un.size) # ADAO & check shape
744                 Xn_predicted = Xn_predicted + Cm * Un
745         elif selfA._parameters["EstimationOf"] == "Parameters": # Observation of forecast
746             # --- > Par principe, M = Id, Q = 0
747             Xn_predicted = Xn
748             HX_predicted = H( [(Xn_predicted[:,i], Un) for i in range(__m)],
749                 argsAsSerie = True,
750                 returnSerieAsArrayMatrix = True )
751         #
752         # Mean of forecast and observation of forecast
753         Xfm  = Xn_predicted.mean(axis=1, dtype=mfp).astype('float')
754         Hfm  = HX_predicted.mean(axis=1, dtype=mfp).astype('float')
755         #
756         #--------------------------
757         if VariantM == "KalmanFilterFormula":
758             PfHT, HPfHT = 0., 0.
759             for i in range(__m):
760                 Exfi = Xn_predicted[:,i] - Xfm.reshape((__n,-1))
761                 Eyfi = (HX_predicted[:,i] - Hfm).reshape((__p,1))
762                 PfHT  += Exfi * Eyfi.T
763                 HPfHT += Eyfi * Eyfi.T
764             PfHT  = (1./(__m-1)) * PfHT
765             HPfHT = (1./(__m-1)) * HPfHT
766             K     = PfHT * ( R + HPfHT ).I
767             del PfHT, HPfHT
768             #
769             for i in range(__m):
770                 ri = numpy.random.multivariate_normal(numpy.zeros(__p), Rn)
771                 Xn[:,i] = Xn_predicted[:,i] + K @ (numpy.ravel(Ynpu) + ri - HX_predicted[:,i]).reshape((__p,1))
772         #--------------------------
773         else:
774             raise ValueError("VariantM has to be chosen in the authorized methods list.")
775         #
776         if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
777             Xn = CovarianceInflation( Xn,
778                 selfA._parameters["InflationType"],
779                 selfA._parameters["InflationFactor"],
780                 )
781         #
782         Xa = Xn.mean(axis=1, dtype=mfp).astype('float')
783         #--------------------------
784         #
785         if selfA._parameters["StoreInternalVariables"] \
786             or selfA._toStore("CostFunctionJ") \
787             or selfA._toStore("CostFunctionJb") \
788             or selfA._toStore("CostFunctionJo") \
789             or selfA._toStore("APosterioriCovariance") \
790             or selfA._toStore("InnovationAtCurrentAnalysis") \
791             or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
792             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
793             _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
794             _Innovation = Ynpu - _HXa
795         #
796         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
797         # ---> avec analysis
798         selfA.StoredVariables["Analysis"].store( Xa )
799         if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
800             selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
801         if selfA._toStore("InnovationAtCurrentAnalysis"):
802             selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
803         # ---> avec current state
804         if selfA._parameters["StoreInternalVariables"] \
805             or selfA._toStore("CurrentState"):
806             selfA.StoredVariables["CurrentState"].store( Xn )
807         if selfA._toStore("ForecastState"):
808             selfA.StoredVariables["ForecastState"].store( Xn_predicted )
809         if selfA._toStore("BMA"):
810             selfA.StoredVariables["BMA"].store( Xn_predicted - Xa )
811         if selfA._toStore("InnovationAtCurrentState"):
812             selfA.StoredVariables["InnovationAtCurrentState"].store( - HX_predicted + Ynpu )
813         if selfA._toStore("SimulatedObservationAtCurrentState") \
814             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
815             selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HX_predicted )
816         # ---> autres
817         if selfA._parameters["StoreInternalVariables"] \
818             or selfA._toStore("CostFunctionJ") \
819             or selfA._toStore("CostFunctionJb") \
820             or selfA._toStore("CostFunctionJo") \
821             or selfA._toStore("CurrentOptimum") \
822             or selfA._toStore("APosterioriCovariance"):
823             Jb  = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
824             Jo  = float( 0.5 * _Innovation.T * RI * _Innovation )
825             J   = Jb + Jo
826             selfA.StoredVariables["CostFunctionJb"].store( Jb )
827             selfA.StoredVariables["CostFunctionJo"].store( Jo )
828             selfA.StoredVariables["CostFunctionJ" ].store( J )
829             #
830             if selfA._toStore("IndexOfOptimum") \
831                 or selfA._toStore("CurrentOptimum") \
832                 or selfA._toStore("CostFunctionJAtCurrentOptimum") \
833                 or selfA._toStore("CostFunctionJbAtCurrentOptimum") \
834                 or selfA._toStore("CostFunctionJoAtCurrentOptimum") \
835                 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
836                 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
837             if selfA._toStore("IndexOfOptimum"):
838                 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
839             if selfA._toStore("CurrentOptimum"):
840                 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["Analysis"][IndexMin] )
841             if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
842                 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"][IndexMin] )
843             if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
844                 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
845             if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
846                 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
847             if selfA._toStore("CostFunctionJAtCurrentOptimum"):
848                 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
849         if selfA._toStore("APosterioriCovariance"):
850             Eai = (1/numpy.sqrt(__m-1)) * (Xn - Xa.reshape((__n,-1))) # Anomalies
851             Pn = Eai @ Eai.T
852             Pn = 0.5 * (Pn + Pn.T)
853             selfA.StoredVariables["APosterioriCovariance"].store( Pn )
854         if selfA._parameters["EstimationOf"] == "Parameters" \
855             and J < previousJMinimum:
856             previousJMinimum    = J
857             XaMin               = Xa
858             if selfA._toStore("APosterioriCovariance"):
859                 covarianceXaMin = Pn
860     #
861     # Stockage final supplémentaire de l'optimum en estimation de paramètres
862     # ----------------------------------------------------------------------
863     if selfA._parameters["EstimationOf"] == "Parameters":
864         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
865         selfA.StoredVariables["Analysis"].store( XaMin )
866         if selfA._toStore("APosterioriCovariance"):
867             selfA.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
868         if selfA._toStore("BMA"):
869             selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
870     #
871     return 0
872
873 # ==============================================================================
874 def etkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, VariantM="KalmanFilterFormula"):
875     """
876     Ensemble-Transform EnKF (ETKF or Deterministic EnKF: Bishop 2001, Hunt 2007)
877
878     selfA est identique au "self" d'algorithme appelant et contient les
879     valeurs.
880     """
881     if selfA._parameters["EstimationOf"] == "Parameters":
882         selfA._parameters["StoreInternalVariables"] = True
883     #
884     # Opérateurs
885     # ----------
886     H = HO["Direct"].appliedControledFormTo
887     #
888     if selfA._parameters["EstimationOf"] == "State":
889         M = EM["Direct"].appliedControledFormTo
890     #
891     if CM is not None and "Tangent" in CM and U is not None:
892         Cm = CM["Tangent"].asMatrix(Xb)
893     else:
894         Cm = None
895     #
896     # Nombre de pas identique au nombre de pas d'observations
897     # -------------------------------------------------------
898     if hasattr(Y,"stepnumber"):
899         duration = Y.stepnumber()
900         __p = numpy.cumprod(Y.shape())[-1]
901     else:
902         duration = 2
903         __p = numpy.array(Y).size
904     #
905     # Précalcul des inversions de B et R
906     # ----------------------------------
907     if selfA._parameters["StoreInternalVariables"] \
908         or selfA._toStore("CostFunctionJ") \
909         or selfA._toStore("CostFunctionJb") \
910         or selfA._toStore("CostFunctionJo") \
911         or selfA._toStore("CurrentOptimum") \
912         or selfA._toStore("APosterioriCovariance"):
913         BI = B.getI()
914         RI = R.getI()
915     elif VariantM != "KalmanFilterFormula":
916         RI = R.getI()
917     if VariantM == "KalmanFilterFormula":
918         RIdemi = R.choleskyI()
919     #
920     # Initialisation
921     # --------------
922     __n = Xb.size
923     __m = selfA._parameters["NumberOfMembers"]
924     if hasattr(B,"asfullmatrix"): Pn = B.asfullmatrix(__n)
925     else:                         Pn = B
926     if hasattr(R,"asfullmatrix"): Rn = R.asfullmatrix(__p)
927     else:                         Rn = R
928     if hasattr(Q,"asfullmatrix"): Qn = Q.asfullmatrix(__n)
929     else:                         Qn = Q
930     Xn = numpy.asmatrix(numpy.dot( Xb.reshape((__n,1)), numpy.ones((1,__m)) ))
931     #
932     if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
933         selfA.StoredVariables["Analysis"].store( numpy.ravel(Xb) )
934         if selfA._toStore("APosterioriCovariance"):
935             selfA.StoredVariables["APosterioriCovariance"].store( Pn )
936             covarianceXa = Pn
937     #
938     previousJMinimum = numpy.finfo(float).max
939     #
940     # Predimensionnement
941     Xn_predicted = numpy.asmatrix(numpy.zeros((__n,__m)))
942     #
943     for step in range(duration-1):
944         if hasattr(Y,"store"):
945             Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
946         else:
947             Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
948         #
949         if U is not None:
950             if hasattr(U,"store") and len(U)>1:
951                 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
952             elif hasattr(U,"store") and len(U)==1:
953                 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
954             else:
955                 Un = numpy.asmatrix(numpy.ravel( U )).T
956         else:
957             Un = None
958         #
959         if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
960             Xn = CovarianceInflation( Xn,
961                 selfA._parameters["InflationType"],
962                 selfA._parameters["InflationFactor"],
963                 )
964         #
965         if selfA._parameters["EstimationOf"] == "State": # Forecast + Q and observation of forecast
966             EMX = M( [(Xn[:,i], Un) for i in range(__m)], argsAsSerie = True )
967             for i in range(__m):
968                 qi = numpy.random.multivariate_normal(numpy.zeros(__n), Qn)
969                 Xn_predicted[:,i] = (numpy.ravel( EMX[i] ) + qi).reshape((__n,-1))
970             HX_predicted = H( [(Xn_predicted[:,i], Un) for i in range(__m)],
971                 argsAsSerie = True,
972                 returnSerieAsArrayMatrix = True )
973             if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
974                 Cm = Cm.reshape(__n,Un.size) # ADAO & check shape
975                 Xn_predicted = Xn_predicted + Cm * Un
976         elif selfA._parameters["EstimationOf"] == "Parameters": # Observation of forecast
977             # --- > Par principe, M = Id, Q = 0
978             Xn_predicted = Xn
979             HX_predicted = H( [(Xn_predicted[:,i], Un) for i in range(__m)],
980                 argsAsSerie = True,
981                 returnSerieAsArrayMatrix = True )
982         #
983         # Mean of forecast and observation of forecast
984         Xfm  = Xn_predicted.mean(axis=1, dtype=mfp).astype('float')
985         Hfm  = HX_predicted.mean(axis=1, dtype=mfp).astype('float')
986         #
987         # Anomalies
988         EaX   = numpy.matrix(Xn_predicted - Xfm.reshape((__n,-1)))
989         EaHX  = numpy.matrix(HX_predicted - Hfm.reshape((__p,-1)))
990         #
991         #--------------------------
992         if VariantM == "KalmanFilterFormula":
993             EaX    = EaX / numpy.sqrt(__m-1)
994             mS    = RIdemi * EaHX / numpy.sqrt(__m-1)
995             delta = RIdemi * ( Ynpu.reshape((__p,-1)) - Hfm.reshape((__p,-1)) )
996             mT    = numpy.linalg.inv( numpy.eye(__m) + mS.T @ mS )
997             vw    = mT @ mS.transpose() @ delta
998             #
999             Tdemi = numpy.real(scipy.linalg.sqrtm(mT))
1000             mU    = numpy.eye(__m)
1001             #
1002             Xn = Xfm.reshape((__n,-1)) + EaX @ ( vw.reshape((__m,-1)) + numpy.sqrt(__m-1) * Tdemi @ mU )
1003         #--------------------------
1004         elif VariantM == "Variational":
1005             HXfm = H((Xfm, Un)) # Eventuellement Hfm
1006             def CostFunction(w):
1007                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1008                 _Jo = 0.5 * _A.T * RI * _A
1009                 _Jb = 0.5 * (__m-1) * w.T @ w
1010                 _J  = _Jo + _Jb
1011                 return float(_J)
1012             def GradientOfCostFunction(w):
1013                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1014                 _GardJo = - EaHX.T * RI * _A
1015                 _GradJb = (__m-1) * w.reshape((__m,1))
1016                 _GradJ  = _GardJo + _GradJb
1017                 return numpy.ravel(_GradJ)
1018             vw = scipy.optimize.fmin_cg(
1019                 f           = CostFunction,
1020                 x0          = numpy.zeros(__m),
1021                 fprime      = GradientOfCostFunction,
1022                 args        = (),
1023                 disp        = False,
1024                 )
1025             #
1026             Hto = EaHX.T * RI * EaHX
1027             Htb = (__m-1) * numpy.eye(__m)
1028             Hta = Hto + Htb
1029             #
1030             Pta = numpy.linalg.inv( Hta )
1031             EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1032             #
1033             Xn = Xfm.reshape((__n,-1)) + EaX @ (vw.reshape((__m,-1)) + EWa)
1034         #--------------------------
1035         elif VariantM == "FiniteSize11": # Jauge Boc2011
1036             HXfm = H((Xfm, Un)) # Eventuellement Hfm
1037             def CostFunction(w):
1038                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1039                 _Jo = 0.5 * _A.T * RI * _A
1040                 _Jb = 0.5 * __m * math.log(1 + 1/__m + w.T @ w)
1041                 _J  = _Jo + _Jb
1042                 return float(_J)
1043             def GradientOfCostFunction(w):
1044                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1045                 _GardJo = - EaHX.T * RI * _A
1046                 _GradJb = __m * w.reshape((__m,1)) / (1 + 1/__m + w.T @ w)
1047                 _GradJ  = _GardJo + _GradJb
1048                 return numpy.ravel(_GradJ)
1049             vw = scipy.optimize.fmin_cg(
1050                 f           = CostFunction,
1051                 x0          = numpy.zeros(__m),
1052                 fprime      = GradientOfCostFunction,
1053                 args        = (),
1054                 disp        = False,
1055                 )
1056             #
1057             Hto = EaHX.T * RI * EaHX
1058             Htb = __m * \
1059                 ( (1 + 1/__m + vw.T @ vw) * numpy.eye(__m) - 2 * vw @ vw.T ) \
1060                 / (1 + 1/__m + vw.T @ vw)**2
1061             Hta = Hto + Htb
1062             #
1063             Pta = numpy.linalg.inv( Hta )
1064             EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1065             #
1066             Xn = Xfm.reshape((__n,-1)) + EaX @ (vw.reshape((__m,-1)) + EWa)
1067         #--------------------------
1068         elif VariantM == "FiniteSize15": # Jauge Boc2015
1069             HXfm = H((Xfm, Un)) # Eventuellement Hfm
1070             def CostFunction(w):
1071                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1072                 _Jo = 0.5 * _A.T * RI * _A
1073                 _Jb = 0.5 * (__m+1) * math.log(1 + 1/__m + w.T @ w)
1074                 _J  = _Jo + _Jb
1075                 return float(_J)
1076             def GradientOfCostFunction(w):
1077                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1078                 _GardJo = - EaHX.T * RI * _A
1079                 _GradJb = (__m+1) * w.reshape((__m,1)) / (1 + 1/__m + w.T @ w)
1080                 _GradJ  = _GardJo + _GradJb
1081                 return numpy.ravel(_GradJ)
1082             vw = scipy.optimize.fmin_cg(
1083                 f           = CostFunction,
1084                 x0          = numpy.zeros(__m),
1085                 fprime      = GradientOfCostFunction,
1086                 args        = (),
1087                 disp        = False,
1088                 )
1089             #
1090             Hto = EaHX.T * RI * EaHX
1091             Htb = (__m+1) * \
1092                 ( (1 + 1/__m + vw.T @ vw) * numpy.eye(__m) - 2 * vw @ vw.T ) \
1093                 / (1 + 1/__m + vw.T @ vw)**2
1094             Hta = Hto + Htb
1095             #
1096             Pta = numpy.linalg.inv( Hta )
1097             EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1098             #
1099             Xn = Xfm.reshape((__n,-1)) + EaX @ (vw.reshape((__m,-1)) + EWa)
1100         #--------------------------
1101         elif VariantM == "FiniteSize16": # Jauge Boc2016
1102             HXfm = H((Xfm, Un)) # Eventuellement Hfm
1103             def CostFunction(w):
1104                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1105                 _Jo = 0.5 * _A.T * RI * _A
1106                 _Jb = 0.5 * (__m+1) * math.log(1 + 1/__m + w.T @ w / (__m-1))
1107                 _J  = _Jo + _Jb
1108                 return float(_J)
1109             def GradientOfCostFunction(w):
1110                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1111                 _GardJo = - EaHX.T * RI * _A
1112                 _GradJb = ((__m+1) / (__m-1)) * w.reshape((__m,1)) / (1 + 1/__m + w.T @ w / (__m-1))
1113                 _GradJ  = _GardJo + _GradJb
1114                 return numpy.ravel(_GradJ)
1115             vw = scipy.optimize.fmin_cg(
1116                 f           = CostFunction,
1117                 x0          = numpy.zeros(__m),
1118                 fprime      = GradientOfCostFunction,
1119                 args        = (),
1120                 disp        = False,
1121                 )
1122             #
1123             Hto = EaHX.T * RI * EaHX
1124             Htb = ((__m+1) / (__m-1)) * \
1125                 ( (1 + 1/__m + vw.T @ vw / (__m-1)) * numpy.eye(__m) - 2 * vw @ vw.T / (__m-1) ) \
1126                 / (1 + 1/__m + vw.T @ vw / (__m-1))**2
1127             Hta = Hto + Htb
1128             #
1129             Pta = numpy.linalg.inv( Hta )
1130             EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1131             #
1132             Xn = Xfm.reshape((__n,-1)) + EaX @ (vw.reshape((__m,-1)) + EWa)
1133         #--------------------------
1134         else:
1135             raise ValueError("VariantM has to be chosen in the authorized methods list.")
1136         #
1137         if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
1138             Xn = CovarianceInflation( Xn,
1139                 selfA._parameters["InflationType"],
1140                 selfA._parameters["InflationFactor"],
1141                 )
1142         #
1143         Xa = Xn.mean(axis=1, dtype=mfp).astype('float')
1144         #--------------------------
1145         #
1146         if selfA._parameters["StoreInternalVariables"] \
1147             or selfA._toStore("CostFunctionJ") \
1148             or selfA._toStore("CostFunctionJb") \
1149             or selfA._toStore("CostFunctionJo") \
1150             or selfA._toStore("APosterioriCovariance") \
1151             or selfA._toStore("InnovationAtCurrentAnalysis") \
1152             or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
1153             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1154             _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
1155             _Innovation = Ynpu - _HXa
1156         #
1157         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1158         # ---> avec analysis
1159         selfA.StoredVariables["Analysis"].store( Xa )
1160         if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
1161             selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
1162         if selfA._toStore("InnovationAtCurrentAnalysis"):
1163             selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
1164         # ---> avec current state
1165         if selfA._parameters["StoreInternalVariables"] \
1166             or selfA._toStore("CurrentState"):
1167             selfA.StoredVariables["CurrentState"].store( Xn )
1168         if selfA._toStore("ForecastState"):
1169             selfA.StoredVariables["ForecastState"].store( Xn_predicted )
1170         if selfA._toStore("BMA"):
1171             selfA.StoredVariables["BMA"].store( Xn_predicted - Xa )
1172         if selfA._toStore("InnovationAtCurrentState"):
1173             selfA.StoredVariables["InnovationAtCurrentState"].store( - HX_predicted + Ynpu )
1174         if selfA._toStore("SimulatedObservationAtCurrentState") \
1175             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1176             selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HX_predicted )
1177         # ---> autres
1178         if selfA._parameters["StoreInternalVariables"] \
1179             or selfA._toStore("CostFunctionJ") \
1180             or selfA._toStore("CostFunctionJb") \
1181             or selfA._toStore("CostFunctionJo") \
1182             or selfA._toStore("CurrentOptimum") \
1183             or selfA._toStore("APosterioriCovariance"):
1184             Jb  = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
1185             Jo  = float( 0.5 * _Innovation.T * RI * _Innovation )
1186             J   = Jb + Jo
1187             selfA.StoredVariables["CostFunctionJb"].store( Jb )
1188             selfA.StoredVariables["CostFunctionJo"].store( Jo )
1189             selfA.StoredVariables["CostFunctionJ" ].store( J )
1190             #
1191             if selfA._toStore("IndexOfOptimum") \
1192                 or selfA._toStore("CurrentOptimum") \
1193                 or selfA._toStore("CostFunctionJAtCurrentOptimum") \
1194                 or selfA._toStore("CostFunctionJbAtCurrentOptimum") \
1195                 or selfA._toStore("CostFunctionJoAtCurrentOptimum") \
1196                 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1197                 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
1198             if selfA._toStore("IndexOfOptimum"):
1199                 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
1200             if selfA._toStore("CurrentOptimum"):
1201                 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["Analysis"][IndexMin] )
1202             if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1203                 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"][IndexMin] )
1204             if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
1205                 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
1206             if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
1207                 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
1208             if selfA._toStore("CostFunctionJAtCurrentOptimum"):
1209                 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
1210         if selfA._toStore("APosterioriCovariance"):
1211             Eai = (1/numpy.sqrt(__m-1)) * (Xn - Xa.reshape((__n,-1))) # Anomalies
1212             Pn = Eai @ Eai.T
1213             Pn = 0.5 * (Pn + Pn.T)
1214             selfA.StoredVariables["APosterioriCovariance"].store( Pn )
1215         if selfA._parameters["EstimationOf"] == "Parameters" \
1216             and J < previousJMinimum:
1217             previousJMinimum    = J
1218             XaMin               = Xa
1219             if selfA._toStore("APosterioriCovariance"):
1220                 covarianceXaMin = Pn
1221     #
1222     # Stockage final supplémentaire de l'optimum en estimation de paramètres
1223     # ----------------------------------------------------------------------
1224     if selfA._parameters["EstimationOf"] == "Parameters":
1225         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1226         selfA.StoredVariables["Analysis"].store( XaMin )
1227         if selfA._toStore("APosterioriCovariance"):
1228             selfA.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
1229         if selfA._toStore("BMA"):
1230             selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
1231     #
1232     return 0
1233
1234 # ==============================================================================
1235 def mlef(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, VariantM="MLEF13",
1236     BnotT=False, _epsilon=1.e-3, _e=1.e-7, _jmax=15000):
1237     """
1238     Maximum Likelihood Ensemble Filter (EnKF/MLEF Zupanski 2005, Bocquet 2013)
1239
1240     selfA est identique au "self" d'algorithme appelant et contient les
1241     valeurs.
1242     """
1243     if selfA._parameters["EstimationOf"] == "Parameters":
1244         selfA._parameters["StoreInternalVariables"] = True
1245     #
1246     # Opérateurs
1247     # ----------
1248     H = HO["Direct"].appliedControledFormTo
1249     #
1250     if selfA._parameters["EstimationOf"] == "State":
1251         M = EM["Direct"].appliedControledFormTo
1252     #
1253     if CM is not None and "Tangent" in CM and U is not None:
1254         Cm = CM["Tangent"].asMatrix(Xb)
1255     else:
1256         Cm = None
1257     #
1258     # Nombre de pas identique au nombre de pas d'observations
1259     # -------------------------------------------------------
1260     if hasattr(Y,"stepnumber"):
1261         duration = Y.stepnumber()
1262         __p = numpy.cumprod(Y.shape())[-1]
1263     else:
1264         duration = 2
1265         __p = numpy.array(Y).size
1266     #
1267     # Précalcul des inversions de B et R
1268     # ----------------------------------
1269     if selfA._parameters["StoreInternalVariables"] \
1270         or selfA._toStore("CostFunctionJ") \
1271         or selfA._toStore("CostFunctionJb") \
1272         or selfA._toStore("CostFunctionJo") \
1273         or selfA._toStore("CurrentOptimum") \
1274         or selfA._toStore("APosterioriCovariance"):
1275         BI = B.getI()
1276     RI = R.getI()
1277     #
1278     # Initialisation
1279     # --------------
1280     __n = Xb.size
1281     __m = selfA._parameters["NumberOfMembers"]
1282     if hasattr(B,"asfullmatrix"): Pn = B.asfullmatrix(__n)
1283     else:                         Pn = B
1284     if hasattr(R,"asfullmatrix"): Rn = R.asfullmatrix(__p)
1285     else:                         Rn = R
1286     if hasattr(Q,"asfullmatrix"): Qn = Q.asfullmatrix(__n)
1287     else:                         Qn = Q
1288     Xn = BackgroundEnsembleGeneration( Xb, None, __m )
1289     #
1290     if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
1291         selfA.StoredVariables["Analysis"].store( numpy.ravel(Xb) )
1292         if selfA._toStore("APosterioriCovariance"):
1293             selfA.StoredVariables["APosterioriCovariance"].store( Pn )
1294             covarianceXa = Pn
1295     #
1296     previousJMinimum = numpy.finfo(float).max
1297     #
1298     Xn_predicted = numpy.zeros((__n,__m))
1299     for step in range(duration-1):
1300         if hasattr(Y,"store"):
1301             Ynpu = numpy.ravel( Y[step+1] )[:,None]
1302         else:
1303             Ynpu = numpy.ravel( Y )[:,None]
1304         #
1305         if U is not None:
1306             if hasattr(U,"store") and len(U)>1:
1307                 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
1308             elif hasattr(U,"store") and len(U)==1:
1309                 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
1310             else:
1311                 Un = numpy.asmatrix(numpy.ravel( U )).T
1312         else:
1313             Un = None
1314         #
1315         if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
1316             Xn = CovarianceInflation( Xn,
1317                 selfA._parameters["InflationType"],
1318                 selfA._parameters["InflationFactor"],
1319                 )
1320         #
1321         if selfA._parameters["EstimationOf"] == "State": # Forecast + Q and observation of forecast
1322             EMX = M( [(Xn[:,i,numpy.newaxis], Un) for i in range(__m)], argsAsSerie = True )
1323             for i in range(__m):
1324                 qi = numpy.random.multivariate_normal(numpy.zeros(__n), Qn)
1325                 Xn_predicted[:,i] = numpy.ravel( EMX[i] ) + qi
1326             if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
1327                 Cm = Cm.reshape(__n,Un.size) # ADAO & check shape
1328                 Xn_predicted = Xn_predicted + Cm * Un
1329         elif selfA._parameters["EstimationOf"] == "Parameters": # Observation of forecast
1330             # --- > Par principe, M = Id, Q = 0
1331             Xn_predicted = Xn
1332         #
1333         #--------------------------
1334         if VariantM == "MLEF13":
1335             Xfm = numpy.asarray(Xn_predicted.mean(axis=1, dtype=mfp).astype('float'))
1336             EaX = numpy.asarray((Xn_predicted - Xfm.reshape((__n,-1))) / numpy.sqrt(__m-1))
1337             Ua  = numpy.eye(__m)
1338             __j = 0
1339             Deltaw = 1
1340             if not BnotT:
1341                 Ta  = numpy.eye(__m)
1342             vw  = numpy.zeros(__m)
1343             while numpy.linalg.norm(Deltaw) >= _e and __j <= _jmax:
1344                 vx1 = numpy.ravel(Xfm) + EaX @ vw
1345                 #
1346                 if BnotT:
1347                     E1 = vx1.reshape((__n,-1)) + _epsilon * EaX
1348                 else:
1349                     E1 = vx1.reshape((__n,-1)) + numpy.sqrt(__m-1) * EaX @ Ta
1350                 #
1351                 HE2 = H( [(E1[:,i,numpy.newaxis], Un) for i in range(__m)],
1352                     argsAsSerie = True,
1353                     returnSerieAsArrayMatrix = True )
1354                 vy2 = HE2.mean(axis=1, dtype=mfp).astype('float').reshape((__p,-1))
1355                 #
1356                 if BnotT:
1357                     EaY = (HE2 - vy2) / _epsilon
1358                 else:
1359                     EaY = ( (HE2 - vy2) @ numpy.linalg.inv(Ta) ) / numpy.sqrt(__m-1)
1360                 #
1361                 GradJ = numpy.ravel(vw[:,None] - EaY.transpose() @ (RI * ( Ynpu - vy2 )))
1362                 mH = numpy.eye(__m) + EaY.transpose() @ (RI * EaY)
1363                 Deltaw = - numpy.linalg.solve(mH,GradJ)
1364                 #
1365                 vw = vw + Deltaw
1366                 #
1367                 if not BnotT:
1368                     Ta = numpy.real(scipy.linalg.sqrtm(numpy.linalg.inv( mH )))
1369                 #
1370                 __j = __j + 1
1371             #
1372             if BnotT:
1373                 Ta = numpy.real(scipy.linalg.sqrtm(numpy.linalg.inv( mH )))
1374             #
1375             Xn = vx1.reshape((__n,-1)) + numpy.sqrt(__m-1) * EaX @ Ta @ Ua
1376         #--------------------------
1377         else:
1378             raise ValueError("VariantM has to be chosen in the authorized methods list.")
1379         #
1380         if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
1381             Xn = CovarianceInflation( Xn,
1382                 selfA._parameters["InflationType"],
1383                 selfA._parameters["InflationFactor"],
1384                 )
1385         #
1386         Xa = Xn.mean(axis=1, dtype=mfp).astype('float').reshape((__n,-1))
1387         #--------------------------
1388         #
1389         if selfA._parameters["StoreInternalVariables"] \
1390             or selfA._toStore("CostFunctionJ") \
1391             or selfA._toStore("CostFunctionJb") \
1392             or selfA._toStore("CostFunctionJo") \
1393             or selfA._toStore("APosterioriCovariance") \
1394             or selfA._toStore("InnovationAtCurrentAnalysis") \
1395             or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
1396             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1397             _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
1398             _Innovation = Ynpu - _HXa
1399         #
1400         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1401         # ---> avec analysis
1402         selfA.StoredVariables["Analysis"].store( Xa )
1403         if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
1404             selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
1405         if selfA._toStore("InnovationAtCurrentAnalysis"):
1406             selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
1407         # ---> avec current state
1408         if selfA._parameters["StoreInternalVariables"] \
1409             or selfA._toStore("CurrentState"):
1410             selfA.StoredVariables["CurrentState"].store( Xn )
1411         if selfA._toStore("ForecastState"):
1412             selfA.StoredVariables["ForecastState"].store( Xn_predicted )
1413         if selfA._toStore("BMA"):
1414             selfA.StoredVariables["BMA"].store( Xn_predicted - Xa )
1415         #~ if selfA._toStore("InnovationAtCurrentState"):
1416             #~ selfA.StoredVariables["InnovationAtCurrentState"].store( - HX_predicted + Ynpu )
1417         #~ if selfA._toStore("SimulatedObservationAtCurrentState") \
1418             #~ or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1419             #~ selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HX_predicted )
1420         # ---> autres
1421         if selfA._parameters["StoreInternalVariables"] \
1422             or selfA._toStore("CostFunctionJ") \
1423             or selfA._toStore("CostFunctionJb") \
1424             or selfA._toStore("CostFunctionJo") \
1425             or selfA._toStore("CurrentOptimum") \
1426             or selfA._toStore("APosterioriCovariance"):
1427             Jb  = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
1428             Jo  = float( 0.5 * _Innovation.T * RI * _Innovation )
1429             J   = Jb + Jo
1430             selfA.StoredVariables["CostFunctionJb"].store( Jb )
1431             selfA.StoredVariables["CostFunctionJo"].store( Jo )
1432             selfA.StoredVariables["CostFunctionJ" ].store( J )
1433             #
1434             if selfA._toStore("IndexOfOptimum") \
1435                 or selfA._toStore("CurrentOptimum") \
1436                 or selfA._toStore("CostFunctionJAtCurrentOptimum") \
1437                 or selfA._toStore("CostFunctionJbAtCurrentOptimum") \
1438                 or selfA._toStore("CostFunctionJoAtCurrentOptimum") \
1439                 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1440                 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
1441             if selfA._toStore("IndexOfOptimum"):
1442                 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
1443             if selfA._toStore("CurrentOptimum"):
1444                 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["Analysis"][IndexMin] )
1445             if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1446                 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"][IndexMin] )
1447             if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
1448                 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
1449             if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
1450                 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
1451             if selfA._toStore("CostFunctionJAtCurrentOptimum"):
1452                 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
1453         if selfA._toStore("APosterioriCovariance"):
1454             Eai = numpy.asarray((Xn - Xa.reshape((__n,-1))) / numpy.sqrt(__m-1)) # Anomalies
1455             Pn = Eai @ Eai.T
1456             Pn = 0.5 * (Pn + Pn.T)
1457             selfA.StoredVariables["APosterioriCovariance"].store( Pn )
1458         if selfA._parameters["EstimationOf"] == "Parameters" \
1459             and J < previousJMinimum:
1460             previousJMinimum    = J
1461             XaMin               = Xa
1462             if selfA._toStore("APosterioriCovariance"):
1463                 covarianceXaMin = Pn
1464     #
1465     # Stockage final supplémentaire de l'optimum en estimation de paramètres
1466     # ----------------------------------------------------------------------
1467     if selfA._parameters["EstimationOf"] == "Parameters":
1468         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1469         selfA.StoredVariables["Analysis"].store( XaMin )
1470         if selfA._toStore("APosterioriCovariance"):
1471             selfA.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
1472         if selfA._toStore("BMA"):
1473             selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
1474     #
1475     return 0
1476
1477 # ==============================================================================
1478 def ienkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, VariantM="IEnKF12",
1479     BnotT=False, _epsilon=1.e-3, _e=1.e-7, _jmax=15000):
1480     """
1481     Iterative EnKF (Sakov 2012, Sakov 2018)
1482
1483     selfA est identique au "self" d'algorithme appelant et contient les
1484     valeurs.
1485     """
1486     if selfA._parameters["EstimationOf"] == "Parameters":
1487         selfA._parameters["StoreInternalVariables"] = True
1488     #
1489     # Opérateurs
1490     # ----------
1491     H = HO["Direct"].appliedControledFormTo
1492     #
1493     if selfA._parameters["EstimationOf"] == "State":
1494         M = EM["Direct"].appliedControledFormTo
1495     #
1496     if CM is not None and "Tangent" in CM and U is not None:
1497         Cm = CM["Tangent"].asMatrix(Xb)
1498     else:
1499         Cm = None
1500     #
1501     # Nombre de pas identique au nombre de pas d'observations
1502     # -------------------------------------------------------
1503     if hasattr(Y,"stepnumber"):
1504         duration = Y.stepnumber()
1505         __p = numpy.cumprod(Y.shape())[-1]
1506     else:
1507         duration = 2
1508         __p = numpy.array(Y).size
1509     #
1510     # Précalcul des inversions de B et R
1511     # ----------------------------------
1512     if selfA._parameters["StoreInternalVariables"] \
1513         or selfA._toStore("CostFunctionJ") \
1514         or selfA._toStore("CostFunctionJb") \
1515         or selfA._toStore("CostFunctionJo") \
1516         or selfA._toStore("CurrentOptimum") \
1517         or selfA._toStore("APosterioriCovariance"):
1518         BI = B.getI()
1519     RI = R.getI()
1520     #
1521     # Initialisation
1522     # --------------
1523     __n = Xb.size
1524     __m = selfA._parameters["NumberOfMembers"]
1525     if hasattr(B,"asfullmatrix"): Pn = B.asfullmatrix(__n)
1526     else:                         Pn = B
1527     if hasattr(R,"asfullmatrix"): Rn = R.asfullmatrix(__p)
1528     else:                         Rn = R
1529     if hasattr(Q,"asfullmatrix"): Qn = Q.asfullmatrix(__n)
1530     else:                         Qn = Q
1531     Xn = BackgroundEnsembleGeneration( Xb, Pn, __m )
1532     #
1533     if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
1534         selfA.StoredVariables["Analysis"].store( numpy.ravel(Xb) )
1535         if selfA._toStore("APosterioriCovariance"):
1536             selfA.StoredVariables["APosterioriCovariance"].store( Pn )
1537             covarianceXa = Pn
1538     #
1539     previousJMinimum = numpy.finfo(float).max
1540     #
1541     for step in range(duration-1):
1542         if hasattr(Y,"store"):
1543             Ynpu = numpy.ravel( Y[step+1] )[:,None]
1544         else:
1545             Ynpu = numpy.ravel( Y )[:,None]
1546         #
1547         if U is not None:
1548             if hasattr(U,"store") and len(U)>1:
1549                 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
1550             elif hasattr(U,"store") and len(U)==1:
1551                 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
1552             else:
1553                 Un = numpy.asmatrix(numpy.ravel( U )).T
1554         else:
1555             Un = None
1556         #
1557         if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
1558             Xn = CovarianceInflation( Xn,
1559                 selfA._parameters["InflationType"],
1560                 selfA._parameters["InflationFactor"],
1561                 )
1562         #
1563         #--------------------------
1564         if VariantM == "IEnKF12":
1565             Xfm = numpy.asarray(Xn.mean(axis=1, dtype=mfp).astype('float'))
1566             EaX = numpy.asarray((Xn - Xfm.reshape((__n,-1))) / numpy.sqrt(__m-1))
1567             # EaX = EnsembleCenteredAnomalies( Xn ) / numpy.sqrt(__m-1)
1568             __j = 0
1569             Deltaw = 1
1570             if not BnotT:
1571                 Ta  = numpy.eye(__m)
1572             vw  = numpy.zeros(__m)
1573             while numpy.linalg.norm(Deltaw) >= _e and __j <= _jmax:
1574                 vx1 = numpy.ravel(Xfm) + EaX @ vw
1575                 #
1576                 if BnotT:
1577                     E1 = vx1.reshape((__n,-1)) + _epsilon * EaX
1578                 else:
1579                     E1 = vx1.reshape((__n,-1)) + numpy.sqrt(__m-1) * EaX @ Ta
1580                 #
1581                 if selfA._parameters["EstimationOf"] == "State": # Forecast + Q
1582                     E2 = M( [(E1[:,i,numpy.newaxis], Un) for i in range(__m)],
1583                         argsAsSerie = True,
1584                         returnSerieAsArrayMatrix = True )
1585                 elif selfA._parameters["EstimationOf"] == "Parameters":
1586                     # --- > Par principe, M = Id
1587                     E2 = Xn
1588                 vx2 = E2.mean(axis=1, dtype=mfp).astype('float').reshape((__n,-1))
1589                 vy1 = H((vx2, Un)).reshape((__p,-1))
1590                 #
1591                 HE2 = H( [(E2[:,i,numpy.newaxis], Un) for i in range(__m)],
1592                     argsAsSerie = True,
1593                     returnSerieAsArrayMatrix = True )
1594                 vy2 = HE2.mean(axis=1, dtype=mfp).astype('float').reshape((__p,-1))
1595                 #
1596                 if BnotT:
1597                     EaY = (HE2 - vy2) / _epsilon
1598                 else:
1599                     EaY = ( (HE2 - vy2) @ numpy.linalg.inv(Ta) ) / numpy.sqrt(__m-1)
1600                 #
1601                 GradJ = numpy.ravel(vw[:,None] - EaY.transpose() @ (RI * ( Ynpu - vy1 )))
1602                 mH = numpy.eye(__m) + EaY.transpose() @ (RI * EaY)
1603                 Deltaw = - numpy.linalg.solve(mH,GradJ)
1604                 #
1605                 vw = vw + Deltaw
1606                 #
1607                 if not BnotT:
1608                     Ta = numpy.real(scipy.linalg.sqrtm(numpy.linalg.inv( mH )))
1609                 #
1610                 __j = __j + 1
1611             #
1612             A2 = EnsembleCenteredAnomalies( E2 )
1613             #
1614             if BnotT:
1615                 Ta = numpy.real(scipy.linalg.sqrtm(numpy.linalg.inv( mH )))
1616                 A2 = numpy.sqrt(__m-1) * A2 @ Ta / _epsilon
1617             #
1618             Xn = vx2 + A2
1619         #--------------------------
1620         else:
1621             raise ValueError("VariantM has to be chosen in the authorized methods list.")
1622         #
1623         if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
1624             Xn = CovarianceInflation( Xn,
1625                 selfA._parameters["InflationType"],
1626                 selfA._parameters["InflationFactor"],
1627                 )
1628         #
1629         Xa = Xn.mean(axis=1, dtype=mfp).astype('float').reshape((__n,-1))
1630         #--------------------------
1631         #
1632         if selfA._parameters["StoreInternalVariables"] \
1633             or selfA._toStore("CostFunctionJ") \
1634             or selfA._toStore("CostFunctionJb") \
1635             or selfA._toStore("CostFunctionJo") \
1636             or selfA._toStore("APosterioriCovariance") \
1637             or selfA._toStore("InnovationAtCurrentAnalysis") \
1638             or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
1639             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1640             _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
1641             _Innovation = Ynpu - _HXa
1642         #
1643         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1644         # ---> avec analysis
1645         selfA.StoredVariables["Analysis"].store( Xa )
1646         if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
1647             selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
1648         if selfA._toStore("InnovationAtCurrentAnalysis"):
1649             selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
1650         # ---> avec current state
1651         if selfA._parameters["StoreInternalVariables"] \
1652             or selfA._toStore("CurrentState"):
1653             selfA.StoredVariables["CurrentState"].store( Xn )
1654         #~ if selfA._toStore("ForecastState"):
1655             #~ selfA.StoredVariables["ForecastState"].store( Xn_predicted )
1656         #~ if selfA._toStore("BMA"):
1657             #~ selfA.StoredVariables["BMA"].store( Xn_predicted - Xa )
1658         #~ if selfA._toStore("InnovationAtCurrentState"):
1659             #~ selfA.StoredVariables["InnovationAtCurrentState"].store( - HX_predicted + Ynpu.reshape((__p,-1)) )
1660         #~ if selfA._toStore("SimulatedObservationAtCurrentState") \
1661             #~ or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1662             #~ selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HX_predicted )
1663         # ---> autres
1664         if selfA._parameters["StoreInternalVariables"] \
1665             or selfA._toStore("CostFunctionJ") \
1666             or selfA._toStore("CostFunctionJb") \
1667             or selfA._toStore("CostFunctionJo") \
1668             or selfA._toStore("CurrentOptimum") \
1669             or selfA._toStore("APosterioriCovariance"):
1670             Jb  = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
1671             Jo  = float( 0.5 * _Innovation.T * RI * _Innovation )
1672             J   = Jb + Jo
1673             selfA.StoredVariables["CostFunctionJb"].store( Jb )
1674             selfA.StoredVariables["CostFunctionJo"].store( Jo )
1675             selfA.StoredVariables["CostFunctionJ" ].store( J )
1676             #
1677             if selfA._toStore("IndexOfOptimum") \
1678                 or selfA._toStore("CurrentOptimum") \
1679                 or selfA._toStore("CostFunctionJAtCurrentOptimum") \
1680                 or selfA._toStore("CostFunctionJbAtCurrentOptimum") \
1681                 or selfA._toStore("CostFunctionJoAtCurrentOptimum") \
1682                 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1683                 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
1684             if selfA._toStore("IndexOfOptimum"):
1685                 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
1686             if selfA._toStore("CurrentOptimum"):
1687                 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["Analysis"][IndexMin] )
1688             if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1689                 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"][IndexMin] )
1690             if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
1691                 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
1692             if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
1693                 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
1694             if selfA._toStore("CostFunctionJAtCurrentOptimum"):
1695                 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
1696         if selfA._toStore("APosterioriCovariance"):
1697             Eai = numpy.asarray((Xn - Xa.reshape((__n,-1))) / numpy.sqrt(__m-1)) # Anomalies
1698             Pn = Eai @ Eai.T
1699             Pn = 0.5 * (Pn + Pn.T)
1700             selfA.StoredVariables["APosterioriCovariance"].store( Pn )
1701         if selfA._parameters["EstimationOf"] == "Parameters" \
1702             and J < previousJMinimum:
1703             previousJMinimum    = J
1704             XaMin               = Xa
1705             if selfA._toStore("APosterioriCovariance"):
1706                 covarianceXaMin = Pn
1707     #
1708     # Stockage final supplémentaire de l'optimum en estimation de paramètres
1709     # ----------------------------------------------------------------------
1710     if selfA._parameters["EstimationOf"] == "Parameters":
1711         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1712         selfA.StoredVariables["Analysis"].store( XaMin )
1713         if selfA._toStore("APosterioriCovariance"):
1714             selfA.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
1715         if selfA._toStore("BMA"):
1716             selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
1717     #
1718     return 0
1719
1720 # ==============================================================================
1721 if __name__ == "__main__":
1722     print('\n AUTODIAGNOSTIC\n')