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