Salome HOME
076f4c294167e5ce1309a3b324bf44c1eb4a5842
[modules/adao.git] / src / daComposant / daAlgorithms / QuantileRegression.py
1 # -*- coding: utf-8 -*-
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
26
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
29     def __init__(self):
30         BasicObjects.Algorithm.__init__(self, "QUANTILEREGRESSION")
31         self.defineRequiredParameter(
32             name     = "Quantile",
33             default  = 0.5,
34             typecast = float,
35             message  = "Quantile pour la regression de quantile",
36             minval   = 0.,
37             maxval   = 1.,
38             )
39         self.defineRequiredParameter(
40             name     = "Minimizer",
41             default  = "MMQR",
42             typecast = str,
43             message  = "Minimiseur utilisé",
44             listval  = ["MMQR"],
45             )
46         self.defineRequiredParameter(
47             name     = "MaximumNumberOfSteps",
48             default  = 15000,
49             typecast = int,
50             message  = "Nombre maximal de pas d'optimisation",
51             minval   = 1,
52             )
53         self.defineRequiredParameter(
54             name     = "CostDecrementTolerance",
55             default  = 1.e-6,
56             typecast = float,
57             message  = "Maximum de variation de la fonction d'estimation lors de l'arrêt",
58             )
59         self.defineRequiredParameter(
60             name     = "StoreInternalVariables",
61             default  = False,
62             typecast = bool,
63             message  = "Stockage des variables internes ou intermédiaires du calcul",
64             )
65         self.defineRequiredParameter(
66             name     = "StoreSupplementaryCalculations",
67             default  = [],
68             typecast = tuple,
69             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
70             listval  = ["BMA", "OMA", "OMB", "CurrentState", "CostFunctionJ", "CostFunctionJb", "CostFunctionJo", "Innovation", "SimulatedObservationAtBackground", "SimulatedObservationAtCurrentState", "SimulatedObservationAtOptimum"]
71             )
72         self.defineRequiredParameter( # Pas de type
73             name     = "Bounds",
74             message  = "Liste des valeurs de bornes",
75             )
76         self.requireInputArguments(
77             mandatory= ("Xb", "Y", "HO" ),
78             )
79
80     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
81         self._pre_run(Parameters, Xb, Y, R, B, Q)
82         #
83         Hm = HO["Direct"].appliedTo
84         #
85         # Utilisation éventuelle d'un vecteur H(Xb) précalculé
86         # ----------------------------------------------------
87         if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
88             HXb = Hm( Xb, HO["AppliedInX"]["HXb"])
89         else:
90             HXb = Hm( Xb )
91         HXb = numpy.asmatrix(numpy.ravel( HXb )).T
92         #
93         # Calcul de l'innovation
94         # ----------------------
95         if Y.size != HXb.size:
96             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))
97         if max(Y.shape) != max(HXb.shape):
98             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))
99         d  = Y - HXb
100         #
101         # Définition de la fonction-coût
102         # ------------------------------
103         def CostFunction(x):
104             _X  = numpy.asmatrix(numpy.ravel( x )).T
105             if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
106                 self.StoredVariables["CurrentState"].store( _X )
107             _HX = Hm( _X )
108             _HX = numpy.asmatrix(numpy.ravel( _HX )).T
109             if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
110                 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
111             Jb  = 0.
112             Jo  = 0.
113             J   = Jb + Jo
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 = HO["Tangent"].asMatrix( _X )
122             return Hg
123         #
124         # Point de démarrage de l'optimisation : Xini = Xb
125         # ------------------------------------
126         if isinstance(Xb, 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                 bounds      = self._parameters["Bounds"],
140                 quantile    = self._parameters["Quantile"],
141                 maxfun      = self._parameters["MaximumNumberOfSteps"],
142                 toler       = self._parameters["CostDecrementTolerance"],
143                 y           = Y,
144                 )
145             nfeval = Informations[2]
146             rc     = Informations[4]
147         else:
148             raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
149         #
150         # Obtention de l'analyse
151         # ----------------------
152         Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
153         #
154         self.StoredVariables["Analysis"].store( Xa.A1 )
155         #
156         if "OMA"                           in self._parameters["StoreSupplementaryCalculations"] or \
157            "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
158             HXa = Hm(Xa)
159         #
160         # Calculs et/ou stockages supplémentaires
161         # ---------------------------------------
162         if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
163             self.StoredVariables["Innovation"].store( numpy.ravel(d) )
164         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
165             self.StoredVariables["BMA"].store( numpy.ravel(Xb - Xa) )
166         if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
167             self.StoredVariables["OMA"].store( numpy.ravel(Y - HXa) )
168         if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
169             self.StoredVariables["OMB"].store( numpy.ravel(d) )
170         if "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
171             self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
172         if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
173             self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
174         #
175         self._post_run(HO)
176         return 0
177
178 # ==============================================================================
179 if __name__ == "__main__":
180     print('\n AUTODIAGNOSTIC \n')