Salome HOME
Code and documentation update
[modules/adao.git] / src / daComposant / daAlgorithms / Atoms / van3dvar.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2022 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 __doc__ = """
24     3DVAR variational analysis with no inversion of B
25 """
26 __author__ = "Jean-Philippe ARGAUD"
27
28 import numpy, scipy, scipy.optimize, scipy.version
29 from daCore.NumericObjects import HessienneEstimation, QuantilesEstimations
30 from daCore.NumericObjects import RecentredBounds
31 from daCore.PlatformInfo import PlatformInfo
32 mpr = PlatformInfo().MachinePrecision()
33
34 # ==============================================================================
35 def van3dvar(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False):
36     """
37     Correction
38     """
39     #
40     # Initialisations
41     # ---------------
42     Hm = HO["Direct"].appliedTo
43     Ha = HO["Adjoint"].appliedInXTo
44     #
45     if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
46         HXb = numpy.asarray(Hm( Xb, HO["AppliedInX"]["HXb"] ))
47     else:
48         HXb = numpy.asarray(Hm( Xb ))
49     HXb = HXb.reshape((-1,1))
50     if Y.size != HXb.size:
51         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))
52     if max(Y.shape) != max(HXb.shape):
53         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))
54     #
55     if selfA._toStore("JacobianMatrixAtBackground"):
56         HtMb = HO["Tangent"].asMatrix(ValueForMethodForm = Xb)
57         HtMb = HtMb.reshape(Y.size,Xb.size) # ADAO & check shape
58         selfA.StoredVariables["JacobianMatrixAtBackground"].store( HtMb )
59     #
60     BT = B.getT()
61     RI = R.getI()
62     if ("Bounds" in selfA._parameters) and selfA._parameters["Bounds"] is not None:
63         BI = B.getI()
64     else:
65         BI = None
66     #
67     Xini = numpy.zeros(Xb.size)
68     #
69     # Définition de la fonction-coût
70     # ------------------------------
71     def CostFunction(v):
72         _V = numpy.asarray(v).reshape((-1,1))
73         _X = Xb + (B @ _V).reshape((-1,1))
74         if selfA._parameters["StoreInternalVariables"] or \
75             selfA._toStore("CurrentState") or \
76             selfA._toStore("CurrentOptimum"):
77             selfA.StoredVariables["CurrentState"].store( _X )
78         _HX = numpy.asarray(Hm( _X )).reshape((-1,1))
79         _Innovation = Y - _HX
80         if selfA._toStore("SimulatedObservationAtCurrentState") or \
81             selfA._toStore("SimulatedObservationAtCurrentOptimum"):
82             selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
83         if selfA._toStore("InnovationAtCurrentState"):
84             selfA.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
85         #
86         Jb  = float( 0.5 * _V.T * (BT * _V) )
87         Jo  = float( 0.5 * _Innovation.T * (RI * _Innovation) )
88         J   = Jb + Jo
89         #
90         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["CostFunctionJ"]) )
91         selfA.StoredVariables["CostFunctionJb"].store( Jb )
92         selfA.StoredVariables["CostFunctionJo"].store( Jo )
93         selfA.StoredVariables["CostFunctionJ" ].store( J )
94         if selfA._toStore("IndexOfOptimum") or \
95             selfA._toStore("CurrentOptimum") or \
96             selfA._toStore("CostFunctionJAtCurrentOptimum") or \
97             selfA._toStore("CostFunctionJbAtCurrentOptimum") or \
98             selfA._toStore("CostFunctionJoAtCurrentOptimum") or \
99             selfA._toStore("SimulatedObservationAtCurrentOptimum"):
100             IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
101         if selfA._toStore("IndexOfOptimum"):
102             selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
103         if selfA._toStore("CurrentOptimum"):
104             selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["CurrentState"][IndexMin] )
105         if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
106             selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] )
107         if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
108             selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
109         if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
110             selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
111         if selfA._toStore("CostFunctionJAtCurrentOptimum"):
112             selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
113         return J
114     #
115     def GradientOfCostFunction(v):
116         _V = numpy.asarray(v).reshape((-1,1))
117         _X = Xb + (B @ _V).reshape((-1,1))
118         _HX     = numpy.asarray(Hm( _X )).reshape((-1,1))
119         GradJb  = BT * _V
120         GradJo  = - BT * Ha( (_X, RI * (Y - _HX)) )
121         GradJ   = numpy.ravel( GradJb ) + numpy.ravel( GradJo )
122         return GradJ
123     #
124     # Minimisation de la fonctionnelle
125     # --------------------------------
126     nbPreviousSteps = selfA.StoredVariables["CostFunctionJ"].stepnumber()
127     #
128     if selfA._parameters["Minimizer"] == "LBFGSB":
129         if "0.19" <= scipy.version.version <= "1.4.99":
130             import daAlgorithms.Atoms.lbfgsb14hlt as optimiseur
131         elif "1.5.0" <= scipy.version.version <= "1.7.99":
132             import daAlgorithms.Atoms.lbfgsb17hlt as optimiseur
133         elif "1.8.0" <= scipy.version.version <= "1.8.99":
134             import daAlgorithms.Atoms.lbfgsb18hlt as optimiseur
135         elif "1.9.0" <= scipy.version.version <= "1.9.99":
136             import daAlgorithms.Atoms.lbfgsb19hlt as optimiseur
137         else:
138             import scipy.optimize as optimiseur
139         Minimum, J_optimal, Informations = optimiseur.fmin_l_bfgs_b(
140             func        = CostFunction,
141             x0          = Xini,
142             fprime      = GradientOfCostFunction,
143             args        = (),
144             bounds      = RecentredBounds(selfA._parameters["Bounds"], Xb, BI),
145             maxfun      = selfA._parameters["MaximumNumberOfIterations"]-1,
146             factr       = selfA._parameters["CostDecrementTolerance"]*1.e14,
147             pgtol       = selfA._parameters["ProjectedGradientTolerance"],
148             iprint      = selfA._parameters["optiprint"],
149             )
150         # nfeval = Informations['funcalls']
151         # rc     = Informations['warnflag']
152     elif selfA._parameters["Minimizer"] == "TNC":
153         Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
154             func        = CostFunction,
155             x0          = Xini,
156             fprime      = GradientOfCostFunction,
157             args        = (),
158             bounds      = RecentredBounds(selfA._parameters["Bounds"], Xb, BI),
159             maxfun      = selfA._parameters["MaximumNumberOfIterations"],
160             pgtol       = selfA._parameters["ProjectedGradientTolerance"],
161             ftol        = selfA._parameters["CostDecrementTolerance"],
162             messages    = selfA._parameters["optmessages"],
163             )
164     elif selfA._parameters["Minimizer"] == "CG":
165         Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
166             f           = CostFunction,
167             x0          = Xini,
168             fprime      = GradientOfCostFunction,
169             args        = (),
170             maxiter     = selfA._parameters["MaximumNumberOfIterations"],
171             gtol        = selfA._parameters["GradientNormTolerance"],
172             disp        = selfA._parameters["optdisp"],
173             full_output = True,
174             )
175     elif selfA._parameters["Minimizer"] == "NCG":
176         Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
177             f           = CostFunction,
178             x0          = Xini,
179             fprime      = GradientOfCostFunction,
180             args        = (),
181             maxiter     = selfA._parameters["MaximumNumberOfIterations"],
182             avextol     = selfA._parameters["CostDecrementTolerance"],
183             disp        = selfA._parameters["optdisp"],
184             full_output = True,
185             )
186     elif selfA._parameters["Minimizer"] == "BFGS":
187         Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
188             f           = CostFunction,
189             x0          = Xini,
190             fprime      = GradientOfCostFunction,
191             args        = (),
192             maxiter     = selfA._parameters["MaximumNumberOfIterations"],
193             gtol        = selfA._parameters["GradientNormTolerance"],
194             disp        = selfA._parameters["optdisp"],
195             full_output = True,
196             )
197     else:
198         raise ValueError("Error in minimizer name: %s is unkown"%selfA._parameters["Minimizer"])
199     #
200     IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
201     MinJ     = selfA.StoredVariables["CostFunctionJ"][IndexMin]
202     #
203     # Correction pour pallier a un bug de TNC sur le retour du Minimum
204     # ----------------------------------------------------------------
205     if selfA._parameters["StoreInternalVariables"] or selfA._toStore("CurrentState"):
206         Minimum = selfA.StoredVariables["CurrentState"][IndexMin]
207     else:
208         Minimum = Xb + B * Minimum.reshape((-1,1)) # Pas @
209     #
210     Xa = Minimum
211     if __storeState: selfA._setInternalState("Xn", Xa)
212     #--------------------------
213     #
214     selfA.StoredVariables["Analysis"].store( Xa )
215     #
216     if selfA._toStore("OMA") or \
217         selfA._toStore("InnovationAtCurrentAnalysis") or \
218         selfA._toStore("SigmaObs2") or \
219         selfA._toStore("SimulationQuantiles") or \
220         selfA._toStore("SimulatedObservationAtOptimum"):
221         if selfA._toStore("SimulatedObservationAtCurrentState"):
222             HXa = selfA.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
223         elif selfA._toStore("SimulatedObservationAtCurrentOptimum"):
224             HXa = selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
225         else:
226             HXa = Hm( Xa )
227         oma = Y - HXa.reshape((-1,1))
228     #
229     if selfA._toStore("APosterioriCovariance") or \
230         selfA._toStore("SimulationQuantiles") or \
231         selfA._toStore("JacobianMatrixAtOptimum") or \
232         selfA._toStore("KalmanGainAtOptimum"):
233         HtM = HO["Tangent"].asMatrix(ValueForMethodForm = Xa)
234         HtM = HtM.reshape(Y.size,Xa.size) # ADAO & check shape
235     if selfA._toStore("APosterioriCovariance") or \
236         selfA._toStore("SimulationQuantiles") or \
237         selfA._toStore("KalmanGainAtOptimum"):
238         HaM = HO["Adjoint"].asMatrix(ValueForMethodForm = Xa)
239         HaM = HaM.reshape(Xa.size,Y.size) # ADAO & check shape
240     if selfA._toStore("APosterioriCovariance") or \
241         selfA._toStore("SimulationQuantiles"):
242         BI = B.getI()
243         A = HessienneEstimation(selfA, Xa.size, HaM, HtM, BI, RI)
244     if selfA._toStore("APosterioriCovariance"):
245         selfA.StoredVariables["APosterioriCovariance"].store( A )
246     if selfA._toStore("JacobianMatrixAtOptimum"):
247         selfA.StoredVariables["JacobianMatrixAtOptimum"].store( HtM )
248     if selfA._toStore("KalmanGainAtOptimum"):
249         if   (Y.size <= Xb.size): KG  = B * HaM * (R + numpy.dot(HtM, B * HaM)).I
250         elif (Y.size >  Xb.size): KG = (BI + numpy.dot(HaM, RI * HtM)).I * HaM * RI
251         selfA.StoredVariables["KalmanGainAtOptimum"].store( KG )
252     #
253     # Calculs et/ou stockages supplémentaires
254     # ---------------------------------------
255     if selfA._toStore("Innovation") or \
256         selfA._toStore("SigmaObs2") or \
257         selfA._toStore("MahalanobisConsistency") or \
258         selfA._toStore("OMB"):
259         Innovation  = Y - HXb
260     if selfA._toStore("Innovation"):
261         selfA.StoredVariables["Innovation"].store( Innovation )
262     if selfA._toStore("BMA"):
263         selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
264     if selfA._toStore("OMA"):
265         selfA.StoredVariables["OMA"].store( oma )
266     if selfA._toStore("InnovationAtCurrentAnalysis"):
267         selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( oma )
268     if selfA._toStore("OMB"):
269         selfA.StoredVariables["OMB"].store( Innovation )
270     if selfA._toStore("SigmaObs2"):
271         TraceR = R.trace(Y.size)
272         selfA.StoredVariables["SigmaObs2"].store( float( (Innovation.T @ oma) ) / TraceR )
273     if selfA._toStore("MahalanobisConsistency"):
274         selfA.StoredVariables["MahalanobisConsistency"].store( float( 2.*MinJ/Innovation.size ) )
275     if selfA._toStore("SimulationQuantiles"):
276         QuantilesEstimations(selfA, A, Xa, HXa, Hm, HtM)
277     if selfA._toStore("SimulatedObservationAtBackground"):
278         selfA.StoredVariables["SimulatedObservationAtBackground"].store( HXb )
279     if selfA._toStore("SimulatedObservationAtOptimum"):
280         selfA.StoredVariables["SimulatedObservationAtOptimum"].store( HXa )
281     #
282     return 0
283
284 # ==============================================================================
285 if __name__ == "__main__":
286     print('\n AUTODIAGNOSTIC\n')