Salome HOME
Fixing iterating observation use (2)
[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, scipy.version
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( triplet ):
38     assert len(triplet) == 3, "Incorrect number of arguments"
39     X, xArgs, funcrepr = triplet
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     if isinstance(xArgs, dict):
46         __HX  = __fonction( __X, **xArgs )
47     else:
48         __HX  = __fonction( __X )
49     return numpy.ravel( __HX )
50
51 # ==============================================================================
52 class FDApproximation(object):
53     """
54     Cette classe sert d'interface pour définir les opérateurs approximés. A la
55     création d'un objet, en fournissant une fonction "Function", on obtient un
56     objet qui dispose de 3 méthodes "DirectOperator", "TangentOperator" et
57     "AdjointOperator". On contrôle l'approximation DF avec l'incrément
58     multiplicatif "increment" valant par défaut 1%, ou avec l'incrément fixe
59     "dX" qui sera multiplié par "increment" (donc en %), et on effectue de DF
60     centrées si le booléen "centeredDF" est vrai.
61     """
62     def __init__(self,
63             name                  = "FDApproximation",
64             Function              = None,
65             centeredDF            = False,
66             increment             = 0.01,
67             dX                    = None,
68             extraArguments        = None,
69             avoidingRedundancy    = True,
70             toleranceInRedundancy = 1.e-18,
71             lenghtOfRedundancy    = -1,
72             mpEnabled             = False,
73             mpWorkers             = None,
74             mfEnabled             = False,
75             ):
76         self.__name = str(name)
77         self.__extraArgs = extraArguments
78         if mpEnabled:
79             try:
80                 import multiprocessing
81                 self.__mpEnabled = True
82             except ImportError:
83                 self.__mpEnabled = False
84         else:
85             self.__mpEnabled = False
86         self.__mpWorkers = mpWorkers
87         if self.__mpWorkers is not None and self.__mpWorkers < 1:
88             self.__mpWorkers = None
89         logging.debug("FDA Calculs en multiprocessing : %s (nombre de processus : %s)"%(self.__mpEnabled,self.__mpWorkers))
90         #
91         if mfEnabled:
92             self.__mfEnabled = True
93         else:
94             self.__mfEnabled = False
95         logging.debug("FDA Calculs en multifonctions : %s"%(self.__mfEnabled,))
96         #
97         if avoidingRedundancy:
98             self.__avoidRC = True
99             self.__tolerBP = float(toleranceInRedundancy)
100             self.__lenghtRJ = int(lenghtOfRedundancy)
101             self.__listJPCP = [] # Jacobian Previous Calculated Points
102             self.__listJPCI = [] # Jacobian Previous Calculated Increment
103             self.__listJPCR = [] # Jacobian Previous Calculated Results
104             self.__listJPPN = [] # Jacobian Previous Calculated Point Norms
105             self.__listJPIN = [] # Jacobian Previous Calculated Increment Norms
106         else:
107             self.__avoidRC = False
108         #
109         if self.__mpEnabled:
110             if isinstance(Function,types.FunctionType):
111                 logging.debug("FDA Calculs en multiprocessing : FunctionType")
112                 self.__userFunction__name = Function.__name__
113                 try:
114                     mod = os.path.join(Function.__globals__['filepath'],Function.__globals__['filename'])
115                 except:
116                     mod = os.path.abspath(Function.__globals__['__file__'])
117                 if not os.path.isfile(mod):
118                     raise ImportError("No user defined function or method found with the name %s"%(mod,))
119                 self.__userFunction__modl = os.path.basename(mod).replace('.pyc','').replace('.pyo','').replace('.py','')
120                 self.__userFunction__path = os.path.dirname(mod)
121                 del mod
122                 self.__userOperator = Operator( name = self.__name, fromMethod = Function, avoidingRedundancy = self.__avoidRC, inputAsMultiFunction = self.__mfEnabled, extraArguments = self.__extraArgs )
123                 self.__userFunction = self.__userOperator.appliedTo # Pour le calcul Direct
124             elif isinstance(Function,types.MethodType):
125                 logging.debug("FDA Calculs en multiprocessing : MethodType")
126                 self.__userFunction__name = Function.__name__
127                 try:
128                     mod = os.path.join(Function.__globals__['filepath'],Function.__globals__['filename'])
129                 except:
130                     mod = os.path.abspath(Function.__func__.__globals__['__file__'])
131                 if not os.path.isfile(mod):
132                     raise ImportError("No user defined function or method found with the name %s"%(mod,))
133                 self.__userFunction__modl = os.path.basename(mod).replace('.pyc','').replace('.pyo','').replace('.py','')
134                 self.__userFunction__path = os.path.dirname(mod)
135                 del mod
136                 self.__userOperator = Operator( name = self.__name, fromMethod = Function, avoidingRedundancy = self.__avoidRC, inputAsMultiFunction = self.__mfEnabled, extraArguments = self.__extraArgs )
137                 self.__userFunction = self.__userOperator.appliedTo # Pour le calcul Direct
138             else:
139                 raise TypeError("User defined function or method has to be provided for finite differences approximation.")
140         else:
141             self.__userOperator = Operator( name = self.__name, fromMethod = Function, avoidingRedundancy = self.__avoidRC, inputAsMultiFunction = self.__mfEnabled, extraArguments = self.__extraArgs )
142             self.__userFunction = self.__userOperator.appliedTo
143         #
144         self.__centeredDF = bool(centeredDF)
145         if abs(float(increment)) > 1.e-15:
146             self.__increment  = float(increment)
147         else:
148             self.__increment  = 0.01
149         if dX is None:
150             self.__dX     = None
151         else:
152             self.__dX     = numpy.asmatrix(numpy.ravel( dX )).T
153         logging.debug("FDA Reduction des doublons de calcul : %s"%self.__avoidRC)
154         if self.__avoidRC:
155             logging.debug("FDA Tolerance de determination des doublons : %.2e"%self.__tolerBP)
156
157     # ---------------------------------------------------------
158     def __doublon__(self, e, l, n, v=None):
159         __ac, __iac = False, -1
160         for i in range(len(l)-1,-1,-1):
161             if numpy.linalg.norm(e - l[i]) < self.__tolerBP * n[i]:
162                 __ac, __iac = True, i
163                 if v is not None: logging.debug("FDA Cas%s déja calculé, récupération du doublon %i"%(v,__iac))
164                 break
165         return __ac, __iac
166
167     # ---------------------------------------------------------
168     def DirectOperator(self, X, **extraArgs ):
169         """
170         Calcul du direct à l'aide de la fonction fournie.
171
172         NB : les extraArgs sont là pour assurer la compatibilité d'appel, mais
173         ne doivent pas être données ici à la fonction utilisateur.
174         """
175         logging.debug("FDA Calcul DirectOperator (explicite)")
176         if self.__mfEnabled:
177             _HX = self.__userFunction( X, argsAsSerie = True )
178         else:
179             _X = numpy.asmatrix(numpy.ravel( X )).T
180             _HX = numpy.ravel(self.__userFunction( _X ))
181         #
182         return _HX
183
184     # ---------------------------------------------------------
185     def TangentMatrix(self, X ):
186         """
187         Calcul de l'opérateur tangent comme la Jacobienne par différences finies,
188         c'est-à-dire le gradient de H en X. On utilise des différences finies
189         directionnelles autour du point X. X est un numpy.matrix.
190
191         Différences finies centrées (approximation d'ordre 2):
192         1/ Pour chaque composante i de X, on ajoute et on enlève la perturbation
193            dX[i] à la  composante X[i], pour composer X_plus_dXi et X_moins_dXi, et
194            on calcule les réponses HX_plus_dXi = H( X_plus_dXi ) et HX_moins_dXi =
195            H( X_moins_dXi )
196         2/ On effectue les différences (HX_plus_dXi-HX_moins_dXi) et on divise par
197            le pas 2*dXi
198         3/ Chaque résultat, par composante, devient une colonne de la Jacobienne
199
200         Différences finies non centrées (approximation d'ordre 1):
201         1/ Pour chaque composante i de X, on ajoute la perturbation dX[i] à la
202            composante X[i] pour composer X_plus_dXi, et on calcule la réponse
203            HX_plus_dXi = H( X_plus_dXi )
204         2/ On calcule la valeur centrale HX = H(X)
205         3/ On effectue les différences (HX_plus_dXi-HX) et on divise par
206            le pas dXi
207         4/ Chaque résultat, par composante, devient une colonne de la Jacobienne
208
209         """
210         logging.debug("FDA Début du calcul de la Jacobienne")
211         logging.debug("FDA   Incrément de............: %s*X"%float(self.__increment))
212         logging.debug("FDA   Approximation centrée...: %s"%(self.__centeredDF))
213         #
214         if X is None or len(X)==0:
215             raise ValueError("Nominal point X for approximate derivatives can not be None or void (given X: %s)."%(str(X),))
216         #
217         _X = numpy.asmatrix(numpy.ravel( X )).T
218         #
219         if self.__dX is None:
220             _dX  = self.__increment * _X
221         else:
222             _dX = numpy.asmatrix(numpy.ravel( self.__dX )).T
223         #
224         if (_dX == 0.).any():
225             moyenne = _dX.mean()
226             if moyenne == 0.:
227                 _dX = numpy.where( _dX == 0., float(self.__increment), _dX )
228             else:
229                 _dX = numpy.where( _dX == 0., moyenne, _dX )
230         #
231         __alreadyCalculated  = False
232         if self.__avoidRC:
233             __bidon, __alreadyCalculatedP = self.__doublon__(_X,  self.__listJPCP, self.__listJPPN, None)
234             __bidon, __alreadyCalculatedI = self.__doublon__(_dX, self.__listJPCI, self.__listJPIN, None)
235             if __alreadyCalculatedP == __alreadyCalculatedI > -1:
236                 __alreadyCalculated, __i = True, __alreadyCalculatedP
237                 logging.debug("FDA Cas J déja calculé, récupération du doublon %i"%__i)
238         #
239         if __alreadyCalculated:
240             logging.debug("FDA   Calcul Jacobienne (par récupération du doublon %i)"%__i)
241             _Jacobienne = self.__listJPCR[__i]
242         else:
243             logging.debug("FDA   Calcul Jacobienne (explicite)")
244             if self.__centeredDF:
245                 #
246                 if self.__mpEnabled and not self.__mfEnabled:
247                     funcrepr = {
248                         "__userFunction__path" : self.__userFunction__path,
249                         "__userFunction__modl" : self.__userFunction__modl,
250                         "__userFunction__name" : self.__userFunction__name,
251                     }
252                     _jobs = []
253                     for i in range( len(_dX) ):
254                         _dXi            = _dX[i]
255                         _X_plus_dXi     = numpy.array( _X.A1, dtype=float )
256                         _X_plus_dXi[i]  = _X[i] + _dXi
257                         _X_moins_dXi    = numpy.array( _X.A1, dtype=float )
258                         _X_moins_dXi[i] = _X[i] - _dXi
259                         #
260                         _jobs.append( (_X_plus_dXi,  self.__extraArgs, funcrepr) )
261                         _jobs.append( (_X_moins_dXi, self.__extraArgs, funcrepr) )
262                     #
263                     import multiprocessing
264                     self.__pool = multiprocessing.Pool(self.__mpWorkers)
265                     _HX_plusmoins_dX = self.__pool.map( ExecuteFunction, _jobs )
266                     self.__pool.close()
267                     self.__pool.join()
268                     #
269                     _Jacobienne  = []
270                     for i in range( len(_dX) ):
271                         _Jacobienne.append( numpy.ravel( _HX_plusmoins_dX[2*i] - _HX_plusmoins_dX[2*i+1] ) / (2.*_dX[i]) )
272                     #
273                 elif self.__mfEnabled:
274                     _xserie = []
275                     for i in range( len(_dX) ):
276                         _dXi            = _dX[i]
277                         _X_plus_dXi     = numpy.array( _X.A1, dtype=float )
278                         _X_plus_dXi[i]  = _X[i] + _dXi
279                         _X_moins_dXi    = numpy.array( _X.A1, dtype=float )
280                         _X_moins_dXi[i] = _X[i] - _dXi
281                         #
282                         _xserie.append( _X_plus_dXi )
283                         _xserie.append( _X_moins_dXi )
284                     #
285                     _HX_plusmoins_dX = self.DirectOperator( _xserie )
286                      #
287                     _Jacobienne  = []
288                     for i in range( len(_dX) ):
289                         _Jacobienne.append( numpy.ravel( _HX_plusmoins_dX[2*i] - _HX_plusmoins_dX[2*i+1] ) / (2.*_dX[i]) )
290                     #
291                 else:
292                     _Jacobienne  = []
293                     for i in range( _dX.size ):
294                         _dXi            = _dX[i]
295                         _X_plus_dXi     = numpy.array( _X.A1, dtype=float )
296                         _X_plus_dXi[i]  = _X[i] + _dXi
297                         _X_moins_dXi    = numpy.array( _X.A1, dtype=float )
298                         _X_moins_dXi[i] = _X[i] - _dXi
299                         #
300                         _HX_plus_dXi    = self.DirectOperator( _X_plus_dXi )
301                         _HX_moins_dXi   = self.DirectOperator( _X_moins_dXi )
302                         #
303                         _Jacobienne.append( numpy.ravel( _HX_plus_dXi - _HX_moins_dXi ) / (2.*_dXi) )
304                 #
305             else:
306                 #
307                 if self.__mpEnabled and not self.__mfEnabled:
308                     funcrepr = {
309                         "__userFunction__path" : self.__userFunction__path,
310                         "__userFunction__modl" : self.__userFunction__modl,
311                         "__userFunction__name" : self.__userFunction__name,
312                     }
313                     _jobs = []
314                     _jobs.append( (_X.A1, self.__extraArgs, funcrepr) )
315                     for i in range( len(_dX) ):
316                         _X_plus_dXi    = numpy.array( _X.A1, dtype=float )
317                         _X_plus_dXi[i] = _X[i] + _dX[i]
318                         #
319                         _jobs.append( (_X_plus_dXi, self.__extraArgs, funcrepr) )
320                     #
321                     import multiprocessing
322                     self.__pool = multiprocessing.Pool(self.__mpWorkers)
323                     _HX_plus_dX = self.__pool.map( ExecuteFunction, _jobs )
324                     self.__pool.close()
325                     self.__pool.join()
326                     #
327                     _HX = _HX_plus_dX.pop(0)
328                     #
329                     _Jacobienne = []
330                     for i in range( len(_dX) ):
331                         _Jacobienne.append( numpy.ravel(( _HX_plus_dX[i] - _HX ) / _dX[i]) )
332                     #
333                 elif self.__mfEnabled:
334                     _xserie = []
335                     _xserie.append( _X.A1 )
336                     for i in range( len(_dX) ):
337                         _X_plus_dXi    = numpy.array( _X.A1, dtype=float )
338                         _X_plus_dXi[i] = _X[i] + _dX[i]
339                         #
340                         _xserie.append( _X_plus_dXi )
341                     #
342                     _HX_plus_dX = self.DirectOperator( _xserie )
343                     #
344                     _HX = _HX_plus_dX.pop(0)
345                     #
346                     _Jacobienne = []
347                     for i in range( len(_dX) ):
348                         _Jacobienne.append( numpy.ravel(( _HX_plus_dX[i] - _HX ) / _dX[i]) )
349                    #
350                 else:
351                     _Jacobienne  = []
352                     _HX = self.DirectOperator( _X )
353                     for i in range( _dX.size ):
354                         _dXi            = _dX[i]
355                         _X_plus_dXi     = numpy.array( _X.A1, dtype=float )
356                         _X_plus_dXi[i]  = _X[i] + _dXi
357                         #
358                         _HX_plus_dXi = self.DirectOperator( _X_plus_dXi )
359                         #
360                         _Jacobienne.append( numpy.ravel(( _HX_plus_dXi - _HX ) / _dXi) )
361                 #
362             #
363             _Jacobienne = numpy.asmatrix( numpy.vstack( _Jacobienne ) ).T
364             if self.__avoidRC:
365                 if self.__lenghtRJ < 0: self.__lenghtRJ = 2 * _X.size
366                 while len(self.__listJPCP) > self.__lenghtRJ:
367                     self.__listJPCP.pop(0)
368                     self.__listJPCI.pop(0)
369                     self.__listJPCR.pop(0)
370                     self.__listJPPN.pop(0)
371                     self.__listJPIN.pop(0)
372                 self.__listJPCP.append( copy.copy(_X) )
373                 self.__listJPCI.append( copy.copy(_dX) )
374                 self.__listJPCR.append( copy.copy(_Jacobienne) )
375                 self.__listJPPN.append( numpy.linalg.norm(_X) )
376                 self.__listJPIN.append( numpy.linalg.norm(_Jacobienne) )
377         #
378         logging.debug("FDA Fin du calcul de la Jacobienne")
379         #
380         return _Jacobienne
381
382     # ---------------------------------------------------------
383     def TangentOperator(self, paire, **extraArgs ):
384         """
385         Calcul du tangent à l'aide de la Jacobienne.
386
387         NB : les extraArgs sont là pour assurer la compatibilité d'appel, mais
388         ne doivent pas être données ici à la fonction utilisateur.
389         """
390         if self.__mfEnabled:
391             assert len(paire) == 1, "Incorrect lenght of arguments"
392             _paire = paire[0]
393             assert len(_paire) == 2, "Incorrect number of arguments"
394         else:
395             assert len(paire) == 2, "Incorrect number of arguments"
396             _paire = paire
397         X, dX = _paire
398         _Jacobienne = self.TangentMatrix( X )
399         if dX is None or len(dX) == 0:
400             #
401             # Calcul de la forme matricielle si le second argument est None
402             # -------------------------------------------------------------
403             if self.__mfEnabled: return [_Jacobienne,]
404             else:                return _Jacobienne
405         else:
406             #
407             # Calcul de la valeur linéarisée de H en X appliqué à dX
408             # ------------------------------------------------------
409             _dX = numpy.asmatrix(numpy.ravel( dX )).T
410             _HtX = numpy.dot(_Jacobienne, _dX)
411             if self.__mfEnabled: return [_HtX.A1,]
412             else:                return _HtX.A1
413
414     # ---------------------------------------------------------
415     def AdjointOperator(self, paire, **extraArgs ):
416         """
417         Calcul de l'adjoint à l'aide de la Jacobienne.
418
419         NB : les extraArgs sont là pour assurer la compatibilité d'appel, mais
420         ne doivent pas être données ici à la fonction utilisateur.
421         """
422         if self.__mfEnabled:
423             assert len(paire) == 1, "Incorrect lenght of arguments"
424             _paire = paire[0]
425             assert len(_paire) == 2, "Incorrect number of arguments"
426         else:
427             assert len(paire) == 2, "Incorrect number of arguments"
428             _paire = paire
429         X, Y = _paire
430         _JacobienneT = self.TangentMatrix( X ).T
431         if Y is None or len(Y) == 0:
432             #
433             # Calcul de la forme matricielle si le second argument est None
434             # -------------------------------------------------------------
435             if self.__mfEnabled: return [_JacobienneT,]
436             else:                return _JacobienneT
437         else:
438             #
439             # Calcul de la valeur de l'adjoint en X appliqué à Y
440             # --------------------------------------------------
441             _Y = numpy.asmatrix(numpy.ravel( Y )).T
442             _HaY = numpy.dot(_JacobienneT, _Y)
443             if self.__mfEnabled: return [_HaY.A1,]
444             else:                return _HaY.A1
445
446 # ==============================================================================
447 def EnsembleOfCenteredPerturbations( _bgcenter, _bgcovariance, _nbmembers ):
448     "Génération d'un ensemble de taille _nbmembers-1 d'états aléatoires centrés"
449     #
450     _bgcenter = numpy.ravel(_bgcenter)[:,None]
451     if _nbmembers < 1:
452         raise ValueError("Number of members has to be strictly more than 1 (given number: %s)."%(str(_nbmembers),))
453     #
454     if _bgcovariance is None:
455         BackgroundEnsemble = numpy.tile( _bgcenter, _nbmembers)
456     else:
457         _Z = numpy.random.multivariate_normal(numpy.zeros(_bgcenter.size), _bgcovariance, size=_nbmembers).T
458         BackgroundEnsemble = numpy.tile( _bgcenter, _nbmembers) + _Z
459     #
460     return BackgroundEnsemble
461
462 # ==============================================================================
463 def EnsembleOfBackgroundPerturbations( _bgcenter, _bgcovariance, _nbmembers, _withSVD = True):
464     "Génération d'un ensemble de taille _nbmembers-1 d'états aléatoires centrés"
465     def __CenteredRandomAnomalies(Zr, N):
466         """
467         Génère une matrice de N anomalies aléatoires centrées sur Zr selon les
468         notes manuscrites de MB et conforme au code de PS avec eps = -1
469         """
470         eps = -1
471         Q = numpy.identity(N-1)-numpy.ones((N-1,N-1))/numpy.sqrt(N)/(numpy.sqrt(N)-eps)
472         Q = numpy.concatenate((Q, [eps*numpy.ones(N-1)/numpy.sqrt(N)]), axis=0)
473         R, _ = numpy.linalg.qr(numpy.random.normal(size = (N-1,N-1)))
474         Q = numpy.dot(Q,R)
475         Zr = numpy.dot(Q,Zr)
476         return Zr.T
477     #
478     _bgcenter = numpy.ravel(_bgcenter).reshape((-1,1))
479     if _nbmembers < 1:
480         raise ValueError("Number of members has to be strictly more than 1 (given number: %s)."%(str(_nbmembers),))
481     if _bgcovariance is None:
482         BackgroundEnsemble = numpy.tile( _bgcenter, _nbmembers)
483     else:
484         if _withSVD:
485             U, s, V = numpy.linalg.svd(_bgcovariance, full_matrices=False)
486             _nbctl = _bgcenter.size
487             if _nbmembers > _nbctl:
488                 _Z = numpy.concatenate((numpy.dot(
489                     numpy.diag(numpy.sqrt(s[:_nbctl])), V[:_nbctl]),
490                     numpy.random.multivariate_normal(numpy.zeros(_nbctl),_bgcovariance,_nbmembers-1-_nbctl)), axis = 0)
491             else:
492                 _Z = numpy.dot(numpy.diag(numpy.sqrt(s[:_nbmembers-1])), V[:_nbmembers-1])
493             _Zca = __CenteredRandomAnomalies(_Z, _nbmembers)
494             BackgroundEnsemble = _bgcenter + _Zca
495         else:
496             if max(abs(_bgcovariance.flatten())) > 0:
497                 _nbctl = _bgcenter.size
498                 _Z = numpy.random.multivariate_normal(numpy.zeros(_nbctl),_bgcovariance,_nbmembers-1)
499                 _Zca = __CenteredRandomAnomalies(_Z, _nbmembers)
500                 BackgroundEnsemble = _bgcenter + _Zca
501             else:
502                 BackgroundEnsemble = numpy.tile( _bgcenter, _nbmembers)
503     #
504     return BackgroundEnsemble
505
506 # ==============================================================================
507 def EnsembleMean( __Ensemble ):
508     "Renvoie la moyenne empirique d'un ensemble"
509     return numpy.asarray(__Ensemble).mean(axis=1, dtype=mfp).astype('float').reshape((-1,1))
510
511 # ==============================================================================
512 def EnsembleOfAnomalies( Ensemble, OptMean = None, Normalisation = 1.):
513     "Renvoie les anomalies centrées à partir d'un ensemble"
514     if OptMean is None:
515         __Em = EnsembleMean( Ensemble )
516     else:
517         __Em = numpy.ravel(OptMean).reshape((-1,1))
518     #
519     return Normalisation * (numpy.asarray(Ensemble) - __Em)
520
521 # ==============================================================================
522 def EnsembleErrorCovariance( Ensemble, __quick = False ):
523     "Renvoie l'estimation empirique de la covariance d'ensemble"
524     if __quick:
525         # Covariance rapide mais rarement définie positive
526         __Covariance = numpy.cov(Ensemble)
527     else:
528         # Résultat souvent identique à numpy.cov, mais plus robuste
529         __n, __m = numpy.asarray(Ensemble).shape
530         __Anomalies = EnsembleOfAnomalies( Ensemble )
531         # Estimation empirique
532         __Covariance = (__Anomalies @ __Anomalies.T) / (__m-1)
533         # Assure la symétrie
534         __Covariance = (__Covariance + __Covariance.T) * 0.5
535         # Assure la positivité
536         __epsilon    = mpr*numpy.trace(__Covariance)
537         __Covariance = __Covariance + __epsilon * numpy.identity(__n)
538     #
539     return __Covariance
540
541 # ==============================================================================
542 def EnsemblePerturbationWithGivenCovariance( __Ensemble, __Covariance, __Seed=None ):
543     "Ajout d'une perturbation à chaque membre d'un ensemble selon une covariance prescrite"
544     if hasattr(__Covariance,"assparsematrix"):
545         if (abs(__Ensemble).mean() > mpr) and (abs(__Covariance.assparsematrix())/abs(__Ensemble).mean() < mpr).all():
546             # Traitement d'une covariance nulle ou presque
547             return __Ensemble
548         if (abs(__Ensemble).mean() <= mpr) and (abs(__Covariance.assparsematrix()) < mpr).all():
549             # Traitement d'une covariance nulle ou presque
550             return __Ensemble
551     else:
552         if (abs(__Ensemble).mean() > mpr) and (abs(__Covariance)/abs(__Ensemble).mean() < mpr).all():
553             # Traitement d'une covariance nulle ou presque
554             return __Ensemble
555         if (abs(__Ensemble).mean() <= mpr) and (abs(__Covariance) < mpr).all():
556             # Traitement d'une covariance nulle ou presque
557             return __Ensemble
558     #
559     __n, __m = __Ensemble.shape
560     if __Seed is not None: numpy.random.seed(__Seed)
561     #
562     if hasattr(__Covariance,"isscalar") and __Covariance.isscalar():
563         # Traitement d'une covariance multiple de l'identité
564         __zero = 0.
565         __std  = numpy.sqrt(__Covariance.assparsematrix())
566         __Ensemble += numpy.random.normal(__zero, __std, size=(__m,__n)).T
567     #
568     elif hasattr(__Covariance,"isvector") and __Covariance.isvector():
569         # Traitement d'une covariance diagonale avec variances non identiques
570         __zero = numpy.zeros(__n)
571         __std  = numpy.sqrt(__Covariance.assparsematrix())
572         __Ensemble += numpy.asarray([numpy.random.normal(__zero, __std) for i in range(__m)]).T
573     #
574     elif hasattr(__Covariance,"ismatrix") and __Covariance.ismatrix():
575         # Traitement d'une covariance pleine
576         __Ensemble += numpy.random.multivariate_normal(numpy.zeros(__n), __Covariance.asfullmatrix(__n), size=__m).T
577     #
578     elif isinstance(__Covariance, numpy.ndarray):
579         # Traitement d'une covariance numpy pleine, sachant qu'on arrive ici en dernier
580         __Ensemble += numpy.random.multivariate_normal(numpy.zeros(__n), __Covariance, size=__m).T
581     #
582     else:
583         raise ValueError("Error in ensemble perturbation with inadequate covariance specification")
584     #
585     return __Ensemble
586
587 # ==============================================================================
588 def CovarianceInflation(
589         InputCovOrEns,
590         InflationType   = None,
591         InflationFactor = None,
592         BackgroundCov   = None,
593         ):
594     """
595     Inflation applicable soit sur Pb ou Pa, soit sur les ensembles EXb ou EXa
596
597     Synthèse : Hunt 2007, section 2.3.5
598     """
599     if InflationFactor is None:
600         return InputCovOrEns
601     else:
602         InflationFactor = float(InflationFactor)
603     #
604     if InflationType in ["MultiplicativeOnAnalysisCovariance", "MultiplicativeOnBackgroundCovariance"]:
605         if InflationFactor < 1.:
606             raise ValueError("Inflation factor for multiplicative inflation has to be greater or equal than 1.")
607         if InflationFactor < 1.+mpr:
608             return InputCovOrEns
609         OutputCovOrEns = InflationFactor**2 * InputCovOrEns
610     #
611     elif InflationType in ["MultiplicativeOnAnalysisAnomalies", "MultiplicativeOnBackgroundAnomalies"]:
612         if InflationFactor < 1.:
613             raise ValueError("Inflation factor for multiplicative inflation has to be greater or equal than 1.")
614         if InflationFactor < 1.+mpr:
615             return InputCovOrEns
616         InputCovOrEnsMean = InputCovOrEns.mean(axis=1, dtype=mfp).astype('float')
617         OutputCovOrEns = InputCovOrEnsMean[:,numpy.newaxis] \
618             + InflationFactor * (InputCovOrEns - InputCovOrEnsMean[:,numpy.newaxis])
619     #
620     elif InflationType in ["AdditiveOnAnalysisCovariance", "AdditiveOnBackgroundCovariance"]:
621         if InflationFactor < 0.:
622             raise ValueError("Inflation factor for additive inflation has to be greater or equal than 0.")
623         if InflationFactor < mpr:
624             return InputCovOrEns
625         __n, __m = numpy.asarray(InputCovOrEns).shape
626         if __n != __m:
627             raise ValueError("Additive inflation can only be applied to squared (covariance) matrix.")
628         OutputCovOrEns = (1. - InflationFactor) * InputCovOrEns + InflationFactor * numpy.identity(__n)
629     #
630     elif InflationType == "HybridOnBackgroundCovariance":
631         if InflationFactor < 0.:
632             raise ValueError("Inflation factor for hybrid inflation has to be greater or equal than 0.")
633         if InflationFactor < mpr:
634             return InputCovOrEns
635         __n, __m = numpy.asarray(InputCovOrEns).shape
636         if __n != __m:
637             raise ValueError("Additive inflation can only be applied to squared (covariance) matrix.")
638         if BackgroundCov is None:
639             raise ValueError("Background covariance matrix B has to be given for hybrid inflation.")
640         if InputCovOrEns.shape != BackgroundCov.shape:
641             raise ValueError("Ensemble covariance matrix has to be of same size than background covariance matrix B.")
642         OutputCovOrEns = (1. - InflationFactor) * InputCovOrEns + InflationFactor * BackgroundCov
643     #
644     elif InflationType == "Relaxation":
645         raise NotImplementedError("InflationType Relaxation")
646     #
647     else:
648         raise ValueError("Error in inflation type, '%s' is not a valid keyword."%InflationType)
649     #
650     return OutputCovOrEns
651
652 # ==============================================================================
653 def QuantilesEstimations(selfA, A, Xa, HXa = None, Hm = None, HtM = None):
654     "Estimation des quantiles a posteriori (selfA est modifié)"
655     nbsamples = selfA._parameters["NumberOfSamplesForQuantiles"]
656     #
657     # Traitement des bornes
658     if "StateBoundsForQuantiles" in selfA._parameters:
659         LBounds = selfA._parameters["StateBoundsForQuantiles"] # Prioritaire
660     elif "Bounds" in selfA._parameters:
661         LBounds = selfA._parameters["Bounds"]  # Défaut raisonnable
662     else:
663         LBounds = None
664     if LBounds is not None:
665         def NoneRemove(paire):
666             bmin, bmax = paire
667             if bmin is None: bmin = numpy.finfo('float').min
668             if bmax is None: bmax = numpy.finfo('float').max
669             return [bmin, bmax]
670         LBounds = numpy.matrix( [NoneRemove(paire) for paire in LBounds] )
671     #
672     # Échantillonnage des états
673     YfQ  = None
674     EXr  = None
675     if selfA._parameters["SimulationForQuantiles"] == "Linear" and HXa is not None:
676         HXa  = numpy.matrix(numpy.ravel( HXa )).T
677     for i in range(nbsamples):
678         if selfA._parameters["SimulationForQuantiles"] == "Linear" and HtM is not None:
679             dXr = numpy.matrix(numpy.random.multivariate_normal(numpy.ravel(Xa),A) - numpy.ravel(Xa)).T
680             if LBounds is not None: # "EstimateProjection" par défaut
681                 dXr = numpy.max(numpy.hstack((dXr,LBounds[:,0]) - Xa),axis=1)
682                 dXr = numpy.min(numpy.hstack((dXr,LBounds[:,1]) - Xa),axis=1)
683             dYr = numpy.matrix(numpy.ravel( HtM * dXr )).T
684             Yr = HXa + dYr
685             if selfA._toStore("SampledStateForQuantiles"): Xr = Xa + dXr
686         elif selfA._parameters["SimulationForQuantiles"] == "NonLinear" and Hm is not None:
687             Xr = numpy.matrix(numpy.random.multivariate_normal(numpy.ravel(Xa),A)).T
688             if LBounds is not None: # "EstimateProjection" par défaut
689                 Xr = numpy.max(numpy.hstack((Xr,LBounds[:,0])),axis=1)
690                 Xr = numpy.min(numpy.hstack((Xr,LBounds[:,1])),axis=1)
691             Yr = numpy.matrix(numpy.ravel( Hm( Xr ) )).T
692         else:
693             raise ValueError("Quantile simulations has only to be Linear or NonLinear.")
694         #
695         if YfQ is None:
696             YfQ = Yr
697             if selfA._toStore("SampledStateForQuantiles"): EXr = numpy.ravel(Xr)
698         else:
699             YfQ = numpy.hstack((YfQ,Yr))
700             if selfA._toStore("SampledStateForQuantiles"): EXr = numpy.vstack((EXr,numpy.ravel(Xr)))
701     #
702     # Extraction des quantiles
703     YfQ.sort(axis=-1)
704     YQ = None
705     for quantile in selfA._parameters["Quantiles"]:
706         if not (0. <= float(quantile) <= 1.): continue
707         indice = int(nbsamples * float(quantile) - 1./nbsamples)
708         if YQ is None: YQ = YfQ[:,indice]
709         else:          YQ = numpy.hstack((YQ,YfQ[:,indice]))
710     selfA.StoredVariables["SimulationQuantiles"].store( YQ )
711     if selfA._toStore("SampledStateForQuantiles"):
712         selfA.StoredVariables["SampledStateForQuantiles"].store( EXr.T )
713     #
714     return 0
715
716 # ==============================================================================
717 def enks(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, VariantM="EnKS16-KalmanFilterFormula"):
718     """
719     EnKS
720     """
721     #
722     # Opérateurs
723     H = HO["Direct"].appliedControledFormTo
724     #
725     if selfA._parameters["EstimationOf"] == "State":
726         M = EM["Direct"].appliedControledFormTo
727     #
728     if CM is not None and "Tangent" in CM and U is not None:
729         Cm = CM["Tangent"].asMatrix(Xb)
730     else:
731         Cm = None
732     #
733     # Précalcul des inversions de B et R
734     RIdemi = R.sqrtmI()
735     #
736     # Durée d'observation et tailles
737     LagL = selfA._parameters["SmootherLagL"]
738     if (not hasattr(Y,"store")) or (not hasattr(Y,"stepnumber")):
739         raise ValueError("Fixed-lag smoother requires a series of observation")
740     if Y.stepnumber() < LagL:
741         raise ValueError("Fixed-lag smoother requires a series of observation greater then the lag L")
742     duration = Y.stepnumber()
743     __p = numpy.cumprod(Y.shape())[-1]
744     __n = Xb.size
745     __m = selfA._parameters["NumberOfMembers"]
746     #
747     if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
748         selfA.StoredVariables["Analysis"].store( Xb )
749         if selfA._toStore("APosterioriCovariance"):
750             if hasattr(B,"asfullmatrix"):
751                 selfA.StoredVariables["APosterioriCovariance"].store( B.asfullmatrix(__n) )
752             else:
753                 selfA.StoredVariables["APosterioriCovariance"].store( B )
754     #
755     # Calcul direct initial (on privilégie la mémorisation au recalcul)
756     __seed = numpy.random.get_state()
757     selfB = copy.deepcopy(selfA)
758     selfB._parameters["StoreSupplementaryCalculations"] = ["CurrentEnsembleState"]
759     if VariantM == "EnKS16-KalmanFilterFormula":
760         etkf(selfB, Xb, Y, U, HO, EM, CM, R, B, Q, VariantM = "KalmanFilterFormula")
761     else:
762         raise ValueError("VariantM has to be chosen in the authorized methods list.")
763     if LagL > 0:
764         EL  = selfB.StoredVariables["CurrentEnsembleState"][LagL-1]
765     else:
766         EL = EnsembleOfBackgroundPerturbations( Xb, None, __m ) # Cf. etkf
767     selfA._parameters["SetSeed"] = numpy.random.set_state(__seed)
768     #
769     for step in range(LagL,duration-1):
770         #
771         sEL = selfB.StoredVariables["CurrentEnsembleState"][step+1-LagL:step+1]
772         sEL.append(None)
773         #
774         if hasattr(Y,"store"):
775             Ynpu = numpy.ravel( Y[step+1] ).reshape((__p,1))
776         else:
777             Ynpu = numpy.ravel( Y ).reshape((__p,1))
778         #
779         if U is not None:
780             if hasattr(U,"store") and len(U)>1:
781                 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
782             elif hasattr(U,"store") and len(U)==1:
783                 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
784             else:
785                 Un = numpy.asmatrix(numpy.ravel( U )).T
786         else:
787             Un = None
788         #
789         #--------------------------
790         if VariantM == "EnKS16-KalmanFilterFormula":
791             if selfA._parameters["EstimationOf"] == "State": # Forecast
792                 EL = M( [(EL[:,i], Un) for i in range(__m)],
793                     argsAsSerie = True,
794                     returnSerieAsArrayMatrix = True )
795                 EL = EnsemblePerturbationWithGivenCovariance( EL, Q )
796                 EZ = H( [(EL[:,i], Un) for i in range(__m)],
797                     argsAsSerie = True,
798                     returnSerieAsArrayMatrix = True )
799                 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
800                     Cm = Cm.reshape(__n,Un.size) # ADAO & check shape
801                     EZ = EZ + Cm * Un
802             elif selfA._parameters["EstimationOf"] == "Parameters":
803                 # --- > Par principe, M = Id, Q = 0
804                 EZ = H( [(EL[:,i], Un) for i in range(__m)],
805                     argsAsSerie = True,
806                     returnSerieAsArrayMatrix = True )
807             #
808             vEm   = EL.mean(axis=1, dtype=mfp).astype('float').reshape((__n,1))
809             vZm   = EZ.mean(axis=1, dtype=mfp).astype('float').reshape((__p,1))
810             #
811             mS    = RIdemi @ EnsembleOfAnomalies( EZ, vZm, 1./math.sqrt(__m-1) )
812             mS    = mS.reshape((-1,__m)) # Pour dimension 1
813             delta = RIdemi @ ( Ynpu - vZm )
814             mT    = numpy.linalg.inv( numpy.identity(__m) + mS.T @ mS )
815             vw    = mT @ mS.T @ delta
816             #
817             Tdemi = numpy.real(scipy.linalg.sqrtm(mT))
818             mU    = numpy.identity(__m)
819             wTU   = (vw.reshape((__m,1)) + math.sqrt(__m-1) * Tdemi @ mU)
820             #
821             EX    = EnsembleOfAnomalies( EL, vEm, 1./math.sqrt(__m-1) )
822             EL    = vEm + EX @ wTU
823             #
824             sEL[LagL] = EL
825             for irl in range(LagL): # Lissage des L précédentes analysis
826                 vEm = sEL[irl].mean(axis=1, dtype=mfp).astype('float').reshape((__n,1))
827                 EX = EnsembleOfAnomalies( sEL[irl], vEm, 1./math.sqrt(__m-1) )
828                 sEL[irl] = vEm + EX @ wTU
829             #
830             # Conservation de l'analyse retrospective d'ordre 0 avant rotation
831             Xa = sEL[0].mean(axis=1, dtype=mfp).astype('float').reshape((__n,1))
832             if selfA._toStore("APosterioriCovariance"):
833                 EXn = sEL[0]
834             #
835             for irl in range(LagL):
836                 sEL[irl] = sEL[irl+1]
837             sEL[LagL] = None
838         #--------------------------
839         else:
840             raise ValueError("VariantM has to be chosen in the authorized methods list.")
841         #
842         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
843         # ---> avec analysis
844         selfA.StoredVariables["Analysis"].store( Xa )
845         if selfA._toStore("APosterioriCovariance"):
846             selfA.StoredVariables["APosterioriCovariance"].store( EnsembleErrorCovariance(EXn) )
847     #
848     # Stockage des dernières analyses incomplètement remises à jour
849     for irl in range(LagL):
850         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
851         Xa = sEL[irl].mean(axis=1, dtype=mfp).astype('float').reshape((__n,1))
852         selfA.StoredVariables["Analysis"].store( Xa )
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
860     """
861     if selfA._parameters["EstimationOf"] == "Parameters":
862         selfA._parameters["StoreInternalVariables"] = True
863     #
864     # Opérateurs
865     H = HO["Direct"].appliedControledFormTo
866     #
867     if selfA._parameters["EstimationOf"] == "State":
868         M = EM["Direct"].appliedControledFormTo
869     #
870     if CM is not None and "Tangent" in CM and U is not None:
871         Cm = CM["Tangent"].asMatrix(Xb)
872     else:
873         Cm = None
874     #
875     # Durée d'observation et tailles
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     if selfA._parameters["StoreInternalVariables"] \
885         or selfA._toStore("CostFunctionJ") \
886         or selfA._toStore("CostFunctionJb") \
887         or selfA._toStore("CostFunctionJo") \
888         or selfA._toStore("CurrentOptimum") \
889         or selfA._toStore("APosterioriCovariance"):
890         BI = B.getI()
891         RI = R.getI()
892     elif VariantM != "KalmanFilterFormula":
893         RI = R.getI()
894     if VariantM == "KalmanFilterFormula":
895         RIdemi = R.sqrtmI()
896     #
897     __n = Xb.size
898     __m = selfA._parameters["NumberOfMembers"]
899     #
900     if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
901         Xn = EnsembleOfBackgroundPerturbations( Xb, None, __m )
902         selfA.StoredVariables["Analysis"].store( Xb )
903         if selfA._toStore("APosterioriCovariance"):
904             if hasattr(B,"asfullmatrix"):
905                 selfA.StoredVariables["APosterioriCovariance"].store( B.asfullmatrix(__n) )
906             else:
907                 selfA.StoredVariables["APosterioriCovariance"].store( B )
908         selfA._setInternalState("seed", numpy.random.get_state())
909     elif selfA._parameters["nextStep"]:
910         Xn = selfA._getInternalState("Xn")
911     #
912     previousJMinimum = numpy.finfo(float).max
913     #
914     for step in range(duration-1):
915         numpy.random.set_state(selfA._getInternalState("seed"))
916         if hasattr(Y,"store"):
917             Ynpu = numpy.ravel( Y[step+1] ).reshape((__p,1))
918         else:
919             Ynpu = numpy.ravel( Y ).reshape((__p,1))
920         #
921         if U is not None:
922             if hasattr(U,"store") and len(U)>1:
923                 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
924             elif hasattr(U,"store") and len(U)==1:
925                 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
926             else:
927                 Un = numpy.asmatrix(numpy.ravel( U )).T
928         else:
929             Un = None
930         #
931         if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
932             Xn = CovarianceInflation( Xn,
933                 selfA._parameters["InflationType"],
934                 selfA._parameters["InflationFactor"],
935                 )
936         #
937         if selfA._parameters["EstimationOf"] == "State": # Forecast + Q and observation of forecast
938             EMX = M( [(Xn[:,i], Un) for i in range(__m)],
939                 argsAsSerie = True,
940                 returnSerieAsArrayMatrix = True )
941             Xn_predicted = EnsemblePerturbationWithGivenCovariance( EMX, Q )
942             HX_predicted = H( [(Xn_predicted[:,i], Un) for i in range(__m)],
943                 argsAsSerie = True,
944                 returnSerieAsArrayMatrix = True )
945             if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
946                 Cm = Cm.reshape(__n,Un.size) # ADAO & check shape
947                 Xn_predicted = Xn_predicted + Cm * Un
948         elif selfA._parameters["EstimationOf"] == "Parameters": # Observation of forecast
949             # --- > Par principe, M = Id, Q = 0
950             Xn_predicted = EMX = Xn
951             HX_predicted = H( [(Xn_predicted[:,i], Un) for i in range(__m)],
952                 argsAsSerie = True,
953                 returnSerieAsArrayMatrix = True )
954         #
955         # Mean of forecast and observation of forecast
956         Xfm  = Xn_predicted.mean(axis=1, dtype=mfp).astype('float').reshape((__n,1))
957         Hfm  = HX_predicted.mean(axis=1, dtype=mfp).astype('float').reshape((__p,1))
958         #
959         # Anomalies
960         EaX   = EnsembleOfAnomalies( Xn_predicted, Xfm )
961         EaHX  = EnsembleOfAnomalies( HX_predicted, Hfm)
962         #
963         #--------------------------
964         if VariantM == "KalmanFilterFormula":
965             mS    = RIdemi * EaHX / math.sqrt(__m-1)
966             mS    = mS.reshape((-1,__m)) # Pour dimension 1
967             delta = RIdemi * ( Ynpu - Hfm )
968             mT    = numpy.linalg.inv( numpy.identity(__m) + mS.T @ mS )
969             vw    = mT @ mS.T @ delta
970             #
971             Tdemi = numpy.real(scipy.linalg.sqrtm(mT))
972             mU    = numpy.identity(__m)
973             #
974             EaX   = EaX / math.sqrt(__m-1)
975             Xn    = Xfm + EaX @ ( vw.reshape((__m,1)) + math.sqrt(__m-1) * Tdemi @ mU )
976         #--------------------------
977         elif VariantM == "Variational":
978             HXfm = H((Xfm[:,None], Un)) # Eventuellement Hfm
979             def CostFunction(w):
980                 _A  = Ynpu - HXfm.reshape((__p,1)) - (EaHX @ w).reshape((__p,1))
981                 _Jo = 0.5 * _A.T @ (RI * _A)
982                 _Jb = 0.5 * (__m-1) * w.T @ w
983                 _J  = _Jo + _Jb
984                 return float(_J)
985             def GradientOfCostFunction(w):
986                 _A  = Ynpu - HXfm.reshape((__p,1)) - (EaHX @ w).reshape((__p,1))
987                 _GardJo = - EaHX.T @ (RI * _A)
988                 _GradJb = (__m-1) * w.reshape((__m,1))
989                 _GradJ  = _GardJo + _GradJb
990                 return numpy.ravel(_GradJ)
991             vw = scipy.optimize.fmin_cg(
992                 f           = CostFunction,
993                 x0          = numpy.zeros(__m),
994                 fprime      = GradientOfCostFunction,
995                 args        = (),
996                 disp        = False,
997                 )
998             #
999             Hto = EaHX.T @ (RI * EaHX).reshape((-1,__m))
1000             Htb = (__m-1) * numpy.identity(__m)
1001             Hta = Hto + Htb
1002             #
1003             Pta = numpy.linalg.inv( Hta )
1004             EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1005             #
1006             Xn  = Xfm + EaX @ (vw[:,None] + EWa)
1007         #--------------------------
1008         elif VariantM == "FiniteSize11": # Jauge Boc2011
1009             HXfm = H((Xfm[:,None], Un)) # Eventuellement Hfm
1010             def CostFunction(w):
1011                 _A  = Ynpu - HXfm.reshape((__p,1)) - (EaHX @ w).reshape((__p,1))
1012                 _Jo = 0.5 * _A.T @ (RI * _A)
1013                 _Jb = 0.5 * __m * math.log(1 + 1/__m + w.T @ w)
1014                 _J  = _Jo + _Jb
1015                 return float(_J)
1016             def GradientOfCostFunction(w):
1017                 _A  = Ynpu - HXfm.reshape((__p,1)) - (EaHX @ w).reshape((__p,1))
1018                 _GardJo = - EaHX.T @ (RI * _A)
1019                 _GradJb = __m * w.reshape((__m,1)) / (1 + 1/__m + w.T @ w)
1020                 _GradJ  = _GardJo + _GradJb
1021                 return numpy.ravel(_GradJ)
1022             vw = scipy.optimize.fmin_cg(
1023                 f           = CostFunction,
1024                 x0          = numpy.zeros(__m),
1025                 fprime      = GradientOfCostFunction,
1026                 args        = (),
1027                 disp        = False,
1028                 )
1029             #
1030             Hto = EaHX.T @ (RI * EaHX).reshape((-1,__m))
1031             Htb = __m * \
1032                 ( (1 + 1/__m + vw.T @ vw) * numpy.identity(__m) - 2 * vw @ vw.T ) \
1033                 / (1 + 1/__m + vw.T @ vw)**2
1034             Hta = Hto + Htb
1035             #
1036             Pta = numpy.linalg.inv( Hta )
1037             EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1038             #
1039             Xn  = Xfm + EaX @ (vw.reshape((__m,1)) + EWa)
1040         #--------------------------
1041         elif VariantM == "FiniteSize15": # Jauge Boc2015
1042             HXfm = H((Xfm[:,None], Un)) # Eventuellement Hfm
1043             def CostFunction(w):
1044                 _A  = Ynpu - HXfm.reshape((__p,1)) - (EaHX @ w).reshape((__p,1))
1045                 _Jo = 0.5 * _A.T * RI * _A
1046                 _Jb = 0.5 * (__m+1) * math.log(1 + 1/__m + w.T @ w)
1047                 _J  = _Jo + _Jb
1048                 return float(_J)
1049             def GradientOfCostFunction(w):
1050                 _A  = Ynpu - HXfm.reshape((__p,1)) - (EaHX @ w).reshape((__p,1))
1051                 _GardJo = - EaHX.T @ (RI * _A)
1052                 _GradJb = (__m+1) * w.reshape((__m,1)) / (1 + 1/__m + w.T @ w)
1053                 _GradJ  = _GardJo + _GradJb
1054                 return numpy.ravel(_GradJ)
1055             vw = scipy.optimize.fmin_cg(
1056                 f           = CostFunction,
1057                 x0          = numpy.zeros(__m),
1058                 fprime      = GradientOfCostFunction,
1059                 args        = (),
1060                 disp        = False,
1061                 )
1062             #
1063             Hto = EaHX.T @ (RI * EaHX).reshape((-1,__m))
1064             Htb = (__m+1) * \
1065                 ( (1 + 1/__m + vw.T @ vw) * numpy.identity(__m) - 2 * vw @ vw.T ) \
1066                 / (1 + 1/__m + vw.T @ vw)**2
1067             Hta = Hto + Htb
1068             #
1069             Pta = numpy.linalg.inv( Hta )
1070             EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1071             #
1072             Xn  = Xfm + EaX @ (vw.reshape((__m,1)) + EWa)
1073         #--------------------------
1074         elif VariantM == "FiniteSize16": # Jauge Boc2016
1075             HXfm = H((Xfm[:,None], Un)) # Eventuellement Hfm
1076             def CostFunction(w):
1077                 _A  = Ynpu - HXfm.reshape((__p,1)) - (EaHX @ w).reshape((__p,1))
1078                 _Jo = 0.5 * _A.T @ (RI * _A)
1079                 _Jb = 0.5 * (__m+1) * math.log(1 + 1/__m + w.T @ w / (__m-1))
1080                 _J  = _Jo + _Jb
1081                 return float(_J)
1082             def GradientOfCostFunction(w):
1083                 _A  = Ynpu - HXfm.reshape((__p,1)) - (EaHX @ w).reshape((__p,1))
1084                 _GardJo = - EaHX.T @ (RI * _A)
1085                 _GradJb = ((__m+1) / (__m-1)) * w.reshape((__m,1)) / (1 + 1/__m + w.T @ w / (__m-1))
1086                 _GradJ  = _GardJo + _GradJb
1087                 return numpy.ravel(_GradJ)
1088             vw = scipy.optimize.fmin_cg(
1089                 f           = CostFunction,
1090                 x0          = numpy.zeros(__m),
1091                 fprime      = GradientOfCostFunction,
1092                 args        = (),
1093                 disp        = False,
1094                 )
1095             #
1096             Hto = EaHX.T @ (RI * EaHX).reshape((-1,__m))
1097             Htb = ((__m+1) / (__m-1)) * \
1098                 ( (1 + 1/__m + vw.T @ vw / (__m-1)) * numpy.identity(__m) - 2 * vw @ vw.T / (__m-1) ) \
1099                 / (1 + 1/__m + vw.T @ vw / (__m-1))**2
1100             Hta = Hto + Htb
1101             #
1102             Pta = numpy.linalg.inv( Hta )
1103             EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1104             #
1105             Xn  = Xfm + EaX @ (vw[:,None] + EWa)
1106         #--------------------------
1107         else:
1108             raise ValueError("VariantM has to be chosen in the authorized methods list.")
1109         #
1110         if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
1111             Xn = CovarianceInflation( Xn,
1112                 selfA._parameters["InflationType"],
1113                 selfA._parameters["InflationFactor"],
1114                 )
1115         #
1116         Xa = Xn.mean(axis=1, dtype=mfp).astype('float').reshape((__n,1))
1117         #--------------------------
1118         selfA._setInternalState("Xn", Xn)
1119         selfA._setInternalState("seed", numpy.random.get_state())
1120         #--------------------------
1121         #
1122         if selfA._parameters["StoreInternalVariables"] \
1123             or selfA._toStore("CostFunctionJ") \
1124             or selfA._toStore("CostFunctionJb") \
1125             or selfA._toStore("CostFunctionJo") \
1126             or selfA._toStore("APosterioriCovariance") \
1127             or selfA._toStore("InnovationAtCurrentAnalysis") \
1128             or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
1129             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1130             _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
1131             _Innovation = Ynpu - _HXa
1132         #
1133         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1134         # ---> avec analysis
1135         selfA.StoredVariables["Analysis"].store( Xa )
1136         if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
1137             selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
1138         if selfA._toStore("InnovationAtCurrentAnalysis"):
1139             selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
1140         # ---> avec current state
1141         if selfA._parameters["StoreInternalVariables"] \
1142             or selfA._toStore("CurrentState"):
1143             selfA.StoredVariables["CurrentState"].store( Xn )
1144         if selfA._toStore("ForecastState"):
1145             selfA.StoredVariables["ForecastState"].store( EMX )
1146         if selfA._toStore("ForecastCovariance"):
1147             selfA.StoredVariables["ForecastCovariance"].store( EnsembleErrorCovariance(EMX) )
1148         if selfA._toStore("BMA"):
1149             selfA.StoredVariables["BMA"].store( EMX - 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             selfA.StoredVariables["APosterioriCovariance"].store( EnsembleErrorCovariance(Xn) )
1190         if selfA._parameters["EstimationOf"] == "Parameters" \
1191             and J < previousJMinimum:
1192             previousJMinimum    = J
1193             XaMin               = Xa
1194             if selfA._toStore("APosterioriCovariance"):
1195                 covarianceXaMin = selfA.StoredVariables["APosterioriCovariance"][-1]
1196         # ---> Pour les smoothers
1197         if selfA._toStore("CurrentEnsembleState"):
1198             selfA.StoredVariables["CurrentEnsembleState"].store( Xn )
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 exkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q):
1214     """
1215     Extended Kalman Filter
1216     """
1217     if selfA._parameters["EstimationOf"] == "Parameters":
1218         selfA._parameters["StoreInternalVariables"] = True
1219     #
1220     # Opérateurs
1221     H = HO["Direct"].appliedControledFormTo
1222     #
1223     if selfA._parameters["EstimationOf"] == "State":
1224         M = EM["Direct"].appliedControledFormTo
1225     #
1226     if CM is not None and "Tangent" in CM and U is not None:
1227         Cm = CM["Tangent"].asMatrix(Xb)
1228     else:
1229         Cm = None
1230     #
1231     # Durée d'observation et tailles
1232     if hasattr(Y,"stepnumber"):
1233         duration = Y.stepnumber()
1234         __p = numpy.cumprod(Y.shape())[-1]
1235     else:
1236         duration = 2
1237         __p = numpy.array(Y).size
1238     #
1239     # Précalcul des inversions de B et R
1240     if selfA._parameters["StoreInternalVariables"] \
1241         or selfA._toStore("CostFunctionJ") \
1242         or selfA._toStore("CostFunctionJb") \
1243         or selfA._toStore("CostFunctionJo") \
1244         or selfA._toStore("CurrentOptimum") \
1245         or selfA._toStore("APosterioriCovariance"):
1246         BI = B.getI()
1247         RI = R.getI()
1248     #
1249     __n = Xb.size
1250     #
1251     if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
1252         Xn = Xb
1253         Pn = B
1254         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1255         selfA.StoredVariables["Analysis"].store( Xb )
1256         if selfA._toStore("APosterioriCovariance"):
1257             if hasattr(B,"asfullmatrix"):
1258                 selfA.StoredVariables["APosterioriCovariance"].store( B.asfullmatrix(__n) )
1259             else:
1260                 selfA.StoredVariables["APosterioriCovariance"].store( B )
1261         selfA._setInternalState("seed", numpy.random.get_state())
1262     elif selfA._parameters["nextStep"]:
1263         Xn = selfA._getInternalState("Xn")
1264         Pn = selfA._getInternalState("Pn")
1265     #
1266     previousJMinimum = numpy.finfo(float).max
1267     #
1268     for step in range(duration-1):
1269         if hasattr(Y,"store"):
1270             Ynpu = numpy.ravel( Y[step+1] ).reshape((__p,1))
1271         else:
1272             Ynpu = numpy.ravel( Y ).reshape((__p,1))
1273         #
1274         Ht = HO["Tangent"].asMatrix(ValueForMethodForm = Xn)
1275         Ht = Ht.reshape(Ynpu.size,Xn.size) # ADAO & check shape
1276         Ha = HO["Adjoint"].asMatrix(ValueForMethodForm = Xn)
1277         Ha = Ha.reshape(Xn.size,Ynpu.size) # ADAO & check shape
1278         #
1279         if selfA._parameters["EstimationOf"] == "State":
1280             Mt = EM["Tangent"].asMatrix(ValueForMethodForm = Xn)
1281             Mt = Mt.reshape(Xn.size,Xn.size) # ADAO & check shape
1282             Ma = EM["Adjoint"].asMatrix(ValueForMethodForm = Xn)
1283             Ma = Ma.reshape(Xn.size,Xn.size) # ADAO & check shape
1284         #
1285         if U is not None:
1286             if hasattr(U,"store") and len(U)>1:
1287                 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
1288             elif hasattr(U,"store") and len(U)==1:
1289                 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
1290             else:
1291                 Un = numpy.asmatrix(numpy.ravel( U )).T
1292         else:
1293             Un = None
1294         #
1295         if selfA._parameters["EstimationOf"] == "State": # Forecast + Q and observation of forecast
1296             Xn_predicted = numpy.asmatrix(numpy.ravel( M( (Xn, Un) ) )).T
1297             if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
1298                 Cm = Cm.reshape(__n,Un.size) # ADAO & check shape
1299                 Xn_predicted = Xn_predicted + Cm * Un
1300             Pn_predicted = Q + Mt * Pn * Ma
1301         elif selfA._parameters["EstimationOf"] == "Parameters": # Observation of forecast
1302             # --- > Par principe, M = Id, Q = 0
1303             Xn_predicted = Xn
1304             Pn_predicted = Pn
1305         #
1306         if selfA._parameters["Bounds"] is not None and selfA._parameters["ConstrainedBy"] == "EstimateProjection":
1307             Xn_predicted = numpy.max(numpy.hstack((Xn_predicted,numpy.asmatrix(selfA._parameters["Bounds"])[:,0])),axis=1)
1308             Xn_predicted = numpy.min(numpy.hstack((Xn_predicted,numpy.asmatrix(selfA._parameters["Bounds"])[:,1])),axis=1)
1309         #
1310         if selfA._parameters["EstimationOf"] == "State":
1311             HX_predicted = numpy.asmatrix(numpy.ravel( H( (Xn_predicted, None) ) )).T
1312             _Innovation  = Ynpu - HX_predicted
1313         elif selfA._parameters["EstimationOf"] == "Parameters":
1314             HX_predicted = numpy.asmatrix(numpy.ravel( H( (Xn_predicted, Un) ) )).T
1315             _Innovation  = Ynpu - HX_predicted
1316             if Cm is not None and Un is not None: # Attention : si Cm est aussi dans H, doublon !
1317                 _Innovation = _Innovation - Cm * Un
1318         #
1319         Kn = Pn_predicted * Ha * numpy.linalg.inv(R + numpy.dot(Ht, Pn_predicted * Ha))
1320         Xn = Xn_predicted + Kn * _Innovation
1321         Pn = Pn_predicted - Kn * Ht * Pn_predicted
1322         #
1323         Xa = Xn # Pointeurs
1324         #--------------------------
1325         selfA._setInternalState("Xn", Xn)
1326         selfA._setInternalState("Pn", Pn)
1327         #--------------------------
1328         #
1329         if selfA._parameters["StoreInternalVariables"] \
1330             or selfA._toStore("CostFunctionJ") \
1331             or selfA._toStore("CostFunctionJb") \
1332             or selfA._toStore("CostFunctionJo") \
1333             or selfA._toStore("APosterioriCovariance") \
1334             or selfA._toStore("InnovationAtCurrentAnalysis") \
1335             or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
1336             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1337             _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
1338         #
1339         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1340         # ---> avec analysis
1341         selfA.StoredVariables["Analysis"].store( Xa )
1342         if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
1343             selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
1344         if selfA._toStore("InnovationAtCurrentAnalysis"):
1345             selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
1346         # ---> avec current state
1347         if selfA._parameters["StoreInternalVariables"] \
1348             or selfA._toStore("CurrentState"):
1349             selfA.StoredVariables["CurrentState"].store( Xn )
1350         if selfA._toStore("ForecastState"):
1351             selfA.StoredVariables["ForecastState"].store( Xn_predicted )
1352         if selfA._toStore("ForecastCovariance"):
1353             selfA.StoredVariables["ForecastCovariance"].store( Pn_predicted )
1354         if selfA._toStore("BMA"):
1355             selfA.StoredVariables["BMA"].store( Xn_predicted - Xa )
1356         if selfA._toStore("InnovationAtCurrentState"):
1357             selfA.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
1358         if selfA._toStore("SimulatedObservationAtCurrentState") \
1359             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1360             selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HX_predicted )
1361         # ---> autres
1362         if selfA._parameters["StoreInternalVariables"] \
1363             or selfA._toStore("CostFunctionJ") \
1364             or selfA._toStore("CostFunctionJb") \
1365             or selfA._toStore("CostFunctionJo") \
1366             or selfA._toStore("CurrentOptimum") \
1367             or selfA._toStore("APosterioriCovariance"):
1368             Jb  = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
1369             Jo  = float( 0.5 * _Innovation.T * RI * _Innovation )
1370             J   = Jb + Jo
1371             selfA.StoredVariables["CostFunctionJb"].store( Jb )
1372             selfA.StoredVariables["CostFunctionJo"].store( Jo )
1373             selfA.StoredVariables["CostFunctionJ" ].store( J )
1374             #
1375             if selfA._toStore("IndexOfOptimum") \
1376                 or selfA._toStore("CurrentOptimum") \
1377                 or selfA._toStore("CostFunctionJAtCurrentOptimum") \
1378                 or selfA._toStore("CostFunctionJbAtCurrentOptimum") \
1379                 or selfA._toStore("CostFunctionJoAtCurrentOptimum") \
1380                 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1381                 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
1382             if selfA._toStore("IndexOfOptimum"):
1383                 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
1384             if selfA._toStore("CurrentOptimum"):
1385                 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["Analysis"][IndexMin] )
1386             if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1387                 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"][IndexMin] )
1388             if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
1389                 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
1390             if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
1391                 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
1392             if selfA._toStore("CostFunctionJAtCurrentOptimum"):
1393                 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
1394         if selfA._toStore("APosterioriCovariance"):
1395             selfA.StoredVariables["APosterioriCovariance"].store( Pn )
1396         if selfA._parameters["EstimationOf"] == "Parameters" \
1397             and J < previousJMinimum:
1398             previousJMinimum    = J
1399             XaMin               = Xa
1400             if selfA._toStore("APosterioriCovariance"):
1401                 covarianceXaMin = selfA.StoredVariables["APosterioriCovariance"][-1]
1402     #
1403     # Stockage final supplémentaire de l'optimum en estimation de paramètres
1404     # ----------------------------------------------------------------------
1405     if selfA._parameters["EstimationOf"] == "Parameters":
1406         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1407         selfA.StoredVariables["Analysis"].store( XaMin )
1408         if selfA._toStore("APosterioriCovariance"):
1409             selfA.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
1410         if selfA._toStore("BMA"):
1411             selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
1412     #
1413     return 0
1414
1415 # ==============================================================================
1416 def ienkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, VariantM="IEnKF12",
1417     BnotT=False, _epsilon=1.e-3, _e=1.e-7, _jmax=15000):
1418     """
1419     Iterative EnKF
1420     """
1421     if selfA._parameters["EstimationOf"] == "Parameters":
1422         selfA._parameters["StoreInternalVariables"] = True
1423     #
1424     # Opérateurs
1425     H = HO["Direct"].appliedControledFormTo
1426     #
1427     if selfA._parameters["EstimationOf"] == "State":
1428         M = EM["Direct"].appliedControledFormTo
1429     #
1430     if CM is not None and "Tangent" in CM and U is not None:
1431         Cm = CM["Tangent"].asMatrix(Xb)
1432     else:
1433         Cm = None
1434     #
1435     # Durée d'observation et tailles
1436     if hasattr(Y,"stepnumber"):
1437         duration = Y.stepnumber()
1438         __p = numpy.cumprod(Y.shape())[-1]
1439     else:
1440         duration = 2
1441         __p = numpy.array(Y).size
1442     #
1443     # Précalcul des inversions de B et R
1444     if selfA._parameters["StoreInternalVariables"] \
1445         or selfA._toStore("CostFunctionJ") \
1446         or selfA._toStore("CostFunctionJb") \
1447         or selfA._toStore("CostFunctionJo") \
1448         or selfA._toStore("CurrentOptimum") \
1449         or selfA._toStore("APosterioriCovariance"):
1450         BI = B.getI()
1451     RI = R.getI()
1452     #
1453     __n = Xb.size
1454     __m = selfA._parameters["NumberOfMembers"]
1455     #
1456     if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
1457         if hasattr(B,"asfullmatrix"): Pn = B.asfullmatrix(__n)
1458         else:                         Pn = B
1459         Xn = EnsembleOfBackgroundPerturbations( Xb, Pn, __m )
1460         selfA.StoredVariables["Analysis"].store( Xb )
1461         if selfA._toStore("APosterioriCovariance"):
1462             if hasattr(B,"asfullmatrix"):
1463                 selfA.StoredVariables["APosterioriCovariance"].store( B.asfullmatrix(__n) )
1464             else:
1465                 selfA.StoredVariables["APosterioriCovariance"].store( B )
1466         selfA._setInternalState("seed", numpy.random.get_state())
1467     elif selfA._parameters["nextStep"]:
1468         Xn = selfA._getInternalState("Xn")
1469     #
1470     previousJMinimum = numpy.finfo(float).max
1471     #
1472     for step in range(duration-1):
1473         numpy.random.set_state(selfA._getInternalState("seed"))
1474         if hasattr(Y,"store"):
1475             Ynpu = numpy.ravel( Y[step+1] ).reshape((__p,1))
1476         else:
1477             Ynpu = numpy.ravel( Y ).reshape((__p,1))
1478         #
1479         if U is not None:
1480             if hasattr(U,"store") and len(U)>1:
1481                 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
1482             elif hasattr(U,"store") and len(U)==1:
1483                 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
1484             else:
1485                 Un = numpy.asmatrix(numpy.ravel( U )).T
1486         else:
1487             Un = None
1488         #
1489         if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
1490             Xn = CovarianceInflation( Xn,
1491                 selfA._parameters["InflationType"],
1492                 selfA._parameters["InflationFactor"],
1493                 )
1494         #
1495         #--------------------------
1496         if VariantM == "IEnKF12":
1497             Xfm = numpy.ravel(Xn.mean(axis=1, dtype=mfp).astype('float'))
1498             EaX = EnsembleOfAnomalies( Xn ) / math.sqrt(__m-1)
1499             __j = 0
1500             Deltaw = 1
1501             if not BnotT:
1502                 Ta  = numpy.identity(__m)
1503             vw  = numpy.zeros(__m)
1504             while numpy.linalg.norm(Deltaw) >= _e and __j <= _jmax:
1505                 vx1 = (Xfm + EaX @ vw).reshape((__n,1))
1506                 #
1507                 if BnotT:
1508                     E1 = vx1 + _epsilon * EaX
1509                 else:
1510                     E1 = vx1 + math.sqrt(__m-1) * EaX @ Ta
1511                 #
1512                 if selfA._parameters["EstimationOf"] == "State": # Forecast + Q
1513                     E2 = M( [(E1[:,i,numpy.newaxis], Un) for i in range(__m)],
1514                         argsAsSerie = True,
1515                         returnSerieAsArrayMatrix = True )
1516                 elif selfA._parameters["EstimationOf"] == "Parameters":
1517                     # --- > Par principe, M = Id
1518                     E2 = Xn
1519                 vx2 = E2.mean(axis=1, dtype=mfp).astype('float').reshape((__n,1))
1520                 vy1 = H((vx2, Un)).reshape((__p,1))
1521                 #
1522                 HE2 = H( [(E2[:,i,numpy.newaxis], Un) for i in range(__m)],
1523                     argsAsSerie = True,
1524                     returnSerieAsArrayMatrix = True )
1525                 vy2 = HE2.mean(axis=1, dtype=mfp).astype('float').reshape((__p,1))
1526                 #
1527                 if BnotT:
1528                     EaY = (HE2 - vy2) / _epsilon
1529                 else:
1530                     EaY = ( (HE2 - vy2) @ numpy.linalg.inv(Ta) ) / math.sqrt(__m-1)
1531                 #
1532                 GradJ = numpy.ravel(vw[:,None] - EaY.transpose() @ (RI * ( Ynpu - vy1 )))
1533                 mH = numpy.identity(__m) + EaY.transpose() @ (RI * EaY).reshape((-1,__m))
1534                 Deltaw = - numpy.linalg.solve(mH,GradJ)
1535                 #
1536                 vw = vw + Deltaw
1537                 #
1538                 if not BnotT:
1539                     Ta = numpy.real(scipy.linalg.sqrtm(numpy.linalg.inv( mH )))
1540                 #
1541                 __j = __j + 1
1542             #
1543             A2 = EnsembleOfAnomalies( E2 )
1544             #
1545             if BnotT:
1546                 Ta = numpy.real(scipy.linalg.sqrtm(numpy.linalg.inv( mH )))
1547                 A2 = math.sqrt(__m-1) * A2 @ Ta / _epsilon
1548             #
1549             Xn = vx2 + A2
1550         #--------------------------
1551         else:
1552             raise ValueError("VariantM has to be chosen in the authorized methods list.")
1553         #
1554         if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
1555             Xn = CovarianceInflation( Xn,
1556                 selfA._parameters["InflationType"],
1557                 selfA._parameters["InflationFactor"],
1558                 )
1559         #
1560         Xa = Xn.mean(axis=1, dtype=mfp).astype('float').reshape((__n,1))
1561         #--------------------------
1562         selfA._setInternalState("Xn", Xn)
1563         selfA._setInternalState("seed", numpy.random.get_state())
1564         #--------------------------
1565         #
1566         if selfA._parameters["StoreInternalVariables"] \
1567             or selfA._toStore("CostFunctionJ") \
1568             or selfA._toStore("CostFunctionJb") \
1569             or selfA._toStore("CostFunctionJo") \
1570             or selfA._toStore("APosterioriCovariance") \
1571             or selfA._toStore("InnovationAtCurrentAnalysis") \
1572             or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
1573             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1574             _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
1575             _Innovation = Ynpu - _HXa
1576         #
1577         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1578         # ---> avec analysis
1579         selfA.StoredVariables["Analysis"].store( Xa )
1580         if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
1581             selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
1582         if selfA._toStore("InnovationAtCurrentAnalysis"):
1583             selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
1584         # ---> avec current state
1585         if selfA._parameters["StoreInternalVariables"] \
1586             or selfA._toStore("CurrentState"):
1587             selfA.StoredVariables["CurrentState"].store( Xn )
1588         if selfA._toStore("ForecastState"):
1589             selfA.StoredVariables["ForecastState"].store( E2 )
1590         if selfA._toStore("ForecastCovariance"):
1591             selfA.StoredVariables["ForecastCovariance"].store( EnsembleErrorCovariance(E2) )
1592         if selfA._toStore("BMA"):
1593             selfA.StoredVariables["BMA"].store( E2 - Xa )
1594         if selfA._toStore("InnovationAtCurrentState"):
1595             selfA.StoredVariables["InnovationAtCurrentState"].store( - HE2 + Ynpu )
1596         if selfA._toStore("SimulatedObservationAtCurrentState") \
1597             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1598             selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HE2 )
1599         # ---> autres
1600         if selfA._parameters["StoreInternalVariables"] \
1601             or selfA._toStore("CostFunctionJ") \
1602             or selfA._toStore("CostFunctionJb") \
1603             or selfA._toStore("CostFunctionJo") \
1604             or selfA._toStore("CurrentOptimum") \
1605             or selfA._toStore("APosterioriCovariance"):
1606             Jb  = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
1607             Jo  = float( 0.5 * _Innovation.T * RI * _Innovation )
1608             J   = Jb + Jo
1609             selfA.StoredVariables["CostFunctionJb"].store( Jb )
1610             selfA.StoredVariables["CostFunctionJo"].store( Jo )
1611             selfA.StoredVariables["CostFunctionJ" ].store( J )
1612             #
1613             if selfA._toStore("IndexOfOptimum") \
1614                 or selfA._toStore("CurrentOptimum") \
1615                 or selfA._toStore("CostFunctionJAtCurrentOptimum") \
1616                 or selfA._toStore("CostFunctionJbAtCurrentOptimum") \
1617                 or selfA._toStore("CostFunctionJoAtCurrentOptimum") \
1618                 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1619                 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
1620             if selfA._toStore("IndexOfOptimum"):
1621                 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
1622             if selfA._toStore("CurrentOptimum"):
1623                 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["Analysis"][IndexMin] )
1624             if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1625                 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"][IndexMin] )
1626             if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
1627                 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
1628             if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
1629                 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
1630             if selfA._toStore("CostFunctionJAtCurrentOptimum"):
1631                 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
1632         if selfA._toStore("APosterioriCovariance"):
1633             selfA.StoredVariables["APosterioriCovariance"].store( EnsembleErrorCovariance(Xn) )
1634         if selfA._parameters["EstimationOf"] == "Parameters" \
1635             and J < previousJMinimum:
1636             previousJMinimum    = J
1637             XaMin               = Xa
1638             if selfA._toStore("APosterioriCovariance"):
1639                 covarianceXaMin = selfA.StoredVariables["APosterioriCovariance"][-1]
1640     #
1641     # Stockage final supplémentaire de l'optimum en estimation de paramètres
1642     # ----------------------------------------------------------------------
1643     if selfA._parameters["EstimationOf"] == "Parameters":
1644         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1645         selfA.StoredVariables["Analysis"].store( XaMin )
1646         if selfA._toStore("APosterioriCovariance"):
1647             selfA.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
1648         if selfA._toStore("BMA"):
1649             selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
1650     #
1651     return 0
1652
1653 # ==============================================================================
1654 def incr3dvar(selfA, Xb, Y, U, HO, EM, CM, R, B, Q):
1655     """
1656     3DVAR incrémental
1657     """
1658     #
1659     # Initialisations
1660     # ---------------
1661     #
1662     # Opérateur non-linéaire pour la boucle externe
1663     Hm = HO["Direct"].appliedTo
1664     #
1665     # Précalcul des inversions de B et R
1666     BI = B.getI()
1667     RI = R.getI()
1668     #
1669     # Point de démarrage de l'optimisation
1670     Xini = selfA._parameters["InitializationPoint"]
1671     #
1672     HXb = numpy.asmatrix(numpy.ravel( Hm( Xb ) )).T
1673     Innovation = Y - HXb
1674     #
1675     # Outer Loop
1676     # ----------
1677     iOuter = 0
1678     J      = 1./mpr
1679     DeltaJ = 1./mpr
1680     Xr     = Xini.reshape((-1,1))
1681     while abs(DeltaJ) >= selfA._parameters["CostDecrementTolerance"] and iOuter <= selfA._parameters["MaximumNumberOfSteps"]:
1682         #
1683         # Inner Loop
1684         # ----------
1685         Ht = HO["Tangent"].asMatrix(Xr)
1686         Ht = Ht.reshape(Y.size,Xr.size) # ADAO & check shape
1687         #
1688         # Définition de la fonction-coût
1689         # ------------------------------
1690         def CostFunction(dx):
1691             _dX  = numpy.asmatrix(numpy.ravel( dx )).T
1692             if selfA._parameters["StoreInternalVariables"] or \
1693                 selfA._toStore("CurrentState") or \
1694                 selfA._toStore("CurrentOptimum"):
1695                 selfA.StoredVariables["CurrentState"].store( Xb + _dX )
1696             _HdX = Ht * _dX
1697             _HdX = numpy.asmatrix(numpy.ravel( _HdX )).T
1698             _dInnovation = Innovation - _HdX
1699             if selfA._toStore("SimulatedObservationAtCurrentState") or \
1700                 selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1701                 selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HXb + _HdX )
1702             if selfA._toStore("InnovationAtCurrentState"):
1703                 selfA.StoredVariables["InnovationAtCurrentState"].store( _dInnovation )
1704             #
1705             Jb  = float( 0.5 * _dX.T * BI * _dX )
1706             Jo  = float( 0.5 * _dInnovation.T * RI * _dInnovation )
1707             J   = Jb + Jo
1708             #
1709             selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["CostFunctionJ"]) )
1710             selfA.StoredVariables["CostFunctionJb"].store( Jb )
1711             selfA.StoredVariables["CostFunctionJo"].store( Jo )
1712             selfA.StoredVariables["CostFunctionJ" ].store( J )
1713             if selfA._toStore("IndexOfOptimum") or \
1714                 selfA._toStore("CurrentOptimum") or \
1715                 selfA._toStore("CostFunctionJAtCurrentOptimum") or \
1716                 selfA._toStore("CostFunctionJbAtCurrentOptimum") or \
1717                 selfA._toStore("CostFunctionJoAtCurrentOptimum") or \
1718                 selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1719                 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
1720             if selfA._toStore("IndexOfOptimum"):
1721                 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
1722             if selfA._toStore("CurrentOptimum"):
1723                 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["CurrentState"][IndexMin] )
1724             if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1725                 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] )
1726             if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
1727                 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
1728             if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
1729                 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
1730             if selfA._toStore("CostFunctionJAtCurrentOptimum"):
1731                 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
1732             return J
1733         #
1734         def GradientOfCostFunction(dx):
1735             _dX          = numpy.asmatrix(numpy.ravel( dx )).T
1736             _HdX         = Ht * _dX
1737             _HdX         = numpy.asmatrix(numpy.ravel( _HdX )).T
1738             _dInnovation = Innovation - _HdX
1739             GradJb       = BI * _dX
1740             GradJo       = - Ht.T @ (RI * _dInnovation)
1741             GradJ        = numpy.ravel( GradJb ) + numpy.ravel( GradJo )
1742             return GradJ
1743         #
1744         # Minimisation de la fonctionnelle
1745         # --------------------------------
1746         nbPreviousSteps = selfA.StoredVariables["CostFunctionJ"].stepnumber()
1747         #
1748         if selfA._parameters["Minimizer"] == "LBFGSB":
1749             # Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
1750             if "0.19" <= scipy.version.version <= "1.1.0":
1751                 import lbfgsbhlt as optimiseur
1752             else:
1753                 import scipy.optimize as optimiseur
1754             Minimum, J_optimal, Informations = optimiseur.fmin_l_bfgs_b(
1755                 func        = CostFunction,
1756                 x0          = numpy.zeros(Xini.size),
1757                 fprime      = GradientOfCostFunction,
1758                 args        = (),
1759                 bounds      = selfA._parameters["Bounds"],
1760                 maxfun      = selfA._parameters["MaximumNumberOfSteps"]-1,
1761                 factr       = selfA._parameters["CostDecrementTolerance"]*1.e14,
1762                 pgtol       = selfA._parameters["ProjectedGradientTolerance"],
1763                 iprint      = selfA._parameters["optiprint"],
1764                 )
1765             nfeval = Informations['funcalls']
1766             rc     = Informations['warnflag']
1767         elif selfA._parameters["Minimizer"] == "TNC":
1768             Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
1769                 func        = CostFunction,
1770                 x0          = numpy.zeros(Xini.size),
1771                 fprime      = GradientOfCostFunction,
1772                 args        = (),
1773                 bounds      = selfA._parameters["Bounds"],
1774                 maxfun      = selfA._parameters["MaximumNumberOfSteps"],
1775                 pgtol       = selfA._parameters["ProjectedGradientTolerance"],
1776                 ftol        = selfA._parameters["CostDecrementTolerance"],
1777                 messages    = selfA._parameters["optmessages"],
1778                 )
1779         elif selfA._parameters["Minimizer"] == "CG":
1780             Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
1781                 f           = CostFunction,
1782                 x0          = numpy.zeros(Xini.size),
1783                 fprime      = GradientOfCostFunction,
1784                 args        = (),
1785                 maxiter     = selfA._parameters["MaximumNumberOfSteps"],
1786                 gtol        = selfA._parameters["GradientNormTolerance"],
1787                 disp        = selfA._parameters["optdisp"],
1788                 full_output = True,
1789                 )
1790         elif selfA._parameters["Minimizer"] == "NCG":
1791             Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
1792                 f           = CostFunction,
1793                 x0          = numpy.zeros(Xini.size),
1794                 fprime      = GradientOfCostFunction,
1795                 args        = (),
1796                 maxiter     = selfA._parameters["MaximumNumberOfSteps"],
1797                 avextol     = selfA._parameters["CostDecrementTolerance"],
1798                 disp        = selfA._parameters["optdisp"],
1799                 full_output = True,
1800                 )
1801         elif selfA._parameters["Minimizer"] == "BFGS":
1802             Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
1803                 f           = CostFunction,
1804                 x0          = numpy.zeros(Xini.size),
1805                 fprime      = GradientOfCostFunction,
1806                 args        = (),
1807                 maxiter     = selfA._parameters["MaximumNumberOfSteps"],
1808                 gtol        = selfA._parameters["GradientNormTolerance"],
1809                 disp        = selfA._parameters["optdisp"],
1810                 full_output = True,
1811                 )
1812         else:
1813             raise ValueError("Error in Minimizer name: %s"%selfA._parameters["Minimizer"])
1814         #
1815         IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
1816         MinJ     = selfA.StoredVariables["CostFunctionJ"][IndexMin]
1817         #
1818         if selfA._parameters["StoreInternalVariables"] or selfA._toStore("CurrentState"):
1819             Minimum = selfA.StoredVariables["CurrentState"][IndexMin]
1820             Minimum = numpy.asmatrix(numpy.ravel( Minimum )).T
1821         else:
1822             Minimum = Xb + numpy.asmatrix(numpy.ravel( Minimum )).T
1823         #
1824         Xr     = Minimum
1825         DeltaJ = selfA.StoredVariables["CostFunctionJ" ][-1] - J
1826         iOuter = selfA.StoredVariables["CurrentIterationNumber"][-1]
1827     #
1828     # Obtention de l'analyse
1829     # ----------------------
1830     Xa = Xr
1831     #
1832     selfA.StoredVariables["Analysis"].store( Xa )
1833     #
1834     if selfA._toStore("OMA") or \
1835         selfA._toStore("SigmaObs2") or \
1836         selfA._toStore("SimulationQuantiles") or \
1837         selfA._toStore("SimulatedObservationAtOptimum"):
1838         if selfA._toStore("SimulatedObservationAtCurrentState"):
1839             HXa = selfA.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
1840         elif selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1841             HXa = selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
1842         else:
1843             HXa = Hm( Xa )
1844     #
1845     # Calcul de la covariance d'analyse
1846     # ---------------------------------
1847     if selfA._toStore("APosterioriCovariance") or \
1848         selfA._toStore("SimulationQuantiles") or \
1849         selfA._toStore("JacobianMatrixAtOptimum") or \
1850         selfA._toStore("KalmanGainAtOptimum"):
1851         HtM = HO["Tangent"].asMatrix(ValueForMethodForm = Xa)
1852         HtM = HtM.reshape(Y.size,Xa.size) # ADAO & check shape
1853     if selfA._toStore("APosterioriCovariance") or \
1854         selfA._toStore("SimulationQuantiles") or \
1855         selfA._toStore("KalmanGainAtOptimum"):
1856         HaM = HO["Adjoint"].asMatrix(ValueForMethodForm = Xa)
1857         HaM = HaM.reshape(Xa.size,Y.size) # ADAO & check shape
1858     if selfA._toStore("APosterioriCovariance") or \
1859         selfA._toStore("SimulationQuantiles"):
1860         HessienneI = []
1861         nb = Xa.size
1862         for i in range(nb):
1863             _ee    = numpy.matrix(numpy.zeros(nb)).T
1864             _ee[i] = 1.
1865             _HtEE  = numpy.dot(HtM,_ee)
1866             _HtEE  = numpy.asmatrix(numpy.ravel( _HtEE )).T
1867             HessienneI.append( numpy.ravel( BI*_ee + HaM * (RI * _HtEE) ) )
1868         HessienneI = numpy.matrix( HessienneI )
1869         A = HessienneI.I
1870         if min(A.shape) != max(A.shape):
1871             raise ValueError("The %s a posteriori covariance matrix A is of shape %s, despites it has to be a squared matrix. There is an error in the observation operator, please check it."%(selfA._name,str(A.shape)))
1872         if (numpy.diag(A) < 0).any():
1873             raise ValueError("The %s a posteriori covariance matrix A has at least one negative value on its diagonal. There is an error in the observation operator, please check it."%(selfA._name,))
1874         if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
1875             try:
1876                 L = numpy.linalg.cholesky( A )
1877             except:
1878                 raise ValueError("The %s a posteriori covariance matrix A is not symmetric positive-definite. Please check your a priori covariances and your observation operator."%(selfA._name,))
1879     if selfA._toStore("APosterioriCovariance"):
1880         selfA.StoredVariables["APosterioriCovariance"].store( A )
1881     if selfA._toStore("JacobianMatrixAtOptimum"):
1882         selfA.StoredVariables["JacobianMatrixAtOptimum"].store( HtM )
1883     if selfA._toStore("KalmanGainAtOptimum"):
1884         if   (Y.size <= Xb.size): KG  = B * HaM * (R + numpy.dot(HtM, B * HaM)).I
1885         elif (Y.size >  Xb.size): KG = (BI + numpy.dot(HaM, RI * HtM)).I * HaM * RI
1886         selfA.StoredVariables["KalmanGainAtOptimum"].store( KG )
1887     #
1888     # Calculs et/ou stockages supplémentaires
1889     # ---------------------------------------
1890     if selfA._toStore("Innovation") or \
1891         selfA._toStore("SigmaObs2") or \
1892         selfA._toStore("MahalanobisConsistency") or \
1893         selfA._toStore("OMB"):
1894         d  = Y - HXb
1895     if selfA._toStore("Innovation"):
1896         selfA.StoredVariables["Innovation"].store( numpy.ravel(d) )
1897     if selfA._toStore("BMA"):
1898         selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
1899     if selfA._toStore("OMA"):
1900         selfA.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
1901     if selfA._toStore("OMB"):
1902         selfA.StoredVariables["OMB"].store( numpy.ravel(d) )
1903     if selfA._toStore("SigmaObs2"):
1904         TraceR = R.trace(Y.size)
1905         selfA.StoredVariables["SigmaObs2"].store( float( (d.T * (numpy.asmatrix(numpy.ravel(Y)).T-numpy.asmatrix(numpy.ravel(HXa)).T)) ) / TraceR )
1906     if selfA._toStore("MahalanobisConsistency"):
1907         selfA.StoredVariables["MahalanobisConsistency"].store( float( 2.*MinJ/d.size ) )
1908     if selfA._toStore("SimulationQuantiles"):
1909         QuantilesEstimations(selfA, A, Xa, HXa, Hm, HtM)
1910     if selfA._toStore("SimulatedObservationAtBackground"):
1911         selfA.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
1912     if selfA._toStore("SimulatedObservationAtOptimum"):
1913         selfA.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
1914     #
1915     return 0
1916
1917 # ==============================================================================
1918 def mlef(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, VariantM="MLEF13",
1919     BnotT=False, _epsilon=1.e-3, _e=1.e-7, _jmax=15000):
1920     """
1921     Maximum Likelihood Ensemble Filter
1922     """
1923     if selfA._parameters["EstimationOf"] == "Parameters":
1924         selfA._parameters["StoreInternalVariables"] = True
1925     #
1926     # Opérateurs
1927     H = HO["Direct"].appliedControledFormTo
1928     #
1929     if selfA._parameters["EstimationOf"] == "State":
1930         M = EM["Direct"].appliedControledFormTo
1931     #
1932     if CM is not None and "Tangent" in CM and U is not None:
1933         Cm = CM["Tangent"].asMatrix(Xb)
1934     else:
1935         Cm = None
1936     #
1937     # Durée d'observation et tailles
1938     if hasattr(Y,"stepnumber"):
1939         duration = Y.stepnumber()
1940         __p = numpy.cumprod(Y.shape())[-1]
1941     else:
1942         duration = 2
1943         __p = numpy.array(Y).size
1944     #
1945     # Précalcul des inversions de B et R
1946     if selfA._parameters["StoreInternalVariables"] \
1947         or selfA._toStore("CostFunctionJ") \
1948         or selfA._toStore("CostFunctionJb") \
1949         or selfA._toStore("CostFunctionJo") \
1950         or selfA._toStore("CurrentOptimum") \
1951         or selfA._toStore("APosterioriCovariance"):
1952         BI = B.getI()
1953     RI = R.getI()
1954     #
1955     __n = Xb.size
1956     __m = selfA._parameters["NumberOfMembers"]
1957     #
1958     if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
1959         Xn = EnsembleOfBackgroundPerturbations( Xb, None, __m )
1960         selfA.StoredVariables["Analysis"].store( Xb )
1961         if selfA._toStore("APosterioriCovariance"):
1962             if hasattr(B,"asfullmatrix"):
1963                 selfA.StoredVariables["APosterioriCovariance"].store( B.asfullmatrix(__n) )
1964             else:
1965                 selfA.StoredVariables["APosterioriCovariance"].store( B )
1966         selfA._setInternalState("seed", numpy.random.get_state())
1967     elif selfA._parameters["nextStep"]:
1968         Xn = selfA._getInternalState("Xn")
1969     #
1970     previousJMinimum = numpy.finfo(float).max
1971     #
1972     for step in range(duration-1):
1973         numpy.random.set_state(selfA._getInternalState("seed"))
1974         if hasattr(Y,"store"):
1975             Ynpu = numpy.ravel( Y[step+1] ).reshape((__p,1))
1976         else:
1977             Ynpu = numpy.ravel( Y ).reshape((__p,1))
1978         #
1979         if U is not None:
1980             if hasattr(U,"store") and len(U)>1:
1981                 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
1982             elif hasattr(U,"store") and len(U)==1:
1983                 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
1984             else:
1985                 Un = numpy.asmatrix(numpy.ravel( U )).T
1986         else:
1987             Un = None
1988         #
1989         if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
1990             Xn = CovarianceInflation( Xn,
1991                 selfA._parameters["InflationType"],
1992                 selfA._parameters["InflationFactor"],
1993                 )
1994         #
1995         if selfA._parameters["EstimationOf"] == "State": # Forecast + Q and observation of forecast
1996             EMX = M( [(Xn[:,i], Un) for i in range(__m)],
1997                 argsAsSerie = True,
1998                 returnSerieAsArrayMatrix = True )
1999             Xn_predicted = EnsemblePerturbationWithGivenCovariance( EMX, Q )
2000             if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
2001                 Cm = Cm.reshape(__n,Un.size) # ADAO & check shape
2002                 Xn_predicted = Xn_predicted + Cm * Un
2003         elif selfA._parameters["EstimationOf"] == "Parameters": # Observation of forecast
2004             # --- > Par principe, M = Id, Q = 0
2005             Xn_predicted = EMX = Xn
2006         #
2007         #--------------------------
2008         if VariantM == "MLEF13":
2009             Xfm = numpy.ravel(Xn_predicted.mean(axis=1, dtype=mfp).astype('float'))
2010             EaX = EnsembleOfAnomalies( Xn_predicted, Xfm, 1./math.sqrt(__m-1) )
2011             Ua  = numpy.identity(__m)
2012             __j = 0
2013             Deltaw = 1
2014             if not BnotT:
2015                 Ta  = numpy.identity(__m)
2016             vw  = numpy.zeros(__m)
2017             while numpy.linalg.norm(Deltaw) >= _e and __j <= _jmax:
2018                 vx1 = (Xfm + EaX @ vw).reshape((__n,1))
2019                 #
2020                 if BnotT:
2021                     E1 = vx1 + _epsilon * EaX
2022                 else:
2023                     E1 = vx1 + math.sqrt(__m-1) * EaX @ Ta
2024                 #
2025                 HE2 = H( [(E1[:,i,numpy.newaxis], Un) for i in range(__m)],
2026                     argsAsSerie = True,
2027                     returnSerieAsArrayMatrix = True )
2028                 vy2 = HE2.mean(axis=1, dtype=mfp).astype('float').reshape((__p,1))
2029                 #
2030                 if BnotT:
2031                     EaY = (HE2 - vy2) / _epsilon
2032                 else:
2033                     EaY = ( (HE2 - vy2) @ numpy.linalg.inv(Ta) ) / math.sqrt(__m-1)
2034                 #
2035                 GradJ = numpy.ravel(vw[:,None] - EaY.transpose() @ (RI * ( Ynpu - vy2 )))
2036                 mH = numpy.identity(__m) + EaY.transpose() @ (RI * EaY).reshape((-1,__m))
2037                 Deltaw = - numpy.linalg.solve(mH,GradJ)
2038                 #
2039                 vw = vw + Deltaw
2040                 #
2041                 if not BnotT:
2042                     Ta = numpy.real(scipy.linalg.sqrtm(numpy.linalg.inv( mH )))
2043                 #
2044                 __j = __j + 1
2045             #
2046             if BnotT:
2047                 Ta = numpy.real(scipy.linalg.sqrtm(numpy.linalg.inv( mH )))
2048             #
2049             Xn = vx1 + math.sqrt(__m-1) * EaX @ Ta @ Ua
2050         #--------------------------
2051         else:
2052             raise ValueError("VariantM has to be chosen in the authorized methods list.")
2053         #
2054         if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
2055             Xn = CovarianceInflation( Xn,
2056                 selfA._parameters["InflationType"],
2057                 selfA._parameters["InflationFactor"],
2058                 )
2059         #
2060         Xa = Xn.mean(axis=1, dtype=mfp).astype('float').reshape((__n,1))
2061         #--------------------------
2062         selfA._setInternalState("Xn", Xn)
2063         selfA._setInternalState("seed", numpy.random.get_state())
2064         #--------------------------
2065         #
2066         if selfA._parameters["StoreInternalVariables"] \
2067             or selfA._toStore("CostFunctionJ") \
2068             or selfA._toStore("CostFunctionJb") \
2069             or selfA._toStore("CostFunctionJo") \
2070             or selfA._toStore("APosterioriCovariance") \
2071             or selfA._toStore("InnovationAtCurrentAnalysis") \
2072             or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
2073             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
2074             _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
2075             _Innovation = Ynpu - _HXa
2076         #
2077         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
2078         # ---> avec analysis
2079         selfA.StoredVariables["Analysis"].store( Xa )
2080         if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
2081             selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
2082         if selfA._toStore("InnovationAtCurrentAnalysis"):
2083             selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
2084         # ---> avec current state
2085         if selfA._parameters["StoreInternalVariables"] \
2086             or selfA._toStore("CurrentState"):
2087             selfA.StoredVariables["CurrentState"].store( Xn )
2088         if selfA._toStore("ForecastState"):
2089             selfA.StoredVariables["ForecastState"].store( EMX )
2090         if selfA._toStore("ForecastCovariance"):
2091             selfA.StoredVariables["ForecastCovariance"].store( EnsembleErrorCovariance(EMX) )
2092         if selfA._toStore("BMA"):
2093             selfA.StoredVariables["BMA"].store( EMX - Xa )
2094         if selfA._toStore("InnovationAtCurrentState"):
2095             selfA.StoredVariables["InnovationAtCurrentState"].store( - HE2 + Ynpu )
2096         if selfA._toStore("SimulatedObservationAtCurrentState") \
2097             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
2098             selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HE2 )
2099         # ---> autres
2100         if selfA._parameters["StoreInternalVariables"] \
2101             or selfA._toStore("CostFunctionJ") \
2102             or selfA._toStore("CostFunctionJb") \
2103             or selfA._toStore("CostFunctionJo") \
2104             or selfA._toStore("CurrentOptimum") \
2105             or selfA._toStore("APosterioriCovariance"):
2106             Jb  = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
2107             Jo  = float( 0.5 * _Innovation.T * RI * _Innovation )
2108             J   = Jb + Jo
2109             selfA.StoredVariables["CostFunctionJb"].store( Jb )
2110             selfA.StoredVariables["CostFunctionJo"].store( Jo )
2111             selfA.StoredVariables["CostFunctionJ" ].store( J )
2112             #
2113             if selfA._toStore("IndexOfOptimum") \
2114                 or selfA._toStore("CurrentOptimum") \
2115                 or selfA._toStore("CostFunctionJAtCurrentOptimum") \
2116                 or selfA._toStore("CostFunctionJbAtCurrentOptimum") \
2117                 or selfA._toStore("CostFunctionJoAtCurrentOptimum") \
2118                 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
2119                 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
2120             if selfA._toStore("IndexOfOptimum"):
2121                 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
2122             if selfA._toStore("CurrentOptimum"):
2123                 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["Analysis"][IndexMin] )
2124             if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
2125                 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"][IndexMin] )
2126             if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
2127                 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
2128             if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
2129                 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
2130             if selfA._toStore("CostFunctionJAtCurrentOptimum"):
2131                 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
2132         if selfA._toStore("APosterioriCovariance"):
2133             selfA.StoredVariables["APosterioriCovariance"].store( EnsembleErrorCovariance(Xn) )
2134         if selfA._parameters["EstimationOf"] == "Parameters" \
2135             and J < previousJMinimum:
2136             previousJMinimum    = J
2137             XaMin               = Xa
2138             if selfA._toStore("APosterioriCovariance"):
2139                 covarianceXaMin = selfA.StoredVariables["APosterioriCovariance"][-1]
2140     #
2141     # Stockage final supplémentaire de l'optimum en estimation de paramètres
2142     # ----------------------------------------------------------------------
2143     if selfA._parameters["EstimationOf"] == "Parameters":
2144         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
2145         selfA.StoredVariables["Analysis"].store( XaMin )
2146         if selfA._toStore("APosterioriCovariance"):
2147             selfA.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
2148         if selfA._toStore("BMA"):
2149             selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
2150     #
2151     return 0
2152
2153 # ==============================================================================
2154 def mmqr(
2155         func     = None,
2156         x0       = None,
2157         fprime   = None,
2158         bounds   = None,
2159         quantile = 0.5,
2160         maxfun   = 15000,
2161         toler    = 1.e-06,
2162         y        = None,
2163         ):
2164     """
2165     Implémentation informatique de l'algorithme MMQR, basée sur la publication :
2166     David R. Hunter, Kenneth Lange, "Quantile Regression via an MM Algorithm",
2167     Journal of Computational and Graphical Statistics, 9, 1, pp.60-77, 2000.
2168     """
2169     #
2170     # Recuperation des donnees et informations initiales
2171     # --------------------------------------------------
2172     variables = numpy.ravel( x0 )
2173     mesures   = numpy.ravel( y )
2174     increment = sys.float_info[0]
2175     p         = variables.size
2176     n         = mesures.size
2177     quantile  = float(quantile)
2178     #
2179     # Calcul des parametres du MM
2180     # ---------------------------
2181     tn      = float(toler) / n
2182     e0      = -tn / math.log(tn)
2183     epsilon = (e0-tn)/(1+math.log(e0))
2184     #
2185     # Calculs d'initialisation
2186     # ------------------------
2187     residus  = mesures - numpy.ravel( func( variables ) )
2188     poids    = 1./(epsilon+numpy.abs(residus))
2189     veps     = 1. - 2. * quantile - residus * poids
2190     lastsurrogate = -numpy.sum(residus*veps) - (1.-2.*quantile)*numpy.sum(residus)
2191     iteration = 0
2192     #
2193     # Recherche iterative
2194     # -------------------
2195     while (increment > toler) and (iteration < maxfun) :
2196         iteration += 1
2197         #
2198         Derivees  = numpy.array(fprime(variables))
2199         Derivees  = Derivees.reshape(n,p) # Necessaire pour remettre en place la matrice si elle passe par des tuyaux YACS
2200         DeriveesT = Derivees.transpose()
2201         M         =   numpy.dot( DeriveesT , (numpy.array(numpy.matrix(p*[poids,]).T)*Derivees) )
2202         SM        =   numpy.transpose(numpy.dot( DeriveesT , veps ))
2203         step      = - numpy.linalg.lstsq( M, SM, rcond=-1 )[0]
2204         #
2205         variables = variables + step
2206         if bounds is not None:
2207             # Attention : boucle infinie à éviter si un intervalle est trop petit
2208             while( (variables < numpy.ravel(numpy.asmatrix(bounds)[:,0])).any() or (variables > numpy.ravel(numpy.asmatrix(bounds)[:,1])).any() ):
2209                 step      = step/2.
2210                 variables = variables - step
2211         residus   = mesures - numpy.ravel( func(variables) )
2212         surrogate = numpy.sum(residus**2 * poids) + (4.*quantile-2.) * numpy.sum(residus)
2213         #
2214         while ( (surrogate > lastsurrogate) and ( max(list(numpy.abs(step))) > 1.e-16 ) ) :
2215             step      = step/2.
2216             variables = variables - step
2217             residus   = mesures - numpy.ravel( func(variables) )
2218             surrogate = numpy.sum(residus**2 * poids) + (4.*quantile-2.) * numpy.sum(residus)
2219         #
2220         increment     = lastsurrogate-surrogate
2221         poids         = 1./(epsilon+numpy.abs(residus))
2222         veps          = 1. - 2. * quantile - residus * poids
2223         lastsurrogate = -numpy.sum(residus * veps) - (1.-2.*quantile)*numpy.sum(residus)
2224     #
2225     # Mesure d'écart
2226     # --------------
2227     Ecart = quantile * numpy.sum(residus) - numpy.sum( residus[residus<0] )
2228     #
2229     return variables, Ecart, [n,p,iteration,increment,0]
2230
2231 # ==============================================================================
2232 def multi3dvar(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, oneCycle):
2233     """
2234     3DVAR multi-pas et multi-méthodes
2235     """
2236     #
2237     # Initialisation
2238     if selfA._parameters["EstimationOf"] == "State":
2239         M = EM["Direct"].appliedTo
2240         #
2241         if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
2242             Xn = numpy.ravel(Xb).reshape((-1,1))
2243             selfA.StoredVariables["Analysis"].store( Xn )
2244             if selfA._toStore("APosterioriCovariance"):
2245                 if hasattr(B,"asfullmatrix"):
2246                     selfA.StoredVariables["APosterioriCovariance"].store( B.asfullmatrix(Xn.size) )
2247                 else:
2248                     selfA.StoredVariables["APosterioriCovariance"].store( B )
2249             if selfA._toStore("ForecastState"):
2250                 selfA.StoredVariables["ForecastState"].store( Xn )
2251         elif selfA._parameters["nextStep"]:
2252             Xn = selfA._getInternalState("Xn")
2253     else:
2254         Xn = numpy.ravel(Xb).reshape((-1,1))
2255     #
2256     if hasattr(Y,"stepnumber"):
2257         duration = Y.stepnumber()
2258     else:
2259         duration = 2
2260     #
2261     # Multi-pas
2262     for step in range(duration-1):
2263         if hasattr(Y,"store"):
2264             Ynpu = numpy.ravel( Y[step+1] ).reshape((-1,1))
2265         else:
2266             Ynpu = numpy.ravel( Y ).reshape((-1,1))
2267         #
2268         if selfA._parameters["EstimationOf"] == "State": # Forecast
2269             Xn_predicted = M( Xn )
2270             if selfA._toStore("ForecastState"):
2271                 selfA.StoredVariables["ForecastState"].store( Xn_predicted )
2272         elif selfA._parameters["EstimationOf"] == "Parameters": # No forecast
2273             # --- > Par principe, M = Id, Q = 0
2274             Xn_predicted = Xn
2275         Xn_predicted = numpy.ravel(Xn_predicted).reshape((-1,1))
2276         #
2277         oneCycle(selfA, Xn_predicted, Ynpu, U, HO, None, None, R, B, None)
2278         #
2279         Xn = selfA.StoredVariables["Analysis"][-1]
2280         #--------------------------
2281         selfA._setInternalState("Xn", Xn)
2282     #
2283     return 0
2284
2285 # ==============================================================================
2286 def psas3dvar(selfA, Xb, Y, U, HO, EM, CM, R, B, Q):
2287     """
2288     3DVAR PSAS
2289     """
2290     #
2291     # Initialisations
2292     # ---------------
2293     #
2294     # Opérateurs
2295     Hm = HO["Direct"].appliedTo
2296     #
2297     # Utilisation éventuelle d'un vecteur H(Xb) précalculé
2298     if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
2299         HXb = Hm( Xb, HO["AppliedInX"]["HXb"] )
2300     else:
2301         HXb = Hm( Xb )
2302     HXb = numpy.asmatrix(numpy.ravel( HXb )).T
2303     if Y.size != HXb.size:
2304         raise ValueError("The size %i of observations Y and %i of observed calculation H(X) are different, they have to be identical."%(Y.size,HXb.size))
2305     if max(Y.shape) != max(HXb.shape):
2306         raise ValueError("The shapes %s of observations Y and %s of observed calculation H(X) are different, they have to be identical."%(Y.shape,HXb.shape))
2307     #
2308     if selfA._toStore("JacobianMatrixAtBackground"):
2309         HtMb = HO["Tangent"].asMatrix(ValueForMethodForm = Xb)
2310         HtMb = HtMb.reshape(Y.size,Xb.size) # ADAO & check shape
2311         selfA.StoredVariables["JacobianMatrixAtBackground"].store( HtMb )
2312     #
2313     Ht = HO["Tangent"].asMatrix(Xb)
2314     BHT = B * Ht.T
2315     HBHTpR = R + Ht * BHT
2316     Innovation = Y - HXb
2317     #
2318     # Point de démarrage de l'optimisation
2319     Xini = numpy.zeros(Xb.shape)
2320     #
2321     # Définition de la fonction-coût
2322     # ------------------------------
2323     def CostFunction(w):
2324         _W = numpy.asmatrix(numpy.ravel( w )).T
2325         if selfA._parameters["StoreInternalVariables"] or \
2326             selfA._toStore("CurrentState") or \
2327             selfA._toStore("CurrentOptimum"):
2328             selfA.StoredVariables["CurrentState"].store( Xb + BHT * _W )
2329         if selfA._toStore("SimulatedObservationAtCurrentState") or \
2330             selfA._toStore("SimulatedObservationAtCurrentOptimum"):
2331             selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( Hm( Xb + BHT * _W ) )
2332         if selfA._toStore("InnovationAtCurrentState"):
2333             selfA.StoredVariables["InnovationAtCurrentState"].store( Innovation )
2334         #
2335         Jb  = float( 0.5 * _W.T * HBHTpR * _W )
2336         Jo  = float( - _W.T * Innovation )
2337         J   = Jb + Jo
2338         #
2339         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["CostFunctionJ"]) )
2340         selfA.StoredVariables["CostFunctionJb"].store( Jb )
2341         selfA.StoredVariables["CostFunctionJo"].store( Jo )
2342         selfA.StoredVariables["CostFunctionJ" ].store( J )
2343         if selfA._toStore("IndexOfOptimum") or \
2344             selfA._toStore("CurrentOptimum") or \
2345             selfA._toStore("CostFunctionJAtCurrentOptimum") or \
2346             selfA._toStore("CostFunctionJbAtCurrentOptimum") or \
2347             selfA._toStore("CostFunctionJoAtCurrentOptimum") or \
2348             selfA._toStore("SimulatedObservationAtCurrentOptimum"):
2349             IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
2350         if selfA._toStore("IndexOfOptimum"):
2351             selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
2352         if selfA._toStore("CurrentOptimum"):
2353             selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["CurrentState"][IndexMin] )
2354         if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
2355             selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] )
2356         if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
2357             selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
2358         if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
2359             selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
2360         if selfA._toStore("CostFunctionJAtCurrentOptimum"):
2361             selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
2362         return J
2363     #
2364     def GradientOfCostFunction(w):
2365         _W = numpy.asmatrix(numpy.ravel( w )).T
2366         GradJb  = HBHTpR * _W
2367         GradJo  = - Innovation
2368         GradJ   = numpy.ravel( GradJb ) + numpy.ravel( GradJo )
2369         return GradJ
2370     #
2371     # Minimisation de la fonctionnelle
2372     # --------------------------------
2373     nbPreviousSteps = selfA.StoredVariables["CostFunctionJ"].stepnumber()
2374     #
2375     if selfA._parameters["Minimizer"] == "LBFGSB":
2376         if "0.19" <= scipy.version.version <= "1.1.0":
2377             import lbfgsbhlt as optimiseur
2378         else:
2379             import scipy.optimize as optimiseur
2380         Minimum, J_optimal, Informations = optimiseur.fmin_l_bfgs_b(
2381             func        = CostFunction,
2382             x0          = Xini,
2383             fprime      = GradientOfCostFunction,
2384             args        = (),
2385             bounds      = selfA._parameters["Bounds"],
2386             maxfun      = selfA._parameters["MaximumNumberOfSteps"]-1,
2387             factr       = selfA._parameters["CostDecrementTolerance"]*1.e14,
2388             pgtol       = selfA._parameters["ProjectedGradientTolerance"],
2389             iprint      = selfA._parameters["optiprint"],
2390             )
2391         nfeval = Informations['funcalls']
2392         rc     = Informations['warnflag']
2393     elif selfA._parameters["Minimizer"] == "TNC":
2394         Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
2395             func        = CostFunction,
2396             x0          = Xini,
2397             fprime      = GradientOfCostFunction,
2398             args        = (),
2399             bounds      = selfA._parameters["Bounds"],
2400             maxfun      = selfA._parameters["MaximumNumberOfSteps"],
2401             pgtol       = selfA._parameters["ProjectedGradientTolerance"],
2402             ftol        = selfA._parameters["CostDecrementTolerance"],
2403             messages    = selfA._parameters["optmessages"],
2404             )
2405     elif selfA._parameters["Minimizer"] == "CG":
2406         Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
2407             f           = CostFunction,
2408             x0          = Xini,
2409             fprime      = GradientOfCostFunction,
2410             args        = (),
2411             maxiter     = selfA._parameters["MaximumNumberOfSteps"],
2412             gtol        = selfA._parameters["GradientNormTolerance"],
2413             disp        = selfA._parameters["optdisp"],
2414             full_output = True,
2415             )
2416     elif selfA._parameters["Minimizer"] == "NCG":
2417         Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
2418             f           = CostFunction,
2419             x0          = Xini,
2420             fprime      = GradientOfCostFunction,
2421             args        = (),
2422             maxiter     = selfA._parameters["MaximumNumberOfSteps"],
2423             avextol     = selfA._parameters["CostDecrementTolerance"],
2424             disp        = selfA._parameters["optdisp"],
2425             full_output = True,
2426             )
2427     elif selfA._parameters["Minimizer"] == "BFGS":
2428         Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
2429             f           = CostFunction,
2430             x0          = Xini,
2431             fprime      = GradientOfCostFunction,
2432             args        = (),
2433             maxiter     = selfA._parameters["MaximumNumberOfSteps"],
2434             gtol        = selfA._parameters["GradientNormTolerance"],
2435             disp        = selfA._parameters["optdisp"],
2436             full_output = True,
2437             )
2438     else:
2439         raise ValueError("Error in Minimizer name: %s"%selfA._parameters["Minimizer"])
2440     #
2441     IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
2442     MinJ     = selfA.StoredVariables["CostFunctionJ"][IndexMin]
2443     #
2444     # Correction pour pallier a un bug de TNC sur le retour du Minimum
2445     # ----------------------------------------------------------------
2446     if selfA._parameters["StoreInternalVariables"] or selfA._toStore("CurrentState"):
2447         Minimum = selfA.StoredVariables["CurrentState"][IndexMin]
2448         Minimum = numpy.asmatrix(numpy.ravel( Minimum )).T
2449     else:
2450         Minimum = Xb + BHT * numpy.asmatrix(numpy.ravel( Minimum )).T
2451     #
2452     # Obtention de l'analyse
2453     # ----------------------
2454     Xa = Minimum
2455     #
2456     selfA.StoredVariables["Analysis"].store( Xa )
2457     #
2458     if selfA._toStore("OMA") or \
2459         selfA._toStore("SigmaObs2") or \
2460         selfA._toStore("SimulationQuantiles") or \
2461         selfA._toStore("SimulatedObservationAtOptimum"):
2462         if selfA._toStore("SimulatedObservationAtCurrentState"):
2463             HXa = selfA.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
2464         elif selfA._toStore("SimulatedObservationAtCurrentOptimum"):
2465             HXa = selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
2466         else:
2467             HXa = Hm( Xa )
2468     #
2469     # Calcul de la covariance d'analyse
2470     # ---------------------------------
2471     if selfA._toStore("APosterioriCovariance") or \
2472         selfA._toStore("SimulationQuantiles") or \
2473         selfA._toStore("JacobianMatrixAtOptimum") or \
2474         selfA._toStore("KalmanGainAtOptimum"):
2475         HtM = HO["Tangent"].asMatrix(ValueForMethodForm = Xa)
2476         HtM = HtM.reshape(Y.size,Xa.size) # ADAO & check shape
2477     if selfA._toStore("APosterioriCovariance") or \
2478         selfA._toStore("SimulationQuantiles") or \
2479         selfA._toStore("KalmanGainAtOptimum"):
2480         HaM = HO["Adjoint"].asMatrix(ValueForMethodForm = Xa)
2481         HaM = HaM.reshape(Xa.size,Y.size) # ADAO & check shape
2482     if selfA._toStore("APosterioriCovariance") or \
2483         selfA._toStore("SimulationQuantiles"):
2484         BI = B.getI()
2485         RI = R.getI()
2486         HessienneI = []
2487         nb = Xa.size
2488         for i in range(nb):
2489             _ee    = numpy.matrix(numpy.zeros(nb)).T
2490             _ee[i] = 1.
2491             _HtEE  = numpy.dot(HtM,_ee)
2492             _HtEE  = numpy.asmatrix(numpy.ravel( _HtEE )).T
2493             HessienneI.append( numpy.ravel( BI*_ee + HaM * (RI * _HtEE) ) )
2494         HessienneI = numpy.matrix( HessienneI )
2495         A = HessienneI.I
2496         if min(A.shape) != max(A.shape):
2497             raise ValueError("The %s a posteriori covariance matrix A is of shape %s, despites it has to be a squared matrix. There is an error in the observation operator, please check it."%(selfA._name,str(A.shape)))
2498         if (numpy.diag(A) < 0).any():
2499             raise ValueError("The %s a posteriori covariance matrix A has at least one negative value on its diagonal. There is an error in the observation operator, please check it."%(selfA._name,))
2500         if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
2501             try:
2502                 L = numpy.linalg.cholesky( A )
2503             except:
2504                 raise ValueError("The %s a posteriori covariance matrix A is not symmetric positive-definite. Please check your a priori covariances and your observation operator."%(selfA._name,))
2505     if selfA._toStore("APosterioriCovariance"):
2506         selfA.StoredVariables["APosterioriCovariance"].store( A )
2507     if selfA._toStore("JacobianMatrixAtOptimum"):
2508         selfA.StoredVariables["JacobianMatrixAtOptimum"].store( HtM )
2509     if selfA._toStore("KalmanGainAtOptimum"):
2510         if   (Y.size <= Xb.size): KG  = B * HaM * (R + numpy.dot(HtM, B * HaM)).I
2511         elif (Y.size >  Xb.size): KG = (BI + numpy.dot(HaM, RI * HtM)).I * HaM * RI
2512         selfA.StoredVariables["KalmanGainAtOptimum"].store( KG )
2513     #
2514     # Calculs et/ou stockages supplémentaires
2515     # ---------------------------------------
2516     if selfA._toStore("Innovation") or \
2517         selfA._toStore("SigmaObs2") or \
2518         selfA._toStore("MahalanobisConsistency") or \
2519         selfA._toStore("OMB"):
2520         d  = Y - HXb
2521     if selfA._toStore("Innovation"):
2522         selfA.StoredVariables["Innovation"].store( numpy.ravel(d) )
2523     if selfA._toStore("BMA"):
2524         selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
2525     if selfA._toStore("OMA"):
2526         selfA.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
2527     if selfA._toStore("OMB"):
2528         selfA.StoredVariables["OMB"].store( numpy.ravel(d) )
2529     if selfA._toStore("SigmaObs2"):
2530         TraceR = R.trace(Y.size)
2531         selfA.StoredVariables["SigmaObs2"].store( float( (d.T * (numpy.asmatrix(numpy.ravel(Y)).T-numpy.asmatrix(numpy.ravel(HXa)).T)) ) / TraceR )
2532     if selfA._toStore("MahalanobisConsistency"):
2533         selfA.StoredVariables["MahalanobisConsistency"].store( float( 2.*MinJ/d.size ) )
2534     if selfA._toStore("SimulationQuantiles"):
2535         QuantilesEstimations(selfA, A, Xa, HXa, Hm, HtM)
2536     if selfA._toStore("SimulatedObservationAtBackground"):
2537         selfA.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
2538     if selfA._toStore("SimulatedObservationAtOptimum"):
2539         selfA.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
2540     #
2541     return 0
2542
2543 # ==============================================================================
2544 def senkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, VariantM="KalmanFilterFormula16"):
2545     """
2546     Stochastic EnKF
2547     """
2548     if selfA._parameters["EstimationOf"] == "Parameters":
2549         selfA._parameters["StoreInternalVariables"] = True
2550     #
2551     # Opérateurs
2552     H = HO["Direct"].appliedControledFormTo
2553     #
2554     if selfA._parameters["EstimationOf"] == "State":
2555         M = EM["Direct"].appliedControledFormTo
2556     #
2557     if CM is not None and "Tangent" in CM and U is not None:
2558         Cm = CM["Tangent"].asMatrix(Xb)
2559     else:
2560         Cm = None
2561     #
2562     # Durée d'observation et tailles
2563     if hasattr(Y,"stepnumber"):
2564         duration = Y.stepnumber()
2565         __p = numpy.cumprod(Y.shape())[-1]
2566     else:
2567         duration = 2
2568         __p = numpy.array(Y).size
2569     #
2570     # Précalcul des inversions de B et R
2571     if selfA._parameters["StoreInternalVariables"] \
2572         or selfA._toStore("CostFunctionJ") \
2573         or selfA._toStore("CostFunctionJb") \
2574         or selfA._toStore("CostFunctionJo") \
2575         or selfA._toStore("CurrentOptimum") \
2576         or selfA._toStore("APosterioriCovariance"):
2577         BI = B.getI()
2578         RI = R.getI()
2579     #
2580     __n = Xb.size
2581     __m = selfA._parameters["NumberOfMembers"]
2582     #
2583     if hasattr(R,"asfullmatrix"): Rn = R.asfullmatrix(__p)
2584     else:                         Rn = R
2585     #
2586     if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
2587         Xn = EnsembleOfBackgroundPerturbations( Xb, None, __m )
2588         selfA.StoredVariables["Analysis"].store( Xb )
2589         if selfA._toStore("APosterioriCovariance"):
2590             if hasattr(B,"asfullmatrix"):
2591                 selfA.StoredVariables["APosterioriCovariance"].store( B.asfullmatrix(__n) )
2592             else:
2593                 selfA.StoredVariables["APosterioriCovariance"].store( B )
2594         selfA._setInternalState("seed", numpy.random.get_state())
2595     elif selfA._parameters["nextStep"]:
2596         Xn = selfA._getInternalState("Xn")
2597     #
2598     previousJMinimum = numpy.finfo(float).max
2599     #
2600     for step in range(duration-1):
2601         numpy.random.set_state(selfA._getInternalState("seed"))
2602         if hasattr(Y,"store"):
2603             Ynpu = numpy.ravel( Y[step+1] ).reshape((__p,1))
2604         else:
2605             Ynpu = numpy.ravel( Y ).reshape((__p,1))
2606         #
2607         if U is not None:
2608             if hasattr(U,"store") and len(U)>1:
2609                 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
2610             elif hasattr(U,"store") and len(U)==1:
2611                 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
2612             else:
2613                 Un = numpy.asmatrix(numpy.ravel( U )).T
2614         else:
2615             Un = None
2616         #
2617         if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
2618             Xn = CovarianceInflation( Xn,
2619                 selfA._parameters["InflationType"],
2620                 selfA._parameters["InflationFactor"],
2621                 )
2622         #
2623         if selfA._parameters["EstimationOf"] == "State": # Forecast + Q and observation of forecast
2624             EMX = M( [(Xn[:,i], Un) for i in range(__m)],
2625                 argsAsSerie = True,
2626                 returnSerieAsArrayMatrix = True )
2627             Xn_predicted = EnsemblePerturbationWithGivenCovariance( EMX, Q )
2628             HX_predicted = H( [(Xn_predicted[:,i], Un) for i in range(__m)],
2629                 argsAsSerie = True,
2630                 returnSerieAsArrayMatrix = True )
2631             if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
2632                 Cm = Cm.reshape(__n,Un.size) # ADAO & check shape
2633                 Xn_predicted = Xn_predicted + Cm * Un
2634         elif selfA._parameters["EstimationOf"] == "Parameters": # Observation of forecast
2635             # --- > Par principe, M = Id, Q = 0
2636             Xn_predicted = EMX = Xn
2637             HX_predicted = H( [(Xn_predicted[:,i], Un) for i in range(__m)],
2638                 argsAsSerie = True,
2639                 returnSerieAsArrayMatrix = True )
2640         #
2641         # Mean of forecast and observation of forecast
2642         Xfm  = Xn_predicted.mean(axis=1, dtype=mfp).astype('float').reshape((__n,1))
2643         Hfm  = HX_predicted.mean(axis=1, dtype=mfp).astype('float').reshape((__p,1))
2644         #
2645         #--------------------------
2646         if VariantM == "KalmanFilterFormula05":
2647             PfHT, HPfHT = 0., 0.
2648             for i in range(__m):
2649                 Exfi = Xn_predicted[:,i].reshape((__n,1)) - Xfm
2650                 Eyfi = HX_predicted[:,i].reshape((__p,1)) - Hfm
2651                 PfHT  += Exfi * Eyfi.T
2652                 HPfHT += Eyfi * Eyfi.T
2653             PfHT  = (1./(__m-1)) * PfHT
2654             HPfHT = (1./(__m-1)) * HPfHT
2655             Kn     = PfHT * ( R + HPfHT ).I
2656             del PfHT, HPfHT
2657             #
2658             for i in range(__m):
2659                 ri = numpy.random.multivariate_normal(numpy.zeros(__p), Rn)
2660                 Xn[:,i] = numpy.ravel(Xn_predicted[:,i]) + Kn @ (numpy.ravel(Ynpu) + ri - HX_predicted[:,i])
2661         #--------------------------
2662         elif VariantM == "KalmanFilterFormula16":
2663             EpY   = EnsembleOfCenteredPerturbations(Ynpu, Rn, __m)
2664             EpYm  = EpY.mean(axis=1, dtype=mfp).astype('float').reshape((__p,1))
2665             #
2666             EaX   = EnsembleOfAnomalies( Xn_predicted ) / math.sqrt(__m-1)
2667             EaY = (HX_predicted - Hfm - EpY + EpYm) / math.sqrt(__m-1)
2668             #
2669             Kn = EaX @ EaY.T @ numpy.linalg.inv( EaY @ EaY.T)
2670             #
2671             for i in range(__m):
2672                 Xn[:,i] = numpy.ravel(Xn_predicted[:,i]) + Kn @ (numpy.ravel(EpY[:,i]) - HX_predicted[:,i])
2673         #--------------------------
2674         else:
2675             raise ValueError("VariantM has to be chosen in the authorized methods list.")
2676         #
2677         if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
2678             Xn = CovarianceInflation( Xn,
2679                 selfA._parameters["InflationType"],
2680                 selfA._parameters["InflationFactor"],
2681                 )
2682         #
2683         Xa = Xn.mean(axis=1, dtype=mfp).astype('float').reshape((__n,1))
2684         #--------------------------
2685         selfA._setInternalState("Xn", Xn)
2686         selfA._setInternalState("seed", numpy.random.get_state())
2687         #--------------------------
2688         #
2689         if selfA._parameters["StoreInternalVariables"] \
2690             or selfA._toStore("CostFunctionJ") \
2691             or selfA._toStore("CostFunctionJb") \
2692             or selfA._toStore("CostFunctionJo") \
2693             or selfA._toStore("APosterioriCovariance") \
2694             or selfA._toStore("InnovationAtCurrentAnalysis") \
2695             or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
2696             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
2697             _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
2698             _Innovation = Ynpu - _HXa
2699         #
2700         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
2701         # ---> avec analysis
2702         selfA.StoredVariables["Analysis"].store( Xa )
2703         if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
2704             selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
2705         if selfA._toStore("InnovationAtCurrentAnalysis"):
2706             selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
2707         # ---> avec current state
2708         if selfA._parameters["StoreInternalVariables"] \
2709             or selfA._toStore("CurrentState"):
2710             selfA.StoredVariables["CurrentState"].store( Xn )
2711         if selfA._toStore("ForecastState"):
2712             selfA.StoredVariables["ForecastState"].store( EMX )
2713         if selfA._toStore("ForecastCovariance"):
2714             selfA.StoredVariables["ForecastCovariance"].store( EnsembleErrorCovariance(EMX) )
2715         if selfA._toStore("BMA"):
2716             selfA.StoredVariables["BMA"].store( EMX - Xa )
2717         if selfA._toStore("InnovationAtCurrentState"):
2718             selfA.StoredVariables["InnovationAtCurrentState"].store( - HX_predicted + Ynpu )
2719         if selfA._toStore("SimulatedObservationAtCurrentState") \
2720             or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
2721             selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HX_predicted )
2722         # ---> autres
2723         if selfA._parameters["StoreInternalVariables"] \
2724             or selfA._toStore("CostFunctionJ") \
2725             or selfA._toStore("CostFunctionJb") \
2726             or selfA._toStore("CostFunctionJo") \
2727             or selfA._toStore("CurrentOptimum") \
2728             or selfA._toStore("APosterioriCovariance"):
2729             Jb  = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
2730             Jo  = float( 0.5 * _Innovation.T * RI * _Innovation )
2731             J   = Jb + Jo
2732             selfA.StoredVariables["CostFunctionJb"].store( Jb )
2733             selfA.StoredVariables["CostFunctionJo"].store( Jo )
2734             selfA.StoredVariables["CostFunctionJ" ].store( J )
2735             #
2736             if selfA._toStore("IndexOfOptimum") \
2737                 or selfA._toStore("CurrentOptimum") \
2738                 or selfA._toStore("CostFunctionJAtCurrentOptimum") \
2739                 or selfA._toStore("CostFunctionJbAtCurrentOptimum") \
2740                 or selfA._toStore("CostFunctionJoAtCurrentOptimum") \
2741                 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
2742                 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
2743             if selfA._toStore("IndexOfOptimum"):
2744                 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
2745             if selfA._toStore("CurrentOptimum"):
2746                 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["Analysis"][IndexMin] )
2747             if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
2748                 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"][IndexMin] )
2749             if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
2750                 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
2751             if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
2752                 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
2753             if selfA._toStore("CostFunctionJAtCurrentOptimum"):
2754                 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
2755         if selfA._toStore("APosterioriCovariance"):
2756             selfA.StoredVariables["APosterioriCovariance"].store( EnsembleErrorCovariance(Xn) )
2757         if selfA._parameters["EstimationOf"] == "Parameters" \
2758             and J < previousJMinimum:
2759             previousJMinimum    = J
2760             XaMin               = Xa
2761             if selfA._toStore("APosterioriCovariance"):
2762                 covarianceXaMin = selfA.StoredVariables["APosterioriCovariance"][-1]
2763     #
2764     # Stockage final supplémentaire de l'optimum en estimation de paramètres
2765     # ----------------------------------------------------------------------
2766     if selfA._parameters["EstimationOf"] == "Parameters":
2767         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
2768         selfA.StoredVariables["Analysis"].store( XaMin )
2769         if selfA._toStore("APosterioriCovariance"):
2770             selfA.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
2771         if selfA._toStore("BMA"):
2772             selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
2773     #
2774     return 0
2775
2776 # ==============================================================================
2777 def std3dvar(selfA, Xb, Y, U, HO, EM, CM, R, B, Q):
2778     """
2779     3DVAR
2780     """
2781     #
2782     # Initialisations
2783     # ---------------
2784     #
2785     # Opérateurs
2786     Hm = HO["Direct"].appliedTo
2787     Ha = HO["Adjoint"].appliedInXTo
2788     #
2789     # Utilisation éventuelle d'un vecteur H(Xb) précalculé
2790     if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
2791         HXb = Hm( Xb, HO["AppliedInX"]["HXb"] )
2792     else:
2793         HXb = Hm( Xb )
2794     HXb = numpy.asmatrix(numpy.ravel( HXb )).T
2795     if Y.size != HXb.size:
2796         raise ValueError("The size %i of observations Y and %i of observed calculation H(X) are different, they have to be identical."%(Y.size,HXb.size))
2797     if max(Y.shape) != max(HXb.shape):
2798         raise ValueError("The shapes %s of observations Y and %s of observed calculation H(X) are different, they have to be identical."%(Y.shape,HXb.shape))
2799     #
2800     if selfA._toStore("JacobianMatrixAtBackground"):
2801         HtMb = HO["Tangent"].asMatrix(ValueForMethodForm = Xb)
2802         HtMb = HtMb.reshape(Y.size,Xb.size) # ADAO & check shape
2803         selfA.StoredVariables["JacobianMatrixAtBackground"].store( HtMb )
2804     #
2805     # Précalcul des inversions de B et R
2806     BI = B.getI()
2807     RI = R.getI()
2808     #
2809     # Point de démarrage de l'optimisation
2810     Xini = selfA._parameters["InitializationPoint"]
2811     #
2812     # Définition de la fonction-coût
2813     # ------------------------------
2814     def CostFunction(x):
2815         _X  = numpy.asmatrix(numpy.ravel( x )).T
2816         if selfA._parameters["StoreInternalVariables"] or \
2817             selfA._toStore("CurrentState") or \
2818             selfA._toStore("CurrentOptimum"):
2819             selfA.StoredVariables["CurrentState"].store( _X )
2820         _HX = Hm( _X )
2821         _HX = numpy.asmatrix(numpy.ravel( _HX )).T
2822         _Innovation = Y - _HX
2823         if selfA._toStore("SimulatedObservationAtCurrentState") or \
2824             selfA._toStore("SimulatedObservationAtCurrentOptimum"):
2825             selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
2826         if selfA._toStore("InnovationAtCurrentState"):
2827             selfA.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
2828         #
2829         Jb  = float( 0.5 * (_X - Xb).T * BI * (_X - Xb) )
2830         Jo  = float( 0.5 * _Innovation.T * RI * _Innovation )
2831         J   = Jb + Jo
2832         #
2833         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["CostFunctionJ"]) )
2834         selfA.StoredVariables["CostFunctionJb"].store( Jb )
2835         selfA.StoredVariables["CostFunctionJo"].store( Jo )
2836         selfA.StoredVariables["CostFunctionJ" ].store( J )
2837         if selfA._toStore("IndexOfOptimum") or \
2838             selfA._toStore("CurrentOptimum") or \
2839             selfA._toStore("CostFunctionJAtCurrentOptimum") or \
2840             selfA._toStore("CostFunctionJbAtCurrentOptimum") or \
2841             selfA._toStore("CostFunctionJoAtCurrentOptimum") or \
2842             selfA._toStore("SimulatedObservationAtCurrentOptimum"):
2843             IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
2844         if selfA._toStore("IndexOfOptimum"):
2845             selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
2846         if selfA._toStore("CurrentOptimum"):
2847             selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["CurrentState"][IndexMin] )
2848         if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
2849             selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] )
2850         if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
2851             selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
2852         if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
2853             selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
2854         if selfA._toStore("CostFunctionJAtCurrentOptimum"):
2855             selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
2856         return J
2857     #
2858     def GradientOfCostFunction(x):
2859         _X      = numpy.asmatrix(numpy.ravel( x )).T
2860         _HX     = Hm( _X )
2861         _HX     = numpy.asmatrix(numpy.ravel( _HX )).T
2862         GradJb  = BI * (_X - Xb)
2863         GradJo  = - Ha( (_X, RI * (Y - _HX)) )
2864         GradJ   = numpy.ravel( GradJb ) + numpy.ravel( GradJo )
2865         return GradJ
2866     #
2867     # Minimisation de la fonctionnelle
2868     # --------------------------------
2869     nbPreviousSteps = selfA.StoredVariables["CostFunctionJ"].stepnumber()
2870     #
2871     if selfA._parameters["Minimizer"] == "LBFGSB":
2872         if "0.19" <= scipy.version.version <= "1.1.0":
2873             import lbfgsbhlt as optimiseur
2874         else:
2875             import scipy.optimize as optimiseur
2876         Minimum, J_optimal, Informations = optimiseur.fmin_l_bfgs_b(
2877             func        = CostFunction,
2878             x0          = Xini,
2879             fprime      = GradientOfCostFunction,
2880             args        = (),
2881             bounds      = selfA._parameters["Bounds"],
2882             maxfun      = selfA._parameters["MaximumNumberOfSteps"]-1,
2883             factr       = selfA._parameters["CostDecrementTolerance"]*1.e14,
2884             pgtol       = selfA._parameters["ProjectedGradientTolerance"],
2885             iprint      = selfA._parameters["optiprint"],
2886             )
2887         nfeval = Informations['funcalls']
2888         rc     = Informations['warnflag']
2889     elif selfA._parameters["Minimizer"] == "TNC":
2890         Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
2891             func        = CostFunction,
2892             x0          = Xini,
2893             fprime      = GradientOfCostFunction,
2894             args        = (),
2895             bounds      = selfA._parameters["Bounds"],
2896             maxfun      = selfA._parameters["MaximumNumberOfSteps"],
2897             pgtol       = selfA._parameters["ProjectedGradientTolerance"],
2898             ftol        = selfA._parameters["CostDecrementTolerance"],
2899             messages    = selfA._parameters["optmessages"],
2900             )
2901     elif selfA._parameters["Minimizer"] == "CG":
2902         Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
2903             f           = CostFunction,
2904             x0          = Xini,
2905             fprime      = GradientOfCostFunction,
2906             args        = (),
2907             maxiter     = selfA._parameters["MaximumNumberOfSteps"],
2908             gtol        = selfA._parameters["GradientNormTolerance"],
2909             disp        = selfA._parameters["optdisp"],
2910             full_output = True,
2911             )
2912     elif selfA._parameters["Minimizer"] == "NCG":
2913         Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
2914             f           = CostFunction,
2915             x0          = Xini,
2916             fprime      = GradientOfCostFunction,
2917             args        = (),
2918             maxiter     = selfA._parameters["MaximumNumberOfSteps"],
2919             avextol     = selfA._parameters["CostDecrementTolerance"],
2920             disp        = selfA._parameters["optdisp"],
2921             full_output = True,
2922             )
2923     elif selfA._parameters["Minimizer"] == "BFGS":
2924         Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
2925             f           = CostFunction,
2926             x0          = Xini,
2927             fprime      = GradientOfCostFunction,
2928             args        = (),
2929             maxiter     = selfA._parameters["MaximumNumberOfSteps"],
2930             gtol        = selfA._parameters["GradientNormTolerance"],
2931             disp        = selfA._parameters["optdisp"],
2932             full_output = True,
2933             )
2934     else:
2935         raise ValueError("Error in Minimizer name: %s"%selfA._parameters["Minimizer"])
2936     #
2937     IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
2938     MinJ     = selfA.StoredVariables["CostFunctionJ"][IndexMin]
2939     #
2940     # Correction pour pallier a un bug de TNC sur le retour du Minimum
2941     # ----------------------------------------------------------------
2942     if selfA._parameters["StoreInternalVariables"] or selfA._toStore("CurrentState"):
2943         Minimum = selfA.StoredVariables["CurrentState"][IndexMin]
2944     #
2945     # Obtention de l'analyse
2946     # ----------------------
2947     Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
2948     #
2949     selfA.StoredVariables["Analysis"].store( Xa )
2950     #
2951     if selfA._toStore("OMA") or \
2952         selfA._toStore("SigmaObs2") or \
2953         selfA._toStore("SimulationQuantiles") or \
2954         selfA._toStore("SimulatedObservationAtOptimum"):
2955         if selfA._toStore("SimulatedObservationAtCurrentState"):
2956             HXa = selfA.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
2957         elif selfA._toStore("SimulatedObservationAtCurrentOptimum"):
2958             HXa = selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
2959         else:
2960             HXa = Hm( Xa )
2961     #
2962     # Calcul de la covariance d'analyse
2963     # ---------------------------------
2964     if selfA._toStore("APosterioriCovariance") or \
2965         selfA._toStore("SimulationQuantiles") or \
2966         selfA._toStore("JacobianMatrixAtOptimum") or \
2967         selfA._toStore("KalmanGainAtOptimum"):
2968         HtM = HO["Tangent"].asMatrix(ValueForMethodForm = Xa)
2969         HtM = HtM.reshape(Y.size,Xa.size) # ADAO & check shape
2970     if selfA._toStore("APosterioriCovariance") or \
2971         selfA._toStore("SimulationQuantiles") or \
2972         selfA._toStore("KalmanGainAtOptimum"):
2973         HaM = HO["Adjoint"].asMatrix(ValueForMethodForm = Xa)
2974         HaM = HaM.reshape(Xa.size,Y.size) # ADAO & check shape
2975     if selfA._toStore("APosterioriCovariance") or \
2976         selfA._toStore("SimulationQuantiles"):
2977         HessienneI = []
2978         nb = Xa.size
2979         for i in range(nb):
2980             _ee    = numpy.matrix(numpy.zeros(nb)).T
2981             _ee[i] = 1.
2982             _HtEE  = numpy.dot(HtM,_ee)
2983             _HtEE  = numpy.asmatrix(numpy.ravel( _HtEE )).T
2984             HessienneI.append( numpy.ravel( BI*_ee + HaM * (RI * _HtEE) ) )
2985         HessienneI = numpy.matrix( HessienneI )
2986         A = HessienneI.I
2987         if min(A.shape) != max(A.shape):
2988             raise ValueError("The %s a posteriori covariance matrix A is of shape %s, despites it has to be a squared matrix. There is an error in the observation operator, please check it."%(selfA._name,str(A.shape)))
2989         if (numpy.diag(A) < 0).any():
2990             raise ValueError("The %s a posteriori covariance matrix A has at least one negative value on its diagonal. There is an error in the observation operator, please check it."%(selfA._name,))
2991         if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
2992             try:
2993                 L = numpy.linalg.cholesky( A )
2994             except:
2995                 raise ValueError("The %s a posteriori covariance matrix A is not symmetric positive-definite. Please check your a priori covariances and your observation operator."%(selfA._name,))
2996     if selfA._toStore("APosterioriCovariance"):
2997         selfA.StoredVariables["APosterioriCovariance"].store( A )
2998     if selfA._toStore("JacobianMatrixAtOptimum"):
2999         selfA.StoredVariables["JacobianMatrixAtOptimum"].store( HtM )
3000     if selfA._toStore("KalmanGainAtOptimum"):
3001         if   (Y.size <= Xb.size): KG  = B * HaM * (R + numpy.dot(HtM, B * HaM)).I
3002         elif (Y.size >  Xb.size): KG = (BI + numpy.dot(HaM, RI * HtM)).I * HaM * RI
3003         selfA.StoredVariables["KalmanGainAtOptimum"].store( KG )
3004     #
3005     # Calculs et/ou stockages supplémentaires
3006     # ---------------------------------------
3007     if selfA._toStore("Innovation") or \
3008         selfA._toStore("SigmaObs2") or \
3009         selfA._toStore("MahalanobisConsistency") or \
3010         selfA._toStore("OMB"):
3011         d  = Y - HXb
3012     if selfA._toStore("Innovation"):
3013         selfA.StoredVariables["Innovation"].store( numpy.ravel(d) )
3014     if selfA._toStore("BMA"):
3015         selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
3016     if selfA._toStore("OMA"):
3017         selfA.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
3018     if selfA._toStore("OMB"):
3019         selfA.StoredVariables["OMB"].store( numpy.ravel(d) )
3020     if selfA._toStore("SigmaObs2"):
3021         TraceR = R.trace(Y.size)
3022         selfA.StoredVariables["SigmaObs2"].store( float( (d.T * (numpy.asmatrix(numpy.ravel(Y)).T-numpy.asmatrix(numpy.ravel(HXa)).T)) ) / TraceR )
3023     if selfA._toStore("MahalanobisConsistency"):
3024         selfA.StoredVariables["MahalanobisConsistency"].store( float( 2.*MinJ/d.size ) )
3025     if selfA._toStore("SimulationQuantiles"):
3026         QuantilesEstimations(selfA, A, Xa, HXa, Hm, HtM)
3027     if selfA._toStore("SimulatedObservationAtBackground"):
3028         selfA.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
3029     if selfA._toStore("SimulatedObservationAtOptimum"):
3030         selfA.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
3031     #
3032     return 0
3033
3034 # ==============================================================================
3035 def std4dvar(selfA, Xb, Y, U, HO, EM, CM, R, B, Q):
3036     """
3037     4DVAR
3038     """
3039     #
3040     # Initialisations
3041     # ---------------
3042     #
3043     # Opérateurs
3044     Hm = HO["Direct"].appliedControledFormTo
3045     Mm = EM["Direct"].appliedControledFormTo
3046     #
3047     if CM is not None and "Tangent" in CM and U is not None:
3048         Cm = CM["Tangent"].asMatrix(Xb)
3049     else:
3050         Cm = None
3051     #
3052     def Un(_step):
3053         if U is not None:
3054             if hasattr(U,"store") and 1<=_step<len(U) :
3055                 _Un = numpy.asmatrix(numpy.ravel( U[_step] )).T
3056             elif hasattr(U,"store") and len(U)==1:
3057                 _Un = numpy.asmatrix(numpy.ravel( U[0] )).T
3058             else:
3059                 _Un = numpy.asmatrix(numpy.ravel( U )).T
3060         else:
3061             _Un = None
3062         return _Un
3063     def CmUn(_xn,_un):
3064         if Cm is not None and _un is not None: # Attention : si Cm est aussi dans M, doublon !
3065             _Cm   = Cm.reshape(_xn.size,_un.size) # ADAO & check shape
3066             _CmUn = _Cm * _un
3067         else:
3068             _CmUn = 0.
3069         return _CmUn
3070     #
3071     # Remarque : les observations sont exploitées à partir du pas de temps
3072     # numéro 1, et sont utilisées dans Yo comme rangées selon ces indices.
3073     # Donc le pas 0 n'est pas utilisé puisque la première étape commence
3074     # avec l'observation du pas 1.
3075     #
3076     # Nombre de pas identique au nombre de pas d'observations
3077     if hasattr(Y,"stepnumber"):
3078         duration = Y.stepnumber()
3079     else:
3080         duration = 2
3081     #
3082     # Précalcul des inversions de B et R
3083     BI = B.getI()
3084     RI = R.getI()
3085     #
3086     # Point de démarrage de l'optimisation
3087     Xini = selfA._parameters["InitializationPoint"]
3088     #
3089     # Définition de la fonction-coût
3090     # ------------------------------
3091     selfA.DirectCalculation = [None,] # Le pas 0 n'est pas observé
3092     selfA.DirectInnovation  = [None,] # Le pas 0 n'est pas observé
3093     def CostFunction(x):
3094         _X  = numpy.asmatrix(numpy.ravel( x )).T
3095         if selfA._parameters["StoreInternalVariables"] or \
3096             selfA._toStore("CurrentState") or \
3097             selfA._toStore("CurrentOptimum"):
3098             selfA.StoredVariables["CurrentState"].store( _X )
3099         Jb  = float( 0.5 * (_X - Xb).T * BI * (_X - Xb) )
3100         selfA.DirectCalculation = [None,]
3101         selfA.DirectInnovation  = [None,]
3102         Jo  = 0.
3103         _Xn = _X
3104         for step in range(0,duration-1):
3105             if hasattr(Y,"store"):
3106                 _Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
3107             else:
3108                 _Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
3109             _Un = Un(step)
3110             #
3111             # Etape d'évolution
3112             if selfA._parameters["EstimationOf"] == "State":
3113                 _Xn = Mm( (_Xn, _Un) ) + CmUn(_Xn, _Un)
3114             elif selfA._parameters["EstimationOf"] == "Parameters":
3115                 pass
3116             #
3117             if selfA._parameters["Bounds"] is not None and selfA._parameters["ConstrainedBy"] == "EstimateProjection":
3118                 _Xn = numpy.max(numpy.hstack((_Xn,numpy.asmatrix(selfA._parameters["Bounds"])[:,0])),axis=1)
3119                 _Xn = numpy.min(numpy.hstack((_Xn,numpy.asmatrix(selfA._parameters["Bounds"])[:,1])),axis=1)
3120             #
3121             # Etape de différence aux observations
3122             if selfA._parameters["EstimationOf"] == "State":
3123                 _YmHMX = _Ynpu - numpy.asmatrix(numpy.ravel( Hm( (_Xn, None) ) )).T
3124             elif selfA._parameters["EstimationOf"] == "Parameters":
3125                 _YmHMX = _Ynpu - numpy.asmatrix(numpy.ravel( Hm( (_Xn, _Un) ) )).T - CmUn(_Xn, _Un)
3126             #
3127             # Stockage de l'état
3128             selfA.DirectCalculation.append( _Xn )
3129             selfA.DirectInnovation.append( _YmHMX )
3130             #
3131             # Ajout dans la fonctionnelle d'observation
3132             Jo = Jo + 0.5 * float( _YmHMX.T * RI * _YmHMX )
3133         J = Jb + Jo
3134         #
3135         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["CostFunctionJ"]) )
3136         selfA.StoredVariables["CostFunctionJb"].store( Jb )
3137         selfA.StoredVariables["CostFunctionJo"].store( Jo )
3138         selfA.StoredVariables["CostFunctionJ" ].store( J )
3139         if selfA._toStore("IndexOfOptimum") or \
3140             selfA._toStore("CurrentOptimum") or \
3141             selfA._toStore("CostFunctionJAtCurrentOptimum") or \
3142             selfA._toStore("CostFunctionJbAtCurrentOptimum") or \
3143             selfA._toStore("CostFunctionJoAtCurrentOptimum"):
3144             IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
3145         if selfA._toStore("IndexOfOptimum"):
3146             selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
3147         if selfA._toStore("CurrentOptimum"):
3148             selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["CurrentState"][IndexMin] )
3149         if selfA._toStore("CostFunctionJAtCurrentOptimum"):
3150             selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
3151         if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
3152             selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
3153         if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
3154             selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
3155         return J
3156     #
3157     def GradientOfCostFunction(x):
3158         _X      = numpy.asmatrix(numpy.ravel( x )).T
3159         GradJb  = BI * (_X - Xb)
3160         GradJo  = 0.
3161         for step in range(duration-1,0,-1):
3162             # Étape de récupération du dernier stockage de l'évolution
3163             _Xn = selfA.DirectCalculation.pop()
3164             # Étape de récupération du dernier stockage de l'innovation
3165             _YmHMX = selfA.DirectInnovation.pop()
3166             # Calcul des adjoints
3167             Ha = HO["Adjoint"].asMatrix(ValueForMethodForm = _Xn)
3168             Ha = Ha.reshape(_Xn.size,_YmHMX.size) # ADAO & check shape
3169             Ma = EM["Adjoint"].asMatrix(ValueForMethodForm = _Xn)
3170             Ma = Ma.reshape(_Xn.size,_Xn.size) # ADAO & check shape
3171             # Calcul du gradient par état adjoint
3172             GradJo = GradJo + Ha * RI * _YmHMX # Équivaut pour Ha linéaire à : Ha( (_Xn, RI * _YmHMX) )
3173             GradJo = Ma * GradJo               # Équivaut pour Ma linéaire à : Ma( (_Xn, GradJo) )
3174         GradJ = numpy.ravel( GradJb ) - numpy.ravel( GradJo )
3175         return GradJ
3176     #
3177     # Minimisation de la fonctionnelle
3178     # --------------------------------
3179     nbPreviousSteps = selfA.StoredVariables["CostFunctionJ"].stepnumber()
3180     #
3181     if selfA._parameters["Minimizer"] == "LBFGSB":
3182         if "0.19" <= scipy.version.version <= "1.1.0":
3183             import lbfgsbhlt as optimiseur
3184         else:
3185             import scipy.optimize as optimiseur
3186         Minimum, J_optimal, Informations = optimiseur.fmin_l_bfgs_b(
3187             func        = CostFunction,
3188             x0          = Xini,
3189             fprime      = GradientOfCostFunction,
3190             args        = (),
3191             bounds      = selfA._parameters["Bounds"],
3192             maxfun      = selfA._parameters["MaximumNumberOfSteps"]-1,
3193             factr       = selfA._parameters["CostDecrementTolerance"]*1.e14,
3194             pgtol       = selfA._parameters["ProjectedGradientTolerance"],
3195             iprint      = selfA._parameters["optiprint"],
3196             )
3197         nfeval = Informations['funcalls']
3198         rc     = Informations['warnflag']
3199     elif selfA._parameters["Minimizer"] == "TNC":
3200         Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
3201             func        = CostFunction,
3202             x0          = Xini,
3203             fprime      = GradientOfCostFunction,
3204             args        = (),
3205             bounds      = selfA._parameters["Bounds"],
3206             maxfun      = selfA._parameters["MaximumNumberOfSteps"],
3207             pgtol       = selfA._parameters["ProjectedGradientTolerance"],
3208             ftol        = selfA._parameters["CostDecrementTolerance"],
3209             messages    = selfA._parameters["optmessages"],
3210             )
3211     elif selfA._parameters["Minimizer"] == "CG":
3212         Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
3213             f           = CostFunction,
3214             x0          = Xini,
3215             fprime      = GradientOfCostFunction,
3216             args        = (),
3217             maxiter     = selfA._parameters["MaximumNumberOfSteps"],
3218             gtol        = selfA._parameters["GradientNormTolerance"],
3219             disp        = selfA._parameters["optdisp"],
3220             full_output = True,
3221             )
3222     elif selfA._parameters["Minimizer"] == "NCG":
3223         Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
3224             f           = CostFunction,
3225             x0          = Xini,
3226             fprime      = GradientOfCostFunction,
3227             args        = (),
3228             maxiter     = selfA._parameters["MaximumNumberOfSteps"],
3229             avextol     = selfA._parameters["CostDecrementTolerance"],
3230             disp        = selfA._parameters["optdisp"],
3231             full_output = True,
3232             )
3233     elif selfA._parameters["Minimizer"] == "BFGS":
3234         Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
3235             f           = CostFunction,
3236             x0          = Xini,
3237             fprime      = GradientOfCostFunction,
3238             args        = (),
3239             maxiter     = selfA._parameters["MaximumNumberOfSteps"],
3240             gtol        = selfA._parameters["GradientNormTolerance"],
3241             disp        = selfA._parameters["optdisp"],
3242             full_output = True,
3243             )
3244     else:
3245         raise ValueError("Error in Minimizer name: %s"%selfA._parameters["Minimizer"])
3246     #
3247     IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
3248     MinJ     = selfA.StoredVariables["CostFunctionJ"][IndexMin]
3249     #
3250     # Correction pour pallier a un bug de TNC sur le retour du Minimum
3251     # ----------------------------------------------------------------
3252     if selfA._parameters["StoreInternalVariables"] or selfA._toStore("CurrentState"):
3253         Minimum = selfA.StoredVariables["CurrentState"][IndexMin]
3254     #
3255     # Obtention de l'analyse
3256     # ----------------------
3257     Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
3258     #
3259     selfA.StoredVariables["Analysis"].store( Xa )
3260     #
3261     # Calculs et/ou stockages supplémentaires
3262     # ---------------------------------------
3263     if selfA._toStore("BMA"):
3264         selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
3265     #
3266     return 0
3267
3268 # ==============================================================================
3269 def van3dvar(selfA, Xb, Y, U, HO, EM, CM, R, B, Q):
3270     """
3271     3DVAR variational analysis with no inversion of B
3272     """
3273     #
3274     # Initialisations
3275     # ---------------
3276     #
3277     # Opérateurs
3278     Hm = HO["Direct"].appliedTo
3279     Ha = HO["Adjoint"].appliedInXTo
3280     #
3281     # Précalcul des inversions de B et R
3282     BT = B.getT()
3283     RI = R.getI()
3284     #
3285     # Point de démarrage de l'optimisation
3286     Xini = numpy.zeros(Xb.shape)
3287     #
3288     # Définition de la fonction-coût
3289     # ------------------------------
3290     def CostFunction(v):
3291         _V = numpy.asmatrix(numpy.ravel( v )).T
3292         _X = Xb + B * _V
3293         if selfA._parameters["StoreInternalVariables"] or \
3294             selfA._toStore("CurrentState") or \
3295             selfA._toStore("CurrentOptimum"):
3296             selfA.StoredVariables["CurrentState"].store( _X )
3297         _HX = Hm( _X )
3298         _HX = numpy.asmatrix(numpy.ravel( _HX )).T
3299         _Innovation = Y - _HX
3300         if selfA._toStore("SimulatedObservationAtCurrentState") or \
3301             selfA._toStore("SimulatedObservationAtCurrentOptimum"):
3302             selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
3303         if selfA._toStore("InnovationAtCurrentState"):
3304             selfA.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
3305         #
3306         Jb  = float( 0.5 * _V.T * BT * _V )
3307         Jo  = float( 0.5 * _Innovation.T * RI * _Innovation )
3308         J   = Jb + Jo
3309         #
3310         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["CostFunctionJ"]) )
3311         selfA.StoredVariables["CostFunctionJb"].store( Jb )
3312         selfA.StoredVariables["CostFunctionJo"].store( Jo )
3313         selfA.StoredVariables["CostFunctionJ" ].store( J )
3314         if selfA._toStore("IndexOfOptimum") or \
3315             selfA._toStore("CurrentOptimum") or \
3316             selfA._toStore("CostFunctionJAtCurrentOptimum") or \
3317             selfA._toStore("CostFunctionJbAtCurrentOptimum") or \
3318             selfA._toStore("CostFunctionJoAtCurrentOptimum") or \
3319             selfA._toStore("SimulatedObservationAtCurrentOptimum"):
3320             IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
3321         if selfA._toStore("IndexOfOptimum"):
3322             selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
3323         if selfA._toStore("CurrentOptimum"):
3324             selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["CurrentState"][IndexMin] )
3325         if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
3326             selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] )
3327         if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
3328             selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
3329         if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
3330             selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
3331         if selfA._toStore("CostFunctionJAtCurrentOptimum"):
3332             selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
3333         return J
3334     #
3335     def GradientOfCostFunction(v):
3336         _V = numpy.asmatrix(numpy.ravel( v )).T
3337         _X = Xb + B * _V
3338         _HX     = Hm( _X )
3339         _HX     = numpy.asmatrix(numpy.ravel( _HX )).T
3340         GradJb  = BT * _V
3341         GradJo  = - Ha( (_X, RI * (Y - _HX)) )
3342         GradJ   = numpy.ravel( GradJb ) + numpy.ravel( GradJo )
3343         return GradJ
3344     #
3345     # Minimisation de la fonctionnelle
3346     # --------------------------------
3347     nbPreviousSteps = selfA.StoredVariables["CostFunctionJ"].stepnumber()
3348     #
3349     if selfA._parameters["Minimizer"] == "LBFGSB":
3350         if "0.19" <= scipy.version.version <= "1.1.0":
3351             import lbfgsbhlt as optimiseur
3352         else:
3353             import scipy.optimize as optimiseur
3354         Minimum, J_optimal, Informations = optimiseur.fmin_l_bfgs_b(
3355             func        = CostFunction,
3356             x0          = Xini,
3357             fprime      = GradientOfCostFunction,
3358             args        = (),
3359             bounds      = selfA._parameters["Bounds"],
3360             maxfun      = selfA._parameters["MaximumNumberOfSteps"]-1,
3361             factr       = selfA._parameters["CostDecrementTolerance"]*1.e14,
3362             pgtol       = selfA._parameters["ProjectedGradientTolerance"],
3363             iprint      = selfA._parameters["optiprint"],
3364             )
3365         nfeval = Informations['funcalls']
3366         rc     = Informations['warnflag']
3367     elif selfA._parameters["Minimizer"] == "TNC":
3368         Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
3369             func        = CostFunction,
3370             x0          = Xini,
3371             fprime      = GradientOfCostFunction,
3372             args        = (),
3373             bounds      = selfA._parameters["Bounds"],
3374             maxfun      = selfA._parameters["MaximumNumberOfSteps"],
3375             pgtol       = selfA._parameters["ProjectedGradientTolerance"],
3376             ftol        = selfA._parameters["CostDecrementTolerance"],
3377             messages    = selfA._parameters["optmessages"],
3378             )
3379     elif selfA._parameters["Minimizer"] == "CG":
3380         Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
3381             f           = CostFunction,
3382             x0          = Xini,
3383             fprime      = GradientOfCostFunction,
3384             args        = (),
3385             maxiter     = selfA._parameters["MaximumNumberOfSteps"],
3386             gtol        = selfA._parameters["GradientNormTolerance"],
3387             disp        = selfA._parameters["optdisp"],
3388             full_output = True,
3389             )
3390     elif selfA._parameters["Minimizer"] == "NCG":
3391         Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
3392             f           = CostFunction,
3393             x0          = Xini,
3394             fprime      = GradientOfCostFunction,
3395             args        = (),
3396             maxiter     = selfA._parameters["MaximumNumberOfSteps"],
3397             avextol     = selfA._parameters["CostDecrementTolerance"],
3398             disp        = selfA._parameters["optdisp"],
3399             full_output = True,
3400             )
3401     elif selfA._parameters["Minimizer"] == "BFGS":
3402         Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
3403             f           = CostFunction,
3404             x0          = Xini,
3405             fprime      = GradientOfCostFunction,
3406             args        = (),
3407             maxiter     = selfA._parameters["MaximumNumberOfSteps"],
3408             gtol        = selfA._parameters["GradientNormTolerance"],
3409             disp        = selfA._parameters["optdisp"],
3410             full_output = True,
3411             )
3412     else:
3413         raise ValueError("Error in Minimizer name: %s"%selfA._parameters["Minimizer"])
3414     #
3415     IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
3416     MinJ     = selfA.StoredVariables["CostFunctionJ"][IndexMin]
3417     #
3418     # Correction pour pallier a un bug de TNC sur le retour du Minimum
3419     # ----------------------------------------------------------------
3420     if selfA._parameters["StoreInternalVariables"] or selfA._toStore("CurrentState"):
3421         Minimum = selfA.StoredVariables["CurrentState"][IndexMin]
3422         Minimum = numpy.asmatrix(numpy.ravel( Minimum )).T
3423     else:
3424         Minimum = Xb + B * numpy.asmatrix(numpy.ravel( Minimum )).T
3425     #
3426     # Obtention de l'analyse
3427     # ----------------------
3428     Xa = Minimum
3429     #
3430     selfA.StoredVariables["Analysis"].store( Xa )
3431     #
3432     if selfA._toStore("OMA") or \
3433         selfA._toStore("SigmaObs2") or \
3434         selfA._toStore("SimulationQuantiles") or \
3435         selfA._toStore("SimulatedObservationAtOptimum"):
3436         if selfA._toStore("SimulatedObservationAtCurrentState"):
3437             HXa = selfA.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
3438         elif selfA._toStore("SimulatedObservationAtCurrentOptimum"):
3439             HXa = selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
3440         else:
3441             HXa = Hm( Xa )
3442     #
3443     # Calcul de la covariance d'analyse
3444     # ---------------------------------
3445     if selfA._toStore("APosterioriCovariance") or \
3446         selfA._toStore("SimulationQuantiles") or \
3447         selfA._toStore("JacobianMatrixAtOptimum") or \
3448         selfA._toStore("KalmanGainAtOptimum"):
3449         HtM = HO["Tangent"].asMatrix(ValueForMethodForm = Xa)
3450         HtM = HtM.reshape(Y.size,Xa.size) # ADAO & check shape
3451     if selfA._toStore("APosterioriCovariance") or \
3452         selfA._toStore("SimulationQuantiles") or \
3453         selfA._toStore("KalmanGainAtOptimum"):
3454         HaM = HO["Adjoint"].asMatrix(ValueForMethodForm = Xa)
3455         HaM = HaM.reshape(Xa.size,Y.size) # ADAO & check shape
3456     if selfA._toStore("APosterioriCovariance") or \
3457         selfA._toStore("SimulationQuantiles"):
3458         BI = B.getI()
3459         HessienneI = []
3460         nb = Xa.size
3461         for i in range(nb):
3462             _ee    = numpy.matrix(numpy.zeros(nb)).T
3463             _ee[i] = 1.
3464             _HtEE  = numpy.dot(HtM,_ee)
3465             _HtEE  = numpy.asmatrix(numpy.ravel( _HtEE )).T
3466             HessienneI.append( numpy.ravel( BI*_ee + HaM * (RI * _HtEE) ) )
3467         HessienneI = numpy.matrix( HessienneI )
3468         A = HessienneI.I
3469         if min(A.shape) != max(A.shape):
3470             raise ValueError("The %s a posteriori covariance matrix A is of shape %s, despites it has to be a squared matrix. There is an error in the observation operator, please check it."%(selfA._name,str(A.shape)))
3471         if (numpy.diag(A) < 0).any():
3472             raise ValueError("The %s a posteriori covariance matrix A has at least one negative value on its diagonal. There is an error in the observation operator, please check it."%(selfA._name,))
3473         if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
3474             try:
3475                 L = numpy.linalg.cholesky( A )
3476             except:
3477                 raise ValueError("The %s a posteriori covariance matrix A is not symmetric positive-definite. Please check your a priori covariances and your observation operator."%(selfA._name,))
3478     if selfA._toStore("APosterioriCovariance"):
3479         selfA.StoredVariables["APosterioriCovariance"].store( A )
3480     if selfA._toStore("JacobianMatrixAtOptimum"):
3481         selfA.StoredVariables["JacobianMatrixAtOptimum"].store( HtM )
3482     if selfA._toStore("KalmanGainAtOptimum"):
3483         if   (Y.size <= Xb.size): KG  = B * HaM * (R + numpy.dot(HtM, B * HaM)).I
3484         elif (Y.size >  Xb.size): KG = (BI + numpy.dot(HaM, RI * HtM)).I * HaM * RI
3485         selfA.StoredVariables["KalmanGainAtOptimum"].store( KG )
3486     #
3487     # Calculs et/ou stockages supplémentaires
3488     # ---------------------------------------
3489     if selfA._toStore("Innovation") or \
3490         selfA._toStore("SigmaObs2") or \
3491         selfA._toStore("MahalanobisConsistency") or \
3492         selfA._toStore("OMB"):
3493         d  = Y - HXb
3494     if selfA._toStore("Innovation"):
3495         selfA.StoredVariables["Innovation"].store( numpy.ravel(d) )
3496     if selfA._toStore("BMA"):
3497         selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
3498     if selfA._toStore("OMA"):
3499         selfA.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
3500     if selfA._toStore("OMB"):
3501         selfA.StoredVariables["OMB"].store( numpy.ravel(d) )
3502     if selfA._toStore("SigmaObs2"):
3503         TraceR = R.trace(Y.size)
3504         selfA.StoredVariables["SigmaObs2"].store( float( (d.T * (numpy.asmatrix(numpy.ravel(Y)).T-numpy.asmatrix(numpy.ravel(HXa)).T)) ) / TraceR )
3505     if selfA._toStore("MahalanobisConsistency"):
3506         selfA.StoredVariables["MahalanobisConsistency"].store( float( 2.*MinJ/d.size ) )
3507     if selfA._toStore("SimulationQuantiles"):
3508         QuantilesEstimations(selfA, A, Xa, HXa, Hm, HtM)
3509     if selfA._toStore("SimulatedObservationAtBackground"):
3510         selfA.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
3511     if selfA._toStore("SimulatedObservationAtOptimum"):
3512         selfA.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
3513     #
3514     return 0
3515
3516 # ==============================================================================
3517 if __name__ == "__main__":
3518     print('\n AUTODIAGNOSTIC\n')