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