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