]> SALOME platform Git repositories - modules/adao.git/blob - src/daComposant/daAlgorithms/Blue.py
Salome HOME
Minor modification of debug information
[modules/adao.git] / src / daComposant / daAlgorithms / Blue.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2014 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
25 import numpy
26
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
29     def __init__(self):
30         BasicObjects.Algorithm.__init__(self, "BLUE")
31         self.defineRequiredParameter(
32             name     = "StoreInternalVariables",
33             default  = False,
34             typecast = bool,
35             message  = "Stockage des variables internes ou intermédiaires du calcul",
36             )
37         self.defineRequiredParameter(
38             name     = "StoreSupplementaryCalculations",
39             default  = [],
40             typecast = tuple,
41             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
42             listval  = ["APosterioriCovariance", "BMA", "OMA", "OMB", "Innovation", "SigmaBck2", "SigmaObs2", "MahalanobisConsistency", "SimulationQuantiles"]
43             )
44         self.defineRequiredParameter(
45             name     = "Quantiles",
46             default  = [],
47             typecast = tuple,
48             message  = "Liste des valeurs de quantiles",
49             )
50         self.defineRequiredParameter(
51             name     = "SetSeed",
52             typecast = numpy.random.seed,
53             message  = "Graine fixée pour le générateur aléatoire",
54             )
55         self.defineRequiredParameter(
56             name     = "NumberOfSamplesForQuantiles",
57             default  = 100,
58             typecast = int,
59             message  = "Nombre d'échantillons simulés pour le calcul des quantiles",
60             minval   = 1,
61             )
62         self.defineRequiredParameter(
63             name     = "SimulationForQuantiles",
64             default  = "Linear",
65             typecast = str,
66             message  = "Type de simulation pour l'estimation des quantiles",
67             listval  = ["Linear", "NonLinear"]
68             )
69
70     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
71         self._pre_run()
72         #
73         # Paramètres de pilotage
74         # ----------------------
75         self.setParameters(Parameters)
76         #
77         # Opérateur d'observation
78         # -----------------------
79         Hm = HO["Tangent"].asMatrix(Xb)
80         Hm = Hm.reshape(Y.size,Xb.size) # ADAO & check shape
81         Ha = HO["Adjoint"].asMatrix(Xb)
82         Ha = Ha.reshape(Xb.size,Y.size) # ADAO & check shape
83         #
84         # Utilisation éventuelle d'un vecteur H(Xb) précalculé
85         # ----------------------------------------------------
86         if HO["AppliedToX"] is not None and HO["AppliedToX"].has_key("HXb"):
87             HXb = HO["AppliedToX"]["HXb"]
88         else:
89             HXb = Hm * Xb
90         HXb = numpy.asmatrix(numpy.ravel( HXb )).T
91         #
92         # Précalcul des inversions de B et R
93         # ----------------------------------
94         BI = B.getI()
95         RI = R.getI()
96         #
97         # Calcul de l'innovation
98         # ----------------------
99         if Y.size != HXb.size:
100             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))
101         if max(Y.shape) != max(HXb.shape):
102             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))
103         d  = Y - HXb
104         #
105         # Calcul de la matrice de gain et de l'analyse
106         # --------------------------------------------
107         if Y.size <= Xb.size:
108             if Y.size > 100: # len(R)
109                 _A = R + Hm * B * Ha
110                 _u = numpy.linalg.solve( _A , d )
111                 Xa = Xb + B * Ha * _u
112             else:
113                 K  = B * Ha * (R + Hm * B * Ha).I
114                 Xa = Xb + K*d
115         else:
116             if Y.size > 100: # len(R)
117                 _A = BI + Ha * RI * Hm
118                 _u = numpy.linalg.solve( _A , Ha * RI * d )
119                 Xa = Xb + _u
120             else:
121                 K = (BI + Ha * RI * Hm).I * Ha * RI
122                 Xa = Xb + K*d
123         self.StoredVariables["Analysis"].store( Xa.A1 )
124         #
125         # Calcul de la fonction coût
126         # --------------------------
127         if self._parameters["StoreInternalVariables"] or \
128            "OMA" in self._parameters["StoreSupplementaryCalculations"] or \
129            "SigmaObs2" in self._parameters["StoreSupplementaryCalculations"] or \
130            "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"] or \
131            "SimulationQuantiles" in self._parameters["StoreSupplementaryCalculations"]:
132             HXa = Hm * Xa
133             oma = Y - HXa
134         if self._parameters["StoreInternalVariables"] or \
135            "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"]:
136             Jb  = 0.5 * (Xa - Xb).T * BI * (Xa - Xb)
137             Jo  = 0.5 * oma.T * RI * oma
138             J   = float( Jb ) + float( Jo )
139             self.StoredVariables["CostFunctionJb"].store( Jb )
140             self.StoredVariables["CostFunctionJo"].store( Jo )
141             self.StoredVariables["CostFunctionJ" ].store( J )
142         #
143         # Calcul de la covariance d'analyse
144         # ---------------------------------
145         if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"] or \
146            "SimulationQuantiles" in self._parameters["StoreSupplementaryCalculations"]:
147             A = B - K * Hm * B
148             if min(A.shape) != max(A.shape):
149                 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)))
150             if (numpy.diag(A) < 0).any():
151                 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,))
152             if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
153                 try:
154                     L = numpy.linalg.cholesky( A )
155                 except:
156                     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,))
157             self.StoredVariables["APosterioriCovariance"].store( A )
158         #
159         # Calculs et/ou stockages supplémentaires
160         # ---------------------------------------
161         if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
162             self.StoredVariables["Innovation"].store( numpy.ravel(d) )
163         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
164             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
165         if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
166             self.StoredVariables["OMA"].store( numpy.ravel(oma) )
167         if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
168             self.StoredVariables["OMB"].store( numpy.ravel(d) )
169         if "SigmaObs2" in self._parameters["StoreSupplementaryCalculations"]:
170             TraceR = R.trace(Y.size)
171             self.StoredVariables["SigmaObs2"].store( float( (d.T * (numpy.asmatrix(numpy.ravel(oma)).T)) ) / TraceR )
172         if "SigmaBck2" in self._parameters["StoreSupplementaryCalculations"]:
173             self.StoredVariables["SigmaBck2"].store( float( (d.T * Hm * (Xa - Xb))/(Hm * B * Hm.T).trace() ) )
174         if "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"]:
175             self.StoredVariables["MahalanobisConsistency"].store( float( 2.*J/d.size ) )
176         if "SimulationQuantiles" in self._parameters["StoreSupplementaryCalculations"]:
177             Qtls = self._parameters["Quantiles"]
178             nech = self._parameters["NumberOfSamplesForQuantiles"]
179             YfQ  = None
180             for i in range(nech):
181                 if self._parameters["SimulationForQuantiles"] == "Linear":
182                     dXr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A) - Xa.A1).T
183                     dYr = numpy.matrix(numpy.ravel( Hm * dXr )).T
184                     Yr = HXa + dYr
185                 elif self._parameters["SimulationForQuantiles"] == "NonLinear":
186                     Xr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A)).T
187                     Yr = numpy.matrix(numpy.ravel( Hm * Xr )).T
188                 if YfQ is None:
189                     YfQ = Yr
190                 else:
191                     YfQ = numpy.hstack((YfQ,Yr))
192             YfQ.sort(axis=-1)
193             YQ = None
194             for quantile in Qtls:
195                 if not (0. <= quantile <= 1.): continue
196                 indice = int(nech * quantile - 1./nech)
197                 if YQ is None: YQ = YfQ[:,indice]
198                 else:          YQ = numpy.hstack((YQ,YfQ[:,indice]))
199             self.StoredVariables["SimulationQuantiles"].store( YQ )
200         #
201         self._post_run(HO)
202         return 0
203
204 # ==============================================================================
205 if __name__ == "__main__":
206     print '\n AUTODIAGNOSTIC \n'