Salome HOME
Internal tests improvements and version update
[modules/adao.git] / src / daComposant / daAlgorithms / ExtendedBlue.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2017 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, "EXTENDEDBLUE")
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", "CostFunctionJb", "CostFunctionJo", "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         self.requireInputArguments(
72             mandatory= ("Xb", "Y", "HO", "R", "B" ),
73             )
74
75     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
76         self._pre_run(Parameters, Xb, Y, R, B, Q)
77         #
78         Hm = HO["Tangent"].asMatrix(Xb)
79         Hm = Hm.reshape(Y.size,Xb.size) # ADAO & check shape
80         Ha = HO["Adjoint"].asMatrix(Xb)
81         Ha = Ha.reshape(Xb.size,Y.size) # ADAO & check shape
82         H  = HO["Direct"].appliedTo
83         #
84         # Utilisation éventuelle d'un vecteur H(Xb) précalculé
85         # ----------------------------------------------------
86         if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
87             HXb = H( Xb, HO["AppliedInX"]["HXb"])
88         else:
89             HXb = H( 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             _A = R + Hm * B * Ha
109             _u = numpy.linalg.solve( _A , d )
110             Xa = Xb + B * Ha * _u
111         else:
112             _A = BI + Ha * RI * Hm
113             _u = numpy.linalg.solve( _A , Ha * RI * d )
114             Xa = Xb + _u
115         self.StoredVariables["Analysis"].store( Xa.A1 )
116         #
117         # Calcul de la fonction coût
118         # --------------------------
119         if self._parameters["StoreInternalVariables"] or \
120            "CostFunctionJ"                      in self._parameters["StoreSupplementaryCalculations"] or \
121            "OMA"                                in self._parameters["StoreSupplementaryCalculations"] or \
122            "SigmaObs2"                          in self._parameters["StoreSupplementaryCalculations"] or \
123            "MahalanobisConsistency"             in self._parameters["StoreSupplementaryCalculations"] or \
124            "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"] or \
125            "SimulatedObservationAtOptimum"      in self._parameters["StoreSupplementaryCalculations"] or \
126            "SimulationQuantiles"                in self._parameters["StoreSupplementaryCalculations"]:
127             HXa  = numpy.matrix(numpy.ravel( H( Xa ) )).T
128             oma = Y - HXa
129         if self._parameters["StoreInternalVariables"] or \
130            "CostFunctionJ"                 in self._parameters["StoreSupplementaryCalculations"] or \
131            "MahalanobisConsistency"        in self._parameters["StoreSupplementaryCalculations"]:
132             Jb  = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
133             Jo  = float( 0.5 * oma.T * RI * oma )
134             J   = Jb + Jo
135             self.StoredVariables["CostFunctionJb"].store( Jb )
136             self.StoredVariables["CostFunctionJo"].store( Jo )
137             self.StoredVariables["CostFunctionJ" ].store( J )
138         #
139         # Calcul de la covariance d'analyse
140         # ---------------------------------
141         if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"] or \
142            "SimulationQuantiles"   in self._parameters["StoreSupplementaryCalculations"]:
143             if   (Y.size <= Xb.size): K  = B * Ha * (R + Hm * B * Ha).I
144             elif (Y.size >  Xb.size): K = (BI + Ha * RI * Hm).I * Ha * RI
145             A = B - K * Hm * B
146             if min(A.shape) != max(A.shape):
147                 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)))
148             if (numpy.diag(A) < 0).any():
149                 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,))
150             if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
151                 try:
152                     L = numpy.linalg.cholesky( A )
153                 except:
154                     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,))
155             self.StoredVariables["APosterioriCovariance"].store( A )
156         #
157         # Calculs et/ou stockages supplémentaires
158         # ---------------------------------------
159         if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
160             self.StoredVariables["CurrentState"].store( numpy.ravel(Xa) )
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             nech = self._parameters["NumberOfSamplesForQuantiles"]
178             HtM  = HO["Tangent"].asMatrix(ValueForMethodForm = Xa)
179             HtM  = HtM.reshape(Y.size,Xa.size) # ADAO & check shape
180             YfQ  = None
181             for i in range(nech):
182                 if self._parameters["SimulationForQuantiles"] == "Linear":
183                     dXr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A) - Xa.A1).T
184                     dYr = numpy.matrix(numpy.ravel( HtM * dXr )).T
185                     Yr = HXa + dYr
186                 elif self._parameters["SimulationForQuantiles"] == "NonLinear":
187                     Xr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A)).T
188                     Yr = numpy.matrix(numpy.ravel( H( Xr ) )).T
189                 if YfQ is None:
190                     YfQ = Yr
191                 else:
192                     YfQ = numpy.hstack((YfQ,Yr))
193             YfQ.sort(axis=-1)
194             YQ = None
195             for quantile in self._parameters["Quantiles"]:
196                 if not (0. <= float(quantile) <= 1.): continue
197                 indice = int(nech * float(quantile) - 1./nech)
198                 if YQ is None: YQ = YfQ[:,indice]
199                 else:          YQ = numpy.hstack((YQ,YfQ[:,indice]))
200             self.StoredVariables["SimulationQuantiles"].store( YQ )
201         if "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
202             self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
203         if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
204             self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(HXa) )
205         if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
206             self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
207         #
208         self._post_run(HO)
209         return 0
210
211 # ==============================================================================
212 if __name__ == "__main__":
213     print('\n AUTODIAGNOSTIC \n')