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 CovarianceInflation(
513 InflationType = None,
514 InflationFactor = None,
515 BackgroundCov = None,
518 Inflation applicable soit sur Pb ou Pa, soit sur les ensembles EXb ou EXa
520 Synthèse : Hunt 2007, section 2.3.5
522 if InflationFactor is None:
525 InflationFactor = float(InflationFactor)
527 if InflationType in ["MultiplicativeOnAnalysisCovariance", "MultiplicativeOnBackgroundCovariance"]:
528 if InflationFactor < 1.:
529 raise ValueError("Inflation factor for multiplicative inflation has to be greater or equal than 1.")
530 if InflationFactor < 1.+mpr:
532 OutputCovOrEns = InflationFactor**2 * InputCovOrEns
534 elif InflationType in ["MultiplicativeOnAnalysisAnomalies", "MultiplicativeOnBackgroundAnomalies"]:
535 if InflationFactor < 1.:
536 raise ValueError("Inflation factor for multiplicative inflation has to be greater or equal than 1.")
537 if InflationFactor < 1.+mpr:
539 InputCovOrEnsMean = InputCovOrEns.mean(axis=1, dtype=mfp).astype('float')
540 OutputCovOrEns = InputCovOrEnsMean[:,numpy.newaxis] \
541 + InflationFactor * (InputCovOrEns - InputCovOrEnsMean[:,numpy.newaxis])
543 elif InflationType in ["AdditiveOnBackgroundCovariance", "AdditiveOnAnalysisCovariance"]:
544 if InflationFactor < 0.:
545 raise ValueError("Inflation factor for additive inflation has to be greater or equal than 0.")
546 if InflationFactor < mpr:
548 __n, __m = numpy.asarray(InputCovOrEns).shape
550 raise ValueError("Additive inflation can only be applied to squared (covariance) matrix.")
551 OutputCovOrEns = (1. - InflationFactor) * InputCovOrEns + InflationFactor * numpy.eye(__n)
553 elif InflationType == "HybridOnBackgroundCovariance":
554 if InflationFactor < 0.:
555 raise ValueError("Inflation factor for hybrid inflation has to be greater or equal than 0.")
556 if InflationFactor < mpr:
558 __n, __m = numpy.asarray(InputCovOrEns).shape
560 raise ValueError("Additive inflation can only be applied to squared (covariance) matrix.")
561 if BackgroundCov is None:
562 raise ValueError("Background covariance matrix B has to be given for hybrid inflation.")
563 if InputCovOrEns.shape != BackgroundCov.shape:
564 raise ValueError("Ensemble covariance matrix has to be of same size than background covariance matrix B.")
565 OutputCovOrEns = (1. - InflationFactor) * InputCovOrEns + InflationFactor * BackgroundCov
567 elif InflationType == "Relaxation":
568 raise NotImplementedError("InflationType Relaxation")
571 raise ValueError("Error in inflation type, '%s' is not a valid keyword."%InflationType)
573 return OutputCovOrEns
575 # ==============================================================================
576 def senkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q):
578 Stochastic EnKF (Envensen 1994, Burgers 1998)
580 selfA est identique au "self" d'algorithme appelant et contient les
583 if selfA._parameters["EstimationOf"] == "Parameters":
584 selfA._parameters["StoreInternalVariables"] = True
588 H = HO["Direct"].appliedControledFormTo
590 if selfA._parameters["EstimationOf"] == "State":
591 M = EM["Direct"].appliedControledFormTo
593 if CM is not None and "Tangent" in CM and U is not None:
594 Cm = CM["Tangent"].asMatrix(Xb)
598 # Nombre de pas identique au nombre de pas d'observations
599 # -------------------------------------------------------
600 if hasattr(Y,"stepnumber"):
601 duration = Y.stepnumber()
602 __p = numpy.cumprod(Y.shape())[-1]
605 __p = numpy.array(Y).size
607 # Précalcul des inversions de B et R
608 # ----------------------------------
609 if selfA._parameters["StoreInternalVariables"] \
610 or selfA._toStore("CostFunctionJ") \
611 or selfA._toStore("CostFunctionJb") \
612 or selfA._toStore("CostFunctionJo") \
613 or selfA._toStore("CurrentOptimum") \
614 or selfA._toStore("APosterioriCovariance"):
621 __m = selfA._parameters["NumberOfMembers"]
622 Xn = numpy.asmatrix(numpy.dot( Xb.reshape(__n,1), numpy.ones((1,__m)) ))
623 if hasattr(B,"asfullmatrix"): Pn = B.asfullmatrix(__n)
625 if hasattr(R,"asfullmatrix"): Rn = R.asfullmatrix(__p)
627 if hasattr(Q,"asfullmatrix"): Qn = Q.asfullmatrix(__n)
630 if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
631 selfA.StoredVariables["Analysis"].store( numpy.ravel(Xb) )
632 if selfA._toStore("APosterioriCovariance"):
633 selfA.StoredVariables["APosterioriCovariance"].store( Pn )
636 previousJMinimum = numpy.finfo(float).max
639 Xn_predicted = numpy.asmatrix(numpy.zeros((__n,__m)))
640 HX_predicted = numpy.asmatrix(numpy.zeros((__p,__m)))
642 for step in range(duration-1):
643 if hasattr(Y,"store"):
644 Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
646 Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
649 if hasattr(U,"store") and len(U)>1:
650 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
651 elif hasattr(U,"store") and len(U)==1:
652 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
654 Un = numpy.asmatrix(numpy.ravel( U )).T
658 if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
659 Xn = CovarianceInflation( Xn,
660 selfA._parameters["InflationType"],
661 selfA._parameters["InflationFactor"],
664 if selfA._parameters["EstimationOf"] == "State": # Forecast + Q and observation of forecast
666 qi = numpy.asmatrix(numpy.random.multivariate_normal(numpy.zeros(__n), Qn, (1,1,1))).T
667 Xn_predicted[:,i] = numpy.asmatrix(numpy.ravel( M((Xn[:,i], Un)) )).T + qi
668 HX_predicted[:,i] = numpy.asmatrix(numpy.ravel( H((Xn_predicted[:,i], Un)) )).T
669 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
670 Cm = Cm.reshape(__n,Un.size) # ADAO & check shape
671 Xn_predicted = Xn_predicted + Cm * Un
672 elif selfA._parameters["EstimationOf"] == "Parameters": # Observation of forecast
673 # --- > Par principe, M = Id, Q = 0
676 HX_predicted[:,i] = numpy.asmatrix(numpy.ravel( H((Xn_predicted[:,i], Un)) )).T
678 # Mean of forecast and observation of forecast
679 Xfm = numpy.asmatrix(numpy.ravel(Xn_predicted.mean(axis=1, dtype=mfp).astype('float'))).T
680 Hfm = numpy.asmatrix(numpy.ravel(HX_predicted.mean(axis=1, dtype=mfp).astype('float'))).T
684 Exfi = Xn_predicted[:,i] - Xfm
685 Eyfi = HX_predicted[:,i] - Hfm
686 PfHT += Exfi * Eyfi.T
687 HPfHT += Eyfi * Eyfi.T
688 PfHT = (1./(__m-1)) * PfHT
689 HPfHT = (1./(__m-1)) * HPfHT
690 K = PfHT * ( R + HPfHT ).I
694 ri = numpy.asmatrix(numpy.random.multivariate_normal(numpy.zeros(__p), Rn, (1,1,1))).T
695 Xn[:,i] = Xn_predicted[:,i] + K * (Ynpu + ri - HX_predicted[:,i])
697 if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
698 Xn = CovarianceInflation( Xn,
699 selfA._parameters["InflationType"],
700 selfA._parameters["InflationFactor"],
703 Xa = Xn.mean(axis=1, dtype=mfp).astype('float')
705 if selfA._parameters["StoreInternalVariables"] \
706 or selfA._toStore("CostFunctionJ") \
707 or selfA._toStore("CostFunctionJb") \
708 or selfA._toStore("CostFunctionJo") \
709 or selfA._toStore("APosterioriCovariance") \
710 or selfA._toStore("InnovationAtCurrentAnalysis") \
711 or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
712 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
713 _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
714 _Innovation = Ynpu - _HXa
716 selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
718 selfA.StoredVariables["Analysis"].store( Xa )
719 if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
720 selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
721 if selfA._toStore("InnovationAtCurrentAnalysis"):
722 selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
723 # ---> avec current state
724 if selfA._parameters["StoreInternalVariables"] \
725 or selfA._toStore("CurrentState"):
726 selfA.StoredVariables["CurrentState"].store( Xn )
727 if selfA._toStore("ForecastState"):
728 selfA.StoredVariables["ForecastState"].store( Xn_predicted )
729 if selfA._toStore("BMA"):
730 selfA.StoredVariables["BMA"].store( Xn_predicted - Xa )
731 if selfA._toStore("InnovationAtCurrentState"):
732 selfA.StoredVariables["InnovationAtCurrentState"].store( - HX_predicted + Ynpu )
733 if selfA._toStore("SimulatedObservationAtCurrentState") \
734 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
735 selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HX_predicted )
737 if selfA._parameters["StoreInternalVariables"] \
738 or selfA._toStore("CostFunctionJ") \
739 or selfA._toStore("CostFunctionJb") \
740 or selfA._toStore("CostFunctionJo") \
741 or selfA._toStore("CurrentOptimum") \
742 or selfA._toStore("APosterioriCovariance"):
743 Jb = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
744 Jo = float( 0.5 * _Innovation.T * RI * _Innovation )
746 selfA.StoredVariables["CostFunctionJb"].store( Jb )
747 selfA.StoredVariables["CostFunctionJo"].store( Jo )
748 selfA.StoredVariables["CostFunctionJ" ].store( J )
750 if selfA._toStore("IndexOfOptimum") \
751 or selfA._toStore("CurrentOptimum") \
752 or selfA._toStore("CostFunctionJAtCurrentOptimum") \
753 or selfA._toStore("CostFunctionJbAtCurrentOptimum") \
754 or selfA._toStore("CostFunctionJoAtCurrentOptimum") \
755 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
756 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
757 if selfA._toStore("IndexOfOptimum"):
758 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
759 if selfA._toStore("CurrentOptimum"):
760 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["Analysis"][IndexMin] )
761 if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
762 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"][IndexMin] )
763 if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
764 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
765 if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
766 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
767 if selfA._toStore("CostFunctionJAtCurrentOptimum"):
768 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
769 if selfA._toStore("APosterioriCovariance"):
770 Eai = (1/numpy.sqrt(__m-1)) * (Xn - Xa.reshape((__n,-1))) # Anomalies
772 Pn = 0.5 * (Pn + Pn.T)
773 selfA.StoredVariables["APosterioriCovariance"].store( Pn )
774 if selfA._parameters["EstimationOf"] == "Parameters" \
775 and J < previousJMinimum:
778 if selfA._toStore("APosterioriCovariance"):
781 # Stockage final supplémentaire de l'optimum en estimation de paramètres
782 # ----------------------------------------------------------------------
783 if selfA._parameters["EstimationOf"] == "Parameters":
784 selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
785 selfA.StoredVariables["Analysis"].store( XaMin )
786 if selfA._toStore("APosterioriCovariance"):
787 selfA.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
788 if selfA._toStore("BMA"):
789 selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
793 # ==============================================================================
794 def etkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, KorV="KalmanFilterFormula"):
796 Ensemble-Transform EnKF (ETKF or Deterministic EnKF: Bishop 2001, Hunt 2007)
798 selfA est identique au "self" d'algorithme appelant et contient les
801 if selfA._parameters["EstimationOf"] == "Parameters":
802 selfA._parameters["StoreInternalVariables"] = True
806 H = HO["Direct"].appliedControledFormTo
808 if selfA._parameters["EstimationOf"] == "State":
809 M = EM["Direct"].appliedControledFormTo
811 if CM is not None and "Tangent" in CM and U is not None:
812 Cm = CM["Tangent"].asMatrix(Xb)
816 # Nombre de pas identique au nombre de pas d'observations
817 # -------------------------------------------------------
818 if hasattr(Y,"stepnumber"):
819 duration = Y.stepnumber()
820 __p = numpy.cumprod(Y.shape())[-1]
823 __p = numpy.array(Y).size
825 # Précalcul des inversions de B et R
826 # ----------------------------------
827 if selfA._parameters["StoreInternalVariables"] \
828 or selfA._toStore("CostFunctionJ") \
829 or selfA._toStore("CostFunctionJb") \
830 or selfA._toStore("CostFunctionJo") \
831 or selfA._toStore("CurrentOptimum") \
832 or selfA._toStore("APosterioriCovariance"):
839 __m = selfA._parameters["NumberOfMembers"]
840 Xn = numpy.asmatrix(numpy.dot( Xb.reshape(__n,1), numpy.ones((1,__m)) ))
841 if hasattr(B,"asfullmatrix"): Pn = B.asfullmatrix(__n)
843 if hasattr(R,"asfullmatrix"): Rn = R.asfullmatrix(__p)
845 if hasattr(Q,"asfullmatrix"): Qn = Q.asfullmatrix(__n)
848 if len(selfA.StoredVariables["Analysis"])==0 or not selfA._parameters["nextStep"]:
849 selfA.StoredVariables["Analysis"].store( numpy.ravel(Xb) )
850 if selfA._toStore("APosterioriCovariance"):
851 selfA.StoredVariables["APosterioriCovariance"].store( Pn )
854 previousJMinimum = numpy.finfo(float).max
857 Xn_predicted = numpy.asmatrix(numpy.zeros((__n,__m)))
858 HX_predicted = numpy.asmatrix(numpy.zeros((__p,__m)))
860 for step in range(duration-1):
861 if hasattr(Y,"store"):
862 Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
864 Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
867 if hasattr(U,"store") and len(U)>1:
868 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
869 elif hasattr(U,"store") and len(U)==1:
870 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
872 Un = numpy.asmatrix(numpy.ravel( U )).T
876 if selfA._parameters["InflationType"] == "MultiplicativeOnBackgroundAnomalies":
877 Xn = CovarianceInflation( Xn,
878 selfA._parameters["InflationType"],
879 selfA._parameters["InflationFactor"],
882 if selfA._parameters["EstimationOf"] == "State": # Forecast + Q and observation of forecast
884 qi = numpy.asmatrix(numpy.random.multivariate_normal(numpy.zeros(__n), Qn, (1,1,1))).T
885 Xn_predicted[:,i] = numpy.asmatrix(numpy.ravel( M((Xn[:,i], Un)) )).T + qi
886 HX_predicted[:,i] = numpy.asmatrix(numpy.ravel( H((Xn_predicted[:,i], Un)) )).T
887 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
888 Cm = Cm.reshape(__n,Un.size) # ADAO & check shape
889 Xn_predicted = Xn_predicted + Cm * Un
890 elif selfA._parameters["EstimationOf"] == "Parameters": # Observation of forecast
891 # --- > Par principe, M = Id, Q = 0
894 HX_predicted[:,i] = numpy.asmatrix(numpy.ravel( H((Xn_predicted[:,i], Un)) )).T
896 # Mean of forecast and observation of forecast
897 Xfm = Xn_predicted.mean(axis=1, dtype=mfp).astype('float')
898 Hfm = HX_predicted.mean(axis=1, dtype=mfp).astype('float')
900 EaX = (Xn_predicted - Xfm.reshape((__n,-1)))
901 EaHX = (HX_predicted - Hfm.reshape((__p,-1)))
903 #--------------------------
904 if KorV == "KalmanFilterFormula":
905 EaX = EaX / numpy.sqrt(__m-1)
906 RIdemi = R.choleskyI()
907 mS = RIdemi * EaHX / numpy.sqrt(__m-1)
908 delta = RIdemi * ( Ynpu.reshape((__p,-1)) - Hfm.reshape((__p,-1)) )
909 mT = numpy.linalg.inv( numpy.eye(__m) + mS.T @ mS )
910 vw = mT @ mS.transpose() @ delta
912 Tdemi = numpy.real(scipy.linalg.sqrtm(mT))
915 Xn = Xfm.reshape((__n,-1)) + EaX @ ( vw.reshape((__m,-1)) + numpy.sqrt(__m-1) * Tdemi @ mU )
916 #--------------------------
917 elif KorV == "Variational":
919 HXfm = H((Xfm, Un)) # Eventuellement Hfm
921 _A = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
922 _J = 0.5 * (__m-1) * w.T @ w + 0.5 * _A.T * RI * _A
924 def GradientOfCostFunction(w):
925 _A = Ynpu.reshape((__p,-1)) - HXfm.reshape((__p,-1)) - (EaHX @ w).reshape((__p,-1))
926 _GradJ = (__m-1) * w.reshape((__m,1)) - EaHX.T * RI * _A
927 return numpy.ravel(_GradJ)
928 vw = scipy.optimize.fmin_cg(
930 x0 = numpy.zeros(__m),
931 fprime = GradientOfCostFunction,
936 Pta = numpy.linalg.inv( (__m-1)*numpy.eye(__m) + EaHX.T * RI * EaHX )
937 EWa = numpy.real(scipy.linalg.sqrtm((__m-1)*Pta)) # Partie imaginaire ~= 10^-18
939 Xn = Xfm.reshape((__n,-1)) + EaX @ (vw.reshape((__m,-1)) + EWa)
940 #--------------------------
942 raise ValueError("KorV has to be chosen as either \"KalmanFilterFormula\" or \"Variational\".")
944 if selfA._parameters["InflationType"] == "MultiplicativeOnAnalysisAnomalies":
945 Xn = CovarianceInflation( Xn,
946 selfA._parameters["InflationType"],
947 selfA._parameters["InflationFactor"],
950 Xa = Xn.mean(axis=1, dtype=mfp).astype('float')
951 #--------------------------
953 if selfA._parameters["StoreInternalVariables"] \
954 or selfA._toStore("CostFunctionJ") \
955 or selfA._toStore("CostFunctionJb") \
956 or selfA._toStore("CostFunctionJo") \
957 or selfA._toStore("APosterioriCovariance") \
958 or selfA._toStore("InnovationAtCurrentAnalysis") \
959 or selfA._toStore("SimulatedObservationAtCurrentAnalysis") \
960 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
961 _HXa = numpy.asmatrix(numpy.ravel( H((Xa, Un)) )).T
962 _Innovation = Ynpu - _HXa
964 selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
966 selfA.StoredVariables["Analysis"].store( Xa )
967 if selfA._toStore("SimulatedObservationAtCurrentAnalysis"):
968 selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"].store( _HXa )
969 if selfA._toStore("InnovationAtCurrentAnalysis"):
970 selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( _Innovation )
971 # ---> avec current state
972 if selfA._parameters["StoreInternalVariables"] \
973 or selfA._toStore("CurrentState"):
974 selfA.StoredVariables["CurrentState"].store( Xn )
975 if selfA._toStore("ForecastState"):
976 selfA.StoredVariables["ForecastState"].store( Xn_predicted )
977 if selfA._toStore("BMA"):
978 selfA.StoredVariables["BMA"].store( Xn_predicted - Xa )
979 if selfA._toStore("InnovationAtCurrentState"):
980 selfA.StoredVariables["InnovationAtCurrentState"].store( - HX_predicted + Ynpu )
981 if selfA._toStore("SimulatedObservationAtCurrentState") \
982 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
983 selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( HX_predicted )
985 if selfA._parameters["StoreInternalVariables"] \
986 or selfA._toStore("CostFunctionJ") \
987 or selfA._toStore("CostFunctionJb") \
988 or selfA._toStore("CostFunctionJo") \
989 or selfA._toStore("CurrentOptimum") \
990 or selfA._toStore("APosterioriCovariance"):
991 Jb = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
992 Jo = float( 0.5 * _Innovation.T * RI * _Innovation )
994 selfA.StoredVariables["CostFunctionJb"].store( Jb )
995 selfA.StoredVariables["CostFunctionJo"].store( Jo )
996 selfA.StoredVariables["CostFunctionJ" ].store( J )
998 if selfA._toStore("IndexOfOptimum") \
999 or selfA._toStore("CurrentOptimum") \
1000 or selfA._toStore("CostFunctionJAtCurrentOptimum") \
1001 or selfA._toStore("CostFunctionJbAtCurrentOptimum") \
1002 or selfA._toStore("CostFunctionJoAtCurrentOptimum") \
1003 or selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1004 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
1005 if selfA._toStore("IndexOfOptimum"):
1006 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
1007 if selfA._toStore("CurrentOptimum"):
1008 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["Analysis"][IndexMin] )
1009 if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
1010 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentAnalysis"][IndexMin] )
1011 if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
1012 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
1013 if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
1014 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
1015 if selfA._toStore("CostFunctionJAtCurrentOptimum"):
1016 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
1017 if selfA._toStore("APosterioriCovariance"):
1018 Eai = (1/numpy.sqrt(__m-1)) * (Xn - Xa.reshape((__n,-1))) # Anomalies
1020 Pn = 0.5 * (Pn + Pn.T)
1021 selfA.StoredVariables["APosterioriCovariance"].store( Pn )
1022 if selfA._parameters["EstimationOf"] == "Parameters" \
1023 and J < previousJMinimum:
1024 previousJMinimum = J
1026 if selfA._toStore("APosterioriCovariance"):
1027 covarianceXaMin = Pn
1029 # Stockage final supplémentaire de l'optimum en estimation de paramètres
1030 # ----------------------------------------------------------------------
1031 if selfA._parameters["EstimationOf"] == "Parameters":
1032 selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["Analysis"]) )
1033 selfA.StoredVariables["Analysis"].store( XaMin )
1034 if selfA._toStore("APosterioriCovariance"):
1035 selfA.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
1036 if selfA._toStore("BMA"):
1037 selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
1041 # ==============================================================================
1042 if __name__ == "__main__":
1043 print('\n AUTODIAGNOSTIC\n')