]> SALOME platform Git repositories - modules/adao.git/blob - src/daComposant/daAlgorithms/3DVAR.py
Salome HOME
Improving performance when using diagonal sparse matrices
[modules/adao.git] / src / daComposant / daAlgorithms / 3DVAR.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2013 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 import logging
24 from daCore import BasicObjects, PlatformInfo
25 m = PlatformInfo.SystemUsage()
26
27 import numpy
28 import scipy.optimize
29
30 if logging.getLogger().level < logging.WARNING:
31     iprint  = 1
32     message = scipy.optimize.tnc.MSG_ALL
33     disp    = 1
34 else:
35     iprint  = -1
36     message = scipy.optimize.tnc.MSG_NONE
37     disp    = 0
38
39 # ==============================================================================
40 class ElementaryAlgorithm(BasicObjects.Algorithm):
41     def __init__(self):
42         BasicObjects.Algorithm.__init__(self, "3DVAR")
43         self.defineRequiredParameter(
44             name     = "Minimizer",
45             default  = "LBFGSB",
46             typecast = str,
47             message  = "Minimiseur utilisé",
48             listval  = ["LBFGSB","TNC", "CG", "NCG", "BFGS"],
49             )
50         self.defineRequiredParameter(
51             name     = "MaximumNumberOfSteps",
52             default  = 15000,
53             typecast = int,
54             message  = "Nombre maximal de pas d'optimisation",
55             minval   = -1,
56             )
57         self.defineRequiredParameter(
58             name     = "CostDecrementTolerance",
59             default  = 1.e-7,
60             typecast = float,
61             message  = "Diminution relative minimale du cout lors de l'arrêt",
62             )
63         self.defineRequiredParameter(
64             name     = "ProjectedGradientTolerance",
65             default  = -1,
66             typecast = float,
67             message  = "Maximum des composantes du gradient projeté lors de l'arrêt",
68             minval   = -1,
69             )
70         self.defineRequiredParameter(
71             name     = "GradientNormTolerance",
72             default  = 1.e-05,
73             typecast = float,
74             message  = "Maximum des composantes du gradient lors de l'arrêt",
75             )
76         self.defineRequiredParameter(
77             name     = "StoreInternalVariables",
78             default  = False,
79             typecast = bool,
80             message  = "Stockage des variables internes ou intermédiaires du calcul",
81             )
82         self.defineRequiredParameter(
83             name     = "StoreSupplementaryCalculations",
84             default  = [],
85             typecast = tuple,
86             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
87             listval  = ["APosterioriCovariance", "BMA", "OMA", "OMB", "Innovation", "SigmaObs2", "MahalanobisConsistency"]
88             )
89
90     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
91         logging.debug("%s Lancement"%self._name)
92         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
93         #
94         # Paramètres de pilotage
95         # ----------------------
96         self.setParameters(Parameters)
97         #
98         if self._parameters.has_key("Bounds") and (type(self._parameters["Bounds"]) is type([]) or type(self._parameters["Bounds"]) is type(())) and (len(self._parameters["Bounds"]) > 0):
99             Bounds = self._parameters["Bounds"]
100             logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
101         else:
102             Bounds = None
103         #
104         # Correction pour pallier a un bug de TNC sur le retour du Minimum
105         if self._parameters.has_key("Minimizer") == "TNC":
106             self.setParameterValue("StoreInternalVariables",True)
107         #
108         # Opérateur d'observation
109         # -----------------------
110         Hm = HO["Direct"].appliedTo
111         Ha = HO["Adjoint"].appliedInXTo
112         #
113         # Utilisation éventuelle d'un vecteur H(Xb) précalculé
114         # ----------------------------------------------------
115         if HO["AppliedToX"] is not None and HO["AppliedToX"].has_key("HXb"):
116             HXb = HO["AppliedToX"]["HXb"]
117         else:
118             HXb = Hm( Xb )
119         HXb = numpy.asmatrix(numpy.ravel( HXb )).T
120         #
121         # Calcul de l'innovation
122         # ----------------------
123         if Y.size != HXb.size:
124             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))
125         if max(Y.shape) != max(HXb.shape):
126             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))
127         d  = Y - HXb
128         #
129         # Précalcul des inversions de B et R
130         # ----------------------------------
131         BI = B.getI()
132         RI = R.getI()
133         #
134         # Définition de la fonction-coût
135         # ------------------------------
136         def CostFunction(x):
137             _X  = numpy.asmatrix(numpy.ravel( x )).T
138             _HX = Hm( _X )
139             _HX = numpy.asmatrix(numpy.ravel( _HX )).T
140             Jb  = 0.5 * (_X - Xb).T * BI * (_X - Xb)
141             Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
142             J   = float( Jb ) + float( Jo )
143             if self._parameters["StoreInternalVariables"]:
144                 self.StoredVariables["CurrentState"].store( _X.A1 )
145             self.StoredVariables["CostFunctionJb"].store( Jb )
146             self.StoredVariables["CostFunctionJo"].store( Jo )
147             self.StoredVariables["CostFunctionJ" ].store( J )
148             return J
149         #
150         def GradientOfCostFunction(x):
151             _X      = numpy.asmatrix(numpy.ravel( x )).T
152             _HX     = Hm( _X )
153             _HX     = numpy.asmatrix(numpy.ravel( _HX )).T
154             GradJb  = BI * (_X - Xb)
155             GradJo  = - Ha( (_X, RI * (Y - _HX)) )
156             GradJ   = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
157             return GradJ.A1
158         #
159         # Point de démarrage de l'optimisation : Xini = Xb
160         # ------------------------------------
161         if type(Xb) is type(numpy.matrix([])):
162             Xini = Xb.A1.tolist()
163         else:
164             Xini = list(Xb)
165         #
166         # Minimisation de la fonctionnelle
167         # --------------------------------
168         nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
169         #
170         if self._parameters["Minimizer"] == "LBFGSB":
171             Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
172                 func        = CostFunction,
173                 x0          = Xini,
174                 fprime      = GradientOfCostFunction,
175                 args        = (),
176                 bounds      = Bounds,
177                 maxfun      = self._parameters["MaximumNumberOfSteps"]-1,
178                 factr       = self._parameters["CostDecrementTolerance"]*1.e14,
179                 pgtol       = self._parameters["ProjectedGradientTolerance"],
180                 iprint      = iprint,
181                 )
182             nfeval = Informations['funcalls']
183             rc     = Informations['warnflag']
184         elif self._parameters["Minimizer"] == "TNC":
185             Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
186                 func        = CostFunction,
187                 x0          = Xini,
188                 fprime      = GradientOfCostFunction,
189                 args        = (),
190                 bounds      = Bounds,
191                 maxfun      = self._parameters["MaximumNumberOfSteps"],
192                 pgtol       = self._parameters["ProjectedGradientTolerance"],
193                 ftol        = self._parameters["CostDecrementTolerance"],
194                 messages    = message,
195                 )
196         elif self._parameters["Minimizer"] == "CG":
197             Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
198                 f           = CostFunction,
199                 x0          = Xini,
200                 fprime      = GradientOfCostFunction,
201                 args        = (),
202                 maxiter     = self._parameters["MaximumNumberOfSteps"],
203                 gtol        = self._parameters["GradientNormTolerance"],
204                 disp        = disp,
205                 full_output = True,
206                 )
207         elif self._parameters["Minimizer"] == "NCG":
208             Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
209                 f           = CostFunction,
210                 x0          = Xini,
211                 fprime      = GradientOfCostFunction,
212                 args        = (),
213                 maxiter     = self._parameters["MaximumNumberOfSteps"],
214                 avextol     = self._parameters["CostDecrementTolerance"],
215                 disp        = disp,
216                 full_output = True,
217                 )
218         elif self._parameters["Minimizer"] == "BFGS":
219             Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
220                 f           = CostFunction,
221                 x0          = Xini,
222                 fprime      = GradientOfCostFunction,
223                 args        = (),
224                 maxiter     = self._parameters["MaximumNumberOfSteps"],
225                 gtol        = self._parameters["GradientNormTolerance"],
226                 disp        = disp,
227                 full_output = True,
228                 )
229         else:
230             raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
231         #
232         IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
233         MinJ     = self.StoredVariables["CostFunctionJ"][IndexMin]
234         #
235         # Correction pour pallier a un bug de TNC sur le retour du Minimum
236         # ----------------------------------------------------------------
237         if self._parameters["StoreInternalVariables"]:
238             Minimum = self.StoredVariables["CurrentState"][IndexMin]
239         #
240         # Obtention de l'analyse
241         # ----------------------
242         Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
243         #
244         self.StoredVariables["Analysis"].store( Xa.A1 )
245         #
246         # Calcul de la covariance d'analyse
247         # ---------------------------------
248         if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
249             HtM = HO["Tangent"].asMatrix(ValueForMethodForm = Xa)
250             HtM = HtM.reshape(Y.size,Xa.size) # ADAO & check shape
251             HaM = HO["Adjoint"].asMatrix(ValueForMethodForm = Xa)
252             HaM = HaM.reshape(Xa.size,Y.size) # ADAO & check shape
253             HessienneI = []
254             nb = Xa.size
255             for i in range(nb):
256                 _ee    = numpy.matrix(numpy.zeros(nb)).T
257                 _ee[i] = 1.
258                 _HtEE  = numpy.dot(HtM,_ee)
259                 _HtEE  = numpy.asmatrix(numpy.ravel( _HtEE )).T
260                 HessienneI.append( numpy.ravel( BI*_ee + HaM * (RI * _HtEE) ) )
261             HessienneI = numpy.matrix( HessienneI )
262             A = HessienneI.I
263             if min(A.shape) != max(A.shape):
264                 raise ValueError("The %s a posteriori covariance matrix A is of shape %s, despites it has to be a squared matrix. There is an error in the observation operator, please check it."%(self._name,str(A.shape)))
265             if (numpy.diag(A) < 0).any():
266                 raise ValueError("The %s a posteriori covariance matrix A has at least one negative value on its diagonal. There is an error in the observation operator, please check it."%(self._name,))
267             if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
268                 try:
269                     L = numpy.linalg.cholesky( A )
270                 except:
271                     raise ValueError("The %s a posteriori covariance matrix A is not symmetric positive-definite. Please check your a priori covariances and your observation operator."%(self._name,))
272             self.StoredVariables["APosterioriCovariance"].store( A )
273         #
274         # Calculs et/ou stockages supplémentaires
275         # ---------------------------------------
276         if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
277             self.StoredVariables["Innovation"].store( numpy.ravel(d) )
278         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
279             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
280         if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
281             self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(Hm(Xa)) )
282         if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
283             self.StoredVariables["OMB"].store( numpy.ravel(d) )
284         if "SigmaObs2" in self._parameters["StoreSupplementaryCalculations"]:
285             TraceR = R.trace(Y.size)
286             self.StoredVariables["SigmaObs2"].store( float( (d.T * (numpy.asmatrix(numpy.ravel(Y)).T-numpy.asmatrix(numpy.ravel(Hm(Xa))).T)) ) / TraceR )
287         if "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"]:
288             self.StoredVariables["MahalanobisConsistency"].store( float( 2.*MinJ/d.size ) )
289         #
290         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
291         logging.debug("%s Terminé"%self._name)
292         #
293         return 0
294
295 # ==============================================================================
296 if __name__ == "__main__":
297     print '\n AUTODIAGNOSTIC \n'