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