Salome HOME
4b0dd223528f1ad1c12dab21206bc9de2e779e0c
[modules/adao.git] / src / daComposant / daAlgorithms / QuantileRegression.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2019 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, NumericObjects
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  = [
71                 "Analysis",
72                 "BMA",
73                 "CostFunctionJ",
74                 "CostFunctionJb",
75                 "CostFunctionJo",
76                 "CurrentState",
77                 "Innovation",
78                 "OMA",
79                 "OMB",
80                 "SimulatedObservationAtBackground",
81                 "SimulatedObservationAtCurrentState",
82                 "SimulatedObservationAtOptimum",
83                 ]
84             )
85         self.defineRequiredParameter( # Pas de type
86             name     = "Bounds",
87             message  = "Liste des valeurs de bornes",
88             )
89         self.requireInputArguments(
90             mandatory= ("Xb", "Y", "HO" ),
91             )
92
93     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
94         self._pre_run(Parameters, Xb, Y, R, B, Q)
95         #
96         Hm = HO["Direct"].appliedTo
97         #
98         # Utilisation éventuelle d'un vecteur H(Xb) précalculé
99         # ----------------------------------------------------
100         if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
101             HXb = Hm( Xb, HO["AppliedInX"]["HXb"])
102         else:
103             HXb = Hm( Xb )
104         HXb = numpy.asmatrix(numpy.ravel( HXb )).T
105         #
106         # Calcul de l'innovation
107         # ----------------------
108         if Y.size != HXb.size:
109             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))
110         if max(Y.shape) != max(HXb.shape):
111             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))
112         d  = Y - HXb
113         #
114         # Définition de la fonction-coût
115         # ------------------------------
116         def CostFunction(x):
117             _X  = numpy.asmatrix(numpy.ravel( x )).T
118             if self._parameters["StoreInternalVariables"] or self._toStore("CurrentState"):
119                 self.StoredVariables["CurrentState"].store( _X )
120             _HX = Hm( _X )
121             _HX = numpy.asmatrix(numpy.ravel( _HX )).T
122             if self._toStore("SimulatedObservationAtCurrentState"):
123                 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
124             Jb  = 0.
125             Jo  = 0.
126             J   = Jb + Jo
127             self.StoredVariables["CostFunctionJb"].store( Jb )
128             self.StoredVariables["CostFunctionJo"].store( Jo )
129             self.StoredVariables["CostFunctionJ" ].store( J )
130             return _HX
131         #
132         def GradientOfCostFunction(x):
133             _X      = numpy.asmatrix(numpy.ravel( x )).T
134             Hg = HO["Tangent"].asMatrix( _X )
135             return Hg
136         #
137         # Point de démarrage de l'optimisation : Xini = Xb
138         # ------------------------------------
139         if isinstance(Xb, type(numpy.matrix([]))):
140             Xini = Xb.A1.tolist()
141         else:
142             Xini = list(Xb)
143         #
144         # Minimisation de la fonctionnelle
145         # --------------------------------
146         if self._parameters["Minimizer"] == "MMQR":
147             Minimum, J_optimal, Informations = NumericObjects.mmqr(
148                 func        = CostFunction,
149                 x0          = Xini,
150                 fprime      = GradientOfCostFunction,
151                 bounds      = self._parameters["Bounds"],
152                 quantile    = self._parameters["Quantile"],
153                 maxfun      = self._parameters["MaximumNumberOfSteps"],
154                 toler       = self._parameters["CostDecrementTolerance"],
155                 y           = Y,
156                 )
157             nfeval = Informations[2]
158             rc     = Informations[4]
159         else:
160             raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
161         #
162         # Obtention de l'analyse
163         # ----------------------
164         Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
165         #
166         self.StoredVariables["Analysis"].store( Xa.A1 )
167         #
168         if self._toStore("OMA") or \
169             self._toStore("SimulatedObservationAtOptimum"):
170             HXa = Hm(Xa)
171         #
172         # Calculs et/ou stockages supplémentaires
173         # ---------------------------------------
174         if self._toStore("Innovation"):
175             self.StoredVariables["Innovation"].store( numpy.ravel(d) )
176         if self._toStore("BMA"):
177             self.StoredVariables["BMA"].store( numpy.ravel(Xb - Xa) )
178         if self._toStore("OMA"):
179             self.StoredVariables["OMA"].store( numpy.ravel(Y - HXa) )
180         if self._toStore("OMB"):
181             self.StoredVariables["OMB"].store( numpy.ravel(d) )
182         if self._toStore("SimulatedObservationAtBackground"):
183             self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
184         if self._toStore("SimulatedObservationAtOptimum"):
185             self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
186         #
187         self._post_run(HO)
188         return 0
189
190 # ==============================================================================
191 if __name__ == "__main__":
192     print('\n AUTODIAGNOSTIC\n')