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
31 # ==============================================================================
32 def std3dvar(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False):
39 Hm = HO["Direct"].appliedTo
40 Ha = HO["Adjoint"].appliedInXTo
42 if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
43 HXb = numpy.asarray(Hm( Xb, HO["AppliedInX"]["HXb"] ))
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))
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))
52 if selfA._toStore("JacobianMatrixAtBackground"):
53 HtMb = HO["Tangent"].asMatrix(Xb)
54 HtMb = HtMb.reshape(Y.size,Xb.size) # ADAO & check shape
55 selfA.StoredVariables["JacobianMatrixAtBackground"].store( HtMb )
60 Xini = selfA._parameters["InitializationPoint"]
62 # Définition de la fonction-coût
63 # ------------------------------
65 _X = numpy.asarray(x).reshape((-1,1))
66 if selfA._parameters["StoreInternalVariables"] or \
67 selfA._toStore("CurrentState") or \
68 selfA._toStore("CurrentOptimum"):
69 selfA.StoredVariables["CurrentState"].store( _X )
70 _HX = numpy.asarray(Hm( _X )).reshape((-1,1))
72 if selfA._toStore("SimulatedObservationAtCurrentState") or \
73 selfA._toStore("SimulatedObservationAtCurrentOptimum"):
74 selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
75 if selfA._toStore("InnovationAtCurrentState"):
76 selfA.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
78 Jb = float( 0.5 * (_X - Xb).T * (BI * (_X - Xb)) )
79 Jo = float( 0.5 * _Innovation.T * (RI * _Innovation) )
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] )
99 if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
100 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
101 if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
102 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
103 if selfA._toStore("CostFunctionJAtCurrentOptimum"):
104 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
107 def GradientOfCostFunction(x):
108 _X = numpy.asarray(x).reshape((-1,1))
109 _HX = numpy.asarray(Hm( _X )).reshape((-1,1))
110 GradJb = BI * (_X - Xb)
111 GradJo = - Ha( (_X, RI * (Y - _HX)) )
112 GradJ = numpy.ravel( GradJb ) + numpy.ravel( GradJo )
115 # Minimisation de la fonctionnelle
116 # --------------------------------
117 nbPreviousSteps = selfA.StoredVariables["CostFunctionJ"].stepnumber()
119 if selfA._parameters["Minimizer"] == "LBFGSB":
120 if "0.19" <= scipy.version.version <= "1.4.99":
121 import daAlgorithms.Atoms.lbfgsb14hlt as optimiseur
122 elif "1.5.0" <= scipy.version.version <= "1.7.99":
123 import daAlgorithms.Atoms.lbfgsb17hlt as optimiseur
124 elif "1.8.0" <= scipy.version.version <= "1.8.99":
125 import daAlgorithms.Atoms.lbfgsb18hlt as optimiseur
126 elif "1.9.0" <= scipy.version.version <= "1.9.99":
127 import daAlgorithms.Atoms.lbfgsb19hlt as optimiseur
129 import scipy.optimize as optimiseur
130 Minimum, J_optimal, Informations = optimiseur.fmin_l_bfgs_b(
133 fprime = GradientOfCostFunction,
135 bounds = selfA._parameters["Bounds"],
136 maxfun = selfA._parameters["MaximumNumberOfIterations"]-1,
137 factr = selfA._parameters["CostDecrementTolerance"]*1.e14,
138 pgtol = selfA._parameters["ProjectedGradientTolerance"],
139 iprint = selfA._parameters["optiprint"],
141 # nfeval = Informations['funcalls']
142 # rc = Informations['warnflag']
143 elif selfA._parameters["Minimizer"] == "TNC":
144 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
147 fprime = GradientOfCostFunction,
149 bounds = selfA._parameters["Bounds"],
150 maxfun = selfA._parameters["MaximumNumberOfIterations"],
151 pgtol = selfA._parameters["ProjectedGradientTolerance"],
152 ftol = selfA._parameters["CostDecrementTolerance"],
153 messages = selfA._parameters["optmessages"],
155 elif selfA._parameters["Minimizer"] == "CG":
156 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
159 fprime = GradientOfCostFunction,
161 maxiter = selfA._parameters["MaximumNumberOfIterations"],
162 gtol = selfA._parameters["GradientNormTolerance"],
163 disp = selfA._parameters["optdisp"],
166 elif selfA._parameters["Minimizer"] == "NCG":
167 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
170 fprime = GradientOfCostFunction,
172 maxiter = selfA._parameters["MaximumNumberOfIterations"],
173 avextol = selfA._parameters["CostDecrementTolerance"],
174 disp = selfA._parameters["optdisp"],
177 elif selfA._parameters["Minimizer"] == "BFGS":
178 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
181 fprime = GradientOfCostFunction,
183 maxiter = selfA._parameters["MaximumNumberOfIterations"],
184 gtol = selfA._parameters["GradientNormTolerance"],
185 disp = selfA._parameters["optdisp"],
189 raise ValueError("Error in minimizer name: %s is unkown"%selfA._parameters["Minimizer"])
191 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
192 MinJ = selfA.StoredVariables["CostFunctionJ"][IndexMin]
194 # Correction pour pallier a un bug de TNC sur le retour du Minimum
195 # ----------------------------------------------------------------
196 if selfA._parameters["StoreInternalVariables"] or selfA._toStore("CurrentState"):
197 Minimum = selfA.StoredVariables["CurrentState"][IndexMin]
200 if __storeState: selfA._setInternalState("Xn", Xa)
201 #--------------------------
203 selfA.StoredVariables["Analysis"].store( Xa )
205 if selfA._toStore("OMA") or \
206 selfA._toStore("InnovationAtCurrentAnalysis") or \
207 selfA._toStore("SigmaObs2") or \
208 selfA._toStore("SimulationQuantiles") or \
209 selfA._toStore("SimulatedObservationAtOptimum"):
210 if selfA._toStore("SimulatedObservationAtCurrentState"):
211 HXa = selfA.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
212 elif selfA._toStore("SimulatedObservationAtCurrentOptimum"):
213 HXa = selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
216 oma = Y - HXa.reshape((-1,1))
218 if selfA._toStore("APosterioriCovariance") or \
219 selfA._toStore("SimulationQuantiles") or \
220 selfA._toStore("JacobianMatrixAtOptimum") or \
221 selfA._toStore("KalmanGainAtOptimum"):
222 HtM = HO["Tangent"].asMatrix(ValueForMethodForm = Xa)
223 HtM = HtM.reshape(Y.size,Xa.size) # ADAO & check shape
224 if selfA._toStore("APosterioriCovariance") or \
225 selfA._toStore("SimulationQuantiles") or \
226 selfA._toStore("KalmanGainAtOptimum"):
227 HaM = HO["Adjoint"].asMatrix(ValueForMethodForm = Xa)
228 HaM = HaM.reshape(Xa.size,Y.size) # ADAO & check shape
229 if selfA._toStore("APosterioriCovariance") or \
230 selfA._toStore("SimulationQuantiles"):
231 A = HessienneEstimation(selfA, Xa.size, HaM, HtM, BI, RI)
232 if selfA._toStore("APosterioriCovariance"):
233 selfA.StoredVariables["APosterioriCovariance"].store( A )
234 if selfA._toStore("JacobianMatrixAtOptimum"):
235 selfA.StoredVariables["JacobianMatrixAtOptimum"].store( HtM )
236 if selfA._toStore("KalmanGainAtOptimum"):
237 if (Y.size <= Xb.size): KG = B * HaM * (R + numpy.dot(HtM, B * HaM)).I
238 elif (Y.size > Xb.size): KG = (BI + numpy.dot(HaM, RI * HtM)).I * HaM * RI
239 selfA.StoredVariables["KalmanGainAtOptimum"].store( KG )
241 # Calculs et/ou stockages supplémentaires
242 # ---------------------------------------
243 if selfA._toStore("Innovation") or \
244 selfA._toStore("SigmaObs2") or \
245 selfA._toStore("MahalanobisConsistency") or \
246 selfA._toStore("OMB"):
248 if selfA._toStore("Innovation"):
249 selfA.StoredVariables["Innovation"].store( Innovation )
250 if selfA._toStore("BMA"):
251 selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
252 if selfA._toStore("OMA"):
253 selfA.StoredVariables["OMA"].store( oma )
254 if selfA._toStore("InnovationAtCurrentAnalysis"):
255 selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( oma )
256 if selfA._toStore("OMB"):
257 selfA.StoredVariables["OMB"].store( Innovation )
258 if selfA._toStore("SigmaObs2"):
259 TraceR = R.trace(Y.size)
260 selfA.StoredVariables["SigmaObs2"].store( float( (Innovation.T @ oma) ) / TraceR )
261 if selfA._toStore("MahalanobisConsistency"):
262 selfA.StoredVariables["MahalanobisConsistency"].store( float( 2.*MinJ/Innovation.size ) )
263 if selfA._toStore("SimulationQuantiles"):
264 QuantilesEstimations(selfA, A, Xa, HXa, Hm, HtM)
265 if selfA._toStore("SimulatedObservationAtBackground"):
266 selfA.StoredVariables["SimulatedObservationAtBackground"].store( HXb )
267 if selfA._toStore("SimulatedObservationAtOptimum"):
268 selfA.StoredVariables["SimulatedObservationAtOptimum"].store( HXa )
272 # ==============================================================================
273 if __name__ == "__main__":
274 print('\n AUTODIAGNOSTIC\n')