Salome HOME
6022aed9d5e66b5f8eea546f10578372d7261d99
[modules/adao.git] / src / daComposant / daAlgorithms / QuantileRegression.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2013 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, U=None, HO=None, EM=None, CM=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         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):
84             Bounds = self._parameters["Bounds"]
85             logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
86         else:
87             Bounds = None
88         #
89         # Opérateur d'observation
90         # -----------------------
91         Hm = HO["Direct"].appliedTo
92         #
93         # Utilisation éventuelle d'un vecteur H(Xb) précalculé
94         # ----------------------------------------------------
95         if HO["AppliedToX"] is not None and HO["AppliedToX"].has_key("HXb"):
96             HXb = HO["AppliedToX"]["HXb"]
97         else:
98             HXb = Hm( Xb )
99         HXb = numpy.asmatrix(numpy.ravel( HXb )).T
100         #
101         # Calcul de l'innovation
102         # ----------------------
103         if Y.size != HXb.size:
104             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))
105         if max(Y.shape) != max(HXb.shape):
106             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))
107         d  = Y - HXb
108         #
109         # Définition de la fonction-coût
110         # ------------------------------
111         def CostFunction(x):
112             _X  = numpy.asmatrix(numpy.ravel( x )).T
113             _HX = Hm( _X )
114             _HX = numpy.asmatrix(numpy.ravel( _HX )).T
115             Jb  = 0.
116             Jo  = 0.
117             J   = Jb + Jo
118             if self._parameters["StoreInternalVariables"]:
119                 self.StoredVariables["CurrentState"].store( _X.A1 )
120             self.StoredVariables["CostFunctionJb"].store( Jb )
121             self.StoredVariables["CostFunctionJo"].store( Jo )
122             self.StoredVariables["CostFunctionJ" ].store( J )
123             return _HX
124         #
125         def GradientOfCostFunction(x):
126             _X      = numpy.asmatrix(numpy.ravel( x )).T
127             Hg = HO["Tangent"].asMatrix( _X )
128             return Hg
129         #
130         # Point de démarrage de l'optimisation : Xini = Xb
131         # ------------------------------------
132         if type(Xb) is type(numpy.matrix([])):
133             Xini = Xb.A1.tolist()
134         else:
135             Xini = list(Xb)
136         #
137         # Minimisation de la fonctionnelle
138         # --------------------------------
139         if self._parameters["Minimizer"] == "MMQR":
140             import mmqr
141             Minimum, J_optimal, Informations = mmqr.mmqr(
142                 func        = CostFunction,
143                 x0          = Xini,
144                 fprime      = GradientOfCostFunction,
145                 bounds      = Bounds,
146                 quantile    = self._parameters["Quantile"],
147                 maxfun      = self._parameters["MaximumNumberOfSteps"],
148                 toler       = self._parameters["CostDecrementTolerance"],
149                 y           = Y,
150                 )
151             nfeval = Informations[2]
152             rc     = Informations[4]
153         else:
154             raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
155         #
156         # Obtention de l'analyse
157         # ----------------------
158         Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
159         #
160         self.StoredVariables["Analysis"].store( Xa.A1 )
161         #
162         # Calculs et/ou stockages supplémentaires
163         # ---------------------------------------
164         if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
165             self.StoredVariables["Innovation"].store( numpy.ravel(d) )
166         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
167             self.StoredVariables["BMA"].store( numpy.ravel(Xb - Xa) )
168         if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
169             self.StoredVariables["OMA"].store( numpy.ravel(Y - Hm(Xa)) )
170         if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
171             self.StoredVariables["OMB"].store( numpy.ravel(d) )
172         #
173         logging.debug("%s Nombre d'évaluation(s) de l'opérateur d'observation direct/tangent/adjoint : %i/%i/%i"%(self._name, HO["Direct"].nbcalls()[0],HO["Tangent"].nbcalls()[0],HO["Adjoint"].nbcalls()[0]))
174         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
175         logging.debug("%s Terminé"%self._name)
176         #
177         return 0
178
179 # ==============================================================================
180 if __name__ == "__main__":
181     print '\n AUTODIAGNOSTIC \n'