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):
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')
741 Exfi = Xn_predicted[:,i] - Xfm.reshape((__n,-1))
742 Eyfi = (HX_predicted[:,i] - Hfm).reshape((__p,1))
743 PfHT += Exfi * Eyfi.T
744 HPfHT += Eyfi * Eyfi.T
745 PfHT = (1./(__m-1)) * PfHT
746 HPfHT = (1./(__m-1)) * HPfHT
747 K = PfHT * ( R + HPfHT ).I
751 ri = numpy.random.multivariate_normal(numpy.zeros(__p), Rn)
752 Xn[:,i] = Xn_predicted[:,i] + K @ (numpy.ravel(Ynpu) + ri - HX_predicted[:,i]).reshape((__p,1))
754 if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
755 Xn = CovarianceInflation( Xn,
756 selfA._parameters["InflationType"],
757 selfA._parameters["InflationFactor"],
760 Xa = Xn.mean(axis=1, dtype=mfp).astype('float')
761 #--------------------------
763 if selfA._parameters["StoreInternalVariables"] \
764 or selfA._toStore("CostFunctionJ") \
765 or selfA._toStore("CostFunctionJb") \
766 or selfA._toStore("CostFunctionJo") \
767 or selfA._toStore("APosterioriCovariance") \
768 or selfA._toStore("InnovationAtCurrentAnalysis") \
769 or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
770 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
771 _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
772 _Innovation = Ynpu - _HXa
774 selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
776 selfA.StoredVariables["Analysis"].store( Xa )
777 if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
778 selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
779 if selfA._toStore("InnovationAtCurrentAnalysis"):
780 selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
781 # ---> avec current state
782 if selfA._parameters["StoreInternalVariables"] \
783 or selfA._toStore("CurrentState"):
784 selfA.StoredVariables["CurrentState"].store( Xn )
785 if selfA._toStore("ForecastState"):
786 selfA.StoredVariables["ForecastState"].store( Xn_predicted )
787 if selfA._toStore("BMA"):
788 selfA.StoredVariables["BMA"].store( Xn_predicted - Xa )
789 if selfA._toStore("InnovationAtCurrentState"):
790 selfA.StoredVariables["InnovationAtCurrentState"].store( - HX_predicted + Ynpu )
791 if selfA._toStore("SimulatedObservationAtCurrentState") \
792 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
793 selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HX_predicted )
795 if selfA._parameters["StoreInternalVariables"] \
796 or selfA._toStore("CostFunctionJ") \
797 or selfA._toStore("CostFunctionJb") \
798 or selfA._toStore("CostFunctionJo") \
799 or selfA._toStore("CurrentOptimum") \
800 or selfA._toStore("APosterioriCovariance"):
801 Jb = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
802 Jo = float( 0.5 * _Innovation.T * RI * _Innovation )
804 selfA.StoredVariables["CostFunctionJb"].store( Jb )
805 selfA.StoredVariables["CostFunctionJo"].store( Jo )
806 selfA.StoredVariables["CostFunctionJ" ].store( J )
808 if selfA._toStore("IndexOfOptimum") \
809 or selfA._toStore("CurrentOptimum") \
810 or selfA._toStore("CostFunctionJAtCurrentOptimum") \
811 or selfA._toStore("CostFunctionJbAtCurrentOptimum") \
812 or selfA._toStore("CostFunctionJoAtCurrentOptimum") \
813 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
814 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
815 if selfA._toStore("IndexOfOptimum"):
816 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
817 if selfA._toStore("CurrentOptimum"):
818 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["Analysis"][IndexMin] )
819 if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
820 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"][IndexMin] )
821 if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
822 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
823 if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
824 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
825 if selfA._toStore("CostFunctionJAtCurrentOptimum"):
826 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
827 if selfA._toStore("APosterioriCovariance"):
828 Eai = (1/numpy.sqrt(__m-1)) * (Xn - Xa.reshape((__n,-1))) # Anomalies
830 Pn = 0.5 * (Pn + Pn.T)
831 selfA.StoredVariables["APosterioriCovariance"].store( Pn )
832 if selfA._parameters["EstimationOf"] == "Parameters" \
833 and J < previousJMinimum:
836 if selfA._toStore("APosterioriCovariance"):
839 # Stockage final supplémentaire de l'optimum en estimation de paramètres
840 # ----------------------------------------------------------------------
841 if selfA._parameters["EstimationOf"] == "Parameters":
842 selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
843 selfA.StoredVariables["Analysis"].store( XaMin )
844 if selfA._toStore("APosterioriCovariance"):
845 selfA.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
846 if selfA._toStore("BMA"):
847 selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
851 # ==============================================================================
852 def etkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, KorV="KalmanFilterFormula"):
854 Ensemble-Transform EnKF (ETKF or Deterministic EnKF: Bishop 2001, Hunt 2007)
856 selfA est identique au "self" d'algorithme appelant et contient les
859 if selfA._parameters["EstimationOf"] == "Parameters":
860 selfA._parameters["StoreInternalVariables"] = True
864 H = HO["Direct"].appliedControledFormTo
866 if selfA._parameters["EstimationOf"] == "State":
867 M = EM["Direct"].appliedControledFormTo
869 if CM is not None and "Tangent" in CM and U is not None:
870 Cm = CM["Tangent"].asMatrix(Xb)
874 # Nombre de pas identique au nombre de pas d'observations
875 # -------------------------------------------------------
876 if hasattr(Y,"stepnumber"):
877 duration = Y.stepnumber()
878 __p = numpy.cumprod(Y.shape())[-1]
881 __p = numpy.array(Y).size
883 # Précalcul des inversions de B et R
884 # ----------------------------------
885 if selfA._parameters["StoreInternalVariables"] \
886 or selfA._toStore("CostFunctionJ") \
887 or selfA._toStore("CostFunctionJb") \
888 or selfA._toStore("CostFunctionJo") \
889 or selfA._toStore("CurrentOptimum") \
890 or selfA._toStore("APosterioriCovariance"):
893 elif KorV != "KalmanFilterFormula":
895 if KorV == "KalmanFilterFormula":
896 RIdemi = R.choleskyI()
901 __m = selfA._parameters["NumberOfMembers"]
902 Xn = numpy.asmatrix(numpy.dot( Xb.reshape(__n,1), numpy.ones((1,__m)) ))
903 if hasattr(B,"asfullmatrix"): Pn = B.asfullmatrix(__n)
905 if hasattr(R,"asfullmatrix"): Rn = R.asfullmatrix(__p)
907 if hasattr(Q,"asfullmatrix"): Qn = Q.asfullmatrix(__n)
910 if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
911 selfA.StoredVariables["Analysis"].store( numpy.ravel(Xb) )
912 if selfA._toStore("APosterioriCovariance"):
913 selfA.StoredVariables["APosterioriCovariance"].store( Pn )
916 previousJMinimum = numpy.finfo(float).max
919 Xn_predicted = numpy.asmatrix(numpy.zeros((__n,__m)))
920 HX_predicted = numpy.asmatrix(numpy.zeros((__p,__m)))
922 for step in range(duration-1):
923 if hasattr(Y,"store"):
924 Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
926 Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
929 if hasattr(U,"store") and len(U)>1:
930 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
931 elif hasattr(U,"store") and len(U)==1:
932 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
934 Un = numpy.asmatrix(numpy.ravel( U )).T
938 if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
939 Xn = CovarianceInflation( Xn,
940 selfA._parameters["InflationType"],
941 selfA._parameters["InflationFactor"],
944 if selfA._parameters["EstimationOf"] == "State": # Forecast + Q and observation of forecast
945 EMX = M( [(Xn[:,i], Un) for i in range(__m)], argsAsSerie = True )
947 qi = numpy.random.multivariate_normal(numpy.zeros(__n), Qn)
948 Xn_predicted[:,i] = (numpy.ravel( EMX[i] ) + qi).reshape((__n,-1))
949 HX_predicted = H( [(Xn_predicted[:,i], Un) for i in range(__m)],
951 returnSerieAsArrayMatrix = True )
952 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
953 Cm = Cm.reshape(__n,Un.size) # ADAO & check shape
954 Xn_predicted = Xn_predicted + Cm * Un
955 elif selfA._parameters["EstimationOf"] == "Parameters": # Observation of forecast
956 # --- > Par principe, M = Id, Q = 0
958 HX_predicted = H( [(Xn_predicted[:,i], Un) for i in range(__m)],
960 returnSerieAsArrayMatrix = True )
962 # Mean of forecast and observation of forecast
963 Xfm = Xn_predicted.mean(axis=1, dtype=mfp).astype('float')
964 Hfm = HX_predicted.mean(axis=1, dtype=mfp).astype('float')
966 EaX = numpy.matrix(Xn_predicted - Xfm.reshape((__n,-1)))
967 EaHX = numpy.matrix(HX_predicted - Hfm.reshape((__p,-1)))
969 #--------------------------
970 if KorV == "KalmanFilterFormula":
971 EaX = EaX / numpy.sqrt(__m-1)
972 mS = RIdemi * EaHX / numpy.sqrt(__m-1)
973 delta = RIdemi * ( Ynpu.reshape((__p,-1)) - Hfm.reshape((__p,-1)) )
974 mT = numpy.linalg.inv( numpy.eye(__m) + mS.T @ mS )
975 vw = mT @ mS.transpose() @ delta
977 Tdemi = numpy.real(scipy.linalg.sqrtm(mT))
980 Xn = Xfm.reshape((__n,-1)) + EaX @ ( vw.reshape((__m,-1)) + numpy.sqrt(__m-1) * Tdemi @ mU )
981 #--------------------------
982 elif KorV == "Variational":
983 HXfm = H((Xfm, Un)) # Eventuellement Hfm
985 _A = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
986 _Jo = 0.5 * _A.T * RI * _A
987 _Jb = 0.5 * (__m-1) * w.T @ w
990 def GradientOfCostFunction(w):
991 _A = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
992 _GardJo = - EaHX.T * RI * _A
993 _GradJb = (__m-1) * w.reshape((__m,1))
994 _GradJ = _GardJo + _GradJb
995 return numpy.ravel(_GradJ)
996 vw = scipy.optimize.fmin_cg(
998 x0 = numpy.zeros(__m),
999 fprime = GradientOfCostFunction,
1004 Hto = EaHX.T * RI * EaHX
1005 Htb = (__m-1) * numpy.eye(__m)
1008 Pta = numpy.linalg.inv( Hta )
1009 EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1011 Xn = Xfm.reshape((__n,-1)) + EaX @ (vw.reshape((__m,-1)) + EWa)
1012 #--------------------------
1013 elif KorV == "FiniteSize11": # Jauge Boc2011
1014 HXfm = H((Xfm, Un)) # Eventuellement Hfm
1015 def CostFunction(w):
1016 _A = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1017 _Jo = 0.5 * _A.T * RI * _A
1018 _Jb = 0.5 * __m * math.log(1 + 1/__m + w.T @ w)
1021 def GradientOfCostFunction(w):
1022 _A = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1023 _GardJo = - EaHX.T * RI * _A
1024 _GradJb = __m * w.reshape((__m,1)) / (1 + 1/__m + w.T @ w)
1025 _GradJ = _GardJo + _GradJb
1026 return numpy.ravel(_GradJ)
1027 vw = scipy.optimize.fmin_cg(
1029 x0 = numpy.zeros(__m),
1030 fprime = GradientOfCostFunction,
1035 Hto = EaHX.T * RI * EaHX
1037 ( (1 + 1/__m + vw.T @ vw) * numpy.eye(__m) - 2 * vw @ vw.T ) \
1038 / (1 + 1/__m + vw.T @ vw)**2
1041 Pta = numpy.linalg.inv( Hta )
1042 EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1044 Xn = Xfm.reshape((__n,-1)) + EaX @ (vw.reshape((__m,-1)) + EWa)
1045 #--------------------------
1046 elif KorV == "FiniteSize15": # Jauge Boc2015
1047 HXfm = H((Xfm, Un)) # Eventuellement Hfm
1048 def CostFunction(w):
1049 _A = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1050 _Jo = 0.5 * _A.T * RI * _A
1051 _Jb = 0.5 * (__m+1) * math.log(1 + 1/__m + w.T @ w)
1054 def GradientOfCostFunction(w):
1055 _A = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1056 _GardJo = - EaHX.T * RI * _A
1057 _GradJb = (__m+1) * w.reshape((__m,1)) / (1 + 1/__m + w.T @ w)
1058 _GradJ = _GardJo + _GradJb
1059 return numpy.ravel(_GradJ)
1060 vw = scipy.optimize.fmin_cg(
1062 x0 = numpy.zeros(__m),
1063 fprime = GradientOfCostFunction,
1068 Hto = EaHX.T * RI * EaHX
1070 ( (1 + 1/__m + vw.T @ vw) * numpy.eye(__m) - 2 * vw @ vw.T ) \
1071 / (1 + 1/__m + vw.T @ vw)**2
1074 Pta = numpy.linalg.inv( Hta )
1075 EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1077 Xn = Xfm.reshape((__n,-1)) + EaX @ (vw.reshape((__m,-1)) + EWa)
1078 #--------------------------
1079 elif KorV == "FiniteSize16": # Jauge Boc2016
1080 HXfm = H((Xfm, Un)) # Eventuellement Hfm
1081 def CostFunction(w):
1082 _A = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1083 _Jo = 0.5 * _A.T * RI * _A
1084 _Jb = 0.5 * (__m+1) * math.log(1 + 1/__m + w.T @ w / (__m-1))
1087 def GradientOfCostFunction(w):
1088 _A = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
1089 _GardJo = - EaHX.T * RI * _A
1090 _GradJb = ((__m+1) / (__m-1)) * w.reshape((__m,1)) / (1 + 1/__m + w.T @ w / (__m-1))
1091 _GradJ = _GardJo + _GradJb
1092 return numpy.ravel(_GradJ)
1093 vw = scipy.optimize.fmin_cg(
1095 x0 = numpy.zeros(__m),
1096 fprime = GradientOfCostFunction,
1101 Hto = EaHX.T * RI * EaHX
1102 Htb = ((__m+1) / (__m-1)) * \
1103 ( (1 + 1/__m + vw.T @ vw / (__m-1)) * numpy.eye(__m) - 2 * vw @ vw.T / (__m-1) ) \
1104 / (1 + 1/__m + vw.T @ vw / (__m-1))**2
1107 Pta = numpy.linalg.inv( Hta )
1108 EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
1110 Xn = Xfm.reshape((__n,-1)) + EaX @ (vw.reshape((__m,-1)) + EWa)
1111 #--------------------------
1113 raise ValueError("KorV has to be chosen in the authorized methods list.")
1115 if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
1116 Xn = CovarianceInflation( Xn,
1117 selfA._parameters["InflationType"],
1118 selfA._parameters["InflationFactor"],
1121 Xa = Xn.mean(axis=1, dtype=mfp).astype('float')
1122 #--------------------------
1124 if selfA._parameters["StoreInternalVariables"] \
1125 or selfA._toStore("CostFunctionJ") \
1126 or selfA._toStore("CostFunctionJb") \
1127 or selfA._toStore("CostFunctionJo") \
1128 or selfA._toStore("APosterioriCovariance") \
1129 or selfA._toStore("InnovationAtCurrentAnalysis") \
1130 or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
1131 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1132 _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
1133 _Innovation = Ynpu - _HXa
1135 selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1136 # ---> avec analysis
1137 selfA.StoredVariables["Analysis"].store( Xa )
1138 if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
1139 selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
1140 if selfA._toStore("InnovationAtCurrentAnalysis"):
1141 selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
1142 # ---> avec current state
1143 if selfA._parameters["StoreInternalVariables"] \
1144 or selfA._toStore("CurrentState"):
1145 selfA.StoredVariables["CurrentState"].store( Xn )
1146 if selfA._toStore("ForecastState"):
1147 selfA.StoredVariables["ForecastState"].store( Xn_predicted )
1148 if selfA._toStore("BMA"):
1149 selfA.StoredVariables["BMA"].store( Xn_predicted - Xa )
1150 if selfA._toStore("InnovationAtCurrentState"):
1151 selfA.StoredVariables["InnovationAtCurrentState"].store( - HX_predicted + Ynpu )
1152 if selfA._toStore("SimulatedObservationAtCurrentState") \
1153 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1154 selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HX_predicted )
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 Eai = (1/numpy.sqrt(__m-1)) * (Xn - Xa.reshape((__n,-1))) # Anomalies
1191 Pn = 0.5 * (Pn + Pn.T)
1192 selfA.StoredVariables["APosterioriCovariance"].store( Pn )
1193 if selfA._parameters["EstimationOf"] == "Parameters" \
1194 and J < previousJMinimum:
1195 previousJMinimum = J
1197 if selfA._toStore("APosterioriCovariance"):
1198 covarianceXaMin = Pn
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 mlef(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, BnotT=False, _epsilon=1.e-1, _e=1.e-7, _jmax=15000):
1215 Maximum Likelihood Ensemble Filter (EnKF/MLEF Zupanski 2005, Bocquet 2013)
1217 selfA est identique au "self" d'algorithme appelant et contient les
1220 if selfA._parameters["EstimationOf"] == "Parameters":
1221 selfA._parameters["StoreInternalVariables"] = True
1225 H = HO["Direct"].appliedControledFormTo
1227 if selfA._parameters["EstimationOf"] == "State":
1228 M = EM["Direct"].appliedControledFormTo
1230 if CM is not None and "Tangent" in CM and U is not None:
1231 Cm = CM["Tangent"].asMatrix(Xb)
1235 # Nombre de pas identique au nombre de pas d'observations
1236 # -------------------------------------------------------
1237 if hasattr(Y,"stepnumber"):
1238 duration = Y.stepnumber()
1239 __p = numpy.cumprod(Y.shape())[-1]
1242 __p = numpy.array(Y).size
1244 # Précalcul des inversions de B et R
1245 # ----------------------------------
1246 if selfA._parameters["StoreInternalVariables"] \
1247 or selfA._toStore("CostFunctionJ") \
1248 or selfA._toStore("CostFunctionJb") \
1249 or selfA._toStore("CostFunctionJo") \
1250 or selfA._toStore("CurrentOptimum") \
1251 or selfA._toStore("APosterioriCovariance"):
1258 __m = selfA._parameters["NumberOfMembers"]
1259 if hasattr(B,"asfullmatrix"): Pn = B.asfullmatrix(__n)
1261 if hasattr(R,"asfullmatrix"): Rn = R.asfullmatrix(__p)
1263 if hasattr(Q,"asfullmatrix"): Qn = Q.asfullmatrix(__n)
1265 Xn = BackgroundEnsembleGeneration( Xb, None, __m )
1267 if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
1268 selfA.StoredVariables["Analysis"].store( numpy.ravel(Xb) )
1269 if selfA._toStore("APosterioriCovariance"):
1270 selfA.StoredVariables["APosterioriCovariance"].store( Pn )
1273 previousJMinimum = numpy.finfo(float).max
1275 Xn_predicted = numpy.zeros((__n,__m))
1276 for step in range(duration-1):
1277 if hasattr(Y,"store"):
1278 Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
1280 Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
1283 if hasattr(U,"store") and len(U)>1:
1284 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
1285 elif hasattr(U,"store") and len(U)==1:
1286 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
1288 Un = numpy.asmatrix(numpy.ravel( U )).T
1292 if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
1293 Xn = CovarianceInflation( Xn,
1294 selfA._parameters["InflationType"],
1295 selfA._parameters["InflationFactor"],
1298 if selfA._parameters["EstimationOf"] == "State": # Forecast + Q and observation of forecast
1299 EMX = M( [(Xn[:,i], Un) for i in range(__m)], argsAsSerie = True )
1300 for i in range(__m):
1301 qi = numpy.random.multivariate_normal(numpy.zeros(__n), Qn)
1302 Xn_predicted[:,i] = (numpy.ravel( EMX[i] ) + qi).reshape((__n,-1))
1303 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
1304 Cm = Cm.reshape(__n,Un.size) # ADAO & check shape
1305 Xn_predicted = Xn_predicted + Cm * Un
1306 elif selfA._parameters["EstimationOf"] == "Parameters": # Observation of forecast
1307 # --- > Par principe, M = Id, Q = 0
1310 # Mean of forecast and observation of forecast
1311 Xfm = Xn_predicted.mean(axis=1, dtype=mfp).astype('float')
1313 EaX = (Xn_predicted - Xfm.reshape((__n,-1))) / numpy.sqrt(__m-1)
1315 #--------------------------
1320 vw = numpy.zeros(__m) # 4:
1322 while numpy.linalg.norm(Deltaw) >= _e or __j >= _jmax: # 5: et 19:
1323 vx = numpy.ravel(Xfm) + EaX @ vw # 6:
1326 EE = vx.reshape((__n,-1)) + _epsilon * EaX # 7:
1328 EE = vx.reshape((__n,-1)) + numpy.sqrt(__m-1) * EaX @ Ta # 8:
1330 EZ = H( [(EE[:,i], Un) for i in range(__m)],
1332 returnSerieAsArrayMatrix = True )
1334 ybar = EZ.mean(axis=1, dtype=mfp).astype('float').reshape((__p,-1)) # 10: Observation mean
1337 EY = (EZ - ybar) / _epsilon # 11:
1339 EY = ( (EZ - ybar) @ numpy.linalg.inv(Ta) ) / numpy.sqrt(__m-1) # 12:
1341 GradJ = numpy.ravel(vw.reshape((__m,1)) - EY.transpose() @ (RI * (Ynpu - ybar))) # 13:
1342 mH = numpy.eye(__m) + EY.transpose() @ (RI * EY) # 14:
1343 Deltaw = numpy.linalg.solve(mH,GradJ) # 15:
1344 vw = vw - Deltaw # 16:
1346 Ta = numpy.linalg.inv(numpy.real(scipy.linalg.sqrtm( mH ))) # 17:
1350 Ta = numpy.linalg.inv(numpy.real(scipy.linalg.sqrtm( mH ))) # 20:
1352 Xn = vx.reshape((__n,-1)) + numpy.sqrt(__m-1) * EaX @ Ta @ Ua # 21:
1354 if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
1355 Xn = CovarianceInflation( Xn,
1356 selfA._parameters["InflationType"],
1357 selfA._parameters["InflationFactor"],
1360 Xa = Xn.mean(axis=1, dtype=mfp).astype('float')
1361 #--------------------------
1363 if selfA._parameters["StoreInternalVariables"] \
1364 or selfA._toStore("CostFunctionJ") \
1365 or selfA._toStore("CostFunctionJb") \
1366 or selfA._toStore("CostFunctionJo") \
1367 or selfA._toStore("APosterioriCovariance") \
1368 or selfA._toStore("InnovationAtCurrentAnalysis") \
1369 or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
1370 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1371 _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
1372 _Innovation = Ynpu - _HXa
1374 selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1375 # ---> avec analysis
1376 selfA.StoredVariables["Analysis"].store( Xa )
1377 if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
1378 selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
1379 if selfA._toStore("InnovationAtCurrentAnalysis"):
1380 selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
1381 # ---> avec current state
1382 if selfA._parameters["StoreInternalVariables"] \
1383 or selfA._toStore("CurrentState"):
1384 selfA.StoredVariables["CurrentState"].store( Xn )
1385 if selfA._toStore("ForecastState"):
1386 selfA.StoredVariables["ForecastState"].store( Xn_predicted )
1387 if selfA._toStore("BMA"):
1388 selfA.StoredVariables["BMA"].store( Xn_predicted - Xa )
1389 #~ if selfA._toStore("InnovationAtCurrentState"):
1390 #~ selfA.StoredVariables["InnovationAtCurrentState"].store( - HX_predicted + Ynpu )
1391 #~ if selfA._toStore("SimulatedObservationAtCurrentState") \
1392 #~ or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1393 #~ selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HX_predicted )
1395 if selfA._parameters["StoreInternalVariables"] \
1396 or selfA._toStore("CostFunctionJ") \
1397 or selfA._toStore("CostFunctionJb") \
1398 or selfA._toStore("CostFunctionJo") \
1399 or selfA._toStore("CurrentOptimum") \
1400 or selfA._toStore("APosterioriCovariance"):
1401 Jb = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
1402 Jo = float( 0.5 * _Innovation.T * RI * _Innovation )
1404 selfA.StoredVariables["CostFunctionJb"].store( Jb )
1405 selfA.StoredVariables["CostFunctionJo"].store( Jo )
1406 selfA.StoredVariables["CostFunctionJ" ].store( J )
1408 if selfA._toStore("IndexOfOptimum") \
1409 or selfA._toStore("CurrentOptimum") \
1410 or selfA._toStore("CostFunctionJAtCurrentOptimum") \
1411 or selfA._toStore("CostFunctionJbAtCurrentOptimum") \
1412 or selfA._toStore("CostFunctionJoAtCurrentOptimum") \
1413 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1414 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
1415 if selfA._toStore("IndexOfOptimum"):
1416 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
1417 if selfA._toStore("CurrentOptimum"):
1418 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["Analysis"][IndexMin] )
1419 if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1420 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"][IndexMin] )
1421 if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
1422 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
1423 if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
1424 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
1425 if selfA._toStore("CostFunctionJAtCurrentOptimum"):
1426 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
1427 if selfA._toStore("APosterioriCovariance"):
1428 Eai = (1/numpy.sqrt(__m-1)) * (Xn - Xa.reshape((__n,-1))) # Anomalies
1430 Pn = 0.5 * (Pn + Pn.T)
1431 selfA.StoredVariables["APosterioriCovariance"].store( Pn )
1432 if selfA._parameters["EstimationOf"] == "Parameters" \
1433 and J < previousJMinimum:
1434 previousJMinimum = J
1436 if selfA._toStore("APosterioriCovariance"):
1437 covarianceXaMin = Pn
1439 # Stockage final supplémentaire de l'optimum en estimation de paramètres
1440 # ----------------------------------------------------------------------
1441 if selfA._parameters["EstimationOf"] == "Parameters":
1442 selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1443 selfA.StoredVariables["Analysis"].store( XaMin )
1444 if selfA._toStore("APosterioriCovariance"):
1445 selfA.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
1446 if selfA._toStore("BMA"):
1447 selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
1451 # ==============================================================================
1452 if __name__ == "__main__":
1453 print('\n AUTODIAGNOSTIC\n')