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