Salome HOME
f4fe6a92dd04daf6a756fb659cab65b5ed16ef08
[modules/adao.git] / src / daComposant / daAlgorithms / Blue.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, "BLUE")
33         self.defineRequiredParameter(
34             name     = "StoreInternalVariables",
35             default  = False,
36             typecast = bool,
37             message  = "Stockage des variables internes ou intermédiaires du calcul",
38             )
39         self.defineRequiredParameter(
40             name     = "StoreSupplementaryCalculations",
41             default  = [],
42             typecast = tuple,
43             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
44             listval  = ["APosterioriCovariance", "BMA", "OMA", "OMB", "Innovation", "SigmaBck2", "SigmaObs2", "MahalanobisConsistency"]
45             )
46
47     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
48         logging.debug("%s Lancement"%self._name)
49         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
50         #
51         # Paramètres de pilotage
52         # ----------------------
53         self.setParameters(Parameters)
54         #
55         # Opérateur d'observation
56         # -----------------------
57         Hm = HO["Tangent"].asMatrix(Xb)
58         Hm = Hm.reshape(Y.size,Xb.size) # ADAO & check shape
59         Ha = HO["Adjoint"].asMatrix(Xb)
60         Ha = Ha.reshape(Xb.size,Y.size) # ADAO & check shape
61         #
62         # Utilisation éventuelle d'un vecteur H(Xb) précalculé
63         # ----------------------------------------------------
64         if HO["AppliedToX"] is not None and HO["AppliedToX"].has_key("HXb"):
65             HXb = HO["AppliedToX"]["HXb"]
66         else:
67             HXb = Hm * Xb
68         HXb = numpy.asmatrix(numpy.ravel( HXb )).T
69         #
70         # Précalcul des inversions de B et R
71         # ----------------------------------
72         if B is not None:
73             BI = B.I
74         elif self._parameters["B_scalar"] is not None:
75             BI = 1.0 / self._parameters["B_scalar"]
76             B = self._parameters["B_scalar"]
77         else:
78             raise ValueError("Background error covariance matrix has to be properly defined!")
79         #
80         if R is not None:
81             RI = R.I
82         elif self._parameters["R_scalar"] is not None:
83             RI = 1.0 / self._parameters["R_scalar"]
84         else:
85             raise ValueError("Observation error covariance matrix has to be properly defined!")
86         #
87         # Calcul de l'innovation
88         # ----------------------
89         if Y.size != HXb.size:
90             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))
91         if max(Y.shape) != max(HXb.shape):
92             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))
93         d  = Y - HXb
94         #
95         # Calcul de la matrice de gain et de l'analyse
96         # --------------------------------------------
97         if Y.size <= Xb.size:
98             if self._parameters["R_scalar"] is not None:
99                 R = self._parameters["R_scalar"] * numpy.eye(Y.size, dtype=numpy.float)
100             if Y.size > 100: # len(R)
101                 _A = Hm * B * Ha + R
102                 _u = numpy.linalg.solve( _A , d )
103                 Xa = Xb + B * Ha * _u
104             else:
105                 K  = B * Ha * (Hm * B * Ha + R).I
106                 Xa = Xb + K*d
107         else:
108             if Y.size > 100: # len(R)
109                 _A = Ha * RI * Hm + BI
110                 _u = numpy.linalg.solve( _A , Ha * RI * d )
111                 Xa = Xb + _u
112             else:
113                 K = (Ha * RI * Hm + BI).I * Ha * RI
114                 Xa = Xb + K*d
115         self.StoredVariables["Analysis"].store( Xa.A1 )
116         #
117         # Calcul de la fonction coût
118         # --------------------------
119         if self._parameters["StoreInternalVariables"] or "OMA" in self._parameters["StoreSupplementaryCalculations"] or "SigmaObs2" in self._parameters["StoreSupplementaryCalculations"] or "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"]:
120             oma = Y - Hm * Xa
121         if self._parameters["StoreInternalVariables"] or "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"]:
122             Jb  = 0.5 * (Xa - Xb).T * BI * (Xa - Xb)
123             Jo  = 0.5 * oma.T * RI * oma
124             J   = float( Jb ) + float( Jo )
125             self.StoredVariables["CostFunctionJb"].store( Jb )
126             self.StoredVariables["CostFunctionJo"].store( Jo )
127             self.StoredVariables["CostFunctionJ" ].store( J )
128         #
129         # Calcul de la covariance d'analyse
130         # ---------------------------------
131         if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
132             A = B - K * Hm * B
133             if min(A.shape) != max(A.shape):
134                 raise ValueError("The %s 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, please check it."%(self._name,str(A.shape)))
135             if (numpy.diag(A) < 0).any():
136                 raise ValueError("The %s a posteriori covariance matrix A has at least one negative value on its diagonal. There is an error in the observation operator, please check it."%(self._name,))
137             if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
138                 try:
139                     L = numpy.linalg.cholesky( A )
140                 except:
141                     raise ValueError("The %s a posteriori covariance matrix A is not symmetric positive-definite. Please check your a priori covariances and your observation operator."%(self._name,))
142             self.StoredVariables["APosterioriCovariance"].store( A )
143         #
144         # Calculs et/ou stockages supplémentaires
145         # ---------------------------------------
146         if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
147             self.StoredVariables["Innovation"].store( numpy.ravel(d) )
148         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
149             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
150         if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
151             self.StoredVariables["OMA"].store( numpy.ravel(oma) )
152         if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
153             self.StoredVariables["OMB"].store( numpy.ravel(d) )
154         if "SigmaObs2" in self._parameters["StoreSupplementaryCalculations"]:
155             if R is not None:
156                 TraceR = R.trace()
157             elif self._parameters["R_scalar"] is not None:
158                 TraceR =  float(self._parameters["R_scalar"]*Y.size)
159             self.StoredVariables["SigmaObs2"].store( float( (d.T * (numpy.asmatrix(numpy.ravel(oma)).T)) ) / TraceR )
160         if "SigmaBck2" in self._parameters["StoreSupplementaryCalculations"]:
161             self.StoredVariables["SigmaBck2"].store( float( (d.T * Hm * (Xa - Xb))/(Hm * B * Hm.T).trace() ) )
162         if "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"]:
163             self.StoredVariables["MahalanobisConsistency"].store( float( 2.*J/d.size ) )
164         #
165         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
166         logging.debug("%s Terminé"%self._name)
167         #
168         return 0
169
170 # ==============================================================================
171 if __name__ == "__main__":
172     print '\n AUTODIAGNOSTIC \n'