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