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 psas3dvar(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False):
39 Hm = HO["Direct"].appliedTo
41 if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
42 HXb = numpy.asarray(Hm( Xb, HO["AppliedInX"]["HXb"] ))
44 HXb = numpy.asarray(Hm( Xb ))
45 HXb = HXb.reshape((-1,1))
46 if Y.size != HXb.size:
47 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))
48 if max(Y.shape) != max(HXb.shape):
49 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))
51 Ht = HO["Tangent"].asMatrix(Xb)
52 Ht = Ht.reshape(Y.size,Xb.size) # ADAO & check shape
57 if selfA._toStore("JacobianMatrixAtBackground"):
58 selfA.StoredVariables["JacobianMatrixAtBackground"].store( Ht )
60 Xini = numpy.zeros(Y.size)
62 # Définition de la fonction-coût
63 # ------------------------------
65 _W = numpy.asarray(w).reshape((-1,1))
66 if selfA._parameters["StoreInternalVariables"] or \
67 selfA._toStore("CurrentState") or \
68 selfA._toStore("CurrentOptimum"):
69 selfA.StoredVariables["CurrentState"].store( Xb + BHT @ _W )
70 if selfA._toStore("SimulatedObservationAtCurrentState") or \
71 selfA._toStore("SimulatedObservationAtCurrentOptimum"):
72 selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( Hm( Xb + BHT @ _W ) )
73 if selfA._toStore("InnovationAtCurrentState"):
74 selfA.StoredVariables["InnovationAtCurrentState"].store( Innovation )
76 Jb = float( 0.5 * _W.T @ (HBHTpR @ _W) )
77 Jo = float( - _W.T @ Innovation )
80 selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["CostFunctionJ"]) )
81 selfA.StoredVariables["CostFunctionJb"].store( Jb )
82 selfA.StoredVariables["CostFunctionJo"].store( Jo )
83 selfA.StoredVariables["CostFunctionJ" ].store( J )
84 if selfA._toStore("IndexOfOptimum") or \
85 selfA._toStore("CurrentOptimum") or \
86 selfA._toStore("CostFunctionJAtCurrentOptimum") or \
87 selfA._toStore("CostFunctionJbAtCurrentOptimum") or \
88 selfA._toStore("CostFunctionJoAtCurrentOptimum") or \
89 selfA._toStore("SimulatedObservationAtCurrentOptimum"):
90 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
91 if selfA._toStore("IndexOfOptimum"):
92 selfA.StoredVariables["IndexOfOptimum"].store( IndexMin )
93 if selfA._toStore("CurrentOptimum"):
94 selfA.StoredVariables["CurrentOptimum"].store( selfA.StoredVariables["CurrentState"][IndexMin] )
95 if selfA._toStore("SimulatedObservationAtCurrentOptimum"):
96 selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( selfA.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] )
97 if selfA._toStore("CostFunctionJbAtCurrentOptimum"):
98 selfA.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJb"][IndexMin] )
99 if selfA._toStore("CostFunctionJoAtCurrentOptimum"):
100 selfA.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( selfA.StoredVariables["CostFunctionJo"][IndexMin] )
101 if selfA._toStore("CostFunctionJAtCurrentOptimum"):
102 selfA.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( selfA.StoredVariables["CostFunctionJ" ][IndexMin] )
105 def GradientOfCostFunction(w):
106 _W = numpy.asarray(w).reshape((-1,1))
108 GradJo = - Innovation
109 GradJ = numpy.ravel( GradJb ) + numpy.ravel( GradJo )
112 # Minimisation de la fonctionnelle
113 # --------------------------------
114 nbPreviousSteps = selfA.StoredVariables["CostFunctionJ"].stepnumber()
116 if selfA._parameters["Minimizer"] == "LBFGSB":
117 if "0.19" <= scipy.version.version <= "1.4.99":
118 import daAlgorithms.Atoms.lbfgsb14hlt as optimiseur
119 elif "1.5.0" <= scipy.version.version <= "1.7.99":
120 import daAlgorithms.Atoms.lbfgsb17hlt as optimiseur
121 elif "1.8.0" <= scipy.version.version <= "1.8.99":
122 import daAlgorithms.Atoms.lbfgsb18hlt as optimiseur
123 elif "1.9.0" <= scipy.version.version <= "1.9.99":
124 import daAlgorithms.Atoms.lbfgsb19hlt as optimiseur
126 import scipy.optimize as optimiseur
127 Minimum, J_optimal, Informations = optimiseur.fmin_l_bfgs_b(
130 fprime = GradientOfCostFunction,
132 maxfun = selfA._parameters["MaximumNumberOfIterations"]-1,
133 factr = selfA._parameters["CostDecrementTolerance"]*1.e14,
134 pgtol = selfA._parameters["ProjectedGradientTolerance"],
135 iprint = selfA._parameters["optiprint"],
137 # nfeval = Informations['funcalls']
138 # rc = Informations['warnflag']
139 elif selfA._parameters["Minimizer"] == "TNC":
140 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
143 fprime = GradientOfCostFunction,
145 maxfun = selfA._parameters["MaximumNumberOfIterations"],
146 pgtol = selfA._parameters["ProjectedGradientTolerance"],
147 ftol = selfA._parameters["CostDecrementTolerance"],
148 messages = selfA._parameters["optmessages"],
150 elif selfA._parameters["Minimizer"] == "CG":
151 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
154 fprime = GradientOfCostFunction,
156 maxiter = selfA._parameters["MaximumNumberOfIterations"],
157 gtol = selfA._parameters["GradientNormTolerance"],
158 disp = selfA._parameters["optdisp"],
161 elif selfA._parameters["Minimizer"] == "NCG":
162 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
165 fprime = GradientOfCostFunction,
167 maxiter = selfA._parameters["MaximumNumberOfIterations"],
168 avextol = selfA._parameters["CostDecrementTolerance"],
169 disp = selfA._parameters["optdisp"],
172 elif selfA._parameters["Minimizer"] == "BFGS":
173 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
176 fprime = GradientOfCostFunction,
178 maxiter = selfA._parameters["MaximumNumberOfIterations"],
179 gtol = selfA._parameters["GradientNormTolerance"],
180 disp = selfA._parameters["optdisp"],
184 raise ValueError("Error in minimizer name: %s is unkown"%selfA._parameters["Minimizer"])
186 IndexMin = numpy.argmin( selfA.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
187 MinJ = selfA.StoredVariables["CostFunctionJ"][IndexMin]
189 # Correction pour pallier a un bug de TNC sur le retour du Minimum
190 # ----------------------------------------------------------------
191 if selfA._parameters["StoreInternalVariables"] or selfA._toStore("CurrentState"):
192 Minimum = selfA.StoredVariables["CurrentState"][IndexMin]
194 Minimum = Xb + BHT @ Minimum.reshape((-1,1))
197 if __storeState: selfA._setInternalState("Xn", Xa)
198 #--------------------------
200 selfA.StoredVariables["Analysis"].store( Xa )
202 if selfA._toStore("OMA") or \
203 selfA._toStore("InnovationAtCurrentAnalysis") or \
204 selfA._toStore("SigmaObs2") or \
205 selfA._toStore("SimulationQuantiles") or \
206 selfA._toStore("SimulatedObservationAtOptimum"):
207 if selfA._toStore("SimulatedObservationAtCurrentState"):
208 HXa = selfA.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
209 elif selfA._toStore("SimulatedObservationAtCurrentOptimum"):
210 HXa = selfA.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
213 oma = Y - HXa.reshape((-1,1))
215 if selfA._toStore("APosterioriCovariance") or \
216 selfA._toStore("SimulationQuantiles") or \
217 selfA._toStore("JacobianMatrixAtOptimum") or \
218 selfA._toStore("KalmanGainAtOptimum"):
219 HtM = HO["Tangent"].asMatrix(ValueForMethodForm = Xa)
220 HtM = HtM.reshape(Y.size,Xa.size) # ADAO & check shape
221 if selfA._toStore("APosterioriCovariance") or \
222 selfA._toStore("SimulationQuantiles") or \
223 selfA._toStore("KalmanGainAtOptimum"):
224 HaM = HO["Adjoint"].asMatrix(ValueForMethodForm = Xa)
225 HaM = HaM.reshape(Xa.size,Y.size) # ADAO & check shape
226 if selfA._toStore("APosterioriCovariance") or \
227 selfA._toStore("SimulationQuantiles"):
230 A = HessienneEstimation(selfA, Xa.size, HaM, HtM, BI, RI)
231 if selfA._toStore("APosterioriCovariance"):
232 selfA.StoredVariables["APosterioriCovariance"].store( A )
233 if selfA._toStore("JacobianMatrixAtOptimum"):
234 selfA.StoredVariables["JacobianMatrixAtOptimum"].store( HtM )
235 if selfA._toStore("KalmanGainAtOptimum"):
236 if (Y.size <= Xb.size): KG = B * HaM * (R + numpy.dot(HtM, B * HaM)).I
237 elif (Y.size > Xb.size): KG = (BI + numpy.dot(HaM, RI * HtM)).I * HaM * RI
238 selfA.StoredVariables["KalmanGainAtOptimum"].store( KG )
240 # Calculs et/ou stockages supplémentaires
241 # ---------------------------------------
242 if selfA._toStore("Innovation") or \
243 selfA._toStore("SigmaObs2") or \
244 selfA._toStore("MahalanobisConsistency") or \
245 selfA._toStore("OMB"):
247 if selfA._toStore("Innovation"):
248 selfA.StoredVariables["Innovation"].store( Innovation )
249 if selfA._toStore("BMA"):
250 selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
251 if selfA._toStore("OMA"):
252 selfA.StoredVariables["OMA"].store( oma )
253 if selfA._toStore("InnovationAtCurrentAnalysis"):
254 selfA.StoredVariables["InnovationAtCurrentAnalysis"].store( oma )
255 if selfA._toStore("OMB"):
256 selfA.StoredVariables["OMB"].store( Innovation )
257 if selfA._toStore("SigmaObs2"):
258 TraceR = R.trace(Y.size)
259 selfA.StoredVariables["SigmaObs2"].store( float( (Innovation.T @ oma) ) / TraceR )
260 if selfA._toStore("MahalanobisConsistency"):
261 selfA.StoredVariables["MahalanobisConsistency"].store( float( 2.*MinJ/Innovation.size ) )
262 if selfA._toStore("SimulationQuantiles"):
263 QuantilesEstimations(selfA, A, Xa, HXa, Hm, HtM)
264 if selfA._toStore("SimulatedObservationAtBackground"):
265 selfA.StoredVariables["SimulatedObservationAtBackground"].store( HXb )
266 if selfA._toStore("SimulatedObservationAtOptimum"):
267 selfA.StoredVariables["SimulatedObservationAtOptimum"].store( HXa )
271 # ==============================================================================
272 if __name__ == "__main__":
273 print('\n AUTODIAGNOSTIC\n')