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