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