Salome HOME
Correcting A-shape verification
[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", "MahalanobisConsistency"]
39             )
40
41     def run(self, Xb=None, Y=None, H=None, M=None, R=None, B=None, Q=None, Parameters=None):
42         logging.debug("%s Lancement"%self._name)
43         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
44         #
45         # Paramètres de pilotage
46         # ----------------------
47         self.setParameters(Parameters)
48         #
49         # Opérateur d'observation
50         # -----------------------
51         Hm = H["Tangent"].asMatrix(None)
52         Ha = H["Adjoint"].asMatrix(None)
53         #
54         # Utilisation éventuelle d'un vecteur H(Xb) précalculé
55         # ----------------------------------------------------
56         if H["AppliedToX"] is not None and H["AppliedToX"].has_key("HXb"):
57             HXb = H["AppliedToX"]["HXb"]
58         else:
59             HXb = Hm * Xb
60         HXb = numpy.asmatrix(numpy.ravel( HXb )).T
61         #
62         # Précalcul des inversions de B et R
63         # ----------------------------------
64         if B is not None:
65             BI = B.I
66         elif self._parameters["B_scalar"] is not None:
67             BI = 1.0 / self._parameters["B_scalar"]
68             B = self._parameters["B_scalar"]
69         else:
70             raise ValueError("Background error covariance matrix has to be properly defined!")
71         #
72         if R is not None:
73             RI = R.I
74         elif self._parameters["R_scalar"] is not None:
75             RI = 1.0 / self._parameters["R_scalar"]
76         else:
77             raise ValueError("Observation error covariance matrix has to be properly defined!")
78         #
79         # Calcul de l'innovation
80         # ----------------------
81         if Y.size != HXb.size:
82             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))
83         if max(Y.shape) != max(HXb.shape):
84             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))
85         d  = Y - HXb
86         #
87         # Calcul de la matrice de gain et de l'analyse
88         # --------------------------------------------
89         if Y.size <= Xb.size:
90             if self._parameters["R_scalar"] is not None:
91                 R = self._parameters["R_scalar"] * numpy.eye(len(Y), dtype=numpy.float)
92             K  = B * Ha * (Hm * B * Ha + R).I
93         else:
94             K = (Ha * RI * Hm + BI).I * Ha * RI
95         Xa = Xb + K*d
96         #
97         # Calcul de la fonction coût
98         # --------------------------
99         oma = Y - Hm * Xa
100         Jb  = 0.5 * (Xa - Xb).T * BI * (Xa - Xb)
101         Jo  = 0.5 * oma.T * RI * oma
102         J   = float( Jb ) + float( Jo )
103         self.StoredVariables["Analysis"].store( Xa.A1 )
104         self.StoredVariables["CostFunctionJb"].store( Jb )
105         self.StoredVariables["CostFunctionJo"].store( Jo )
106         self.StoredVariables["CostFunctionJ" ].store( J )
107         #
108         # Calcul de la covariance d'analyse
109         # ---------------------------------
110         if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
111             A = B - K * Hm * B
112             if min(A.shape) != max(A.shape):
113                 raise ValueError("The 3DVAR a posteriori covariance matrix A is of shape %s, despites it has to be a squared matrix. There is an error in the observation operator."%str(A.shape))
114             if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
115                 try:
116                     L = numpy.linalg.cholesky( A )
117                 except:
118                     raise ValueError("The BLUE a posteriori covariance matrix A is not symmetric positive-definite. Check your B and R a priori covariances.")
119             self.StoredVariables["APosterioriCovariance"].store( A )
120         #
121         # Calculs et/ou stockages supplémentaires
122         # ---------------------------------------
123         if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
124             self.StoredVariables["Innovation"].store( numpy.ravel(d) )
125         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
126             self.StoredVariables["BMA"].store( numpy.ravel(Xb - Xa) )
127         if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
128             self.StoredVariables["OMA"].store( numpy.ravel(oma) )
129         if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
130             self.StoredVariables["OMB"].store( numpy.ravel(d) )
131         if "SigmaObs2" in self._parameters["StoreSupplementaryCalculations"]:
132             self.StoredVariables["SigmaObs2"].store( float( (d.T * (Y-Hm*Xa)) / R.trace() ) )
133         if "SigmaBck2" in self._parameters["StoreSupplementaryCalculations"]:
134             self.StoredVariables["SigmaBck2"].store( float( (d.T * Hm * (Xa - Xb))/(Hm * B * Hm.T).trace() ) )
135         if "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"]:
136             self.StoredVariables["MahalanobisConsistency"].store( float( 2.*J/len(d) ) )
137         #
138         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
139         logging.debug("%s Terminé"%self._name)
140         #
141         return 0
142
143 # ==============================================================================
144 if __name__ == "__main__":
145     print '\n AUTODIAGNOSTIC \n'