Salome HOME
616b41ae76c2a75c8e701f26d32edfd43b074a7c
[modules/adao.git] / src / daComposant / daAlgorithms / QuantileRegression.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2012 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
22 import logging
23 from daCore import BasicObjects, PlatformInfo
24 m = PlatformInfo.SystemUsage()
25
26 import numpy
27
28 # ==============================================================================
29 class ElementaryAlgorithm(BasicObjects.Algorithm):
30     def __init__(self):
31         BasicObjects.Algorithm.__init__(self, "QUANTILEREGRESSION")
32         self.defineRequiredParameter(
33             name     = "Quantile",
34             default  = 0.5,
35             typecast = float,
36             message  = "Quantile pour la regression de quantile",
37             minval   = 0.,
38             maxval   = 1.,
39             )
40         self.defineRequiredParameter(
41             name     = "Minimizer",
42             default  = "MMQR",
43             typecast = str,
44             message  = "Minimiseur utilisé",
45             listval  = ["MMQR"],
46             )
47         self.defineRequiredParameter(
48             name     = "MaximumNumberOfSteps",
49             default  = 15000,
50             typecast = int,
51             message  = "Nombre maximal de pas d'optimisation",
52             minval   = 1,
53             )
54         self.defineRequiredParameter(
55             name     = "CostDecrementTolerance",
56             default  = 1.e-6,
57             typecast = float,
58             message  = "Maximum de variation de la fonction d'estimation lors de l'arrêt",
59             )
60         self.defineRequiredParameter(
61             name     = "StoreInternalVariables",
62             default  = False,
63             typecast = bool,
64             message  = "Stockage des variables internes ou intermédiaires du calcul",
65             )
66
67     def run(self, Xb=None, Y=None, H=None, M=None, R=None, B=None, Q=None, Parameters=None):
68         """
69         Calcul des parametres definissant le quantile
70         """
71         logging.debug("%s Lancement"%self._name)
72         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("Mo")))
73         #
74         # Paramètres de pilotage
75         # ----------------------
76         self.setParameters(Parameters)
77         #
78         # Opérateur d'observation
79         # -----------------------
80         Hm = H["Direct"].appliedTo
81         #
82         # Utilisation éventuelle d'un vecteur H(Xb) précalculé
83         # ----------------------------------------------------
84         if H["AppliedToX"] is not None and H["AppliedToX"].has_key("HXb"):
85             logging.debug("%s Utilisation de HXb"%self._name)
86             HXb = H["AppliedToX"]["HXb"]
87         else:
88             logging.debug("%s Calcul de Hm(Xb)"%self._name)
89             HXb = Hm( Xb )
90         HXb = numpy.asmatrix(HXb).flatten().T
91         #
92         # Calcul de l'innovation
93         # ----------------------
94         if Y.size != HXb.size:
95             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))
96         if max(Y.shape) != max(HXb.shape):
97             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))
98         d  = Y - HXb
99         logging.debug("%s Innovation d = %s"%(self._name, d))
100         #
101         # Définition de la fonction-coût
102         # ------------------------------
103         def CostFunction(x):
104             _X  = numpy.asmatrix(x).flatten().T
105             logging.debug("%s CostFunction X  = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
106             _HX = Hm( _X )
107             _HX = numpy.asmatrix(_HX).flatten().T
108             Jb  = 0.
109             Jo  = 0.
110             J   = Jb + Jo
111             logging.debug("%s CostFunction Jb = %s"%(self._name, Jb))
112             logging.debug("%s CostFunction Jo = %s"%(self._name, Jo))
113             logging.debug("%s CostFunction J  = %s"%(self._name, J))
114             if self._parameters["StoreInternalVariables"]:
115                 self.StoredVariables["CurrentState"].store( _X.A1 )
116             self.StoredVariables["CostFunctionJb"].store( Jb )
117             self.StoredVariables["CostFunctionJo"].store( Jo )
118             self.StoredVariables["CostFunctionJ" ].store( J )
119             return _HX
120         #
121         def GradientOfCostFunction(x):
122             _X      = numpy.asmatrix(x).flatten().T
123             logging.debug("%s GradientOfCostFunction X      = %s"%(self._name, _X.A1))
124             Hg = H["Tangent"].asMatrix( _X )
125             return Hg
126         #
127         # Point de démarrage de l'optimisation : Xini = Xb
128         # ------------------------------------
129         if type(Xb) is type(numpy.matrix([])):
130             Xini = Xb.A1.tolist()
131         else:
132             Xini = list(Xb)
133         logging.debug("%s Point de démarrage Xini = %s"%(self._name, Xini))
134         #
135         # Minimisation de la fonctionnelle
136         # --------------------------------
137         if self._parameters["Minimizer"] == "MMQR":
138             import mmqr
139             Minimum, J_optimal, Informations = mmqr.mmqr(
140                 func        = CostFunction,
141                 x0          = Xini,
142                 fprime      = GradientOfCostFunction,
143                 quantile    = self._parameters["Quantile"],
144                 maxfun      = self._parameters["MaximumNumberOfSteps"],
145                 toler       = self._parameters["CostDecrementTolerance"],
146                 y           = Y,
147                 )
148             nfeval = Informations[2]
149             rc     = Informations[4]
150         else:
151             raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
152         #
153         logging.debug("%s %s Step of min cost  = %s"%(self._name, self._parameters["Minimizer"], nfeval))
154         logging.debug("%s %s Minimum cost      = %s"%(self._name, self._parameters["Minimizer"], J_optimal))
155         logging.debug("%s %s Minimum state     = %s"%(self._name, self._parameters["Minimizer"], Minimum))
156         logging.debug("%s %s Nb of F           = %s"%(self._name, self._parameters["Minimizer"], nfeval))
157         logging.debug("%s %s RetCode           = %s"%(self._name, self._parameters["Minimizer"], rc))
158         #
159         # Obtention de l'analyse
160         # ----------------------
161         Xa = numpy.asmatrix(Minimum).flatten().T
162         logging.debug("%s Analyse Xa = %s"%(self._name, Xa))
163         #
164         self.StoredVariables["Analysis"].store( Xa.A1 )
165         self.StoredVariables["Innovation"].store( d.A1 )
166         #
167         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("MB")))
168         logging.debug("%s Terminé"%self._name)
169         #
170         return 0
171
172 # ==============================================================================
173 if __name__ == "__main__":
174     print '\n AUTODIAGNOSTIC \n'