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
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( paire ):
38 assert len(paire) == 2, "Incorrect number of arguments"
40 __X = numpy.asmatrix(numpy.ravel( X )).T
41 __sys_path_tmp = sys.path ; sys.path.insert(0,funcrepr["__userFunction__path"])
42 __module = __import__(funcrepr["__userFunction__modl"], globals(), locals(), [])
43 __fonction = getattr(__module,funcrepr["__userFunction__name"])
44 sys.path = __sys_path_tmp ; del __sys_path_tmp
45 __HX = __fonction( __X )
46 return numpy.ravel( __HX )
48 # ==============================================================================
49 class FDApproximation(object):
51 Cette classe sert d'interface pour définir les opérateurs approximés. A la
52 création d'un objet, en fournissant une fonction "Function", on obtient un
53 objet qui dispose de 3 méthodes "DirectOperator", "TangentOperator" et
54 "AdjointOperator". On contrôle l'approximation DF avec l'incrément
55 multiplicatif "increment" valant par défaut 1%, ou avec l'incrément fixe
56 "dX" qui sera multiplié par "increment" (donc en %), et on effectue de DF
57 centrées si le booléen "centeredDF" est vrai.
60 name = "FDApproximation",
65 avoidingRedundancy = True,
66 toleranceInRedundancy = 1.e-18,
67 lenghtOfRedundancy = -1,
72 self.__name = str(name)
75 import multiprocessing
76 self.__mpEnabled = True
78 self.__mpEnabled = False
80 self.__mpEnabled = False
81 self.__mpWorkers = mpWorkers
82 if self.__mpWorkers is not None and self.__mpWorkers < 1:
83 self.__mpWorkers = None
84 logging.debug("FDA Calculs en multiprocessing : %s (nombre de processus : %s)"%(self.__mpEnabled,self.__mpWorkers))
87 self.__mfEnabled = True
89 self.__mfEnabled = False
90 logging.debug("FDA Calculs en multifonctions : %s"%(self.__mfEnabled,))
92 if avoidingRedundancy:
94 self.__tolerBP = float(toleranceInRedundancy)
95 self.__lenghtRJ = int(lenghtOfRedundancy)
96 self.__listJPCP = [] # Jacobian Previous Calculated Points
97 self.__listJPCI = [] # Jacobian Previous Calculated Increment
98 self.__listJPCR = [] # Jacobian Previous Calculated Results
99 self.__listJPPN = [] # Jacobian Previous Calculated Point Norms
100 self.__listJPIN = [] # Jacobian Previous Calculated Increment Norms
102 self.__avoidRC = False
105 if isinstance(Function,types.FunctionType):
106 logging.debug("FDA Calculs en multiprocessing : FunctionType")
107 self.__userFunction__name = Function.__name__
109 mod = os.path.join(Function.__globals__['filepath'],Function.__globals__['filename'])
111 mod = os.path.abspath(Function.__globals__['__file__'])
112 if not os.path.isfile(mod):
113 raise ImportError("No user defined function or method found with the name %s"%(mod,))
114 self.__userFunction__modl = os.path.basename(mod).replace('.pyc','').replace('.pyo','').replace('.py','')
115 self.__userFunction__path = os.path.dirname(mod)
117 self.__userOperator = Operator( name = self.__name, fromMethod = Function, avoidingRedundancy = self.__avoidRC, inputAsMultiFunction = self.__mfEnabled )
118 self.__userFunction = self.__userOperator.appliedTo # Pour le calcul Direct
119 elif isinstance(Function,types.MethodType):
120 logging.debug("FDA Calculs en multiprocessing : MethodType")
121 self.__userFunction__name = Function.__name__
123 mod = os.path.join(Function.__globals__['filepath'],Function.__globals__['filename'])
125 mod = os.path.abspath(Function.__func__.__globals__['__file__'])
126 if not os.path.isfile(mod):
127 raise ImportError("No user defined function or method found with the name %s"%(mod,))
128 self.__userFunction__modl = os.path.basename(mod).replace('.pyc','').replace('.pyo','').replace('.py','')
129 self.__userFunction__path = os.path.dirname(mod)
131 self.__userOperator = Operator( name = self.__name, fromMethod = Function, avoidingRedundancy = self.__avoidRC, inputAsMultiFunction = self.__mfEnabled )
132 self.__userFunction = self.__userOperator.appliedTo # Pour le calcul Direct
134 raise TypeError("User defined function or method has to be provided for finite differences approximation.")
136 self.__userOperator = Operator( name = self.__name, fromMethod = Function, avoidingRedundancy = self.__avoidRC, inputAsMultiFunction = self.__mfEnabled )
137 self.__userFunction = self.__userOperator.appliedTo
139 self.__centeredDF = bool(centeredDF)
140 if abs(float(increment)) > 1.e-15:
141 self.__increment = float(increment)
143 self.__increment = 0.01
147 self.__dX = numpy.asmatrix(numpy.ravel( dX )).T
148 logging.debug("FDA Reduction des doublons de calcul : %s"%self.__avoidRC)
150 logging.debug("FDA Tolerance de determination des doublons : %.2e"%self.__tolerBP)
152 # ---------------------------------------------------------
153 def __doublon__(self, e, l, n, v=None):
154 __ac, __iac = False, -1
155 for i in range(len(l)-1,-1,-1):
156 if numpy.linalg.norm(e - l[i]) < self.__tolerBP * n[i]:
157 __ac, __iac = True, i
158 if v is not None: logging.debug("FDA Cas%s déja calculé, récupération du doublon %i"%(v,__iac))
162 # ---------------------------------------------------------
163 def DirectOperator(self, X ):
165 Calcul du direct à l'aide de la fonction fournie.
167 logging.debug("FDA Calcul DirectOperator (explicite)")
169 _HX = self.__userFunction( X, argsAsSerie = True )
171 _X = numpy.asmatrix(numpy.ravel( X )).T
172 _HX = numpy.ravel(self.__userFunction( _X ))
176 # ---------------------------------------------------------
177 def TangentMatrix(self, X ):
179 Calcul de l'opérateur tangent comme la Jacobienne par différences finies,
180 c'est-à-dire le gradient de H en X. On utilise des différences finies
181 directionnelles autour du point X. X est un numpy.matrix.
183 Différences finies centrées (approximation d'ordre 2):
184 1/ Pour chaque composante i de X, on ajoute et on enlève la perturbation
185 dX[i] à la composante X[i], pour composer X_plus_dXi et X_moins_dXi, et
186 on calcule les réponses HX_plus_dXi = H( X_plus_dXi ) et HX_moins_dXi =
188 2/ On effectue les différences (HX_plus_dXi-HX_moins_dXi) et on divise par
190 3/ Chaque résultat, par composante, devient une colonne de la Jacobienne
192 Différences finies non centrées (approximation d'ordre 1):
193 1/ Pour chaque composante i de X, on ajoute la perturbation dX[i] à la
194 composante X[i] pour composer X_plus_dXi, et on calcule la réponse
195 HX_plus_dXi = H( X_plus_dXi )
196 2/ On calcule la valeur centrale HX = H(X)
197 3/ On effectue les différences (HX_plus_dXi-HX) et on divise par
199 4/ Chaque résultat, par composante, devient une colonne de la Jacobienne
202 logging.debug("FDA Début du calcul de la Jacobienne")
203 logging.debug("FDA Incrément de............: %s*X"%float(self.__increment))
204 logging.debug("FDA Approximation centrée...: %s"%(self.__centeredDF))
206 if X is None or len(X)==0:
207 raise ValueError("Nominal point X for approximate derivatives can not be None or void (given X: %s)."%(str(X),))
209 _X = numpy.asmatrix(numpy.ravel( X )).T
211 if self.__dX is None:
212 _dX = self.__increment * _X
214 _dX = numpy.asmatrix(numpy.ravel( self.__dX )).T
216 if (_dX == 0.).any():
219 _dX = numpy.where( _dX == 0., float(self.__increment), _dX )
221 _dX = numpy.where( _dX == 0., moyenne, _dX )
223 __alreadyCalculated = False
225 __bidon, __alreadyCalculatedP = self.__doublon__(_X, self.__listJPCP, self.__listJPPN, None)
226 __bidon, __alreadyCalculatedI = self.__doublon__(_dX, self.__listJPCI, self.__listJPIN, None)
227 if __alreadyCalculatedP == __alreadyCalculatedI > -1:
228 __alreadyCalculated, __i = True, __alreadyCalculatedP
229 logging.debug("FDA Cas J déja calculé, récupération du doublon %i"%__i)
231 if __alreadyCalculated:
232 logging.debug("FDA Calcul Jacobienne (par récupération du doublon %i)"%__i)
233 _Jacobienne = self.__listJPCR[__i]
235 logging.debug("FDA Calcul Jacobienne (explicite)")
236 if self.__centeredDF:
238 if self.__mpEnabled and not self.__mfEnabled:
240 "__userFunction__path" : self.__userFunction__path,
241 "__userFunction__modl" : self.__userFunction__modl,
242 "__userFunction__name" : self.__userFunction__name,
245 for i in range( len(_dX) ):
247 _X_plus_dXi = numpy.array( _X.A1, dtype=float )
248 _X_plus_dXi[i] = _X[i] + _dXi
249 _X_moins_dXi = numpy.array( _X.A1, dtype=float )
250 _X_moins_dXi[i] = _X[i] - _dXi
252 _jobs.append( (_X_plus_dXi, funcrepr) )
253 _jobs.append( (_X_moins_dXi, funcrepr) )
255 import multiprocessing
256 self.__pool = multiprocessing.Pool(self.__mpWorkers)
257 _HX_plusmoins_dX = self.__pool.map( ExecuteFunction, _jobs )
262 for i in range( len(_dX) ):
263 _Jacobienne.append( numpy.ravel( _HX_plusmoins_dX[2*i] - _HX_plusmoins_dX[2*i+1] ) / (2.*_dX[i]) )
265 elif self.__mfEnabled:
267 for i in range( len(_dX) ):
269 _X_plus_dXi = numpy.array( _X.A1, dtype=float )
270 _X_plus_dXi[i] = _X[i] + _dXi
271 _X_moins_dXi = numpy.array( _X.A1, dtype=float )
272 _X_moins_dXi[i] = _X[i] - _dXi
274 _xserie.append( _X_plus_dXi )
275 _xserie.append( _X_moins_dXi )
277 _HX_plusmoins_dX = self.DirectOperator( _xserie )
280 for i in range( len(_dX) ):
281 _Jacobienne.append( numpy.ravel( _HX_plusmoins_dX[2*i] - _HX_plusmoins_dX[2*i+1] ) / (2.*_dX[i]) )
285 for i in range( _dX.size ):
287 _X_plus_dXi = numpy.array( _X.A1, dtype=float )
288 _X_plus_dXi[i] = _X[i] + _dXi
289 _X_moins_dXi = numpy.array( _X.A1, dtype=float )
290 _X_moins_dXi[i] = _X[i] - _dXi
292 _HX_plus_dXi = self.DirectOperator( _X_plus_dXi )
293 _HX_moins_dXi = self.DirectOperator( _X_moins_dXi )
295 _Jacobienne.append( numpy.ravel( _HX_plus_dXi - _HX_moins_dXi ) / (2.*_dXi) )
299 if self.__mpEnabled and not self.__mfEnabled:
301 "__userFunction__path" : self.__userFunction__path,
302 "__userFunction__modl" : self.__userFunction__modl,
303 "__userFunction__name" : self.__userFunction__name,
306 _jobs.append( (_X.A1, funcrepr) )
307 for i in range( len(_dX) ):
308 _X_plus_dXi = numpy.array( _X.A1, dtype=float )
309 _X_plus_dXi[i] = _X[i] + _dX[i]
311 _jobs.append( (_X_plus_dXi, funcrepr) )
313 import multiprocessing
314 self.__pool = multiprocessing.Pool(self.__mpWorkers)
315 _HX_plus_dX = self.__pool.map( ExecuteFunction, _jobs )
319 _HX = _HX_plus_dX.pop(0)
322 for i in range( len(_dX) ):
323 _Jacobienne.append( numpy.ravel(( _HX_plus_dX[i] - _HX ) / _dX[i]) )
325 elif self.__mfEnabled:
327 _xserie.append( _X.A1 )
328 for i in range( len(_dX) ):
329 _X_plus_dXi = numpy.array( _X.A1, dtype=float )
330 _X_plus_dXi[i] = _X[i] + _dX[i]
332 _xserie.append( _X_plus_dXi )
334 _HX_plus_dX = self.DirectOperator( _xserie )
336 _HX = _HX_plus_dX.pop(0)
339 for i in range( len(_dX) ):
340 _Jacobienne.append( numpy.ravel(( _HX_plus_dX[i] - _HX ) / _dX[i]) )
344 _HX = self.DirectOperator( _X )
345 for i in range( _dX.size ):
347 _X_plus_dXi = numpy.array( _X.A1, dtype=float )
348 _X_plus_dXi[i] = _X[i] + _dXi
350 _HX_plus_dXi = self.DirectOperator( _X_plus_dXi )
352 _Jacobienne.append( numpy.ravel(( _HX_plus_dXi - _HX ) / _dXi) )
355 _Jacobienne = numpy.asmatrix( numpy.vstack( _Jacobienne ) ).T
357 if self.__lenghtRJ < 0: self.__lenghtRJ = 2 * _X.size
358 while len(self.__listJPCP) > self.__lenghtRJ:
359 self.__listJPCP.pop(0)
360 self.__listJPCI.pop(0)
361 self.__listJPCR.pop(0)
362 self.__listJPPN.pop(0)
363 self.__listJPIN.pop(0)
364 self.__listJPCP.append( copy.copy(_X) )
365 self.__listJPCI.append( copy.copy(_dX) )
366 self.__listJPCR.append( copy.copy(_Jacobienne) )
367 self.__listJPPN.append( numpy.linalg.norm(_X) )
368 self.__listJPIN.append( numpy.linalg.norm(_Jacobienne) )
370 logging.debug("FDA Fin du calcul de la Jacobienne")
374 # ---------------------------------------------------------
375 def TangentOperator(self, paire ):
377 Calcul du tangent à l'aide de la Jacobienne.
380 assert len(paire) == 1, "Incorrect lenght of arguments"
382 assert len(_paire) == 2, "Incorrect number of arguments"
384 assert len(paire) == 2, "Incorrect number of arguments"
387 _Jacobienne = self.TangentMatrix( X )
388 if dX is None or len(dX) == 0:
390 # Calcul de la forme matricielle si le second argument est None
391 # -------------------------------------------------------------
392 if self.__mfEnabled: return [_Jacobienne,]
393 else: return _Jacobienne
396 # Calcul de la valeur linéarisée de H en X appliqué à dX
397 # ------------------------------------------------------
398 _dX = numpy.asmatrix(numpy.ravel( dX )).T
399 _HtX = numpy.dot(_Jacobienne, _dX)
400 if self.__mfEnabled: return [_HtX.A1,]
403 # ---------------------------------------------------------
404 def AdjointOperator(self, paire ):
406 Calcul de l'adjoint à l'aide de la Jacobienne.
409 assert len(paire) == 1, "Incorrect lenght of arguments"
411 assert len(_paire) == 2, "Incorrect number of arguments"
413 assert len(paire) == 2, "Incorrect number of arguments"
416 _JacobienneT = self.TangentMatrix( X ).T
417 if Y is None or len(Y) == 0:
419 # Calcul de la forme matricielle si le second argument est None
420 # -------------------------------------------------------------
421 if self.__mfEnabled: return [_JacobienneT,]
422 else: return _JacobienneT
425 # Calcul de la valeur de l'adjoint en X appliqué à Y
426 # --------------------------------------------------
427 _Y = numpy.asmatrix(numpy.ravel( Y )).T
428 _HaY = numpy.dot(_JacobienneT, _Y)
429 if self.__mfEnabled: return [_HaY.A1,]
432 # ==============================================================================
444 Implémentation informatique de l'algorithme MMQR, basée sur la publication :
445 David R. Hunter, Kenneth Lange, "Quantile Regression via an MM Algorithm",
446 Journal of Computational and Graphical Statistics, 9, 1, pp.60-77, 2000.
449 # Recuperation des donnees et informations initiales
450 # --------------------------------------------------
451 variables = numpy.ravel( x0 )
452 mesures = numpy.ravel( y )
453 increment = sys.float_info[0]
456 quantile = float(quantile)
458 # Calcul des parametres du MM
459 # ---------------------------
460 tn = float(toler) / n
461 e0 = -tn / math.log(tn)
462 epsilon = (e0-tn)/(1+math.log(e0))
464 # Calculs d'initialisation
465 # ------------------------
466 residus = mesures - numpy.ravel( func( variables ) )
467 poids = 1./(epsilon+numpy.abs(residus))
468 veps = 1. - 2. * quantile - residus * poids
469 lastsurrogate = -numpy.sum(residus*veps) - (1.-2.*quantile)*numpy.sum(residus)
472 # Recherche iterative
473 # -------------------
474 while (increment > toler) and (iteration < maxfun) :
477 Derivees = numpy.array(fprime(variables))
478 Derivees = Derivees.reshape(n,p) # Necessaire pour remettre en place la matrice si elle passe par des tuyaux YACS
479 DeriveesT = Derivees.transpose()
480 M = numpy.dot( DeriveesT , (numpy.array(numpy.matrix(p*[poids,]).T)*Derivees) )
481 SM = numpy.transpose(numpy.dot( DeriveesT , veps ))
482 step = - numpy.linalg.lstsq( M, SM, rcond=-1 )[0]
484 variables = variables + step
485 if bounds is not None:
486 # Attention : boucle infinie à éviter si un intervalle est trop petit
487 while( (variables < numpy.ravel(numpy.asmatrix(bounds)[:,0])).any() or (variables > numpy.ravel(numpy.asmatrix(bounds)[:,1])).any() ):
489 variables = variables - step
490 residus = mesures - numpy.ravel( func(variables) )
491 surrogate = numpy.sum(residus**2 * poids) + (4.*quantile-2.) * numpy.sum(residus)
493 while ( (surrogate > lastsurrogate) and ( max(list(numpy.abs(step))) > 1.e-16 ) ) :
495 variables = variables - step
496 residus = mesures - numpy.ravel( func(variables) )
497 surrogate = numpy.sum(residus**2 * poids) + (4.*quantile-2.) * numpy.sum(residus)
499 increment = lastsurrogate-surrogate
500 poids = 1./(epsilon+numpy.abs(residus))
501 veps = 1. - 2. * quantile - residus * poids
502 lastsurrogate = -numpy.sum(residus * veps) - (1.-2.*quantile)*numpy.sum(residus)
506 Ecart = quantile * numpy.sum(residus) - numpy.sum( residus[residus<0] )
508 return variables, Ecart, [n,p,iteration,increment,0]
510 # ==============================================================================
511 def BackgroundEnsembleGeneration( _bgcenter, _bgcovariance, _nbmembers, _withSVD = True):
512 "Génération d'un ensemble d'ébauches aléatoires de taille _nbmembers-1"
513 def __CenteredRandomAnomalies(Zr, N):
515 Génère une matrice de N anomalies aléatoires centrées sur Zr selon les
516 notes manuscrites de MB et conforme au code de PS avec eps = -1
519 Q = numpy.eye(N-1)-numpy.ones((N-1,N-1))/numpy.sqrt(N)/(numpy.sqrt(N)-eps)
520 Q = numpy.concatenate((Q, [eps*numpy.ones(N-1)/numpy.sqrt(N)]), axis=0)
521 R, _ = numpy.linalg.qr(numpy.random.normal(size = (N-1,N-1)))
527 raise ValueError("Number of members has to be strictly more than 1 (given number: %s)."%(str(_nbmembers),))
528 if _bgcovariance is None:
529 BackgroundEnsemble = numpy.tile( numpy.ravel(_bgcenter)[:,None], _nbmembers)
532 U, s, V = numpy.linalg.svd(_bgcovariance, full_matrices=False)
533 _nbctl = numpy.ravel(_bgcenter).size
534 if _nbmembers > _nbctl:
535 _Z = numpy.concatenate((numpy.dot(
536 numpy.diag(numpy.sqrt(s[:_nbctl])), V[:_nbctl]),
537 numpy.random.multivariate_normal(numpy.zeros(_nbctl),_bgcovariance,_nbmembers-1-_nbctl)), axis = 0)
539 _Z = numpy.dot(numpy.diag(numpy.sqrt(s[:_nbmembers-1])), V[:_nbmembers-1])
540 _Zca = __CenteredRandomAnomalies(_Z, _nbmembers)
541 BackgroundEnsemble = numpy.ravel(_bgcenter)[:,None] + _Zca
543 if max(abs(_bgcovariance.flatten())) > 0:
544 _nbctl = numpy.ravel(_bgcenter).size
545 _Z = numpy.random.multivariate_normal(numpy.zeros(_nbctl),_bgcovariance,_nbmembers-1)
546 _Zca = __CenteredRandomAnomalies(_Z, _nbmembers)
547 BackgroundEnsemble = numpy.ravel(_bgcenter)[:,None] + _Zca
549 BackgroundEnsemble = numpy.tile( numpy.ravel(_bgcenter)[:,None], _nbmembers)
551 return BackgroundEnsemble
553 # ==============================================================================
554 def EnsembleCenteredAnomalies( _ensemble, _optmean = None):
555 "Renvoie les anomalies centrées à partir d'un ensemble TailleEtat*NbMembres"
557 Em = numpy.asarray(_ensemble).mean(axis=1, dtype=mfp).astype('float')[:,numpy.newaxis]
559 Em = numpy.ravel(_optmean)[:,numpy.newaxis]
561 return numpy.asarray(_ensemble) - Em
563 # ==============================================================================
564 def CovarianceInflation(
566 InflationType = None,
567 InflationFactor = None,
568 BackgroundCov = None,
571 Inflation applicable soit sur Pb ou Pa, soit sur les ensembles EXb ou EXa
573 Synthèse : Hunt 2007, section 2.3.5
575 if InflationFactor is None:
578 InflationFactor = float(InflationFactor)
580 if InflationType in ["MultiplicativeOnAnalysisCovariance", "MultiplicativeOnBackgroundCovariance"]:
581 if InflationFactor < 1.:
582 raise ValueError("Inflation factor for multiplicative inflation has to be greater or equal than 1.")
583 if InflationFactor < 1.+mpr:
585 OutputCovOrEns = InflationFactor**2 * InputCovOrEns
587 elif InflationType in ["MultiplicativeOnAnalysisAnomalies", "MultiplicativeOnBackgroundAnomalies"]:
588 if InflationFactor < 1.:
589 raise ValueError("Inflation factor for multiplicative inflation has to be greater or equal than 1.")
590 if InflationFactor < 1.+mpr:
592 InputCovOrEnsMean = InputCovOrEns.mean(axis=1, dtype=mfp).astype('float')
593 OutputCovOrEns = InputCovOrEnsMean[:,numpy.newaxis] \
594 + InflationFactor * (InputCovOrEns - InputCovOrEnsMean[:,numpy.newaxis])
596 elif InflationType in ["AdditiveOnBackgroundCovariance", "AdditiveOnAnalysisCovariance"]:
597 if InflationFactor < 0.:
598 raise ValueError("Inflation factor for additive inflation has to be greater or equal than 0.")
599 if InflationFactor < mpr:
601 __n, __m = numpy.asarray(InputCovOrEns).shape
603 raise ValueError("Additive inflation can only be applied to squared (covariance) matrix.")
604 OutputCovOrEns = (1. - InflationFactor) * InputCovOrEns + InflationFactor * numpy.eye(__n)
606 elif InflationType == "HybridOnBackgroundCovariance":
607 if InflationFactor < 0.:
608 raise ValueError("Inflation factor for hybrid inflation has to be greater or equal than 0.")
609 if InflationFactor < mpr:
611 __n, __m = numpy.asarray(InputCovOrEns).shape
613 raise ValueError("Additive inflation can only be applied to squared (covariance) matrix.")
614 if BackgroundCov is None:
615 raise ValueError("Background covariance matrix B has to be given for hybrid inflation.")
616 if InputCovOrEns.shape != BackgroundCov.shape:
617 raise ValueError("Ensemble covariance matrix has to be of same size than background covariance matrix B.")
618 OutputCovOrEns = (1. - InflationFactor) * InputCovOrEns + InflationFactor * BackgroundCov
620 elif InflationType == "Relaxation":
621 raise NotImplementedError("InflationType Relaxation")
624 raise ValueError("Error in inflation type, '%s' is not a valid keyword."%InflationType)
626 return OutputCovOrEns
628 # ==============================================================================
629 def senkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, VariantM="KalmanFilterFormula"):
631 Stochastic EnKF (Envensen 1994, Burgers 1998)
633 selfA est identique au "self" d'algorithme appelant et contient les
636 if selfA._parameters["EstimationOf"] == "Parameters":
637 selfA._parameters["StoreInternalVariables"] = True
641 H = HO["Direct"].appliedControledFormTo
643 if selfA._parameters["EstimationOf"] == "State":
644 M = EM["Direct"].appliedControledFormTo
646 if CM is not None and "Tangent" in CM and U is not None:
647 Cm = CM["Tangent"].asMatrix(Xb)
651 # Nombre de pas identique au nombre de pas d'observations
652 # -------------------------------------------------------
653 if hasattr(Y,"stepnumber"):
654 duration = Y.stepnumber()
655 __p = numpy.cumprod(Y.shape())[-1]
658 __p = numpy.array(Y).size
660 # Précalcul des inversions de B et R
661 # ----------------------------------
662 if selfA._parameters["StoreInternalVariables"] \
663 or selfA._toStore("CostFunctionJ") \
664 or selfA._toStore("CostFunctionJb") \
665 or selfA._toStore("CostFunctionJo") \
666 or selfA._toStore("CurrentOptimum") \
667 or selfA._toStore("APosterioriCovariance"):
674 __m = selfA._parameters["NumberOfMembers"]
675 if hasattr(B,"asfullmatrix"): Pn = B.asfullmatrix(__n)
677 if hasattr(R,"asfullmatrix"): Rn = R.asfullmatrix(__p)
679 if hasattr(Q,"asfullmatrix"): Qn = Q.asfullmatrix(__n)
681 Xn = numpy.asmatrix(numpy.dot( Xb.reshape((__n,1)), numpy.ones((1,__m)) ))
683 if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
684 selfA.StoredVariables["Analysis"].store( numpy.ravel(Xb) )
685 if selfA._toStore("APosterioriCovariance"):
686 selfA.StoredVariables["APosterioriCovariance"].store( Pn )
689 previousJMinimum = numpy.finfo(float).max
692 Xn_predicted = numpy.asmatrix(numpy.zeros((__n,__m)))
693 HX_predicted = numpy.asmatrix(numpy.zeros((__p,__m)))
695 for step in range(duration-1):
696 if hasattr(Y,"store"):
697 Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
699 Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
702 if hasattr(U,"store") and len(U)>1:
703 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
704 elif hasattr(U,"store") and len(U)==1:
705 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
707 Un = numpy.asmatrix(numpy.ravel( U )).T
711 if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
712 Xn = CovarianceInflation( Xn,
713 selfA._parameters["InflationType"],
714 selfA._parameters["InflationFactor"],
717 if selfA._parameters["EstimationOf"] == "State": # Forecast + Q and observation of forecast
718 EMX = M( [(Xn[:,i], Un) for i in range(__m)], argsAsSerie = True )
720 qi = numpy.random.multivariate_normal(numpy.zeros(__n), Qn)
721 Xn_predicted[:,i] = (numpy.ravel( EMX[i] ) + qi).reshape((__n,-1))
722 HX_predicted = H( [(Xn_predicted[:,i], Un) for i in range(__m)],
724 returnSerieAsArrayMatrix = True )
725 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
726 Cm = Cm.reshape(__n,Un.size) # ADAO & check shape
727 Xn_predicted = Xn_predicted + Cm * Un
728 elif selfA._parameters["EstimationOf"] == "Parameters": # Observation of forecast
729 # --- > Par principe, M = Id, Q = 0
731 HX_predicted = H( [(Xn_predicted[:,i], Un) for i in range(__m)],
733 returnSerieAsArrayMatrix = True )
735 # Mean of forecast and observation of forecast
736 Xfm = Xn_predicted.mean(axis=1, dtype=mfp).astype('float')
737 Hfm = HX_predicted.mean(axis=1, dtype=mfp).astype('float')
739 #--------------------------
740 if VariantM == "KalmanFilterFormula":
743 Exfi = Xn_predicted[:,i] - Xfm.reshape((__n,-1))
744 Eyfi = (HX_predicted[:,i] - Hfm).reshape((__p,1))
745 PfHT += Exfi * Eyfi.T
746 HPfHT += Eyfi * Eyfi.T
747 PfHT = (1./(__m-1)) * PfHT
748 HPfHT = (1./(__m-1)) * HPfHT
749 K = PfHT * ( R + HPfHT ).I
753 ri = numpy.random.multivariate_normal(numpy.zeros(__p), Rn)
754 Xn[:,i] = Xn_predicted[:,i] + K @ (numpy.ravel(Ynpu) + ri - HX_predicted[:,i]).reshape((__p,1))
755 #--------------------------
757 raise ValueError("VariantM has to be chosen in the authorized methods list.")
759 if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
760 Xn = CovarianceInflation( Xn,
761 selfA._parameters["InflationType"],
762 selfA._parameters["InflationFactor"],
765 Xa = Xn.mean(axis=1, dtype=mfp).astype('float')
766 #--------------------------
768 if selfA._parameters["StoreInternalVariables"] \
769 or selfA._toStore("CostFunctionJ") \
770 or selfA._toStore("CostFunctionJb") \
771 or selfA._toStore("CostFunctionJo") \
772 or selfA._toStore("APosterioriCovariance") \
773 or selfA._toStore("InnovationAtCurrentAnalysis") \
774 or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
775 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
776 _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
777 _Innovation = Ynpu - _HXa
779 selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
781 selfA.StoredVariables["Analysis"].store( Xa )
782 if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
783 selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
784 if selfA._toStore("InnovationAtCurrentAnalysis"):
785 selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
786 # ---> avec current state
787 if selfA._parameters["StoreInternalVariables"] \
788 or selfA._toStore("CurrentState"):
789 selfA.StoredVariables["CurrentState"].store( Xn )
790 if selfA._toStore("ForecastState"):
791 selfA.StoredVariables["ForecastState"].store( Xn_predicted )
792 if selfA._toStore("BMA"):
793 selfA.StoredVariables["BMA"].store( Xn_predicted - Xa )
794 if selfA._toStore("InnovationAtCurrentState"):
795 selfA.StoredVariables["InnovationAtCurrentState"].store( - HX_predicted + Ynpu )
796 if selfA._toStore("SimulatedObservationAtCurrentState") \
797 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
798 selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HX_predicted )
800 if selfA._parameters["StoreInternalVariables"] \
801 or selfA._toStore("CostFunctionJ") \
802 or selfA._toStore("CostFunctionJb") \
803 or selfA._toStore("CostFunctionJo") \
804 or selfA._toStore("CurrentOptimum") \
805 or selfA._toStore("APosterioriCovariance"):
806 Jb = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
807 Jo = float( 0.5 * _Innovation.T * RI * _Innovation )
809 selfA.StoredVariables["CostFunctionJb"].store( Jb )
810 selfA.StoredVariables["CostFunctionJo"].store( Jo )
811 selfA.StoredVariables["CostFunctionJ" ].store( J )
813 if selfA._toStore("IndexOfOptimum") \
814 or selfA._toStore("CurrentOptimum") \
815 or selfA._toStore("CostFunctionJAtCurrentOptimum") \
816 or selfA._toStore("CostFunctionJbAtCurrentOptimum") \
817 or selfA._toStore("CostFunctionJoAtCurrentOptimum") \
818 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
819 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
820 if selfA._toStore("IndexOfOptimum"):
821 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
822 if selfA._toStore("CurrentOptimum"):
823 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["Analysis"][IndexMin] )
824 if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
825 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"][IndexMin] )
826 if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
827 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
828 if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
829 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
830 if selfA._toStore("CostFunctionJAtCurrentOptimum"):
831 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
832 if selfA._toStore("APosterioriCovariance"):
833 Eai = (1/numpy.sqrt(__m-1)) * (Xn - Xa.reshape((__n,-1))) # Anomalies
835 Pn = 0.5 * (Pn + Pn.T)
836 selfA.StoredVariables["APosterioriCovariance"].store( Pn )
837 if selfA._parameters["EstimationOf"] == "Parameters" \
838 and J < previousJMinimum:
841 if selfA._toStore("APosterioriCovariance"):
844 # Stockage final supplémentaire de l'optimum en estimation de paramètres
845 # ----------------------------------------------------------------------
846 if selfA._parameters["EstimationOf"] == "Parameters":
847 selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
848 selfA.StoredVariables["Analysis"].store( XaMin )
849 if selfA._toStore("APosterioriCovariance"):
850 selfA.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
851 if selfA._toStore("BMA"):
852 selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
856 # ==============================================================================
857 def etkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, VariantM="KalmanFilterFormula"):
859 Ensemble-Transform EnKF (ETKF or Deterministic EnKF: Bishop 2001, Hunt 2007)
861 selfA est identique au "self" d'algorithme appelant et contient les
864 if selfA._parameters["EstimationOf"] == "Parameters":
865 selfA._parameters["StoreInternalVariables"] = True
869 H = HO["Direct"].appliedControledFormTo
871 if selfA._parameters["EstimationOf"] == "State":
872 M = EM["Direct"].appliedControledFormTo
874 if CM is not None and "Tangent" in CM and U is not None:
875 Cm = CM["Tangent"].asMatrix(Xb)
879 # Nombre de pas identique au nombre de pas d'observations
880 # -------------------------------------------------------
881 if hasattr(Y,"stepnumber"):
882 duration = Y.stepnumber()
883 __p = numpy.cumprod(Y.shape())[-1]
886 __p = numpy.array(Y).size
888 # Précalcul des inversions de B et R
889 # ----------------------------------
890 if selfA._parameters["StoreInternalVariables"] \
891 or selfA._toStore("CostFunctionJ") \
892 or selfA._toStore("CostFunctionJb") \
893 or selfA._toStore("CostFunctionJo") \
894 or selfA._toStore("CurrentOptimum") \
895 or selfA._toStore("APosterioriCovariance"):
898 elif VariantM != "KalmanFilterFormula":
900 if VariantM == "KalmanFilterFormula":
901 RIdemi = R.choleskyI()
906 __m = selfA._parameters["NumberOfMembers"]
907 if hasattr(B,"asfullmatrix"): Pn = B.asfullmatrix(__n)
909 if hasattr(R,"asfullmatrix"): Rn = R.asfullmatrix(__p)
911 if hasattr(Q,"asfullmatrix"): Qn = Q.asfullmatrix(__n)
913 Xn = numpy.asmatrix(numpy.dot( Xb.reshape((__n,1)), numpy.ones((1,__m)) ))
915 if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
916 selfA.StoredVariables["Analysis"].store( numpy.ravel(Xb) )
917 if selfA._toStore("APosterioriCovariance"):
918 selfA.StoredVariables["APosterioriCovariance"].store( Pn )
921 previousJMinimum = numpy.finfo(float).max
924 Xn_predicted = numpy.asmatrix(numpy.zeros((__n,__m)))
926 for step in range(duration-1):
927 if hasattr(Y,"store"):
928 Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
930 Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
933 if hasattr(U,"store") and len(U)>1:
934 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
935 elif hasattr(U,"store") and len(U)==1:
936 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
938 Un = numpy.asmatrix(numpy.ravel( U )).T
942 if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
943 Xn = CovarianceInflation( Xn,
944 selfA._parameters["InflationType"],
945 selfA._parameters["InflationFactor"],
948 if selfA._parameters["EstimationOf"] == "State": # Forecast + Q and observation of forecast
949 EMX = M( [(Xn[:,i], Un) for i in range(__m)], argsAsSerie = True )
951 qi = numpy.random.multivariate_normal(numpy.zeros(__n), Qn)
952 Xn_predicted[:,i] = (numpy.ravel( EMX[i] ) + qi).reshape((__n,-1))
953 HX_predicted = H( [(Xn_predicted[:,i], Un) for i in range(__m)],
955 returnSerieAsArrayMatrix = True )
956 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
957 Cm = Cm.reshape(__n,Un.size) # ADAO & check shape
958 Xn_predicted = Xn_predicted + Cm * Un
959 elif selfA._parameters["EstimationOf"] == "Parameters": # Observation of forecast
960 # --- > Par principe, M = Id, Q = 0
962 HX_predicted = H( [(Xn_predicted[:,i], Un) for i in range(__m)],
964 returnSerieAsArrayMatrix = True )
966 # Mean of forecast and observation of forecast
967 Xfm = Xn_predicted.mean(axis=1, dtype=mfp).astype('float')
968 Hfm = HX_predicted.mean(axis=1, dtype=mfp).astype('float')
971 EaX = numpy.matrix(Xn_predicted - Xfm.reshape((__n,-1)))
972 EaHX = numpy.matrix(HX_predicted - Hfm.reshape((__p,-1)))
974 #--------------------------
975 if VariantM == "KalmanFilterFormula":
976 EaX = EaX / numpy.sqrt(__m-1)
977 mS = RIdemi * EaHX / numpy.sqrt(__m-1)
978 delta = RIdemi * ( Ynpu.reshape((__p,-1)) - Hfm.reshape((__p,-1)) )
979 mT = numpy.linalg.inv( numpy.eye(__m) + mS.T @ mS )
980 vw = mT @ mS.transpose() @ delta
982 Tdemi = numpy.real(scipy.linalg.sqrtm(mT))
985 Xn = Xfm.reshape((__n,-1)) + EaX @ ( vw.reshape((__m,-1)) + numpy.sqrt(__m-1) * Tdemi @ mU )
986 #--------------------------
987 elif VariantM == "Variational":
988 HXfm = H((Xfm, Un)) # Eventuellement Hfm
990 _A = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
991 _Jo = 0.5 * _A.T * RI * _A
992 _Jb = 0.5 * (__m-1) * w.T @ w
995 def GradientOfCostFunction(w):
996 _A = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
997 _GardJo = - EaHX.T * RI * _A
998 _GradJb = (__m-1) * w.reshape((__m,1))
999 _GradJ = _GardJo + _GradJb
1000 return numpy.ravel(_GradJ)
1001 vw = scipy.optimize.fmin_cg(
1003 x0 = numpy.zeros(__m),
1004 fprime = GradientOfCostFunction,
1009 Hto = EaHX.T * RI * EaHX
1010 Htb = (__m-1) * numpy.eye(__m)
1013 Pta = numpy.linalg.inv( Hta )
1014 EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1016 Xn = Xfm.reshape((__n,-1)) + EaX @ (vw.reshape((__m,-1)) + EWa)
1017 #--------------------------
1018 elif VariantM == "FiniteSize11": # Jauge Boc2011
1019 HXfm = H((Xfm, Un)) # Eventuellement Hfm
1020 def CostFunction(w):
1021 _A = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1022 _Jo = 0.5 * _A.T * RI * _A
1023 _Jb = 0.5 * __m * math.log(1 + 1/__m + w.T @ w)
1026 def GradientOfCostFunction(w):
1027 _A = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1028 _GardJo = - EaHX.T * RI * _A
1029 _GradJb = __m * w.reshape((__m,1)) / (1 + 1/__m + w.T @ w)
1030 _GradJ = _GardJo + _GradJb
1031 return numpy.ravel(_GradJ)
1032 vw = scipy.optimize.fmin_cg(
1034 x0 = numpy.zeros(__m),
1035 fprime = GradientOfCostFunction,
1040 Hto = EaHX.T * RI * EaHX
1042 ( (1 + 1/__m + vw.T @ vw) * numpy.eye(__m) - 2 * vw @ vw.T ) \
1043 / (1 + 1/__m + vw.T @ vw)**2
1046 Pta = numpy.linalg.inv( Hta )
1047 EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1049 Xn = Xfm.reshape((__n,-1)) + EaX @ (vw.reshape((__m,-1)) + EWa)
1050 #--------------------------
1051 elif VariantM == "FiniteSize15": # Jauge Boc2015
1052 HXfm = H((Xfm, Un)) # Eventuellement Hfm
1053 def CostFunction(w):
1054 _A = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1055 _Jo = 0.5 * _A.T * RI * _A
1056 _Jb = 0.5 * (__m+1) * math.log(1 + 1/__m + w.T @ w)
1059 def GradientOfCostFunction(w):
1060 _A = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1061 _GardJo = - EaHX.T * RI * _A
1062 _GradJb = (__m+1) * w.reshape((__m,1)) / (1 + 1/__m + w.T @ w)
1063 _GradJ = _GardJo + _GradJb
1064 return numpy.ravel(_GradJ)
1065 vw = scipy.optimize.fmin_cg(
1067 x0 = numpy.zeros(__m),
1068 fprime = GradientOfCostFunction,
1073 Hto = EaHX.T * RI * EaHX
1075 ( (1 + 1/__m + vw.T @ vw) * numpy.eye(__m) - 2 * vw @ vw.T ) \
1076 / (1 + 1/__m + vw.T @ vw)**2
1079 Pta = numpy.linalg.inv( Hta )
1080 EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1082 Xn = Xfm.reshape((__n,-1)) + EaX @ (vw.reshape((__m,-1)) + EWa)
1083 #--------------------------
1084 elif VariantM == "FiniteSize16": # Jauge Boc2016
1085 HXfm = H((Xfm, Un)) # Eventuellement Hfm
1086 def CostFunction(w):
1087 _A = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1088 _Jo = 0.5 * _A.T * RI * _A
1089 _Jb = 0.5 * (__m+1) * math.log(1 + 1/__m + w.T @ w / (__m-1))
1092 def GradientOfCostFunction(w):
1093 _A = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1094 _GardJo = - EaHX.T * RI * _A
1095 _GradJb = ((__m+1) / (__m-1)) * w.reshape((__m,1)) / (1 + 1/__m + w.T @ w / (__m-1))
1096 _GradJ = _GardJo + _GradJb
1097 return numpy.ravel(_GradJ)
1098 vw = scipy.optimize.fmin_cg(
1100 x0 = numpy.zeros(__m),
1101 fprime = GradientOfCostFunction,
1106 Hto = EaHX.T * RI * EaHX
1107 Htb = ((__m+1) / (__m-1)) * \
1108 ( (1 + 1/__m + vw.T @ vw / (__m-1)) * numpy.eye(__m) - 2 * vw @ vw.T / (__m-1) ) \
1109 / (1 + 1/__m + vw.T @ vw / (__m-1))**2
1112 Pta = numpy.linalg.inv( Hta )
1113 EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1115 Xn = Xfm.reshape((__n,-1)) + EaX @ (vw.reshape((__m,-1)) + EWa)
1116 #--------------------------
1118 raise ValueError("VariantM has to be chosen in the authorized methods list.")
1120 if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
1121 Xn = CovarianceInflation( Xn,
1122 selfA._parameters["InflationType"],
1123 selfA._parameters["InflationFactor"],
1126 Xa = Xn.mean(axis=1, dtype=mfp).astype('float')
1127 #--------------------------
1129 if selfA._parameters["StoreInternalVariables"] \
1130 or selfA._toStore("CostFunctionJ") \
1131 or selfA._toStore("CostFunctionJb") \
1132 or selfA._toStore("CostFunctionJo") \
1133 or selfA._toStore("APosterioriCovariance") \
1134 or selfA._toStore("InnovationAtCurrentAnalysis") \
1135 or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
1136 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1137 _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
1138 _Innovation = Ynpu - _HXa
1140 selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1141 # ---> avec analysis
1142 selfA.StoredVariables["Analysis"].store( Xa )
1143 if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
1144 selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
1145 if selfA._toStore("InnovationAtCurrentAnalysis"):
1146 selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
1147 # ---> avec current state
1148 if selfA._parameters["StoreInternalVariables"] \
1149 or selfA._toStore("CurrentState"):
1150 selfA.StoredVariables["CurrentState"].store( Xn )
1151 if selfA._toStore("ForecastState"):
1152 selfA.StoredVariables["ForecastState"].store( Xn_predicted )
1153 if selfA._toStore("BMA"):
1154 selfA.StoredVariables["BMA"].store( Xn_predicted - Xa )
1155 if selfA._toStore("InnovationAtCurrentState"):
1156 selfA.StoredVariables["InnovationAtCurrentState"].store( - HX_predicted + Ynpu )
1157 if selfA._toStore("SimulatedObservationAtCurrentState") \
1158 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1159 selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HX_predicted )
1161 if selfA._parameters["StoreInternalVariables"] \
1162 or selfA._toStore("CostFunctionJ") \
1163 or selfA._toStore("CostFunctionJb") \
1164 or selfA._toStore("CostFunctionJo") \
1165 or selfA._toStore("CurrentOptimum") \
1166 or selfA._toStore("APosterioriCovariance"):
1167 Jb = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
1168 Jo = float( 0.5 * _Innovation.T * RI * _Innovation )
1170 selfA.StoredVariables["CostFunctionJb"].store( Jb )
1171 selfA.StoredVariables["CostFunctionJo"].store( Jo )
1172 selfA.StoredVariables["CostFunctionJ" ].store( J )
1174 if selfA._toStore("IndexOfOptimum") \
1175 or selfA._toStore("CurrentOptimum") \
1176 or selfA._toStore("CostFunctionJAtCurrentOptimum") \
1177 or selfA._toStore("CostFunctionJbAtCurrentOptimum") \
1178 or selfA._toStore("CostFunctionJoAtCurrentOptimum") \
1179 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1180 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
1181 if selfA._toStore("IndexOfOptimum"):
1182 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
1183 if selfA._toStore("CurrentOptimum"):
1184 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["Analysis"][IndexMin] )
1185 if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1186 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"][IndexMin] )
1187 if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
1188 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
1189 if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
1190 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
1191 if selfA._toStore("CostFunctionJAtCurrentOptimum"):
1192 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
1193 if selfA._toStore("APosterioriCovariance"):
1194 Eai = (1/numpy.sqrt(__m-1)) * (Xn - Xa.reshape((__n,-1))) # Anomalies
1196 Pn = 0.5 * (Pn + Pn.T)
1197 selfA.StoredVariables["APosterioriCovariance"].store( Pn )
1198 if selfA._parameters["EstimationOf"] == "Parameters" \
1199 and J < previousJMinimum:
1200 previousJMinimum = J
1202 if selfA._toStore("APosterioriCovariance"):
1203 covarianceXaMin = Pn
1205 # Stockage final supplémentaire de l'optimum en estimation de paramètres
1206 # ----------------------------------------------------------------------
1207 if selfA._parameters["EstimationOf"] == "Parameters":
1208 selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1209 selfA.StoredVariables["Analysis"].store( XaMin )
1210 if selfA._toStore("APosterioriCovariance"):
1211 selfA.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
1212 if selfA._toStore("BMA"):
1213 selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
1217 # ==============================================================================
1218 def mlef(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, VariantM="MLEF13",
1219 BnotT=False, _epsilon=1.e-3, _e=1.e-7, _jmax=15000):
1221 Maximum Likelihood Ensemble Filter (EnKF/MLEF Zupanski 2005, Bocquet 2013)
1223 selfA est identique au "self" d'algorithme appelant et contient les
1226 if selfA._parameters["EstimationOf"] == "Parameters":
1227 selfA._parameters["StoreInternalVariables"] = True
1231 H = HO["Direct"].appliedControledFormTo
1233 if selfA._parameters["EstimationOf"] == "State":
1234 M = EM["Direct"].appliedControledFormTo
1236 if CM is not None and "Tangent" in CM and U is not None:
1237 Cm = CM["Tangent"].asMatrix(Xb)
1241 # Nombre de pas identique au nombre de pas d'observations
1242 # -------------------------------------------------------
1243 if hasattr(Y,"stepnumber"):
1244 duration = Y.stepnumber()
1245 __p = numpy.cumprod(Y.shape())[-1]
1248 __p = numpy.array(Y).size
1250 # Précalcul des inversions de B et R
1251 # ----------------------------------
1252 if selfA._parameters["StoreInternalVariables"] \
1253 or selfA._toStore("CostFunctionJ") \
1254 or selfA._toStore("CostFunctionJb") \
1255 or selfA._toStore("CostFunctionJo") \
1256 or selfA._toStore("CurrentOptimum") \
1257 or selfA._toStore("APosterioriCovariance"):
1264 __m = selfA._parameters["NumberOfMembers"]
1265 if hasattr(B,"asfullmatrix"): Pn = B.asfullmatrix(__n)
1267 if hasattr(R,"asfullmatrix"): Rn = R.asfullmatrix(__p)
1269 if hasattr(Q,"asfullmatrix"): Qn = Q.asfullmatrix(__n)
1271 Xn = BackgroundEnsembleGeneration( Xb, None, __m )
1273 if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
1274 selfA.StoredVariables["Analysis"].store( numpy.ravel(Xb) )
1275 if selfA._toStore("APosterioriCovariance"):
1276 selfA.StoredVariables["APosterioriCovariance"].store( Pn )
1279 previousJMinimum = numpy.finfo(float).max
1281 Xn_predicted = numpy.zeros((__n,__m))
1282 for step in range(duration-1):
1283 if hasattr(Y,"store"):
1284 Ynpu = numpy.ravel( Y[step+1] )[:,None]
1286 Ynpu = numpy.ravel( Y )[:,None]
1289 if hasattr(U,"store") and len(U)>1:
1290 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
1291 elif hasattr(U,"store") and len(U)==1:
1292 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
1294 Un = numpy.asmatrix(numpy.ravel( U )).T
1298 if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
1299 Xn = CovarianceInflation( Xn,
1300 selfA._parameters["InflationType"],
1301 selfA._parameters["InflationFactor"],
1304 if selfA._parameters["EstimationOf"] == "State": # Forecast + Q and observation of forecast
1305 EMX = M( [(Xn[:,i,numpy.newaxis], Un) for i in range(__m)], argsAsSerie = True )
1306 for i in range(__m):
1307 qi = numpy.random.multivariate_normal(numpy.zeros(__n), Qn)
1308 Xn_predicted[:,i] = numpy.ravel( EMX[i] ) + qi
1309 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
1310 Cm = Cm.reshape(__n,Un.size) # ADAO & check shape
1311 Xn_predicted = Xn_predicted + Cm * Un
1312 elif selfA._parameters["EstimationOf"] == "Parameters": # Observation of forecast
1313 # --- > Par principe, M = Id, Q = 0
1316 #--------------------------
1317 if VariantM == "MLEF13":
1318 Xfm = numpy.asarray(Xn_predicted.mean(axis=1, dtype=mfp).astype('float'))
1319 EaX = numpy.asarray((Xn_predicted - Xfm.reshape((__n,-1))) / numpy.sqrt(__m-1))
1325 vw = numpy.zeros(__m)
1326 while numpy.linalg.norm(Deltaw) >= _e and __j <= _jmax:
1327 vx1 = numpy.ravel(Xfm) + EaX @ vw
1330 E1 = vx1.reshape((__n,-1)) + _epsilon * EaX
1332 E1 = vx1.reshape((__n,-1)) + numpy.sqrt(__m-1) * EaX @ Ta
1334 HE2 = H( [(E1[:,i,numpy.newaxis], Un) for i in range(__m)],
1336 returnSerieAsArrayMatrix = True )
1337 vy2 = HE2.mean(axis=1, dtype=mfp).astype('float').reshape((__p,-1))
1340 EaY = (HE2 - vy2) / _epsilon
1342 EaY = ( (HE2 - vy2) @ numpy.linalg.inv(Ta) ) / numpy.sqrt(__m-1)
1344 GradJ = numpy.ravel(vw[:,None] - EaY.transpose() @ (RI * ( Ynpu - vy2 )))
1345 mH = numpy.eye(__m) + EaY.transpose() @ (RI * EaY)
1346 Deltaw = - numpy.linalg.solve(mH,GradJ)
1351 Ta = numpy.real(scipy.linalg.sqrtm(numpy.linalg.inv( mH )))
1356 Ta = numpy.real(scipy.linalg.sqrtm(numpy.linalg.inv( mH )))
1358 Xn = vx1.reshape((__n,-1)) + numpy.sqrt(__m-1) * EaX @ Ta @ Ua
1359 #--------------------------
1361 raise ValueError("VariantM has to be chosen in the authorized methods list.")
1363 if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
1364 Xn = CovarianceInflation( Xn,
1365 selfA._parameters["InflationType"],
1366 selfA._parameters["InflationFactor"],
1369 Xa = Xn.mean(axis=1, dtype=mfp).astype('float').reshape((__n,-1))
1370 #--------------------------
1372 if selfA._parameters["StoreInternalVariables"] \
1373 or selfA._toStore("CostFunctionJ") \
1374 or selfA._toStore("CostFunctionJb") \
1375 or selfA._toStore("CostFunctionJo") \
1376 or selfA._toStore("APosterioriCovariance") \
1377 or selfA._toStore("InnovationAtCurrentAnalysis") \
1378 or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
1379 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1380 _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
1381 _Innovation = Ynpu - _HXa
1383 selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1384 # ---> avec analysis
1385 selfA.StoredVariables["Analysis"].store( Xa )
1386 if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
1387 selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
1388 if selfA._toStore("InnovationAtCurrentAnalysis"):
1389 selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
1390 # ---> avec current state
1391 if selfA._parameters["StoreInternalVariables"] \
1392 or selfA._toStore("CurrentState"):
1393 selfA.StoredVariables["CurrentState"].store( Xn )
1394 if selfA._toStore("ForecastState"):
1395 selfA.StoredVariables["ForecastState"].store( Xn_predicted )
1396 if selfA._toStore("BMA"):
1397 selfA.StoredVariables["BMA"].store( Xn_predicted - Xa )
1398 #~ if selfA._toStore("InnovationAtCurrentState"):
1399 #~ selfA.StoredVariables["InnovationAtCurrentState"].store( - HX_predicted + Ynpu )
1400 #~ if selfA._toStore("SimulatedObservationAtCurrentState") \
1401 #~ or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1402 #~ selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HX_predicted )
1404 if selfA._parameters["StoreInternalVariables"] \
1405 or selfA._toStore("CostFunctionJ") \
1406 or selfA._toStore("CostFunctionJb") \
1407 or selfA._toStore("CostFunctionJo") \
1408 or selfA._toStore("CurrentOptimum") \
1409 or selfA._toStore("APosterioriCovariance"):
1410 Jb = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
1411 Jo = float( 0.5 * _Innovation.T * RI * _Innovation )
1413 selfA.StoredVariables["CostFunctionJb"].store( Jb )
1414 selfA.StoredVariables["CostFunctionJo"].store( Jo )
1415 selfA.StoredVariables["CostFunctionJ" ].store( J )
1417 if selfA._toStore("IndexOfOptimum") \
1418 or selfA._toStore("CurrentOptimum") \
1419 or selfA._toStore("CostFunctionJAtCurrentOptimum") \
1420 or selfA._toStore("CostFunctionJbAtCurrentOptimum") \
1421 or selfA._toStore("CostFunctionJoAtCurrentOptimum") \
1422 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1423 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
1424 if selfA._toStore("IndexOfOptimum"):
1425 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
1426 if selfA._toStore("CurrentOptimum"):
1427 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["Analysis"][IndexMin] )
1428 if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1429 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"][IndexMin] )
1430 if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
1431 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
1432 if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
1433 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
1434 if selfA._toStore("CostFunctionJAtCurrentOptimum"):
1435 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
1436 if selfA._toStore("APosterioriCovariance"):
1437 Eai = numpy.asarray((Xn - Xa.reshape((__n,-1))) / numpy.sqrt(__m-1)) # Anomalies
1439 Pn = 0.5 * (Pn + Pn.T)
1440 selfA.StoredVariables["APosterioriCovariance"].store( Pn )
1441 if selfA._parameters["EstimationOf"] == "Parameters" \
1442 and J < previousJMinimum:
1443 previousJMinimum = J
1445 if selfA._toStore("APosterioriCovariance"):
1446 covarianceXaMin = Pn
1448 # Stockage final supplémentaire de l'optimum en estimation de paramètres
1449 # ----------------------------------------------------------------------
1450 if selfA._parameters["EstimationOf"] == "Parameters":
1451 selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1452 selfA.StoredVariables["Analysis"].store( XaMin )
1453 if selfA._toStore("APosterioriCovariance"):
1454 selfA.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
1455 if selfA._toStore("BMA"):
1456 selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
1460 # ==============================================================================
1461 def ienkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, VariantM="IEnKF12",
1462 BnotT=False, _epsilon=1.e-3, _e=1.e-7, _jmax=15000):
1464 Iterative EnKF (Sakov 2012, Sakov 2018)
1466 selfA est identique au "self" d'algorithme appelant et contient les
1469 if selfA._parameters["EstimationOf"] == "Parameters":
1470 selfA._parameters["StoreInternalVariables"] = True
1474 H = HO["Direct"].appliedControledFormTo
1476 if selfA._parameters["EstimationOf"] == "State":
1477 M = EM["Direct"].appliedControledFormTo
1479 if CM is not None and "Tangent" in CM and U is not None:
1480 Cm = CM["Tangent"].asMatrix(Xb)
1484 # Nombre de pas identique au nombre de pas d'observations
1485 # -------------------------------------------------------
1486 if hasattr(Y,"stepnumber"):
1487 duration = Y.stepnumber()
1488 __p = numpy.cumprod(Y.shape())[-1]
1491 __p = numpy.array(Y).size
1493 # Précalcul des inversions de B et R
1494 # ----------------------------------
1495 if selfA._parameters["StoreInternalVariables"] \
1496 or selfA._toStore("CostFunctionJ") \
1497 or selfA._toStore("CostFunctionJb") \
1498 or selfA._toStore("CostFunctionJo") \
1499 or selfA._toStore("CurrentOptimum") \
1500 or selfA._toStore("APosterioriCovariance"):
1507 __m = selfA._parameters["NumberOfMembers"]
1508 if hasattr(B,"asfullmatrix"): Pn = B.asfullmatrix(__n)
1510 if hasattr(R,"asfullmatrix"): Rn = R.asfullmatrix(__p)
1512 if hasattr(Q,"asfullmatrix"): Qn = Q.asfullmatrix(__n)
1514 Xn = BackgroundEnsembleGeneration( Xb, Pn, __m )
1516 if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
1517 selfA.StoredVariables["Analysis"].store( numpy.ravel(Xb) )
1518 if selfA._toStore("APosterioriCovariance"):
1519 selfA.StoredVariables["APosterioriCovariance"].store( Pn )
1522 previousJMinimum = numpy.finfo(float).max
1524 for step in range(duration-1):
1525 if hasattr(Y,"store"):
1526 Ynpu = numpy.ravel( Y[step+1] )[:,None]
1528 Ynpu = numpy.ravel( Y )[:,None]
1531 if hasattr(U,"store") and len(U)>1:
1532 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
1533 elif hasattr(U,"store") and len(U)==1:
1534 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
1536 Un = numpy.asmatrix(numpy.ravel( U )).T
1540 if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
1541 Xn = CovarianceInflation( Xn,
1542 selfA._parameters["InflationType"],
1543 selfA._parameters["InflationFactor"],
1546 #--------------------------
1547 if VariantM == "IEnKF12":
1548 Xfm = numpy.asarray(Xn.mean(axis=1, dtype=mfp).astype('float'))
1549 EaX = numpy.asarray((Xn - Xfm.reshape((__n,-1))) / numpy.sqrt(__m-1))
1550 # EaX = EnsembleCenteredAnomalies( Xn ) / numpy.sqrt(__m-1)
1555 vw = numpy.zeros(__m)
1556 while numpy.linalg.norm(Deltaw) >= _e and __j <= _jmax:
1557 vx1 = numpy.ravel(Xfm) + EaX @ vw
1560 E1 = vx1.reshape((__n,-1)) + _epsilon * EaX
1562 E1 = vx1.reshape((__n,-1)) + numpy.sqrt(__m-1) * EaX @ Ta
1564 if selfA._parameters["EstimationOf"] == "State": # Forecast + Q
1565 E2 = M( [(E1[:,i,numpy.newaxis], Un) for i in range(__m)],
1567 returnSerieAsArrayMatrix = True )
1568 elif selfA._parameters["EstimationOf"] == "Parameters":
1569 # --- > Par principe, M = Id
1571 vx2 = E2.mean(axis=1, dtype=mfp).astype('float').reshape((__n,-1))
1572 vy1 = H((vx2, Un)).reshape((__p,-1))
1574 HE2 = H( [(E2[:,i,numpy.newaxis], Un) for i in range(__m)],
1576 returnSerieAsArrayMatrix = True )
1577 vy2 = HE2.mean(axis=1, dtype=mfp).astype('float').reshape((__p,-1))
1580 EaY = (HE2 - vy2) / _epsilon
1582 EaY = ( (HE2 - vy2) @ numpy.linalg.inv(Ta) ) / numpy.sqrt(__m-1)
1584 GradJ = numpy.ravel(vw[:,None] - EaY.transpose() @ (RI * ( Ynpu - vy1 )))
1585 mH = numpy.eye(__m) + EaY.transpose() @ (RI * EaY)
1586 Deltaw = - numpy.linalg.solve(mH,GradJ)
1591 Ta = numpy.real(scipy.linalg.sqrtm(numpy.linalg.inv( mH )))
1595 A2 = EnsembleCenteredAnomalies( E2 )
1598 Ta = numpy.real(scipy.linalg.sqrtm(numpy.linalg.inv( mH )))
1599 A2 = numpy.sqrt(__m-1) * A2 @ Ta / _epsilon
1602 #--------------------------
1604 raise ValueError("VariantM has to be chosen in the authorized methods list.")
1606 if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
1607 Xn = CovarianceInflation( Xn,
1608 selfA._parameters["InflationType"],
1609 selfA._parameters["InflationFactor"],
1612 Xa = Xn.mean(axis=1, dtype=mfp).astype('float').reshape((__n,-1))
1613 #--------------------------
1615 if selfA._parameters["StoreInternalVariables"] \
1616 or selfA._toStore("CostFunctionJ") \
1617 or selfA._toStore("CostFunctionJb") \
1618 or selfA._toStore("CostFunctionJo") \
1619 or selfA._toStore("APosterioriCovariance") \
1620 or selfA._toStore("InnovationAtCurrentAnalysis") \
1621 or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
1622 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1623 _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
1624 _Innovation = Ynpu - _HXa
1626 selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1627 # ---> avec analysis
1628 selfA.StoredVariables["Analysis"].store( Xa )
1629 if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
1630 selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
1631 if selfA._toStore("InnovationAtCurrentAnalysis"):
1632 selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
1633 # ---> avec current state
1634 if selfA._parameters["StoreInternalVariables"] \
1635 or selfA._toStore("CurrentState"):
1636 selfA.StoredVariables["CurrentState"].store( Xn )
1637 #~ if selfA._toStore("ForecastState"):
1638 #~ selfA.StoredVariables["ForecastState"].store( Xn_predicted )
1639 #~ if selfA._toStore("BMA"):
1640 #~ selfA.StoredVariables["BMA"].store( Xn_predicted - Xa )
1641 #~ if selfA._toStore("InnovationAtCurrentState"):
1642 #~ selfA.StoredVariables["InnovationAtCurrentState"].store( - HX_predicted + Ynpu.reshape((__p,-1)) )
1643 #~ if selfA._toStore("SimulatedObservationAtCurrentState") \
1644 #~ or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1645 #~ selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HX_predicted )
1647 if selfA._parameters["StoreInternalVariables"] \
1648 or selfA._toStore("CostFunctionJ") \
1649 or selfA._toStore("CostFunctionJb") \
1650 or selfA._toStore("CostFunctionJo") \
1651 or selfA._toStore("CurrentOptimum") \
1652 or selfA._toStore("APosterioriCovariance"):
1653 Jb = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
1654 Jo = float( 0.5 * _Innovation.T * RI * _Innovation )
1656 selfA.StoredVariables["CostFunctionJb"].store( Jb )
1657 selfA.StoredVariables["CostFunctionJo"].store( Jo )
1658 selfA.StoredVariables["CostFunctionJ" ].store( J )
1660 if selfA._toStore("IndexOfOptimum") \
1661 or selfA._toStore("CurrentOptimum") \
1662 or selfA._toStore("CostFunctionJAtCurrentOptimum") \
1663 or selfA._toStore("CostFunctionJbAtCurrentOptimum") \
1664 or selfA._toStore("CostFunctionJoAtCurrentOptimum") \
1665 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1666 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
1667 if selfA._toStore("IndexOfOptimum"):
1668 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
1669 if selfA._toStore("CurrentOptimum"):
1670 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["Analysis"][IndexMin] )
1671 if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1672 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"][IndexMin] )
1673 if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
1674 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
1675 if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
1676 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
1677 if selfA._toStore("CostFunctionJAtCurrentOptimum"):
1678 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
1679 if selfA._toStore("APosterioriCovariance"):
1680 Eai = numpy.asarray((Xn - Xa.reshape((__n,-1))) / numpy.sqrt(__m-1)) # Anomalies
1682 Pn = 0.5 * (Pn + Pn.T)
1683 selfA.StoredVariables["APosterioriCovariance"].store( Pn )
1684 if selfA._parameters["EstimationOf"] == "Parameters" \
1685 and J < previousJMinimum:
1686 previousJMinimum = J
1688 if selfA._toStore("APosterioriCovariance"):
1689 covarianceXaMin = Pn
1691 # Stockage final supplémentaire de l'optimum en estimation de paramètres
1692 # ----------------------------------------------------------------------
1693 if selfA._parameters["EstimationOf"] == "Parameters":
1694 selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1695 selfA.StoredVariables["Analysis"].store( XaMin )
1696 if selfA._toStore("APosterioriCovariance"):
1697 selfA.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
1698 if selfA._toStore("BMA"):
1699 selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
1703 # ==============================================================================
1704 if __name__ == "__main__":
1705 print('\n AUTODIAGNOSTIC\n')