Salome HOME
Various minor style correction
[modules/adao.git] / src / daComposant / daAlgorithms / Blue.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, "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  = [
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         #
103         # Utilisation éventuelle d'un vecteur H(Xb) précalculé
104         # ----------------------------------------------------
105         if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
106             HXb = HO["AppliedInX"]["HXb"]
107         else:
108             HXb = Hm * Xb
109         HXb = numpy.asmatrix(numpy.ravel( HXb )).T
110         if Y.size != HXb.size:
111             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))
112         if max(Y.shape) != max(HXb.shape):
113             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))
114         #
115         # Précalcul des inversions de B et R
116         # ----------------------------------
117         BI = B.getI()
118         RI = R.getI()
119         #
120         # Calcul de l'innovation
121         # ----------------------
122         d  = Y - HXb
123         #
124         # Calcul de la matrice de gain et de l'analyse
125         # --------------------------------------------
126         if Y.size <= Xb.size:
127             _A = R + Hm * B * Ha
128             _u = numpy.linalg.solve( _A , d )
129             Xa = Xb + B * Ha * _u
130         else:
131             _A = BI + Ha * RI * Hm
132             _u = numpy.linalg.solve( _A , Ha * RI * d )
133             Xa = Xb + _u
134         self.StoredVariables["Analysis"].store( Xa.A1 )
135         #
136         # Calcul de la fonction coût
137         # --------------------------
138         if self._parameters["StoreInternalVariables"] or \
139             self._toStore("CostFunctionJ") or \
140             self._toStore("OMA") or \
141             self._toStore("SigmaObs2") or \
142             self._toStore("MahalanobisConsistency") or \
143             self._toStore("SimulatedObservationAtCurrentState") or \
144             self._toStore("SimulatedObservationAtOptimum") or \
145             self._toStore("SimulationQuantiles"):
146             HXa = Hm * Xa
147             oma = Y - HXa
148         if self._parameters["StoreInternalVariables"] or \
149             self._toStore("CostFunctionJ") or \
150             self._toStore("MahalanobisConsistency"):
151             Jb  = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
152             Jo  = float( 0.5 * oma.T * RI * oma )
153             J   = Jb + Jo
154             self.StoredVariables["CostFunctionJb"].store( Jb )
155             self.StoredVariables["CostFunctionJo"].store( Jo )
156             self.StoredVariables["CostFunctionJ" ].store( J )
157         #
158         # Calcul de la covariance d'analyse
159         # ---------------------------------
160         if self._toStore("APosterioriCovariance") or \
161            self._toStore("SimulationQuantiles"):
162             if   (Y.size <= Xb.size): K  = B * Ha * (R + Hm * B * Ha).I
163             elif (Y.size >  Xb.size): K = (BI + Ha * RI * Hm).I * Ha * RI
164             A = B - K * Hm * B
165             if min(A.shape) != max(A.shape):
166                 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)))
167             if (numpy.diag(A) < 0).any():
168                 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,))
169             if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
170                 try:
171                     L = numpy.linalg.cholesky( A )
172                 except:
173                     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,))
174             self.StoredVariables["APosterioriCovariance"].store( A )
175         #
176         # Calculs et/ou stockages supplémentaires
177         # ---------------------------------------
178         if self._parameters["StoreInternalVariables"] or self._toStore("CurrentState"):
179             self.StoredVariables["CurrentState"].store( numpy.ravel(Xa) )
180         if self._toStore("Innovation"):
181             self.StoredVariables["Innovation"].store( numpy.ravel(d) )
182         if self._toStore("BMA"):
183             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
184         if self._toStore("OMA"):
185             self.StoredVariables["OMA"].store( numpy.ravel(oma) )
186         if self._toStore("OMB"):
187             self.StoredVariables["OMB"].store( numpy.ravel(d) )
188         if self._toStore("SigmaObs2"):
189             TraceR = R.trace(Y.size)
190             self.StoredVariables["SigmaObs2"].store( float( (d.T * (numpy.asmatrix(numpy.ravel(oma)).T)) ) / TraceR )
191         if self._toStore("SigmaBck2"):
192             self.StoredVariables["SigmaBck2"].store( float( (d.T * Hm * (Xa - Xb))/(Hm * B * Hm.T).trace() ) )
193         if self._toStore("MahalanobisConsistency"):
194             self.StoredVariables["MahalanobisConsistency"].store( float( 2.*J/d.size ) )
195         if self._toStore("SimulationQuantiles"):
196             nech = self._parameters["NumberOfSamplesForQuantiles"]
197             YfQ  = None
198             for i in range(nech):
199                 if self._parameters["SimulationForQuantiles"] == "Linear":
200                     dXr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A) - Xa.A1).T
201                     dYr = numpy.matrix(numpy.ravel( Hm * dXr )).T
202                     Yr = HXa + dYr
203                 elif self._parameters["SimulationForQuantiles"] == "NonLinear":
204                     Xr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A)).T
205                     Yr = numpy.matrix(numpy.ravel( Hm * Xr )).T
206                 if YfQ is None:
207                     YfQ = Yr
208                 else:
209                     YfQ = numpy.hstack((YfQ,Yr))
210             YfQ.sort(axis=-1)
211             YQ = None
212             for quantile in self._parameters["Quantiles"]:
213                 if not (0. <= float(quantile) <= 1.): continue
214                 indice = int(nech * float(quantile) - 1./nech)
215                 if YQ is None: YQ = YfQ[:,indice]
216                 else:          YQ = numpy.hstack((YQ,YfQ[:,indice]))
217             self.StoredVariables["SimulationQuantiles"].store( YQ )
218         if self._toStore("SimulatedObservationAtBackground"):
219             self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
220         if self._toStore("SimulatedObservationAtCurrentState"):
221             self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(HXa) )
222         if self._toStore("SimulatedObservationAtOptimum"):
223             self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
224         #
225         self._post_run(HO)
226         return 0
227
228 # ==============================================================================
229 if __name__ == "__main__":
230     print('\n AUTODIAGNOSTIC \n')