Salome HOME
Improving size checking and conversions
[modules/adao.git] / src / daComposant / daAlgorithms / EnsembleBlue.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2013 EDF R&D
4 #
5 #  This library is free software; you can redistribute it and/or
6 #  modify it under the terms of the GNU Lesser General Public
7 #  License as published by the Free Software Foundation; either
8 #  version 2.1 of the License.
9 #
10 #  This library is distributed in the hope that it will be useful,
11 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 #  Lesser General Public License for more details.
14 #
15 #  You should have received a copy of the GNU Lesser General Public
16 #  License along with this library; if not, write to the Free Software
17 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18 #
19 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #
21 #  Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
22
23 import logging
24 from daCore import BasicObjects, PlatformInfo
25 m = PlatformInfo.SystemUsage()
26
27 import numpy
28
29 # ==============================================================================
30 class ElementaryAlgorithm(BasicObjects.Algorithm):
31     def __init__(self):
32         BasicObjects.Algorithm.__init__(self, "ENSEMBLEBLUE")
33         self.defineRequiredParameter(
34             name     = "SetSeed",
35             typecast = numpy.random.seed,
36             message  = "Graine fixée pour le générateur aléatoire",
37             )
38
39     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
40         logging.debug("%s Lancement"%self._name)
41         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
42         #
43         # Paramètres de pilotage
44         # ----------------------
45         self.setParameters(Parameters)
46         #
47         # Précalcul des inversions de B et R
48         # ----------------------------------
49         if B is not None:
50             BI = B.I
51         elif self._parameters["B_scalar"] is not None:
52             BI = 1.0 / self._parameters["B_scalar"]
53             B = self._parameters["B_scalar"]
54         else:
55             raise ValueError("Background error covariance matrix has to be properly defined!")
56         #
57         if R is not None:
58             RI = R.I
59         elif self._parameters["R_scalar"] is not None:
60             RI = 1.0 / self._parameters["R_scalar"]
61         else:
62             raise ValueError("Observation error covariance matrix has to be properly defined!")
63         #
64         # Nombre d'ensemble pour l'ébauche 
65         # --------------------------------
66         nb_ens = Xb.stepnumber()
67         #
68         # Construction de l'ensemble des observations, par génération a partir
69         # de la diagonale de R
70         # --------------------------------------------------------------------
71         DiagonaleR = numpy.diag(R)
72         EnsembleY = numpy.zeros([Y.size,nb_ens])
73         for npar in range(DiagonaleR.size) : 
74             bruit = numpy.random.normal(0,DiagonaleR[npar],nb_ens)
75             EnsembleY[npar,:] = Y[npar] + bruit
76         EnsembleY = numpy.matrix(EnsembleY)
77         #
78         # Initialisation des opérateurs d'observation et de la matrice gain
79         # -----------------------------------------------------------------
80         Hm = HO["Tangent"].asMatrix(None)
81         Hm = Hm.reshape(Y.size,Xb[0].size) # ADAO & check shape
82         Ha = HO["Adjoint"].asMatrix(None)
83         Ha = Ha.reshape(Xb[0].size,Y.size) # ADAO & check shape
84         #
85         # Calcul de la matrice de gain dans l'espace le plus petit et de l'analyse
86         # ------------------------------------------------------------------------
87         if Y.size <= Xb[0].size:
88             if self._parameters["R_scalar"] is not None:
89                 R = self._parameters["R_scalar"] * numpy.eye(Y.size, dtype=numpy.float)
90             K  = B * Ha * (Hm * B * Ha + R).I
91         else:
92             K = (Ha * RI * Hm + BI).I * Ha * RI
93         #
94         # Calcul du BLUE pour chaque membre de l'ensemble
95         # -----------------------------------------------
96         for iens in range(nb_ens):
97             d  = EnsembleY[:,iens] - Hm * Xb[iens]
98             Xa = Xb[iens] + K*d
99             
100             self.StoredVariables["CurrentState"].store( Xa.A1 )
101             self.StoredVariables["Innovation"].store( d.A1 )
102         #
103         # Fabrication de l'analyse
104         # ------------------------
105         Members = self.StoredVariables["CurrentState"][-nb_ens:]
106         Xa = numpy.matrix( Members ).mean(axis=0)
107         self.StoredVariables["Analysis"].store( Xa.A1 )
108         #
109         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
110         logging.debug("%s Terminé"%self._name)
111         return 0
112
113 # ==============================================================================
114 if __name__ == "__main__":
115     print '\n AUTODIAGNOSTIC \n'