1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2024 EDF R&D
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.
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.
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
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
24 3DVAR variational analysis with no inversion of B
26 __author__ = "Jean-Philippe ARGAUD"
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, vt, vfloat
32 mpr = PlatformInfo().MachinePrecision()
34 # ==============================================================================
35 def van3dvar(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False):
42 Hm = HO["Direct"].appliedTo
43 Ha = HO["Adjoint"].appliedInXTo
45 if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
46 HXb = numpy.asarray(Hm( Xb, HO["AppliedInX"]["HXb"] ))
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)) # noqa: E501
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)) # noqa: E501
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 )
62 if ("Bounds" in selfA._parameters) and selfA._parameters["Bounds"] is not None:
67 Xini = numpy.zeros(Xb.size)
69 # Définition de la fonction-coût
70 # ------------------------------
73 _V = numpy.asarray(v).reshape((-1, 1))
74 _X = Xb + (B @ _V).reshape((-1, 1))
75 if selfA._parameters["StoreInternalVariables"] or \
76 selfA._toStore("CurrentState") or \
77 selfA._toStore("CurrentOptimum"):
78 selfA.StoredVariables["CurrentState"].store( _X )
79 _HX = numpy.asarray(Hm( _X )).reshape((-1, 1))
81 if selfA._toStore("SimulatedObservationAtCurrentState") or \
82 selfA._toStore("SimulatedObservationAtCurrentOptimum"):
83 selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
84 if selfA._toStore("InnovationAtCurrentState"):
85 selfA.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
87 Jb = vfloat( 0.5 * _V.T * (BT * _V) )
88 Jo = vfloat( 0.5 * _Innovation.T * (RI * _Innovation) )
91 selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["CostFunctionJ"]) )
92 selfA.StoredVariables["CostFunctionJb"].store( Jb )
93 selfA.StoredVariables["CostFunctionJo"].store( Jo )
94 selfA.StoredVariables["CostFunctionJ" ].store( J )
95 if selfA._toStore("IndexOfOptimum") or \
96 selfA._toStore("CurrentOptimum") or \
97 selfA._toStore("CostFunctionJAtCurrentOptimum") or \
98 selfA._toStore("CostFunctionJbAtCurrentOptimum") or \
99 selfA._toStore("CostFunctionJoAtCurrentOptimum") or \
100 selfA._toStore("SimulatedObservationAtCurrentOptimum"):
101 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps # noqa: E501
102 if selfA._toStore("IndexOfOptimum"):
103 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
104 if selfA._toStore("CurrentOptimum"):
105 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["CurrentState"][IndexMin] ) # noqa: E501
106 if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
107 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] ) # noqa: E501
108 if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
109 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] ) # noqa: E501
110 if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
111 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] ) # noqa: E501
112 if selfA._toStore("CostFunctionJAtCurrentOptimum"):
113 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] ) # noqa: E501
116 def GradientOfCostFunction(v):
117 _V = numpy.asarray(v).reshape((-1, 1))
118 _X = Xb + (B @ _V).reshape((-1, 1))
119 _HX = numpy.asarray(Hm( _X )).reshape((-1, 1))
121 GradJo = - BT * Ha( (_X, RI * (Y - _HX)) )
122 GradJ = numpy.ravel( GradJb ) + numpy.ravel( GradJo )
125 # Minimisation de la fonctionnelle
126 # --------------------------------
127 nbPreviousSteps = selfA.StoredVariables["CostFunctionJ"].stepnumber()
129 if selfA._parameters["Minimizer"] == "LBFGSB":
130 if vt("0.19") <= vt(scipy.version.version) <= vt("1.4.99"):
131 import daAlgorithms.Atoms.lbfgsb14hlt as optimiseur
132 elif vt("1.5.0") <= vt(scipy.version.version) <= vt("1.7.99"):
133 import daAlgorithms.Atoms.lbfgsb17hlt as optimiseur
134 elif vt("1.8.0") <= vt(scipy.version.version) <= vt("1.8.99"):
135 import daAlgorithms.Atoms.lbfgsb18hlt as optimiseur
136 elif vt("1.9.0") <= vt(scipy.version.version) <= vt("1.10.99"):
137 import daAlgorithms.Atoms.lbfgsb19hlt as optimiseur
138 elif vt("1.11.0") <= vt(scipy.version.version) <= vt("1.11.99"):
139 import daAlgorithms.Atoms.lbfgsb111hlt as optimiseur
140 elif vt("1.12.0") <= vt(scipy.version.version) <= vt("1.12.99"):
141 import daAlgorithms.Atoms.lbfgsb112hlt as optimiseur
142 elif vt("1.13.0") <= vt(scipy.version.version) <= vt("1.13.99"):
143 import daAlgorithms.Atoms.lbfgsb113hlt as optimiseur
144 elif vt("1.14.0") <= vt(scipy.version.version) <= vt("1.14.99"):
145 import daAlgorithms.Atoms.lbfgsb114hlt as optimiseur
147 import scipy.optimize as optimiseur
148 Minimum, J_optimal, Informations = optimiseur.fmin_l_bfgs_b(
151 fprime = GradientOfCostFunction,
153 bounds = RecentredBounds(selfA._parameters["Bounds"], Xb, BI),
154 maxfun = selfA._parameters["MaximumNumberOfIterations"] - 1,
155 factr = selfA._parameters["CostDecrementTolerance"] * 1.e14,
156 pgtol = selfA._parameters["ProjectedGradientTolerance"],
157 iprint = selfA._parameters["optiprint"],
159 # nfeval = Informations['funcalls']
160 # rc = Informations['warnflag']
161 elif selfA._parameters["Minimizer"] == "TNC":
162 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
165 fprime = GradientOfCostFunction,
167 bounds = RecentredBounds(selfA._parameters["Bounds"], Xb, BI),
168 maxfun = selfA._parameters["MaximumNumberOfIterations"],
169 pgtol = selfA._parameters["ProjectedGradientTolerance"],
170 ftol = selfA._parameters["CostDecrementTolerance"],
171 messages = selfA._parameters["optmessages"],
173 elif selfA._parameters["Minimizer"] == "CG":
174 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
177 fprime = GradientOfCostFunction,
179 maxiter = selfA._parameters["MaximumNumberOfIterations"],
180 gtol = selfA._parameters["GradientNormTolerance"],
181 disp = selfA._parameters["optdisp"],
184 elif selfA._parameters["Minimizer"] == "NCG":
185 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
188 fprime = GradientOfCostFunction,
190 maxiter = selfA._parameters["MaximumNumberOfIterations"],
191 avextol = selfA._parameters["CostDecrementTolerance"],
192 disp = selfA._parameters["optdisp"],
195 elif selfA._parameters["Minimizer"] == "BFGS":
196 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
199 fprime = GradientOfCostFunction,
201 maxiter = selfA._parameters["MaximumNumberOfIterations"],
202 gtol = selfA._parameters["GradientNormTolerance"],
203 disp = selfA._parameters["optdisp"],
207 raise ValueError("Error in minimizer name: %s is unkown"%selfA._parameters["Minimizer"])
209 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
210 MinJ = selfA.StoredVariables["CostFunctionJ"][IndexMin]
212 # Correction pour pallier a un bug de TNC sur le retour du Minimum
213 # ----------------------------------------------------------------
214 if selfA._parameters["StoreInternalVariables"] or selfA._toStore("CurrentState"):
215 Minimum = selfA.StoredVariables["CurrentState"][IndexMin]
217 Minimum = Xb + B * Minimum.reshape((-1, 1)) # Pas de @
221 selfA._setInternalState("Xn", Xa)
222 # --------------------------
224 selfA.StoredVariables["Analysis"].store( Xa )
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]
237 oma = Y - numpy.asarray(HXa).reshape((-1, 1))
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"):
253 A = HessienneEstimation(selfA, Xa.size, HaM, HtM, BI, RI)
254 if selfA._toStore("APosterioriCovariance"):
255 selfA.StoredVariables["APosterioriCovariance"].store( A )
256 if selfA._toStore("JacobianMatrixAtOptimum"):
257 selfA.StoredVariables["JacobianMatrixAtOptimum"].store( HtM )
258 if selfA._toStore("KalmanGainAtOptimum"):
259 if (Y.size <= Xb.size):
260 KG = B * HaM * (R + numpy.dot(HtM, B * HaM)).I
261 elif (Y.size > Xb.size):
262 KG = (BI + numpy.dot(HaM, RI * HtM)).I * HaM * RI
263 selfA.StoredVariables["KalmanGainAtOptimum"].store( KG )
265 # Calculs et/ou stockages supplémentaires
266 # ---------------------------------------
267 if selfA._toStore("Innovation") or \
268 selfA._toStore("SigmaObs2") or \
269 selfA._toStore("MahalanobisConsistency") or \
270 selfA._toStore("OMB"):
272 if selfA._toStore("Innovation"):
273 selfA.StoredVariables["Innovation"].store( Innovation )
274 if selfA._toStore("BMA"):
275 selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
276 if selfA._toStore("OMA"):
277 selfA.StoredVariables["OMA"].store( oma )
278 if selfA._toStore("InnovationAtCurrentAnalysis"):
279 selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( oma )
280 if selfA._toStore("OMB"):
281 selfA.StoredVariables["OMB"].store( Innovation )
282 if selfA._toStore("SigmaObs2"):
283 TraceR = R.trace(Y.size)
284 selfA.StoredVariables["SigmaObs2"].store( vfloat( (Innovation.T @ oma) ) / TraceR )
285 if selfA._toStore("MahalanobisConsistency"):
286 selfA.StoredVariables["MahalanobisConsistency"].store( float( 2. * MinJ / Innovation.size ) )
287 if selfA._toStore("SimulationQuantiles"):
288 QuantilesEstimations(selfA, A, Xa, HXa, Hm, HtM)
289 if selfA._toStore("SimulatedObservationAtBackground"):
290 selfA.StoredVariables["SimulatedObservationAtBackground"].store( HXb )
291 if selfA._toStore("SimulatedObservationAtOptimum"):
292 selfA.StoredVariables["SimulatedObservationAtOptimum"].store( HXa )
296 # ==============================================================================
297 if __name__ == "__main__":
298 print('\n AUTODIAGNOSTIC\n')