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