Salome HOME
Minor documentation and source update for compatibilities
[modules/adao.git] / src / daComposant / daAlgorithms / Atoms / psas3dvar.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 PSAS
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 psas3dvar(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False):
34     """
35     Correction
36     """
37     #
38     # Initialisations
39     # ---------------
40     Hm = HO["Direct"].appliedTo
41     #
42     if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
43         HXb = numpy.asarray(Hm( Xb, HO["AppliedInX"]["HXb"] ))
44     else:
45         HXb = numpy.asarray(Hm( Xb ))
46     HXb = HXb.reshape((-1, 1))
47     if Y.size != HXb.size:
48         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
49     if max(Y.shape) != max(HXb.shape):
50         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
51     #
52     Ht = HO["Tangent"].asMatrix(Xb)
53     Ht = Ht.reshape(Y.size, Xb.size)  # ADAO & check shape
54     BHT = B * Ht.T
55     HBHTpR = R + Ht * BHT
56     Innovation = Y - HXb
57     #
58     if selfA._toStore("JacobianMatrixAtBackground"):
59         selfA.StoredVariables["JacobianMatrixAtBackground"].store( Ht )
60     #
61     Xini = numpy.zeros(Y.size)
62     #
63     # Définition de la fonction-coût
64     # ------------------------------
65
66     def CostFunction(w):
67         _W = numpy.asarray(w).reshape((-1, 1))
68         if selfA._parameters["StoreInternalVariables"] or \
69                 selfA._toStore("CurrentState") or \
70                 selfA._toStore("CurrentOptimum"):
71             selfA.StoredVariables["CurrentState"].store( Xb + BHT @ _W )
72         if selfA._toStore("SimulatedObservationAtCurrentState") or \
73                 selfA._toStore("SimulatedObservationAtCurrentOptimum"):
74             selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( Hm( Xb + BHT @ _W ) )
75         if selfA._toStore("InnovationAtCurrentState"):
76             selfA.StoredVariables["InnovationAtCurrentState"].store( Innovation )
77         #
78         Jb  = vfloat( 0.5 * _W.T @ (HBHTpR @ _W) )
79         Jo  = vfloat( - _W.T @ Innovation )
80         J   = Jb + Jo
81         #
82         selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["CostFunctionJ"]) )
83         selfA.StoredVariables["CostFunctionJb"].store( Jb )
84         selfA.StoredVariables["CostFunctionJo"].store( Jo )
85         selfA.StoredVariables["CostFunctionJ" ].store( J )
86         if selfA._toStore("IndexOfOptimum") or \
87                 selfA._toStore("CurrentOptimum") or \
88                 selfA._toStore("CostFunctionJAtCurrentOptimum") or \
89                 selfA._toStore("CostFunctionJbAtCurrentOptimum") or \
90                 selfA._toStore("CostFunctionJoAtCurrentOptimum") or \
91                 selfA._toStore("SimulatedObservationAtCurrentOptimum"):
92             IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
93         if selfA._toStore("IndexOfOptimum"):
94             selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
95         if selfA._toStore("CurrentOptimum"):
96             selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["CurrentState"][IndexMin] )
97         if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
98             selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] )  # noqa: E501
99         if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
100             selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )  # noqa: E501
101         if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
102             selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )  # noqa: E501
103         if selfA._toStore("CostFunctionJAtCurrentOptimum"):
104             selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )  # noqa: E501
105         return J
106
107     def GradientOfCostFunction(w):
108         _W = numpy.asarray(w).reshape((-1, 1))
109         GradJb  = HBHTpR @ _W
110         GradJo  = - Innovation
111         GradJ   = numpy.ravel( GradJb ) + numpy.ravel( GradJo )
112         return GradJ
113     #
114     # Minimisation de la fonctionnelle
115     # --------------------------------
116     nbPreviousSteps = selfA.StoredVariables["CostFunctionJ"].stepnumber()
117     #
118     if selfA._parameters["Minimizer"] == "LBFGSB":
119         if vt("0.19")  <= vt(scipy.version.version) <= vt("1.4.99"):
120             import daAlgorithms.Atoms.lbfgsb14hlt as optimiseur
121         elif vt("1.5.0") <= vt(scipy.version.version) <= vt("1.7.99"):
122             import daAlgorithms.Atoms.lbfgsb17hlt as optimiseur
123         elif vt("1.8.0") <= vt(scipy.version.version) <= vt("1.8.99"):
124             import daAlgorithms.Atoms.lbfgsb18hlt as optimiseur
125         elif vt("1.9.0") <= vt(scipy.version.version) <= vt("1.10.99"):
126             import daAlgorithms.Atoms.lbfgsb19hlt as optimiseur
127         elif vt("1.11.0") <= vt(scipy.version.version) <= vt("1.11.99"):
128             import daAlgorithms.Atoms.lbfgsb111hlt as optimiseur
129         elif vt("1.12.0") <= vt(scipy.version.version) <= vt("1.12.99"):
130             import daAlgorithms.Atoms.lbfgsb112hlt as optimiseur
131         elif vt("1.13.0") <= vt(scipy.version.version) <= vt("1.13.99"):
132             import daAlgorithms.Atoms.lbfgsb113hlt as optimiseur
133         elif vt("1.14.0") <= vt(scipy.version.version) <= vt("1.14.99"):
134             import daAlgorithms.Atoms.lbfgsb114hlt as optimiseur
135         else:
136             import scipy.optimize as optimiseur
137         Minimum, J_optimal, Informations = optimiseur.fmin_l_bfgs_b(
138             func        = CostFunction,
139             x0          = Xini,
140             fprime      = GradientOfCostFunction,
141             args        = (),
142             maxfun      = selfA._parameters["MaximumNumberOfIterations"] - 1,
143             factr       = selfA._parameters["CostDecrementTolerance"] * 1.e14,
144             pgtol       = selfA._parameters["ProjectedGradientTolerance"],
145             iprint      = selfA._parameters["optiprint"],
146         )
147         # nfeval = Informations['funcalls']
148         # rc     = Informations['warnflag']
149     elif selfA._parameters["Minimizer"] == "TNC":
150         Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
151             func        = CostFunction,
152             x0          = Xini,
153             fprime      = GradientOfCostFunction,
154             args        = (),
155             maxfun      = selfA._parameters["MaximumNumberOfIterations"],
156             pgtol       = selfA._parameters["ProjectedGradientTolerance"],
157             ftol        = selfA._parameters["CostDecrementTolerance"],
158             messages    = selfA._parameters["optmessages"],
159         )
160     elif selfA._parameters["Minimizer"] == "CG":
161         Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
162             f           = CostFunction,
163             x0          = Xini,
164             fprime      = GradientOfCostFunction,
165             args        = (),
166             maxiter     = selfA._parameters["MaximumNumberOfIterations"],
167             gtol        = selfA._parameters["GradientNormTolerance"],
168             disp        = selfA._parameters["optdisp"],
169             full_output = True,
170         )
171     elif selfA._parameters["Minimizer"] == "NCG":
172         Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
173             f           = CostFunction,
174             x0          = Xini,
175             fprime      = GradientOfCostFunction,
176             args        = (),
177             maxiter     = selfA._parameters["MaximumNumberOfIterations"],
178             avextol     = selfA._parameters["CostDecrementTolerance"],
179             disp        = selfA._parameters["optdisp"],
180             full_output = True,
181         )
182     elif selfA._parameters["Minimizer"] == "BFGS":
183         Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
184             f           = CostFunction,
185             x0          = Xini,
186             fprime      = GradientOfCostFunction,
187             args        = (),
188             maxiter     = selfA._parameters["MaximumNumberOfIterations"],
189             gtol        = selfA._parameters["GradientNormTolerance"],
190             disp        = selfA._parameters["optdisp"],
191             full_output = True,
192         )
193     else:
194         raise ValueError("Error in minimizer name: %s is unkown"%selfA._parameters["Minimizer"])
195     #
196     IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
197     MinJ     = selfA.StoredVariables["CostFunctionJ"][IndexMin]
198     #
199     # Correction pour pallier a un bug de TNC sur le retour du Minimum
200     # ----------------------------------------------------------------
201     if selfA._parameters["StoreInternalVariables"] or selfA._toStore("CurrentState"):
202         Minimum = selfA.StoredVariables["CurrentState"][IndexMin]
203     else:
204         Minimum = Xb + BHT @ Minimum.reshape((-1, 1))
205     #
206     Xa = Minimum
207     if __storeState:
208         selfA._setInternalState("Xn", Xa)
209     # --------------------------
210     #
211     selfA.StoredVariables["Analysis"].store( Xa )
212     #
213     if selfA._toStore("OMA") or \
214             selfA._toStore("InnovationAtCurrentAnalysis") or \
215             selfA._toStore("SigmaObs2") or \
216             selfA._toStore("SimulationQuantiles") or \
217             selfA._toStore("SimulatedObservationAtOptimum"):
218         if selfA._toStore("SimulatedObservationAtCurrentState"):
219             HXa = selfA.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
220         elif selfA._toStore("SimulatedObservationAtCurrentOptimum"):
221             HXa = selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
222         else:
223             HXa = Hm( Xa )
224         oma = Y - numpy.asarray(HXa).reshape((-1, 1))
225     #
226     if selfA._toStore("APosterioriCovariance") or \
227             selfA._toStore("SimulationQuantiles") or \
228             selfA._toStore("JacobianMatrixAtOptimum") or \
229             selfA._toStore("KalmanGainAtOptimum"):
230         HtM = HO["Tangent"].asMatrix(ValueForMethodForm = Xa)
231         HtM = HtM.reshape(Y.size, Xa.size)  # ADAO & check shape
232     if selfA._toStore("APosterioriCovariance") or \
233             selfA._toStore("SimulationQuantiles") or \
234             selfA._toStore("KalmanGainAtOptimum"):
235         HaM = HO["Adjoint"].asMatrix(ValueForMethodForm = Xa)
236         HaM = HaM.reshape(Xa.size, Y.size)  # ADAO & check shape
237     if selfA._toStore("APosterioriCovariance") or \
238             selfA._toStore("SimulationQuantiles"):
239         BI = B.getI()
240         RI = R.getI()
241         A = HessienneEstimation(selfA, Xa.size, HaM, HtM, BI, RI)
242     if selfA._toStore("APosterioriCovariance"):
243         selfA.StoredVariables["APosterioriCovariance"].store( A )
244     if selfA._toStore("JacobianMatrixAtOptimum"):
245         selfA.StoredVariables["JacobianMatrixAtOptimum"].store( HtM )
246     if selfA._toStore("KalmanGainAtOptimum"):
247         if (Y.size <= Xb.size):
248             KG  = B * HaM * (R + numpy.dot(HtM, B * HaM)).I
249         elif (Y.size > Xb.size):
250             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( vfloat( (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')