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 BackgroundEnsembleGeneration( _bgcenter, _bgcovariance, _nbmembers, _withSVD = True):
512     "Génération d'un ensemble d'ébauches aléatoires de taille _nbmembers-1"
513     def __CenteredRandomAnomalies(Zr, N):
514         """
515         Génère une matrice de N anomalies aléatoires centrées sur Zr selon les
516         notes manuscrites de MB et conforme au code de PS avec eps = -1
517         """
518         eps = -1
519         Q = numpy.eye(N-1)-numpy.ones((N-1,N-1))/numpy.sqrt(N)/(numpy.sqrt(N)-eps)
520         Q = numpy.concatenate((Q, [eps*numpy.ones(N-1)/numpy.sqrt(N)]), axis=0)
521         R, _ = numpy.linalg.qr(numpy.random.normal(size = (N-1,N-1)))
522         Q = numpy.dot(Q,R)
523         Zr = numpy.dot(Q,Zr)
524         return Zr.T
525     #
526     if _nbmembers < 1:
527         raise ValueError("Number of members has to be strictly more than 1 (given number: %s)."%(str(_nbmembers),))
528     if _bgcovariance is None:
529         BackgroundEnsemble = numpy.tile( numpy.ravel(_bgcenter)[:,None], _nbmembers)
530     else:
531         if _withSVD:
532             U, s, V = numpy.linalg.svd(_bgcovariance, full_matrices=False)
533             _nbctl = numpy.ravel(_bgcenter).size
534             if _nbmembers > _nbctl:
535                 _Z = numpy.concatenate((numpy.dot(
536                     numpy.diag(numpy.sqrt(s[:_nbctl])), V[:_nbctl]),
537                     numpy.random.multivariate_normal(numpy.zeros(_nbctl),_bgcovariance,_nbmembers-1-_nbctl)), axis = 0)
538             else:
539                 _Z = numpy.dot(numpy.diag(numpy.sqrt(s[:_nbmembers-1])), V[:_nbmembers-1])
540             _Zca = __CenteredRandomAnomalies(_Z, _nbmembers)
541             BackgroundEnsemble = numpy.ravel(_bgcenter)[:,None] + _Zca
542         else:
543             if max(abs(_bgcovariance.flatten())) > 0:
544                 _nbctl = numpy.ravel(_bgcenter).size
545                 _Z = numpy.random.multivariate_normal(numpy.zeros(_nbctl),_bgcovariance,_nbmembers-1)
546                 _Zca = __CenteredRandomAnomalies(_Z, _nbmembers)
547                 BackgroundEnsemble = numpy.ravel(_bgcenter)[:,None] + _Zca
548             else:
549                 BackgroundEnsemble = numpy.tile( numpy.ravel(_bgcenter)[:,None], _nbmembers)
550     #
551     return BackgroundEnsemble
552
553 # ==============================================================================
554 def EnsembleCenteredAnomalies( _ensemble, _optmean = None):
555     "Renvoie les anomalies centrées à partir d'un ensemble TailleEtat*NbMembres"
556     if _optmean is None:
557         Em = numpy.asarray(_ensemble).mean(axis=1, dtype=mfp).astype('float')[:,numpy.newaxis]
558     else:
559         Em = numpy.ravel(_optmean)[:,numpy.newaxis]
560     #
561     return numpy.asarray(_ensemble) - Em
562
563 # ==============================================================================
564 def CovarianceInflation(
565         InputCovOrEns,
566         InflationType   = None,
567         InflationFactor = None,
568         BackgroundCov   = None,
569         ):
570     """
571     Inflation applicable soit sur Pb ou Pa, soit sur les ensembles EXb ou EXa
572
573     Synthèse : Hunt 2007, section 2.3.5
574     """
575     if InflationFactor is None:
576         return InputCovOrEns
577     else:
578         InflationFactor = float(InflationFactor)
579     #
580     if InflationType in ["MultiplicativeOnAnalysisCovariance", "MultiplicativeOnBackgroundCovariance"]:
581         if InflationFactor < 1.:
582             raise ValueError("Inflation factor for multiplicative inflation has to be greater or equal than 1.")
583         if InflationFactor < 1.+mpr:
584             return InputCovOrEns
585         OutputCovOrEns = InflationFactor**2 * InputCovOrEns
586     #
587     elif InflationType in ["MultiplicativeOnAnalysisAnomalies", "MultiplicativeOnBackgroundAnomalies"]:
588         if InflationFactor < 1.:
589             raise ValueError("Inflation factor for multiplicative inflation has to be greater or equal than 1.")
590         if InflationFactor < 1.+mpr:
591             return InputCovOrEns
592         InputCovOrEnsMean = InputCovOrEns.mean(axis=1, dtype=mfp).astype('float')
593         OutputCovOrEns = InputCovOrEnsMean[:,numpy.newaxis] \
594             + InflationFactor * (InputCovOrEns - InputCovOrEnsMean[:,numpy.newaxis])
595     #
596     elif InflationType in ["AdditiveOnBackgroundCovariance", "AdditiveOnAnalysisCovariance"]:
597         if InflationFactor < 0.:
598             raise ValueError("Inflation factor for additive inflation has to be greater or equal than 0.")
599         if InflationFactor < mpr:
600             return InputCovOrEns
601         __n, __m = numpy.asarray(InputCovOrEns).shape
602         if __n != __m:
603             raise ValueError("Additive inflation can only be applied to squared (covariance) matrix.")
604         OutputCovOrEns = (1. - InflationFactor) * InputCovOrEns + InflationFactor * numpy.eye(__n)
605     #
606     elif InflationType == "HybridOnBackgroundCovariance":
607         if InflationFactor < 0.:
608             raise ValueError("Inflation factor for hybrid inflation has to be greater or equal than 0.")
609         if InflationFactor < mpr:
610             return InputCovOrEns
611         __n, __m = numpy.asarray(InputCovOrEns).shape
612         if __n != __m:
613             raise ValueError("Additive inflation can only be applied to squared (covariance) matrix.")
614         if BackgroundCov is None:
615             raise ValueError("Background covariance matrix B has to be given for hybrid inflation.")
616         if InputCovOrEns.shape != BackgroundCov.shape:
617             raise ValueError("Ensemble covariance matrix has to be of same size than background covariance matrix B.")
618         OutputCovOrEns = (1. - InflationFactor) * InputCovOrEns + InflationFactor * BackgroundCov
619     #
620     elif InflationType == "Relaxation":
621         raise NotImplementedError("InflationType Relaxation")
622     #
623     else:
624         raise ValueError("Error in inflation type, '%s' is not a valid keyword."%InflationType)
625     #
626     return OutputCovOrEns
627
628 # ==============================================================================
629 def senkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, VariantM="KalmanFilterFormula"):
630     """
631     Stochastic EnKF (Envensen 1994, Burgers 1998)
632
633     selfA est identique au "self" d'algorithme appelant et contient les
634     valeurs.
635     """
636     if selfA._parameters["EstimationOf"] == "Parameters":
637         selfA._parameters["StoreInternalVariables"] = True
638     #
639     # Opérateurs
640     # ----------
641     H = HO["Direct"].appliedControledFormTo
642     #
643     if selfA._parameters["EstimationOf"] == "State":
644         M = EM["Direct"].appliedControledFormTo
645     #
646     if CM is not None and "Tangent" in CM and U is not None:
647         Cm = CM["Tangent"].asMatrix(Xb)
648     else:
649         Cm = None
650     #
651     # Nombre de pas identique au nombre de pas d'observations
652     # -------------------------------------------------------
653     if hasattr(Y,"stepnumber"):
654         duration = Y.stepnumber()
655         __p = numpy.cumprod(Y.shape())[-1]
656     else:
657         duration = 2
658         __p = numpy.array(Y).size
659     #
660     # Précalcul des inversions de B et R
661     # ----------------------------------
662     if selfA._parameters["StoreInternalVariables"] \
663         or selfA._toStore("CostFunctionJ") \
664         or selfA._toStore("CostFunctionJb") \
665         or selfA._toStore("CostFunctionJo") \
666         or selfA._toStore("CurrentOptimum") \
667         or selfA._toStore("APosterioriCovariance"):
668         BI = B.getI()
669         RI = R.getI()
670     #
671     # Initialisation
672     # --------------
673     __n = Xb.size
674     __m = selfA._parameters["NumberOfMembers"]
675     if hasattr(B,"asfullmatrix"): Pn = B.asfullmatrix(__n)
676     else:                         Pn = B
677     if hasattr(R,"asfullmatrix"): Rn = R.asfullmatrix(__p)
678     else:                         Rn = R
679     if hasattr(Q,"asfullmatrix"): Qn = Q.asfullmatrix(__n)
680     else:                         Qn = Q
681     Xn = numpy.asmatrix(numpy.dot( Xb.reshape((__n,1)), numpy.ones((1,__m)) ))
682     #
683     if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
684         selfA.StoredVariables["Analysis"].store( numpy.ravel(Xb) )
685         if selfA._toStore("APosterioriCovariance"):
686             selfA.StoredVariables["APosterioriCovariance"].store( Pn )
687             covarianceXa = Pn
688     #
689     previousJMinimum = numpy.finfo(float).max
690     #
691     # Predimensionnement
692     Xn_predicted = numpy.asmatrix(numpy.zeros((__n,__m)))
693     HX_predicted = numpy.asmatrix(numpy.zeros((__p,__m)))
694     #
695     for step in range(duration-1):
696         if hasattr(Y,"store"):
697             Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
698         else:
699             Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
700         #
701         if U is not None:
702             if hasattr(U,"store") and len(U)>1:
703                 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
704             elif hasattr(U,"store") and len(U)==1:
705                 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
706             else:
707                 Un = numpy.asmatrix(numpy.ravel( U )).T
708         else:
709             Un = None
710         #
711         if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
712             Xn = CovarianceInflation( Xn,
713                 selfA._parameters["InflationType"],
714                 selfA._parameters["InflationFactor"],
715                 )
716         #
717         if selfA._parameters["EstimationOf"] == "State": # Forecast + Q and observation of forecast
718             EMX = M( [(Xn[:,i], Un) for i in range(__m)], argsAsSerie = True )
719             for i in range(__m):
720                 qi = numpy.random.multivariate_normal(numpy.zeros(__n), Qn)
721                 Xn_predicted[:,i] = (numpy.ravel( EMX[i] ) + qi).reshape((__n,-1))
722             HX_predicted = H( [(Xn_predicted[:,i], Un) for i in range(__m)],
723                 argsAsSerie = True,
724                 returnSerieAsArrayMatrix = True )
725             if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
726                 Cm = Cm.reshape(__n,Un.size) # ADAO & check shape
727                 Xn_predicted = Xn_predicted + Cm * Un
728         elif selfA._parameters["EstimationOf"] == "Parameters": # Observation of forecast
729             # --- > Par principe, M = Id, Q = 0
730             Xn_predicted = Xn
731             HX_predicted = H( [(Xn_predicted[:,i], Un) for i in range(__m)],
732                 argsAsSerie = True,
733                 returnSerieAsArrayMatrix = True )
734         #
735         # Mean of forecast and observation of forecast
736         Xfm  = Xn_predicted.mean(axis=1, dtype=mfp).astype('float')
737         Hfm  = HX_predicted.mean(axis=1, dtype=mfp).astype('float')
738         #
739         #--------------------------
740         if VariantM == "KalmanFilterFormula":
741             PfHT, HPfHT = 0., 0.
742             for i in range(__m):
743                 Exfi = Xn_predicted[:,i] - Xfm.reshape((__n,-1))
744                 Eyfi = (HX_predicted[:,i] - Hfm).reshape((__p,1))
745                 PfHT  += Exfi * Eyfi.T
746                 HPfHT += Eyfi * Eyfi.T
747             PfHT  = (1./(__m-1)) * PfHT
748             HPfHT = (1./(__m-1)) * HPfHT
749             K     = PfHT * ( R + HPfHT ).I
750             del PfHT, HPfHT
751             #
752             for i in range(__m):
753                 ri = numpy.random.multivariate_normal(numpy.zeros(__p), Rn)
754                 Xn[:,i] = Xn_predicted[:,i] + K @ (numpy.ravel(Ynpu) + ri - HX_predicted[:,i]).reshape((__p,1))
755         #--------------------------
756         else:
757             raise ValueError("VariantM has to be chosen in the authorized methods list.")
758         #
759         if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
760             Xn = CovarianceInflation( Xn,
761                 selfA._parameters["InflationType"],
762                 selfA._parameters["InflationFactor"],
763                 )
764         #
765         Xa = Xn.mean(axis=1, dtype=mfp).astype('float')
766         #--------------------------
767         #
768         if selfA._parameters["StoreInternalVariables"] \
769             or selfA._toStore("CostFunctionJ") \
770             or selfA._toStore("CostFunctionJb") \
771             or selfA._toStore("CostFunctionJo") \
772             or selfA._toStore("APosterioriCovariance") \
773             or selfA._toStore("InnovationAtCurrentAnalysis") \
774             or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
775             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
776             _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
777             _Innovation = Ynpu - _HXa
778         #
779         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
780         # ---> avec analysis
781         selfA.StoredVariables["Analysis"].store( Xa )
782         if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
783             selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
784         if selfA._toStore("InnovationAtCurrentAnalysis"):
785             selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
786         # ---> avec current state
787         if selfA._parameters["StoreInternalVariables"] \
788             or selfA._toStore("CurrentState"):
789             selfA.StoredVariables["CurrentState"].store( Xn )
790         if selfA._toStore("ForecastState"):
791             selfA.StoredVariables["ForecastState"].store( Xn_predicted )
792         if selfA._toStore("BMA"):
793             selfA.StoredVariables["BMA"].store( Xn_predicted - Xa )
794         if selfA._toStore("InnovationAtCurrentState"):
795             selfA.StoredVariables["InnovationAtCurrentState"].store( - HX_predicted + Ynpu )
796         if selfA._toStore("SimulatedObservationAtCurrentState") \
797             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
798             selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HX_predicted )
799         # ---> autres
800         if selfA._parameters["StoreInternalVariables"] \
801             or selfA._toStore("CostFunctionJ") \
802             or selfA._toStore("CostFunctionJb") \
803             or selfA._toStore("CostFunctionJo") \
804             or selfA._toStore("CurrentOptimum") \
805             or selfA._toStore("APosterioriCovariance"):
806             Jb  = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
807             Jo  = float( 0.5 * _Innovation.T * RI * _Innovation )
808             J   = Jb + Jo
809             selfA.StoredVariables["CostFunctionJb"].store( Jb )
810             selfA.StoredVariables["CostFunctionJo"].store( Jo )
811             selfA.StoredVariables["CostFunctionJ" ].store( J )
812             #
813             if selfA._toStore("IndexOfOptimum") \
814                 or selfA._toStore("CurrentOptimum") \
815                 or selfA._toStore("CostFunctionJAtCurrentOptimum") \
816                 or selfA._toStore("CostFunctionJbAtCurrentOptimum") \
817                 or selfA._toStore("CostFunctionJoAtCurrentOptimum") \
818                 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
819                 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
820             if selfA._toStore("IndexOfOptimum"):
821                 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
822             if selfA._toStore("CurrentOptimum"):
823                 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["Analysis"][IndexMin] )
824             if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
825                 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"][IndexMin] )
826             if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
827                 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
828             if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
829                 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
830             if selfA._toStore("CostFunctionJAtCurrentOptimum"):
831                 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
832         if selfA._toStore("APosterioriCovariance"):
833             Eai = (1/numpy.sqrt(__m-1)) * (Xn - Xa.reshape((__n,-1))) # Anomalies
834             Pn = Eai @ Eai.T
835             Pn = 0.5 * (Pn + Pn.T)
836             selfA.StoredVariables["APosterioriCovariance"].store( Pn )
837         if selfA._parameters["EstimationOf"] == "Parameters" \
838             and J < previousJMinimum:
839             previousJMinimum    = J
840             XaMin               = Xa
841             if selfA._toStore("APosterioriCovariance"):
842                 covarianceXaMin = Pn
843     #
844     # Stockage final supplémentaire de l'optimum en estimation de paramètres
845     # ----------------------------------------------------------------------
846     if selfA._parameters["EstimationOf"] == "Parameters":
847         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
848         selfA.StoredVariables["Analysis"].store( XaMin )
849         if selfA._toStore("APosterioriCovariance"):
850             selfA.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
851         if selfA._toStore("BMA"):
852             selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
853     #
854     return 0
855
856 # ==============================================================================
857 def etkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, VariantM="KalmanFilterFormula"):
858     """
859     Ensemble-Transform EnKF (ETKF or Deterministic EnKF: Bishop 2001, Hunt 2007)
860
861     selfA est identique au "self" d'algorithme appelant et contient les
862     valeurs.
863     """
864     if selfA._parameters["EstimationOf"] == "Parameters":
865         selfA._parameters["StoreInternalVariables"] = True
866     #
867     # Opérateurs
868     # ----------
869     H = HO["Direct"].appliedControledFormTo
870     #
871     if selfA._parameters["EstimationOf"] == "State":
872         M = EM["Direct"].appliedControledFormTo
873     #
874     if CM is not None and "Tangent" in CM and U is not None:
875         Cm = CM["Tangent"].asMatrix(Xb)
876     else:
877         Cm = None
878     #
879     # Nombre de pas identique au nombre de pas d'observations
880     # -------------------------------------------------------
881     if hasattr(Y,"stepnumber"):
882         duration = Y.stepnumber()
883         __p = numpy.cumprod(Y.shape())[-1]
884     else:
885         duration = 2
886         __p = numpy.array(Y).size
887     #
888     # Précalcul des inversions de B et R
889     # ----------------------------------
890     if selfA._parameters["StoreInternalVariables"] \
891         or selfA._toStore("CostFunctionJ") \
892         or selfA._toStore("CostFunctionJb") \
893         or selfA._toStore("CostFunctionJo") \
894         or selfA._toStore("CurrentOptimum") \
895         or selfA._toStore("APosterioriCovariance"):
896         BI = B.getI()
897         RI = R.getI()
898     elif VariantM != "KalmanFilterFormula":
899         RI = R.getI()
900     if VariantM == "KalmanFilterFormula":
901         RIdemi = R.choleskyI()
902     #
903     # Initialisation
904     # --------------
905     __n = Xb.size
906     __m = selfA._parameters["NumberOfMembers"]
907     if hasattr(B,"asfullmatrix"): Pn = B.asfullmatrix(__n)
908     else:                         Pn = B
909     if hasattr(R,"asfullmatrix"): Rn = R.asfullmatrix(__p)
910     else:                         Rn = R
911     if hasattr(Q,"asfullmatrix"): Qn = Q.asfullmatrix(__n)
912     else:                         Qn = Q
913     Xn = numpy.asmatrix(numpy.dot( Xb.reshape((__n,1)), numpy.ones((1,__m)) ))
914     #
915     if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
916         selfA.StoredVariables["Analysis"].store( numpy.ravel(Xb) )
917         if selfA._toStore("APosterioriCovariance"):
918             selfA.StoredVariables["APosterioriCovariance"].store( Pn )
919             covarianceXa = Pn
920     #
921     previousJMinimum = numpy.finfo(float).max
922     #
923     # Predimensionnement
924     Xn_predicted = numpy.asmatrix(numpy.zeros((__n,__m)))
925     #
926     for step in range(duration-1):
927         if hasattr(Y,"store"):
928             Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
929         else:
930             Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
931         #
932         if U is not None:
933             if hasattr(U,"store") and len(U)>1:
934                 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
935             elif hasattr(U,"store") and len(U)==1:
936                 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
937             else:
938                 Un = numpy.asmatrix(numpy.ravel( U )).T
939         else:
940             Un = None
941         #
942         if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
943             Xn = CovarianceInflation( Xn,
944                 selfA._parameters["InflationType"],
945                 selfA._parameters["InflationFactor"],
946                 )
947         #
948         if selfA._parameters["EstimationOf"] == "State": # Forecast + Q and observation of forecast
949             EMX = M( [(Xn[:,i], Un) for i in range(__m)], argsAsSerie = True )
950             for i in range(__m):
951                 qi = numpy.random.multivariate_normal(numpy.zeros(__n), Qn)
952                 Xn_predicted[:,i] = (numpy.ravel( EMX[i] ) + qi).reshape((__n,-1))
953             HX_predicted = H( [(Xn_predicted[:,i], Un) for i in range(__m)],
954                 argsAsSerie = True,
955                 returnSerieAsArrayMatrix = True )
956             if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
957                 Cm = Cm.reshape(__n,Un.size) # ADAO & check shape
958                 Xn_predicted = Xn_predicted + Cm * Un
959         elif selfA._parameters["EstimationOf"] == "Parameters": # Observation of forecast
960             # --- > Par principe, M = Id, Q = 0
961             Xn_predicted = Xn
962             HX_predicted = H( [(Xn_predicted[:,i], Un) for i in range(__m)],
963                 argsAsSerie = True,
964                 returnSerieAsArrayMatrix = True )
965         #
966         # Mean of forecast and observation of forecast
967         Xfm  = Xn_predicted.mean(axis=1, dtype=mfp).astype('float')
968         Hfm  = HX_predicted.mean(axis=1, dtype=mfp).astype('float')
969         #
970         # Anomalies
971         EaX   = numpy.matrix(Xn_predicted - Xfm.reshape((__n,-1)))
972         EaHX  = numpy.matrix(HX_predicted - Hfm.reshape((__p,-1)))
973         #
974         #--------------------------
975         if VariantM == "KalmanFilterFormula":
976             EaX    = EaX / numpy.sqrt(__m-1)
977             mS    = RIdemi * EaHX / numpy.sqrt(__m-1)
978             delta = RIdemi * ( Ynpu.reshape((__p,-1)) - Hfm.reshape((__p,-1)) )
979             mT    = numpy.linalg.inv( numpy.eye(__m) + mS.T @ mS )
980             vw    = mT @ mS.transpose() @ delta
981             #
982             Tdemi = numpy.real(scipy.linalg.sqrtm(mT))
983             mU    = numpy.eye(__m)
984             #
985             Xn = Xfm.reshape((__n,-1)) + EaX @ ( vw.reshape((__m,-1)) + numpy.sqrt(__m-1) * Tdemi @ mU )
986         #--------------------------
987         elif VariantM == "Variational":
988             HXfm = H((Xfm, Un)) # Eventuellement Hfm
989             def CostFunction(w):
990                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
991                 _Jo = 0.5 * _A.T * RI * _A
992                 _Jb = 0.5 * (__m-1) * w.T @ w
993                 _J  = _Jo + _Jb
994                 return float(_J)
995             def GradientOfCostFunction(w):
996                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
997                 _GardJo = - EaHX.T * RI * _A
998                 _GradJb = (__m-1) * w.reshape((__m,1))
999                 _GradJ  = _GardJo + _GradJb
1000                 return numpy.ravel(_GradJ)
1001             vw = scipy.optimize.fmin_cg(
1002                 f           = CostFunction,
1003                 x0          = numpy.zeros(__m),
1004                 fprime      = GradientOfCostFunction,
1005                 args        = (),
1006                 disp        = False,
1007                 )
1008             #
1009             Hto = EaHX.T * RI * EaHX
1010             Htb = (__m-1) * numpy.eye(__m)
1011             Hta = Hto + Htb
1012             #
1013             Pta = numpy.linalg.inv( Hta )
1014             EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1015             #
1016             Xn = Xfm.reshape((__n,-1)) + EaX @ (vw.reshape((__m,-1)) + EWa)
1017         #--------------------------
1018         elif VariantM == "FiniteSize11": # Jauge Boc2011
1019             HXfm = H((Xfm, Un)) # Eventuellement Hfm
1020             def CostFunction(w):
1021                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1022                 _Jo = 0.5 * _A.T * RI * _A
1023                 _Jb = 0.5 * __m * math.log(1 + 1/__m + w.T @ w)
1024                 _J  = _Jo + _Jb
1025                 return float(_J)
1026             def GradientOfCostFunction(w):
1027                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1028                 _GardJo = - EaHX.T * RI * _A
1029                 _GradJb = __m * w.reshape((__m,1)) / (1 + 1/__m + w.T @ w)
1030                 _GradJ  = _GardJo + _GradJb
1031                 return numpy.ravel(_GradJ)
1032             vw = scipy.optimize.fmin_cg(
1033                 f           = CostFunction,
1034                 x0          = numpy.zeros(__m),
1035                 fprime      = GradientOfCostFunction,
1036                 args        = (),
1037                 disp        = False,
1038                 )
1039             #
1040             Hto = EaHX.T * RI * EaHX
1041             Htb = __m * \
1042                 ( (1 + 1/__m + vw.T @ vw) * numpy.eye(__m) - 2 * vw @ vw.T ) \
1043                 / (1 + 1/__m + vw.T @ vw)**2
1044             Hta = Hto + Htb
1045             #
1046             Pta = numpy.linalg.inv( Hta )
1047             EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1048             #
1049             Xn = Xfm.reshape((__n,-1)) + EaX @ (vw.reshape((__m,-1)) + EWa)
1050         #--------------------------
1051         elif VariantM == "FiniteSize15": # Jauge Boc2015
1052             HXfm = H((Xfm, Un)) # Eventuellement Hfm
1053             def CostFunction(w):
1054                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1055                 _Jo = 0.5 * _A.T * RI * _A
1056                 _Jb = 0.5 * (__m+1) * math.log(1 + 1/__m + w.T @ w)
1057                 _J  = _Jo + _Jb
1058                 return float(_J)
1059             def GradientOfCostFunction(w):
1060                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1061                 _GardJo = - EaHX.T * RI * _A
1062                 _GradJb = (__m+1) * w.reshape((__m,1)) / (1 + 1/__m + w.T @ w)
1063                 _GradJ  = _GardJo + _GradJb
1064                 return numpy.ravel(_GradJ)
1065             vw = scipy.optimize.fmin_cg(
1066                 f           = CostFunction,
1067                 x0          = numpy.zeros(__m),
1068                 fprime      = GradientOfCostFunction,
1069                 args        = (),
1070                 disp        = False,
1071                 )
1072             #
1073             Hto = EaHX.T * RI * EaHX
1074             Htb = (__m+1) * \
1075                 ( (1 + 1/__m + vw.T @ vw) * numpy.eye(__m) - 2 * vw @ vw.T ) \
1076                 / (1 + 1/__m + vw.T @ vw)**2
1077             Hta = Hto + Htb
1078             #
1079             Pta = numpy.linalg.inv( Hta )
1080             EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1081             #
1082             Xn = Xfm.reshape((__n,-1)) + EaX @ (vw.reshape((__m,-1)) + EWa)
1083         #--------------------------
1084         elif VariantM == "FiniteSize16": # Jauge Boc2016
1085             HXfm = H((Xfm, Un)) # Eventuellement Hfm
1086             def CostFunction(w):
1087                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1088                 _Jo = 0.5 * _A.T * RI * _A
1089                 _Jb = 0.5 * (__m+1) * math.log(1 + 1/__m + w.T @ w / (__m-1))
1090                 _J  = _Jo + _Jb
1091                 return float(_J)
1092             def GradientOfCostFunction(w):
1093                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1094                 _GardJo = - EaHX.T * RI * _A
1095                 _GradJb = ((__m+1) / (__m-1)) * w.reshape((__m,1)) / (1 + 1/__m + w.T @ w / (__m-1))
1096                 _GradJ  = _GardJo + _GradJb
1097                 return numpy.ravel(_GradJ)
1098             vw = scipy.optimize.fmin_cg(
1099                 f           = CostFunction,
1100                 x0          = numpy.zeros(__m),
1101                 fprime      = GradientOfCostFunction,
1102                 args        = (),
1103                 disp        = False,
1104                 )
1105             #
1106             Hto = EaHX.T * RI * EaHX
1107             Htb = ((__m+1) / (__m-1)) * \
1108                 ( (1 + 1/__m + vw.T @ vw / (__m-1)) * numpy.eye(__m) - 2 * vw @ vw.T / (__m-1) ) \
1109                 / (1 + 1/__m + vw.T @ vw / (__m-1))**2
1110             Hta = Hto + Htb
1111             #
1112             Pta = numpy.linalg.inv( Hta )
1113             EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1114             #
1115             Xn = Xfm.reshape((__n,-1)) + EaX @ (vw.reshape((__m,-1)) + EWa)
1116         #--------------------------
1117         else:
1118             raise ValueError("VariantM has to be chosen in the authorized methods list.")
1119         #
1120         if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
1121             Xn = CovarianceInflation( Xn,
1122                 selfA._parameters["InflationType"],
1123                 selfA._parameters["InflationFactor"],
1124                 )
1125         #
1126         Xa = Xn.mean(axis=1, dtype=mfp).astype('float')
1127         #--------------------------
1128         #
1129         if selfA._parameters["StoreInternalVariables"] \
1130             or selfA._toStore("CostFunctionJ") \
1131             or selfA._toStore("CostFunctionJb") \
1132             or selfA._toStore("CostFunctionJo") \
1133             or selfA._toStore("APosterioriCovariance") \
1134             or selfA._toStore("InnovationAtCurrentAnalysis") \
1135             or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
1136             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1137             _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
1138             _Innovation = Ynpu - _HXa
1139         #
1140         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1141         # ---> avec analysis
1142         selfA.StoredVariables["Analysis"].store( Xa )
1143         if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
1144             selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
1145         if selfA._toStore("InnovationAtCurrentAnalysis"):
1146             selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
1147         # ---> avec current state
1148         if selfA._parameters["StoreInternalVariables"] \
1149             or selfA._toStore("CurrentState"):
1150             selfA.StoredVariables["CurrentState"].store( Xn )
1151         if selfA._toStore("ForecastState"):
1152             selfA.StoredVariables["ForecastState"].store( Xn_predicted )
1153         if selfA._toStore("BMA"):
1154             selfA.StoredVariables["BMA"].store( Xn_predicted - Xa )
1155         if selfA._toStore("InnovationAtCurrentState"):
1156             selfA.StoredVariables["InnovationAtCurrentState"].store( - HX_predicted + Ynpu )
1157         if selfA._toStore("SimulatedObservationAtCurrentState") \
1158             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1159             selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HX_predicted )
1160         # ---> autres
1161         if selfA._parameters["StoreInternalVariables"] \
1162             or selfA._toStore("CostFunctionJ") \
1163             or selfA._toStore("CostFunctionJb") \
1164             or selfA._toStore("CostFunctionJo") \
1165             or selfA._toStore("CurrentOptimum") \
1166             or selfA._toStore("APosterioriCovariance"):
1167             Jb  = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
1168             Jo  = float( 0.5 * _Innovation.T * RI * _Innovation )
1169             J   = Jb + Jo
1170             selfA.StoredVariables["CostFunctionJb"].store( Jb )
1171             selfA.StoredVariables["CostFunctionJo"].store( Jo )
1172             selfA.StoredVariables["CostFunctionJ" ].store( J )
1173             #
1174             if selfA._toStore("IndexOfOptimum") \
1175                 or selfA._toStore("CurrentOptimum") \
1176                 or selfA._toStore("CostFunctionJAtCurrentOptimum") \
1177                 or selfA._toStore("CostFunctionJbAtCurrentOptimum") \
1178                 or selfA._toStore("CostFunctionJoAtCurrentOptimum") \
1179                 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1180                 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
1181             if selfA._toStore("IndexOfOptimum"):
1182                 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
1183             if selfA._toStore("CurrentOptimum"):
1184                 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["Analysis"][IndexMin] )
1185             if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1186                 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"][IndexMin] )
1187             if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
1188                 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
1189             if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
1190                 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
1191             if selfA._toStore("CostFunctionJAtCurrentOptimum"):
1192                 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
1193         if selfA._toStore("APosterioriCovariance"):
1194             Eai = (1/numpy.sqrt(__m-1)) * (Xn - Xa.reshape((__n,-1))) # Anomalies
1195             Pn = Eai @ Eai.T
1196             Pn = 0.5 * (Pn + Pn.T)
1197             selfA.StoredVariables["APosterioriCovariance"].store( Pn )
1198         if selfA._parameters["EstimationOf"] == "Parameters" \
1199             and J < previousJMinimum:
1200             previousJMinimum    = J
1201             XaMin               = Xa
1202             if selfA._toStore("APosterioriCovariance"):
1203                 covarianceXaMin = Pn
1204     #
1205     # Stockage final supplémentaire de l'optimum en estimation de paramètres
1206     # ----------------------------------------------------------------------
1207     if selfA._parameters["EstimationOf"] == "Parameters":
1208         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1209         selfA.StoredVariables["Analysis"].store( XaMin )
1210         if selfA._toStore("APosterioriCovariance"):
1211             selfA.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
1212         if selfA._toStore("BMA"):
1213             selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
1214     #
1215     return 0
1216
1217 # ==============================================================================
1218 def mlef(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, VariantM="MLEF13",
1219     BnotT=False, _epsilon=1.e-3, _e=1.e-7, _jmax=15000):
1220     """
1221     Maximum Likelihood Ensemble Filter (EnKF/MLEF Zupanski 2005, Bocquet 2013)
1222
1223     selfA est identique au "self" d'algorithme appelant et contient les
1224     valeurs.
1225     """
1226     if selfA._parameters["EstimationOf"] == "Parameters":
1227         selfA._parameters["StoreInternalVariables"] = True
1228     #
1229     # Opérateurs
1230     # ----------
1231     H = HO["Direct"].appliedControledFormTo
1232     #
1233     if selfA._parameters["EstimationOf"] == "State":
1234         M = EM["Direct"].appliedControledFormTo
1235     #
1236     if CM is not None and "Tangent" in CM and U is not None:
1237         Cm = CM["Tangent"].asMatrix(Xb)
1238     else:
1239         Cm = None
1240     #
1241     # Nombre de pas identique au nombre de pas d'observations
1242     # -------------------------------------------------------
1243     if hasattr(Y,"stepnumber"):
1244         duration = Y.stepnumber()
1245         __p = numpy.cumprod(Y.shape())[-1]
1246     else:
1247         duration = 2
1248         __p = numpy.array(Y).size
1249     #
1250     # Précalcul des inversions de B et R
1251     # ----------------------------------
1252     if selfA._parameters["StoreInternalVariables"] \
1253         or selfA._toStore("CostFunctionJ") \
1254         or selfA._toStore("CostFunctionJb") \
1255         or selfA._toStore("CostFunctionJo") \
1256         or selfA._toStore("CurrentOptimum") \
1257         or selfA._toStore("APosterioriCovariance"):
1258         BI = B.getI()
1259     RI = R.getI()
1260     #
1261     # Initialisation
1262     # --------------
1263     __n = Xb.size
1264     __m = selfA._parameters["NumberOfMembers"]
1265     if hasattr(B,"asfullmatrix"): Pn = B.asfullmatrix(__n)
1266     else:                         Pn = B
1267     if hasattr(R,"asfullmatrix"): Rn = R.asfullmatrix(__p)
1268     else:                         Rn = R
1269     if hasattr(Q,"asfullmatrix"): Qn = Q.asfullmatrix(__n)
1270     else:                         Qn = Q
1271     Xn = BackgroundEnsembleGeneration( Xb, None, __m )
1272     #
1273     if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
1274         selfA.StoredVariables["Analysis"].store( numpy.ravel(Xb) )
1275         if selfA._toStore("APosterioriCovariance"):
1276             selfA.StoredVariables["APosterioriCovariance"].store( Pn )
1277             covarianceXa = Pn
1278     #
1279     previousJMinimum = numpy.finfo(float).max
1280     #
1281     Xn_predicted = numpy.zeros((__n,__m))
1282     for step in range(duration-1):
1283         if hasattr(Y,"store"):
1284             Ynpu = numpy.ravel( Y[step+1] )[:,None]
1285         else:
1286             Ynpu = numpy.ravel( Y )[:,None]
1287         #
1288         if U is not None:
1289             if hasattr(U,"store") and len(U)>1:
1290                 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
1291             elif hasattr(U,"store") and len(U)==1:
1292                 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
1293             else:
1294                 Un = numpy.asmatrix(numpy.ravel( U )).T
1295         else:
1296             Un = None
1297         #
1298         if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
1299             Xn = CovarianceInflation( Xn,
1300                 selfA._parameters["InflationType"],
1301                 selfA._parameters["InflationFactor"],
1302                 )
1303         #
1304         if selfA._parameters["EstimationOf"] == "State": # Forecast + Q and observation of forecast
1305             EMX = M( [(Xn[:,i,numpy.newaxis], Un) for i in range(__m)], argsAsSerie = True )
1306             for i in range(__m):
1307                 qi = numpy.random.multivariate_normal(numpy.zeros(__n), Qn)
1308                 Xn_predicted[:,i] = numpy.ravel( EMX[i] ) + qi
1309             if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
1310                 Cm = Cm.reshape(__n,Un.size) # ADAO & check shape
1311                 Xn_predicted = Xn_predicted + Cm * Un
1312         elif selfA._parameters["EstimationOf"] == "Parameters": # Observation of forecast
1313             # --- > Par principe, M = Id, Q = 0
1314             Xn_predicted = Xn
1315         #
1316         #--------------------------
1317         if VariantM == "MLEF13":
1318             Xfm = numpy.asarray(Xn_predicted.mean(axis=1, dtype=mfp).astype('float'))
1319             EaX = numpy.asarray((Xn_predicted - Xfm.reshape((__n,-1))) / numpy.sqrt(__m-1))
1320             Ua  = numpy.eye(__m)
1321             __j = 0
1322             Deltaw = 1
1323             if not BnotT:
1324                 Ta  = numpy.eye(__m)
1325             vw  = numpy.zeros(__m)
1326             while numpy.linalg.norm(Deltaw) >= _e and __j <= _jmax:
1327                 vx1 = numpy.ravel(Xfm) + EaX @ vw
1328                 #
1329                 if BnotT:
1330                     E1 = vx1.reshape((__n,-1)) + _epsilon * EaX
1331                 else:
1332                     E1 = vx1.reshape((__n,-1)) + numpy.sqrt(__m-1) * EaX @ Ta
1333                 #
1334                 HE2 = H( [(E1[:,i,numpy.newaxis], Un) for i in range(__m)],
1335                     argsAsSerie = True,
1336                     returnSerieAsArrayMatrix = True )
1337                 vy2 = HE2.mean(axis=1, dtype=mfp).astype('float').reshape((__p,-1))
1338                 #
1339                 if BnotT:
1340                     EaY = (HE2 - vy2) / _epsilon
1341                 else:
1342                     EaY = ( (HE2 - vy2) @ numpy.linalg.inv(Ta) ) / numpy.sqrt(__m-1)
1343                 #
1344                 GradJ = numpy.ravel(vw[:,None] - EaY.transpose() @ (RI * ( Ynpu - vy2 )))
1345                 mH = numpy.eye(__m) + EaY.transpose() @ (RI * EaY)
1346                 Deltaw = - numpy.linalg.solve(mH,GradJ)
1347                 #
1348                 vw = vw + Deltaw
1349                 #
1350                 if not BnotT:
1351                     Ta = numpy.real(scipy.linalg.sqrtm(numpy.linalg.inv( mH )))
1352                 #
1353                 __j = __j + 1
1354             #
1355             if BnotT:
1356                 Ta = numpy.real(scipy.linalg.sqrtm(numpy.linalg.inv( mH )))
1357             #
1358             Xn = vx1.reshape((__n,-1)) + numpy.sqrt(__m-1) * EaX @ Ta @ Ua
1359         #--------------------------
1360         else:
1361             raise ValueError("VariantM has to be chosen in the authorized methods list.")
1362         #
1363         if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
1364             Xn = CovarianceInflation( Xn,
1365                 selfA._parameters["InflationType"],
1366                 selfA._parameters["InflationFactor"],
1367                 )
1368         #
1369         Xa = Xn.mean(axis=1, dtype=mfp).astype('float').reshape((__n,-1))
1370         #--------------------------
1371         #
1372         if selfA._parameters["StoreInternalVariables"] \
1373             or selfA._toStore("CostFunctionJ") \
1374             or selfA._toStore("CostFunctionJb") \
1375             or selfA._toStore("CostFunctionJo") \
1376             or selfA._toStore("APosterioriCovariance") \
1377             or selfA._toStore("InnovationAtCurrentAnalysis") \
1378             or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
1379             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1380             _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
1381             _Innovation = Ynpu - _HXa
1382         #
1383         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1384         # ---> avec analysis
1385         selfA.StoredVariables["Analysis"].store( Xa )
1386         if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
1387             selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
1388         if selfA._toStore("InnovationAtCurrentAnalysis"):
1389             selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
1390         # ---> avec current state
1391         if selfA._parameters["StoreInternalVariables"] \
1392             or selfA._toStore("CurrentState"):
1393             selfA.StoredVariables["CurrentState"].store( Xn )
1394         if selfA._toStore("ForecastState"):
1395             selfA.StoredVariables["ForecastState"].store( Xn_predicted )
1396         if selfA._toStore("BMA"):
1397             selfA.StoredVariables["BMA"].store( Xn_predicted - Xa )
1398         #~ if selfA._toStore("InnovationAtCurrentState"):
1399             #~ selfA.StoredVariables["InnovationAtCurrentState"].store( - HX_predicted + Ynpu )
1400         #~ if selfA._toStore("SimulatedObservationAtCurrentState") \
1401             #~ or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1402             #~ selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HX_predicted )
1403         # ---> autres
1404         if selfA._parameters["StoreInternalVariables"] \
1405             or selfA._toStore("CostFunctionJ") \
1406             or selfA._toStore("CostFunctionJb") \
1407             or selfA._toStore("CostFunctionJo") \
1408             or selfA._toStore("CurrentOptimum") \
1409             or selfA._toStore("APosterioriCovariance"):
1410             Jb  = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
1411             Jo  = float( 0.5 * _Innovation.T * RI * _Innovation )
1412             J   = Jb + Jo
1413             selfA.StoredVariables["CostFunctionJb"].store( Jb )
1414             selfA.StoredVariables["CostFunctionJo"].store( Jo )
1415             selfA.StoredVariables["CostFunctionJ" ].store( J )
1416             #
1417             if selfA._toStore("IndexOfOptimum") \
1418                 or selfA._toStore("CurrentOptimum") \
1419                 or selfA._toStore("CostFunctionJAtCurrentOptimum") \
1420                 or selfA._toStore("CostFunctionJbAtCurrentOptimum") \
1421                 or selfA._toStore("CostFunctionJoAtCurrentOptimum") \
1422                 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1423                 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
1424             if selfA._toStore("IndexOfOptimum"):
1425                 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
1426             if selfA._toStore("CurrentOptimum"):
1427                 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["Analysis"][IndexMin] )
1428             if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1429                 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"][IndexMin] )
1430             if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
1431                 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
1432             if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
1433                 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
1434             if selfA._toStore("CostFunctionJAtCurrentOptimum"):
1435                 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
1436         if selfA._toStore("APosterioriCovariance"):
1437             Eai = numpy.asarray((Xn - Xa.reshape((__n,-1))) / numpy.sqrt(__m-1)) # Anomalies
1438             Pn = Eai @ Eai.T
1439             Pn = 0.5 * (Pn + Pn.T)
1440             selfA.StoredVariables["APosterioriCovariance"].store( Pn )
1441         if selfA._parameters["EstimationOf"] == "Parameters" \
1442             and J < previousJMinimum:
1443             previousJMinimum    = J
1444             XaMin               = Xa
1445             if selfA._toStore("APosterioriCovariance"):
1446                 covarianceXaMin = Pn
1447     #
1448     # Stockage final supplémentaire de l'optimum en estimation de paramètres
1449     # ----------------------------------------------------------------------
1450     if selfA._parameters["EstimationOf"] == "Parameters":
1451         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1452         selfA.StoredVariables["Analysis"].store( XaMin )
1453         if selfA._toStore("APosterioriCovariance"):
1454             selfA.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
1455         if selfA._toStore("BMA"):
1456             selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
1457     #
1458     return 0
1459
1460 # ==============================================================================
1461 if __name__ == "__main__":
1462     print('\n AUTODIAGNOSTIC\n')