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