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