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