1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2022 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
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
32 mpr = PlatformInfo().MachinePrecision()
34 # ==============================================================================
35 def incr3dvar(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False):
42 Hm = HO["Direct"].appliedTo
44 if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
45 HXb = numpy.asarray(Hm( Xb, HO["AppliedInX"]["HXb"] ))
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))
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 )
69 Xr = numpy.asarray(selfA._parameters["InitializationPoint"]).reshape((-1,1))
70 while abs(DeltaJ) >= selfA._parameters["CostDecrementTolerance"] and iOuter <= selfA._parameters["MaximumNumberOfIterations"]:
74 Ht = HO["Tangent"].asMatrix(Xr)
75 Ht = Ht.reshape(Y.size,Xr.size) # ADAO & check shape
77 # Définition de la fonction-coût
78 # ------------------------------
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 )
93 Jb = float( 0.5 * _dX.T * (BI * _dX) )
94 Jo = float( 0.5 * _dInnovation.T * (RI * _dInnovation) )
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] )
122 def GradientOfCostFunction(dx):
123 _dX = numpy.ravel( dx )
124 _HdX = (Ht @ _dX).reshape((-1,1))
125 _dInnovation = Innovation - _HdX
127 GradJo = - Ht.T @ (RI * _dInnovation)
128 GradJ = numpy.ravel( GradJb ) + numpy.ravel( GradJo )
131 # Minimisation de la fonctionnelle
132 # --------------------------------
133 nbPreviousSteps = selfA.StoredVariables["CostFunctionJ"].stepnumber()
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
146 import scipy.optimize as optimiseur
147 Minimum, J_optimal, Informations = optimiseur.fmin_l_bfgs_b(
149 x0 = numpy.zeros(Xb.size),
150 fprime = GradientOfCostFunction,
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"],
158 # nfeval = Informations['funcalls']
159 # rc = Informations['warnflag']
160 elif selfA._parameters["Minimizer"] == "TNC":
161 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
163 x0 = numpy.zeros(Xb.size),
164 fprime = GradientOfCostFunction,
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"],
172 elif selfA._parameters["Minimizer"] == "CG":
173 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
175 x0 = numpy.zeros(Xb.size),
176 fprime = GradientOfCostFunction,
178 maxiter = selfA._parameters["MaximumNumberOfIterations"],
179 gtol = selfA._parameters["GradientNormTolerance"],
180 disp = selfA._parameters["optdisp"],
183 elif selfA._parameters["Minimizer"] == "NCG":
184 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
186 x0 = numpy.zeros(Xb.size),
187 fprime = GradientOfCostFunction,
189 maxiter = selfA._parameters["MaximumNumberOfIterations"],
190 avextol = selfA._parameters["CostDecrementTolerance"],
191 disp = selfA._parameters["optdisp"],
194 elif selfA._parameters["Minimizer"] == "BFGS":
195 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
197 x0 = numpy.zeros(Xb.size),
198 fprime = GradientOfCostFunction,
200 maxiter = selfA._parameters["MaximumNumberOfIterations"],
201 gtol = selfA._parameters["GradientNormTolerance"],
202 disp = selfA._parameters["optdisp"],
206 raise ValueError("Error in minimizer name: %s is unkown"%selfA._parameters["Minimizer"])
208 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
209 MinJ = selfA.StoredVariables["CostFunctionJ"][IndexMin]
211 if selfA._parameters["StoreInternalVariables"] or selfA._toStore("CurrentState"):
212 Minimum = selfA.StoredVariables["CurrentState"][IndexMin]
214 Minimum = Xb + Minimum.reshape((-1,1))
217 DeltaJ = selfA.StoredVariables["CostFunctionJ" ][-1] - J
218 iOuter = selfA.StoredVariables["CurrentIterationNumber"][-1]
221 if __storeState: 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 - 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"):
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 )
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"):
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 )
293 # ==============================================================================
294 if __name__ == "__main__":
295 print('\n AUTODIAGNOSTIC\n')