]> SALOME platform Git repositories - modules/adao.git/blob - src/daComposant/daAlgorithms/Blue.py
Salome HOME
Unified management of supplementary variables to calculate or store
[modules/adao.git] / src / daComposant / daAlgorithms / Blue.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2012 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, "BLUE")
33         self.defineRequiredParameter(
34             name     = "StoreSupplementaryCalculations",
35             default  = [],
36             typecast = tuple,
37             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
38             listval  = ["APosterioriCovariance", "BMA", "OMA", "OMB", "Innovation", "SigmaBck2", "SigmaObs2"]
39             )
40
41     def run(self, Xb=None, Y=None, H=None, M=None, R=None, B=None, Q=None, Parameters=None):
42         """
43         Calcul de l'estimateur BLUE (ou Kalman simple, ou Interpolation Optimale)
44         """
45         logging.debug("%s Lancement"%self._name)
46         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
47         #
48         # Paramètres de pilotage
49         # ----------------------
50         self.setParameters(Parameters)
51         #
52         # Opérateur d'observation
53         # -----------------------
54         Hm = H["Tangent"].asMatrix(None)
55         Ha = H["Adjoint"].asMatrix(None)
56         #
57         # Utilisation éventuelle d'un vecteur H(Xb) précalculé
58         # ----------------------------------------------------
59         if H["AppliedToX"] is not None and H["AppliedToX"].has_key("HXb"):
60             logging.debug("%s Utilisation de HXb"%self._name)
61             HXb = H["AppliedToX"]["HXb"]
62         else:
63             logging.debug("%s Calcul de Hm * Xb"%self._name)
64             HXb = Hm * Xb
65         HXb = numpy.asmatrix(HXb).flatten().T
66         #
67         # Précalcul des inversions de B et R
68         # ----------------------------------
69         if B is not None:
70             BI = B.I
71         elif self._parameters["B_scalar"] is not None:
72             BI = 1.0 / self._parameters["B_scalar"]
73             B = self._parameters["B_scalar"]
74         else:
75             raise ValueError("Background error covariance matrix has to be properly defined!")
76         #
77         if R is not None:
78             RI = R.I
79         elif self._parameters["R_scalar"] is not None:
80             RI = 1.0 / self._parameters["R_scalar"]
81         else:
82             raise ValueError("Observation error covariance matrix has to be properly defined!")
83         #
84         # Calcul de l'innovation
85         # ----------------------
86         if Y.size != HXb.size:
87             raise ValueError("The size %i of observations Y and %i of observed calculation H(X) are different, they have to be identical."%(Y.size,HXb.size))
88         if max(Y.shape) != max(HXb.shape):
89             raise ValueError("The shapes %s of observations Y and %s of observed calculation H(X) are different, they have to be identical."%(Y.shape,HXb.shape))
90         d  = Y - HXb
91         Jb  = 0.
92         Jo  = 0.5 * d.T * RI * d
93         J   = float( Jb ) + float( Jo )
94         logging.debug("%s Innovation d    = %s"%(self._name, d))
95         logging.debug("%s CostFunction Jb = %s"%(self._name, Jb))
96         logging.debug("%s CostFunction Jo = %s"%(self._name, Jo))
97         logging.debug("%s CostFunction J  = %s"%(self._name, J))
98         #
99         self.StoredVariables["CostFunctionJb"].store( Jb )
100         self.StoredVariables["CostFunctionJo"].store( Jo )
101         self.StoredVariables["CostFunctionJ" ].store( J )
102         #
103         # Calcul de la matrice de gain et de l'analyse
104         # --------------------------------------------
105         if Y.size <= Xb.size:
106             if self._parameters["R_scalar"] is not None:
107                 R = self._parameters["R_scalar"] * numpy.eye(len(Y), dtype=numpy.float)
108             logging.debug("%s Calcul de K dans l'espace des observations"%self._name)
109             K  = B * Ha * (Hm * B * Ha + R).I
110         else:
111             logging.debug("%s Calcul de K dans l'espace d'ébauche"%self._name)
112             K = (Ha * RI * Hm + BI).I * Ha * RI
113         Xa = Xb + K*d
114         logging.debug("%s Analyse Xa = %s"%(self._name, Xa))
115         #
116         # Calcul de la fonction coût
117         # --------------------------
118         oma = Y - Hm * Xa
119         Jb  = 0.5 * (Xa - Xb).T * BI * (Xa - Xb)
120         Jo  = 0.5 * oma.T * RI * oma
121         J   = float( Jb ) + float( Jo )
122         logging.debug("%s OMA             = %s"%(self._name, oma))
123         logging.debug("%s CostFunction Jb = %s"%(self._name, Jb))
124         logging.debug("%s CostFunction Jo = %s"%(self._name, Jo))
125         logging.debug("%s CostFunction J  = %s"%(self._name, J))
126         #
127         self.StoredVariables["Analysis"].store( Xa.A1 )
128         self.StoredVariables["CostFunctionJb"].store( Jb )
129         self.StoredVariables["CostFunctionJo"].store( Jo )
130         self.StoredVariables["CostFunctionJ" ].store( J )
131         #
132         # Calcul de la covariance d'analyse
133         # ---------------------------------
134         if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
135             A = B - K * Hm * B
136             if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
137                 try:
138                     L = numpy.linalg.cholesky( A )
139                 except:
140                     raise ValueError("The BLUE a posteriori covariance matrix A is not symmetric positive-definite. Check your B and R a priori covariances.")
141             self.StoredVariables["APosterioriCovariance"].store( A )
142         #
143         # Calculs et/ou stockages supplémentaires
144         # ---------------------------------------
145         if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
146             self.StoredVariables["Innovation"].store( numpy.asmatrix(d).flatten().A1 )
147         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
148             self.StoredVariables["BMA"].store( numpy.asmatrix(Xb - Xa).flatten().A1 )
149         if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
150             self.StoredVariables["OMA"].store( numpy.asmatrix(oma).flatten().A1 )
151         if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
152             self.StoredVariables["OMB"].store( numpy.asmatrix(d).flatten().A1 )
153         if "SigmaObs2" in self._parameters["StoreSupplementaryCalculations"]:
154             self.StoredVariables["SigmaObs2"].store( float( (d.T * (Y-Hm*Xa)) / R.trace() ) )
155         if "SigmaBck2" in self._parameters["StoreSupplementaryCalculations"]:
156             self.StoredVariables["SigmaBck2"].store( float( (d.T * Hm * (Xa - Xb))/(Hm * B * Hm.T).trace() ) )
157         #
158         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
159         logging.debug("%s Terminé"%self._name)
160         #
161         return 0
162
163 # ==============================================================================
164 if __name__ == "__main__":
165     print '\n AUTODIAGNOSTIC \n'