Salome HOME
Minor improvements for internal variables
[modules/adao.git] / src / daComposant / daAlgorithms / EnsembleBlue.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
25 import numpy
26
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
29     def __init__(self):
30         BasicObjects.Algorithm.__init__(self, "ENSEMBLEBLUE")
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                 "CurrentState",
45                 "Innovation",
46                 "SimulatedObservationAtBackground",
47                 "SimulatedObservationAtCurrentState",
48                 "SimulatedObservationAtOptimum",
49                 ]
50             )
51         self.defineRequiredParameter(
52             name     = "SetSeed",
53             typecast = numpy.random.seed,
54             message  = "Graine fixée pour le générateur aléatoire",
55             )
56         self.requireInputArguments(
57             mandatory= ("Xb", "Y", "HO", "R", "B"),
58             )
59         self.setAttributes(tags=(
60             "DataAssimilation",
61             "NonLinear",
62             "Filter",
63             "Ensemble",
64             ))
65
66     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
67         self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
68         #
69         # Précalcul des inversions de B et R
70         # ----------------------------------
71         BI = B.getI()
72         RI = R.getI()
73         #
74         # Nombre d'ensemble pour l'ébauche
75         # --------------------------------
76         nb_ens = Xb.stepnumber()
77         #
78         # Construction de l'ensemble des observations, par génération a partir
79         # de la diagonale de R
80         # --------------------------------------------------------------------
81         DiagonaleR = R.diag(Y.size)
82         EnsembleY = numpy.zeros([Y.size,nb_ens])
83         for npar in range(DiagonaleR.size):
84             bruit = numpy.random.normal(0,DiagonaleR[npar],nb_ens)
85             EnsembleY[npar,:] = Y[npar] + bruit
86         #
87         # Initialisation des opérateurs d'observation et de la matrice gain
88         # -----------------------------------------------------------------
89         Hm = HO["Tangent"].asMatrix(None)
90         Hm = Hm.reshape(Y.size,Xb[0].size) # ADAO & check shape
91         Ha = HO["Adjoint"].asMatrix(None)
92         Ha = Ha.reshape(Xb[0].size,Y.size) # ADAO & check shape
93         #
94         # Calcul de la matrice de gain dans l'espace le plus petit et de l'analyse
95         # ------------------------------------------------------------------------
96         if Y.size <= Xb[0].size:
97             K  = B * Ha * (R + Hm * B * Ha).I
98         else:
99             K = (BI + Ha * RI * Hm).I * Ha * RI
100         #
101         # Calcul du BLUE pour chaque membre de l'ensemble
102         # -----------------------------------------------
103         for iens in range(nb_ens):
104             HXb = numpy.ravel(numpy.dot(Hm, Xb[iens]))
105             if self._toStore("SimulatedObservationAtBackground"):
106                 self.StoredVariables["SimulatedObservationAtBackground"].store( HXb )
107             d  = numpy.ravel(EnsembleY[:,iens]) - HXb
108             if self._toStore("Innovation"):
109                 self.StoredVariables["Innovation"].store( d )
110             Xa = numpy.ravel(Xb[iens]) + numpy.dot(K, d)
111             self.StoredVariables["CurrentState"].store( Xa )
112             if self._toStore("SimulatedObservationAtCurrentState"):
113                 self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.dot(Hm, Xa) )
114         #
115         # Fabrication de l'analyse
116         # ------------------------
117         Members = self.StoredVariables["CurrentState"][-nb_ens:]
118         Xa = numpy.array( Members ).mean(axis=0)
119         self.StoredVariables["Analysis"].store( Xa )
120         if self._toStore("SimulatedObservationAtOptimum"):
121             self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.dot(Hm, Xa) )
122         #
123         self._post_run(HO)
124         return 0
125
126 # ==============================================================================
127 if __name__ == "__main__":
128     print('\n AUTODIAGNOSTIC\n')