Salome HOME
Updating copyright date information
[modules/adao.git] / src / daComposant / daAlgorithms / Blue.py
1 #-*-coding:iso-8859-1-*-
2 #
3 # Copyright (C) 2008-2016 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  = ["APosterioriCorrelations", "APosterioriCovariance", "APosterioriStandardDeviations", "APosterioriVariances", "BMA", "OMA", "OMB", "CurrentState", "CostFunctionJ", "Innovation", "SigmaBck2", "SigmaObs2", "MahalanobisConsistency", "SimulationQuantiles", "SimulatedObservationAtBackground", "SimulatedObservationAtCurrentState", "SimulatedObservationAtOptimum"]
43             )
44         self.defineRequiredParameter(
45             name     = "Quantiles",
46             default  = [],
47             typecast = tuple,
48             message  = "Liste des valeurs de quantiles",
49             minval   = 0.,
50             maxval   = 1.,
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         self._pre_run()
74         #
75         # Paramètres de pilotage
76         # ----------------------
77         self.setParameters(Parameters)
78         #
79         # Opérateurs
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é (sans cout)
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         if Y.size != HXb.size:
94             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))
95         if max(Y.shape) != max(HXb.shape):
96             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))
97         #
98         # Précalcul des inversions de B et R
99         # ----------------------------------
100         BI = B.getI()
101         RI = R.getI()
102         #
103         # Calcul de l'innovation
104         # ----------------------
105         d  = Y - HXb
106         #
107         # Calcul de la matrice de gain et de l'analyse
108         # --------------------------------------------
109         if Y.size <= Xb.size:
110             _A = R + Hm * B * Ha
111             _u = numpy.linalg.solve( _A , d )
112             Xa = Xb + B * Ha * _u
113         else:
114             _A = BI + Ha * RI * Hm
115             _u = numpy.linalg.solve( _A , Ha * RI * d )
116             Xa = Xb + _u
117         self.StoredVariables["Analysis"].store( Xa.A1 )
118         #
119         # Calcul de la fonction coût
120         # --------------------------
121         if self._parameters["StoreInternalVariables"] or \
122            "CostFunctionJ"                      in self._parameters["StoreSupplementaryCalculations"] or \
123            "OMA"                                in self._parameters["StoreSupplementaryCalculations"] or \
124            "SigmaObs2"                          in self._parameters["StoreSupplementaryCalculations"] or \
125            "MahalanobisConsistency"             in self._parameters["StoreSupplementaryCalculations"] or \
126            "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"] or \
127            "SimulatedObservationAtOptimum"      in self._parameters["StoreSupplementaryCalculations"] or \
128            "SimulationQuantiles"                in self._parameters["StoreSupplementaryCalculations"]:
129             HXa = Hm * Xa
130             oma = Y - HXa
131         if self._parameters["StoreInternalVariables"] or \
132            "CostFunctionJ"                 in self._parameters["StoreSupplementaryCalculations"] or \
133            "MahalanobisConsistency"        in self._parameters["StoreSupplementaryCalculations"]:
134             #
135             Jb  = 0.5 * (Xa - Xb).T * BI * (Xa - Xb)
136             Jo  = 0.5 * oma.T * RI * oma
137             J   = float( Jb ) + float( Jo )
138             #
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             if   (Y.size <= Xb.size): K  = B * Ha * (R + Hm * B * Ha).I
148             elif (Y.size >  Xb.size): K = (BI + Ha * RI * Hm).I * Ha * RI
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 self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
164             self.StoredVariables["CurrentState"].store( numpy.ravel(Xa) )
165         if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
166             self.StoredVariables["Innovation"].store( numpy.ravel(d) )
167         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
168             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
169         if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
170             self.StoredVariables["OMA"].store( numpy.ravel(oma) )
171         if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
172             self.StoredVariables["OMB"].store( numpy.ravel(d) )
173         if "SigmaObs2" in self._parameters["StoreSupplementaryCalculations"]:
174             TraceR = R.trace(Y.size)
175             self.StoredVariables["SigmaObs2"].store( float( (d.T * (numpy.asmatrix(numpy.ravel(oma)).T)) ) / TraceR )
176         if "SigmaBck2" in self._parameters["StoreSupplementaryCalculations"]:
177             self.StoredVariables["SigmaBck2"].store( float( (d.T * Hm * (Xa - Xb))/(Hm * B * Hm.T).trace() ) )
178         if "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"]:
179             self.StoredVariables["MahalanobisConsistency"].store( float( 2.*J/d.size ) )
180         if "SimulationQuantiles" in self._parameters["StoreSupplementaryCalculations"]:
181             Qtls = map(float, self._parameters["Quantiles"])
182             nech = self._parameters["NumberOfSamplesForQuantiles"]
183             YfQ  = None
184             for i in range(nech):
185                 if self._parameters["SimulationForQuantiles"] == "Linear":
186                     dXr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A) - Xa.A1).T
187                     dYr = numpy.matrix(numpy.ravel( Hm * dXr )).T
188                     Yr = HXa + dYr
189                 elif self._parameters["SimulationForQuantiles"] == "NonLinear":
190                     Xr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A)).T
191                     Yr = numpy.matrix(numpy.ravel( Hm * Xr )).T
192                 if YfQ is None:
193                     YfQ = Yr
194                 else:
195                     YfQ = numpy.hstack((YfQ,Yr))
196             YfQ.sort(axis=-1)
197             YQ = None
198             for quantile in Qtls:
199                 if not (0. <= quantile <= 1.): continue
200                 indice = int(nech * quantile - 1./nech)
201                 if YQ is None: YQ = YfQ[:,indice]
202                 else:          YQ = numpy.hstack((YQ,YfQ[:,indice]))
203             self.StoredVariables["SimulationQuantiles"].store( YQ )
204         if "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
205             self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
206         if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
207             self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(HXa) )
208         if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
209             self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
210         #
211         self._post_run(HO)
212         return 0
213
214 # ==============================================================================
215 if __name__ == "__main__":
216     print '\n AUTODIAGNOSTIC \n'