Salome HOME
Minor improvements for internal method 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):
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         PfHT, HPfHT = 0., 0.
740         for i in range(__m):
741             Exfi = Xn_predicted[:,i] - Xfm.reshape((__n,-1))
742             Eyfi = (HX_predicted[:,i] - Hfm).reshape((__p,1))
743             PfHT  += Exfi * Eyfi.T
744             HPfHT += Eyfi * Eyfi.T
745         PfHT  = (1./(__m-1)) * PfHT
746         HPfHT = (1./(__m-1)) * HPfHT
747         K     = PfHT * ( R + HPfHT ).I
748         del PfHT, HPfHT
749         #
750         for i in range(__m):
751             ri = numpy.random.multivariate_normal(numpy.zeros(__p), Rn)
752             Xn[:,i] = Xn_predicted[:,i] + K @ (numpy.ravel(Ynpu) + ri - HX_predicted[:,i]).reshape((__p,1))
753         #
754         if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
755             Xn = CovarianceInflation( Xn,
756                 selfA._parameters["InflationType"],
757                 selfA._parameters["InflationFactor"],
758                 )
759         #
760         Xa = Xn.mean(axis=1, dtype=mfp).astype('float')
761         #--------------------------
762         #
763         if selfA._parameters["StoreInternalVariables"] \
764             or selfA._toStore("CostFunctionJ") \
765             or selfA._toStore("CostFunctionJb") \
766             or selfA._toStore("CostFunctionJo") \
767             or selfA._toStore("APosterioriCovariance") \
768             or selfA._toStore("InnovationAtCurrentAnalysis") \
769             or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
770             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
771             _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
772             _Innovation = Ynpu - _HXa
773         #
774         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
775         # ---> avec analysis
776         selfA.StoredVariables["Analysis"].store( Xa )
777         if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
778             selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
779         if selfA._toStore("InnovationAtCurrentAnalysis"):
780             selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
781         # ---> avec current state
782         if selfA._parameters["StoreInternalVariables"] \
783             or selfA._toStore("CurrentState"):
784             selfA.StoredVariables["CurrentState"].store( Xn )
785         if selfA._toStore("ForecastState"):
786             selfA.StoredVariables["ForecastState"].store( Xn_predicted )
787         if selfA._toStore("BMA"):
788             selfA.StoredVariables["BMA"].store( Xn_predicted - Xa )
789         if selfA._toStore("InnovationAtCurrentState"):
790             selfA.StoredVariables["InnovationAtCurrentState"].store( - HX_predicted + Ynpu )
791         if selfA._toStore("SimulatedObservationAtCurrentState") \
792             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
793             selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HX_predicted )
794         # ---> autres
795         if selfA._parameters["StoreInternalVariables"] \
796             or selfA._toStore("CostFunctionJ") \
797             or selfA._toStore("CostFunctionJb") \
798             or selfA._toStore("CostFunctionJo") \
799             or selfA._toStore("CurrentOptimum") \
800             or selfA._toStore("APosterioriCovariance"):
801             Jb  = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
802             Jo  = float( 0.5 * _Innovation.T * RI * _Innovation )
803             J   = Jb + Jo
804             selfA.StoredVariables["CostFunctionJb"].store( Jb )
805             selfA.StoredVariables["CostFunctionJo"].store( Jo )
806             selfA.StoredVariables["CostFunctionJ" ].store( J )
807             #
808             if selfA._toStore("IndexOfOptimum") \
809                 or selfA._toStore("CurrentOptimum") \
810                 or selfA._toStore("CostFunctionJAtCurrentOptimum") \
811                 or selfA._toStore("CostFunctionJbAtCurrentOptimum") \
812                 or selfA._toStore("CostFunctionJoAtCurrentOptimum") \
813                 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
814                 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
815             if selfA._toStore("IndexOfOptimum"):
816                 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
817             if selfA._toStore("CurrentOptimum"):
818                 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["Analysis"][IndexMin] )
819             if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
820                 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"][IndexMin] )
821             if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
822                 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
823             if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
824                 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
825             if selfA._toStore("CostFunctionJAtCurrentOptimum"):
826                 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
827         if selfA._toStore("APosterioriCovariance"):
828             Eai = (1/numpy.sqrt(__m-1)) * (Xn - Xa.reshape((__n,-1))) # Anomalies
829             Pn = Eai @ Eai.T
830             Pn = 0.5 * (Pn + Pn.T)
831             selfA.StoredVariables["APosterioriCovariance"].store( Pn )
832         if selfA._parameters["EstimationOf"] == "Parameters" \
833             and J < previousJMinimum:
834             previousJMinimum    = J
835             XaMin               = Xa
836             if selfA._toStore("APosterioriCovariance"):
837                 covarianceXaMin = Pn
838     #
839     # Stockage final supplémentaire de l'optimum en estimation de paramètres
840     # ----------------------------------------------------------------------
841     if selfA._parameters["EstimationOf"] == "Parameters":
842         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
843         selfA.StoredVariables["Analysis"].store( XaMin )
844         if selfA._toStore("APosterioriCovariance"):
845             selfA.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
846         if selfA._toStore("BMA"):
847             selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
848     #
849     return 0
850
851 # ==============================================================================
852 def etkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, VariantM="KalmanFilterFormula"):
853     """
854     Ensemble-Transform EnKF (ETKF or Deterministic EnKF: Bishop 2001, Hunt 2007)
855
856     selfA est identique au "self" d'algorithme appelant et contient les
857     valeurs.
858     """
859     if selfA._parameters["EstimationOf"] == "Parameters":
860         selfA._parameters["StoreInternalVariables"] = True
861     #
862     # Opérateurs
863     # ----------
864     H = HO["Direct"].appliedControledFormTo
865     #
866     if selfA._parameters["EstimationOf"] == "State":
867         M = EM["Direct"].appliedControledFormTo
868     #
869     if CM is not None and "Tangent" in CM and U is not None:
870         Cm = CM["Tangent"].asMatrix(Xb)
871     else:
872         Cm = None
873     #
874     # Nombre de pas identique au nombre de pas d'observations
875     # -------------------------------------------------------
876     if hasattr(Y,"stepnumber"):
877         duration = Y.stepnumber()
878         __p = numpy.cumprod(Y.shape())[-1]
879     else:
880         duration = 2
881         __p = numpy.array(Y).size
882     #
883     # Précalcul des inversions de B et R
884     # ----------------------------------
885     if selfA._parameters["StoreInternalVariables"] \
886         or selfA._toStore("CostFunctionJ") \
887         or selfA._toStore("CostFunctionJb") \
888         or selfA._toStore("CostFunctionJo") \
889         or selfA._toStore("CurrentOptimum") \
890         or selfA._toStore("APosterioriCovariance"):
891         BI = B.getI()
892         RI = R.getI()
893     elif VariantM != "KalmanFilterFormula":
894         RI = R.getI()
895     if VariantM == "KalmanFilterFormula":
896         RIdemi = R.choleskyI()
897     #
898     # Initialisation
899     # --------------
900     __n = Xb.size
901     __m = selfA._parameters["NumberOfMembers"]
902     if hasattr(B,"asfullmatrix"): Pn = B.asfullmatrix(__n)
903     else:                         Pn = B
904     if hasattr(R,"asfullmatrix"): Rn = R.asfullmatrix(__p)
905     else:                         Rn = R
906     if hasattr(Q,"asfullmatrix"): Qn = Q.asfullmatrix(__n)
907     else:                         Qn = Q
908     Xn = numpy.asmatrix(numpy.dot( Xb.reshape((__n,1)), numpy.ones((1,__m)) ))
909     #
910     if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
911         selfA.StoredVariables["Analysis"].store( numpy.ravel(Xb) )
912         if selfA._toStore("APosterioriCovariance"):
913             selfA.StoredVariables["APosterioriCovariance"].store( Pn )
914             covarianceXa = Pn
915     #
916     previousJMinimum = numpy.finfo(float).max
917     #
918     # Predimensionnement
919     Xn_predicted = numpy.asmatrix(numpy.zeros((__n,__m)))
920     #
921     for step in range(duration-1):
922         if hasattr(Y,"store"):
923             Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
924         else:
925             Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
926         #
927         if U is not None:
928             if hasattr(U,"store") and len(U)>1:
929                 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
930             elif hasattr(U,"store") and len(U)==1:
931                 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
932             else:
933                 Un = numpy.asmatrix(numpy.ravel( U )).T
934         else:
935             Un = None
936         #
937         if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
938             Xn = CovarianceInflation( Xn,
939                 selfA._parameters["InflationType"],
940                 selfA._parameters["InflationFactor"],
941                 )
942         #
943         if selfA._parameters["EstimationOf"] == "State": # Forecast + Q and observation of forecast
944             EMX = M( [(Xn[:,i], Un) for i in range(__m)], argsAsSerie = True )
945             for i in range(__m):
946                 qi = numpy.random.multivariate_normal(numpy.zeros(__n), Qn)
947                 Xn_predicted[:,i] = (numpy.ravel( EMX[i] ) + qi).reshape((__n,-1))
948             HX_predicted = H( [(Xn_predicted[:,i], Un) for i in range(__m)],
949                 argsAsSerie = True,
950                 returnSerieAsArrayMatrix = True )
951             if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
952                 Cm = Cm.reshape(__n,Un.size) # ADAO & check shape
953                 Xn_predicted = Xn_predicted + Cm * Un
954         elif selfA._parameters["EstimationOf"] == "Parameters": # Observation of forecast
955             # --- > Par principe, M = Id, Q = 0
956             Xn_predicted = Xn
957             HX_predicted = H( [(Xn_predicted[:,i], Un) for i in range(__m)],
958                 argsAsSerie = True,
959                 returnSerieAsArrayMatrix = True )
960         #
961         # Mean of forecast and observation of forecast
962         Xfm  = Xn_predicted.mean(axis=1, dtype=mfp).astype('float')
963         Hfm  = HX_predicted.mean(axis=1, dtype=mfp).astype('float')
964         #
965         # Anomalies
966         EaX   = numpy.matrix(Xn_predicted - Xfm.reshape((__n,-1)))
967         EaHX  = numpy.matrix(HX_predicted - Hfm.reshape((__p,-1)))
968         #
969         #--------------------------
970         if VariantM == "KalmanFilterFormula":
971             EaX    = EaX / numpy.sqrt(__m-1)
972             mS    = RIdemi * EaHX / numpy.sqrt(__m-1)
973             delta = RIdemi * ( Ynpu.reshape((__p,-1)) - Hfm.reshape((__p,-1)) )
974             mT    = numpy.linalg.inv( numpy.eye(__m) + mS.T @ mS )
975             vw    = mT @ mS.transpose() @ delta
976             #
977             Tdemi = numpy.real(scipy.linalg.sqrtm(mT))
978             mU    = numpy.eye(__m)
979             #
980             Xn = Xfm.reshape((__n,-1)) + EaX @ ( vw.reshape((__m,-1)) + numpy.sqrt(__m-1) * Tdemi @ mU )
981         #--------------------------
982         elif VariantM == "Variational":
983             HXfm = H((Xfm, Un)) # Eventuellement Hfm
984             def CostFunction(w):
985                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
986                 _Jo = 0.5 * _A.T * RI * _A
987                 _Jb = 0.5 * (__m-1) * w.T @ w
988                 _J  = _Jo + _Jb
989                 return float(_J)
990             def GradientOfCostFunction(w):
991                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
992                 _GardJo = - EaHX.T * RI * _A
993                 _GradJb = (__m-1) * w.reshape((__m,1))
994                 _GradJ  = _GardJo + _GradJb
995                 return numpy.ravel(_GradJ)
996             vw = scipy.optimize.fmin_cg(
997                 f           = CostFunction,
998                 x0          = numpy.zeros(__m),
999                 fprime      = GradientOfCostFunction,
1000                 args        = (),
1001                 disp        = False,
1002                 )
1003             #
1004             Hto = EaHX.T * RI * EaHX
1005             Htb = (__m-1) * numpy.eye(__m)
1006             Hta = Hto + Htb
1007             #
1008             Pta = numpy.linalg.inv( Hta )
1009             EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1010             #
1011             Xn = Xfm.reshape((__n,-1)) + EaX @ (vw.reshape((__m,-1)) + EWa)
1012         #--------------------------
1013         elif VariantM == "FiniteSize11": # Jauge Boc2011
1014             HXfm = H((Xfm, Un)) # Eventuellement Hfm
1015             def CostFunction(w):
1016                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1017                 _Jo = 0.5 * _A.T * RI * _A
1018                 _Jb = 0.5 * __m * math.log(1 + 1/__m + w.T @ w)
1019                 _J  = _Jo + _Jb
1020                 return float(_J)
1021             def GradientOfCostFunction(w):
1022                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1023                 _GardJo = - EaHX.T * RI * _A
1024                 _GradJb = __m * w.reshape((__m,1)) / (1 + 1/__m + w.T @ w)
1025                 _GradJ  = _GardJo + _GradJb
1026                 return numpy.ravel(_GradJ)
1027             vw = scipy.optimize.fmin_cg(
1028                 f           = CostFunction,
1029                 x0          = numpy.zeros(__m),
1030                 fprime      = GradientOfCostFunction,
1031                 args        = (),
1032                 disp        = False,
1033                 )
1034             #
1035             Hto = EaHX.T * RI * EaHX
1036             Htb = __m * \
1037                 ( (1 + 1/__m + vw.T @ vw) * numpy.eye(__m) - 2 * vw @ vw.T ) \
1038                 / (1 + 1/__m + vw.T @ vw)**2
1039             Hta = Hto + Htb
1040             #
1041             Pta = numpy.linalg.inv( Hta )
1042             EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1043             #
1044             Xn = Xfm.reshape((__n,-1)) + EaX @ (vw.reshape((__m,-1)) + EWa)
1045         #--------------------------
1046         elif VariantM == "FiniteSize15": # Jauge Boc2015
1047             HXfm = H((Xfm, Un)) # Eventuellement Hfm
1048             def CostFunction(w):
1049                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1050                 _Jo = 0.5 * _A.T * RI * _A
1051                 _Jb = 0.5 * (__m+1) * math.log(1 + 1/__m + w.T @ w)
1052                 _J  = _Jo + _Jb
1053                 return float(_J)
1054             def GradientOfCostFunction(w):
1055                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1056                 _GardJo = - EaHX.T * RI * _A
1057                 _GradJb = (__m+1) * w.reshape((__m,1)) / (1 + 1/__m + w.T @ w)
1058                 _GradJ  = _GardJo + _GradJb
1059                 return numpy.ravel(_GradJ)
1060             vw = scipy.optimize.fmin_cg(
1061                 f           = CostFunction,
1062                 x0          = numpy.zeros(__m),
1063                 fprime      = GradientOfCostFunction,
1064                 args        = (),
1065                 disp        = False,
1066                 )
1067             #
1068             Hto = EaHX.T * RI * EaHX
1069             Htb = (__m+1) * \
1070                 ( (1 + 1/__m + vw.T @ vw) * numpy.eye(__m) - 2 * vw @ vw.T ) \
1071                 / (1 + 1/__m + vw.T @ vw)**2
1072             Hta = Hto + Htb
1073             #
1074             Pta = numpy.linalg.inv( Hta )
1075             EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1076             #
1077             Xn = Xfm.reshape((__n,-1)) + EaX @ (vw.reshape((__m,-1)) + EWa)
1078         #--------------------------
1079         elif VariantM == "FiniteSize16": # Jauge Boc2016
1080             HXfm = H((Xfm, Un)) # Eventuellement Hfm
1081             def CostFunction(w):
1082                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1083                 _Jo = 0.5 * _A.T * RI * _A
1084                 _Jb = 0.5 * (__m+1) * math.log(1 + 1/__m + w.T @ w / (__m-1))
1085                 _J  = _Jo + _Jb
1086                 return float(_J)
1087             def GradientOfCostFunction(w):
1088                 _A  = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1089                 _GardJo = - EaHX.T * RI * _A
1090                 _GradJb = ((__m+1) / (__m-1)) * w.reshape((__m,1)) / (1 + 1/__m + w.T @ w / (__m-1))
1091                 _GradJ  = _GardJo + _GradJb
1092                 return numpy.ravel(_GradJ)
1093             vw = scipy.optimize.fmin_cg(
1094                 f           = CostFunction,
1095                 x0          = numpy.zeros(__m),
1096                 fprime      = GradientOfCostFunction,
1097                 args        = (),
1098                 disp        = False,
1099                 )
1100             #
1101             Hto = EaHX.T * RI * EaHX
1102             Htb = ((__m+1) / (__m-1)) * \
1103                 ( (1 + 1/__m + vw.T @ vw / (__m-1)) * numpy.eye(__m) - 2 * vw @ vw.T / (__m-1) ) \
1104                 / (1 + 1/__m + vw.T @ vw / (__m-1))**2
1105             Hta = Hto + Htb
1106             #
1107             Pta = numpy.linalg.inv( Hta )
1108             EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1109             #
1110             Xn = Xfm.reshape((__n,-1)) + EaX @ (vw.reshape((__m,-1)) + EWa)
1111         #--------------------------
1112         else:
1113             raise ValueError("VariantM has to be chosen in the authorized methods list.")
1114         #
1115         if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
1116             Xn = CovarianceInflation( Xn,
1117                 selfA._parameters["InflationType"],
1118                 selfA._parameters["InflationFactor"],
1119                 )
1120         #
1121         Xa = Xn.mean(axis=1, dtype=mfp).astype('float')
1122         #--------------------------
1123         #
1124         if selfA._parameters["StoreInternalVariables"] \
1125             or selfA._toStore("CostFunctionJ") \
1126             or selfA._toStore("CostFunctionJb") \
1127             or selfA._toStore("CostFunctionJo") \
1128             or selfA._toStore("APosterioriCovariance") \
1129             or selfA._toStore("InnovationAtCurrentAnalysis") \
1130             or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
1131             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1132             _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
1133             _Innovation = Ynpu - _HXa
1134         #
1135         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1136         # ---> avec analysis
1137         selfA.StoredVariables["Analysis"].store( Xa )
1138         if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
1139             selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
1140         if selfA._toStore("InnovationAtCurrentAnalysis"):
1141             selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
1142         # ---> avec current state
1143         if selfA._parameters["StoreInternalVariables"] \
1144             or selfA._toStore("CurrentState"):
1145             selfA.StoredVariables["CurrentState"].store( Xn )
1146         if selfA._toStore("ForecastState"):
1147             selfA.StoredVariables["ForecastState"].store( Xn_predicted )
1148         if selfA._toStore("BMA"):
1149             selfA.StoredVariables["BMA"].store( Xn_predicted - Xa )
1150         if selfA._toStore("InnovationAtCurrentState"):
1151             selfA.StoredVariables["InnovationAtCurrentState"].store( - HX_predicted + Ynpu )
1152         if selfA._toStore("SimulatedObservationAtCurrentState") \
1153             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1154             selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HX_predicted )
1155         # ---> autres
1156         if selfA._parameters["StoreInternalVariables"] \
1157             or selfA._toStore("CostFunctionJ") \
1158             or selfA._toStore("CostFunctionJb") \
1159             or selfA._toStore("CostFunctionJo") \
1160             or selfA._toStore("CurrentOptimum") \
1161             or selfA._toStore("APosterioriCovariance"):
1162             Jb  = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
1163             Jo  = float( 0.5 * _Innovation.T * RI * _Innovation )
1164             J   = Jb + Jo
1165             selfA.StoredVariables["CostFunctionJb"].store( Jb )
1166             selfA.StoredVariables["CostFunctionJo"].store( Jo )
1167             selfA.StoredVariables["CostFunctionJ" ].store( J )
1168             #
1169             if selfA._toStore("IndexOfOptimum") \
1170                 or selfA._toStore("CurrentOptimum") \
1171                 or selfA._toStore("CostFunctionJAtCurrentOptimum") \
1172                 or selfA._toStore("CostFunctionJbAtCurrentOptimum") \
1173                 or selfA._toStore("CostFunctionJoAtCurrentOptimum") \
1174                 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1175                 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
1176             if selfA._toStore("IndexOfOptimum"):
1177                 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
1178             if selfA._toStore("CurrentOptimum"):
1179                 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["Analysis"][IndexMin] )
1180             if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1181                 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"][IndexMin] )
1182             if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
1183                 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
1184             if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
1185                 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
1186             if selfA._toStore("CostFunctionJAtCurrentOptimum"):
1187                 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
1188         if selfA._toStore("APosterioriCovariance"):
1189             Eai = (1/numpy.sqrt(__m-1)) * (Xn - Xa.reshape((__n,-1))) # Anomalies
1190             Pn = Eai @ Eai.T
1191             Pn = 0.5 * (Pn + Pn.T)
1192             selfA.StoredVariables["APosterioriCovariance"].store( Pn )
1193         if selfA._parameters["EstimationOf"] == "Parameters" \
1194             and J < previousJMinimum:
1195             previousJMinimum    = J
1196             XaMin               = Xa
1197             if selfA._toStore("APosterioriCovariance"):
1198                 covarianceXaMin = Pn
1199     #
1200     # Stockage final supplémentaire de l'optimum en estimation de paramètres
1201     # ----------------------------------------------------------------------
1202     if selfA._parameters["EstimationOf"] == "Parameters":
1203         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1204         selfA.StoredVariables["Analysis"].store( XaMin )
1205         if selfA._toStore("APosterioriCovariance"):
1206             selfA.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
1207         if selfA._toStore("BMA"):
1208             selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
1209     #
1210     return 0
1211
1212 # ==============================================================================
1213 def mlef(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, BnotT=False, _epsilon=1.e-1, _e=1.e-7, _jmax=15000):
1214     """
1215     Maximum Likelihood Ensemble Filter (EnKF/MLEF Zupanski 2005, Bocquet 2013)
1216
1217     selfA est identique au "self" d'algorithme appelant et contient les
1218     valeurs.
1219     """
1220     if selfA._parameters["EstimationOf"] == "Parameters":
1221         selfA._parameters["StoreInternalVariables"] = True
1222     #
1223     # Opérateurs
1224     # ----------
1225     H = HO["Direct"].appliedControledFormTo
1226     #
1227     if selfA._parameters["EstimationOf"] == "State":
1228         M = EM["Direct"].appliedControledFormTo
1229     #
1230     if CM is not None and "Tangent" in CM and U is not None:
1231         Cm = CM["Tangent"].asMatrix(Xb)
1232     else:
1233         Cm = None
1234     #
1235     # Nombre de pas identique au nombre de pas d'observations
1236     # -------------------------------------------------------
1237     if hasattr(Y,"stepnumber"):
1238         duration = Y.stepnumber()
1239         __p = numpy.cumprod(Y.shape())[-1]
1240     else:
1241         duration = 2
1242         __p = numpy.array(Y).size
1243     #
1244     # Précalcul des inversions de B et R
1245     # ----------------------------------
1246     if selfA._parameters["StoreInternalVariables"] \
1247         or selfA._toStore("CostFunctionJ") \
1248         or selfA._toStore("CostFunctionJb") \
1249         or selfA._toStore("CostFunctionJo") \
1250         or selfA._toStore("CurrentOptimum") \
1251         or selfA._toStore("APosterioriCovariance"):
1252         BI = B.getI()
1253     RI = R.getI()
1254     #
1255     # Initialisation
1256     # --------------
1257     __n = Xb.size
1258     __m = selfA._parameters["NumberOfMembers"]
1259     if hasattr(B,"asfullmatrix"): Pn = B.asfullmatrix(__n)
1260     else:                         Pn = B
1261     if hasattr(R,"asfullmatrix"): Rn = R.asfullmatrix(__p)
1262     else:                         Rn = R
1263     if hasattr(Q,"asfullmatrix"): Qn = Q.asfullmatrix(__n)
1264     else:                         Qn = Q
1265     Xn = BackgroundEnsembleGeneration( Xb, None, __m )
1266     #
1267     if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
1268         selfA.StoredVariables["Analysis"].store( numpy.ravel(Xb) )
1269         if selfA._toStore("APosterioriCovariance"):
1270             selfA.StoredVariables["APosterioriCovariance"].store( Pn )
1271             covarianceXa = Pn
1272     #
1273     previousJMinimum = numpy.finfo(float).max
1274     #
1275     Xn_predicted = numpy.zeros((__n,__m))
1276     for step in range(duration-1):
1277         if hasattr(Y,"store"):
1278             Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
1279         else:
1280             Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
1281         #
1282         if U is not None:
1283             if hasattr(U,"store") and len(U)>1:
1284                 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
1285             elif hasattr(U,"store") and len(U)==1:
1286                 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
1287             else:
1288                 Un = numpy.asmatrix(numpy.ravel( U )).T
1289         else:
1290             Un = None
1291         #
1292         if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
1293             Xn = CovarianceInflation( Xn,
1294                 selfA._parameters["InflationType"],
1295                 selfA._parameters["InflationFactor"],
1296                 )
1297         #
1298         if selfA._parameters["EstimationOf"] == "State": # Forecast + Q and observation of forecast
1299             EMX = M( [(Xn[:,i], Un) for i in range(__m)], argsAsSerie = True )
1300             for i in range(__m):
1301                 qi = numpy.random.multivariate_normal(numpy.zeros(__n), Qn)
1302                 Xn_predicted[:,i] = (numpy.ravel( EMX[i] ) + qi).reshape((__n,-1))
1303             if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
1304                 Cm = Cm.reshape(__n,Un.size) # ADAO & check shape
1305                 Xn_predicted = Xn_predicted + Cm * Un
1306         elif selfA._parameters["EstimationOf"] == "Parameters": # Observation of forecast
1307             # --- > Par principe, M = Id, Q = 0
1308             Xn_predicted = Xn
1309         #
1310         # Mean of forecast and observation of forecast
1311         Xfm  = Xn_predicted.mean(axis=1, dtype=mfp).astype('float')
1312         #
1313         EaX   = (Xn_predicted - Xfm.reshape((__n,-1))) / numpy.sqrt(__m-1)
1314         #
1315         #--------------------------
1316         Ua = numpy.eye(__m)
1317         Ta = numpy.eye(__m)
1318         #
1319         __j = 0 # 4:
1320         vw = numpy.zeros(__m) # 4:
1321         Deltaw = 1
1322         while numpy.linalg.norm(Deltaw) >= _e or __j >= _jmax: # 5: et 19:
1323             vx = numpy.ravel(Xfm) + EaX @ vw # 6:
1324             #
1325             if BnotT:
1326                 EE = vx.reshape((__n,-1)) + _epsilon * EaX # 7:
1327             else:
1328                 EE = vx.reshape((__n,-1)) + numpy.sqrt(__m-1) * EaX @ Ta # 8:
1329             #
1330             EZ = H( [(EE[:,i], Un) for i in range(__m)],
1331                 argsAsSerie = True,
1332                 returnSerieAsArrayMatrix = True )
1333             #
1334             ybar = EZ.mean(axis=1, dtype=mfp).astype('float').reshape((__p,-1)) # 10: Observation mean
1335             #
1336             if BnotT:
1337                 EY = (EZ - ybar) / _epsilon # 11:
1338             else:
1339                 EY = ( (EZ - ybar) @ numpy.linalg.inv(Ta) ) / numpy.sqrt(__m-1) # 12:
1340             #
1341             GradJ = numpy.ravel(vw.reshape((__m,1)) - EY.transpose() @ (RI * (Ynpu - ybar))) # 13:
1342             mH = numpy.eye(__m) + EY.transpose() @ (RI * EY) # 14:
1343             Deltaw = numpy.linalg.solve(mH,GradJ) # 15:
1344             vw = vw - Deltaw # 16:
1345             if not BnotT:
1346                 Ta = numpy.linalg.inv(numpy.real(scipy.linalg.sqrtm( mH ))) # 17:
1347             __j = __j + 1 # 18:
1348         #
1349         if BnotT:
1350             Ta = numpy.linalg.inv(numpy.real(scipy.linalg.sqrtm( mH ))) # 20:
1351         #
1352         Xn = vx.reshape((__n,-1)) + numpy.sqrt(__m-1) * EaX @ Ta @ Ua # 21:
1353         #
1354         if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
1355             Xn = CovarianceInflation( Xn,
1356                 selfA._parameters["InflationType"],
1357                 selfA._parameters["InflationFactor"],
1358                 )
1359         #
1360         Xa = Xn.mean(axis=1, dtype=mfp).astype('float')
1361         #--------------------------
1362         #
1363         if selfA._parameters["StoreInternalVariables"] \
1364             or selfA._toStore("CostFunctionJ") \
1365             or selfA._toStore("CostFunctionJb") \
1366             or selfA._toStore("CostFunctionJo") \
1367             or selfA._toStore("APosterioriCovariance") \
1368             or selfA._toStore("InnovationAtCurrentAnalysis") \
1369             or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
1370             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1371             _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
1372             _Innovation = Ynpu - _HXa
1373         #
1374         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1375         # ---> avec analysis
1376         selfA.StoredVariables["Analysis"].store( Xa )
1377         if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
1378             selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
1379         if selfA._toStore("InnovationAtCurrentAnalysis"):
1380             selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
1381         # ---> avec current state
1382         if selfA._parameters["StoreInternalVariables"] \
1383             or selfA._toStore("CurrentState"):
1384             selfA.StoredVariables["CurrentState"].store( Xn )
1385         if selfA._toStore("ForecastState"):
1386             selfA.StoredVariables["ForecastState"].store( Xn_predicted )
1387         if selfA._toStore("BMA"):
1388             selfA.StoredVariables["BMA"].store( Xn_predicted - Xa )
1389         #~ if selfA._toStore("InnovationAtCurrentState"):
1390             #~ selfA.StoredVariables["InnovationAtCurrentState"].store( - HX_predicted + Ynpu )
1391         #~ if selfA._toStore("SimulatedObservationAtCurrentState") \
1392             #~ or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1393             #~ selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HX_predicted )
1394         # ---> autres
1395         if selfA._parameters["StoreInternalVariables"] \
1396             or selfA._toStore("CostFunctionJ") \
1397             or selfA._toStore("CostFunctionJb") \
1398             or selfA._toStore("CostFunctionJo") \
1399             or selfA._toStore("CurrentOptimum") \
1400             or selfA._toStore("APosterioriCovariance"):
1401             Jb  = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
1402             Jo  = float( 0.5 * _Innovation.T * RI * _Innovation )
1403             J   = Jb + Jo
1404             selfA.StoredVariables["CostFunctionJb"].store( Jb )
1405             selfA.StoredVariables["CostFunctionJo"].store( Jo )
1406             selfA.StoredVariables["CostFunctionJ" ].store( J )
1407             #
1408             if selfA._toStore("IndexOfOptimum") \
1409                 or selfA._toStore("CurrentOptimum") \
1410                 or selfA._toStore("CostFunctionJAtCurrentOptimum") \
1411                 or selfA._toStore("CostFunctionJbAtCurrentOptimum") \
1412                 or selfA._toStore("CostFunctionJoAtCurrentOptimum") \
1413                 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1414                 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
1415             if selfA._toStore("IndexOfOptimum"):
1416                 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
1417             if selfA._toStore("CurrentOptimum"):
1418                 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["Analysis"][IndexMin] )
1419             if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1420                 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"][IndexMin] )
1421             if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
1422                 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
1423             if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
1424                 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
1425             if selfA._toStore("CostFunctionJAtCurrentOptimum"):
1426                 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
1427         if selfA._toStore("APosterioriCovariance"):
1428             Eai = (1/numpy.sqrt(__m-1)) * (Xn - Xa.reshape((__n,-1))) # Anomalies
1429             Pn = Eai @ Eai.T
1430             Pn = 0.5 * (Pn + Pn.T)
1431             selfA.StoredVariables["APosterioriCovariance"].store( Pn )
1432         if selfA._parameters["EstimationOf"] == "Parameters" \
1433             and J < previousJMinimum:
1434             previousJMinimum    = J
1435             XaMin               = Xa
1436             if selfA._toStore("APosterioriCovariance"):
1437                 covarianceXaMin = Pn
1438     #
1439     # Stockage final supplémentaire de l'optimum en estimation de paramètres
1440     # ----------------------------------------------------------------------
1441     if selfA._parameters["EstimationOf"] == "Parameters":
1442         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1443         selfA.StoredVariables["Analysis"].store( XaMin )
1444         if selfA._toStore("APosterioriCovariance"):
1445             selfA.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
1446         if selfA._toStore("BMA"):
1447             selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
1448     #
1449     return 0
1450
1451 # ==============================================================================
1452 if __name__ == "__main__":
1453     print('\n AUTODIAGNOSTIC\n')