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