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