1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2021 EDF R&D
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.
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.
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
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
24 Définit les objets numériques génériques.
26 __author__ = "Jean-Philippe ARGAUD"
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)
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 )
48 __HX = __fonction( __X )
49 return numpy.ravel( __HX )
51 # ==============================================================================
52 class FDApproximation(object):
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.
63 name = "FDApproximation",
68 extraArguments = None,
69 avoidingRedundancy = True,
70 toleranceInRedundancy = 1.e-18,
71 lenghtOfRedundancy = -1,
76 self.__name = str(name)
77 self.__extraArgs = extraArguments
80 import multiprocessing
81 self.__mpEnabled = True
83 self.__mpEnabled = False
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))
92 self.__mfEnabled = True
94 self.__mfEnabled = False
95 logging.debug("FDA Calculs en multifonctions : %s"%(self.__mfEnabled,))
97 if avoidingRedundancy:
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
107 self.__avoidRC = False
110 if isinstance(Function,types.FunctionType):
111 logging.debug("FDA Calculs en multiprocessing : FunctionType")
112 self.__userFunction__name = Function.__name__
114 mod = os.path.join(Function.__globals__['filepath'],Function.__globals__['filename'])
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)
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__
128 mod = os.path.join(Function.__globals__['filepath'],Function.__globals__['filename'])
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)
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
139 raise TypeError("User defined function or method has to be provided for finite differences approximation.")
141 self.__userOperator = Operator( name = self.__name, fromMethod = Function, avoidingRedundancy = self.__avoidRC, inputAsMultiFunction = self.__mfEnabled, extraArguments = self.__extraArgs )
142 self.__userFunction = self.__userOperator.appliedTo
144 self.__centeredDF = bool(centeredDF)
145 if abs(float(increment)) > 1.e-15:
146 self.__increment = float(increment)
148 self.__increment = 0.01
152 self.__dX = numpy.asmatrix(numpy.ravel( dX )).T
153 logging.debug("FDA Reduction des doublons de calcul : %s"%self.__avoidRC)
155 logging.debug("FDA Tolerance de determination des doublons : %.2e"%self.__tolerBP)
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))
167 # ---------------------------------------------------------
168 def DirectOperator(self, X, **extraArgs ):
170 Calcul du direct à l'aide de la fonction fournie.
172 NB : les extraArgs sont là pour assurer la compatibilité d'appel, mais
173 ne doivent pas être données ici à la fonction utilisateur.
175 logging.debug("FDA Calcul DirectOperator (explicite)")
177 _HX = self.__userFunction( X, argsAsSerie = True )
179 _X = numpy.asmatrix(numpy.ravel( X )).T
180 _HX = numpy.ravel(self.__userFunction( _X ))
184 # ---------------------------------------------------------
185 def TangentMatrix(self, X ):
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.
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 =
196 2/ On effectue les différences (HX_plus_dXi-HX_moins_dXi) et on divise par
198 3/ Chaque résultat, par composante, devient une colonne de la Jacobienne
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
207 4/ Chaque résultat, par composante, devient une colonne de la Jacobienne
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))
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),))
217 _X = numpy.asmatrix(numpy.ravel( X )).T
219 if self.__dX is None:
220 _dX = self.__increment * _X
222 _dX = numpy.asmatrix(numpy.ravel( self.__dX )).T
224 if (_dX == 0.).any():
227 _dX = numpy.where( _dX == 0., float(self.__increment), _dX )
229 _dX = numpy.where( _dX == 0., moyenne, _dX )
231 __alreadyCalculated = False
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)
239 if __alreadyCalculated:
240 logging.debug("FDA Calcul Jacobienne (par récupération du doublon %i)"%__i)
241 _Jacobienne = self.__listJPCR[__i]
243 logging.debug("FDA Calcul Jacobienne (explicite)")
244 if self.__centeredDF:
246 if self.__mpEnabled and not self.__mfEnabled:
248 "__userFunction__path" : self.__userFunction__path,
249 "__userFunction__modl" : self.__userFunction__modl,
250 "__userFunction__name" : self.__userFunction__name,
253 for i in range( len(_dX) ):
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
260 _jobs.append( (_X_plus_dXi, self.__extraArgs, funcrepr) )
261 _jobs.append( (_X_moins_dXi, self.__extraArgs, funcrepr) )
263 import multiprocessing
264 self.__pool = multiprocessing.Pool(self.__mpWorkers)
265 _HX_plusmoins_dX = self.__pool.map( ExecuteFunction, _jobs )
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]) )
273 elif self.__mfEnabled:
275 for i in range( len(_dX) ):
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
282 _xserie.append( _X_plus_dXi )
283 _xserie.append( _X_moins_dXi )
285 _HX_plusmoins_dX = self.DirectOperator( _xserie )
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]) )
293 for i in range( _dX.size ):
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
300 _HX_plus_dXi = self.DirectOperator( _X_plus_dXi )
301 _HX_moins_dXi = self.DirectOperator( _X_moins_dXi )
303 _Jacobienne.append( numpy.ravel( _HX_plus_dXi - _HX_moins_dXi ) / (2.*_dXi) )
307 if self.__mpEnabled and not self.__mfEnabled:
309 "__userFunction__path" : self.__userFunction__path,
310 "__userFunction__modl" : self.__userFunction__modl,
311 "__userFunction__name" : self.__userFunction__name,
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]
319 _jobs.append( (_X_plus_dXi, self.__extraArgs, funcrepr) )
321 import multiprocessing
322 self.__pool = multiprocessing.Pool(self.__mpWorkers)
323 _HX_plus_dX = self.__pool.map( ExecuteFunction, _jobs )
327 _HX = _HX_plus_dX.pop(0)
330 for i in range( len(_dX) ):
331 _Jacobienne.append( numpy.ravel(( _HX_plus_dX[i] - _HX ) / _dX[i]) )
333 elif self.__mfEnabled:
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]
340 _xserie.append( _X_plus_dXi )
342 _HX_plus_dX = self.DirectOperator( _xserie )
344 _HX = _HX_plus_dX.pop(0)
347 for i in range( len(_dX) ):
348 _Jacobienne.append( numpy.ravel(( _HX_plus_dX[i] - _HX ) / _dX[i]) )
352 _HX = self.DirectOperator( _X )
353 for i in range( _dX.size ):
355 _X_plus_dXi = numpy.array( _X.A1, dtype=float )
356 _X_plus_dXi[i] = _X[i] + _dXi
358 _HX_plus_dXi = self.DirectOperator( _X_plus_dXi )
360 _Jacobienne.append( numpy.ravel(( _HX_plus_dXi - _HX ) / _dXi) )
363 _Jacobienne = numpy.asmatrix( numpy.vstack( _Jacobienne ) ).T
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) )
378 logging.debug("FDA Fin du calcul de la Jacobienne")
382 # ---------------------------------------------------------
383 def TangentOperator(self, paire, **extraArgs ):
385 Calcul du tangent à l'aide de la Jacobienne.
387 NB : les extraArgs sont là pour assurer la compatibilité d'appel, mais
388 ne doivent pas être données ici à la fonction utilisateur.
391 assert len(paire) == 1, "Incorrect lenght of arguments"
393 assert len(_paire) == 2, "Incorrect number of arguments"
395 assert len(paire) == 2, "Incorrect number of arguments"
398 _Jacobienne = self.TangentMatrix( X )
399 if dX is None or len(dX) == 0:
401 # Calcul de la forme matricielle si le second argument est None
402 # -------------------------------------------------------------
403 if self.__mfEnabled: return [_Jacobienne,]
404 else: return _Jacobienne
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,]
414 # ---------------------------------------------------------
415 def AdjointOperator(self, paire, **extraArgs ):
417 Calcul de l'adjoint à l'aide de la Jacobienne.
419 NB : les extraArgs sont là pour assurer la compatibilité d'appel, mais
420 ne doivent pas être données ici à la fonction utilisateur.
423 assert len(paire) == 1, "Incorrect lenght of arguments"
425 assert len(_paire) == 2, "Incorrect number of arguments"
427 assert len(paire) == 2, "Incorrect number of arguments"
430 _JacobienneT = self.TangentMatrix( X ).T
431 if Y is None or len(Y) == 0:
433 # Calcul de la forme matricielle si le second argument est None
434 # -------------------------------------------------------------
435 if self.__mfEnabled: return [_JacobienneT,]
436 else: return _JacobienneT
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,]
446 # ==============================================================================
447 def EnsembleOfCenteredPerturbations( _bgcenter, _bgcovariance, _nbmembers ):
448 "Génération d'un ensemble de taille _nbmembers-1 d'états aléatoires centrés"
450 _bgcenter = numpy.ravel(_bgcenter)[:,None]
452 raise ValueError("Number of members has to be strictly more than 1 (given number: %s)."%(str(_nbmembers),))
454 if _bgcovariance is None:
455 BackgroundEnsemble = numpy.tile( _bgcenter, _nbmembers)
457 _Z = numpy.random.multivariate_normal(numpy.zeros(_bgcenter.size), _bgcovariance, size=_nbmembers).T
458 BackgroundEnsemble = numpy.tile( _bgcenter, _nbmembers) + _Z
460 return BackgroundEnsemble
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):
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
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)))
478 _bgcenter = numpy.ravel(_bgcenter).reshape((-1,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)
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)
492 _Z = numpy.dot(numpy.diag(numpy.sqrt(s[:_nbmembers-1])), V[:_nbmembers-1])
493 _Zca = __CenteredRandomAnomalies(_Z, _nbmembers)
494 BackgroundEnsemble = _bgcenter + _Zca
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
502 BackgroundEnsemble = numpy.tile( _bgcenter, _nbmembers)
504 return BackgroundEnsemble
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))
511 # ==============================================================================
512 def EnsembleOfAnomalies( Ensemble, OptMean = None, Normalisation = 1.):
513 "Renvoie les anomalies centrées à partir d'un ensemble"
515 __Em = EnsembleMean( Ensemble )
517 __Em = numpy.ravel(OptMean).reshape((-1,1))
519 return Normalisation * (numpy.asarray(Ensemble) - __Em)
521 # ==============================================================================
522 def EnsembleErrorCovariance( Ensemble, __quick = False ):
523 "Renvoie l'estimation empirique de la covariance d'ensemble"
525 # Covariance rapide mais rarement définie positive
526 __Covariance = numpy.cov(Ensemble)
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)
534 __Covariance = (__Covariance + __Covariance.T) * 0.5
535 # Assure la positivité
536 __epsilon = mpr*numpy.trace(__Covariance)
537 __Covariance = __Covariance + __epsilon * numpy.identity(__n)
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
548 if (abs(__Ensemble).mean() <= mpr) and (abs(__Covariance.assparsematrix()) < mpr).all():
549 # Traitement d'une covariance nulle ou presque
552 if (abs(__Ensemble).mean() > mpr) and (abs(__Covariance)/abs(__Ensemble).mean() < mpr).all():
553 # Traitement d'une covariance nulle ou presque
555 if (abs(__Ensemble).mean() <= mpr) and (abs(__Covariance) < mpr).all():
556 # Traitement d'une covariance nulle ou presque
559 __n, __m = __Ensemble.shape
560 if __Seed is not None: numpy.random.seed(__Seed)
562 if hasattr(__Covariance,"isscalar") and __Covariance.isscalar():
563 # Traitement d'une covariance multiple de l'identité
565 __std = numpy.sqrt(__Covariance.assparsematrix())
566 __Ensemble += numpy.random.normal(__zero, __std, size=(__m,__n)).T
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
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
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
583 raise ValueError("Error in ensemble perturbation with inadequate covariance specification")
587 # ==============================================================================
588 def CovarianceInflation(
590 InflationType = None,
591 InflationFactor = None,
592 BackgroundCov = None,
595 Inflation applicable soit sur Pb ou Pa, soit sur les ensembles EXb ou EXa
597 Synthèse : Hunt 2007, section 2.3.5
599 if InflationFactor is None:
602 InflationFactor = float(InflationFactor)
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:
609 OutputCovOrEns = InflationFactor**2 * InputCovOrEns
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:
616 InputCovOrEnsMean = InputCovOrEns.mean(axis=1, dtype=mfp).astype('float')
617 OutputCovOrEns = InputCovOrEnsMean[:,numpy.newaxis] \
618 + InflationFactor * (InputCovOrEns - InputCovOrEnsMean[:,numpy.newaxis])
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:
625 __n, __m = numpy.asarray(InputCovOrEns).shape
627 raise ValueError("Additive inflation can only be applied to squared (covariance) matrix.")
628 OutputCovOrEns = (1. - InflationFactor) * InputCovOrEns + InflationFactor * numpy.identity(__n)
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:
635 __n, __m = numpy.asarray(InputCovOrEns).shape
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
644 elif InflationType == "Relaxation":
645 raise NotImplementedError("InflationType Relaxation")
648 raise ValueError("Error in inflation type, '%s' is not a valid keyword."%InflationType)
650 return OutputCovOrEns
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"]
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
664 if LBounds is not None:
665 def NoneRemove(paire):
667 if bmin is None: bmin = numpy.finfo('float').min
668 if bmax is None: bmax = numpy.finfo('float').max
670 LBounds = numpy.matrix( [NoneRemove(paire) for paire in LBounds] )
672 # Échantillonnage des états
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
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
693 raise ValueError("Quantile simulations has only to be Linear or NonLinear.")
697 if selfA._toStore("SampledStateForQuantiles"): EXr = numpy.ravel(Xr)
699 YfQ = numpy.hstack((YfQ,Yr))
700 if selfA._toStore("SampledStateForQuantiles"): EXr = numpy.vstack((EXr,numpy.ravel(Xr)))
702 # Extraction des quantiles
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 )
716 # ==============================================================================
717 def enks(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, VariantM="EnKS16-KalmanFilterFormula"):
723 H = HO["Direct"].appliedControledFormTo
725 if selfA._parameters["EstimationOf"] == "State":
726 M = EM["Direct"].appliedControledFormTo
728 if CM is not None and "Tangent" in CM and U is not None:
729 Cm = CM["Tangent"].asMatrix(Xb)
733 # Précalcul des inversions de B et R
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]
745 __m = selfA._parameters["NumberOfMembers"]
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) )
753 selfA.StoredVariables["APosterioriCovariance"].store( B )
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")
762 raise ValueError("VariantM has to be chosen in the authorized methods list.")
764 EL = selfB.StoredVariables["CurrentEnsembleState"][LagL-1]
766 EL = EnsembleOfBackgroundPerturbations( Xb, None, __m ) # Cf. etkf
767 selfA._parameters["SetSeed"] = numpy.random.set_state(__seed)
769 for step in range(LagL,duration-1):
771 sEL = selfB.StoredVariables["CurrentEnsembleState"][step+1-LagL:step+1]
774 if hasattr(Y,"store"):
775 Ynpu = numpy.ravel( Y[step+1] ).reshape((__p,1))
777 Ynpu = numpy.ravel( Y ).reshape((__p,1))
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
785 Un = numpy.asmatrix(numpy.ravel( U )).T
789 #--------------------------
790 if VariantM == "EnKS16-KalmanFilterFormula":
791 if selfA._parameters["EstimationOf"] == "State": # Forecast
792 EL = M( [(EL[:,i], Un) for i in range(__m)],
794 returnSerieAsArrayMatrix = True )
795 EL = EnsemblePerturbationWithGivenCovariance( EL, Q )
796 EZ = H( [(EL[:,i], Un) for i in range(__m)],
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
802 elif selfA._parameters["EstimationOf"] == "Parameters":
803 # --- > Par principe, M = Id, Q = 0
804 EZ = H( [(EL[:,i], Un) for i in range(__m)],
806 returnSerieAsArrayMatrix = True )
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))
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
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)
821 EX = EnsembleOfAnomalies( EL, vEm, 1./math.sqrt(__m-1) )
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
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"):
835 for irl in range(LagL):
836 sEL[irl] = sEL[irl+1]
838 #--------------------------
840 raise ValueError("VariantM has to be chosen in the authorized methods list.")
842 selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
844 selfA.StoredVariables["Analysis"].store( Xa )
845 if selfA._toStore("APosterioriCovariance"):
846 selfA.StoredVariables["APosterioriCovariance"].store( EnsembleErrorCovariance(EXn) )
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 )
856 # ==============================================================================
857 def etkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, VariantM="KalmanFilterFormula"):
859 Ensemble-Transform EnKF
861 if selfA._parameters["EstimationOf"] == "Parameters":
862 selfA._parameters["StoreInternalVariables"] = True
865 H = HO["Direct"].appliedControledFormTo
867 if selfA._parameters["EstimationOf"] == "State":
868 M = EM["Direct"].appliedControledFormTo
870 if CM is not None and "Tangent" in CM and U is not None:
871 Cm = CM["Tangent"].asMatrix(Xb)
875 # Durée d'observation et tailles
876 if hasattr(Y,"stepnumber"):
877 duration = Y.stepnumber()
878 __p = numpy.cumprod(Y.shape())[-1]
881 __p = numpy.array(Y).size
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"):
892 elif VariantM != "KalmanFilterFormula":
894 if VariantM == "KalmanFilterFormula":
898 __m = selfA._parameters["NumberOfMembers"]
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) )
907 selfA.StoredVariables["APosterioriCovariance"].store( B )
908 selfA._setInternalState("seed", numpy.random.get_state())
909 elif selfA._parameters["nextStep"]:
910 Xn = selfA._getInternalState("Xn")
912 previousJMinimum = numpy.finfo(float).max
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))
919 Ynpu = numpy.ravel( Y ).reshape((__p,1))
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
927 Un = numpy.asmatrix(numpy.ravel( U )).T
931 if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
932 Xn = CovarianceInflation( Xn,
933 selfA._parameters["InflationType"],
934 selfA._parameters["InflationFactor"],
937 if selfA._parameters["EstimationOf"] == "State": # Forecast + Q and observation of forecast
938 EMX = M( [(Xn[:,i], Un) for i in range(__m)],
940 returnSerieAsArrayMatrix = True )
941 Xn_predicted = EnsemblePerturbationWithGivenCovariance( EMX, Q )
942 HX_predicted = H( [(Xn_predicted[:,i], Un) for i in range(__m)],
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)],
953 returnSerieAsArrayMatrix = True )
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))
960 EaX = EnsembleOfAnomalies( Xn_predicted, Xfm )
961 EaHX = EnsembleOfAnomalies( HX_predicted, Hfm)
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
971 Tdemi = numpy.real(scipy.linalg.sqrtm(mT))
972 mU = numpy.identity(__m)
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
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
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(
993 x0 = numpy.zeros(__m),
994 fprime = GradientOfCostFunction,
999 Hto = EaHX.T @ (RI * EaHX).reshape((-1,__m))
1000 Htb = (__m-1) * numpy.identity(__m)
1003 Pta = numpy.linalg.inv( Hta )
1004 EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
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)
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(
1024 x0 = numpy.zeros(__m),
1025 fprime = GradientOfCostFunction,
1030 Hto = EaHX.T @ (RI * EaHX).reshape((-1,__m))
1032 ( (1 + 1/__m + vw.T @ vw) * numpy.identity(__m) - 2 * vw @ vw.T ) \
1033 / (1 + 1/__m + vw.T @ vw)**2
1036 Pta = numpy.linalg.inv( Hta )
1037 EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
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)
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(
1057 x0 = numpy.zeros(__m),
1058 fprime = GradientOfCostFunction,
1063 Hto = EaHX.T @ (RI * EaHX).reshape((-1,__m))
1065 ( (1 + 1/__m + vw.T @ vw) * numpy.identity(__m) - 2 * vw @ vw.T ) \
1066 / (1 + 1/__m + vw.T @ vw)**2
1069 Pta = numpy.linalg.inv( Hta )
1070 EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
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))
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(
1090 x0 = numpy.zeros(__m),
1091 fprime = GradientOfCostFunction,
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
1102 Pta = numpy.linalg.inv( Hta )
1103 EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1105 Xn = Xfm + EaX @ (vw[:,None] + EWa)
1106 #--------------------------
1108 raise ValueError("VariantM has to be chosen in the authorized methods list.")
1110 if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
1111 Xn = CovarianceInflation( Xn,
1112 selfA._parameters["InflationType"],
1113 selfA._parameters["InflationFactor"],
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 #--------------------------
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
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 )
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 )
1165 selfA.StoredVariables["CostFunctionJb"].store( Jb )
1166 selfA.StoredVariables["CostFunctionJo"].store( Jo )
1167 selfA.StoredVariables["CostFunctionJ" ].store( J )
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
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 )
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) )
1212 # ==============================================================================
1213 def exkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q):
1215 Extended Kalman Filter
1217 if selfA._parameters["EstimationOf"] == "Parameters":
1218 selfA._parameters["StoreInternalVariables"] = True
1221 H = HO["Direct"].appliedControledFormTo
1223 if selfA._parameters["EstimationOf"] == "State":
1224 M = EM["Direct"].appliedControledFormTo
1226 if CM is not None and "Tangent" in CM and U is not None:
1227 Cm = CM["Tangent"].asMatrix(Xb)
1231 # Durée d'observation et tailles
1232 if hasattr(Y,"stepnumber"):
1233 duration = Y.stepnumber()
1234 __p = numpy.cumprod(Y.shape())[-1]
1237 __p = numpy.array(Y).size
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"):
1251 if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
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) )
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")
1266 previousJMinimum = numpy.finfo(float).max
1268 for step in range(duration-1):
1269 if hasattr(Y,"store"):
1270 Ynpu = numpy.ravel( Y[step+1] ).reshape((__p,1))
1272 Ynpu = numpy.ravel( Y ).reshape((__p,1))
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
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
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
1291 Un = numpy.asmatrix(numpy.ravel( U )).T
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
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)
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
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
1324 #--------------------------
1325 selfA._setInternalState("Xn", Xn)
1326 selfA._setInternalState("Pn", Pn)
1327 #--------------------------
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
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 )
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 )
1371 selfA.StoredVariables["CostFunctionJb"].store( Jb )
1372 selfA.StoredVariables["CostFunctionJo"].store( Jo )
1373 selfA.StoredVariables["CostFunctionJ" ].store( J )
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
1400 if selfA._toStore("APosterioriCovariance"):
1401 covarianceXaMin = selfA.StoredVariables["APosterioriCovariance"][-1]
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) )
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):
1421 if selfA._parameters["EstimationOf"] == "Parameters":
1422 selfA._parameters["StoreInternalVariables"] = True
1425 H = HO["Direct"].appliedControledFormTo
1427 if selfA._parameters["EstimationOf"] == "State":
1428 M = EM["Direct"].appliedControledFormTo
1430 if CM is not None and "Tangent" in CM and U is not None:
1431 Cm = CM["Tangent"].asMatrix(Xb)
1435 # Durée d'observation et tailles
1436 if hasattr(Y,"stepnumber"):
1437 duration = Y.stepnumber()
1438 __p = numpy.cumprod(Y.shape())[-1]
1441 __p = numpy.array(Y).size
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"):
1454 __m = selfA._parameters["NumberOfMembers"]
1456 if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
1457 if hasattr(B,"asfullmatrix"): Pn = B.asfullmatrix(__n)
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) )
1465 selfA.StoredVariables["APosterioriCovariance"].store( B )
1466 selfA._setInternalState("seed", numpy.random.get_state())
1467 elif selfA._parameters["nextStep"]:
1468 Xn = selfA._getInternalState("Xn")
1470 previousJMinimum = numpy.finfo(float).max
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))
1477 Ynpu = numpy.ravel( Y ).reshape((__p,1))
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
1485 Un = numpy.asmatrix(numpy.ravel( U )).T
1489 if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
1490 Xn = CovarianceInflation( Xn,
1491 selfA._parameters["InflationType"],
1492 selfA._parameters["InflationFactor"],
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)
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))
1508 E1 = vx1 + _epsilon * EaX
1510 E1 = vx1 + math.sqrt(__m-1) * EaX @ Ta
1512 if selfA._parameters["EstimationOf"] == "State": # Forecast + Q
1513 E2 = M( [(E1[:,i,numpy.newaxis], Un) for i in range(__m)],
1515 returnSerieAsArrayMatrix = True )
1516 elif selfA._parameters["EstimationOf"] == "Parameters":
1517 # --- > Par principe, M = Id
1519 vx2 = E2.mean(axis=1, dtype=mfp).astype('float').reshape((__n,1))
1520 vy1 = H((vx2, Un)).reshape((__p,1))
1522 HE2 = H( [(E2[:,i,numpy.newaxis], Un) for i in range(__m)],
1524 returnSerieAsArrayMatrix = True )
1525 vy2 = HE2.mean(axis=1, dtype=mfp).astype('float').reshape((__p,1))
1528 EaY = (HE2 - vy2) / _epsilon
1530 EaY = ( (HE2 - vy2) @ numpy.linalg.inv(Ta) ) / math.sqrt(__m-1)
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)
1539 Ta = numpy.real(scipy.linalg.sqrtm(numpy.linalg.inv( mH )))
1543 A2 = EnsembleOfAnomalies( E2 )
1546 Ta = numpy.real(scipy.linalg.sqrtm(numpy.linalg.inv( mH )))
1547 A2 = math.sqrt(__m-1) * A2 @ Ta / _epsilon
1550 #--------------------------
1552 raise ValueError("VariantM has to be chosen in the authorized methods list.")
1554 if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
1555 Xn = CovarianceInflation( Xn,
1556 selfA._parameters["InflationType"],
1557 selfA._parameters["InflationFactor"],
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 #--------------------------
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
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 )
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 )
1609 selfA.StoredVariables["CostFunctionJb"].store( Jb )
1610 selfA.StoredVariables["CostFunctionJo"].store( Jo )
1611 selfA.StoredVariables["CostFunctionJ" ].store( J )
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
1638 if selfA._toStore("APosterioriCovariance"):
1639 covarianceXaMin = selfA.StoredVariables["APosterioriCovariance"][-1]
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) )
1653 # ==============================================================================
1654 def incr3dvar(selfA, Xb, Y, U, HO, EM, CM, R, B, Q):
1662 # Opérateur non-linéaire pour la boucle externe
1663 Hm = HO["Direct"].appliedTo
1665 # Précalcul des inversions de B et R
1669 # Point de démarrage de l'optimisation
1670 Xini = selfA._parameters["InitializationPoint"]
1672 HXb = numpy.asmatrix(numpy.ravel( Hm( Xb ) )).T
1673 Innovation = Y - HXb
1680 Xr = Xini.reshape((-1,1))
1681 while abs(DeltaJ) >= selfA._parameters["CostDecrementTolerance"] and iOuter <= selfA._parameters["MaximumNumberOfSteps"]:
1685 Ht = HO["Tangent"].asMatrix(Xr)
1686 Ht = Ht.reshape(Y.size,Xr.size) # ADAO & check shape
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 )
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 )
1705 Jb = float( 0.5 * _dX.T * BI * _dX )
1706 Jo = float( 0.5 * _dInnovation.T * RI * _dInnovation )
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] )
1734 def GradientOfCostFunction(dx):
1735 _dX = numpy.asmatrix(numpy.ravel( dx )).T
1737 _HdX = numpy.asmatrix(numpy.ravel( _HdX )).T
1738 _dInnovation = Innovation - _HdX
1740 GradJo = - Ht.T @ (RI * _dInnovation)
1741 GradJ = numpy.ravel( GradJb ) + numpy.ravel( GradJo )
1744 # Minimisation de la fonctionnelle
1745 # --------------------------------
1746 nbPreviousSteps = selfA.StoredVariables["CostFunctionJ"].stepnumber()
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
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,
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"],
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,
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"],
1779 elif selfA._parameters["Minimizer"] == "CG":
1780 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
1782 x0 = numpy.zeros(Xini.size),
1783 fprime = GradientOfCostFunction,
1785 maxiter = selfA._parameters["MaximumNumberOfSteps"],
1786 gtol = selfA._parameters["GradientNormTolerance"],
1787 disp = selfA._parameters["optdisp"],
1790 elif selfA._parameters["Minimizer"] == "NCG":
1791 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
1793 x0 = numpy.zeros(Xini.size),
1794 fprime = GradientOfCostFunction,
1796 maxiter = selfA._parameters["MaximumNumberOfSteps"],
1797 avextol = selfA._parameters["CostDecrementTolerance"],
1798 disp = selfA._parameters["optdisp"],
1801 elif selfA._parameters["Minimizer"] == "BFGS":
1802 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
1804 x0 = numpy.zeros(Xini.size),
1805 fprime = GradientOfCostFunction,
1807 maxiter = selfA._parameters["MaximumNumberOfSteps"],
1808 gtol = selfA._parameters["GradientNormTolerance"],
1809 disp = selfA._parameters["optdisp"],
1813 raise ValueError("Error in Minimizer name: %s"%selfA._parameters["Minimizer"])
1815 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
1816 MinJ = selfA.StoredVariables["CostFunctionJ"][IndexMin]
1818 if selfA._parameters["StoreInternalVariables"] or selfA._toStore("CurrentState"):
1819 Minimum = selfA.StoredVariables["CurrentState"][IndexMin]
1820 Minimum = numpy.asmatrix(numpy.ravel( Minimum )).T
1822 Minimum = Xb + numpy.asmatrix(numpy.ravel( Minimum )).T
1825 DeltaJ = selfA.StoredVariables["CostFunctionJ" ][-1] - J
1826 iOuter = selfA.StoredVariables["CurrentIterationNumber"][-1]
1828 # Obtention de l'analyse
1829 # ----------------------
1832 selfA.StoredVariables["Analysis"].store( Xa )
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]
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"):
1863 _ee = numpy.matrix(numpy.zeros(nb)).T
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 )
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
1876 L = numpy.linalg.cholesky( A )
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 )
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"):
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) )
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):
1921 Maximum Likelihood Ensemble Filter
1923 if selfA._parameters["EstimationOf"] == "Parameters":
1924 selfA._parameters["StoreInternalVariables"] = True
1927 H = HO["Direct"].appliedControledFormTo
1929 if selfA._parameters["EstimationOf"] == "State":
1930 M = EM["Direct"].appliedControledFormTo
1932 if CM is not None and "Tangent" in CM and U is not None:
1933 Cm = CM["Tangent"].asMatrix(Xb)
1937 # Durée d'observation et tailles
1938 if hasattr(Y,"stepnumber"):
1939 duration = Y.stepnumber()
1940 __p = numpy.cumprod(Y.shape())[-1]
1943 __p = numpy.array(Y).size
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"):
1956 __m = selfA._parameters["NumberOfMembers"]
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) )
1965 selfA.StoredVariables["APosterioriCovariance"].store( B )
1966 selfA._setInternalState("seed", numpy.random.get_state())
1967 elif selfA._parameters["nextStep"]:
1968 Xn = selfA._getInternalState("Xn")
1970 previousJMinimum = numpy.finfo(float).max
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))
1977 Ynpu = numpy.ravel( Y ).reshape((__p,1))
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
1985 Un = numpy.asmatrix(numpy.ravel( U )).T
1989 if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
1990 Xn = CovarianceInflation( Xn,
1991 selfA._parameters["InflationType"],
1992 selfA._parameters["InflationFactor"],
1995 if selfA._parameters["EstimationOf"] == "State": # Forecast + Q and observation of forecast
1996 EMX = M( [(Xn[:,i], Un) for i in range(__m)],
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
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)
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))
2021 E1 = vx1 + _epsilon * EaX
2023 E1 = vx1 + math.sqrt(__m-1) * EaX @ Ta
2025 HE2 = H( [(E1[:,i,numpy.newaxis], Un) for i in range(__m)],
2027 returnSerieAsArrayMatrix = True )
2028 vy2 = HE2.mean(axis=1, dtype=mfp).astype('float').reshape((__p,1))
2031 EaY = (HE2 - vy2) / _epsilon
2033 EaY = ( (HE2 - vy2) @ numpy.linalg.inv(Ta) ) / math.sqrt(__m-1)
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)
2042 Ta = numpy.real(scipy.linalg.sqrtm(numpy.linalg.inv( mH )))
2047 Ta = numpy.real(scipy.linalg.sqrtm(numpy.linalg.inv( mH )))
2049 Xn = vx1 + math.sqrt(__m-1) * EaX @ Ta @ Ua
2050 #--------------------------
2052 raise ValueError("VariantM has to be chosen in the authorized methods list.")
2054 if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
2055 Xn = CovarianceInflation( Xn,
2056 selfA._parameters["InflationType"],
2057 selfA._parameters["InflationFactor"],
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 #--------------------------
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
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 )
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 )
2109 selfA.StoredVariables["CostFunctionJb"].store( Jb )
2110 selfA.StoredVariables["CostFunctionJo"].store( Jo )
2111 selfA.StoredVariables["CostFunctionJ" ].store( J )
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
2138 if selfA._toStore("APosterioriCovariance"):
2139 covarianceXaMin = selfA.StoredVariables["APosterioriCovariance"][-1]
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) )
2153 # ==============================================================================
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.
2170 # Recuperation des donnees et informations initiales
2171 # --------------------------------------------------
2172 variables = numpy.ravel( x0 )
2173 mesures = numpy.ravel( y )
2174 increment = sys.float_info[0]
2177 quantile = float(quantile)
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))
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)
2193 # Recherche iterative
2194 # -------------------
2195 while (increment > toler) and (iteration < maxfun) :
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]
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() ):
2210 variables = variables - step
2211 residus = mesures - numpy.ravel( func(variables) )
2212 surrogate = numpy.sum(residus**2 * poids) + (4.*quantile-2.) * numpy.sum(residus)
2214 while ( (surrogate > lastsurrogate) and ( max(list(numpy.abs(step))) > 1.e-16 ) ) :
2216 variables = variables - step
2217 residus = mesures - numpy.ravel( func(variables) )
2218 surrogate = numpy.sum(residus**2 * poids) + (4.*quantile-2.) * numpy.sum(residus)
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)
2227 Ecart = quantile * numpy.sum(residus) - numpy.sum( residus[residus<0] )
2229 return variables, Ecart, [n,p,iteration,increment,0]
2231 # ==============================================================================
2232 def multi3dvar(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, oneCycle):
2234 3DVAR multi-pas et multi-méthodes
2238 if selfA._parameters["EstimationOf"] == "State":
2239 M = EM["Direct"].appliedTo
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) )
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")
2254 Xn = numpy.ravel(Xb).reshape((-1,1))
2256 if hasattr(Y,"stepnumber"):
2257 duration = Y.stepnumber()
2262 for step in range(duration-1):
2263 if hasattr(Y,"store"):
2264 Ynpu = numpy.ravel( Y[step+1] ).reshape((-1,1))
2266 Ynpu = numpy.ravel( Y ).reshape((-1,1))
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
2275 Xn_predicted = numpy.ravel(Xn_predicted).reshape((-1,1))
2277 oneCycle(selfA, Xn_predicted, Ynpu, U, HO, None, None, R, B, None)
2279 Xn = selfA.StoredVariables["Analysis"][-1]
2280 #--------------------------
2281 selfA._setInternalState("Xn", Xn)
2285 # ==============================================================================
2286 def psas3dvar(selfA, Xb, Y, U, HO, EM, CM, R, B, Q):
2295 Hm = HO["Direct"].appliedTo
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"] )
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))
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 )
2313 Ht = HO["Tangent"].asMatrix(Xb)
2315 HBHTpR = R + Ht * BHT
2316 Innovation = Y - HXb
2318 # Point de démarrage de l'optimisation
2319 Xini = numpy.zeros(Xb.shape)
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 )
2335 Jb = float( 0.5 * _W.T * HBHTpR * _W )
2336 Jo = float( - _W.T * Innovation )
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] )
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 )
2371 # Minimisation de la fonctionnelle
2372 # --------------------------------
2373 nbPreviousSteps = selfA.StoredVariables["CostFunctionJ"].stepnumber()
2375 if selfA._parameters["Minimizer"] == "LBFGSB":
2376 if "0.19" <= scipy.version.version <= "1.1.0":
2377 import lbfgsbhlt as optimiseur
2379 import scipy.optimize as optimiseur
2380 Minimum, J_optimal, Informations = optimiseur.fmin_l_bfgs_b(
2381 func = CostFunction,
2383 fprime = GradientOfCostFunction,
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"],
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,
2397 fprime = GradientOfCostFunction,
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"],
2405 elif selfA._parameters["Minimizer"] == "CG":
2406 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
2409 fprime = GradientOfCostFunction,
2411 maxiter = selfA._parameters["MaximumNumberOfSteps"],
2412 gtol = selfA._parameters["GradientNormTolerance"],
2413 disp = selfA._parameters["optdisp"],
2416 elif selfA._parameters["Minimizer"] == "NCG":
2417 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
2420 fprime = GradientOfCostFunction,
2422 maxiter = selfA._parameters["MaximumNumberOfSteps"],
2423 avextol = selfA._parameters["CostDecrementTolerance"],
2424 disp = selfA._parameters["optdisp"],
2427 elif selfA._parameters["Minimizer"] == "BFGS":
2428 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
2431 fprime = GradientOfCostFunction,
2433 maxiter = selfA._parameters["MaximumNumberOfSteps"],
2434 gtol = selfA._parameters["GradientNormTolerance"],
2435 disp = selfA._parameters["optdisp"],
2439 raise ValueError("Error in Minimizer name: %s"%selfA._parameters["Minimizer"])
2441 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
2442 MinJ = selfA.StoredVariables["CostFunctionJ"][IndexMin]
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
2450 Minimum = Xb + BHT * numpy.asmatrix(numpy.ravel( Minimum )).T
2452 # Obtention de l'analyse
2453 # ----------------------
2456 selfA.StoredVariables["Analysis"].store( Xa )
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]
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"):
2489 _ee = numpy.matrix(numpy.zeros(nb)).T
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 )
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
2502 L = numpy.linalg.cholesky( A )
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 )
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"):
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) )
2543 # ==============================================================================
2544 def senkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, VariantM="KalmanFilterFormula16"):
2548 if selfA._parameters["EstimationOf"] == "Parameters":
2549 selfA._parameters["StoreInternalVariables"] = True
2552 H = HO["Direct"].appliedControledFormTo
2554 if selfA._parameters["EstimationOf"] == "State":
2555 M = EM["Direct"].appliedControledFormTo
2557 if CM is not None and "Tangent" in CM and U is not None:
2558 Cm = CM["Tangent"].asMatrix(Xb)
2562 # Durée d'observation et tailles
2563 if hasattr(Y,"stepnumber"):
2564 duration = Y.stepnumber()
2565 __p = numpy.cumprod(Y.shape())[-1]
2568 __p = numpy.array(Y).size
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"):
2581 __m = selfA._parameters["NumberOfMembers"]
2583 if hasattr(R,"asfullmatrix"): Rn = R.asfullmatrix(__p)
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) )
2593 selfA.StoredVariables["APosterioriCovariance"].store( B )
2594 selfA._setInternalState("seed", numpy.random.get_state())
2595 elif selfA._parameters["nextStep"]:
2596 Xn = selfA._getInternalState("Xn")
2598 previousJMinimum = numpy.finfo(float).max
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))
2605 Ynpu = numpy.ravel( Y ).reshape((__p,1))
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
2613 Un = numpy.asmatrix(numpy.ravel( U )).T
2617 if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
2618 Xn = CovarianceInflation( Xn,
2619 selfA._parameters["InflationType"],
2620 selfA._parameters["InflationFactor"],
2623 if selfA._parameters["EstimationOf"] == "State": # Forecast + Q and observation of forecast
2624 EMX = M( [(Xn[:,i], Un) for i in range(__m)],
2626 returnSerieAsArrayMatrix = True )
2627 Xn_predicted = EnsemblePerturbationWithGivenCovariance( EMX, Q )
2628 HX_predicted = H( [(Xn_predicted[:,i], Un) for i in range(__m)],
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)],
2639 returnSerieAsArrayMatrix = True )
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))
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
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))
2666 EaX = EnsembleOfAnomalies( Xn_predicted ) / math.sqrt(__m-1)
2667 EaY = (HX_predicted - Hfm - EpY + EpYm) / math.sqrt(__m-1)
2669 Kn = EaX @ EaY.T @ numpy.linalg.inv( EaY @ EaY.T)
2671 for i in range(__m):
2672 Xn[:,i] = numpy.ravel(Xn_predicted[:,i]) + Kn @ (numpy.ravel(EpY[:,i]) - HX_predicted[:,i])
2673 #--------------------------
2675 raise ValueError("VariantM has to be chosen in the authorized methods list.")
2677 if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
2678 Xn = CovarianceInflation( Xn,
2679 selfA._parameters["InflationType"],
2680 selfA._parameters["InflationFactor"],
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 #--------------------------
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
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 )
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 )
2732 selfA.StoredVariables["CostFunctionJb"].store( Jb )
2733 selfA.StoredVariables["CostFunctionJo"].store( Jo )
2734 selfA.StoredVariables["CostFunctionJ" ].store( J )
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
2761 if selfA._toStore("APosterioriCovariance"):
2762 covarianceXaMin = selfA.StoredVariables["APosterioriCovariance"][-1]
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) )
2776 # ==============================================================================
2777 def std3dvar(selfA, Xb, Y, U, HO, EM, CM, R, B, Q):
2786 Hm = HO["Direct"].appliedTo
2787 Ha = HO["Adjoint"].appliedInXTo
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"] )
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))
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 )
2805 # Précalcul des inversions de B et R
2809 # Point de démarrage de l'optimisation
2810 Xini = selfA._parameters["InitializationPoint"]
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 )
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 )
2829 Jb = float( 0.5 * (_X - Xb).T * BI * (_X - Xb) )
2830 Jo = float( 0.5 * _Innovation.T * RI * _Innovation )
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] )
2858 def GradientOfCostFunction(x):
2859 _X = numpy.asmatrix(numpy.ravel( x )).T
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 )
2867 # Minimisation de la fonctionnelle
2868 # --------------------------------
2869 nbPreviousSteps = selfA.StoredVariables["CostFunctionJ"].stepnumber()
2871 if selfA._parameters["Minimizer"] == "LBFGSB":
2872 if "0.19" <= scipy.version.version <= "1.1.0":
2873 import lbfgsbhlt as optimiseur
2875 import scipy.optimize as optimiseur
2876 Minimum, J_optimal, Informations = optimiseur.fmin_l_bfgs_b(
2877 func = CostFunction,
2879 fprime = GradientOfCostFunction,
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"],
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,
2893 fprime = GradientOfCostFunction,
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"],
2901 elif selfA._parameters["Minimizer"] == "CG":
2902 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
2905 fprime = GradientOfCostFunction,
2907 maxiter = selfA._parameters["MaximumNumberOfSteps"],
2908 gtol = selfA._parameters["GradientNormTolerance"],
2909 disp = selfA._parameters["optdisp"],
2912 elif selfA._parameters["Minimizer"] == "NCG":
2913 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
2916 fprime = GradientOfCostFunction,
2918 maxiter = selfA._parameters["MaximumNumberOfSteps"],
2919 avextol = selfA._parameters["CostDecrementTolerance"],
2920 disp = selfA._parameters["optdisp"],
2923 elif selfA._parameters["Minimizer"] == "BFGS":
2924 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
2927 fprime = GradientOfCostFunction,
2929 maxiter = selfA._parameters["MaximumNumberOfSteps"],
2930 gtol = selfA._parameters["GradientNormTolerance"],
2931 disp = selfA._parameters["optdisp"],
2935 raise ValueError("Error in Minimizer name: %s"%selfA._parameters["Minimizer"])
2937 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
2938 MinJ = selfA.StoredVariables["CostFunctionJ"][IndexMin]
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]
2945 # Obtention de l'analyse
2946 # ----------------------
2947 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
2949 selfA.StoredVariables["Analysis"].store( Xa )
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]
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"):
2980 _ee = numpy.matrix(numpy.zeros(nb)).T
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 )
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
2993 L = numpy.linalg.cholesky( A )
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 )
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"):
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) )
3034 # ==============================================================================
3035 def std4dvar(selfA, Xb, Y, U, HO, EM, CM, R, B, Q):
3044 Hm = HO["Direct"].appliedControledFormTo
3045 Mm = EM["Direct"].appliedControledFormTo
3047 if CM is not None and "Tangent" in CM and U is not None:
3048 Cm = CM["Tangent"].asMatrix(Xb)
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
3059 _Un = numpy.asmatrix(numpy.ravel( U )).T
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
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.
3076 # Nombre de pas identique au nombre de pas d'observations
3077 if hasattr(Y,"stepnumber"):
3078 duration = Y.stepnumber()
3082 # Précalcul des inversions de B et R
3086 # Point de démarrage de l'optimisation
3087 Xini = selfA._parameters["InitializationPoint"]
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,]
3104 for step in range(0,duration-1):
3105 if hasattr(Y,"store"):
3106 _Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
3108 _Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
3112 if selfA._parameters["EstimationOf"] == "State":
3113 _Xn = Mm( (_Xn, _Un) ) + CmUn(_Xn, _Un)
3114 elif selfA._parameters["EstimationOf"] == "Parameters":
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)
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)
3127 # Stockage de l'état
3128 selfA.DirectCalculation.append( _Xn )
3129 selfA.DirectInnovation.append( _YmHMX )
3131 # Ajout dans la fonctionnelle d'observation
3132 Jo = Jo + 0.5 * float( _YmHMX.T * RI * _YmHMX )
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] )
3157 def GradientOfCostFunction(x):
3158 _X = numpy.asmatrix(numpy.ravel( x )).T
3159 GradJb = BI * (_X - Xb)
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 )
3177 # Minimisation de la fonctionnelle
3178 # --------------------------------
3179 nbPreviousSteps = selfA.StoredVariables["CostFunctionJ"].stepnumber()
3181 if selfA._parameters["Minimizer"] == "LBFGSB":
3182 if "0.19" <= scipy.version.version <= "1.1.0":
3183 import lbfgsbhlt as optimiseur
3185 import scipy.optimize as optimiseur
3186 Minimum, J_optimal, Informations = optimiseur.fmin_l_bfgs_b(
3187 func = CostFunction,
3189 fprime = GradientOfCostFunction,
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"],
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,
3203 fprime = GradientOfCostFunction,
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"],
3211 elif selfA._parameters["Minimizer"] == "CG":
3212 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
3215 fprime = GradientOfCostFunction,
3217 maxiter = selfA._parameters["MaximumNumberOfSteps"],
3218 gtol = selfA._parameters["GradientNormTolerance"],
3219 disp = selfA._parameters["optdisp"],
3222 elif selfA._parameters["Minimizer"] == "NCG":
3223 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
3226 fprime = GradientOfCostFunction,
3228 maxiter = selfA._parameters["MaximumNumberOfSteps"],
3229 avextol = selfA._parameters["CostDecrementTolerance"],
3230 disp = selfA._parameters["optdisp"],
3233 elif selfA._parameters["Minimizer"] == "BFGS":
3234 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
3237 fprime = GradientOfCostFunction,
3239 maxiter = selfA._parameters["MaximumNumberOfSteps"],
3240 gtol = selfA._parameters["GradientNormTolerance"],
3241 disp = selfA._parameters["optdisp"],
3245 raise ValueError("Error in Minimizer name: %s"%selfA._parameters["Minimizer"])
3247 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
3248 MinJ = selfA.StoredVariables["CostFunctionJ"][IndexMin]
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]
3255 # Obtention de l'analyse
3256 # ----------------------
3257 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
3259 selfA.StoredVariables["Analysis"].store( Xa )
3261 # Calculs et/ou stockages supplémentaires
3262 # ---------------------------------------
3263 if selfA._toStore("BMA"):
3264 selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
3268 # ==============================================================================
3269 def van3dvar(selfA, Xb, Y, U, HO, EM, CM, R, B, Q):
3271 3DVAR variational analysis with no inversion of B
3278 Hm = HO["Direct"].appliedTo
3279 Ha = HO["Adjoint"].appliedInXTo
3281 # Précalcul des inversions de B et R
3285 # Point de démarrage de l'optimisation
3286 Xini = numpy.zeros(Xb.shape)
3288 # Définition de la fonction-coût
3289 # ------------------------------
3290 def CostFunction(v):
3291 _V = numpy.asmatrix(numpy.ravel( v )).T
3293 if selfA._parameters["StoreInternalVariables"] or \
3294 selfA._toStore("CurrentState") or \
3295 selfA._toStore("CurrentOptimum"):
3296 selfA.StoredVariables["CurrentState"].store( _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 )
3306 Jb = float( 0.5 * _V.T * BT * _V )
3307 Jo = float( 0.5 * _Innovation.T * RI * _Innovation )
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] )
3335 def GradientOfCostFunction(v):
3336 _V = numpy.asmatrix(numpy.ravel( v )).T
3339 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
3341 GradJo = - Ha( (_X, RI * (Y - _HX)) )
3342 GradJ = numpy.ravel( GradJb ) + numpy.ravel( GradJo )
3345 # Minimisation de la fonctionnelle
3346 # --------------------------------
3347 nbPreviousSteps = selfA.StoredVariables["CostFunctionJ"].stepnumber()
3349 if selfA._parameters["Minimizer"] == "LBFGSB":
3350 if "0.19" <= scipy.version.version <= "1.1.0":
3351 import lbfgsbhlt as optimiseur
3353 import scipy.optimize as optimiseur
3354 Minimum, J_optimal, Informations = optimiseur.fmin_l_bfgs_b(
3355 func = CostFunction,
3357 fprime = GradientOfCostFunction,
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"],
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,
3371 fprime = GradientOfCostFunction,
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"],
3379 elif selfA._parameters["Minimizer"] == "CG":
3380 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
3383 fprime = GradientOfCostFunction,
3385 maxiter = selfA._parameters["MaximumNumberOfSteps"],
3386 gtol = selfA._parameters["GradientNormTolerance"],
3387 disp = selfA._parameters["optdisp"],
3390 elif selfA._parameters["Minimizer"] == "NCG":
3391 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
3394 fprime = GradientOfCostFunction,
3396 maxiter = selfA._parameters["MaximumNumberOfSteps"],
3397 avextol = selfA._parameters["CostDecrementTolerance"],
3398 disp = selfA._parameters["optdisp"],
3401 elif selfA._parameters["Minimizer"] == "BFGS":
3402 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
3405 fprime = GradientOfCostFunction,
3407 maxiter = selfA._parameters["MaximumNumberOfSteps"],
3408 gtol = selfA._parameters["GradientNormTolerance"],
3409 disp = selfA._parameters["optdisp"],
3413 raise ValueError("Error in Minimizer name: %s"%selfA._parameters["Minimizer"])
3415 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
3416 MinJ = selfA.StoredVariables["CostFunctionJ"][IndexMin]
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
3424 Minimum = Xb + B * numpy.asmatrix(numpy.ravel( Minimum )).T
3426 # Obtention de l'analyse
3427 # ----------------------
3430 selfA.StoredVariables["Analysis"].store( Xa )
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]
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"):
3462 _ee = numpy.matrix(numpy.zeros(nb)).T
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 )
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
3475 L = numpy.linalg.cholesky( A )
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 )
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"):
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) )
3516 # ==============================================================================
3517 if __name__ == "__main__":
3518 print('\n AUTODIAGNOSTIC\n')