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